@collective-intelligence/cli 0.1.6 → 0.1.8
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/README.md +62 -21
- package/dist/cli.js +20 -18
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// @bun
|
|
3
3
|
var __create=Object.create;var __getProtoOf=Object.getPrototypeOf;var __defProp=Object.defineProperty;var __getOwnPropNames=Object.getOwnPropertyNames;var __hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node;var __toESMCache_esm;var __toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap;var cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};const to=isNodeMode||!mod||!mod.__esModule||!__hasOwnProp.call(mod,"default")?__defProp(target,"default",{value:mod,enumerable:true}):target;if(mod&&typeof mod==="object"||typeof mod==="function"){for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:true})}if(canCache)cache.set(mod,to);return to};var __commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __esm=(fn,res,err)=>()=>{if(fn)try{res=fn(fn=0)}catch(e){err=[e]}if(err)throw err[0];return res};var __require=import.meta.require;function isAssetLikeImport(source){return ASSET_LIKE_IMPORT_RE.test(source)}function isViteOptimizableEntry(resolvedPath){return VITE_OPTIMIZABLE_ENTRY_RE.test(resolvedPath)}function removeTrailingSlash(value){return value.endsWith("/")?value.slice(0,-1):value}function ensureTrailingSlash(value){return`${removeTrailingSlash(value)}/`}function getBasePath(base){return removeTrailingSlash(base||"/")}function isNuxtClientBase(base){return getBasePath(base).endsWith("/_nuxt")}function stripQueryAndHash(id){const queryIndex=id.indexOf("?");const hashIndex=id.indexOf("#");const endIndex=queryIndex===-1?hashIndex:hashIndex===-1?queryIndex:Math.min(queryIndex,hashIndex);return endIndex===-1?id:id.slice(0,endIndex)}function stripViteFsPrefix(id){if(!id.startsWith("/@fs/"))return id;const file=id.slice(5);return file.startsWith("/")||/^[a-z]:\//i.test(file)?file:`/${file}`}function normalizeNodeModulePath(source){return stripQueryAndHash(source).replace(/\\/g,"/")}function getNodeModulesSuffix(source){const normalized=normalizeNodeModulePath(source);const index=normalized.lastIndexOf("/node_modules/");return index===-1?undefined:normalized.slice(index+14)}function isNodeModulePath(source){return source.includes("/node_modules/")||source.includes("\\node_modules\\")}function filterId(id){return typeof id==="string"&&!id.includes("\x00")}function getCommonSharedSubpaths(sharedKey){return COMMON_SHARED_SUBPATHS[removeTrailingSlash(sharedKey)]||[]}function resolvePublicPath(options,viteBase,originalBase){if(options.publicPath&&options.publicPath!=="auto")return options.publicPath;if(!originalBase)return"auto";if(viteBase){if(viteBase==="./")return"auto";return ensureTrailingSlash(viteBase)}return"auto"}function getSharedRequest(key,shareItem){const request=shareItem?.shareConfig?.request;return typeof request==="string"?request:key}function isUnderPrefix(prefix,source){return prefix.endsWith("/")&&(source===prefix.slice(0,-1)||source.startsWith(prefix))}function getSharedRuntimeKey(source,shareItem){const name=typeof shareItem?.name==="string"?shareItem.name:undefined;const request=getSharedRequest(name??source,shareItem);const configuredShareKey=shareItem?.shareConfig?.shareKey;const sourceMatchesRequest=source===request||isUnderPrefix(request,source);const shareKey=typeof configuredShareKey==="string"?configuredShareKey:name!==undefined&&sourceMatchesRequest?name:source;if(!request.endsWith("/"))return shareKey;const requestBase=request.slice(0,-1);if(source===requestBase)return shareKey.endsWith("/")?shareKey.slice(0,-1):shareKey;if(source.startsWith(`${requestBase}/`))return shareKey+source.slice(request.length);return isUnderPrefix(shareKey,source)?source:shareKey}function matchesSharedSource(source,key,shareItem){const request=getSharedRequest(key,shareItem);const keyBase=request.endsWith("/")?request.slice(0,-1):request;if(keyBase==="vue"&&(source==="vue/dist/vue.esm-bundler.js"||source==="vue/dist/vue.runtime.esm-bundler.js"))return true;if(request.endsWith("/"))return source===keyBase||source.startsWith(`${keyBase}/`);if(shareItem?.shareConfig?.request===undefined&&shareItem?.shareConfig?.shareKey===undefined&&getCommonSharedSubpaths(keyBase).includes(source))return true;return source===keyBase}function invalidateSharedKeyMatcher(shared){sharedKeyMatcherCache.delete(shared)}function findSharedKey(source,shared){return getSharedKeyMatcher(shared).find(source)}function pickLongestWildcardKey(wildcardKeys,source){let best;for(const wildcard of wildcardKeys){if(source!==wildcard.base&&!source.startsWith(`${wildcard.base}/`))continue;if(!best||wildcard.base.length>best.base.length||wildcard.base.length===best.base.length&&wildcard.key.length>best.key.length)best=wildcard}return best?.key}function getSharedKeyMatcher(shared){if(!shared)return emptySharedKeyMatcher;const cached=sharedKeyMatcherCache.get(shared);if(cached)return cached;const keys=Object.keys(shared);const exactKeys=new Map;const commonSubpathKeys=new Map;const wildcardKeys=[];let vueKey;for(const key of keys){const shareItem=shared[key];const request=getSharedRequest(key,shareItem);const keyBase=request.endsWith("/")?request.slice(0,-1):request;if(!exactKeys.has(request)||request===key)exactKeys.set(request,key);if(!vueKey&&keyBase==="vue")vueKey=key;if(request.endsWith("/"))wildcardKeys.push({key,base:keyBase});if(shareItem?.shareConfig?.import!==false&&shareItem?.shareConfig?.request===undefined&&shareItem?.shareConfig?.shareKey===undefined){for(const subpath of getCommonSharedSubpaths(keyBase))if(!commonSubpathKeys.has(subpath))commonSubpathKeys.set(subpath,key)}}const sourceCache=new Map;const matcher={find(source){if(sourceCache.has(source))return sourceCache.get(source);let result=exactKeys.get(source);if(!result&&vueKey){if(source==="vue/dist/vue.esm-bundler.js"||source==="vue/dist/vue.runtime.esm-bundler.js")result=vueKey}if(!result)result=commonSubpathKeys.get(source);if(!result)result=pickLongestWildcardKey(wildcardKeys,source);sourceCache.set(source,result);return result}};sharedKeyMatcherCache.set(shared,matcher);return matcher}var COMMON_SHARED_SUBPATHS,VITE_DEFAULT_ASSET_TYPES,ASSET_LIKE_IMPORT_RE,VITE_OPTIMIZABLE_ENTRY_RE,emptySharedKeyMatcher,sharedKeyMatcherCache;var init_sharedKeyMatcher_Od_nYxJA=__esm(()=>{COMMON_SHARED_SUBPATHS={react:["react/jsx-runtime","react/jsx-dev-runtime","react/compiler-runtime"],"react-dom":["react-dom/client","react-dom/profiling"],"solid-js":["solid-js/web","solid-js/store","solid-js/html","solid-js/h","solid-js/jsx-runtime","solid-js/jsx-dev-runtime"],zustand:["zustand/vanilla","zustand/react","zustand/middleware","zustand/shallow"]};VITE_DEFAULT_ASSET_TYPES=["apng","bmp","png","jpe?g","jfif","pjpeg","pjp","gif","svg","ico","webp","avif","cur","jxl","mp4","webm","ogg","mp3","wav","flac","aac","opus","mov","m4a","vtt","woff2?","eot","ttf","otf","webmanifest","pdf","txt"];ASSET_LIKE_IMPORT_RE=new RegExp(`\\.(${[...["css","scss","sass","less","styl","stylus"],...VITE_DEFAULT_ASSET_TYPES].join("|")})(?:[?#].*)?$`,"i");VITE_OPTIMIZABLE_ENTRY_RE=/\.[cm]?[jt]s$/;emptySharedKeyMatcher={find:()=>{return}};sharedKeyMatcherCache=new WeakMap});function rebaseImport(importSrc,dir){if(!dir)return importSrc;if(isAbsoluteUrl(importSrc))return importSrc;const normalizedDir=dir.replace(/^\/+|\/+$/g,"");if(!normalizedDir)return importSrc;const stripDirPrefix=(src,prefix)=>{if(src===prefix)return"";if(src.startsWith(prefix+"/"))return src.slice(prefix.length)};const absoluteRemainder=stripDirPrefix(importSrc,"/"+normalizedDir);if(absoluteRemainder!==undefined){const remainder=absoluteRemainder.replace(/^\/+/,"");return remainder?"./"+remainder:"./"}const relativeRemainder=stripDirPrefix(importSrc,normalizedDir);if(relativeRemainder!==undefined){const remainder=relativeRemainder.replace(/^\/+/,"");return remainder?"./"+remainder:"./"}const upLevels=normalizedDir.split("/").filter(Boolean).length;const prefix=upLevels>0?"../".repeat(upLevels):"./";if(importSrc.startsWith("./"))return prefix+importSrc.slice(2);if(importSrc.startsWith("/"))return prefix+importSrc.slice(1);return prefix+importSrc}function normalizePathForImport(path){return path.replace(/\\/g,"/")}function isAbsoluteUrl(src){if(/^[a-z]:[\\/]/i.test(src))return false;return EXTERNAL_URL_RE.test(src)}function hasFileExtension(fileName){return fileName.slice(Math.max(fileName.lastIndexOf("/"),fileName.lastIndexOf("\\"))+1).lastIndexOf(".")>0}function resolveHashPlaceholderFileName(fileName){if(!fileName.includes("[hash"))return fileName;const normalized=fileName.replace(HASH_PLACEHOLDER_RE,"");return hasFileExtension(normalized)?normalized:`${normalized}.js`}function createSourceMap(code,source=""){return{version:3,sources:[source],sourcesContent:[code],names:[],mappings:generateLineMappings(code,code,[])}}function applyReplacements(original,replacements){let code="";let cursor=0;let delta=0;const applied=[];for(const replacement of replacements){if(replacement.start<cursor)throw new Error("Overlapping overwrite ranges are not supported");code+=original.slice(cursor,replacement.start);const generatedStart=replacement.start+delta;code+=replacement.content;const generatedEnd=generatedStart+replacement.content.length;applied.push({...replacement,generatedStart,generatedEnd});cursor=replacement.end;delta+=replacement.content.length-(replacement.end-replacement.start)}code+=original.slice(cursor);return{code,replacements:applied}}function generateLineMappings(generated,original,replacements){const generatedLineStarts=getLineStarts(generated);const originalLineStarts=getLineStarts(original);let previousOriginalLine=0;let previousOriginalColumn=0;let mappings="";generatedLineStarts.forEach((generatedOffset,lineIndex)=>{if(lineIndex>0)mappings+=";";const originalOffset=generatedOffsetToOriginalOffset(generatedOffset,replacements);const originalLine=findLine(originalLineStarts,originalOffset);const originalColumn=originalOffset-originalLineStarts[originalLine];mappings+=encodeSegment([0,0,originalLine-previousOriginalLine,originalColumn-previousOriginalColumn]);previousOriginalLine=originalLine;previousOriginalColumn=originalColumn});return mappings}function generatedOffsetToOriginalOffset(offset,replacements){let delta=0;for(const replacement of replacements){if(offset<replacement.generatedStart)break;if(offset<replacement.generatedEnd)return replacement.start;delta+=replacement.content.length-(replacement.end-replacement.start)}return offset-delta}function getLineStarts(code){const starts=[0];for(let i=0;i<code.length;i++)if(code.charCodeAt(i)===10)starts.push(i+1);return starts}function findLine(lineStarts,offset){let low=0;let high=lineStarts.length-1;while(low<=high){const mid=low+high>>1;if(lineStarts[mid]<=offset)low=mid+1;else high=mid-1}return Math.max(0,high)}function encodeSegment(values){return values.map(encodeVlq).join("")}function encodeVlq(value){let vlq=value<0?(-value<<1)+1:value<<1;let encoded="";do{let digit=vlq&31;vlq>>>=5;if(vlq>0)digit|=32;encoded+=BASE64_CHARS[digit]}while(vlq>0);return encoded}function isJsxClosingTagSlash(code,slashIndex){if(code[slashIndex-1]!=="<")return false;let cursor=slashIndex+1;while(/\s/.test(code[cursor]||""))cursor++;if(code[cursor]===">")return true;const tagStart=cursor;while(/[-:.$_\u200C\u200D\p{ID_Continue}]/u.test(code[cursor]||""))cursor++;if(cursor===tagStart)return false;while(/\s/.test(code[cursor]||""))cursor++;return code[cursor]===">"}function createCodePositionMap(code,onComment){const positions=Array(code.length).fill(true);const mask=(start,end)=>{for(let index=start;index<end;index++)positions[index]=false};let canStartRegex=true;for(let index=0;index<code.length;){const char=code[index];const next=code[index+1];if(/\s/.test(char)){index++;continue}if(char==="/"&&next==="/"){const start=index;index+=2;while(index<code.length&&code[index]!==`
|
|
4
4
|
`&&code[index]!=="\r")index++;mask(start,index);onComment?.(start,index);continue}if(char==="/"&&next==="*"){const start=index;index+=2;while(index<code.length&&!(code[index]==="*"&&code[index+1]==="/"))index++;index=Math.min(code.length,index+2);mask(start,index);onComment?.(start,index);continue}if(char==='"'||char==="'"||char==="`"){const quote=char;const start=index++;while(index<code.length){if(code[index]==="\\"){index+=2;continue}if(code[index]===quote){index++;break}index++}mask(start,index);canStartRegex=false;continue}const closesJsxTag=isJsxClosingTagSlash(code,index);if(char==="/"&&canStartRegex&&!closesJsxTag){const start=index;let cursor=index+1;let escaped=false;let inCharacterClass=false;let closed=false;for(;cursor<code.length;cursor++){const regexChar=code[cursor];if(regexChar===`
|
|
5
|
-
`||regexChar==="\r")break;if(escaped){escaped=false;continue}if(regexChar==="\\"){escaped=true;continue}if(regexChar==="["){inCharacterClass=true;continue}if(regexChar==="]"&&inCharacterClass){inCharacterClass=false;continue}if(regexChar==="/"&&!inCharacterClass){cursor++;while(/[$_\p{ID_Continue}]/u.test(code[cursor]||""))cursor++;closed=true;break}}if(closed){mask(start,cursor);index=cursor;canStartRegex=false;continue}}if(/[$_\p{ID_Start}]/u.test(char)){const start=index++;while(/[$_\u200C\u200D\p{ID_Continue}]/u.test(code[index]||""))index++;canStartRegex=REGEX_PREFIX_KEYWORDS.has(code.slice(start,index));continue}if(/\d/.test(char)){index++;while(/[\w.]/.test(code[index]||""))index++;canStartRegex=false;continue}if((char==="+"||char==="-")&&next===char){index+=2;continue}if(char==="!"&&next!=="="){index++;continue}if(char===")"||char==="]"||char==="}")canStartRegex=false;else if(char!==".")canStartRegex=true;index++}return positions}function formatModuleFederationMessage(message){return`${MODULE_FEDERATION_LOG_PREFIX} ${message}`}function createModuleFederationError(message){return new Error(formatModuleFederationMessage(message))}function toConsoleArgs(message,rest=[]){if(typeof message==="string")return[formatModuleFederationMessage(message),...rest];if(message===undefined)return[MODULE_FEDERATION_LOG_PREFIX,...rest];return[MODULE_FEDERATION_LOG_PREFIX,message,...rest]}var EXTERNAL_URL_RE,HASH_PLACEHOLDER_RE,BASE64_CHARS="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",CodeRewriter=class{original;replacements=[];constructor(original){this.original=original}overwrite(start,end,content){if(start<0||end<start||end>this.original.length)throw new Error(`Invalid overwrite range: ${start}-${end}`);this.replacements.push({start,end,content})}toString(){return applyReplacements(this.original,this.getSortedReplacements()).code}generateMap(source=""){const{code,replacements}=applyReplacements(this.original,this.getSortedReplacements());return{version:3,sources:[source],sourcesContent:[this.original],names:[],mappings:generateLineMappings(code,this.original,replacements)}}getSortedReplacements(){return[...this.replacements].sort((a,b)=>a.start-b.start||a.end-b.end)}},REGEX_PREFIX_KEYWORDS,MODULE_FEDERATION_LOG_PREFIX="[Module Federation]",moduleFederationConsole,mfWarn,mfError;var init_logger_DOwfTlw5=__esm(()=>{EXTERNAL_URL_RE=/^(?:[a-z]+:|\/\/)/i;HASH_PLACEHOLDER_RE=/(?:[._-]?\[hash(?::\d+)?\])/g;REGEX_PREFIX_KEYWORDS=new Set(["await","case","delete","in","instanceof","new","return","throw","typeof","void","yield"]);moduleFederationConsole={log(message,...rest){console.log(...toConsoleArgs(message,rest))},warn(message,...rest){console.warn(...toConsoleArgs(message,rest))},error(message,...rest){console.error(...toConsoleArgs(message,rest))}};mfWarn=moduleFederationConsole.warn;mfError=moduleFederationConsole.error});import{existsSync as existsSync2,readFileSync as readFileSync2,readdirSync,realpathSync}from"fs";import{createRequire}from"module";import*as path$1 from"path";import{fileURLToPath as fileURLToPath6,pathToFileURL as pathToFileURL3}from"url";import{createHash as createHash4}from"crypto";function isReactCoreShare(pkg){return pkg==="react"||pkg.startsWith("react/")}function getDependencyCacheKey(cwd,dependencyName){return`${cwd}:${dependencyName}`}function setPackageDetectionCwd(cwd){packageDetectionCwd=cwd}function getPackageDetectionCwd(){return packageDetectionCwd||process.cwd()}function resolveImportPath(specifier){const resolved=import.meta.resolve(specifier);if(!resolved.startsWith("file:"))return resolved;const filePath=fileURLToPath6(resolved);if(!existsSync2(filePath)){const error=new Error(`Cannot find module '${specifier}'`);error.code="MODULE_NOT_FOUND";throw error}return filePath}function resolveExportsEntry(exportsField,conditions=DEFAULT_EXPORT_CONDITIONS){return resolveExportsEntryWithConditions(exportsField,new Set(conditions))}function resolveExportsEntryWithConditions(exportsField,conditions){if(typeof exportsField==="string")return exportsField;if(!exportsField||typeof exportsField!=="object")return;if(Array.isArray(exportsField)){for(const target of exportsField){const resolved=resolveExportsEntryWithConditions(target,conditions);if(resolved)return resolved}return}const record=exportsField;const rootExport=record["."];if(rootExport)return resolveExportsEntryWithConditions(rootExport,conditions);for(const[condition,value]of Object.entries(record)){if(condition!=="default"&&!conditions.has(condition))continue;const target=resolveExportsEntryWithConditions(value,conditions);if(target)return target}}function substituteExportsWildcard(target,patternMatch){if(typeof target==="string")return target.split("*").join(patternMatch);if(Array.isArray(target))return target.map((entry)=>substituteExportsWildcard(entry,patternMatch));if(target&&typeof target==="object"){const source=target;const out={};for(const key of Object.keys(source))out[key]=substituteExportsWildcard(source[key],patternMatch);return out}return target}function matchExportsSubpath(record,subpath){if(subpath in record)return record[subpath];let bestKey;let bestBaseLength=-1;let bestKeyLength=-1;for(const key of Object.keys(record)){const wildcardIndex=key.indexOf("*");if(wildcardIndex===-1)continue;const patternBase=key.slice(0,wildcardIndex);const patternTrailer=key.slice(wildcardIndex+1);if(patternTrailer.includes("*"))continue;if(!subpath.startsWith(patternBase)||!subpath.endsWith(patternTrailer))continue;if(subpath.length<=patternBase.length+patternTrailer.length)continue;if(patternBase.length>bestBaseLength||patternBase.length===bestBaseLength&&key.length>bestKeyLength){bestKey=key;bestBaseLength=patternBase.length;bestKeyLength=key.length}}if(bestKey===undefined)return;const patternTrailer=bestKey.slice(bestKey.indexOf("*")+1);const patternMatch=subpath.slice(bestBaseLength,subpath.length-patternTrailer.length);return substituteExportsWildcard(record[bestKey],patternMatch)}function getPackageExportsTarget(pkg,packageName,exportsField){if(typeof exportsField==="string")return pkg===packageName?exportsField:undefined;if(!exportsField||typeof exportsField!=="object")return;const record=exportsField;const subpath=pkg===packageName?".":`.${pkg.slice(packageName.length)}`;if(subpath!==".")return matchExportsSubpath(record,subpath);return record["."]??(!Object.keys(record).some((key)=>key.startsWith("."))?record:undefined)}function isPackageInstalled(pkg,opts={}){return getInstalledPackageJson(getPackageName(pkg),opts)!==undefined}function isPackageExportAvailable(pkg,opts={}){const packageName=getPackageName(pkg);const installed=getInstalledPackageJson(packageName,opts);if(installed?.packageJson.exports==null)return true;return resolveExportsEntry(getPackageExportsTarget(pkg,packageName,installed.packageJson.exports),opts.conditions)!==undefined}function packageNameEncode(name){if(typeof name!=="string")throw createModuleFederationError("A string package name is required");const encoded=name.replace(/@/g,"_mf_0_").replace(/\//g,"_mf_1_").replace(/-/g,"_mf_2_").replace(/\./g,"_mf_3_");if(encoded.length<=MF_HASHED_NAME_THRESHOLD)return encoded;const hashedName=`${encoded.slice(0,MF_HASHED_NAME_PREFIX_LENGTH)}${createHash4("sha256").update(name).digest("hex").slice(0,MF_HASHED_NAME_HASH_LENGTH)}`;mfHashedNameMap.set(hashedName,name);return hashedName}function packageNameDecode(encoded){if(typeof encoded!=="string")throw createModuleFederationError("A string encoded file name is required");const original=mfHashedNameMap.get(encoded);if(original!==undefined)return original;return encoded.replace(/_mf_0_/g,"@").replace(/_mf_1_/g,"/").replace(/_mf_2_/g,"-").replace(/_mf_3_/g,".")}function getPackageName(packageString){const match=packageString.match(/^(?:@[^/]+\/)?[^/]+/);return match?match[0]:packageString}function getPackageNameFromNodeModulePath(source){const suffix=getNodeModulesSuffix(source);if(!suffix)return;const parts=suffix.split("/");if(!parts[0])return;if(parts[0].startsWith("@"))return parts[1]?`${parts[0]}/${parts[1]}`:undefined;return parts[0]}function getSharedCacheKeyParts(input){const scope=(Array.isArray(input.scope)?input.scope[0]:input.scope)||"default";const id=input.singleton||!input.version?input.pkg:`${input.pkg}@${input.version}`;return{scope,id,key:`${scope}:${id}`}}function getSharedCacheDescriptor(pkg,shareItem){const parts=getSharedCacheKeyParts({pkg:shareItem.shareConfig.request!==undefined||shareItem.shareConfig.shareKey!==undefined?getSharedRuntimeKey(pkg,shareItem):pkg,singleton:shareItem.shareConfig.singleton,version:shareItem.version,scope:shareItem.scope});return{canonical:parts.key,...parts.scope==="default"?{aliases:[parts.id]}:{}}}function getInstalledPackageJson(pkg,opts){const cwd=opts?.cwd||getPackageDetectionCwd();const packageName=opts?.packageName||getPackageName(pkg);const cacheKey=`${cwd}\x00${pkg}\x00${packageName}\x00${opts?.fromResolvedEntry??""}`;if(installedPackageJsonCache.has(cacheKey))return installedPackageJsonCache.get(cacheKey);const result=resolveInstalledPackageJson(pkg,cwd,packageName,opts);installedPackageJsonCache.set(cacheKey,result);return result}function tryReadPackageJson(packageJsonPath,expectedName){if(!existsSync2(packageJsonPath))return;try{const packageJson=JSON.parse(readFileSync2(packageJsonPath,"utf-8"));if(expectedName!==undefined&&packageJson.name!==expectedName)return;return{path:packageJsonPath,dir:path$1.dirname(packageJsonPath),packageJson}}catch{return}}function resolveInstalledPackageJson(pkg,cwd,packageName,opts){const findPackageInPnpmStore=(startDir)=>{for(const dir of ancestorDirs(startDir)){const pnpmStoreDir=path$1.join(dir,"node_modules",".pnpm");if(!existsSync2(pnpmStoreDir))continue;try{for(const entry of readdirSync(pnpmStoreDir,{withFileTypes:true})){if(!entry.isDirectory())continue;const candidate=tryReadPackageJson(path$1.join(pnpmStoreDir,entry.name,"node_modules",packageName,"package.json"));if(candidate?.packageJson.name===packageName)return candidate}}catch{}}};let resolvedPath;try{const rootPackageJson=path$1.join(cwd,"package.json");if(opts?.fromResolvedEntry)resolvedPath=opts.fromResolvedEntry;else try{resolvedPath=resolveModulePath(pkg,rootPackageJson)}catch{resolvedPath=resolveModulePath(packageName,rootPackageJson)}}catch{resolvedPath=undefined}if(resolvedPath!==undefined&&!path$1.isAbsolute(resolvedPath))resolvedPath=undefined;if(resolvedPath!==undefined){const owner=findOwningPackageJson(path$1.dirname(resolvedPath),packageName);if(owner)return owner}for(const dir of ancestorDirs(cwd)){const directCandidate=tryReadPackageJson(path$1.join(dir,"node_modules",packageName,"package.json"),packageName);if(directCandidate)return directCandidate}return findPackageInDependents(packageName,cwd)??findPackageInPnpmStore(cwd)}function findPackageInDependents(packageName,cwd){const cacheKey=`${cwd}\x00${packageName}`;if(!dependentsLookupCache.has(cacheKey))dependentsLookupCache.set(cacheKey,walkDependents(packageName,cwd));return dependentsLookupCache.get(cacheKey)}function walkDependents(packageName,cwd){const root=tryReadPackageJson(path$1.join(cwd,"package.json"));if(!root)return;const visited=new Set;const rootDependencyGroups=[getDependencyNames(root.packageJson),getDependencyNames(root.packageJson,["devDependencies"])];for(const rootDependencies of rootDependencyGroups){let level=rootDependencies.map((name)=>({name,fromDir:cwd}));while(level.length){const candidates=[];const nextLevel=[];for(const{name,fromDir}of level){if(name===packageName)continue;const dependent=findPackageFrom(name,fromDir);if(!dependent||visited.has(dependent.dir))continue;visited.add(dependent.dir);const dependencies=getDependencyNames(dependent.packageJson);if(dependencies.includes(packageName)){const copy=findPackageFrom(packageName,dependent.dir);if(copy)candidates.push({copy,via:name})}for(const dependency of dependencies)nextLevel.push({name:dependency,fromDir:dependent.dir})}if(candidates.length){warnOnAmbiguousDependents(packageName,candidates);return candidates[0].copy}level=nextLevel}}}function warnOnAmbiguousDependents(packageName,candidates){const viaByVersion=new Map;for(const{copy,via}of candidates)if(!viaByVersion.has(copy.packageJson.version))viaByVersion.set(copy.packageJson.version,via);if(viaByVersion.size<2)return;const versions=[...viaByVersion].map(([version,via])=>`${version} (via ${via})`);mfWarn(`Shared package "${packageName}" is not a dependency of the project, and its closest dependents install different versions: ${versions.join(", ")}. The fallback uses ${versions[0]}. Add "${packageName}" to the project's dependencies or set its shared "import" to choose the version.`)}function findPackageFrom(packageName,fromDir){const entry=findNodeModulesEntry(packageName,fromDir);if(!entry)return;try{return tryReadPackageJson(path$1.join(realpathSync(entry),"package.json"),packageName)}catch{return}}function findOwningPackageJson(startDir,packageName){let matchingPackage;for(const dir of ancestorDirs(startDir)){const candidate=tryReadPackageJson(path$1.join(dir,"package.json"),packageName);if(!candidate)continue;if(dir.endsWith(path$1.join("node_modules",packageName)))return candidate;matchingPackage??=candidate}return matchingPackage}function*ancestorDirs(startDir){let dir=startDir;while(true){yield dir;const parentDir=path$1.dirname(dir);if(parentDir===dir)return;dir=parentDir}}function findNodeModulesEntry(packageName,fromDir){for(const dir of ancestorDirs(fromDir)){const entry=path$1.join(dir,"node_modules",packageName);if(existsSync2(entry))return entry}}function resolveModulePath(specifier,from){const resolved=createRequire(pathToFileURL3(from)).resolve(specifier);if(!path$1.isAbsolute(resolved)||specifier.startsWith(".")||path$1.isAbsolute(specifier)||process.versions.pnp)return resolved;if(findNodeModulesEntry(getPackageName(specifier),path$1.dirname(from)))return resolved;const error=new Error(`Cannot find module '${specifier}' from '${from}'`);error.code="MODULE_NOT_FOUND";throw error}function getDependencyNames(packageJson,fields=["dependencies","peerDependencies","optionalDependencies"]){if(!packageJson)return[];const names=new Set;for(const field of fields){const deps=packageJson[field];if(!deps||typeof deps!=="object")continue;for(const dep of Object.keys(deps))names.add(dep)}return[...names]}function getInstalledPackageEntry(pkg,opts){const installed=getInstalledPackageJson(pkg,opts);if(!installed)return;const cwd=opts?.cwd||getPackageDetectionCwd();const packageName=opts?.packageName||getPackageName(pkg);const packageJson=installed.packageJson;if(pkg!==packageName&&(opts?.resolveSubpathWithRequire!==false||packageJson.exports===undefined))try{return resolveModulePath(pkg,path$1.join(cwd,"package.json"))}catch{}const explicitEntry=resolveExportsEntry(getPackageExportsTarget(pkg,packageName,packageJson.exports),opts?.conditions)||(typeof packageJson.module==="string"?packageJson.module:undefined)||(typeof packageJson.main==="string"?packageJson.main:undefined)||"index.js";return path$1.join(installed.dir,explicitEntry)}function getIsRolldown(ctx){const viteVersion=ctx?.meta?.viteVersion;const viteMajor=Number(String(viteVersion??"").split(".")[0]);return Number.isFinite(viteMajor)&&viteMajor>=8||!!ctx?.meta?.rolldownVersion}function supportsCodeSplittingGroupDebugName(ctx){const rolldownVersion=ctx?.meta?.rolldownVersion;if(typeof rolldownVersion!=="string")return false;const[major=0,minor=0,patch=0]=rolldownVersion.split(/[.+-]/,3).map((part)=>parseInt(part,10)||0);if(major!==1)return major>1;if(minor!==2)return minor>2;return patch>=10}function isNuxtProjectRoot(root){let dir=root;for(let i=0;i<8;i++){if(hasPackageDependency("nuxt",dir)||hasPackageDependency("nuxt-nightly",dir))return true;const parent=path$1.dirname(dir);if(parent===dir)break;dir=parent}return false}function hasPackageDependency(dependencyName,cwd=packageDetectionCwd||process.cwd()){const cacheKey=getDependencyCacheKey(cwd,dependencyName);const cached=dependencyPresenceCache.get(cacheKey);if(cached!==undefined)return cached;try{const packageJson=JSON.parse(readFileSync2(path$1.join(cwd,"package.json"),"utf8"));const hasDependency=[packageJson.dependencies,packageJson.devDependencies,packageJson.peerDependencies,packageJson.optionalDependencies].some((deps)=>!!deps?.[dependencyName]);dependencyPresenceCache.set(cacheKey,hasDependency);return hasDependency}catch{dependencyPresenceCache.set(cacheKey,false);return false}}var REACT_CLIENT_INTERNALS_KEY="__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE",REACT_INTERNALS_KEYS,REACT_DOM_CLIENT_SHARE="react-dom/client",dependencyPresenceCache,packageDetectionCwd,installedPackageJsonCache,dependentsLookupCache,DEFAULT_EXPORT_CONDITIONS,MF_HASHED_NAME_THRESHOLD=90,MF_HASHED_NAME_HASH_LENGTH=16,MF_HASHED_NAME_PREFIX_LENGTH,mfHashedNameMap,sharedCacheHelperCode;var init_dtsConstants_r5OfegUr=__esm(()=>{init_sharedKeyMatcher_Od_nYxJA();init_logger_DOwfTlw5();REACT_INTERNALS_KEYS=[REACT_CLIENT_INTERNALS_KEY,"__TEST_INTERNALS","__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED"];dependencyPresenceCache=new Map;installedPackageJsonCache=new Map;dependentsLookupCache=new Map;DEFAULT_EXPORT_CONDITIONS=["browser","import","module","default"];MF_HASHED_NAME_PREFIX_LENGTH=MF_HASHED_NAME_THRESHOLD-MF_HASHED_NAME_HASH_LENGTH;mfHashedNameMap=new Map;sharedCacheHelperCode=`const __mfGetSharedCacheDescriptor = (pkg, singleton, version, scope) => {
|
|
5
|
+
`||regexChar==="\r")break;if(escaped){escaped=false;continue}if(regexChar==="\\"){escaped=true;continue}if(regexChar==="["){inCharacterClass=true;continue}if(regexChar==="]"&&inCharacterClass){inCharacterClass=false;continue}if(regexChar==="/"&&!inCharacterClass){cursor++;while(/[$_\p{ID_Continue}]/u.test(code[cursor]||""))cursor++;closed=true;break}}if(closed){mask(start,cursor);index=cursor;canStartRegex=false;continue}}if(/[$_\p{ID_Start}]/u.test(char)){const start=index++;while(/[$_\u200C\u200D\p{ID_Continue}]/u.test(code[index]||""))index++;canStartRegex=REGEX_PREFIX_KEYWORDS.has(code.slice(start,index));continue}if(/\d/.test(char)){index++;while(/[\w.]/.test(code[index]||""))index++;canStartRegex=false;continue}if((char==="+"||char==="-")&&next===char){index+=2;continue}if(char==="!"&&next!=="="){index++;continue}if(char===")"||char==="]"||char==="}")canStartRegex=false;else if(char!==".")canStartRegex=true;index++}return positions}function formatModuleFederationMessage(message){return`${MODULE_FEDERATION_LOG_PREFIX} ${message}`}function createModuleFederationError(message){return new Error(formatModuleFederationMessage(message))}function toConsoleArgs(message,rest=[]){if(typeof message==="string")return[formatModuleFederationMessage(message),...rest];if(message===undefined)return[MODULE_FEDERATION_LOG_PREFIX,...rest];return[MODULE_FEDERATION_LOG_PREFIX,message,...rest]}var EXTERNAL_URL_RE,HASH_PLACEHOLDER_RE,BASE64_CHARS="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",CodeRewriter=class{original;replacements=[];constructor(original){this.original=original}overwrite(start,end,content){if(start<0||end<start||end>this.original.length)throw new Error(`Invalid overwrite range: ${start}-${end}`);this.replacements.push({start,end,content})}toString(){return applyReplacements(this.original,this.getSortedReplacements()).code}generateMap(source=""){const{code,replacements}=applyReplacements(this.original,this.getSortedReplacements());return{version:3,sources:[source],sourcesContent:[this.original],names:[],mappings:generateLineMappings(code,this.original,replacements)}}getSortedReplacements(){return[...this.replacements].sort((a,b)=>a.start-b.start||a.end-b.end)}},REGEX_PREFIX_KEYWORDS,MODULE_FEDERATION_LOG_PREFIX="[Module Federation]",moduleFederationConsole,mfWarn,mfError;var init_logger_DOwfTlw5=__esm(()=>{EXTERNAL_URL_RE=/^(?:[a-z]+:|\/\/)/i;HASH_PLACEHOLDER_RE=/(?:[._-]?\[hash(?::\d+)?\])/g;REGEX_PREFIX_KEYWORDS=new Set(["await","case","delete","in","instanceof","new","return","throw","typeof","void","yield"]);moduleFederationConsole={log(message,...rest){console.log(...toConsoleArgs(message,rest))},warn(message,...rest){console.warn(...toConsoleArgs(message,rest))},error(message,...rest){console.error(...toConsoleArgs(message,rest))}};mfWarn=moduleFederationConsole.warn;mfError=moduleFederationConsole.error});import{existsSync as existsSync2,readFileSync as readFileSync2,readdirSync,realpathSync}from"fs";import{createRequire}from"module";import*as path$1 from"path";import{fileURLToPath as fileURLToPath6,pathToFileURL as pathToFileURL3}from"url";import{createHash as createHash5}from"crypto";function isReactCoreShare(pkg){return pkg==="react"||pkg.startsWith("react/")}function getDependencyCacheKey(cwd,dependencyName){return`${cwd}:${dependencyName}`}function setPackageDetectionCwd(cwd){packageDetectionCwd=cwd}function getPackageDetectionCwd(){return packageDetectionCwd||process.cwd()}function resolveImportPath(specifier){const resolved=import.meta.resolve(specifier);if(!resolved.startsWith("file:"))return resolved;const filePath=fileURLToPath6(resolved);if(!existsSync2(filePath)){const error=new Error(`Cannot find module '${specifier}'`);error.code="MODULE_NOT_FOUND";throw error}return filePath}function resolveExportsEntry(exportsField,conditions=DEFAULT_EXPORT_CONDITIONS){return resolveExportsEntryWithConditions(exportsField,new Set(conditions))}function resolveExportsEntryWithConditions(exportsField,conditions){if(typeof exportsField==="string")return exportsField;if(!exportsField||typeof exportsField!=="object")return;if(Array.isArray(exportsField)){for(const target of exportsField){const resolved=resolveExportsEntryWithConditions(target,conditions);if(resolved)return resolved}return}const record=exportsField;const rootExport=record["."];if(rootExport)return resolveExportsEntryWithConditions(rootExport,conditions);for(const[condition,value]of Object.entries(record)){if(condition!=="default"&&!conditions.has(condition))continue;const target=resolveExportsEntryWithConditions(value,conditions);if(target)return target}}function substituteExportsWildcard(target,patternMatch){if(typeof target==="string")return target.split("*").join(patternMatch);if(Array.isArray(target))return target.map((entry)=>substituteExportsWildcard(entry,patternMatch));if(target&&typeof target==="object"){const source=target;const out={};for(const key of Object.keys(source))out[key]=substituteExportsWildcard(source[key],patternMatch);return out}return target}function matchExportsSubpath(record,subpath){if(subpath in record)return record[subpath];let bestKey;let bestBaseLength=-1;let bestKeyLength=-1;for(const key of Object.keys(record)){const wildcardIndex=key.indexOf("*");if(wildcardIndex===-1)continue;const patternBase=key.slice(0,wildcardIndex);const patternTrailer=key.slice(wildcardIndex+1);if(patternTrailer.includes("*"))continue;if(!subpath.startsWith(patternBase)||!subpath.endsWith(patternTrailer))continue;if(subpath.length<=patternBase.length+patternTrailer.length)continue;if(patternBase.length>bestBaseLength||patternBase.length===bestBaseLength&&key.length>bestKeyLength){bestKey=key;bestBaseLength=patternBase.length;bestKeyLength=key.length}}if(bestKey===undefined)return;const patternTrailer=bestKey.slice(bestKey.indexOf("*")+1);const patternMatch=subpath.slice(bestBaseLength,subpath.length-patternTrailer.length);return substituteExportsWildcard(record[bestKey],patternMatch)}function getPackageExportsTarget(pkg,packageName,exportsField){if(typeof exportsField==="string")return pkg===packageName?exportsField:undefined;if(!exportsField||typeof exportsField!=="object")return;const record=exportsField;const subpath=pkg===packageName?".":`.${pkg.slice(packageName.length)}`;if(subpath!==".")return matchExportsSubpath(record,subpath);return record["."]??(!Object.keys(record).some((key)=>key.startsWith("."))?record:undefined)}function isPackageInstalled(pkg,opts={}){return getInstalledPackageJson(getPackageName(pkg),opts)!==undefined}function isPackageExportAvailable(pkg,opts={}){const packageName=getPackageName(pkg);const installed=getInstalledPackageJson(packageName,opts);if(installed?.packageJson.exports==null)return true;return resolveExportsEntry(getPackageExportsTarget(pkg,packageName,installed.packageJson.exports),opts.conditions)!==undefined}function packageNameEncode(name){if(typeof name!=="string")throw createModuleFederationError("A string package name is required");const encoded=name.replace(/@/g,"_mf_0_").replace(/\//g,"_mf_1_").replace(/-/g,"_mf_2_").replace(/\./g,"_mf_3_");if(encoded.length<=MF_HASHED_NAME_THRESHOLD)return encoded;const hashedName=`${encoded.slice(0,MF_HASHED_NAME_PREFIX_LENGTH)}${createHash5("sha256").update(name).digest("hex").slice(0,MF_HASHED_NAME_HASH_LENGTH)}`;mfHashedNameMap.set(hashedName,name);return hashedName}function packageNameDecode(encoded){if(typeof encoded!=="string")throw createModuleFederationError("A string encoded file name is required");const original=mfHashedNameMap.get(encoded);if(original!==undefined)return original;return encoded.replace(/_mf_0_/g,"@").replace(/_mf_1_/g,"/").replace(/_mf_2_/g,"-").replace(/_mf_3_/g,".")}function getPackageName(packageString){const match=packageString.match(/^(?:@[^/]+\/)?[^/]+/);return match?match[0]:packageString}function getPackageNameFromNodeModulePath(source){const suffix=getNodeModulesSuffix(source);if(!suffix)return;const parts=suffix.split("/");if(!parts[0])return;if(parts[0].startsWith("@"))return parts[1]?`${parts[0]}/${parts[1]}`:undefined;return parts[0]}function getSharedCacheKeyParts(input){const scope=(Array.isArray(input.scope)?input.scope[0]:input.scope)||"default";const id=input.singleton||!input.version?input.pkg:`${input.pkg}@${input.version}`;return{scope,id,key:`${scope}:${id}`}}function getSharedCacheDescriptor(pkg,shareItem){const parts=getSharedCacheKeyParts({pkg:shareItem.shareConfig.request!==undefined||shareItem.shareConfig.shareKey!==undefined?getSharedRuntimeKey(pkg,shareItem):pkg,singleton:shareItem.shareConfig.singleton,version:shareItem.version,scope:shareItem.scope});return{canonical:parts.key,...parts.scope==="default"?{aliases:[parts.id]}:{}}}function getInstalledPackageJson(pkg,opts){const cwd=opts?.cwd||getPackageDetectionCwd();const packageName=opts?.packageName||getPackageName(pkg);const cacheKey=`${cwd}\x00${pkg}\x00${packageName}\x00${opts?.fromResolvedEntry??""}`;if(installedPackageJsonCache.has(cacheKey))return installedPackageJsonCache.get(cacheKey);const result=resolveInstalledPackageJson(pkg,cwd,packageName,opts);installedPackageJsonCache.set(cacheKey,result);return result}function tryReadPackageJson(packageJsonPath,expectedName){if(!existsSync2(packageJsonPath))return;try{const packageJson=JSON.parse(readFileSync2(packageJsonPath,"utf-8"));if(expectedName!==undefined&&packageJson.name!==expectedName)return;return{path:packageJsonPath,dir:path$1.dirname(packageJsonPath),packageJson}}catch{return}}function resolveInstalledPackageJson(pkg,cwd,packageName,opts){const findPackageInPnpmStore=(startDir)=>{for(const dir of ancestorDirs(startDir)){const pnpmStoreDir=path$1.join(dir,"node_modules",".pnpm");if(!existsSync2(pnpmStoreDir))continue;try{for(const entry of readdirSync(pnpmStoreDir,{withFileTypes:true})){if(!entry.isDirectory())continue;const candidate=tryReadPackageJson(path$1.join(pnpmStoreDir,entry.name,"node_modules",packageName,"package.json"));if(candidate?.packageJson.name===packageName)return candidate}}catch{}}};let resolvedPath;try{const rootPackageJson=path$1.join(cwd,"package.json");if(opts?.fromResolvedEntry)resolvedPath=opts.fromResolvedEntry;else try{resolvedPath=resolveModulePath(pkg,rootPackageJson)}catch{resolvedPath=resolveModulePath(packageName,rootPackageJson)}}catch{resolvedPath=undefined}if(resolvedPath!==undefined&&!path$1.isAbsolute(resolvedPath))resolvedPath=undefined;if(resolvedPath!==undefined){const owner=findOwningPackageJson(path$1.dirname(resolvedPath),packageName);if(owner)return owner}for(const dir of ancestorDirs(cwd)){const directCandidate=tryReadPackageJson(path$1.join(dir,"node_modules",packageName,"package.json"),packageName);if(directCandidate)return directCandidate}return findPackageInDependents(packageName,cwd)??findPackageInPnpmStore(cwd)}function findPackageInDependents(packageName,cwd){const cacheKey=`${cwd}\x00${packageName}`;if(!dependentsLookupCache.has(cacheKey))dependentsLookupCache.set(cacheKey,walkDependents(packageName,cwd));return dependentsLookupCache.get(cacheKey)}function walkDependents(packageName,cwd){const root=tryReadPackageJson(path$1.join(cwd,"package.json"));if(!root)return;const visited=new Set;const rootDependencyGroups=[getDependencyNames(root.packageJson),getDependencyNames(root.packageJson,["devDependencies"])];for(const rootDependencies of rootDependencyGroups){let level=rootDependencies.map((name)=>({name,fromDir:cwd}));while(level.length){const candidates=[];const nextLevel=[];for(const{name,fromDir}of level){if(name===packageName)continue;const dependent=findPackageFrom(name,fromDir);if(!dependent||visited.has(dependent.dir))continue;visited.add(dependent.dir);const dependencies=getDependencyNames(dependent.packageJson);if(dependencies.includes(packageName)){const copy=findPackageFrom(packageName,dependent.dir);if(copy)candidates.push({copy,via:name})}for(const dependency of dependencies)nextLevel.push({name:dependency,fromDir:dependent.dir})}if(candidates.length){warnOnAmbiguousDependents(packageName,candidates);return candidates[0].copy}level=nextLevel}}}function warnOnAmbiguousDependents(packageName,candidates){const viaByVersion=new Map;for(const{copy,via}of candidates)if(!viaByVersion.has(copy.packageJson.version))viaByVersion.set(copy.packageJson.version,via);if(viaByVersion.size<2)return;const versions=[...viaByVersion].map(([version,via])=>`${version} (via ${via})`);mfWarn(`Shared package "${packageName}" is not a dependency of the project, and its closest dependents install different versions: ${versions.join(", ")}. The fallback uses ${versions[0]}. Add "${packageName}" to the project's dependencies or set its shared "import" to choose the version.`)}function findPackageFrom(packageName,fromDir){const entry=findNodeModulesEntry(packageName,fromDir);if(!entry)return;try{return tryReadPackageJson(path$1.join(realpathSync(entry),"package.json"),packageName)}catch{return}}function findOwningPackageJson(startDir,packageName){let matchingPackage;for(const dir of ancestorDirs(startDir)){const candidate=tryReadPackageJson(path$1.join(dir,"package.json"),packageName);if(!candidate)continue;if(dir.endsWith(path$1.join("node_modules",packageName)))return candidate;matchingPackage??=candidate}return matchingPackage}function*ancestorDirs(startDir){let dir=startDir;while(true){yield dir;const parentDir=path$1.dirname(dir);if(parentDir===dir)return;dir=parentDir}}function findNodeModulesEntry(packageName,fromDir){for(const dir of ancestorDirs(fromDir)){const entry=path$1.join(dir,"node_modules",packageName);if(existsSync2(entry))return entry}}function resolveModulePath(specifier,from){const resolved=createRequire(pathToFileURL3(from)).resolve(specifier);if(!path$1.isAbsolute(resolved)||specifier.startsWith(".")||path$1.isAbsolute(specifier)||process.versions.pnp)return resolved;if(findNodeModulesEntry(getPackageName(specifier),path$1.dirname(from)))return resolved;const error=new Error(`Cannot find module '${specifier}' from '${from}'`);error.code="MODULE_NOT_FOUND";throw error}function getDependencyNames(packageJson,fields=["dependencies","peerDependencies","optionalDependencies"]){if(!packageJson)return[];const names=new Set;for(const field of fields){const deps=packageJson[field];if(!deps||typeof deps!=="object")continue;for(const dep of Object.keys(deps))names.add(dep)}return[...names]}function getInstalledPackageEntry(pkg,opts){const installed=getInstalledPackageJson(pkg,opts);if(!installed)return;const cwd=opts?.cwd||getPackageDetectionCwd();const packageName=opts?.packageName||getPackageName(pkg);const packageJson=installed.packageJson;if(pkg!==packageName&&(opts?.resolveSubpathWithRequire!==false||packageJson.exports===undefined))try{return resolveModulePath(pkg,path$1.join(cwd,"package.json"))}catch{}const explicitEntry=resolveExportsEntry(getPackageExportsTarget(pkg,packageName,packageJson.exports),opts?.conditions)||(typeof packageJson.module==="string"?packageJson.module:undefined)||(typeof packageJson.main==="string"?packageJson.main:undefined)||"index.js";return path$1.join(installed.dir,explicitEntry)}function getIsRolldown(ctx){const viteVersion=ctx?.meta?.viteVersion;const viteMajor=Number(String(viteVersion??"").split(".")[0]);return Number.isFinite(viteMajor)&&viteMajor>=8||!!ctx?.meta?.rolldownVersion}function supportsCodeSplittingGroupDebugName(ctx){const rolldownVersion=ctx?.meta?.rolldownVersion;if(typeof rolldownVersion!=="string")return false;const[major=0,minor=0,patch=0]=rolldownVersion.split(/[.+-]/,3).map((part)=>parseInt(part,10)||0);if(major!==1)return major>1;if(minor!==2)return minor>2;return patch>=10}function isNuxtProjectRoot(root){let dir=root;for(let i=0;i<8;i++){if(hasPackageDependency("nuxt",dir)||hasPackageDependency("nuxt-nightly",dir))return true;const parent=path$1.dirname(dir);if(parent===dir)break;dir=parent}return false}function hasPackageDependency(dependencyName,cwd=packageDetectionCwd||process.cwd()){const cacheKey=getDependencyCacheKey(cwd,dependencyName);const cached=dependencyPresenceCache.get(cacheKey);if(cached!==undefined)return cached;try{const packageJson=JSON.parse(readFileSync2(path$1.join(cwd,"package.json"),"utf8"));const hasDependency=[packageJson.dependencies,packageJson.devDependencies,packageJson.peerDependencies,packageJson.optionalDependencies].some((deps)=>!!deps?.[dependencyName]);dependencyPresenceCache.set(cacheKey,hasDependency);return hasDependency}catch{dependencyPresenceCache.set(cacheKey,false);return false}}var REACT_CLIENT_INTERNALS_KEY="__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE",REACT_INTERNALS_KEYS,REACT_DOM_CLIENT_SHARE="react-dom/client",dependencyPresenceCache,packageDetectionCwd,installedPackageJsonCache,dependentsLookupCache,DEFAULT_EXPORT_CONDITIONS,MF_HASHED_NAME_THRESHOLD=90,MF_HASHED_NAME_HASH_LENGTH=16,MF_HASHED_NAME_PREFIX_LENGTH,mfHashedNameMap,sharedCacheHelperCode;var init_dtsConstants_r5OfegUr=__esm(()=>{init_sharedKeyMatcher_Od_nYxJA();init_logger_DOwfTlw5();REACT_INTERNALS_KEYS=[REACT_CLIENT_INTERNALS_KEY,"__TEST_INTERNALS","__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED"];dependencyPresenceCache=new Map;installedPackageJsonCache=new Map;dependentsLookupCache=new Map;DEFAULT_EXPORT_CONDITIONS=["browser","import","module","default"];MF_HASHED_NAME_PREFIX_LENGTH=MF_HASHED_NAME_THRESHOLD-MF_HASHED_NAME_HASH_LENGTH;mfHashedNameMap=new Map;sharedCacheHelperCode=`const __mfGetSharedCacheDescriptor = (pkg, singleton, version, scope) => {
|
|
6
6
|
const normalizedScope = Array.isArray(scope) ? scope[0] : scope;
|
|
7
7
|
const scopeName = normalizedScope || "default";
|
|
8
8
|
const id = singleton || !version ? pkg : pkg + "@" + version;
|
|
@@ -236,7 +236,7 @@ ${renderErrorCause(cause.cause,`${prefix} `)}
|
|
|
236
236
|
${prefix}}`}return stack};var FiberTypeId="~effect/Fiber";var fiberVariance={_A:identity,_E:identity};var fiberIdStore={id:0};var AsyncResource=(()=>{try{return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource}catch{return}})();var captureAsyncContext=()=>AsyncResource===undefined?undefined:new AsyncResource("effect/Fiber");var getCurrentFiber=()=>globalThis[currentFiberTypeId];class FiberImpl{constructor(context,interruptible=true){this.setContext(context);this.id=++fiberIdStore.id;this.currentOpCount=0;this.interruptible=interruptible;this._stack=[];this._observers=undefined;this._exit=undefined;this._children=undefined;this._interruptedCause=undefined;this._yielded=undefined;this._running=false;this._deferredInterrupt=false;this._parent=undefined;this._asyncContext=undefined;this.cache.runtimeMetrics?.recordFiberStart(this.context)}get[FiberTypeId](){return fiberVariance}get currentDispatcher(){return this._dispatcher??=this.cache.scheduler.makeDispatcher()}getRef(ref){return get(this.context,ref)}addObserver(cb){if(this._exit){cb(this._exit);return constVoid}if(this._observers===undefined){this._observers=[cb]}else{this._observers.push(cb)}return()=>this.removeObserver(cb)}removeObserver(cb){if(this._exit||this._observers===undefined)return;const index=this._observers.indexOf(cb);if(index>=0){this._observers.splice(index,1)}}interruptUnsafe(fiberId,annotations){if(this._exit){return}let cause=causeInterrupt(fiberId);if(this.cache.stackFrame){cause=causeAnnotate(cause,make4(StackTraceKey,this.cache.stackFrame))}if(annotations){cause=causeAnnotate(cause,annotations)}this._interruptedCause=this._interruptedCause?causeCombine(this._interruptedCause,cause):cause;if(this.interruptible){if(this._running){this._deferredInterrupt=true}else{this.evaluate(failCause(this._interruptedCause))}}}pollUnsafe(){return this._exit}evaluate(effect){if(this._exit){return}else if(this._asyncContext!==undefined){const asyncContext=this._asyncContext;this._asyncContext=undefined;return asyncContext.runInAsyncScope(this.evaluate,this,effect)}else if(this._yielded!==undefined){const yielded=this._yielded;this._yielded=undefined;yielded()}const exit=this.runLoop(effect);if(exit===Yield){this._asyncContext=captureAsyncContext();return}const interruptChildren=fiberMiddleware.interruptChildren&&fiberMiddleware.interruptChildren(this);if(interruptChildren!==undefined){return this.evaluate(flatMap2(interruptChildren,()=>exit))}this._exit=exit;this.cache.runtimeMetrics?.recordFiberEnd(this.context,this._exit);if(this._parent){this._parent._children?.delete(this);this._parent=undefined}if(this._observers!==undefined){const observers=this._observers;this._observers=undefined;for(let i=0;i<observers.length;i++){observers[i](exit)}}this._stack.length=0;this._children=undefined;this.context=empty()}runLoop(effect){const prevFiber=globalThis[currentFiberTypeId];globalThis[currentFiberTypeId]=this;const prevRunning=this._running;this._running=true;let yielding=false;let current=effect;this.currentOpCount=0;try{while(true){if(this._deferredInterrupt){this._deferredInterrupt=false;current=failCause(this._interruptedCause)}this.currentOpCount++;const cache=this.cache;if(!yielding&&!cache.preventYield&&cache.scheduler.shouldYield(this)){yielding=true;const prev=current;current=flatMap2(yieldNow,()=>prev)}current=cache.tracerContext?cache.tracerContext(current,this):current[evaluate](this);if(current===Yield){const yielded=this._yielded;if(ExitTypeId in yielded){this._deferredInterrupt=false;this._yielded=undefined;return yielded}else if(this._deferredInterrupt){this._yielded=undefined;yielded();continue}return Yield}}}catch(error){if(!hasProperty(current,evaluate)){return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`)}return this.runLoop(exitDie(error))}finally{this._running=prevRunning;globalThis[currentFiberTypeId]=prevFiber}}getCont(symbol){if(this._deferredInterrupt){this._deferredInterrupt=false;return deferredInterruptCont}while(true){const op=this._stack.pop();if(!op)return;const all=op[contAll];if(all!==undefined){const cont=all.call(op,this);if(cont){cont[symbol]=cont;return cont}}if(op[symbol])return op}}succeedWith(value){if((++this.currentOpCount&maxInlineSteps-1)===0){return exitSucceed(value)}const cont=this.getCont(contA);return cont?cont[contA](value,this):this.yieldWith(exitSucceed(value))}yieldWith(value){this._yielded=value;return Yield}children(){return this._children??=new Set}pipe(){return pipeArguments(this,arguments)}setContext(context){const previous=this.context;this.context=context;if(previous!==undefined&&hasSameCache(previous,context))return;const root=context.cacheRoot;const cache=root._fiberCache??=makeFiberContextCache(context);if(this.cache?.scheduler!==cache.scheduler){this._dispatcher=undefined}this.cache=cache}get currentSpanLocal(){const span=this.cache.span;return span?._tag==="Span"?span:undefined}}var makeFiberContextCache=(context)=>{const currentTracer=getOrUndefinedUnsafe(context,TracerKey);return{scheduler:get(context,Scheduler),tracer:currentTracer,tracerContext:currentTracer?currentTracer["context"]:undefined,tracerEnabled:get(context,TracerEnabled),span:getOrUndefinedUnsafe(context,ParentSpanKey),logLevel:get(context,CurrentLogLevel),minimumLogLevel:get(context,MinimumLogLevel),stackFrame:get(context,CurrentStackFrame),runtimeMetrics:getOrUndefinedUnsafe(context,FiberRuntimeMetricsKey),maxOpsBeforeYield:get(context,MaxOpsBeforeYield),preventYield:get(context,PreventSchedulerYield)}};var deferredInterruptCont={[contA](_value,fiber){return failCause(fiber._interruptedCause)},[contE](_cause,fiber){return failCause(fiber._interruptedCause)}};var maxInlineSteps=32;var fiberMiddleware={interruptChildren:undefined};var fiberStackAnnotations=(fiber)=>{if(!fiber.cache.stackFrame)return;const annotations=new Map;annotations.set(InterruptorStackTrace.key,fiber.cache.stackFrame);return makeUnsafe(annotations)};var fiberAwait=(self)=>{const impl=self;if(impl._exit)return succeed3(impl._exit);return callback((resume)=>{if(impl._exit)return resume(succeed3(impl._exit));return sync(self.addObserver((exit)=>resume(succeed3(exit))))})};var fiberAwaitAll=(self)=>callback((resume)=>{const iter=self[Symbol.iterator]();const exits=[];let cancel=undefined;function loop(){let result=iter.next();while(!result.done){if(result.value._exit){exits.push(result.value._exit);result=iter.next();continue}cancel=result.value.addObserver((exit)=>{exits.push(exit);loop()});return}resume(succeed3(exits))}loop();return sync(()=>cancel?.())});var fiberInterrupt=(self)=>withFiber((fiber)=>fiberInterruptAs(self,fiber.id));var fiberInterruptAs=dual((args)=>hasProperty(args[0],FiberTypeId),(self,fiberId,annotations)=>withFiber((parent)=>{let ann=fiberStackAnnotations(parent);ann=ann&&annotations?merge(ann,annotations):ann??annotations;self.interruptUnsafe(fiberId,ann);return asVoid(fiberAwait(self))}));var fiberInterruptAll=(fibers)=>withFiber((parent)=>{const annotations=fiberStackAnnotations(parent);let fiberArr=empty2();for(const fiber of fibers){fiber.interruptUnsafe(parent.id,annotations);fiberArr.push(fiber)}return asVoid(fiberAwaitAll(fiberArr))});var succeed3=exitSucceed;var failCause=exitFailCause;var fail3=exitFail;var sync=makePrimitive({op:"Sync",[evaluate](fiber){const value=this[args]();const cont=fiber.getCont(contA);return cont?cont[contA](value,fiber):fiber.yieldWith(exitSucceed(value))}});var suspend=makePrimitive({op:"Suspend",[evaluate](_fiber){return this[args]()}});var fromResult=match2({onFailure:fail3,onSuccess:succeed3});var yieldNowWith=makePrimitive({op:"Yield",[evaluate](fiber){let resumed=false;fiber.currentDispatcher.scheduleTask(()=>{if(resumed)return;fiber.evaluate(exitVoid)},this[args]??0);return fiber.yieldWith(()=>{resumed=true})}});var yieldNow=yieldNowWith(0);var succeedNone=succeed3(none2());var failCauseSync=(evaluate)=>suspend(()=>failCause(evaluate()));var die=(defect)=>exitDie(defect);var failSync=(error)=>suspend(()=>fail3(error()));var void_=succeed3(undefined);var try_=(options)=>{const evaluate=typeof options==="function"?options:options.try;const catcher=typeof options==="function"?(cause)=>new UnknownError(cause,"An error occurred in Effect.try"):options.catch;return suspend(()=>{try{return succeed3(evaluate())}catch(err){return fail3(catcher(err))}})};var promise=(evaluate)=>callbackOptions(function(resume,signal){evaluate(signal).then((a)=>resume(succeed3(a)),(e)=>resume(die(e)))},evaluate.length!==0);var tryPromise=(options)=>{const f=typeof options==="function"?options:options.try;const catcher=typeof options==="function"?(cause)=>new UnknownError(cause,"An error occurred in Effect.tryPromise"):options.catch;return callbackOptions(function(resume,signal){const failWithCatch=(cause)=>suspend(()=>{try{return fail3(internalCall(()=>catcher(cause)))}catch(err){return die(err)}});try{f(signal).then((a)=>resume(succeed3(a)),(e)=>resume(failWithCatch(e)))}catch(err){resume(failWithCatch(err))}},f.length!==0)};var withFiberId=(f)=>withFiber((fiber)=>f(fiber.id));var callbackOptions=function(){const Proto=makePrimitiveProto({op:"Async",[evaluate](fiber){let resumed=false;let yielded=false;const controller=this.withSignal?new AbortController:undefined;const onCancel=this.register.call(fiber.cache.scheduler,(effect)=>{if(resumed)return;resumed=true;if(yielded){fiber.evaluate(effect)}else{yielded=effect}},controller?.signal);if(yielded!==false)return yielded;yielded=true;fiber._yielded=()=>{resumed=true};if(controller===undefined&&onCancel===undefined){return Yield}fiber._stack.push(asyncFinalizer(()=>{resumed=true;controller?.abort();return onCancel??exitVoid}));return Yield}});const AsyncImpl=function(register,withSignal){this.register=register;this.withSignal=withSignal};AsyncImpl.prototype=Proto;return function(register,withSignal){return new AsyncImpl(register,withSignal)}}();var asyncFinalizer=makePrimitive({op:"AsyncFinalizer",[contAll](fiber){if(fiber.interruptible){fiber.interruptible=false;fiber._stack.push(setInterruptibleTrue)}},[contE](cause,_fiber){return hasInterrupts(cause)?flatMap2(combineFinalizerCause(exitFailCause(cause),this[args]()),()=>failCause(cause)):failCause(cause)}});var callback=(register)=>callbackOptions(register,register.length>=2);var never=callback(constVoid);var gen=(...args)=>{if(args.length===1){const body=args[0];return suspend(()=>fromIteratorUnsafe(body()))}const[options,body]=args;return suspend(()=>fromIteratorUnsafe(body.call(options.self)))};var fnUntraced=(body,...pipeables)=>{const fn=pipeables.length===0?function(){return suspend(()=>fromIteratorUnsafe(body.apply(this,arguments)))}:function(){let effect=suspend(()=>fromIteratorUnsafe(body.apply(this,arguments)));for(let i=0;i<pipeables.length;i++){effect=pipeables[i](effect,...arguments)}return effect};return defineFunctionLength(body.length,fn)};var defineFunctionLength=(length,fn)=>Object.defineProperty(fn,"length",{value:length,configurable:true});var fnStackCleaner=makeStackCleaner(2);var fn=function(){const nameFirst=typeof arguments[0]==="string";const name=nameFirst?arguments[0]:"Effect.fn";const spanOptions=nameFirst?arguments[1]:undefined;const prevLimit=getStackTraceLimit();let defError;if(prevLimit!==0){setStackTraceLimit(2);defError=new globalThis.Error;setStackTraceLimit(prevLimit)}if(nameFirst){return(body,...pipeables)=>makeFn(name,body,defError,pipeables,nameFirst,spanOptions)}return makeFn(name,arguments[0],defError,Array.prototype.slice.call(arguments,1),nameFirst,spanOptions)};var makeFn=(name,bodyOrOptions,defError,pipeables,addSpan,spanOptions)=>{const body=typeof bodyOrOptions==="function"?bodyOrOptions:pipeables.shift().bind(bodyOrOptions.self);const definitionName=`${name} (definition)`;const definitionStack=defError?fnStackCleaner(()=>defError.stack):constUndefined;return defineFunctionLength(body.length,function(...args){let result=suspend(()=>{const iter=body.apply(this,arguments);return isEffect(iter)?iter:fromIteratorUnsafe(iter)});for(let i=0;i<pipeables.length;i++){result=pipeables[i](result,...args)}if(!isEffect(result)){return result}const prevLimit=getStackTraceLimit();let callError;if(prevLimit!==0){setStackTraceLimit(2);callError=new globalThis.Error;setStackTraceLimit(prevLimit)}return updateService(addSpan?useSpan(name,spanOptions,(span)=>provideParentSpan(result,span)):result,CurrentStackFrame,(prev)=>({name,stack:callError?fnStackCleaner(()=>callError.stack):constUndefined,parent:{name:definitionName,stack:definitionStack,parent:prev}}))})};var fnUntracedEager=(body,...pipeables)=>defineFunctionLength(body.length,pipeables.length===0?function(){return fromIteratorEagerUnsafe(()=>body.apply(this,arguments))}:function(){let effect=fromIteratorEagerUnsafe(()=>body.apply(this,arguments));for(const pipeable of pipeables){effect=pipeable(effect,...arguments)}return effect});var fromIteratorEagerUnsafe=(evaluate)=>{try{const iterator=evaluate();let value=undefined;while(true){const state=iterator.next(value);if(state.done){return succeed3(state.value)}const primitive=state.value;if(primitive&&primitive._tag==="Success"){value=primitive.value;continue}else if(primitive&&primitive._tag==="Failure"){return state.value}else{let isFirstExecution=true;return suspend(()=>{if(isFirstExecution){isFirstExecution=false;return flatMap2(state.value,(value)=>fromIteratorUnsafe(iterator,value))}else{return suspend(()=>fromIteratorUnsafe(evaluate()))}})}}}catch(error){return die(error)}};var fromIteratorUnsafe=function(){const Proto=makePrimitiveProto({op:"Iterator",[contA](value,fiber){const iter=this.iterator;while(true){const state=iter.next(value);if(state.done)return succeed3(state.value);if(!effectIsExit(state.value)){fiber._stack.push(this);return state.value}else if(state.value._tag==="Failure"){return state.value}value=state.value.value}},[evaluate](fiber){return this[contA](this.initial,fiber)}});const IteratorImpl=function(iterator,initial){this.iterator=iterator;this.initial=initial};IteratorImpl.prototype=Proto;return function(iterator,initial){return new IteratorImpl(iterator,initial)}}();var as=dual(2,(self,value)=>new ContImpl(self,returnPayload,succeed3(value)));var evaluateCont=function(fiber){fiber._stack.push(this);return this[args]};var OnSuccessProto=makePrimitiveProto({op:"OnSuccess",[evaluate]:evaluateCont});var ContImpl=function(self,cont,payload){this[args]=self;this[contA]=cont;this.payload=payload};ContImpl.prototype=OnSuccessProto;var returnPayload=function(){return this.payload};var succeedPayload=function(_value,fiber){return fiber.succeedWith(this.payload)};var continuationMarksStack=(()=>{const marker="~effect/Effect/stackProbe";const probe={[marker]:function stackProbe(){return new Error().stack}};return probe[marker]()?.includes("[as "+marker+"]")===true})();var mapCont=function(value,fiber){const f=this.payload;return fiber.succeedWith(continuationMarksStack?f(value):internalCall(()=>f(value)))};var andThenCont=function(value){const f=this.payload;return f(value)};var tapCont=function(value){const f=this.payload;return new ContImpl(f(value),succeedPayload,value)};var tapEffectCont=function(value){return new ContImpl(this.payload,succeedPayload,value)};var asSome=(self)=>map2(self,some2);var andThen=dual(2,(self,f)=>new ContImpl(self,isEffect(f)?returnPayload:andThenCont,f));var tap=dual(2,(self,f)=>new ContImpl(self,isEffect(f)?tapEffectCont:tapCont,f));var asVoid=(self)=>new ContImpl(self,returnPayload,exitVoid);var raceAllFirst=(all,options)=>withFiber((parent)=>{const fibers=new Set;onExitUnsafe(parent,()=>fibers.size===0?undefined:fiberInterruptAll(fibers));return callback((resume)=>{let done=false;let i=0;for(const effect of all){if(done)break;const index=i++;const fiber=forkUnsafe(parent,effect,true,true,false);fibers.add(fiber);fiber.addObserver((exit)=>{fibers.delete(fiber);const isWinner=!done;done=true;resume(exit);if(isWinner&&options?.onWinner){options.onWinner({fiber,index,parentFiber:parent})}})}})});var raceFirst=dual((args)=>isEffect(args[1]),(self,that,options)=>raceAllFirst([self,that],options));var flatMap2=dual(2,(self,f)=>new ContImpl(self,andThenCont,f));var effectIsExit=(effect)=>effect[ExitTypeId]!==undefined;var flatMapEager=dual(2,(self,f)=>{if(effectIsExit(self)){return self._tag==="Success"?f(self.value):self}return flatMap2(self,f)});var flatten2=(self)=>flatMap2(self,identity);var map2=dual(2,(self,f)=>new ContImpl(self,mapCont,f));var mapEager=dual(2,(self,f)=>effectIsExit(self)?exitMap(self,f):map2(self,f));var mapErrorEager=dual(2,(self,f)=>effectIsExit(self)?exitMapError(self,f):mapError(self,f));var mapBothEager=dual(2,(self,options)=>effectIsExit(self)?exitMapBoth(self,options):mapBoth(self,options));var catchEager=dual(2,(self,f)=>{if(effectIsExit(self)){if(self._tag==="Success")return self;const error=findError(self.cause);if(isFailure2(error))return self;return f(error.success)}return catch_(self,f)});var exitInterrupt=(fiberId)=>exitFailCause(causeInterrupt(fiberId));var exitIsSuccess=(self)=>self._tag==="Success";var exitVoid=exitSucceed(undefined);var exitMap=dual(2,(self,f)=>self._tag==="Success"?exitSucceed(f(self.value)):self);var exitMapError=dual(2,(self,f)=>{if(self._tag==="Success")return self;const error=findError(self.cause);if(isFailure2(error))return self;return exitFail(f(error.success))});var exitMapBoth=dual(2,(self,options)=>{if(self._tag==="Success")return exitSucceed(options.onSuccess(self.value));const error=findError(self.cause);if(isFailure2(error))return self;return exitFail(options.onFailure(error.success))});var exitZipRight=dual(2,(self,that)=>exitIsSuccess(self)?that:self);var exitAsVoidAll=(exits)=>{const failures=[];for(const exit of exits){if(exit._tag==="Failure"){failures.push(...exit.cause.reasons)}}return failures.length===0?exitVoid:exitFailCause(causeFromReasons(failures))};var serviceOption=(service)=>withFiber((fiber)=>succeed3(getOption(fiber.context,service)));var updateContext=dual(2,(self,f)=>withFiber((fiber)=>{const prevContext=fiber.context;const nextContext=f(prevContext);if(prevContext===nextContext)return self;fiber.setContext(nextContext);onExitUnsafe(fiber,()=>{fiber.setContext(prevContext);return});return self}));var updateService=dual(3,(self,service,f)=>updateContext(self,(s)=>{const prev=getUnsafe(s,service);const next=f(prev);if(prev===next)return s;return add(s,service,next)}));var context=()=>getContext;var getContext=withFiber((fiber)=>succeed3(fiber.context));var contextWith=(f)=>withFiber((fiber)=>f(fiber.context));var provideContext=dual(2,(self,context)=>{if(effectIsExit(self))return self;return updateContext(self,merge(context))});var provideService=function(){if(arguments.length===1){return dual(2,(self,impl)=>provideServiceImpl(self,arguments[0],impl))}return dual(3,(self,service,impl)=>provideServiceImpl(self,service,impl)).apply(this,arguments)};var provideServiceImpl=(self,service,implementation)=>updateContext(self,add(service,implementation));var forever=dual((args)=>isEffect(args[0]),(self,options)=>whileLoop({while:constTrue,body:constant(options?.disableYield?self:flatMap2(self,(_)=>yieldNow)),step:constVoid}));var catchCause=dual(2,(self,f)=>new OnFailureImpl(self,f.length!==1?(cause)=>f(cause):f));var OnFailureProto=makePrimitiveProto({op:"OnFailure",[evaluate]:evaluateCont});var OnFailureImpl=function(self,f){this[args]=self;this[contE]=f};OnFailureImpl.prototype=OnFailureProto;var catchCauseFilter=dual(3,(self,filter,f)=>catchCause(self,(cause)=>{const eb=filter(cause);return isFailure2(eb)?failCause(eb.failure):f(eb.success,cause)}));var catch_=dual(2,(self,f)=>catchCauseFilter(self,findError,(e)=>f(e)));var catchDefect=dual(2,(self,f)=>catchCauseFilter(self,findDefect,f));var tapCauseFilter=dual(3,(self,filter,f)=>catchCause(self,(cause)=>{const result=filter(cause);if(isFailure2(result)){return failCause(cause)}return andThen(f(result.success,cause),failCause(cause))}));var tapError=dual(2,(self,f)=>tapCauseFilter(self,findError,(e)=>f(e)));var tapDefect=dual(2,(self,f)=>tapCauseFilter(self,findDefect,(_)=>f(_)));var catchIf=dual((args)=>isEffect(args[0]),(self,predicate,f,orElse)=>catchCause(self,(cause)=>{const error=findError(cause);if(isFailure2(error))return failCause(error.failure);if(!predicate(error.success)){return orElse?orElse(error.success):failCause(cause)}return f(error.success)}));var catchTag=dual((args)=>isEffect(args[0]),(self,k,f,orElse)=>{const pred=Array.isArray(k)?(e)=>hasProperty(e,"_tag")&&k.includes(e._tag):isTagged(k);return catchIf(self,pred,f,orElse)});var mapError=dual(2,(self,f)=>catch_(self,(error)=>failSync(()=>f(error))));var mapBoth=dual(2,(self,options)=>matchEffect(self,{onFailure:(e)=>failSync(()=>options.onFailure(e)),onSuccess:(a)=>sync(()=>options.onSuccess(a))}));var orDie=(self)=>catch_(self,die);var orElseSucceed=dual(2,(self,f)=>catch_(self,(error)=>sync(()=>f(error))));var ignore=dual((args)=>isEffect(args[0]),(self,options)=>{if(!options?.log){return matchEffect(self,{onFailure:(_)=>void_,onSuccess:(_)=>void_})}const logEffect=logWithLevel(options.log===true?undefined:options.log);return matchCauseEffect(self,{onFailure(cause){const failure=findFail(cause);return isFailure2(failure)?failCause(failure.failure):options.message===undefined?logEffect(cause):logEffect(options.message,cause)},onSuccess:(_)=>void_})});var option=(self)=>match4(self,{onFailure:none2,onSuccess:some2});var result=(self)=>matchEager(self,{onFailure:fail2,onSuccess:succeed2});var matchCauseEffect=dual(2,(self,options)=>new OnSuccessAndFailureImpl(self,options.onSuccess.length!==1?(a)=>options.onSuccess(a):options.onSuccess,options.onFailure.length!==1?(cause)=>options.onFailure(cause):options.onFailure));var OnSuccessAndFailureProto=makePrimitiveProto({op:"OnSuccessAndFailure",[evaluate]:evaluateCont});var OnSuccessAndFailureImpl=function(self,onSuccess,onFailure){this[args]=self;this[contA]=onSuccess;this[contE]=onFailure};OnSuccessAndFailureImpl.prototype=OnSuccessAndFailureProto;var matchSuccess=function(value,fiber){const handlers=this.payload;return fiber.succeedWith(continuationMarksStack?handlers.onSuccess(value):internalCall(()=>handlers.onSuccess(value)))};var makeMatch=(op,onFailure)=>{const Proto=makePrimitiveProto({op,[evaluate]:evaluateCont,[contA]:matchSuccess,[contE]:onFailure});const MatchImpl=function(self,handlers){this[args]=self;this.payload=handlers};MatchImpl.prototype=Proto;return MatchImpl};var MatchImpl=makeMatch("Match",function(cause,fiber){const fail=cause.reasons.find(isFailReason);if(fail===undefined)return failCause(cause);const handlers=this.payload;return fiber.succeedWith(continuationMarksStack?handlers.onFailure(fail.error):internalCall(()=>handlers.onFailure(fail.error)))});var matchEffect=dual(2,(self,options)=>matchCauseEffect(self,{onFailure:(cause)=>{const fail=cause.reasons.find(isFailReason);return fail?options.onFailure(fail.error):failCause(cause)},onSuccess:options.onSuccess}));var match4=dual(2,(self,options)=>new MatchImpl(self,options));var matchEager=dual(2,(self,options)=>{if(effectIsExit(self)){if(self._tag==="Success")return exitSucceed(options.onSuccess(self.value));const error=findError(self.cause);if(isFailure2(error))return self;return exitSucceed(options.onFailure(error.success))}return match4(self,options)});var exit=(self)=>effectIsExit(self)?exitSucceed(self):exitPrimitive(self);var exitPrimitive=makePrimitive({op:"Exit",[evaluate](fiber){fiber._stack.push(this);return this[args]},[contA](value,fiber,exit){return fiber.succeedWith(exit??exitSucceed(value))},[contE](cause,fiber,exit){return fiber.succeedWith(exit??exitFailCause(cause))}});var delay=dual(2,(self,duration)=>andThen(sleep(duration),self));var timeoutOrElse=dual(2,(self,options)=>flatMap2(timeoutOption(self,options.duration),(option)=>isNone2(option)?options.orElse():succeed3(option.value)));var timeoutErrorFromDuration=(duration)=>new TimeoutError(`Operation timed out after '${format2(duration)}'`);var timeout=dual(2,(self,duration)=>{const decoded=fromInputUnsafe2(duration);return timeoutOrElse(self,{duration:decoded,orElse:()=>fail3(timeoutErrorFromDuration(decoded))})});var timeoutOption=dual(2,(self,duration)=>raceFirst(asSome(self),as(sleep(duration),none2())));var ScopeTypeId="~effect/Scope";var ScopeCloseableTypeId="~effect/Scope/Closeable";var scopeTag=Service("effect/Scope");var scopeClose=(self,exit_)=>withFiber((fiber)=>{const close=scopeCloseUnsafe(self,exit_);if(close===undefined)return void_;fiberEnterUninterruptibleUnsafe(fiber);return close});var scopeCloseUnsafe=(self,exit_)=>{const state=self.state;if(state._tag==="Closed")return;self.state={_tag:"Closed",exit:exit_};if(self.parent!==undefined){scopeRemoveFinalizerUnsafe(self.parent,self)}if(state._tag==="Empty")return;if(state.finalizer!==undefined){return runFinalizer(state.finalizer,exit_)}const finalizers=state.finalizers;if(finalizers.size===1){return runFinalizer(finalizers.values().next().value,exit_)}return scopeCloseFinalizers(self,finalizers,exit_)};var runFinalizer=(finalizer,exit_)=>{try{return finalizer(exit_)}catch(defect){return exitDie(defect)}};var combineFinalizerCause=(exit_,finalizer)=>exitIsSuccess(exit_)?finalizer:catchCause(finalizer,(cause)=>failCause(causeCombine(exit_.cause,cause)));var scopeCloseFinalizers=fnUntraced(function*(self,finalizers,exit_){let exits=[];const fibers=[];const arr=Array.from(finalizers.values());const parent=getCurrentFiber();for(let i=arr.length-1;i>=0;i--){const finalizer=arr[i];if(self.strategy==="sequential"){exits.push(yield*exit(runFinalizer(finalizer,exit_)))}else{fibers.push(forkUnsafe(parent,runFinalizer(finalizer,exit_),true,true,"inherit"))}}if(fibers.length>0){exits=yield*fiberAwaitAll(fibers)}return yield*exitAsVoidAll(exits)});var scopeForkUnsafe=(scope,finalizerStrategy)=>{const child=makeScope(finalizerStrategy,scope);if(scope.state._tag==="Closed"){child.state=scope.state;return child}scopeAddFinalizerUnsafe(scope,child,(exit)=>scopeClose(child,exit));return child};var scopeAddFinalizerExit=(scope,finalizer)=>{return suspend(()=>{if(scope.state._tag==="Closed"){return finalizer(scope.state.exit)}scopeAddFinalizerUnsafe(scope,{},finalizer);return void_})};var scopeAddFinalizer=(scope,finalizer)=>scopeAddFinalizerExit(scope,constant(finalizer));var scopeAddFinalizerUnsafe=(scope,key,finalizer)=>{if(scope.state._tag==="Empty"){scope.state={_tag:"Open",finalizerKey:key,finalizer,finalizers:undefined}}else if(scope.state._tag==="Open"){const state=scope.state;if(state.finalizer!==undefined){state.finalizers=new Map([[state.finalizerKey,state.finalizer]]);state.finalizerKey=undefined;state.finalizer=undefined;state.finalizers.set(key,finalizer)}else{state.finalizers.set(key,finalizer)}}};var scopeRemoveFinalizerUnsafe=(scope,key)=>{if(scope.state._tag!=="Open")return;const state=scope.state;if(state.finalizerKey===key){scope.state=constScopeEmpty}else if(state.finalizers!==undefined){state.finalizers.delete(key);if(state.finalizers.size===0){scope.state=constScopeEmpty}}};var scopeMakeUnsafe=(finalizerStrategy)=>makeScope(finalizerStrategy,undefined);var makeScope=(finalizerStrategy="sequential",parent)=>({[ScopeCloseableTypeId]:ScopeCloseableTypeId,[ScopeTypeId]:ScopeTypeId,strategy:finalizerStrategy,parent,state:constScopeEmpty});var constScopeEmpty={_tag:"Empty"};var scope=scopeTag;var provideScope=provideService(scopeTag);var scopedWith=(f)=>suspend(()=>{const scope=scopeMakeUnsafe();return onExit(f(scope),(exit)=>suspend(()=>scopeCloseUnsafe(scope,exit)??void_))});var acquireRelease=(acquire,release,options)=>contextWith((context)=>uninterruptibleMask((restore)=>flatMap2(scope,(scope)=>tap(options?.interruptible?restore(acquire):acquire,(a)=>scopeAddFinalizerExit(scope,(exit)=>provideContext(release(a,exit),context))))));var OnExitImpl=function(){const Proto=makePrimitiveProto({op:"OnExit",[evaluate](fiber){fiber._stack.push(this);return this.effect},[contAll](fiber){if(fiber.interruptible&&this.interruptible!==true){fiber._stack.push(setInterruptibleTrue);fiber.interruptible=false}},[contA](value,_,exit){exit??=exitSucceed(value);let eff;try{eff=this.onExit(exit)}catch(defect){eff=exitDie(defect)}return eff?flatMap2(eff,(_)=>exit):exit},[contE](cause,_,exit){exit??=exitFailCause(cause);let eff;try{eff=this.onExit(exit)}catch(defect){eff=exitDie(defect)}return eff?flatMap2(combineFinalizerCause(exit,eff),(_)=>exit):exit}});const OnExitImpl=function(effect,onExit,interruptible){this.effect=effect;this.onExit=onExit;this.interruptible=interruptible};OnExitImpl.prototype=Proto;return OnExitImpl}();var onExitPrimitive=(effect,onExit,interruptible)=>new OnExitImpl(effect,onExit,interruptible);var onExitUnsafe=(fiber,f)=>{fiber._stack.push(new OnExitImpl(undefined,f,undefined))};var onExit=dual(2,onExitPrimitive);var ensuring=dual(2,(self,finalizer)=>onExit(self,(_)=>finalizer));var acquireUseRelease=(acquire,use,release)=>uninterruptibleMask((restore)=>flatMap2(acquire,(a)=>onExitPrimitive(suspend(()=>restore(use(a))),(exit)=>release(a,exit),true)));var uninterruptible=(self)=>withFiber((fiber)=>{if(!fiber.interruptible)return self;fiber.interruptible=false;fiber._stack.push(setInterruptibleTrue);return self});var setInterruptible=makePrimitive({op:"SetInterruptible",[contAll](fiber){fiber.interruptible=this[args];if(fiber._interruptedCause&&fiber.interruptible){return()=>failCause(fiber._interruptedCause)}}});var setInterruptibleTrue=setInterruptible(true);var setInterruptibleFalse=setInterruptible(false);var setFiberInterruptible=(fiber)=>{fiber.interruptible=true;fiber._stack.push(setInterruptibleFalse);if(fiber._interruptedCause)return failCause(fiber._interruptedCause)};var fiberEnterUninterruptibleUnsafe=(fiber)=>{const impl=fiber;if(!impl.interruptible)return;impl.interruptible=false;impl._stack.push(setInterruptibleTrue)};var interruptible=(self)=>withFiber((fiber)=>{if(fiber.interruptible)return self;return setFiberInterruptible(fiber)??self});var uninterruptibleMask=(f)=>withFiber((fiber)=>{if(!fiber.interruptible)return f(identity);fiber.interruptible=false;fiber._stack.push(setInterruptibleTrue);return f(interruptible)});var all=(arg,options)=>{if(isIterable(arg)){return options?.mode==="result"?forEach(arg,result,options):forEach(arg,identity,options)}else if(options?.discard){return options.mode==="result"?forEach(Object.values(arg),result,options):forEach(Object.values(arg),identity,options)}return suspend(()=>{const out={};return as(forEach(Object.entries(arg),([key,effect])=>map2(options?.mode==="result"?result(effect):effect,(value)=>{assignProperty(out,key,value)}),{discard:true,concurrency:options?.concurrency}),out)})};var whileLoop=makePrimitive({op:"While",[contA](value,fiber){this[args].step(value);if(this[args].while()){fiber._stack.push(this);return this[args].body()}return exitVoid},[evaluate](fiber){if(this[args].while()){fiber._stack.push(this);return this[args].body()}return exitVoid}});var forEach=dual((args)=>typeof args[1]==="function",(iterable,f,options)=>suspend(()=>{const concurrency=resolveConcurrency(options?.concurrency);if(concurrency===1){return forEachSequential(iterable,f,options)}const items=fromIterable(iterable);let length=items.length;if(length===0){return options?.discard?void_:succeed3([])}const out=options?.discard?undefined:new Array(length);const eff=forEachConcurrent({f,out},items,{concurrency});return eff?as(eff,out):succeed3(out)}));var forEachSequential=(iterable,f,options)=>suspend(()=>{const out=options?.discard?undefined:[];const iterator=iterable[Symbol.iterator]();let state=iterator.next();let index=0;return as(whileLoop({while:()=>!state.done,body:()=>f(state.value,index++),step:(b)=>{if(out)out.push(b);state=iterator.next()}}),out)});var resolveConcurrency=(concurrency)=>concurrency==="unbounded"?Number.POSITIVE_INFINITY:Math.max(1,concurrency??1);var iterateEager=()=>(options)=>{const onItem=options.onItem;const step=options.step;const resumeSequential=(state,items,index,end,effect)=>flatMap2(exit(effect),(itemExit)=>step(state,items[index],itemExit,index)??runSequential(state,items,index+1,end)??void_);const runSequential=(state,items,index=0,end=items.length)=>{for(;index<end;index++){const item=items[index];const effect=onItem(state,item,index);if(!effectIsExit(effect)){return resumeSequential(state,items,index,end,effect)}const terminal=step(state,item,effect,index);if(terminal)return terminal._tag==="Failure"?terminal:undefined}};return runSequential};var iterateConcurrentImpl=(options)=>{const onItem=options.onItem;const step=options.step;return(state,items,opts)=>{let index=0;const end=opts.end??items.length;const concurrency=opts.concurrency;let done=false;let parentFiber;let fibers;let resume;let terminal;let effect;const failDefect=(error)=>{const defect=exitDie(error);terminal=defect;done=true;return fibers&&fibers.size>0?flatMap2(uninterruptible(fiberInterruptAll(Array.from(fibers))),()=>terminal??defect):defect};const go=()=>{let paused=false;for(;!terminal&&index<end;index++){const item=items[index];const eff=effect??onItem(state,item,index);if(effectIsExit(eff)){terminal=step(state,item,eff,index);if(terminal)break}else if(!parentFiber){return callback((cb)=>{parentFiber=getCurrentFiber();fibers=new Set;effect=eff;resume=cb;let result;try{result=go()}catch(error){return cb(failDefect(error))}if(result)return cb(result);return suspend(()=>{terminal??=exitVoid;return flatMap2(fibers?fiberInterruptAll(fibers):void_,()=>terminal?._tag==="Failure"?terminal:void_)})})}else{effect=undefined;const fiber=forkUnsafe(parentFiber,eff,true,true,"inherit");if(fiber._exit){terminal=step(state,item,fiber._exit,index);if(terminal)break;continue}fibers.add(fiber);const currentIndex=index;fiber.addObserver((exit)=>{fibers.delete(fiber);try{if(terminal){if(exit._tag==="Failure"){const reasons=exit.cause.reasons.filter((reason)=>reason._tag!=="Interrupt");if(reasons.length>0){const cause=causeFromReasons(reasons);terminal=exitFailCause(terminal._tag==="Failure"?causeCombine(terminal.cause,cause):cause)}}}else{const result=step(state,item,exit,currentIndex);if(result){terminal=result;go()}}if(paused){const eff=go();if(eff)resume(eff)}else if(done&&fibers.size===0){resume(terminal??void_)}}catch(error){resume(failDefect(error))}});if(fibers.size<concurrency)continue;paused=true;index++;return}}done=true;if(terminal){if(fibers&&fibers.size>0){const annotations=fiberStackAnnotations(parentFiber);fibers.forEach((f)=>f.interruptUnsafe(parentFiber.id,annotations));return}if(resume||terminal._tag==="Failure"){return terminal}}else if(resume){if(!fibers){return exitVoid}else if(fibers.size===0){resume(void_)}}};return go()}};var iterateConcurrent=()=>(options)=>iterateConcurrentImpl(options);var forEachConcurrent=iterateConcurrentImpl({onItem(state,item,index){return state.f(item,index)},step(state,_,exit,index){if(exit._tag==="Failure")return exit;else if(state.out){state.out[index]=exit.value}}});var forkUnsafe=(parent,effect,immediate=false,daemon=false,uninterruptible=false)=>{const parentRuntime=parent;const interruptible=uninterruptible==="inherit"?parentRuntime.interruptible:!uninterruptible;const child=new FiberImpl(parentRuntime.context,interruptible);if(immediate){child.evaluate(effect)}else{child._asyncContext=captureAsyncContext();parentRuntime.currentDispatcher.scheduleTask(()=>child.evaluate(effect),0)}if(!daemon&&!child._exit){parentRuntime.children().add(child);child._parent=parentRuntime}return child};var forkIn=dual((args)=>isEffect(args[0]),(self,scope,options)=>withFiber((parent)=>{const fiber=forkUnsafe(parent,self,options?.startImmediately,true,options?.uninterruptible);if(!fiber._exit){if(scope.state._tag!=="Closed"){const key={};const finalizer=()=>withFiberId((interruptor)=>interruptor===fiber.id?void_:fiberInterrupt(fiber));scopeAddFinalizerUnsafe(scope,key,finalizer);fiber.addObserver(()=>scopeRemoveFinalizerUnsafe(scope,key))}else{fiber.interruptUnsafe(parent.id,fiberStackAnnotations(parent))}}return succeed3(fiber)}));var runForkWith=(context)=>(effect,options)=>{const fiber=new FiberImpl(options?.scheduler?add(context,Scheduler,options.scheduler):context,options?.uninterruptible!==true);fiber.evaluate(effect);if(fiber._exit)return fiber;if(options?.signal){if(options.signal.aborted){fiber.interruptUnsafe()}else{const abort=()=>fiber.interruptUnsafe();options.signal.addEventListener("abort",abort,{once:true});fiber.addObserver(()=>options.signal.removeEventListener("abort",abort))}}if(options?.onFiberStart){options.onFiberStart(fiber)}return fiber};var runFork=runForkWith(empty());var runPromiseExitWith=(context)=>{const runFork=runForkWith(context);return(effect,options)=>{const fiber=runFork(effect,options);return new Promise((resolve)=>{fiber.addObserver((exit)=>resolve(exit))})}};var runPromiseExit=runPromiseExitWith(empty());var runPromiseWith=(context)=>{const runPromiseExit=runPromiseExitWith(context);return(effect,options)=>runPromiseExit(effect,options).then((exit)=>{if(exit._tag==="Failure"){throw causeSquash(exit.cause)}return exit.value})};var runPromise=runPromiseWith(empty());var runSyncExitWith=(context)=>{const runFork=runForkWith(context);return(effect)=>{if(effectIsExit(effect))return effect;const scheduler=new MixedScheduler("sync");const fiber=runFork(effect,{scheduler});fiber._dispatcher?.flush();return fiber._exit??exitDie(new AsyncFiberError(fiber))}};var runSyncExit=runSyncExitWith(empty());var runSyncWith=(context)=>{const runSyncExit=runSyncExitWith(context);return(effect)=>{const exit=runSyncExit(effect);if(exit._tag==="Failure")throw causeSquash(exit.cause);return exit.value}};var runSync=runSyncWith(empty());var bigint03=BigInt(0);var NoopSpanProto={_tag:"Span",spanId:"noop",traceId:"noop",sampled:false,status:{_tag:"Ended",startTime:bigint03,endTime:bigint03,exit:exitVoid},attributes:new Map,links:[],kind:"internal",attribute(){},event(){},end(){},addLinks(){}};var noopSpan=(options)=>Object.assign(Object.create(NoopSpanProto),options);var filterDisablePropagation=(span)=>{if(!span)return none2();return get(span.annotations,DisablePropagation)?span._tag==="Span"?filterDisablePropagation(getOrUndefined(span.parent)):none2():some2(span)};var makeSpanUnsafe=(fiber,name,options)=>{const disablePropagation=!fiber.cache.tracerEnabled||options?.annotations&&get(options.annotations,DisablePropagation);const parent=options?.parent!==undefined?some2(options.parent):options?.root?none2():filterDisablePropagation(fiber.cache.span);let span;if(disablePropagation){span=noopSpan({name,parent,annotations:add(options?.annotations??empty(),DisablePropagation,true)})}else{const tracer=fiber.cache.tracer??nativeTracer;const clock=fiber.getRef(ClockRef);const timingEnabled=fiber.getRef(TracerTimingEnabled);const annotationsFromEnv=fiber.getRef(TracerSpanAnnotations);const linksFromEnv=fiber.getRef(TracerSpanLinks);const level=options?.level??fiber.getRef(CurrentTraceLevel);const links=options?.links!==undefined?[...linksFromEnv,...options.links]:linksFromEnv.length===0?[]:linksFromEnv.slice();span=tracer.span({name,parent,annotations:options?.annotations??empty(),links,startTime:timingEnabled?clock.currentTimeNanosUnsafe():bigint03,kind:options?.kind??"internal",root:options?.root??isNone2(parent),sampled:options?.sampled??(isSome2(parent)&&parent.value.sampled===false?false:!isLogLevelGreaterThan(fiber.getRef(MinimumTraceLevel),level))});for(const key in annotationsFromEnv){span.attribute(key,annotationsFromEnv[key])}if(options?.attributes!==undefined){for(const key in options.attributes){span.attribute(key,options.attributes[key])}}}return span};var endSpan=(span,exit,clock,timingEnabled)=>sync(()=>{if(span.status._tag==="Ended")return;span.end(timingEnabled?clock.currentTimeNanosUnsafe():bigint03,exit)});var useSpan=(name,...args)=>{const options=args.length===1?undefined:args[0];const evaluate=args[args.length-1];return withFiber((fiber)=>{const span=makeSpanUnsafe(fiber,name,options);const clock=fiber.getRef(ClockRef);const timingEnabled=fiber.getRef(TracerTimingEnabled);onExitUnsafe(fiber,(exit)=>endSpan(span,exit,clock,timingEnabled));return evaluate(span)})};var provideParentSpan=provideService(ParentSpan);var ClockRef=Reference("effect/Clock",{defaultValue:()=>new ClockImpl});var MAX_TIMER_MILLIS=2**31-1;class ClockImpl{currentTimeMillisUnsafe(){return Date.now()}currentTimeMillis=sync(()=>this.currentTimeMillisUnsafe());currentTimeNanosUnsafe(){return wallTimeNanos()}currentTimeNanos=sync(()=>this.currentTimeNanosUnsafe());monotonicTimeNanosUnsafe(){return monotonicNowNanos()}monotonicTimeNanos=sync(()=>this.monotonicTimeNanosUnsafe());sleep(duration){return this.sleepMillis(toMillis(duration))}sleepMillis(millis){if(millis<=0)return yieldNow;else if(!Number.isFinite(millis))return never;return callback((resume)=>{const continuation=millis>MAX_TIMER_MILLIS?this.sleepMillis(millis-MAX_TIMER_MILLIS):void_;const handle=setTimeout(()=>resume(continuation),Math.min(millis,MAX_TIMER_MILLIS));return sync(()=>clearTimeout(handle))})}}var nanosPerMilli=BigInt(1e6);var monotonicNowNanos=function(){const processHrtime=globalThis.process?.hrtime;if(typeof processHrtime?.bigint==="function"){return()=>processHrtime.bigint()}if(typeof performance!=="undefined"&&typeof performance.now==="function"){return()=>BigInt(Math.round(performance.now()*1e6))}let previous=BigInt(0);return()=>{const current=BigInt(Date.now())*nanosPerMilli;if(current>previous){previous=current}return previous}}();var wallTimeNanos=function(){const reanchorThresholdNanos=BigInt(1e9);let origin;return()=>{const monotonic=monotonicNowNanos();const wall=BigInt(Date.now())*nanosPerMilli;if(origin===undefined){origin=wall-monotonic}else{const projected=origin+monotonic;const skew=wall>projected?wall-projected:projected-wall;if(skew>reanchorThresholdNanos){origin=wall-monotonic}}return origin+monotonic}}();var clockWith=(f)=>withFiber((fiber)=>f(fiber.getRef(ClockRef)));var sleep=(duration)=>clockWith((clock)=>clock.sleep(fromInputUnsafe2(duration)));var TimeoutErrorTypeId="~effect/Cause/TimeoutError";class TimeoutError extends TaggedError("TimeoutError"){[TimeoutErrorTypeId]=TimeoutErrorTypeId;constructor(message){super({message})}}var AsyncFiberErrorTypeId="~effect/Cause/AsyncFiberError";class AsyncFiberError extends TaggedError("AsyncFiberError"){[AsyncFiberErrorTypeId]=AsyncFiberErrorTypeId;constructor(fiber){super({message:"An asynchronous Effect was executed with Effect.runSync",fiber})}}var UnknownErrorTypeId="~effect/Cause/UnknownError";class UnknownError extends TaggedError("UnknownError"){[UnknownErrorTypeId]=UnknownErrorTypeId;constructor(cause,message){super({message,cause})}}var ConsoleRef=Reference("effect/Console",{defaultValue:()=>globalThis.console});var logLevelToOrder=(level)=>{switch(level){case"All":return Number.MIN_SAFE_INTEGER;case"Fatal":return 50000;case"Error":return 40000;case"Warn":return 30000;case"Info":return 20000;case"Debug":return 1e4;case"Trace":return 0;case"None":return Number.MAX_SAFE_INTEGER}};var LogLevelOrder=mapInput(Number2,logLevelToOrder);var isLogLevelGreaterThan=isGreaterThan(LogLevelOrder);var CurrentLoggers=Reference("effect/Logger/CurrentLoggers",{defaultValue:()=>new Set([defaultLogger,tracerLogger])});var LogToStderr=Reference("effect/Logger/LogToStderr",{defaultValue:constFalse});var LoggerTypeId="~effect/Logger";var LoggerProto={[LoggerTypeId]:{_Message:identity,_Output:identity},pipe(){return pipeArguments(this,arguments)}};var loggerMake=(log)=>{const self=Object.create(LoggerProto);self.log=log;return self};var formatLabel=(key)=>key.replace(/[\s="]/g,"_");var formatLogSpan=(self,now)=>{const label=formatLabel(self[0]);return`${label}=${now-self[1]}ms`};var logWithLevel=(level)=>(...message)=>{let cause=undefined;for(let i=0,len=message.length;i<len;i++){const msg=message[i];if(isCause(msg)){if(cause){message.splice(i,1)}else{message=message.slice(0,i).concat(message.slice(i+1))}cause=cause?causeFromReasons(cause.reasons.concat(msg.reasons)):msg;i--}}if(cause===undefined){cause=causeEmpty}return withFiber((fiber)=>{const logLevel=level??fiber.cache.logLevel;if(isLogLevelGreaterThan(fiber.cache.minimumLogLevel,logLevel)){return void_}const clock=fiber.getRef(ClockRef);const loggers=fiber.getRef(CurrentLoggers);if(loggers.size>0){const date=new Date(clock.currentTimeMillisUnsafe());for(const logger of loggers){logger.log({cause,fiber,date,logLevel,message})}}return void_})};var colors={bold:"1",red:"31",green:"32",yellow:"33",blue:"34",cyan:"36",white:"37",gray:"90",black:"30",bgBrightRed:"101"};var logLevelColors={None:[],All:[],Trace:[colors.gray],Debug:[colors.blue],Info:[colors.green],Warn:[colors.yellow],Error:[colors.red],Fatal:[colors.bgBrightRed,colors.black]};var defaultDateFormat=(date)=>`${date.getHours().toString().padStart(2,"0")}:${date.getMinutes().toString().padStart(2,"0")}:${date.getSeconds().toString().padStart(2,"0")}.${date.getMilliseconds().toString().padStart(3,"0")}`;var defaultLogger=loggerMake(({cause,date,fiber,logLevel,message})=>{const message_=Array.isArray(message)?message.slice():[message];if(cause.reasons.length>0){message_.push(causePretty(cause))}const now=date.getTime();const spans=fiber.getRef(CurrentLogSpans);let spanString="";for(const span of spans){spanString+=` ${formatLogSpan(span,now)}`}const annotations=fiber.getRef(CurrentLogAnnotations);if(Object.keys(annotations).length>0){message_.push(annotations)}const console2=fiber.getRef(ConsoleRef);const log=fiber.getRef(LogToStderr)?console2.error:console2.log;log(`[${defaultDateFormat(date)}] ${logLevel.toUpperCase()} (#${fiber.id})${spanString}:`,...message_)});var tracerLogger=loggerMake(({cause,fiber,logLevel,message})=>{const clock=fiber.getRef(ClockRef);const annotations=fiber.getRef(CurrentLogAnnotations);const span=fiber.cache.span;if(span===undefined||span._tag==="ExternalSpan")return;const attributes={};for(const[key,value]of Object.entries(annotations)){assignProperty(attributes,key,value)}attributes["effect.fiberId"]=fiber.id;attributes["effect.logLevel"]=logLevel.toUpperCase();if(cause.reasons.length>0){attributes["effect.cause"]=causePretty(cause)}span.event(toStringUnknown(Array.isArray(message)&&message.length===1?message[0]:message),clock.currentTimeNanosUnsafe(),attributes)});var isFailReason2=isFailReason;var isDieReason2=isDieReason;var fromReasons=causeFromReasons;var fail4=causeFail;var die2=causeDie;var map3=causeMap;var squash=causeSquash;var isDone2=isDone;var done2=done;var succeed4=exitSucceed;var failCause2=exitFailCause;var fail5=exitFail;var void_2=exitVoid;var isSuccess3=exitIsSuccess;var TypeId5="~effect/Deferred";var DeferredProto={[TypeId5]:{_A:identity,_E:identity},pipe(){return pipeArguments(this,arguments)}};var DeferredImpl=function(){this.resumes=undefined;this.effect=undefined};DeferredImpl.prototype=DeferredProto;var makeUnsafe2=()=>new DeferredImpl;var _await=(self)=>callback((resume)=>{if(self.effect)return resume(self.effect);self.resumes??=[];self.resumes.push(resume);return sync(()=>{const resumes=self.resumes;if(resumes===undefined)return;const index=resumes.indexOf(resume);if(index>=0)resumes.splice(index,1)})});var doneUnsafe=(self,effect)=>{if(self.effect)return false;self.effect=effect;if(self.resumes){const resumes=self.resumes;self.resumes=undefined;for(let i=0;i<resumes.length;i++){resumes[i](effect)}}return true};var makeUnsafe3=scopeMakeUnsafe;var provide=provideScope;var addFinalizer=scopeAddFinalizer;var forkUnsafe2=scopeForkUnsafe;var close=scopeClose;var TypeId6="~effect/Layer";var MemoMapTypeId="~effect/Layer/MemoMap";var makeMemoMapEntry=(memoMap,layer)=>{const entry={observers:0,deferred:makeUnsafe2(),scope:makeUnsafe3(),finalizer:(exit)=>suspend(()=>{if(--entry.observers>0)return void_;memoMap.map.delete(layer);return close(entry.scope,exit)})};return entry};var memoMapObserve=(entry,scope)=>{if(scope.state._tag==="Closed")return false;entry.observers++;scopeAddFinalizerUnsafe(scope,{},entry.finalizer);return true};var LayerProto={[TypeId6]:{_ROut:identity,_E:identity,_RIn:identity},pipe(){return pipeArguments(this,arguments)}};var fromBuildUnsafe=(build)=>{const self=Object.create(LayerProto);self.build=build;return self};var fromBuild=(build)=>fromBuildUnsafe((memoMap,scope)=>{const layerScope=forkUnsafe2(scope);return onExit(build(memoMap,layerScope),(exit)=>exit._tag==="Failure"?close(layerScope,exit):void_)});var fromBuildMemo=(build)=>{const self=fromBuild((memoMap,scope)=>memoMap.getOrElseMemoize(self,scope,build));return self};class MemoMapImpl{get[MemoMapTypeId](){return MemoMapTypeId}parent;constructor(parent){this.parent=parent}map=new Map;get(layer,scope){const local=this.map.get(layer);if(local){memoMapObserve(local,scope);return local.deferred.effect??_await(local.deferred)}return this.parent?.get(layer,scope)}getOrElseMemoize(layer,scope,build){return suspend(()=>{let deferred;return onExitPrimitive(suspend(()=>{const existing=this.get(layer,scope);if(existing)return existing;const entry=makeMemoMapEntry(this,layer);if(!memoMapObserve(entry,scope))return build(this,scope);deferred=entry.deferred;this.map.set(layer,entry);return build(this,entry.scope)}),(exit)=>{if(deferred)doneUnsafe(deferred,exit)})})}}var makeMemoMapUnsafe=()=>new MemoMapImpl;var forkMemoMapUnsafe=(parent)=>new MemoMapImpl(parent);class CurrentMemoMap extends Service()("effect/Layer/CurrentMemoMap"){static forkOrCreate(self){const current=getOrUndefined2(self,CurrentMemoMap);return current?forkMemoMapUnsafe(current):makeMemoMapUnsafe()}}var buildWithMemoMap=dual(3,(self,memoMap,scope)=>provideService(map2(self.build(memoMap,scope),add(CurrentMemoMap,memoMap)),CurrentMemoMap,memoMap));var buildWithScope=dual(2,(self,scope)=>withFiber((fiber)=>buildWithMemoMap(self,CurrentMemoMap.forkOrCreate(fiber.context),scope)));var succeed5=function(){if(arguments.length===1){return(resource)=>succeedContext(make4(arguments[0],resource))}return succeedContext(make4(arguments[0],arguments[1]))};var succeedContext=(context)=>fromBuildUnsafe(constant(succeed3(context)));var effect=function(){if(arguments.length===1){return(effect)=>effectImpl(arguments[0],effect)}return effectImpl(arguments[0],arguments[1])};var effectImpl=(service,effect)=>effectContext(map2(effect,(value)=>make4(service,value)));var effectContext=(effect)=>fromBuildMemo((_,scope)=>provide(effect,scope));var mergeAllEffect=(layers,memoMap,scope)=>{const parentScope=forkUnsafe2(scope,"parallel");return forEach(layers,(layer)=>layer.build(memoMap,forkUnsafe2(parentScope,"sequential")),{concurrency:layers.length}).pipe(map2((context)=>mergeAll(...context)))};var mergeAll2=(...layers)=>fromBuild((memoMap,scope)=>mergeAllEffect(layers,memoMap,scope));var catchDone=dual(2,(effect,f)=>catchCauseFilter(effect,filterDoneLeftover,(l)=>f(l)));var isDoneCause=(cause)=>cause.reasons.some(isDoneFailure);var isDoneFailure=(failure)=>failure._tag==="Fail"&&isDone2(failure.error);var filterDone=(cause)=>{let done;let hasFailure=false;for(const reason of cause.reasons){if(isDoneFailure(reason)){done??=reason.error}else if(reason._tag!=="Interrupt"){hasFailure=true}}if(done===undefined)return fail2(cause);return hasFailure?fail2(fromReasons(cause.reasons.filter((reason)=>!isDoneFailure(reason)))):succeed2(done)};var filterDoneLeftover=(cause)=>{const done=filterDone(cause);return isFailure2(done)?done:succeed2(done.success.value)};var provideLayer=(self,layer,options)=>scopedWith((scope)=>flatMap2(options?.local?buildWithMemoMap(layer,makeMemoMapUnsafe(),scope):buildWithScope(layer,scope),(context)=>provideContext(self,context)));var provide2=dual((args)=>isEffect(args[0]),(self,source,options)=>isContext(source)?provideContext(self,source):provideLayer(self,Array.isArray(source)?mergeAll2(...source):source,options));var isEffect2=isEffect;var all2=all;var forEach2=forEach;var promise2=promise;var tryPromise2=tryPromise;var succeed6=succeed3;var succeedNone2=succeedNone;var suspend2=suspend;var sync2=sync;var void_3=void_;var callback2=callback;var gen2=gen;var fail6=fail3;var failCause3=failCause;var failCauseSync2=failCauseSync;var die3=die;var try_2=try_;var fromResult2=fromResult;var flatMap3=flatMap2;var flatten3=flatten2;var andThen2=andThen;var tap2=tap;var result2=result;var option2=option;var exit2=exit;var map4=map2;var as2=as;var asVoid2=asVoid;var catch_2=catch_;var catchTag2=catchTag;var catchCause2=catchCause;var catchDefect2=catchDefect;var catchIf2=catchIf;var mapError2=mapError;var orDie2=orDie;var tapError2=tapError;var tapDefect2=tapDefect;var ignore2=ignore;var orElseSucceed2=orElseSucceed;var timeout2=timeout;var timeoutOrElse2=timeoutOrElse;var delay2=delay;var sleep2=sleep;var raceFirst2=raceFirst;var matchEffect2=matchEffect;var context2=context;var provide3=provide2;var serviceOption2=serviceOption;var acquireRelease2=acquireRelease;var acquireUseRelease2=acquireUseRelease;var ensuring2=ensuring;var forever2=forever;var forkIn2=forkIn;var runFork2=runFork;var runPromise2=runPromise;var runPromiseWith2=runPromiseWith;var runPromiseExit2=runPromiseExit;var runSync2=runSync;var runSyncExit2=runSyncExit;var fnUntraced2=fnUntraced;var fn2=fn;var effectify=(fn,onError,onSyncError)=>(...args)=>callback2((resume)=>{try{fn(...args,(err,result)=>{if(err){resume(fail6(onError?onError(err,args):err))}else{resume(succeed6(result))}})}catch(err){resume(onSyncError?fail6(onSyncError(err,args)):die3(err))}});var mapEager2=mapEager;var mapErrorEager2=mapErrorEager;var mapBothEager2=mapBothEager;var flatMapEager2=flatMapEager;var catchEager2=catchEager;var fnUntracedEager2=fnUntracedEager;var TypeId7="~effect/PlatformError";class BadArgument extends TaggedError2("BadArgument"){get message(){return`${this.module}.${this.method}${this.description?`: ${this.description}`:""}`}}class SystemError extends Error3{get message(){return`${this._tag}: ${this.module}.${this.method}${this.pathOrDescriptor!==undefined?` (${this.pathOrDescriptor})`:""}${this.description?`: ${this.description}`:""}`}}class PlatformError extends TaggedError2("PlatformError"){constructor(reason){if("cause"in reason){super({reason,cause:reason.cause})}else{super({reason})}}[TypeId7]=TypeId7;get message(){return this.reason.message}}var systemError=(options)=>new PlatformError(new SystemError(options));var badArgument=(options)=>new PlatformError(new BadArgument(options));var interrupt2=fiberInterrupt;var Empty=Symbol.for("effect/MutableList/Empty");var make7=()=>({head:undefined,tail:undefined,length:0});var compactHead=(self)=>{const head=self.head;if(head.offset>=1024&&head===self.tail&&head.mutable&&(head.array.length-head.offset)*8<=head.offset){self.head=self.tail={array:head.array.slice(head.offset),mutable:true,offset:0,next:undefined}}};var emptyBucket=()=>({array:[],mutable:true,offset:0,next:undefined});var append2=(self,message)=>{if(!self.tail){self.head=self.tail=emptyBucket()}else if(!self.tail.mutable){self.tail.next=emptyBucket();self.tail=self.tail.next}self.tail.array.push(message);self.length++};var clear=(self)=>{self.head=self.tail=undefined;self.length=0};var takeN=(self,n)=>{n=normalize(n);if(n<=0||!self.head)return[];n=Math.min(n,self.length);if(n===self.length&&self.head?.offset===0&&!self.head.next){const array=self.head.array;clear(self);return array}const array=new Array(n);let index=0;let chunk=self.head;while(chunk){while(chunk.offset<chunk.array.length){array[index++]=chunk.array[chunk.offset];if(chunk.mutable)chunk.array[chunk.offset]=undefined;chunk.offset++;if(index===n){self.head=chunk.offset===chunk.array.length&&chunk.next?chunk.next:chunk;self.length-=n;if(self.length===0)clear(self);else compactHead(self);return array}}chunk=chunk.next}clear(self);return array};var take=(self)=>{if(!self.head)return Empty;const message=self.head.array[self.head.offset];if(self.head.mutable)self.head.array[self.head.offset]=undefined;self.head.offset++;self.length--;if(self.head.offset===self.head.array.length){if(self.head.next){self.head=self.head.next}else{clear(self)}}else{compactHead(self)}return message};var TypeId8="~effect/Queue";var EnqueueTypeId="~effect/Queue/Enqueue";var DequeueTypeId="~effect/Queue/Dequeue";var variance={_A:identity,_E:identity};var QueueProto={[TypeId8]:variance,[EnqueueTypeId]:variance,[DequeueTypeId]:variance,...PipeInspectableProto,toJSON(){return{_id:"effect/Queue",state:this.state._tag,size:sizeUnsafe(this)}}};var make8=(options)=>withFiber((fiber)=>{const self=Object.create(QueueProto);self.dispatcher=fiber.currentDispatcher;self.capacity=options?.capacity??Number.POSITIVE_INFINITY;self.strategy=options?.strategy??"suspend";self.messages=make7();self.scheduleRunning=false;self.state={_tag:"Open",takers:new Set,offers:new Set,awaiters:new Set};return succeed3(self)});var offer=dual(2,(self,message)=>suspend(()=>offerUnsafe(self,message)?exitTrue:self.state._tag==="Open"&&self.strategy==="suspend"?offerOrWait(self,message):exitFalse));var offerUnsafe=(self,message)=>{if(self.state._tag!=="Open"){return false}else if(self.messages.length>=self.capacity){if(self.strategy==="sliding"){take(self.messages);append2(self.messages,message);return true}else if(self.capacity<=0&&self.state.takers.size>0){append2(self.messages,message);releaseTakers(self);return true}return false}append2(self.messages,message);scheduleReleaseTaker(self);return true};var failCauseUnsafe=(self,cause)=>{if(self.state._tag!=="Open"){return false}const exit=exitFailCause(cause);const fail=exitZipRight(exit,exitFailDone);if(self.state.offers.size===0&&self.messages.length===0){finalize(self,fail);return true}self.state={...self.state,_tag:"Closing",exit:fail};scheduleReleaseTaker(self);return true};var endUnsafe=(self)=>failCauseUnsafe(self,causeFail(Done()));var shutdown=(self)=>sync(()=>shutdownUnsafe(self));var shutdownUnsafe=(self)=>{if(self.state._tag==="Done"){return false}clear(self.messages);const offers=self.state.offers;finalize(self,self.state._tag==="Open"?exitInterrupt2:self.state.exit);for(const entry of offers){resumeUnoffered(entry)}return true};var takeAll2=(self)=>takeBetween(self,1,Number.POSITIVE_INFINITY);var takeBetween=dual(3,(self,min,max)=>{min=normalize(min);max=normalize(max);return suspend(()=>takeBetweenUnsafe(self,min,max)??andThen(awaitTake(self,()=>canTake(self,min)),takeBetween(self,min,max)))});var sizeUnsafe=(self)=>self.state._tag==="Done"?0:self.messages.length;var exitFalse=exitSucceed(false);var exitTrue=exitSucceed(true);var exitFailDone=exitFail(Done());var exitInterrupt2=exitInterrupt();var releaseTakers=(self)=>{if(self.state._tag==="Done"||self.state.takers.size===0){return}for(const taker of self.state.takers){if(!taker.ready())continue;self.state.takers.delete(taker);taker.resume(exitVoid);if(self.messages.length===0){break}}};var scheduleReleaseTaker=(self)=>{if(self.scheduleRunning||self.state._tag==="Done"||self.state.takers.size===0){return}self.scheduleRunning=true;self.dispatcher.scheduleTask(()=>{self.scheduleRunning=false;releaseTakers(self)},0)};var takeBetweenUnsafe=(self,min,max)=>{if(self.state._tag==="Done"){return self.state.exit}else if(max<=0||min<=0){return exitSucceed([])}else if(!canTake(self,min)){return}const messages=self.messages.length>0?takeN(self.messages,max):[takeOfferUnsafe(self.state.offers)];releaseCapacity(self);return exitSucceed(messages)};var canTake=(self,min)=>self.messages.length>=(self.state._tag==="Closing"?1:Math.min(min,self.capacity||1))||self.capacity<=0&&self.state._tag!=="Done"&&self.state.offers.size>0;var awaitTake=(self,ready)=>callback((resume)=>{if(self.state._tag==="Done")return resume(self.state.exit);if(ready())return resume(exitVoid);const taker={ready,resume};self.state.takers.add(taker);return sync(()=>{if(self.state._tag!=="Done")self.state.takers.delete(taker)})});var offerOrWait=(self,message)=>callback((resume)=>offerUnsafe(self,message)?resume(exitTrue):waitToOffer(self,{_tag:"Single",message,resume}));var waitToOffer=(self,entry)=>{if(self.state._tag!=="Open")return resumeUnoffered(entry);const offers=self.state.offers;offers.add(entry);return sync(()=>{if(self.state._tag==="Done")return;offers.delete(entry);if(self.state._tag==="Closing"&&offers.size===0&&self.messages.length===0){finalize(self,self.state.exit)}})};var resumeUnoffered=(entry)=>entry._tag==="Single"?entry.resume(exitFalse):entry.resume(exitSucceed(entry.remaining.slice(entry.offset)));var takeOfferUnsafe=(offers)=>{const entry=offers.values().next().value;if(entry._tag==="Single"){offers.delete(entry);entry.resume(exitTrue);return entry.message}const message=entry.remaining[entry.offset++];if(entry.offset===entry.remaining.length){offers.delete(entry);entry.resume(exitSucceed([]))}return message};var releaseCapacity=(self)=>{if(self.state._tag==="Done"){return isDoneCause(self.state.exit.cause)}else if(self.state.offers.size===0){if(self.state._tag==="Closing"&&self.messages.length===0){finalize(self,self.state.exit);return isDoneCause(self.state.exit.cause)}return false}for(const entry of self.state.offers){let n=self.capacity-self.messages.length;if(n<=0)break;else if(entry._tag==="Single"){append2(self.messages,entry.message);self.state.offers.delete(entry);entry.resume(exitTrue)}else{for(;entry.offset<entry.remaining.length;entry.offset++){if(n===0)return false;append2(self.messages,entry.remaining[entry.offset]);n--}self.state.offers.delete(entry);entry.resume(exitSucceed([]))}}return false};var finalize=(self,exit)=>{if(self.state._tag==="Done"){return}const openState=self.state;self.state={_tag:"Done",exit};for(const taker of openState.takers){taker.resume(exit)}openState.takers.clear();for(const awaiter of openState.awaiters){awaiter(exit)}openState.awaiters.clear()};var TypeId9="~effect/Channel";var ChannelProto={[TypeId9]:{_Env:identity,_InErr:identity,_InElem:identity,_OutErr:identity,_OutElem:identity},pipe(){return pipeArguments(this,arguments)}};var fromTransform=(transform)=>{const self=Object.create(ChannelProto);self.transform=(upstream,scope)=>catchCause2(transform(upstream,scope),(cause)=>succeed6(failCause3(cause)));return self};var fromPull=(effect)=>fromTransform((_,__)=>effect);var toTransform=(channel)=>channel.transform;var asyncQueue=(scope,f,options)=>make8({capacity:options?.bufferSize,strategy:options?.strategy}).pipe(tap2((queue)=>addFinalizer(scope,shutdown(queue))),tap2((queue)=>forkIn2(provide(f(queue),scope),scope)));var callbackArray=(f,options)=>fromTransform((_,scope)=>map4(asyncQueue(scope,f,options),takeAll2));var unwrap=(channel)=>fromTransform((upstream,scope)=>{let pull;return succeed6(suspend2(()=>{if(pull)return pull;return channel.pipe(provide(scope),flatMap3((channel)=>toTransform(channel)(upstream,scope)),flatMap3((pull_)=>pull=pull_))}))});var TypeId10="~effect/Stream";var streamVariance={_R:identity,_E:identity,_A:identity};var Stream=function(channel){this.channel=channel};Stream.prototype={[TypeId10]:streamVariance,pipe(){return pipeArguments(this,arguments)}};var fromChannel=(channel)=>new Stream(channel);var TypeId11="~effect/Sink";var endVoid=succeed6([undefined]);var sinkVariance={_A:identity,_In:identity,_L:identity,_E:identity,_R:identity};var SinkProto={[TypeId11]:sinkVariance,pipe(){return pipeArguments(this,arguments)}};var fromChannel2=(channel)=>fromTransform2((upstream,scope)=>toTransform(channel)(upstream,scope).pipe(flatMap3(forever2({disableYield:true})),catchDone(succeed6)));var fromTransform2=(transform)=>{const self=Object.create(SinkProto);self.transform=transform;return self};var toChannel=(self)=>fromTransform((upstream,scope)=>succeed6(flatMap3(self.transform(upstream,scope),done2)));var forEach3=(f)=>forEachArray(forEach2((_)=>f(_),{discard:true}));var forEachArray=(f)=>fromTransform2((upstream)=>upstream.pipe(flatMap3(f),forever2({disableYield:true}),catchDone(()=>endVoid)));var unwrap2=(effect)=>fromChannel2(unwrap(map4(effect,toChannel)));var fromChannel3=fromChannel;var fromPull2=(pull)=>fromChannel3(fromPull(pull));var toChannel2=(stream)=>stream.channel;var callback3=(f,options)=>fromChannel3(callbackArray(f,options));var unwrap3=(effect)=>fromChannel3(unwrap(map4(effect,toChannel2)));var TypeId12="~effect/FileSystem";var FileSystem=Service("effect/FileSystem");var make9=(impl)=>FileSystem.of({...impl,[TypeId12]:TypeId12,exists:(path)=>pipe(impl.access(path),as2(true),catchTag2("PlatformError",(e)=>e.reason._tag==="NotFound"?succeed6(false):fail6(e))),readFileString:(path,encoding)=>flatMap3(impl.readFile(path),(_)=>try_2({try:()=>new TextDecoder(encoding).decode(_),catch:(cause)=>badArgument({module:"FileSystem",method:"readFileString",description:"invalid encoding",cause})})),stream:fnUntraced2(function*(path,options){const file=yield*impl.open(path,{flag:"r"});const offset=options?.offset===undefined?undefined:fromInputUnsafe(options.offset);if(offset){yield*file.seek(offset,"start")}const bytesToRead=options?.bytesToRead===undefined?undefined:fromInputUnsafe(options.bytesToRead);let totalBytesRead=BigInt(0);const chunkSize=Number(BigInt(options?.chunkSize??64*1024));const readChunk=file.readAlloc(chunkSize);return fromPull2(succeed6(flatMap3(suspend2(()=>{if(bytesToRead!==undefined&&bytesToRead<=totalBytesRead){return done2()}return bytesToRead!==undefined&&bytesToRead-totalBytesRead<chunkSize?file.readAlloc(Number(bytesToRead-totalBytesRead)):readChunk}),match({onNone:()=>done2(),onSome:(buf)=>{totalBytesRead+=BigInt(buf.length);return succeed6(of(buf))}}))))},unwrap3),sink:(path,options)=>pipe(impl.open(path,{...options,flag:options?.flag??"w"}),map4((file)=>forEach3((_)=>file.writeAll(_))),unwrap2),writeFileString:(path,data,options)=>flatMap3(try_2({try:()=>new TextEncoder().encode(data),catch:(cause)=>badArgument({module:"FileSystem",method:"writeFileString",description:"could not encode string",cause})}),(_)=>impl.writeFile(path,_,options))});var FileTypeId="~effect/FileSystem/File";class WatchBackend extends Service()("effect/FileSystem/WatchBackend"){}import*as Crypto from"crypto";import*as NFS from"fs";import*as OS from"os";import*as Path from"path";var handleErrnoException=(module,method)=>(err,[path])=>{let reason="Unknown";switch(err.code){case"ENOENT":reason="NotFound";break;case"EACCES":reason="PermissionDenied";break;case"EEXIST":reason="AlreadyExists";break;case"EISDIR":reason="BadResource";break;case"ENOTDIR":reason="BadResource";break;case"EBUSY":reason="Busy";break;case"ELOOP":reason="BadResource";break}return systemError({_tag:reason,module,method,pathOrDescriptor:path,syscall:err.syscall,cause:err})};var handleBadArgument=(method)=>(err)=>badArgument({module:"FileSystem",method,description:err.message??String(err)});var bigintToNumber=(value,field)=>{const number=Number(value);if(!Number.isSafeInteger(number)){throw new RangeError(`${field} exceeds the safe integer range: ${value}`)}return number};var bigintToNumberOption=(value)=>flatMap(fromNullishOr(value),toNumber);var positionToNumber=(position,method)=>try_2({try:()=>bigintToNumber(position,"position"),catch:handleBadArgument(method)});var access2=(()=>{const nodeAccess=effectify(NFS.access,handleErrnoException("FileSystem","access"),handleBadArgument("access"));return(path,options)=>{let mode=NFS.constants.F_OK;if(options?.readable){mode|=NFS.constants.R_OK}if(options?.writable){mode|=NFS.constants.W_OK}return nodeAccess(path,mode)}})();var copy=(()=>{const nodeCp=effectify(NFS.cp,handleErrnoException("FileSystem","copy"),handleBadArgument("copy"));return(fromPath,toPath,options)=>nodeCp(fromPath,toPath,{force:options?.overwrite??false,preserveTimestamps:options?.preserveTimestamps??false,recursive:true})})();var copyFile2=(()=>{const nodeCopyFile=effectify(NFS.copyFile,handleErrnoException("FileSystem","copyFile"),handleBadArgument("copyFile"));return(fromPath,toPath)=>nodeCopyFile(fromPath,toPath)})();var chmod2=(()=>{const nodeChmod=effectify(NFS.chmod,handleErrnoException("FileSystem","chmod"),handleBadArgument("chmod"));return(path,mode)=>nodeChmod(path,mode)})();var chown2=(()=>{const nodeChown=effectify(NFS.chown,handleErrnoException("FileSystem","chown"),handleBadArgument("chown"));return(path,uid,gid)=>nodeChown(path,uid,gid)})();var glob2=(()=>{const nodeGlob=effectify(NFS.glob,handleErrnoException("FileSystem","glob"),handleBadArgument("glob"));return(pattern,options)=>nodeGlob(pattern,{cwd:options?.root,exclude:options?.exclude})})();var link2=(()=>{const nodeLink=effectify(NFS.link,handleErrnoException("FileSystem","link"),handleBadArgument("link"));return(existingPath,newPath)=>nodeLink(existingPath,newPath)})();var makeDirectory=(()=>{const nodeMkdir=effectify(NFS.mkdir,handleErrnoException("FileSystem","makeDirectory"),handleBadArgument("makeDirectory"));return(path,options)=>nodeMkdir(path,{recursive:options?.recursive??false,mode:options?.mode})})();var makeTempDirectoryFactory=(method)=>{const nodeMkdtemp=effectify(NFS.mkdtemp,handleErrnoException("FileSystem",method),handleBadArgument(method));return(options)=>suspend2(()=>{const prefix=options?.prefix??"";const directory=typeof options?.directory==="string"?Path.join(options.directory,"."):OS.tmpdir();return nodeMkdtemp(prefix?Path.join(directory,prefix):directory+"/")})};var makeTempDirectory=makeTempDirectoryFactory("makeTempDirectory");var removeFactory=(method)=>{const nodeRm=effectify(NFS.rm,handleErrnoException("FileSystem",method),handleBadArgument(method));return(path,options)=>nodeRm(path,{recursive:options?.recursive??false,force:options?.force??false})};var remove=removeFactory("remove");var makeTempDirectoryScoped=(()=>{const makeDirectory=makeTempDirectoryFactory("makeTempDirectoryScoped");const removeDirectory=removeFactory("makeTempDirectoryScoped");return(options)=>acquireRelease2(makeDirectory(options),(directory)=>orDie2(removeDirectory(directory,{recursive:true})))})();var openFactory=(method)=>{const nodeOpen=effectify(NFS.open,handleErrnoException("FileSystem",method),handleBadArgument(method));const nodeClose=effectify(NFS.close,handleErrnoException("FileSystem",method),handleBadArgument(method));return(path,options)=>pipe(acquireRelease2(nodeOpen(path,options?.flag??"r",options?.mode),(fd)=>orDie2(nodeClose(fd))),map4((fd)=>makeFile(fd,options?.flag?.startsWith("a")??false)))};var open2=openFactory("open");var makeFile=(()=>{const nodeReadFactory=(method)=>effectify(NFS.read,handleErrnoException("FileSystem",method),handleBadArgument(method));const nodeRead=nodeReadFactory("read");const nodeReadAlloc=nodeReadFactory("readAlloc");const nodeStat=effectify(NFS.fstat,handleErrnoException("FileSystem","stat"),handleBadArgument("stat"));const nodeTruncate=effectify(NFS.ftruncate,handleErrnoException("FileSystem","truncate"),handleBadArgument("truncate"));const nodeSync=effectify(NFS.fsync,handleErrnoException("FileSystem","sync"),handleBadArgument("sync"));const nodeWriteFactory=(method)=>effectify(NFS.write,handleErrnoException("FileSystem",method),handleBadArgument(method));const nodeWrite=nodeWriteFactory("write");const nodeWriteAll=nodeWriteFactory("writeAll");class FileImpl{[FileTypeId];fd;append;position=BigInt(0);constructor(fd,append){this[FileTypeId]=FileTypeId;this.fd=fd;this.append=append}get stat(){return flatMap3(nodeStat(this.fd,{bigint:true}),makeFileInfo)}get sync(){return nodeSync(this.fd)}seek(offset,from){return suspend2(()=>{const position=from==="start"?offset:this.position+offset;if(position<BigInt(0)){return fail6(badArgument({module:"FileSystem",method:"seek",description:"Cannot seek before the start of the file"}))}this.position=position;return succeed6(position)})}read(buffer){return suspend2(()=>{const position=this.position;return map4(nodeRead(this.fd,{buffer,position}),(bytesRead)=>{this.position=position+BigInt(bytesRead);return bytesRead})})}readAlloc(size){return suspend2(()=>{try{if(!Number.isInteger(size)||size<0){throw new RangeError("size must be a non-negative integer")}const buffer=Buffer.allocUnsafeSlow(size);const position=this.position;return map4(nodeReadAlloc(this.fd,{buffer,position}),(bytesRead)=>{if(bytesRead===0){return none2()}this.position=position+BigInt(bytesRead);if(bytesRead===size){return some2(buffer)}const dst=Buffer.allocUnsafeSlow(bytesRead);buffer.copy(dst,0,0,bytesRead);return some2(dst)})}catch(cause){return fail6(handleBadArgument("readAlloc")(cause))}})}truncate(length){return map4(nodeTruncate(this.fd,length||undefined),()=>{if(!this.append){const len=BigInt(length??0);if(this.position>len){this.position=len}}})}write(buffer){return suspend2(()=>{const position=this.position;return flatMap3(this.append?succeed6(undefined):positionToNumber(position,"write"),(nodePosition)=>map4(nodeWrite(this.fd,buffer,undefined,undefined,nodePosition),(bytesWritten)=>{if(!this.append){this.position=position+BigInt(bytesWritten)}return bytesWritten}))})}writeAllChunk(buffer){return suspend2(()=>{const position=this.position;return flatMap3(this.append?succeed6(undefined):positionToNumber(position,"writeAll"),(nodePosition)=>flatMap3(nodeWriteAll(this.fd,buffer,undefined,undefined,nodePosition),(bytesWritten)=>{if(bytesWritten===0){return fail6(systemError({module:"FileSystem",method:"writeAll",_tag:"WriteZero",pathOrDescriptor:this.fd,description:"write returned 0 bytes written"}))}if(!this.append){this.position=position+BigInt(bytesWritten)}return bytesWritten<buffer.length?this.writeAllChunk(buffer.subarray(bytesWritten)):void_3}))})}writeAll(buffer){return buffer.length===0?void_3:this.writeAllChunk(buffer)}}return(fd,append)=>new FileImpl(fd,append)})();var makeTempFileFactory=(method)=>{const makeDirectory=makeTempDirectoryFactory(method);return fnUntraced2(function*(options){const directory=yield*makeDirectory(options);const random=Crypto.randomBytes(6).toString("hex");const name=Path.join(directory,options?.suffix?`${random}${options.suffix}`:random);yield*writeFile2(name,new Uint8Array(0));return name})};var makeTempFile=makeTempFileFactory("makeTempFile");var makeTempFileScoped=(()=>{const makeFile=makeTempFileFactory("makeTempFileScoped");const removeDirectory=removeFactory("makeTempFileScoped");return(options)=>acquireRelease2(makeFile(options),(file)=>orDie2(removeDirectory(Path.dirname(file),{recursive:true})))})();var readDirectory=(path,options)=>tryPromise2({try:()=>NFS.promises.readdir(path,options),catch:(err)=>handleErrnoException("FileSystem","readDirectory")(err,[path])});var readFile2=(path)=>callback2((resume,signal)=>{try{NFS.readFile(path,{signal},(err,data)=>{if(err){resume(fail6(handleErrnoException("FileSystem","readFile")(err,[path])))}else{resume(succeed6(data))}})}catch(err){resume(fail6(handleBadArgument("readFile")(err)))}});var readLink=(()=>{const nodeReadLink=effectify(NFS.readlink,handleErrnoException("FileSystem","readLink"),handleBadArgument("readLink"));return(path)=>nodeReadLink(path)})();var realPath=(()=>{const nodeRealPath=effectify(NFS.realpath,handleErrnoException("FileSystem","realPath"),handleBadArgument("realPath"));return(path)=>nodeRealPath(path)})();var rename2=(()=>{const nodeRename=effectify(NFS.rename,handleErrnoException("FileSystem","rename"),handleBadArgument("rename"));return(oldPath,newPath)=>nodeRename(oldPath,newPath)})();var makeFileInfo=(stat)=>try_2({try:()=>({type:stat.isFile()?"File":stat.isDirectory()?"Directory":stat.isSymbolicLink()?"SymbolicLink":stat.isBlockDevice()?"BlockDevice":stat.isCharacterDevice()?"CharacterDevice":stat.isFIFO()?"FIFO":stat.isSocket()?"Socket":"Unknown",mtime:fromNullishOr(stat.mtime),atime:fromNullishOr(stat.atime),birthtime:fromNullishOr(stat.birthtime),dev:bigintToNumber(stat.dev,"dev"),rdev:bigintToNumberOption(stat.rdev),ino:bigintToNumberOption(stat.ino),mode:bigintToNumber(stat.mode,"mode"),nlink:bigintToNumberOption(stat.nlink),uid:bigintToNumberOption(stat.uid),gid:bigintToNumberOption(stat.gid),size:bytes(stat.size),blksize:stat.blksize!==undefined?some2(bytes(stat.blksize)):none2(),blocks:bigintToNumberOption(stat.blocks)}),catch:handleBadArgument("stat")});var stat2=(()=>{const nodeStat=effectify(NFS.stat,handleErrnoException("FileSystem","stat"),handleBadArgument("stat"));return(path)=>flatMap3(nodeStat(path,{bigint:true}),makeFileInfo)})();var symlink2=(()=>{const nodeSymlink=effectify(NFS.symlink,handleErrnoException("FileSystem","symlink"),handleBadArgument("symlink"));return(target,path)=>nodeSymlink(target,path)})();var truncate2=(()=>{const nodeTruncate=effectify(NFS.truncate,handleErrnoException("FileSystem","truncate"),handleBadArgument("truncate"));return(path,length)=>nodeTruncate(path,length)})();var utimes2=(()=>{const nodeUtimes=effectify(NFS.utimes,handleErrnoException("FileSystem","utime"),handleBadArgument("utime"));return(path,atime,mtime)=>nodeUtimes(path,atime,mtime)})();var watchNode=(path,info,options)=>callback3((queue)=>acquireRelease2(sync2(()=>{const directory=info.type==="Directory"?path:Path.dirname(path);const watcher=NFS.watch(path,{recursive:options?.recursive??false},(event,path)=>{if(!path)return;switch(event){case"rename":{runFork2(matchEffect2(stat2(Path.resolve(directory,path)),{onSuccess:(_)=>offer(queue,{_tag:"Create",path}),onFailure:(_)=>offer(queue,{_tag:"Remove",path})}));return}case"change":{offerUnsafe(queue,{_tag:"Update",path});return}}});watcher.on("error",(error)=>{failCauseUnsafe(queue,fail4(systemError({module:"FileSystem",_tag:"Unknown",method:"watch",pathOrDescriptor:path,cause:error})))});watcher.on("close",()=>{endUnsafe(queue)});return watcher}),(watcher)=>sync2(()=>watcher.close())));var watch2=(backend,path,options)=>stat2(path).pipe(map4((stat)=>backend.pipe(flatMap((_)=>_.register(path,stat,options)),getOrElse(()=>watchNode(path,stat,options)))),unwrap3);var writeFile2=(path,data,options)=>callback2((resume,signal)=>{try{NFS.writeFile(path,data,{signal,flag:options?.flag,mode:options?.mode},(err)=>{if(err){resume(fail6(handleErrnoException("FileSystem","writeFile")(err,[path])))}else{resume(void_3)}})}catch(err){resume(fail6(handleBadArgument("writeFile")(err)))}});var makeFileSystem=map4(serviceOption2(WatchBackend),(backend)=>make9({access:access2,chmod:chmod2,chown:chown2,copy,copyFile:copyFile2,glob:glob2,link:link2,makeDirectory,makeTempDirectory,makeTempDirectoryScoped,makeTempFile,makeTempFileScoped,open:open2,readDirectory,readFile:readFile2,readLink,realPath,remove,rename:rename2,stat:stat2,symlink:symlink2,truncate:truncate2,utimes:utimes2,watch(path,options){return watch2(backend,path,options)},writeFile:writeFile2}));var layer=effect(FileSystem)(makeFileSystem);var layer2=layer;var TypeId13="~effect/Path";var Path2=Service("effect/Path");function normalizeStringPosix(path,allowAboveRoot){let res="";let lastSegmentLength=0;let lastSlash=-1;let dots=0;let code;for(let i=0;i<=path.length;++i){if(i<path.length){code=path.charCodeAt(i)}else if(code===47){break}else{code=47}if(code===47){if(lastSlash===i-1||dots===1){}else if(lastSlash!==i-1&&dots===2){if(res.length<2||lastSegmentLength!==2||res.charCodeAt(res.length-1)!==46||res.charCodeAt(res.length-2)!==46){if(res.length>2){const lastSlashIndex=res.lastIndexOf("/");if(lastSlashIndex!==res.length-1){if(lastSlashIndex===-1){res="";lastSegmentLength=0}else{res=res.slice(0,lastSlashIndex);lastSegmentLength=res.length-1-res.lastIndexOf("/")}lastSlash=i;dots=0;continue}}else if(res.length===2||res.length===1){res="";lastSegmentLength=0;lastSlash=i;dots=0;continue}}if(allowAboveRoot){if(res.length>0){res+="/.."}else{res=".."}lastSegmentLength=2}}else{if(res.length>0){res+="/"+path.slice(lastSlash+1,i)}else{res=path.slice(lastSlash+1,i)}lastSegmentLength=i-lastSlash-1}lastSlash=i;dots=0}else if(code===46&&dots!==-1){++dots}else{dots=-1}}return res}function _format(sep,pathObject){const dir=pathObject.dir||pathObject.root;const base=pathObject.base||(pathObject.name||"")+(pathObject.ext||"");if(!dir){return base}if(dir===pathObject.root){return dir+base}return dir+sep+base}function fromFileUrl(url){if(url.protocol!=="file:"){return fail6(new BadArgument({module:"Path",method:"fromFileUrl",description:"URL must be of scheme file"}))}else if(url.hostname!==""){return fail6(new BadArgument({module:"Path",method:"fromFileUrl",description:"Invalid file URL host"}))}const pathname=url.pathname;for(let n=0;n<pathname.length;n++){if(pathname[n]==="%"){const third=pathname.codePointAt(n+2)|32;if(pathname[n+1]==="2"&&third===102){return fail6(new BadArgument({module:"Path",method:"fromFileUrl",description:"must not include encoded / characters"}))}}}return succeed6(decodeURIComponent(pathname))}var resolve2=function resolve(){let resolvedPath="";let resolvedAbsolute=false;let cwd=undefined;for(let i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){let path;if(i>=0){path=arguments[i]}else{const process2=globalThis.process;if(cwd===undefined&&"process"in globalThis&&typeof process2==="object"&&process2!==null&&typeof process2.cwd==="function"){cwd=process2.cwd()}path=cwd}if(path.length===0){continue}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=path.charCodeAt(0)===47}resolvedPath=normalizeStringPosix(resolvedPath,!resolvedAbsolute);if(resolvedAbsolute){if(resolvedPath.length>0){return"/"+resolvedPath}else{return"/"}}else if(resolvedPath.length>0){return resolvedPath}else{return"."}};var CHAR_FORWARD_SLASH=47;function toFileUrl(filepath){const outURL=new URL("file://");let resolved=resolve2(filepath);const filePathLast=filepath.charCodeAt(filepath.length-1);if(filePathLast===CHAR_FORWARD_SLASH&&resolved[resolved.length-1]!=="/"){resolved+="/"}outURL.pathname=encodePathChars(resolved);return succeed6(outURL)}var percentRegExp=/%/g;var backslashRegExp=/\\/g;var newlineRegExp=/\n/g;var carriageReturnRegExp=/\r/g;var tabRegExp=/\t/g;function encodePathChars(filepath){if(filepath.includes("%")){filepath=filepath.replace(percentRegExp,"%25")}if(filepath.includes("\\")){filepath=filepath.replace(backslashRegExp,"%5C")}if(filepath.includes(`
|
|
237
237
|
`)){filepath=filepath.replace(newlineRegExp,"%0A")}if(filepath.includes("\r")){filepath=filepath.replace(carriageReturnRegExp,"%0D")}if(filepath.includes("\t")){filepath=filepath.replace(tabRegExp,"%09")}return filepath}var posixImpl=Path2.of({[TypeId13]:TypeId13,resolve:resolve2,normalize(path){if(path.length===0)return".";const isAbsolute=path.charCodeAt(0)===47;const trailingSeparator=path.charCodeAt(path.length-1)===47;path=normalizeStringPosix(path,!isAbsolute);if(path.length===0&&!isAbsolute)path=".";if(path.length>0&&trailingSeparator)path+="/";if(isAbsolute)return"/"+path;return path},isAbsolute(path){return path.length>0&&path.charCodeAt(0)===47},join(){if(arguments.length===0){return"."}let joined;for(let i=0;i<arguments.length;++i){const arg=arguments[i];if(arg.length>0){if(joined===undefined){joined=arg}else{joined+="/"+arg}}}if(joined===undefined){return"."}return posixImpl.normalize(joined)},relative(from,to){if(from===to)return"";from=posixImpl.resolve(from);to=posixImpl.resolve(to);if(from===to)return"";let fromStart=1;for(;fromStart<from.length;++fromStart){if(from.charCodeAt(fromStart)!==47){break}}const fromEnd=from.length;const fromLen=fromEnd-fromStart;let toStart=1;for(;toStart<to.length;++toStart){if(to.charCodeAt(toStart)!==47){break}}const toEnd=to.length;const toLen=toEnd-toStart;const length=fromLen<toLen?fromLen:toLen;let lastCommonSep=-1;let i=0;for(;i<=length;++i){if(i===length){if(toLen>length){if(to.charCodeAt(toStart+i)===47){return to.slice(toStart+i+1)}else if(i===0){return to.slice(toStart+i)}}else if(fromLen>length){if(from.charCodeAt(fromStart+i)===47){lastCommonSep=i}else if(i===0){lastCommonSep=0}}break}const fromCode=from.charCodeAt(fromStart+i);const toCode=to.charCodeAt(toStart+i);if(fromCode!==toCode){break}else if(fromCode===47){lastCommonSep=i}}let out="";for(i=fromStart+lastCommonSep+1;i<=fromEnd;++i){if(i===fromEnd||from.charCodeAt(i)===47){if(out.length===0){out+=".."}else{out+="/.."}}}if(out.length>0){return out+to.slice(toStart+lastCommonSep)}else{toStart+=lastCommonSep;if(to.charCodeAt(toStart)===47){++toStart}return to.slice(toStart)}},dirname(path){if(path.length===0)return".";let code=path.charCodeAt(0);const hasRoot=code===47;let end=-1;let matchedSlash=true;for(let i=path.length-1;i>=1;--i){code=path.charCodeAt(i);if(code===47){if(!matchedSlash){end=i;break}}else{matchedSlash=false}}if(end===-1)return hasRoot?"/":".";if(hasRoot&&end===1)return"//";return path.slice(0,end)},basename(path,ext){let start=0;let end=-1;let matchedSlash=true;let i;if(ext!==undefined&&ext.length>0&&ext.length<=path.length){if(ext.length===path.length&&ext===path)return"";let extIdx=ext.length-1;let firstNonSlashEnd=-1;for(i=path.length-1;i>=0;--i){const code=path.charCodeAt(i);if(code===47){if(!matchedSlash){start=i+1;break}}else{if(firstNonSlashEnd===-1){matchedSlash=false;firstNonSlashEnd=i+1}if(extIdx>=0){if(code===ext.charCodeAt(extIdx)){if(--extIdx===-1){end=i}}else{extIdx=-1;end=firstNonSlashEnd}}}}if(start===end)end=firstNonSlashEnd;else if(end===-1)end=path.length;return path.slice(start,end)}else{for(i=path.length-1;i>=0;--i){if(path.charCodeAt(i)===47){if(!matchedSlash){start=i+1;break}}else if(end===-1){matchedSlash=false;end=i+1}}if(end===-1)return"";return path.slice(start,end)}},extname(path){let startDot=-1;let startPart=0;let end=-1;let matchedSlash=true;let preDotState=0;for(let i=path.length-1;i>=0;--i){const code=path.charCodeAt(i);if(code===47){if(!matchedSlash){startPart=i+1;break}continue}if(end===-1){matchedSlash=false;end=i+1}if(code===46){if(startDot===-1){startDot=i}else if(preDotState!==1){preDotState=1}}else if(startDot!==-1){preDotState=-1}}if(startDot===-1||end===-1||preDotState===0||preDotState===1&&startDot===end-1&&startDot===startPart+1){return""}return path.slice(startDot,end)},format:function format(pathObject){if(pathObject===null||typeof pathObject!=="object"){throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof pathObject)}return _format("/",pathObject)},parse(path){const ret={root:"",dir:"",base:"",ext:"",name:""};if(path.length===0)return ret;let code=path.charCodeAt(0);const isAbsolute=code===47;let start;if(isAbsolute){ret.root="/";start=1}else{start=0}let startDot=-1;let startPart=0;let end=-1;let matchedSlash=true;let i=path.length-1;let preDotState=0;for(;i>=start;--i){code=path.charCodeAt(i);if(code===47){if(!matchedSlash){startPart=i+1;break}continue}if(end===-1){matchedSlash=false;end=i+1}if(code===46){if(startDot===-1)startDot=i;else if(preDotState!==1)preDotState=1}else if(startDot!==-1){preDotState=-1}}if(startDot===-1||end===-1||preDotState===0||preDotState===1&&startDot===end-1&&startDot===startPart+1){if(end!==-1){if(startPart===0&&isAbsolute)ret.base=ret.name=path.slice(1,end);else ret.base=ret.name=path.slice(startPart,end)}}else{if(startPart===0&&isAbsolute){ret.name=path.slice(1,startDot);ret.base=path.slice(1,end)}else{ret.name=path.slice(startPart,startDot);ret.base=path.slice(startPart,end)}ret.ext=path.slice(startDot,end)}if(startPart>0)ret.dir=path.slice(0,startPart-1);else if(isAbsolute)ret.dir="/";return ret},sep:"/",fromFileUrl,toFileUrl,toNamespacedPath:identity});var layer3=succeed5(Path2)(posixImpl);import*as NodePath from"path";import*as NodeUrl from"url";var fileUrlOps=(windows)=>({fromFileUrl:(url)=>try_2({try:()=>NodeUrl.fileURLToPath(url,{windows}),catch:(cause)=>new BadArgument({module:"Path",method:"fromFileUrl",cause})}),toFileUrl:(path)=>try_2({try:()=>NodeUrl.pathToFileURL(path,{windows}),catch:(cause)=>new BadArgument({module:"Path",method:"toFileUrl",cause})})});var layerPosix=succeed5(Path2)({[TypeId13]:TypeId13,...NodePath.posix,...fileUrlOps(false)});var layerWin32=succeed5(Path2)({[TypeId13]:TypeId13,...NodePath.win32,...fileUrlOps(true)});var layer4=succeed5(Path2)({[TypeId13]:TypeId13,...NodePath,...fileUrlOps(undefined)});var layer5=layer4;var encode=(input)=>encodeBytes(typeof input==="string"?encoder.encode(input):input);var decode=(str)=>{const stripped=stripCrlf(str);const length=stripped.length;if(length%4!==0){return fail2(new EncodingError({kind:"Decode",module:"Base64",input:stripped,message:`Length must be a multiple of 4, but is ${length}`}))}const index=stripped.indexOf("=");if(index!==-1&&(index<length-2||index===length-2&&stripped[length-1]!=="=")){return fail2(new EncodingError({kind:"Decode",module:"Base64",input:stripped,message:"Found a '=' character, but it is not at the end"}))}try{const missingOctets=stripped.endsWith("==")?2:stripped.endsWith("=")?1:0;const result=new Uint8Array(3*(length/4)-missingOctets);for(let i=0,j=0;i<length;i+=4,j+=3){const buffer=getCode(stripped.charCodeAt(i))<<18|getCode(stripped.charCodeAt(i+1))<<12|getCode(stripped.charCodeAt(i+2))<<6|getCode(stripped.charCodeAt(i+3));result[j]=buffer>>16;result[j+1]=buffer>>8&255;result[j+2]=buffer&255}return succeed2(result)}catch(cause){return fail2(new EncodingError({kind:"Decode",module:"Base64",input:stripped,message:cause instanceof Error?cause.message:"Invalid input"}))}};var encodeBytes=(bytes)=>{const length=bytes.length;let result="";let i;for(i=2;i<length;i+=3){result+=alphabet[bytes[i-2]>>2];result+=alphabet[(bytes[i-2]&3)<<4|bytes[i-1]>>4];result+=alphabet[(bytes[i-1]&15)<<2|bytes[i]>>6];result+=alphabet[bytes[i]&63]}if(i===length+1){result+=alphabet[bytes[i-2]>>2];result+=alphabet[(bytes[i-2]&3)<<4];result+="=="}if(i===length){result+=alphabet[bytes[i-2]>>2];result+=alphabet[(bytes[i-2]&3)<<4|bytes[i-1]>>4];result+=alphabet[(bytes[i-1]&15)<<2];result+="="}return result};var encoder=new TextEncoder;var stripCrlf=(str)=>str.replace(/[\n\r]/g,"");var alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var codes=new Uint8Array(123).fill(255);for(let i=0;i<alphabet.length;i++)codes[alphabet.charCodeAt(i)]=i;codes[61]=0;var getCode=(charCode)=>{if(charCode>=codes.length||codes[charCode]===255){throw new TypeError(`Invalid character ${String.fromCharCode(charCode)}`)}return codes[charCode]};var redactedRegistry=new WeakMap;var value=(self)=>{if(redactedRegistry.has(self)){return redactedRegistry.get(self)}else{throw new Error("Unable to get redacted value"+(self.label?` with label: "${self.label}"`:""))}};var TypeId14="~effect/Redacted";var isRedacted=(u)=>hasProperty(u,TypeId14);var make10=(value,options)=>{const self=Object.create(Proto2);if(options?.label){self.label=options.label}redactedRegistry.set(self,value);return self};var Proto2={[TypeId14]:{_A:(_)=>_},label:undefined,...PipeInspectableProto,toJSON(){return this.toString()},toString(){return`<redacted${isString(this.label)?":"+this.label:""}>`},[symbol](){return hash(redactedRegistry.get(this))},[symbol2](that){return isRedacted(that)&&equals(redactedRegistry.get(this),redactedRegistry.get(that))}};var value2=value;var makeEquivalence=(isEquivalent)=>make((x,y)=>isEquivalent(value2(x),value2(y)));function resolve3(ast){return ast.checks?ast.checks[ast.checks.length-1].annotations:ast.annotations}var STRUCTURAL_ANNOTATION_KEY="~structural";var SENTINELS_ANNOTATION_KEY="~sentinels";var CONSTRUCTOR_ANNOTATION_KEY="~constructor";var getExpected=memoize((ast)=>{const identifier=resolve3(ast)?.identifier;if(typeof identifier==="string")return identifier;return ast.getExpected(getExpected)});var missing=Symbol();var succeed8=succeed4;var missingExit=succeed8(missing);var sameExit=succeed8(missing);var toOption=(value)=>value===missing?none2():some2(value);var fromOptionExit=(option)=>option._tag==="None"?missingExit:succeed8(option.value);var TypeId15="~effect/SchemaIssue/Issue";function isIssue(u){return hasProperty(u,TypeId15)&&u[TypeId15]===TypeId15}function hasInput(issue){return Object.hasOwn(issue,"input")}class IssueNodeImpl{[TypeId15]=TypeId15;constructor(input,options){if(options?.reportInput===true&&input!==missing){this.input=input}}}var Filter=class extends IssueNodeImpl{_tag="Filter";filter;issue;constructor(filter,issue,input,options){super(input,options);this.filter=filter;this.issue=issue}};var Encoding=class extends IssueNodeImpl{_tag="Encoding";ast;issue;constructor(ast,issue,input,options){super(input,options);this.ast=ast;this.issue=issue}};var Pointer=class extends IssueNodeImpl{_tag="Pointer";path;issue;constructor(path,issue){super();this.path=path;this.issue=issue}};var MissingKey=class extends IssueNodeImpl{_tag="MissingKey";annotations;constructor(annotations){super();this.annotations=annotations}};var UnexpectedKey=class extends IssueNodeImpl{_tag="UnexpectedKey";ast;constructor(ast,input,options){super(input,options);this.ast=ast}};var Composite=class extends IssueNodeImpl{_tag="Composite";ast;issues;constructor(ast,issues,input,options){super(input,options);this.ast=ast;this.issues=issues}};var InvalidType=class extends IssueNodeImpl{_tag="InvalidType";ast;constructor(ast,input,options){super(input,options);this.ast=ast}};var InvalidValue=class extends IssueNodeImpl{_tag="InvalidValue";annotations;constructor(annotations,input,options){super(input,options);this.annotations=annotations}};var Forbidden=class extends IssueNodeImpl{_tag="Forbidden";annotations;constructor(annotations,input,options){super(input,options);this.annotations=annotations}};var AnyOf=class extends IssueNodeImpl{_tag="AnyOf";ast;issues;constructor(ast,issues,input,options){super(input,options);this.ast=ast;this.issues=issues}};var OneOf=class extends IssueNodeImpl{_tag="OneOf";ast;successes;constructor(ast,successes,input,options){super(input,options);this.ast=ast;this.successes=successes}};function makeFilterIssue(entry,input,options){if(isIssue(entry)){return entry}if(typeof entry==="string"){return new InvalidValue({message:entry},input,options)}const inner=typeof entry.issue==="string"?new InvalidValue({message:entry.issue},input,options):entry.issue;return new Pointer(entry.path,inner)}function makeSingle(out,input,options){if(out===undefined){return}if(typeof out==="boolean"){return out?undefined:new InvalidValue(undefined,input,options)}return makeFilterIssue(out,input,options)}function normalizeFilterOutput(ast,out,input,options){if(Array.isArray(out)){if(!isReadonlyArrayNonEmpty(out)){return}return out.length===1?makeFilterIssue(out[0],input,options):new Composite(ast,map(out,(entry)=>makeFilterIssue(entry,input,options)),input,options)}return makeSingle(out,input,options)}var defaultLeafHook=(issue)=>{const message=findMessage(issue);if(message!==undefined)return message;switch(issue._tag){case"InvalidType":return getExpectedMessage(getExpected(issue.ast),issue);case"InvalidValue":{const expected=findExpected(issue);if(expected!==undefined)return getExpectedMessage(expected,issue);const input=formatInput(issue);return input===undefined?"Expected a valid value":`Invalid data ${input}`}case"MissingKey":return"Missing key";case"UnexpectedKey":{const input=formatInput(issue);return input===undefined?"Expected no excess property":`Unexpected key with value ${input}`}case"Forbidden":return"Forbidden operation";case"OneOf":{const input=formatInput(issue);return input===undefined?"Expected exactly one member to match":`Expected exactly one member to match the input ${input}`}}};var defaultCheckHook=(issue)=>findMessage(issue.issue)??findMessage(issue);function formatInput(issue){return hasInput(issue)?format(issue.input):undefined}function findExpected(issue){const expected=issue.annotations?.expected;return typeof expected==="string"?expected:undefined}function getExpectedMessage(expected,issue){const input=formatInput(issue);return input===undefined?`Expected ${expected}`:`Expected ${expected}, got ${input}`}function formatCheck(check){const expected=check.annotations?.expected;if(typeof expected==="string")return expected;switch(check._tag){case"Filter":return"<filter>";case"FilterGroup":return check.checks.map((check)=>formatCheck(check)).join(" & ")}}function makeFormatterDefault(){return(issue)=>formatIssue(issue,"")}var defaultFormatter=makeFormatterDefault();function formatIssue(issue,path){let message;switch(issue._tag){case"Filter":{const annotated=defaultCheckHook(issue);if(annotated!==undefined){message=annotated}else{if(issue.issue._tag!=="InvalidValue"){return formatIssue(issue.issue,path)}const expected=findExpected(issue.issue);message=expected===undefined?getExpectedMessage(formatCheck(issue.filter),issue):getExpectedMessage(expected,issue.issue)}break}case"Encoding":return formatIssue(issue.issue,path);case"Pointer":return formatIssue(issue.issue,path+formatPath(issue.path));case"Composite":case"AnyOf":{if(issue._tag==="Composite"||issue.issues.length>0){return issue.issues.map((issue)=>formatIssue(issue,path)).join(`
|
|
238
238
|
`)}message=findMessage(issue)??getExpectedMessage(getExpected(issue.ast),issue);break}default:message=defaultLeafHook(issue);break}return path?`${message}
|
|
239
|
-
at ${path}`:message}function findMessage(issue){if(issue._tag==="Pointer")return;if(issue._tag==="Encoding")return findMessage(issue.issue);const annotations=issue._tag==="Filter"?issue.filter.annotations:("annotations"in issue)?issue.annotations:issue.ast.annotations;const message=annotations?.[issue._tag==="MissingKey"?"messageMissingKey":issue._tag==="UnexpectedKey"?"messageUnexpectedKey":"message"];if(typeof message==="string")return message}function getSchemaIssue(cause){let issue;for(const reason of cause.reasons){if(!isFailReason2(reason)||!isIssue(reason.error)){return}issue??=reason.error}return issue}function getSchemaIssueOrThrow(cause,message){const issue=getSchemaIssue(cause);if(issue===undefined){throw new Error(message,{cause})}return issue}var makeGetter=(fields)=>Object.assign(Object.create(Prototype),fields);function fail10(f){return transformOptionalEffect((oe,options)=>fail6(f(oe,options)))}function forbidden(message){return fail10((oe,options)=>{const annotations={message:message(oe)};return isSome2(oe)?new Forbidden(annotations,oe.value,options):new Forbidden(annotations)})}var passthrough_=makeGetter({_tag:"Passthrough"});function passthrough(){return passthrough_}function transform(f){return makeGetter({_tag:"Transform",transform:f})}function transformEffect(f){return makeGetter({_tag:"TransformEffect",transform:f})}function transformOptionalEffect(f){return makeGetter({_tag:"TransformOptionalEffect",transform:f})}function String2(){return transform(globalThis.String)}function Number3(){return transform(globalThis.Number)}function parseJson(options){return transformEffect((input,parseOptions)=>try_2({try:()=>JSON.parse(input,options?.reviver),catch:()=>new InvalidValue({expected:"a valid JSON string"},input,parseOptions)}))}function stringifyJson(options){return transformEffect((input,parseOptions)=>try_2({try:()=>{const output=JSON.stringify(input,options?.replacer,options?.space);if(output===undefined){throw new TypeError("Value cannot be represented as JSON")}return output},catch:()=>new InvalidValue({expected:"a JSON-serializable value"},input,parseOptions)}))}function encodeBase64(){return transform(encode)}function decodeBase64(){return transformEffect((input,options)=>mapErrorEager2(fromResult2(decode(input)),()=>new InvalidValue({expected:"a valid Base64 string"},input,options)))}var TypeId16="~effect/SchemaTransformation/Transformation";var Transformation=class extends Class{[TypeId16]=TypeId16;_tag="Transformation";decode;encode;constructor(decode,encode){super();this.decode=decode;this.encode=encode}flip(){return new Transformation(this.encode,this.decode)}};function isTransformation(u){return hasProperty(u,TypeId16)&&u[TypeId16]===TypeId16}var makeTransformation=(options)=>{if(isTransformation(options)){return options}return new Transformation(options.decode,options.encode)};function transformEffect2(options){return new Transformation(transformEffect(options.decode),transformEffect(options.encode))}function transform2(options){return new Transformation(transform(options.decode),transform(options.encode))}var passthrough_2=new Transformation(passthrough(),passthrough());function passthrough2(){return passthrough_2}var numberFromString=new Transformation(Number3(),String2());var urlFromString=transformEffect2({decode:(s,options)=>URL.canParse(s)?succeed6(new URL(s)):fail6(new InvalidValue({expected:"a valid URL string"},s,options)),encode:(url)=>succeed6(url.href)});var uint8ArrayFromBase64String=new Transformation(decodeBase64(),encodeBase64());function fromJsonString(options){return new Transformation(parseJson(options??{}),stringifyJson(options))}function makeGuard(tag){return(ast)=>ast._tag===tag}var isDeclaration=makeGuard("Declaration");var isNever2=makeGuard("Never");var isLiteral=makeGuard("Literal");var isUniqueSymbol=makeGuard("UniqueSymbol");var isArrays=makeGuard("Arrays");var isObjects=makeGuard("Objects");var isSuspend=makeGuard("Suspend");var Link=class{to;transformation;constructor(to,transformation){this.to=to;this.transformation=transformation}};var defaultParseOptions={};var Context=class{isOptional;isMutable;constructorDefault;annotations;constructor(isOptional,isMutable,constructorDefault=undefined,annotations=undefined){this.isOptional=isOptional;this.isMutable=isMutable;this.constructorDefault=constructorDefault;this.annotations=annotations}};var TypeId17="~effect/Schema";class ASTNodeImpl{[TypeId17]=TypeId17;annotations;checks;encoding;context;constructor(annotations=undefined,checks=undefined,encoding=undefined,context=undefined){this.annotations=annotations;this.checks=checks;this.encoding=encoding;this.context=context}toString(){return`<${this._tag}>`}}var Declaration=class extends ASTNodeImpl{_tag="Declaration";typeParameters;run;encodingChecks;encodingRun;constructor(typeParameters,run,annotations,checks,encoding,context,encodingChecks,encodingRun){super(annotations,checks,encoding,context);this.typeParameters=typeParameters;this.run=run;this.encodingChecks=encodingChecks;this.encodingRun=encodingRun}getParser(){let run;return(input,options)=>{if(input===missing)return missingExit;return(run??=this.run(this.typeParameters))(input,this,options)}}_rebuild(recur,checks,encodingChecks,run,encodingRun){const tps=mapOrSame(this.typeParameters,recur);return tps===this.typeParameters&&checks===this.checks&&encodingChecks===this.encodingChecks&&run===this.run&&encodingRun===this.encodingRun?this:new Declaration(tps,run,this.annotations,checks,undefined,this.context,encodingChecks,encodingRun)}recur(recur){return this._rebuild(recur,this.checks,this.encodingChecks,this.run,this.encodingRun)}flip(recur){return this._rebuild(recur,this.encodingChecks,this.checks,this.encodingRun??this.run,this.run)}getExpected(){const expected=this.annotations?.expected;if(typeof expected==="string")return expected;return"<Declaration>"}};var Null=class extends ASTNodeImpl{_tag="Null";getParser(){return fromConst(this,null)}getExpected(){return"null"}};var null_=new Null;var Undefined=class extends ASTNodeImpl{_tag="Undefined";getParser(){return fromConst(this,undefined)}toCodecJson(){return replaceEncoding(this,[undefinedToNull])}getExpected(){return"undefined"}};var undefinedToNull=new Link(null_,new Transformation(transform(()=>{return}),transform(()=>null)));var undefined_2=new Undefined;var Unknown=class extends ASTNodeImpl{_tag="Unknown";getParser(){return fromRefinement(this,isUnknown)}getExpected(){return"unknown"}};var unknown=new Unknown;var Literal=class extends ASTNodeImpl{_tag="Literal";literal;constructor(literal,annotations,checks,encoding,context){super(annotations,checks,encoding,context);if(typeof literal==="number"&&!globalThis.Number.isFinite(literal)){throw new Error(`A numeric literal must be finite, got ${format(literal)}`)}this.literal=literal}getParser(){return fromConst(this,this.literal)}matchPart(s,_options){return s===globalThis.String(this.literal)?this.literal:undefined}toCodecJson(){return typeof this.literal==="bigint"?literalToString(this):this}toCodecStringTree(){return typeof this.literal==="string"?this:literalToString(this)}getExpected(){return typeof this.literal==="string"?JSON.stringify(this.literal):globalThis.String(this.literal)}};function literalToString(ast){const literalAsString=globalThis.String(ast.literal);return replaceEncoding(ast,[new Link(new Literal(literalAsString),new Transformation(transform(()=>ast.literal),transform(()=>literalAsString)))])}var String3=class extends ASTNodeImpl{_tag="String";getParser(){return fromRefinement(this,isString)}matchPart(s,options){const checks=this.checks;return checks&&!options.disableChecks&&collectIssues(checks,s,undefined,this,options)?undefined:s}getExpected(){return"string"}};var string2=new String3;var Number4=class extends ASTNodeImpl{_tag="Number";getParser(){return fromRefinement(this,isNumber)}matchKey(s,options){return this._match(isStringNumberRegExp,s,options)}matchPart(s,options){return this._match(isStringFiniteRegExp,s,options)}_match(regexp,s,options){if(!regexp.test(s))return;const value=globalThis.Number(s);if(options.disableChecks||!this.checks)return value;return collectIssues(this.checks,value,undefined,this,options)?undefined:value}toCodecJson(){if(this.checks&&(hasCheck(this.checks,"effect/schema/isFinite")||hasCheck(this.checks,"effect/schema/isInt"))){return this}return replaceEncoding(this,[numberToJson])}toCodecStringTree(){if(this.toCodecJson()===this){return replaceEncoding(this,[finiteToString])}return replaceEncoding(this,[numberToString])}getExpected(){return"number"}};function hasCheck(checks,id){return checks.some((check)=>check.annotations?.representation?.id===id||check._tag==="FilterGroup"&&hasCheck(check.checks,id))}var number2=new Number4;var Boolean2=class extends ASTNodeImpl{_tag="Boolean";getParser(){return fromRefinement(this,isBoolean)}getExpected(){return"boolean"}};var boolean=new Boolean2;var Arrays=class extends ASTNodeImpl{_tag="Arrays";isMutable;elements;rest;encodingChecks;constructor(isMutable,elements,rest,annotations,checks,encoding,context,encodingChecks){super(annotations,checks,encoding,context);this.isMutable=isMutable;this.elements=elements;this.rest=rest;this.encodingChecks=encodingChecks;let hasOptional=false;for(let i=0;i<elements.length;i++){if(isOptional(elements[i])){hasOptional=true}else if(hasOptional){throw new Error("A required element cannot follow an optional element. ts(1257)")}}if(hasOptional&&rest.length>1){throw new Error("A required element cannot follow an optional element. ts(1257)")}for(let i=1;i<rest.length;i++){if(isOptional(rest[i])){throw new Error("An optional element cannot follow a rest element. ts(1266)")}}}getParser(compile,compileField=compile){const ast=this;let elements;let rest;const elementLen=ast.elements.length;const tailLen=Math.max(0,ast.rest.length-1);function getParser(tailThreshold,index){if(index<elementLen){return elements[index]}else if(index>=tailThreshold){return rest[index-tailThreshold+1]}return rest[0]}const finish=(state)=>{const{input,len,options}=state;if(ast.rest.length===0&&len>elementLen){for(let i=elementLen;i<len;i++){const unexpected=new UnexpectedKey(ast,input[i],options);const issue=new Pointer([i],unexpected);if(options.errors==="all"){if(state.issues)state.issues.push(issue);else state.issues=[issue]}else{return fail6(new Composite(ast,[issue],input,options))}}}if(state.issues){return fail6(new Composite(ast,state.issues,input,options))}return succeed8(state.output)};const parse=(input,options)=>{const len=input.length;const state={ast,getParser,input,len,tailThreshold:Math.max(elementLen,len-tailLen),output:new globalThis.Array(len),issues:undefined,options};const end=ast.rest.length===0?elementLen:Math.max(len,elementLen+tailLen);const concurrency=options.concurrency===undefined?1:resolveConcurrency(options.concurrency);const eff=concurrency===1?parseArray(state,input,0,end):parseArrayConcurrent(state,input,{concurrency,end});if(!eff)return finish(state);if(effectIsExit(eff))return flatMapEager2(eff,()=>finish(state));let first=true;return suspend2(()=>{if(!first)return parse(input,options);first=false;return flatMap3(eff,()=>finish(state))})};return(input,options)=>{if(input===missing)return missingExit;try{if(!Array.isArray(input)){return fail6(new InvalidType(ast,input,options))}if(!elements){elements=ast.elements.map((ast)=>({ast,parser:compileField(ast)}));rest=ast.rest.map((ast)=>({ast,parser:compileField(ast)}))}return parse(input,options)}catch(error){return die3(error)}}}_rebuild(recur,checks,encodingChecks){const elements=mapOrSame(this.elements,recur);const rest=mapOrSame(this.rest,recur);return elements===this.elements&&rest===this.rest&&checks===this.checks&&encodingChecks===this.encodingChecks?this:new Arrays(this.isMutable,elements,rest,this.annotations,checks,undefined,this.context,encodingChecks)}recur(recur){return this._rebuild(recur,this.checks,this.encodingChecks)}flip(recur){return this._rebuild(recur,this.encodingChecks,this.checks)}getExpected(){return"array"}};function stepArray(s,item,exit,i){if(exit._tag==="Failure"){return wrapPropertyKeyIssue(s,s.ast,i,exit)}const value=exit===sameExit?item:exit[args];if(value!==missing){s.output[i]=value}else{const p=s.getParser(s.tailThreshold,i);if(isOptional(p.ast))return;const issue=new Pointer([i],new MissingKey(p.ast.context?.annotations));if(s.options.errors==="all"){if(s.issues)s.issues.push(issue);else s.issues=[issue]}else{return fail5(new Composite(s.ast,[issue],s.input,s.options))}}}var parseArrayOptions={onItem(s,item,i){const value=i<s.len?item:missing;return s.getParser(s.tailThreshold,i).parser(value,s.options)},step:stepArray};var parseArray=iterateEager()(parseArrayOptions);var parseArrayConcurrent=iterateConcurrent()(parseArrayOptions);var wrapPropertyKeyIssue=(s,ast,key,exit)=>{if(exit.cause.reasons.length===0){return exit}const issue=getSchemaIssue(exit.cause);if(issue===undefined){return failCause2(map3(exit.cause,(issue)=>new Composite(ast,[new Pointer([key],issue)],s.input,s.options)))}const pointer=new Pointer([key],issue);if(s.options.errors==="all"){if(s.issues)s.issues.push(pointer);else s.issues=[pointer]}else{return fail5(new Composite(ast,[pointer],s.input,s.options))}};var FINITE_PATTERN="[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?";function getIndexSignatureKeys(input,parameter,options=defaultParseOptions){let stringKeys;let symbolKeys;function go(parameter){switch(parameter._tag){case"String":case"TemplateLiteral":return(stringKeys??=Object.keys(input)).filter((k)=>parameter.matchPart(k,options)!==undefined);case"Number":return(stringKeys??=Object.keys(input)).filter((k)=>parameter.matchKey(k,options)!==undefined);case"Symbol":return(symbolKeys??=Object.getOwnPropertySymbols(input)).filter((k)=>Object.prototype.propertyIsEnumerable.call(input,k)&¶meter.matchKey(k,options)!==undefined);case"Union":return[...new Set(parameter.types.flatMap(go))];default:return[]}}return go(parameterFromPropertyKey(toEncoded(parameter)))}var PropertySignature=class{name;type;constructor(name,type){this.name=name;this.type=type}};function isIndexSignatureParameterSide(ast){switch(ast._tag){case"String":case"Number":case"Symbol":case"TemplateLiteral":return true;case"Union":return ast.types.every(isIndexSignatureParameterSide);default:return false}}function isIndexSignatureParameterEncodedSide(ast){const encoded=getLastEncoding(ast);switch(encoded._tag){case"String":case"Number":case"Symbol":case"TemplateLiteral":return true;case"Union":return encoded.types.every(isIndexSignatureParameterEncodedSide);default:return false}}function isIndexSignatureParameter(ast){return isIndexSignatureParameterSide(ast)&&isIndexSignatureParameterEncodedSide(ast)}var IndexSignature=class{parameter;type;constructor(parameter,type){if(!isIndexSignatureParameter(parameter)){throw new Error(`Invalid index signature parameter ${parameter._tag}`)}this.parameter=parameter;this.type=type;if(isOptional(type)&&!containsUndefined(type)){throw new Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}}};var Objects=class extends ASTNodeImpl{_tag="Objects";propertySignatures;indexSignatures;encodingChecks;constructor(propertySignatures,indexSignatures,annotations,checks,encoding,context,encodingChecks){super(annotations,checks,encoding,context);this.propertySignatures=propertySignatures;this.indexSignatures=indexSignatures;this.encodingChecks=encodingChecks}getParser(compile,compileField=compile){const ast=this;const hasProperties=ast.propertySignatures.length;const indexCount=ast.indexSignatures.length;if(!hasProperties&&!indexCount){return fromRefinement(ast,isNotNullish)}let properties;let indexes;const compileMembers=()=>{if(!properties){properties=ast.propertySignatures.map((ps)=>({parser:compileField(ps.type),name:ps.name,type:ps.type}));indexes=indexCount?ast.indexSignatures.map((is)=>({is,parserKey:compile(parameterFromPropertyKey(is.parameter)),parserValue:compileField(is.type)})):undefined}return properties};const makeFallback=()=>{const expectedKeys=new Set(ast.propertySignatures.map((ps)=>typeof ps.name==="number"?globalThis.String(ps.name):ps.name));const finishIndex=(s,key,k2,inputValue,exitValue)=>{if(exitValue._tag==="Failure"){return wrapPropertyKeyIssue(s,ast,key,exitValue)??void_2}const value=exitValue===sameExit?inputValue:exitValue[args];if(k2!==missing&&value!==missing){if(hasProperties&&(expectedKeys.has(key)||expectedKeys.has(typeof k2==="number"?globalThis.String(k2):k2)))return void_2;assignProperty(s.out,k2,value)}return void_2};const parseIndex=(s,key,index,exitKey)=>{if(!exitKey){const eff=index.parserKey(key,s.options);if(!effectIsExit(eff)){return flatMap3(exit2(eff),(exit)=>parseIndex(s,key,index,exit))}exitKey=eff}if(exitKey._tag==="Failure"){return wrapPropertyKeyIssue(s,ast,key,exitKey)??void_2}const k2=exitKey===sameExit?key:exitKey[args];const inputValue=s.input[key];const result=index.parserValue(inputValue,s.options);return effectIsExit(result)?finishIndex(s,key,k2,inputValue,result):flatMap3(exit2(result),(exit)=>finishIndex(s,key,k2,inputValue,exit))};const parseStringIndex=(s,key,index)=>{const inputValue=s.input[key];const result=index.parserValue(inputValue,s.options);return effectIsExit(result)?finishIndex(s,key,key,inputValue,result):flatMap3(exit2(result),(exit)=>finishIndex(s,key,key,inputValue,exit))};const parseIndexes=indexCount?iterateConcurrent()({onItem:(s,[key,index])=>index.is.parameter===string2?parseStringIndex(s,key,index):parseIndex(s,key,index),step:(_s,_item,exit)=>exit._tag==="Failure"?exit:undefined}):undefined;return fnUntracedEager2(function*(input,options){if(input===missing){return missing}if(!(typeof input==="object"&&input!==null&&!Array.isArray(input))){return yield*fail6(new InvalidType(ast,input,options))}compileMembers();const record=input;const out={};const state={ast,input:record,out,issues:undefined,options};const errorsAllOption=options.errors==="all";const onExcessPropertyError=options.onExcessProperty==="error";const concurrency=options.concurrency===undefined?1:resolveConcurrency(options.concurrency);const indexKeys=indexCount&&onExcessPropertyError?ast.indexSignatures.map((index)=>getIndexSignatureKeys(record,index.parameter,options)):undefined;if(onExcessPropertyError){const coveredKeys=indexKeys?new Set(expectedKeys):expectedKeys;if(indexKeys){for(const keys of indexKeys){for(const key of keys)coveredKeys.add(key)}}const inputKeys=Reflect.ownKeys(record);for(let i=0;i<inputKeys.length;i++){const key=inputKeys[i];if(!coveredKeys.has(key)&&Object.prototype.propertyIsEnumerable.call(record,key)){const unexpected=new UnexpectedKey(ast,record[key],options);const issue=new Pointer([key],unexpected);if(errorsAllOption){if(state.issues){state.issues.push(issue)}else{state.issues=[issue]}continue}else{return yield*fail6(new Composite(ast,[issue],input,options))}}}}if(hasProperties){const eff=concurrency===1?parseProperties(state,properties):parsePropertiesConcurrent(state,properties,{concurrency});if(eff)yield*eff}if(indexCount&&concurrency===1){for(let i=0;i<indexCount;i++){const index=indexes[i];const parse=index.is.parameter===string2?parseStringIndex:parseIndex;const keys=indexKeys?.[i]??(index.is.parameter===string2?Object.keys(record):getIndexSignatureKeys(record,index.is.parameter,options));for(let j=0;j<keys.length;j++){const eff=parse(state,keys[j],index);if(!effectIsExit(eff))yield*eff;else if(eff._tag==="Failure")return yield*eff}}}else if(parseIndexes){const keyPairs=empty2();for(let i=0;i<indexCount;i++){const index=indexes[i];const keys=indexKeys?.[i]??(index.is.parameter===string2?Object.keys(record):getIndexSignatureKeys(record,index.is.parameter,options));for(let j=0;j<keys.length;j++){keyPairs.push([keys[j],index])}}const eff=parseIndexes(state,keyPairs,{concurrency});if(eff)yield*eff}if(state.issues){return yield*fail6(new Composite(ast,state.issues,input,options))}return out})};if(indexCount)return makeFallback();let fallback;const resume=(state,index,pending)=>{const property=properties[index];return flatMap3(exit2(pending),(exit)=>{const terminal=stepProperty(state,property,exit);if(terminal)return terminal;const done=()=>succeed8(state.out);const eff=parseProperties(state,properties.slice(index+1));return eff?flatMapEager2(eff,done):done()})};return(input,options)=>{if(input===missing)return missingExit;if(options.errors==="all"||options.onExcessProperty!==undefined||options.concurrency!==undefined&&resolveConcurrency(options.concurrency)!==1){return(fallback??=makeFallback())(input,options)}if(!(typeof input==="object"&&input!==null&&!Array.isArray(input))){return fail6(new InvalidType(ast,input,options))}const props=compileMembers();const record=input;const out={};const state={ast,input:record,out,issues:undefined,options};try{for(let index=0;index<props.length;index++){const property=props[index];const name=property.name;const hasKey=hasPropertySignature(record,name);const value=hasKey?record[name]:missing;const exit=property.parser(value,options);if(!effectIsExit(exit)){return resume(state,index,exit)}if(exit===sameExit){if(hasKey)assignProperty(out,name,value);continue}const terminal=stepProperty(state,property,exit);if(terminal)return terminal}}catch(error){return die3(error)}return succeed8(out)}}_rebuild(recur,recurParameter,checks,encodingChecks){const props=mapOrSame(this.propertySignatures,(ps)=>{const t=recur(ps.type);return t===ps.type?ps:new PropertySignature(ps.name,t)});const indexes=mapOrSame(this.indexSignatures,(is)=>{const p=recurParameter(is.parameter);const t=recur(is.type);return p===is.parameter&&t===is.type?is:new IndexSignature(p,t)});return props===this.propertySignatures&&indexes===this.indexSignatures&&checks===this.checks&&encodingChecks===this.encodingChecks?this:new Objects(props,indexes,this.annotations,checks,undefined,this.context,encodingChecks)}flip(recur){return this._rebuild(recur,recur,this.encodingChecks,this.checks)}recur(recur,recurParameter=recur){return this._rebuild(recur,recurParameter,this.checks,this.encodingChecks)}getExpected(){if(this.propertySignatures.length===0&&this.indexSignatures.length===0)return"object | array";return"object"}};function stepProperty(s,p,exit){if(exit._tag==="Failure"){return wrapPropertyKeyIssue(s,s.ast,p.name,exit)}if(exit===sameExit)return;const value=exit[args];if(value!==missing){assignProperty(s.out,p.name,value);return}delete s.out[p.name];if(!isOptional(p.type)){const issue=new Pointer([p.name],new MissingKey(p.type.context?.annotations));if(s.options.errors==="all"){if(s.issues)s.issues.push(issue);else s.issues=[issue];return}else{return fail5(new Composite(s.ast,[issue],s.input,s.options))}}}var parsePropertiesOptions={onItem(s,p){if(!hasPropertySignature(s.input,p.name)){return p.parser(missing,s.options)}const value=s.input[p.name];assignProperty(s.out,p.name,value);return p.parser(value,s.options)},step:stepProperty};var parseProperties=iterateEager()(parsePropertiesOptions);var parsePropertiesConcurrent=iterateConcurrent()(parsePropertiesOptions);function combineChecks(a,b){if(!a)return b;if(!b)return a;return[...a,...b]}function struct(fields,checks,annotations){return new Objects(Reflect.ownKeys(fields).map((key)=>{return new PropertySignature(key,fields[key].ast)}),[],annotations,checks)}function getAST(self){return self.ast}function tuple(elements,checks=undefined){return new Arrays(false,elements.map((e)=>e.ast),[],undefined,checks)}function union(members,options,checks){return new Union(members.map(getAST),options,undefined,checks)}var toCandidate=memoizeIdempotent((ast)=>{while(true){if(isSuspend(ast))return unknown;const encoding=ast.encoding;if(!encoding){return ast.recur?.(toCandidate,identity)??ast}if(encoding.some((link)=>link.transformation._tag==="Middleware"&&link.transformation.decode!==identity))return unknown;ast=encoding[encoding.length-1].to}});function getCandidateTypes(ast){switch(ast._tag){case"Null":return["null"];case"Undefined":return["undefined"];case"String":case"TemplateLiteral":return["string"];case"Number":return["number"];case"Boolean":return["boolean"];case"Symbol":case"UniqueSymbol":return["symbol"];case"BigInt":return["bigint"];case"Arrays":return["array"];case"ObjectKeyword":return["object","array","function"];case"Objects":return ast.propertySignatures.length||ast.indexSignatures.length?["object"]:["string","number","boolean","symbol","bigint","object","array","function"];case"Enum":return Array.from(new Set(ast.enums.map(([,v])=>typeof v)));case"Literal":return[typeof ast.literal];case"Union":return Array.from(new Set(ast.types.flatMap(getCandidateTypes)));default:return["null","undefined","string","number","boolean","symbol","bigint","object","array","function"]}}function collectSentinels(ast){switch(ast._tag){default:return[];case"Declaration":{const s=ast.annotations?.[SENTINELS_ANNOTATION_KEY];return Array.isArray(s)?s:[]}case"Objects":return ast.propertySignatures.flatMap((ps)=>{const type=ps.type;if(!isOptional(type)){if(isLiteral(type)){return[{key:ps.name,literal:type.literal}]}if(isUniqueSymbol(type)){return[{key:ps.name,literal:type.symbol}]}}return[]});case"Arrays":return ast.elements.flatMap((e,i)=>{if(!isOptional(e)){if(isLiteral(e)){return[{key:i,literal:e.literal}]}if(isUniqueSymbol(e)){return[{key:i,literal:e.symbol}]}}return[]});case"Union":{if(ast.types.length===0)return[];const members=ast.types.map((type)=>collectSentinels(toCandidate(type)));return members[0].filter((s)=>members.every((sentinels)=>sentinels.some((o)=>o.key===s.key&&o.literal===s.literal)))}case"Suspend":return collectSentinels(ast.thunk())}}var candidateIndexCache=new WeakMap;var emptyCandidates=Object.freeze([]);var getRuntimeType=(input)=>input===null?"null":Array.isArray(input)?"array":typeof input;var hasPropertySignature=(input,key)=>key==="__proto__"?Object.hasOwn(input,key):(key in input);function getCandidateIndex(types){let index=candidateIndexCache.get(types);if(index)return index;let bySentinel;let sentinelCandidateCount=0;let otherwise;let literalCandidates;let onlyLiterals=true;const literalOf=[];for(let i=0;i<types.length;i++){const a=types[i];const encoded=toCandidate(a);if(isNever2(encoded))continue;if(isLiteral(encoded)||isUniqueSymbol(encoded)){literalCandidates??=new Map;const literal=isLiteral(encoded)?encoded.literal:encoded.symbol;literalOf[i]=literal;let arr=literalCandidates.get(literal);if(!arr)literalCandidates.set(literal,arr=[]);arr.push(i)}else{onlyLiterals=false}const sentinels=collectSentinels(encoded);if(sentinels.length){bySentinel??=new Map;sentinelCandidateCount++;for(const{key,literal}of sentinels){let entry=bySentinel.get(key);if(!entry)bySentinel.set(key,entry=[new Map,new Set]);entry[1].add(i);let indexes=entry[0].get(literal);if(!indexes)entry[0].set(literal,indexes=new Set);indexes.add(i)}}else{otherwise??={};const candidateTypes=getCandidateTypes(encoded);for(const t of candidateTypes)(otherwise[t]??=[]).push(i)}}const fallbacks={};const getFallback=(type)=>fallbacks[type]??=Object.freeze(otherwise?.[type]??emptyCandidates);if(onlyLiterals&&literalCandidates){literalCandidates.forEach(Object.freeze);index=(input)=>literalCandidates.get(input)??emptyCandidates}else if(bySentinel?.size===1&&!otherwise){const[key,[byValue]]=bySentinel.entries().next().value;const candidates=new Map;for(const[literal,indexes]of byValue){candidates.set(literal,Object.freeze(Array.from(indexes)))}const all=Object.freeze(types.map((_,i)=>i));index=(input,isConstructor)=>{if(isObjectKeyword(input)){const value=hasPropertySignature(input,key)?input[key]:undefined;if(value!==undefined)return candidates.get(value)??emptyCandidates;if(isConstructor)return all}return emptyCandidates}}else if(bySentinel){let commonSentinel;for(const entry of bySentinel){if((!commonSentinel||entry[1][0].size>commonSentinel[1][0].size)&&entry[1][1].size===sentinelCandidateCount){commonSentinel=entry}}index=(input,isConstructor)=>{const runtimeType=getRuntimeType(input);if(!isObjectKeyword(input))return getFallback(runtimeType);const selected=new Set(otherwise?.[runtimeType]);let directKey;if(commonSentinel){const[key,[byValue]]=commonSentinel;const hasKey=hasPropertySignature(input,key);const value=hasKey?input[key]:undefined;if(hasKey&&(!isConstructor||value!==undefined)){const match=byValue.get(value);if(!match)return getFallback(runtimeType);for(const i of match)selected.add(i);directKey=key}}if(directKey===undefined){for(const[key,[byValue,all]]of bySentinel){const hasKey=hasPropertySignature(input,key);const value=hasKey?input[key]:undefined;if(hasKey&&(!isConstructor||value!==undefined)){const match=byValue.get(value);if(match){for(const i of match)selected.add(i)}}else if(isConstructor){for(const i of all)selected.add(i)}}}for(const[key,[byValue,all]]of bySentinel){if(key===directKey)continue;const hasKey=hasPropertySignature(input,key);const value=hasKey?input[key]:undefined;if(hasKey&&(!isConstructor||value!==undefined)){const match=byValue.get(value);for(const i of selected){if(all.has(i)&&!match?.has(i))selected.delete(i)}}}return Array.from(selected).sort((a,b)=>a-b)}}else{index=(input)=>{const fallback=getFallback(getRuntimeType(input));return literalCandidates?fallback.filter((i)=>literalOf[i]===undefined||literalOf[i]===input):fallback}}candidateIndexCache.set(types,index);return index}var Union=class extends ASTNodeImpl{_tag="Union";types;options;encodingChecks;constructor(types,options,annotations,checks,encoding,context,encodingChecks){super(annotations,checks,encoding,context);this.types=types;this.options=options;this.encodingChecks=encodingChecks}getParser(compile,compileField){const ast=this;const isConstructor=compileField!==undefined;const parsers=[];const parser=(i)=>parsers[i]??=compile(ast.types[i]);let index;return(input,options)=>{if(input===missing){return missingExit}const candidates=(index??=getCandidateIndex(ast.types))(input,isConstructor);if(candidates.length===0){return fail6(new AnyOf(ast,[],input,options))}if(candidates.length===1){const result=parser(candidates[0])(input,options);if(result._tag==="Success")return result;return effectIsExit(result)?failSingleUnionCandidate(ast,result.cause,input,options):catchSingleUnionCandidate(ast,result,input,options)}return parseUnionCandidates(ast,parser,candidates,input,options)}}_rebuild(recur,checks,encodingChecks){const types=mapOrSame(this.types,recur);return types===this.types&&checks===this.checks&&encodingChecks===this.encodingChecks?this:new Union(types,this.options,this.annotations,checks,undefined,this.context,encodingChecks)}recur(recur){return this._rebuild(recur,this.checks,this.encodingChecks)}flip(recur){return this._rebuild(recur,this.encodingChecks,this.checks)}matchPart(s,options){for(const type of this.types){const out=type.matchPart(s,options);if(out!==undefined)return out}return}getExpected(getExpected){const expected=this.annotations?.expected;if(typeof expected==="string")return expected;if(this.types.length===0)return"never";const types=this.types.map((type)=>{const encoded=toEncoded(type);switch(encoded._tag){case"Arrays":{const literals=encoded.elements.filter(isLiteral);if(literals.length>0){return`${formatIsMutable(encoded.isMutable)}[ ${literals.map((e)=>getExpected(e)+formatIsOptional(e.context?.isOptional)).join(", ")}, ... ]`}break}case"Objects":{const literals=encoded.propertySignatures.filter((ps)=>isLiteral(ps.type));if(literals.length>0){return`{ ${literals.map((ps)=>`${formatIsMutable(ps.type.context?.isMutable)}${formatPropertyKey(ps.name)}${formatIsOptional(ps.type.context?.isOptional)}: ${getExpected(ps.type)}`).join(", ")}, ... }`}break}}return getExpected(encoded)});return Array.from(new Set(types)).join(" | ")}};function failSingleUnionCandidate(ast,cause,input,options){const issue=getSchemaIssue(cause);if(!issue)return failCause2(cause);return fail5(new AnyOf(ast,[issue],input,options))}function catchSingleUnionCandidate(ast,result,input,options){return catchCause2(result,(cause)=>failSingleUnionCandidate(ast,cause,input,options))}function parseUnionCandidates(ast,parser,candidates,input,options){const state={ast,parser,input,out:undefined,successes:ast.options?.mode==="oneOf"?[]:undefined,issues:undefined,options};const eff=parseUnion(state,candidates);if(!eff){if(state.out)return state.out;return fail6(new AnyOf(ast,state.issues??[],input,options))}return resumeUnion(eff,state)}function resumeUnion(eff,state){return flatMapEager2(eff,(_)=>{if(state.out===sameExit)return succeed6(state.input);if(state.out)return state.out;return fail6(new AnyOf(state.ast,state.issues??[],state.input,state.options))})}var parseUnion=iterateEager()({onItem(s,i){return s.parser(i)(s.input,s.options)},step(s,i,exit){if(exit._tag==="Failure"){const issue=getSchemaIssue(exit.cause);if(issue===undefined){return exit}if(s.issues)s.issues.push(issue);else s.issues=[issue]}else{if(s.out&&s.successes){s.successes.push(s.ast.types[i]);return fail5(new OneOf(s.ast,s.successes,s.input,s.options))}s.out=exit;if(s.successes){s.successes.push(s.ast.types[i])}else{return void_2}}}});var nonFiniteLiterals=new Union([new Literal("Infinity"),new Literal("-Infinity"),new Literal("NaN")]);function formatIsMutable(isMutable){return isMutable?"":"readonly "}function formatIsOptional(isOptional){return isOptional?"?":""}var Filter2=class extends Class{_tag="Filter";run;annotations;aborted;constructor(run,annotations=undefined,aborted=false){super();this.run=run;this.annotations=annotations;this.aborted=aborted}annotate(annotations){return new Filter2(this.run,{...this.annotations,...annotations},this.aborted)}abort(){return new Filter2(this.run,this.annotations,true)}and(other,annotations){return new FilterGroup([this,other],annotations)}};var FilterGroup=class extends Class{_tag="FilterGroup";checks;annotations;constructor(checks,annotations=undefined){super();this.checks=checks;this.annotations=annotations}annotate(annotations){return new FilterGroup(this.checks,{...this.annotations,...annotations})}and(other,annotations){return new FilterGroup([this,other],annotations)}};function makeFilter(filter,annotations,aborted=false){return new Filter2((input,ast,options)=>normalizeFilterOutput(ast,filter(input,ast,options),input,options),annotations,aborted)}function isFinite(annotations){return makeFilter((n)=>globalThis.Number.isFinite(n),{expected:"a finite number",representation:{id:"effect/schema/isFinite",payload:null},toJsonSchema:()=>({type:"number"}),toCode:()=>({runtime:"Schema.isFinite()"}),arbitraryConstraint:{number:"finite"},...annotations})}var finite=appendChecks(number2,[isFinite()]);var numberToJson=new Link(new Union([finite,nonFiniteLiterals]),new Transformation(Number3(),transform((n)=>globalThis.Number.isFinite(n)?n:globalThis.String(n))));function isPattern(regExp,annotations){const copy=new globalThis.RegExp(regExp);const payload={source:copy.source,flags:copy.flags};return makeFilter((s)=>{copy.lastIndex=0;return copy.test(s)},{expected:`a string matching the RegExp ${payload.source}`,representation:{id:"effect/schema/isPattern",payload},toJsonSchema:()=>[{},true],arbitraryConstraint:{patterns:[payload]},...annotations})}var bodyOwners=new WeakMap;function copy2(ast,changes){const out=Object.assign(Object.create(Object.getPrototypeOf(ast)),ast,changes);if(Reflect.ownKeys(changes).every((key)=>key==="context"||key==="encoding")){bodyOwners.set(out,getContextOwner(ast))}return out}function getContextOwner(ast){const existing=bodyOwners.get(ast);if(existing!==undefined)return existing;if(ast.encoding===undefined)return ast;const owner=Object.assign(Object.create(Object.getPrototypeOf(ast)),ast,{encoding:undefined});bodyOwners.set(ast,owner);return owner}function replaceEncoding(ast,encoding){return ast.encoding===encoding?ast:copy2(ast,{encoding})}function replaceContext(ast,context){if(ast.context===context){return ast}const owner=getContextOwner(ast);if(owner.context===context&&owner.encoding===ast.encoding){return owner}return copy2(ast,{context})}function getLastEncoding(ast){return ast.encoding?getLastEncoding(ast.encoding[ast.encoding.length-1].to):ast}function annotate(ast,annotations){if(ast.checks){const last=ast.checks[ast.checks.length-1];return replaceChecks(ast,append(ast.checks.slice(0,-1),last.annotate(annotations)))}return copy2(ast,{annotations:{...ast.annotations,...annotations}})}function replaceChecks(ast,checks){if(ast._tag==="Suspend"&&checks){throw new Error("Cannot add checks to Suspend")}if(ast.checks===checks){return ast}return copy2(ast,{checks})}function appendChecks(ast,checks){return replaceChecks(ast,combineChecks(ast.checks,checks))}function mapLink(link,f){const to=f(link.to);return to===link.to?link:new Link(to,link.transformation)}function updateLastLink(encoding,f){const links=encoding;const last=links[links.length-1];const out=mapLink(last,f);return out===last?encoding:append(encoding.slice(0,encoding.length-1),out)}function applyToLastLink(f){return(ast)=>ast.encoding?replaceEncoding(ast,updateLastLink(ast.encoding,f)):ast}function replaceContextLastLink(ast,context){return applyToLastLink((ast)=>replaceContext(ast,context))(ast)}function applyToSelfOrLastLinkEncoding(f){function out(ast){return ast.encoding?replaceEncoding(ast,updateLastLink(ast.encoding,out)):f(ast)}return memoize(out)}function applyToSelfOrLastLinkEncodingIdempotent(f,options){function out(ast){if(ast.encoding){const last=ast.encoding[ast.encoding.length-1];return options?.stopAt?.(last)?ast:replaceEncoding(ast,updateLastLink(ast.encoding,out))}return f(ast)}return memoizeIdempotent(out)}function appendTransformation(from,transformation,to){const link=new Link(from,transformation);return replaceEncoding(to,to.encoding?[...to.encoding,link]:[link])}function mapOrSame(as,f){let out;for(let i=0;i<as.length;i++){const a=as[i];const fa=f(a);if(out){out[i]=fa}else if(fa!==a){out=new Array(as.length);for(let j=0;j<i;j++){out[j]=as[j]}out[i]=fa}}return out??as}function annotateKey(ast,annotations){const context=ast.context?new Context(ast.context.isOptional,ast.context.isMutable,ast.context.constructorDefault,{...ast.context.annotations,...annotations}):new Context(false,false,undefined,annotations);return replaceContext(ast,context)}var optionalKey=memoizeIdempotent((ast)=>{const context=ast.context?ast.context.isOptional===false?new Context(true,ast.context.isMutable,ast.context.constructorDefault,ast.context.annotations):ast.context:new Context(true,false);return optionalKeyLastLink(replaceContext(ast,context))});var optionalKeyLastLink=applyToLastLink(optionalKey);var optional=memoize((ast)=>optionalKey(new Union([ast,undefined_2])));function withConstructorDefault(ast,defaultValue){const context=ast.context?new Context(ast.context.isOptional,ast.context.isMutable,defaultValue,ast.context.annotations):new Context(false,false,defaultValue);return replaceContext(ast,context)}function decodeTo(from,to,transformation){return appendTransformation(from,transformation,to)}function parseParameter(ast){const literals=[];const parameters=[];function go(ast){switch(ast._tag){case"Literal":if(isPropertyKey(ast.literal)&&!literals.includes(ast.literal)){literals.push(ast.literal)}return;case"UniqueSymbol":if(!literals.includes(ast.symbol)){literals.push(ast.symbol)}return;case"Never":return;case"Union":for(let i=0;i<ast.types.length;i++){go(ast.types[i])}return;default:parameters.push(ast)}}go(ast);return{literals,parameters}}function record(key,value){const{literals,parameters:indexSignatures}=parseParameter(key);return new Objects(literals.map((literal)=>new PropertySignature(literal,value)),indexSignatures.map((parameter)=>new IndexSignature(parameter,value)))}function isOptional(ast){return ast.context?.isOptional??false}function isStructuralCheck(check){return check.annotations?.[STRUCTURAL_ANNOTATION_KEY]===true||check._tag==="FilterGroup"&&check.checks.every(isStructuralCheck)}function extractStructuralChecks(checks){function extract(check){if(isStructuralCheck(check))return[check];return check._tag==="FilterGroup"?check.checks.flatMap(extract):[]}const out=checks.flatMap(extract);return isArrayNonEmpty2(out)?out:undefined}function canPreserveEncodingChecks(ast){let preserve=true;function visit(child){preserve=preserve&&!child.encoding&&!isSuspend(child);if(preserve&&"recur"in child)child.recur(visit);return child}if("recur"in ast)ast.recur(visit);return preserve}var toType=memoizeIdempotent((ast)=>{const owner=getContextOwner(ast);if(owner!==ast){const type=toType(owner);return type===owner&&ast.encoding===undefined?ast:replaceContext(type,ast.context)}const type="recur"in ast?ast.recur(toType):ast;if("encodingChecks"in type&&type.encodingChecks){const checks=canPreserveEncodingChecks(ast)?type.encodingChecks:isArrays(type)||isObjects(type)||isDeclaration(type)&&type.typeParameters.length>0?extractStructuralChecks(type.encodingChecks):undefined;return copy2(type,{encodingChecks:undefined,checks:combineChecks(type.checks,checks)})}return type});var toEncoded=memoizeIdempotent((ast)=>{return toType(flip2(ast))});function flipEncoding(ast,encoding){const links=encoding;const len=links.length;const last=links[len-1];const ls=[new Link(flip2(replaceEncoding(ast,undefined)),links[0].transformation.flip())];for(let i=1;i<len;i++){ls.unshift(new Link(flip2(links[i-1].to),links[i].transformation.flip()))}const to=flip2(last.to);if(to.encoding){return replaceEncoding(to,[...to.encoding,...ls])}else{return replaceEncoding(to,ls)}}var flip2=memoize((ast)=>{if(ast.encoding){return flipEncoding(ast,ast.encoding)}const owner=getContextOwner(ast);if(owner!==ast){const flipped=flip2(owner);return flipped===owner?ast:replaceContext(flipped,ast.context)}return"flip"in ast?ast.flip(flip2):("recur"in ast)?ast.recur(flip2):ast});function containsUndefined(ast){switch(ast._tag){case"Undefined":return true;case"Union":return ast.types.some(containsUndefined);default:return false}}function fromConst(ast,value){const succeed=value===0?sameExit:succeed8(value);return(input,options)=>{if(input===missing)return missingExit;if(input===value)return succeed;return fail6(new InvalidType(ast,input,options))}}function fromRefinement(ast,refinement){return(input,options)=>{if(input===missing)return missingExit;if(refinement(input))return sameExit;return fail6(new InvalidType(ast,input,options))}}var parameterFromPropertyKey=applyToSelfOrLastLinkEncodingIdempotent((ast)=>{switch(ast._tag){default:return ast;case"Number":return ast.toCodecStringTree();case"Union":return ast.recur(parameterFromPropertyKey)}});var parameterFromString=applyToSelfOrLastLinkEncodingIdempotent((ast)=>{switch(ast._tag){default:return ast;case"Symbol":case"UniqueSymbol":return ast.toCodecStringTree();case"Union":return ast.recur(parameterFromString)}});var isStringFiniteRegExp=new globalThis.RegExp(`^${FINITE_PATTERN}$`);var isStringNumberRegExp=new globalThis.RegExp(`^(?:${FINITE_PATTERN}|Infinity|-Infinity|NaN)$`);function isStringFinite(annotations){return isPattern(isStringFiniteRegExp,{expected:"a string representing a finite number",representation:{id:"effect/schema/isStringFinite",payload:null},toJsonSchema:()=>({pattern:isStringFiniteRegExp.source}),...annotations})}var finiteString=appendChecks(string2,[isStringFinite()]);var finiteToString=new Link(finiteString,numberFromString);var numberToString=new Link(new Union([finiteString,nonFiniteLiterals]),numberFromString);var BIGINT_PATTERN="-?\\d+";var isStringBigIntRegExp=new globalThis.RegExp(`^${BIGINT_PATTERN}$`);var REGEXP_PATTERN="Symbol\\(([\\s\\S]*)\\)";var isStringSymbolRegExp=new globalThis.RegExp(`^${REGEXP_PATTERN}$`);function collectIssues(checks,value,issues,ast,options){for(let i=0;i<checks.length;i++){const check=checks[i];if(check._tag==="FilterGroup"){issues=collectIssues(check.checks,value,issues,ast,options);if(issues&&(options.errors!=="all"||issues[issues.length-1].filter.aborted)){return issues}}else{const issue=check.run(value,ast,options);if(issue){const filter=new Filter(check,issue,value,options);if(issues)issues.push(filter);else issues=[filter];if(options.errors!=="all"||check.aborted){return issues}}}}return issues}function getConstructorDescriptor(ast){if(!isDeclaration(ast))return;const getDescriptor=ast.annotations?.[CONSTRUCTOR_ANNOTATION_KEY];return isFunction(getDescriptor)?getDescriptor(ast.typeParameters):undefined}function isJsonLeaf(u){return u===null||typeof u==="string"||typeof u==="boolean"||typeof u==="number"&&globalThis.Number.isFinite(u)}function isStringTreeLeaf(u){return u===undefined||typeof u==="string"}function isTree(u,isLeaf){const cache=new WeakMap;const stack=[];outer:while(true){if(typeof u!=="object"||u===null){if(!isLeaf(u)){return false}}else{const value=u;const cached=cache.get(value);if(cached===false){return false}if(cached===undefined){const isArray=Array.isArray(value);if(!isArray){const prototype=Object.getPrototypeOf(value);if(prototype!==null&&prototype!==Object.prototype&&Object.getPrototypeOf(prototype)!==null){return false}}cache.set(value,false);stack.push({value,keys:isArray?value.length:Object.keys(value),index:0})}}while(stack.length>0){const frame=stack[stack.length-1];const keys=frame.keys;if(typeof keys==="number"){if(frame.index<keys){u=frame.value[frame.index++];continue outer}}else if(frame.index<keys.length){u=frame.value[keys[frame.index++]];continue outer}cache.set(frame.value,true);stack.pop()}return true}}function isJson(u){return isTree(u,isJsonLeaf)}var Json=new Declaration([],()=>(input,ast,options)=>isJson(input)?sameExit:fail6(new InvalidType(ast,input,options)),{representation:{id:"effect/schema/Json",payload:null},expected:"JSON value",toCodecJson:()=>{return},toCodecStringTree:()=>unknownToStringTree});function isStringTree(u){return isTree(u,isStringTreeLeaf)}var StringTree=new Declaration([],()=>(input,ast,options)=>isStringTree(input)?sameExit:fail6(new InvalidType(ast,input,options)),{expected:"StringTree",toCodecStringTree:()=>{return}});var unknownToStringTree=new Link(StringTree,passthrough2());var flatMapTransformation=(result,current,f)=>result===sameExit?f(current):flatMapEager2(result,f);function compileTransformation(transformation){if(transformation._tag==="Middleware"){return(result,current,options)=>{const transformed=result===sameExit?transformation.decode(succeed8(toOption(current)),options):transformation.decode(mapEager2(result,toOption),options);return fromOptionalEffect(transformed)}}const getter=transformation.decode;switch(getter._tag){case"Passthrough":return(result,current)=>result===sameExit?succeed8(current):result;case"Transform":{const transform=(value)=>value===missing?missingExit:succeed8(getter.transform(value));return(result,current)=>flatMapTransformation(result,current,transform)}case"TransformOptional":{const transform=(value)=>fromOptionExit(getter.transform(toOption(value)));return(result,current)=>flatMapTransformation(result,current,transform)}case"TransformEffect":return(result,current,options)=>flatMapTransformation(result,current,(value)=>value===missing?missingExit:getter.transform(value,options));case"TransformOptionalEffect":return(result,current,options)=>flatMapTransformation(result,current,(value)=>fromOptionalEffect(getter.transform(toOption(value),options)))}}var fromOptionalEffect=(effect)=>flatMapEager2(effect,fromOptionExit);var wrapEncoding=(ast,input,options,effect)=>catchCause2(effect,(cause)=>failCauseSync2(()=>map3(cause,(issue)=>new Encoding(ast,issue,input,options))));function makeConstructorParser(descriptor,compile){const transform=compileTransformation(descriptor.link.transformation);let sourceParser;return(input,options)=>{if(input===missing)return missingExit;if(descriptor.isConstructed(input))return sameExit;const result=(sourceParser??=compile(descriptor.link.to))(input,options);return transform(result,input,options)}}function withDefault(ast,parser){const defaultValue=ast.context.constructorDefault;return(input,options)=>{if(input!==missing&&input!==undefined)return parser(input,options);const result=defaultValue;if(effectIsExit(result)&&result._tag==="Success"){const local=parser(result[args],options);return local===sameExit?result:local}return flatMapEager2(wrapEncoding(ast,input,options,result),(value)=>{const local=parser(value,options);return local===sameExit?succeed8(value):local})}}function compileField(ast,compile){const parser=compile(ast);return ast.context?.constructorDefault===undefined?parser:withDefault(ast,parser)}function compile(ast,compile,compileField,base,specialize){if(ast._tag==="Declaration"){for(const parameter of ast.typeParameters)compile(parameter)}const descriptor=compileField?getConstructorDescriptor(ast):undefined;const parser=descriptor?makeConstructorParser(descriptor,compile):base??ast.getParser(compile,compileField);const checks=ast.checks;const links=ast.encoding;const transformations=links?.map((link)=>compileTransformation(link.transformation));const encodingChecks=ast.encodingChecks;if(!links&&!checks&&!encodingChecks){return parser}let encodingParsers;const parseChecks=(input,options)=>{let result=parser(input,options);if(encodingChecks&&!options.disableChecks){if(effectIsExit(result)){if(result._tag==="Success"){const output=result===sameExit?input:result[args];if(input!==missing&&output!==missing){const issues=collectIssues(encodingChecks,input,undefined,ast,options);if(issues){result=fail6(new Composite(ast,issues,input,options))}}}}else{result=flatMap3(result,(value)=>{if(input!==missing&&value!==missing){const issues=collectIssues(encodingChecks,input,undefined,ast,options);if(issues){return fail6(new Composite(ast,issues,input,options))}}return succeed6(value)})}}if(checks&&!options.disableChecks){if(effectIsExit(result)){if(result._tag==="Success"){const value=result===sameExit?input:result[args];if(value===missing)return result;const issues=collectIssues(checks,value,undefined,ast,options);if(issues){result=fail6(new Composite(ast,issues,value,options))}}}else{result=flatMap3(result,(value)=>{if(value!==missing){const issues=collectIssues(checks,value,undefined,ast,options);if(issues){return fail6(new Composite(ast,issues,value,options))}}return succeed6(value)})}}return result};const parseLocal=specialize===undefined?parseChecks:specialize(parseChecks);if(!links){return parseLocal}return(input,options)=>{const parsers=encodingParsers??=links.map((link)=>compile(link.to));let current=input;let result=parsers[parsers.length-1](input,options);for(let i=links.length-1;i>=0;i--){result=transformations[i](result,current,options);if(i!==0){const next=parsers[i-1];if(result._tag==="Success"){current=result[args];result=next(current,options)}else{result=flatMapEager2(result,(value)=>{const nextResult=next(value,options);return nextResult===sameExit?succeed8(value):nextResult})}}}if(result._tag==="Success"){const value=result[args];const local=parseLocal(value,options);return local===sameExit?result:local}result=wrapEncoding(ast,input,options,result);return flatMapEager2(result,(value)=>{const local=parseLocal(value,options);return local===sameExit?succeed8(value):local})}}var invalid3=Symbol();var cache=new WeakMap;var compiler;var compilerAdaptersEnabled=false;var decodeChild=(ast)=>compilerAdaptersEnabled?lazyParser(resolve4,ast,"parser"):resolve4(ast).parser;var makeChild=(ast)=>compilerAdaptersEnabled?lazyParser(resolve4,ast,"makeEffect"):resolve4(ast).makeEffect;var makeField=(ast)=>compileField(ast,makeChild);class InterpretedEntry{ast;constructor(ast){this.ast=ast}get decodeEffect(){return this.cachedDecodeEffect??=compile(this.ast,decodeChild)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=compile(this.ast,makeChild,makeField)}}class CompilerEntry extends InterpretedEntry{compiled;resolve;constructor(ast,compiled,resolve){super(ast);this.compiled=compiled;this.resolve=resolve}save(key,value){Object.defineProperty(this,key,{value});return value}operation(key){const compiled=this.compiled;return typeof compiled==="function"?compiled(this.ast,this.resolve,key):compiled?.[key]}get is(){return this.save("is",this.operation("is"))}get decode(){return this.save("decode",this.operation("decode"))}get make(){return this.save("make",this.operation("make"))}get decodeEffect(){return this.save("decodeEffect",this.operation("decodeEffect")??compile(this.ast,(ast)=>lazyParser(this.resolve,ast,"parser")))}get parser(){const decode=this.decode;return decode===undefined?this.decodeEffect:this.save("parser",withDecode(decode,()=>this.decodeEffect))}get makeEffect(){const makeEffect=this.operation("makeEffect");if(makeEffect!==undefined)return this.save("makeEffect",makeEffect);const child=(ast)=>lazyParser(this.resolve,ast,"makeEffect");return this.save("makeEffect",compile(this.ast,child,(ast)=>compileField(ast,child)))}}function withDecode(fastDecode,decodeEffect){let detailed;return(input,options)=>{if(input!==missing){try{const value=fastDecode(input,options);if(value!==invalid3)return value===input?sameExit:succeed8(value)}catch(error){return die3(error)}}return(detailed??=decodeEffect())(input,options)}}function lazyParser(resolve,ast,operation){const entry=resolve(ast);if(entry.compiled===undefined||Object.hasOwn(entry,operation)){return entry[operation]}let parser;return(input,options)=>(parser??=entry[operation])(input,options)}function resolve4(ast){const cached=cache.get(ast);if(cached!==undefined)return cached;const entry=compiler===undefined?new InterpretedEntry(ast):new CompilerEntry(ast,compiler(ast,resolve4),resolve4);cache.set(ast,entry);return entry}function makeEffect(schema){const ast=schema.ast;let parser;return(input,options)=>{return(parser??=runWithCompiler(constructorCompiler,toType(ast)))(input,options?.disableChecks?options?.parseOptions?{...options.parseOptions,disableChecks:true}:{disableChecks:true}:options?.parseOptions)}}function makeOption(schema){const parser=makeEffect(schema);return(input,options)=>{const exit=runSyncExit2(parser(input,options));if(isSuccess3(exit)){return some2(exit.value)}getSchemaIssueOrThrow(exit.cause,"Option adapter can only return none for schema issues");return none2()}}function make11(schema){return makeConstructorSync(toType(schema.ast))}function is(schema){return _is(schema.ast)}function makeIs(ast){if(!compilerAdaptersEnabled){const parser=asExit(run(ast));return(input)=>{const exit=parser(input,defaultParseOptions);if(isSuccess3(exit))return true;getSchemaIssueOrThrow(exit.cause,"Type guard adapter can only return false for schema issues");return false}}const entry=resolve4(ast);const guard=entry.is;if(guard!==undefined){return(input)=>{try{return guard(input,defaultParseOptions)}catch(error){getSchemaIssueOrThrow(die2(error),"Type guard adapter can only return false for schema issues");return false}}}const parser=entry.parser;return(input)=>{const exit=runSyncExit2(parserResult(parser(input,defaultParseOptions),input));if(isSuccess3(exit))return true;getSchemaIssueOrThrow(exit.cause,"Type guard adapter can only return false for schema issues");return false}}function _is(ast){const typeAST=toType(ast);let guard=(input)=>{guard=makeIs(typeAST);return guard(input)};return(input)=>{return guard(input)}}function decodeUnknownEffect(schema,options){const parser=run(schema.ast);return options===undefined?parser:(input,overrideOptions)=>parser(input,mergeParseOptions(options,overrideOptions))}function encodeUnknownEffect(schema,options){const parser=run(flip2(schema.ast));return options===undefined?parser:(input,overrideOptions)=>parser(input,mergeParseOptions(options,overrideOptions))}var mergeParseOptions=(options,overrideOptions)=>overrideOptions?{...options,...overrideOptions}:options;var getValue=(value)=>{if(value===missing){return fail6(new InvalidValue)}return succeed6(value)};function run(ast){return runWithCompiler(normalCompiler,ast)}function parserResult(result,input){if(result===sameExit){return succeed6(input)}if(!effectIsExit(result)){return flatMapEager2(result,getValue)}return result[args]===missing?getValue(missing):result}function runWithCompiler(compiler,ast){let parser;return(input,options)=>{const result=(parser??=compiler(ast))(input,options??defaultParseOptions);if(result===sameExit){return succeed6(input)}if(!effectIsExit(result)){return flatMapEager2(result,getValue)}return result[args]===missing?getValue(missing):result}}function asExit(parser){return(input,options)=>runSyncExit2(parser(input,options))}function runSync3(effect,message){const exit=runSyncExit2(effect);if(isSuccess3(exit)){return exit.value}const issue=getSchemaIssueOrThrow(exit.cause,message);throw new Error("Schema validation failed",{cause:issue})}function makeConstructorSync(ast){let entry;let parser;return(input,options)=>{entry??=resolve4(ast);const parseOptions=options?.disableChecks?options.parseOptions?{...options.parseOptions,disableChecks:true}:{disableChecks:true}:options?.parseOptions??defaultParseOptions;const make=entry.make;if(make!==undefined&&input!==missing){let output;try{output=make(input,parseOptions)}catch(error){getSchemaIssueOrThrow(die2(error),"Constructor adapter can only throw schema issues");throw error}if(output!==invalid3&&output!==missing)return output}const result=(parser??=entry.makeEffect)(input,parseOptions);return runSync3(parserResult(result,input),"Constructor adapter can only throw schema issues")}}var normalCompiler=(ast)=>resolve4(ast).parser;var constructorCompiler=(ast)=>resolve4(ast).makeEffect;var TypeId18="~effect/Schema/Schema";var RebuildOptions=Symbol();var SchemaProto={[TypeId18]:TypeId18,get make(){const value=make11(this);Object.defineProperty(this,"make",{value,enumerable:true});return value},get makeEffect(){const value=makeEffect(this);Object.defineProperty(this,"makeEffect",{value,enumerable:true});return value},get makeOption(){const value=makeOption(this);Object.defineProperty(this,"makeOption",{value,enumerable:true});return value},pipe(){return pipeArguments(this,arguments)},annotate(annotations){return this.rebuild(annotate(this.ast,annotations))},annotateKey(annotations){return this.rebuild(annotateKey(this.ast,annotations))},check(...checks){return this.rebuild(appendChecks(this.ast,checks))},rebuild(ast){return make12(ast,this[RebuildOptions])}};function make12(ast,options){function Schema(){}const self=Object.setPrototypeOf(Schema,SchemaProto);if(options&&(Object.hasOwn(options,"name")||Object.hasOwn(options,"length")||Object.hasOwn(options,"__proto__"))){Object.defineProperties(self,Object.getOwnPropertyDescriptors({...options}))}else{Object.assign(self,options)}self[RebuildOptions]=options;self.ast=ast;return self}function withoutConstructorDefault(context){return context.constructorDefault===undefined?context:new Context(context.isOptional,context.isMutable,undefined,context.annotations)}function validateCanonicalObjectPropertyNames(ast){if(ast.propertySignatures.some((ps)=>typeof ps.name!=="string")){throw new globalThis.Error("Objects property names must be strings",{cause:ast})}}function makeReorder(getPriority){return(types)=>{const sortedTypes=[...types].sort((a,b)=>getPriority(toEncoded(a))-getPriority(toEncoded(b)));const orderChanged=sortedTypes.some((ast,index)=>ast!==types[index]);if(!orderChanged)return types;return sortedTypes}}function toCodecStringTree(schema){return make12(toCodecStringTreeAST(schema.ast),{schema})}var toStringTreeReorder=makeReorder((ast)=>{switch(ast._tag){case"Null":case"Boolean":case"Number":case"BigInt":case"Symbol":case"UniqueSymbol":return 0;default:return 1}});function toCodecStringTreeASTStep(ast,recur,onMissingAnnotation){switch(ast._tag){case"Declaration":{const typeParameters=ast.typeParameters.map((tp)=>make12(recur(toEncoded(tp))));const getStringTreeLink=ast.annotations?.toCodecStringTree;if(isFunction(getStringTreeLink)){const link=getStringTreeLink(typeParameters);if(link===undefined)return ast;return replaceEncoding(ast,[mapLink(link,recur)])}const getJsonLink=ast.annotations?.toCodecJson;const jsonLink=isFunction(getJsonLink)?getJsonLink(typeParameters):undefined;const getLink=jsonLink===undefined?ast.annotations?.toCodec:undefined;const link=jsonLink??(isFunction(getLink)?getLink(typeParameters):undefined);return link===undefined?onMissingAnnotation(ast):replaceEncoding(ast,[mapLink(link,recur)])}case"Null":return replaceEncoding(ast,[nullToString]);case"Boolean":return replaceEncoding(ast,[booleanToString]);case"Unknown":case"ObjectKeyword":return replaceEncoding(ast,[unknownToStringTree]);case"Enum":case"Number":case"Literal":case"UniqueSymbol":case"Symbol":case"BigInt":return ast.toCodecStringTree();case"Objects":{validateCanonicalObjectPropertyNames(ast);return ast.recur(recur,parameterFromString)}case"Union":{const sortedTypes=toStringTreeReorder(ast.types);if(sortedTypes!==ast.types){return new Union(sortedTypes,ast.options,ast.annotations,ast.checks,ast.encoding,ast.context,ast.encodingChecks).recur(recur)}return ast.recur(recur)}case"Arrays":case"Suspend":return ast.recur(recur)}return ast}var nullToString=new Link(new Literal("null"),new Transformation(transform(()=>null),transform(()=>"null")));var booleanToString=new Link(new Union([new Literal("true"),new Literal("false")]),new Transformation(transform((s)=>s==="true"),String2()));var arrayFromSingleTransformation=new Transformation(transform((input)=>typeof input==="string"?[input]:input),passthrough());var isCodecArrayFromSingleLink=(link)=>link.transformation===arrayFromSingleTransformation;var toCodecStringTreeAST=applyToSelfOrLastLinkEncodingIdempotent((ast)=>{const out=toCodecStringTreeASTStep(ast,toCodecStringTreeAST,(ast)=>{throw new globalThis.Error("Missing structural codec for StringTree",{cause:ast})});if(out!==ast&&ast.context!==undefined){return replaceContextLastLink(out,withoutConstructorDefault(ast.context))}return out},{stopAt:isCodecArrayFromSingleLink});var lambda=(f)=>f;var SchemaErrorTypeId="~effect/Schema/SchemaError";function isSchemaError(u){return hasProperty(u,SchemaErrorTypeId)&&u[SchemaErrorTypeId]===SchemaErrorTypeId}var TypeId19=TypeId18;function declareConstructor(){return(typeParameters,run,annotations)=>{return make13(new Declaration(typeParameters.map(getAST),(typeParameters)=>run(typeParameters.map((ast)=>make13(ast))),annotations))}}function declare(is,annotations){return declareConstructor()([],()=>(input,ast,options)=>is(input)?succeed6(input):fail6(new InvalidType(ast,input,options)),annotations)}class SchemaError extends TaggedError2("SchemaError"){[SchemaErrorTypeId]=SchemaErrorTypeId;constructor(issue){const stackTraceLimit=getStackTraceLimit();setStackTraceLimit(0);try{super({issue})}finally{setStackTraceLimit(stackTraceLimit)}}get message(){return defaultFormatter(this.issue)}toString(){return`SchemaError(${this.message})`}}function isSchemaError2(u){return isSchemaError(u)}function fromIssueEffect(self){if(effectIsExit(self)){return fromIssueExit(self)}return catchCause2(self,(cause)=>failCauseSync2(()=>map3(cause,(issue)=>new SchemaError(issue))))}function fromIssueExit(exit){return isSuccess3(exit)?exit:failCause2(map3(exit.cause,(issue)=>new SchemaError(issue)))}function getSchemaErrorOrThrow(cause,message){let schemaError;for(const reason of cause.reasons){if(!isFailReason2(reason)||!isSchemaError2(reason.error)){throw new globalThis.Error(message,{cause})}schemaError??=reason.error}if(schemaError===undefined){throw new globalThis.Error(message,{cause})}return schemaError}function runSchemaErrorPromise(self){return runPromiseExit2(self).then((exit)=>{if(isSuccess3(exit)){return exit.value}throw getSchemaErrorOrThrow(exit.cause,"Promise adapter can only reject schema errors")})}function runSchemaErrorSync(self){const exit=runSyncExit2(self);if(isSuccess3(exit)){return exit.value}throw getSchemaErrorOrThrow(exit.cause,"Sync adapter can only throw schema errors")}var is2=is;function decodeUnknownEffect2(schema,options){const parser=decodeUnknownEffect(schema,options);return(input,options)=>{return fromIssueEffect(parser(input,options))}}function decodeUnknownPromise(schema,options){const parser=decodeUnknownEffect2(schema,options);return(input,options)=>{return runSchemaErrorPromise(parser(input,options))}}var decodePromise=decodeUnknownPromise;function decodeUnknownSync(schema,options){const parser=decodeUnknownEffect2(schema,options);return(input,options)=>{return runSchemaErrorSync(parser(input,options))}}var decodeSync=decodeUnknownSync;function encodeUnknownEffect2(schema,options){const parser=encodeUnknownEffect(schema,options);return(input,options)=>{return fromIssueEffect(parser(input,options))}}var encodeEffect=encodeUnknownEffect2;function encodeUnknownSync(schema,options){const parser=encodeUnknownEffect2(schema,options);return(input,options)=>{return runSchemaErrorSync(parser(input,options))}}var encodeSync=encodeUnknownSync;var make13=make12;function isSchema(u){return hasProperty(u,TypeId19)&&u[TypeId19]===TypeId19}var optionalKey2=lambda((schema)=>make13(optionalKey(schema.ast),{schema}));var optional2=lambda((self)=>{const schema=UndefinedOr(self);return make13(optional(self.ast),{schema})});function Literal2(literal){const out=make13(new Literal(literal),{literal,transform(to){return out.pipe(decodeTo2(Literal2(to),{decode:transform(()=>to),encode:transform(()=>literal)}))}});return out}var Unknown2=make13(unknown);var Undefined2=make13(undefined_2);var String4=make13(string2);var Number5=make13(number2);var Boolean3=make13(boolean);function makeStruct(ast,fields){return make13(ast,{fields,mapFields(f,options){const fields=f(this.fields);return makeStruct(struct(fields,options?.unsafePreserveChecks?this.ast.checks:undefined),fields)}})}function Struct(fields){return makeStruct(struct(fields,undefined),fields)}function Record(key,value){return make13(record(key.ast,value.ast),{key,value})}function makeTuple(ast,elements){return make13(ast,{elements,mapElements(f,options){const elements=f(this.elements);return makeTuple(tuple(elements,options?.unsafePreserveChecks?this.ast.checks:undefined),elements)}})}function Tuple(elements){return makeTuple(tuple(elements),elements)}var ArraySchema=lambda((schema)=>make13(new Arrays(false,[],[schema.ast]),{value:schema}));function makeUnion(ast,members){return make13(ast,{members,mapMembers(f,options){const members=f(this.members);return makeUnion(union(members,this.ast.options,options?.unsafePreserveChecks?this.ast.checks:undefined),members)}})}function Union2(members,options){return makeUnion(union(members,options,undefined),members)}function Literals(literals){const members=literals.map(Literal2);return make13(union(members,undefined,undefined),{literals,members,mapMembers(f){return Union2(f(this.members))},pick(literals){return Literals(literals)},transform(to){return Union2(members.map((member,index)=>member.transform(to[index])))}})}var UndefinedOr=lambda((self)=>Union2([self,Undefined2]));function decodeTo2(to,transformation){return(from)=>{return make13(decodeTo(from.ast,to.ast,transformation?makeTransformation(transformation):passthrough2()),{from,to})}}function withConstructorDefault2(defaultValue){return(schema)=>make13(withConstructorDefault(schema.ast,defaultValue),{schema})}function tag(literal){return Literal2(literal).pipe(withConstructorDefault2(succeed6(literal)))}function TaggedStruct(value,fields){return Struct({_tag:tag(value),...fields})}function instanceOf(constructor,annotations){return declare((u)=>u instanceof constructor,annotations)}function link3(){return(encodeTo,transformation)=>{return new Link(encodeTo.ast,makeTransformation(transformation))}}var makeFilter2=makeFilter;function isPattern2(regExp,annotations){const source=regExp.source;const flags=regExp.flags;const canExport=/^[dg]*uy?$/.test(flags);const runtimeRegExp=flags===""?`new RegExp(${format(source)})`:`new RegExp(${format(source)}, ${format(flags)})`;return isPattern(regExp,{toJsonSchema:()=>canExport?{pattern:flags.endsWith("y")?`^(?:${source})`:source}:[{},true],toCode:()=>({runtime:`Schema.isPattern(${runtimeRegExp})`}),...annotations})}function isBase64(annotations){const regExp=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;return isPattern2(regExp,{expected:"a base64 encoded string",representation:{id:"effect/schema/isBase64",payload:null},toJsonSchema:()=>({pattern:regExp.source}),toCode:()=>({runtime:"Schema.isBase64()"}),...annotations})}var Finite=make13(finite);function isInt(annotations){return makeFilter2((n)=>globalThis.Number.isSafeInteger(n),{expected:"an integer",representation:{id:"effect/schema/isInt",payload:null},toJsonSchema:()=>[{type:"integer"},true],toCode:()=>({runtime:"Schema.isInt()"}),arbitraryConstraint:{number:"integer"},...annotations})}var Int=Number5.check(isInt());function isMinLength(minLength,annotations){minLength=normalizeCardinality(minLength);return makeIsMinLength(minLength,Math.ceil(minLength/2),annotations)}function makeIsMinLength(minLength,minCodePoints,annotations){return makeFilter2((input)=>input.length>=minLength,{expected:`a value with a length of at least ${minLength}`,representation:{id:"effect/schema/isMinLength",payload:{minLength}},toJsonSchema:({type})=>type==="string"?minLength<=1?{minLength:minCodePoints}:[{minLength:minCodePoints},true]:type==="array"?{minItems:minLength}:type===undefined?[{minLength:minCodePoints,minItems:minLength},true]:[{},true],toCode:()=>({runtime:`Schema.isMinLength(${minLength})`}),[STRUCTURAL_ANNOTATION_KEY]:true,arbitraryConstraint:{minLength},...annotations})}function normalizeCardinality(value){if(!globalThis.Number.isFinite(value)){throw new globalThis.RangeError(`Expected a finite number, got ${value}`)}return Math.max(0,Math.floor(value))}var RegExp2=instanceOf(globalThis.RegExp,{representation:{id:"effect/schema/RegExp",payload:null},toCode:()=>({runtime:`Schema.RegExp`,Type:`globalThis.RegExp`}),expected:"RegExp",toCodecJson:()=>link3()(Struct({source:String4,flags:String4}),transformEffect2({decode:(e,options)=>try_2({try:()=>new globalThis.RegExp(e.source,e.flags),catch:()=>new InvalidValue({expected:"valid RegExp source and flags"},e,options)}),encode:(regExp)=>succeed6({source:regExp.source,flags:regExp.flags})}))});var URLString=String4.annotate({expected:"a string that will be decoded as a URL"});var URL2=instanceOf(globalThis.URL,{representation:{id:"effect/schema/URL",payload:null},toCode:()=>({runtime:`Schema.URL`,Type:`globalThis.URL`}),expected:"URL",toCodecJson:()=>link3()(URLString,urlFromString)});var JsonString=String4.annotate({expected:"a string that will be decoded as JSON",contentMediaType:"application/json"});function fromJsonString2(schema,options){return JsonString.pipe(decodeTo2(schema,fromJsonString(options)))}var File=instanceOf(globalThis.File,{representation:{id:"effect/schema/File",payload:null},toCode:()=>({runtime:`Schema.File`,Type:`globalThis.File`}),expected:"File",toCodecJson:()=>link3()(Struct({data:String4.check(isBase64()),type:String4,name:String4,lastModified:Int}),transformEffect2({decode:(e,options)=>match2(decode(e.data),{onFailure:()=>fail6(new InvalidValue({expected:"a valid Base64 string"},e.data,options)),onSuccess:(bytes)=>{const buffer=new globalThis.Uint8Array(bytes);return succeed6(new globalThis.File([buffer],e.name,{type:e.type,lastModified:e.lastModified}))}}),encode:(file,options)=>tryPromise2({try:async()=>{const bytes=new globalThis.Uint8Array(await file.arrayBuffer());return{data:encode(bytes),type:file.type,name:file.name,lastModified:file.lastModified}},catch:()=>new InvalidValue({expected:"a readable File"},file,options)})}))});var FormData2=instanceOf(globalThis.FormData,{representation:{id:"effect/schema/FormData",payload:null},toCode:()=>({runtime:`Schema.FormData`,Type:`globalThis.FormData`}),expected:"FormData",toCodecJson:()=>link3()(ArraySchema(Tuple([String4,Union2([Struct({_tag:tag("String"),value:String4}),Struct({_tag:tag("File"),value:File})])])),transformEffect2({decode:(e)=>{const out=new globalThis.FormData;for(const[key,entry]of e){out.append(key,entry.value)}return succeed6(out)},encode:(formData)=>{return succeed6(globalThis.Array.from(formData.entries()).map(([key,value])=>{if(typeof value==="string"){return[key,{_tag:"String",value}]}else{return[key,{_tag:"File",value}]}}))}}))});var URLSearchParams2=instanceOf(globalThis.URLSearchParams,{representation:{id:"effect/schema/URLSearchParams",payload:null},toCode:()=>({runtime:`Schema.URLSearchParams`,Type:`globalThis.URLSearchParams`}),expected:"URLSearchParams",toCodecJson:()=>link3()(String4.annotate({expected:"a query string that will be decoded as URLSearchParams"}),transform2({decode:(e)=>new globalThis.URLSearchParams(e),encode:(params)=>params.toString()}))});var Base64String=String4.annotate({expected:"a base64 encoded string that will be decoded as Uint8Array",format:"byte",contentEncoding:"base64"});var Uint8Array2=instanceOf(globalThis.Uint8Array,{representation:{id:"effect/schema/Uint8Array",payload:null},toCode:()=>({runtime:`Schema.Uint8Array`,Type:`globalThis.Uint8Array`}),expected:"Uint8Array",toCodecJson:()=>link3()(Base64String,uint8ArrayFromBase64String)});var arbitraryMinimumDateTimestamp=-8640000000000000;var arbitraryMaximumDateTimestamp=8640000000000000;var arbitraryMinimumZonedDateTimeTimestamp=arbitraryMinimumDateTimestamp+14*60*60*1000;var arbitraryMaximumZonedDateTimeTimestamp=arbitraryMaximumDateTimestamp-14*60*60*1000;var arbitraryMinimumTimeZoneOffset=-12*60*60*1000;var arbitraryMaximumTimeZoneOffset=14*60*60*1000;function Redacted(value,options){const label=typeof options?.label==="string"?options.label:undefined;const disallowJsonEncode=options?.disallowJsonEncode===true;const normalizedOptions=label!==undefined?disallowJsonEncode?{label,disallowJsonEncode:true}:{label}:disallowJsonEncode?{disallowJsonEncode:true}:undefined;const decodeLabel=label!==undefined?decodeUnknownEffect(Literal2(label)):undefined;const schema=declareConstructor()([value],([value])=>(input,ast,poptions)=>{if(isRedacted(input)){const label=decodeLabel!==undefined?mapErrorEager2(decodeLabel(input.label,poptions),(issue)=>new Pointer(["label"],issue)):void_3;return flatMapEager2(label,()=>mapBothEager2(decodeUnknownEffect(value)(value2(input),poptions),{onSuccess:(value)=>make10(value,{label:input.label}),onFailure:()=>{return new Composite(ast,[new Pointer(["value"],new InvalidValue(undefined,input,poptions))],input,poptions)}}))}return fail6(new InvalidType(ast,input,poptions))},{representation:{id:"effect/schema/Redacted",payload:normalizedOptions??null},toCode:({typeParameters})=>({runtime:normalizedOptions!==undefined?`Schema.Redacted(${typeParameters[0].runtime}, ${format(normalizedOptions)})`:`Schema.Redacted(${typeParameters[0].runtime})`,Type:`Redacted.Redacted<${typeParameters[0].Type}>`,importDeclarations:[`import * as Redacted from "effect/Redacted"`]}),expected:"Redacted",toCodecJson:([value])=>link3()(value,{decode:transform((e)=>make10(e,{label})),encode:disallowJsonEncode?forbidden((oe)=>"Cannot serialize Redacted"+(isSome2(oe)&&typeof oe.value.label==="string"?` with label: "${oe.value.label}"`:"")):transform(value2)}),toEquivalence:([value])=>makeEquivalence(value)});return make13(schema.ast,{value})}var immerable=globalThis.Symbol.for("immer-draftable");var payloadToken={};function makeClass(Inherited,identifier,struct2,annotations,proto){const getClassSchema=getClassSchemaFactory(struct2,identifier,annotations);const ClassTypeId=getClassTypeId(identifier);const out=class extends Inherited{constructor(...[input,options]){const internalOptions=options;const payload=internalOptions?.["~payload"];const value=payload?.token===payloadToken?payload.value:struct2.make(input??{},options);super(value,{...options,disableChecks:true,"~payload":{token:payloadToken,value}})}static[TypeId19]=TypeId19;get[ClassTypeId](){return ClassTypeId}static[immerable]=true;static identifier=identifier;static fields=struct2.fields;static get ast(){return getClassSchema(this).ast}static pipe(){return pipeArguments(this,arguments)}static rebuild(ast){return getClassSchema(this).rebuild(ast)}static make(input,options){return make11(getClassSchema(this))(input??{},options)}static makeOption(input,options){return makeOption(getClassSchema(this))(input??{},options)}static makeEffect(input,options){return getClassSchema(this).makeEffect(input??{},options)}static annotate(annotations){return this.rebuild(annotate(this.ast,annotations))}static annotateKey(annotations){return this.rebuild(annotateKey(this.ast,annotations))}static check(...checks){return this.rebuild(appendChecks(this.ast,checks))}static extend(identifier2){return(schema,annotations)=>{const extension=isStruct(schema)?schema:Struct(schema);const fields={...struct2.fields,...extension.fields};const ast=struct(fields,struct2.ast.checks,{identifier:identifier2});return makeClass(this,identifier2,makeStruct(appendChecks(ast,extension.ast.checks),fields),annotations,proto)}}static mapFields(f,options){return struct2.mapFields(f,options)}};if(proto!==undefined){Object.assign(out.prototype,proto(identifier))}return out}function getClassTransformation(self){return new Transformation(transform((input)=>new self(input,{"~payload":{token:payloadToken,value:input}})),passthrough())}function getClassTypeId(identifier){return`~effect/Schema/Class/${identifier}`}function getClassSchemaFactory(from,identifier,annotations){let memo;return(self)=>{if(memo!==undefined){return memo}const ClassTypeId=getClassTypeId(identifier);const isClassValue=(input)=>input instanceof self||hasProperty(input,ClassTypeId);const transformation=getClassTransformation(self);const to=make13(new Declaration([from.ast],()=>(input,ast,options)=>{return isClassValue(input)?succeed6(input):fail6(new InvalidType(ast,input,options))},{identifier,[CONSTRUCTOR_ANNOTATION_KEY]:([from])=>({isConstructed:isClassValue,link:new Link(from,transformation)}),toCodec:([from])=>new Link(from.ast,transformation),toEquivalence:([from])=>from,toFormatter:([from])=>(t)=>`${self.identifier}(${from(t)})`,[SENTINELS_ANNOTATION_KEY]:collectSentinels(from.ast),...annotations}));return memo=decodeTo2(to,transformation)(from)}}function isStruct(schema){return isSchema(schema)}var Error4=(identifier)=>(schema,annotations)=>{const struct=isStruct(schema)?schema:Struct(schema);const self=makeClass(Error2,identifier,struct,annotations,(identifier)=>({name:identifier}));return self};var TaggedError3=(identifier)=>{return(tagValue,schema,annotations)=>{const struct=isStruct(schema)?schema.mapFields((fields)=>({_tag:tag(tagValue),...fields}),{unsafePreserveChecks:true}):TaggedStruct(tagValue,schema);return Error4(identifier??tagValue)(struct,annotations)}};var toCodecStringTree2=toCodecStringTree;var Json2=make13(annotate(Json,{toCode:()=>({runtime:"Schema.Json",Type:"Schema.Json"})}));var JsonObject=Record(String4,Json2);import{chmodSync as chmodSync2,existsSync as existsSync10,readFileSync as readFileSync8,realpathSync as realpathSync5,renameSync as renameSync2,statSync as statSync3,writeFileSync as writeFileSync6}from"fs";import{hostname}from"os";import{pathToFileURL as pathToFileURL5}from"url";var name="@collective-intelligence/cli";var version="0.1.6";var jsonBodySerializer={bodySerializer:(body)=>JSON.stringify(body,(_key,value)=>typeof value==="bigint"?value.toString():value)};function createSseClient({onRequest,onSseError,onSseEvent,responseTransformer,responseValidator,sseDefaultRetryDelay,sseMaxRetryAttempts,sseMaxRetryDelay,sseSleepFn,url,...options}){let lastEventId;const sleep=sseSleepFn??((ms)=>new Promise((resolve)=>setTimeout(resolve,ms)));const createStream=async function*(){let retryDelay=sseDefaultRetryDelay??3000;let attempt=0;const signal=options.signal??new AbortController().signal;while(true){if(signal.aborted)break;attempt++;const headers=options.headers instanceof Headers?options.headers:new Headers(options.headers);if(lastEventId!==undefined){headers.set("Last-Event-ID",lastEventId)}try{const requestInit={redirect:"follow",...options,body:options.serializedBody??null,headers,signal};let request=new Request(url,requestInit);if(onRequest){request=await onRequest(url,requestInit)}const _fetch=options.fetch??globalThis.fetch;const response=await _fetch(request);if(!response.ok)throw new Error(`SSE failed: ${response.status} ${response.statusText}`);if(!response.body)throw new Error("No body in SSE response");const reader=response.body.pipeThrough(new TextDecoderStream).getReader();let buffer="";const abortHandler=()=>{try{reader.cancel()}catch{}};signal.addEventListener("abort",abortHandler);try{while(true){const{done,value}=await reader.read();if(done)break;buffer+=value;buffer=buffer.replace(/\r\n?/g,`
|
|
239
|
+
at ${path}`:message}function findMessage(issue){if(issue._tag==="Pointer")return;if(issue._tag==="Encoding")return findMessage(issue.issue);const annotations=issue._tag==="Filter"?issue.filter.annotations:("annotations"in issue)?issue.annotations:issue.ast.annotations;const message=annotations?.[issue._tag==="MissingKey"?"messageMissingKey":issue._tag==="UnexpectedKey"?"messageUnexpectedKey":"message"];if(typeof message==="string")return message}function getSchemaIssue(cause){let issue;for(const reason of cause.reasons){if(!isFailReason2(reason)||!isIssue(reason.error)){return}issue??=reason.error}return issue}function getSchemaIssueOrThrow(cause,message){const issue=getSchemaIssue(cause);if(issue===undefined){throw new Error(message,{cause})}return issue}var makeGetter=(fields)=>Object.assign(Object.create(Prototype),fields);function fail10(f){return transformOptionalEffect((oe,options)=>fail6(f(oe,options)))}function forbidden(message){return fail10((oe,options)=>{const annotations={message:message(oe)};return isSome2(oe)?new Forbidden(annotations,oe.value,options):new Forbidden(annotations)})}var passthrough_=makeGetter({_tag:"Passthrough"});function passthrough(){return passthrough_}function transform(f){return makeGetter({_tag:"Transform",transform:f})}function transformEffect(f){return makeGetter({_tag:"TransformEffect",transform:f})}function transformOptionalEffect(f){return makeGetter({_tag:"TransformOptionalEffect",transform:f})}function String2(){return transform(globalThis.String)}function Number3(){return transform(globalThis.Number)}function parseJson(options){return transformEffect((input,parseOptions)=>try_2({try:()=>JSON.parse(input,options?.reviver),catch:()=>new InvalidValue({expected:"a valid JSON string"},input,parseOptions)}))}function stringifyJson(options){return transformEffect((input,parseOptions)=>try_2({try:()=>{const output=JSON.stringify(input,options?.replacer,options?.space);if(output===undefined){throw new TypeError("Value cannot be represented as JSON")}return output},catch:()=>new InvalidValue({expected:"a JSON-serializable value"},input,parseOptions)}))}function encodeBase64(){return transform(encode)}function decodeBase64(){return transformEffect((input,options)=>mapErrorEager2(fromResult2(decode(input)),()=>new InvalidValue({expected:"a valid Base64 string"},input,options)))}var TypeId16="~effect/SchemaTransformation/Transformation";var Transformation=class extends Class{[TypeId16]=TypeId16;_tag="Transformation";decode;encode;constructor(decode,encode){super();this.decode=decode;this.encode=encode}flip(){return new Transformation(this.encode,this.decode)}};function isTransformation(u){return hasProperty(u,TypeId16)&&u[TypeId16]===TypeId16}var makeTransformation=(options)=>{if(isTransformation(options)){return options}return new Transformation(options.decode,options.encode)};function transformEffect2(options){return new Transformation(transformEffect(options.decode),transformEffect(options.encode))}function transform2(options){return new Transformation(transform(options.decode),transform(options.encode))}var passthrough_2=new Transformation(passthrough(),passthrough());function passthrough2(){return passthrough_2}var numberFromString=new Transformation(Number3(),String2());var urlFromString=transformEffect2({decode:(s,options)=>URL.canParse(s)?succeed6(new URL(s)):fail6(new InvalidValue({expected:"a valid URL string"},s,options)),encode:(url)=>succeed6(url.href)});var uint8ArrayFromBase64String=new Transformation(decodeBase64(),encodeBase64());function fromJsonString(options){return new Transformation(parseJson(options??{}),stringifyJson(options))}function makeGuard(tag){return(ast)=>ast._tag===tag}var isDeclaration=makeGuard("Declaration");var isNever2=makeGuard("Never");var isLiteral=makeGuard("Literal");var isUniqueSymbol=makeGuard("UniqueSymbol");var isArrays=makeGuard("Arrays");var isObjects=makeGuard("Objects");var isSuspend=makeGuard("Suspend");var Link=class{to;transformation;constructor(to,transformation){this.to=to;this.transformation=transformation}};var defaultParseOptions={};var Context=class{isOptional;isMutable;constructorDefault;annotations;constructor(isOptional,isMutable,constructorDefault=undefined,annotations=undefined){this.isOptional=isOptional;this.isMutable=isMutable;this.constructorDefault=constructorDefault;this.annotations=annotations}};var TypeId17="~effect/Schema";class ASTNodeImpl{[TypeId17]=TypeId17;annotations;checks;encoding;context;constructor(annotations=undefined,checks=undefined,encoding=undefined,context=undefined){this.annotations=annotations;this.checks=checks;this.encoding=encoding;this.context=context}toString(){return`<${this._tag}>`}}var Declaration=class extends ASTNodeImpl{_tag="Declaration";typeParameters;run;encodingChecks;encodingRun;constructor(typeParameters,run,annotations,checks,encoding,context,encodingChecks,encodingRun){super(annotations,checks,encoding,context);this.typeParameters=typeParameters;this.run=run;this.encodingChecks=encodingChecks;this.encodingRun=encodingRun}getParser(){let run;return(input,options)=>{if(input===missing)return missingExit;return(run??=this.run(this.typeParameters))(input,this,options)}}_rebuild(recur,checks,encodingChecks,run,encodingRun){const tps=mapOrSame(this.typeParameters,recur);return tps===this.typeParameters&&checks===this.checks&&encodingChecks===this.encodingChecks&&run===this.run&&encodingRun===this.encodingRun?this:new Declaration(tps,run,this.annotations,checks,undefined,this.context,encodingChecks,encodingRun)}recur(recur){return this._rebuild(recur,this.checks,this.encodingChecks,this.run,this.encodingRun)}flip(recur){return this._rebuild(recur,this.encodingChecks,this.checks,this.encodingRun??this.run,this.run)}getExpected(){const expected=this.annotations?.expected;if(typeof expected==="string")return expected;return"<Declaration>"}};var Null=class extends ASTNodeImpl{_tag="Null";getParser(){return fromConst(this,null)}getExpected(){return"null"}};var null_=new Null;var Undefined=class extends ASTNodeImpl{_tag="Undefined";getParser(){return fromConst(this,undefined)}toCodecJson(){return replaceEncoding(this,[undefinedToNull])}getExpected(){return"undefined"}};var undefinedToNull=new Link(null_,new Transformation(transform(()=>{return}),transform(()=>null)));var undefined_2=new Undefined;var Unknown=class extends ASTNodeImpl{_tag="Unknown";getParser(){return fromRefinement(this,isUnknown)}getExpected(){return"unknown"}};var unknown=new Unknown;var Literal=class extends ASTNodeImpl{_tag="Literal";literal;constructor(literal,annotations,checks,encoding,context){super(annotations,checks,encoding,context);if(typeof literal==="number"&&!globalThis.Number.isFinite(literal)){throw new Error(`A numeric literal must be finite, got ${format(literal)}`)}this.literal=literal}getParser(){return fromConst(this,this.literal)}matchPart(s,_options){return s===globalThis.String(this.literal)?this.literal:undefined}toCodecJson(){return typeof this.literal==="bigint"?literalToString(this):this}toCodecStringTree(){return typeof this.literal==="string"?this:literalToString(this)}getExpected(){return typeof this.literal==="string"?JSON.stringify(this.literal):globalThis.String(this.literal)}};function literalToString(ast){const literalAsString=globalThis.String(ast.literal);return replaceEncoding(ast,[new Link(new Literal(literalAsString),new Transformation(transform(()=>ast.literal),transform(()=>literalAsString)))])}var String3=class extends ASTNodeImpl{_tag="String";getParser(){return fromRefinement(this,isString)}matchPart(s,options){const checks=this.checks;return checks&&!options.disableChecks&&collectIssues(checks,s,undefined,this,options)?undefined:s}getExpected(){return"string"}};var string2=new String3;var Number4=class extends ASTNodeImpl{_tag="Number";getParser(){return fromRefinement(this,isNumber)}matchKey(s,options){return this._match(isStringNumberRegExp,s,options)}matchPart(s,options){return this._match(isStringFiniteRegExp,s,options)}_match(regexp,s,options){if(!regexp.test(s))return;const value=globalThis.Number(s);if(options.disableChecks||!this.checks)return value;return collectIssues(this.checks,value,undefined,this,options)?undefined:value}toCodecJson(){if(this.checks&&(hasCheck(this.checks,"effect/schema/isFinite")||hasCheck(this.checks,"effect/schema/isInt"))){return this}return replaceEncoding(this,[numberToJson])}toCodecStringTree(){if(this.toCodecJson()===this){return replaceEncoding(this,[finiteToString])}return replaceEncoding(this,[numberToString])}getExpected(){return"number"}};function hasCheck(checks,id){return checks.some((check)=>check.annotations?.representation?.id===id||check._tag==="FilterGroup"&&hasCheck(check.checks,id))}var number2=new Number4;var Boolean2=class extends ASTNodeImpl{_tag="Boolean";getParser(){return fromRefinement(this,isBoolean)}getExpected(){return"boolean"}};var boolean=new Boolean2;var Arrays=class extends ASTNodeImpl{_tag="Arrays";isMutable;elements;rest;encodingChecks;constructor(isMutable,elements,rest,annotations,checks,encoding,context,encodingChecks){super(annotations,checks,encoding,context);this.isMutable=isMutable;this.elements=elements;this.rest=rest;this.encodingChecks=encodingChecks;let hasOptional=false;for(let i=0;i<elements.length;i++){if(isOptional(elements[i])){hasOptional=true}else if(hasOptional){throw new Error("A required element cannot follow an optional element. ts(1257)")}}if(hasOptional&&rest.length>1){throw new Error("A required element cannot follow an optional element. ts(1257)")}for(let i=1;i<rest.length;i++){if(isOptional(rest[i])){throw new Error("An optional element cannot follow a rest element. ts(1266)")}}}getParser(compile,compileField=compile){const ast=this;let elements;let rest;const elementLen=ast.elements.length;const tailLen=Math.max(0,ast.rest.length-1);function getParser(tailThreshold,index){if(index<elementLen){return elements[index]}else if(index>=tailThreshold){return rest[index-tailThreshold+1]}return rest[0]}const finish=(state)=>{const{input,len,options}=state;if(ast.rest.length===0&&len>elementLen){for(let i=elementLen;i<len;i++){const unexpected=new UnexpectedKey(ast,input[i],options);const issue=new Pointer([i],unexpected);if(options.errors==="all"){if(state.issues)state.issues.push(issue);else state.issues=[issue]}else{return fail6(new Composite(ast,[issue],input,options))}}}if(state.issues){return fail6(new Composite(ast,state.issues,input,options))}return succeed8(state.output)};const parse=(input,options)=>{const len=input.length;const state={ast,getParser,input,len,tailThreshold:Math.max(elementLen,len-tailLen),output:new globalThis.Array(len),issues:undefined,options};const end=ast.rest.length===0?elementLen:Math.max(len,elementLen+tailLen);const concurrency=options.concurrency===undefined?1:resolveConcurrency(options.concurrency);const eff=concurrency===1?parseArray(state,input,0,end):parseArrayConcurrent(state,input,{concurrency,end});if(!eff)return finish(state);if(effectIsExit(eff))return flatMapEager2(eff,()=>finish(state));let first=true;return suspend2(()=>{if(!first)return parse(input,options);first=false;return flatMap3(eff,()=>finish(state))})};return(input,options)=>{if(input===missing)return missingExit;try{if(!Array.isArray(input)){return fail6(new InvalidType(ast,input,options))}if(!elements){elements=ast.elements.map((ast)=>({ast,parser:compileField(ast)}));rest=ast.rest.map((ast)=>({ast,parser:compileField(ast)}))}return parse(input,options)}catch(error){return die3(error)}}}_rebuild(recur,checks,encodingChecks){const elements=mapOrSame(this.elements,recur);const rest=mapOrSame(this.rest,recur);return elements===this.elements&&rest===this.rest&&checks===this.checks&&encodingChecks===this.encodingChecks?this:new Arrays(this.isMutable,elements,rest,this.annotations,checks,undefined,this.context,encodingChecks)}recur(recur){return this._rebuild(recur,this.checks,this.encodingChecks)}flip(recur){return this._rebuild(recur,this.encodingChecks,this.checks)}getExpected(){return"array"}};function stepArray(s,item,exit,i){if(exit._tag==="Failure"){return wrapPropertyKeyIssue(s,s.ast,i,exit)}const value=exit===sameExit?item:exit[args];if(value!==missing){s.output[i]=value}else{const p=s.getParser(s.tailThreshold,i);if(isOptional(p.ast))return;const issue=new Pointer([i],new MissingKey(p.ast.context?.annotations));if(s.options.errors==="all"){if(s.issues)s.issues.push(issue);else s.issues=[issue]}else{return fail5(new Composite(s.ast,[issue],s.input,s.options))}}}var parseArrayOptions={onItem(s,item,i){const value=i<s.len?item:missing;return s.getParser(s.tailThreshold,i).parser(value,s.options)},step:stepArray};var parseArray=iterateEager()(parseArrayOptions);var parseArrayConcurrent=iterateConcurrent()(parseArrayOptions);var wrapPropertyKeyIssue=(s,ast,key,exit)=>{if(exit.cause.reasons.length===0){return exit}const issue=getSchemaIssue(exit.cause);if(issue===undefined){return failCause2(map3(exit.cause,(issue)=>new Composite(ast,[new Pointer([key],issue)],s.input,s.options)))}const pointer=new Pointer([key],issue);if(s.options.errors==="all"){if(s.issues)s.issues.push(pointer);else s.issues=[pointer]}else{return fail5(new Composite(ast,[pointer],s.input,s.options))}};var FINITE_PATTERN="[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?";function getIndexSignatureKeys(input,parameter,options=defaultParseOptions){let stringKeys;let symbolKeys;function go(parameter){switch(parameter._tag){case"String":case"TemplateLiteral":return(stringKeys??=Object.keys(input)).filter((k)=>parameter.matchPart(k,options)!==undefined);case"Number":return(stringKeys??=Object.keys(input)).filter((k)=>parameter.matchKey(k,options)!==undefined);case"Symbol":return(symbolKeys??=Object.getOwnPropertySymbols(input)).filter((k)=>Object.prototype.propertyIsEnumerable.call(input,k)&¶meter.matchKey(k,options)!==undefined);case"Union":return[...new Set(parameter.types.flatMap(go))];default:return[]}}return go(parameterFromPropertyKey(toEncoded(parameter)))}var PropertySignature=class{name;type;constructor(name,type){this.name=name;this.type=type}};function isIndexSignatureParameterSide(ast){switch(ast._tag){case"String":case"Number":case"Symbol":case"TemplateLiteral":return true;case"Union":return ast.types.every(isIndexSignatureParameterSide);default:return false}}function isIndexSignatureParameterEncodedSide(ast){const encoded=getLastEncoding(ast);switch(encoded._tag){case"String":case"Number":case"Symbol":case"TemplateLiteral":return true;case"Union":return encoded.types.every(isIndexSignatureParameterEncodedSide);default:return false}}function isIndexSignatureParameter(ast){return isIndexSignatureParameterSide(ast)&&isIndexSignatureParameterEncodedSide(ast)}var IndexSignature=class{parameter;type;constructor(parameter,type){if(!isIndexSignatureParameter(parameter)){throw new Error(`Invalid index signature parameter ${parameter._tag}`)}this.parameter=parameter;this.type=type;if(isOptional(type)&&!containsUndefined(type)){throw new Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}}};var Objects=class extends ASTNodeImpl{_tag="Objects";propertySignatures;indexSignatures;encodingChecks;constructor(propertySignatures,indexSignatures,annotations,checks,encoding,context,encodingChecks){super(annotations,checks,encoding,context);this.propertySignatures=propertySignatures;this.indexSignatures=indexSignatures;this.encodingChecks=encodingChecks}getParser(compile,compileField=compile){const ast=this;const hasProperties=ast.propertySignatures.length;const indexCount=ast.indexSignatures.length;if(!hasProperties&&!indexCount){return fromRefinement(ast,isNotNullish)}let properties;let indexes;const compileMembers=()=>{if(!properties){properties=ast.propertySignatures.map((ps)=>({parser:compileField(ps.type),name:ps.name,type:ps.type}));indexes=indexCount?ast.indexSignatures.map((is)=>({is,parserKey:compile(parameterFromPropertyKey(is.parameter)),parserValue:compileField(is.type)})):undefined}return properties};const makeFallback=()=>{const expectedKeys=new Set(ast.propertySignatures.map((ps)=>typeof ps.name==="number"?globalThis.String(ps.name):ps.name));const finishIndex=(s,key,k2,inputValue,exitValue)=>{if(exitValue._tag==="Failure"){return wrapPropertyKeyIssue(s,ast,key,exitValue)??void_2}const value=exitValue===sameExit?inputValue:exitValue[args];if(k2!==missing&&value!==missing){if(hasProperties&&(expectedKeys.has(key)||expectedKeys.has(typeof k2==="number"?globalThis.String(k2):k2)))return void_2;assignProperty(s.out,k2,value)}return void_2};const parseIndex=(s,key,index,exitKey)=>{if(!exitKey){const eff=index.parserKey(key,s.options);if(!effectIsExit(eff)){return flatMap3(exit2(eff),(exit)=>parseIndex(s,key,index,exit))}exitKey=eff}if(exitKey._tag==="Failure"){return wrapPropertyKeyIssue(s,ast,key,exitKey)??void_2}const k2=exitKey===sameExit?key:exitKey[args];const inputValue=s.input[key];const result=index.parserValue(inputValue,s.options);return effectIsExit(result)?finishIndex(s,key,k2,inputValue,result):flatMap3(exit2(result),(exit)=>finishIndex(s,key,k2,inputValue,exit))};const parseStringIndex=(s,key,index)=>{const inputValue=s.input[key];const result=index.parserValue(inputValue,s.options);return effectIsExit(result)?finishIndex(s,key,key,inputValue,result):flatMap3(exit2(result),(exit)=>finishIndex(s,key,key,inputValue,exit))};const parseIndexes=indexCount?iterateConcurrent()({onItem:(s,[key,index])=>index.is.parameter===string2?parseStringIndex(s,key,index):parseIndex(s,key,index),step:(_s,_item,exit)=>exit._tag==="Failure"?exit:undefined}):undefined;return fnUntracedEager2(function*(input,options){if(input===missing){return missing}if(!(typeof input==="object"&&input!==null&&!Array.isArray(input))){return yield*fail6(new InvalidType(ast,input,options))}compileMembers();const record=input;const out={};const state={ast,input:record,out,issues:undefined,options};const errorsAllOption=options.errors==="all";const onExcessPropertyError=options.onExcessProperty==="error";const concurrency=options.concurrency===undefined?1:resolveConcurrency(options.concurrency);const indexKeys=indexCount&&onExcessPropertyError?ast.indexSignatures.map((index)=>getIndexSignatureKeys(record,index.parameter,options)):undefined;if(onExcessPropertyError){const coveredKeys=indexKeys?new Set(expectedKeys):expectedKeys;if(indexKeys){for(const keys of indexKeys){for(const key of keys)coveredKeys.add(key)}}const inputKeys=Reflect.ownKeys(record);for(let i=0;i<inputKeys.length;i++){const key=inputKeys[i];if(!coveredKeys.has(key)&&Object.prototype.propertyIsEnumerable.call(record,key)){const unexpected=new UnexpectedKey(ast,record[key],options);const issue=new Pointer([key],unexpected);if(errorsAllOption){if(state.issues){state.issues.push(issue)}else{state.issues=[issue]}continue}else{return yield*fail6(new Composite(ast,[issue],input,options))}}}}if(hasProperties){const eff=concurrency===1?parseProperties(state,properties):parsePropertiesConcurrent(state,properties,{concurrency});if(eff)yield*eff}if(indexCount&&concurrency===1){for(let i=0;i<indexCount;i++){const index=indexes[i];const parse=index.is.parameter===string2?parseStringIndex:parseIndex;const keys=indexKeys?.[i]??(index.is.parameter===string2?Object.keys(record):getIndexSignatureKeys(record,index.is.parameter,options));for(let j=0;j<keys.length;j++){const eff=parse(state,keys[j],index);if(!effectIsExit(eff))yield*eff;else if(eff._tag==="Failure")return yield*eff}}}else if(parseIndexes){const keyPairs=empty2();for(let i=0;i<indexCount;i++){const index=indexes[i];const keys=indexKeys?.[i]??(index.is.parameter===string2?Object.keys(record):getIndexSignatureKeys(record,index.is.parameter,options));for(let j=0;j<keys.length;j++){keyPairs.push([keys[j],index])}}const eff=parseIndexes(state,keyPairs,{concurrency});if(eff)yield*eff}if(state.issues){return yield*fail6(new Composite(ast,state.issues,input,options))}return out})};if(indexCount)return makeFallback();let fallback;const resume=(state,index,pending)=>{const property=properties[index];return flatMap3(exit2(pending),(exit)=>{const terminal=stepProperty(state,property,exit);if(terminal)return terminal;const done=()=>succeed8(state.out);const eff=parseProperties(state,properties.slice(index+1));return eff?flatMapEager2(eff,done):done()})};return(input,options)=>{if(input===missing)return missingExit;if(options.errors==="all"||options.onExcessProperty!==undefined||options.concurrency!==undefined&&resolveConcurrency(options.concurrency)!==1){return(fallback??=makeFallback())(input,options)}if(!(typeof input==="object"&&input!==null&&!Array.isArray(input))){return fail6(new InvalidType(ast,input,options))}const props=compileMembers();const record=input;const out={};const state={ast,input:record,out,issues:undefined,options};try{for(let index=0;index<props.length;index++){const property=props[index];const name=property.name;const hasKey=hasPropertySignature(record,name);const value=hasKey?record[name]:missing;const exit=property.parser(value,options);if(!effectIsExit(exit)){return resume(state,index,exit)}if(exit===sameExit){if(hasKey)assignProperty(out,name,value);continue}const terminal=stepProperty(state,property,exit);if(terminal)return terminal}}catch(error){return die3(error)}return succeed8(out)}}_rebuild(recur,recurParameter,checks,encodingChecks){const props=mapOrSame(this.propertySignatures,(ps)=>{const t=recur(ps.type);return t===ps.type?ps:new PropertySignature(ps.name,t)});const indexes=mapOrSame(this.indexSignatures,(is)=>{const p=recurParameter(is.parameter);const t=recur(is.type);return p===is.parameter&&t===is.type?is:new IndexSignature(p,t)});return props===this.propertySignatures&&indexes===this.indexSignatures&&checks===this.checks&&encodingChecks===this.encodingChecks?this:new Objects(props,indexes,this.annotations,checks,undefined,this.context,encodingChecks)}flip(recur){return this._rebuild(recur,recur,this.encodingChecks,this.checks)}recur(recur,recurParameter=recur){return this._rebuild(recur,recurParameter,this.checks,this.encodingChecks)}getExpected(){if(this.propertySignatures.length===0&&this.indexSignatures.length===0)return"object | array";return"object"}};function stepProperty(s,p,exit){if(exit._tag==="Failure"){return wrapPropertyKeyIssue(s,s.ast,p.name,exit)}if(exit===sameExit)return;const value=exit[args];if(value!==missing){assignProperty(s.out,p.name,value);return}delete s.out[p.name];if(!isOptional(p.type)){const issue=new Pointer([p.name],new MissingKey(p.type.context?.annotations));if(s.options.errors==="all"){if(s.issues)s.issues.push(issue);else s.issues=[issue];return}else{return fail5(new Composite(s.ast,[issue],s.input,s.options))}}}var parsePropertiesOptions={onItem(s,p){if(!hasPropertySignature(s.input,p.name)){return p.parser(missing,s.options)}const value=s.input[p.name];assignProperty(s.out,p.name,value);return p.parser(value,s.options)},step:stepProperty};var parseProperties=iterateEager()(parsePropertiesOptions);var parsePropertiesConcurrent=iterateConcurrent()(parsePropertiesOptions);function combineChecks(a,b){if(!a)return b;if(!b)return a;return[...a,...b]}function struct(fields,checks,annotations){return new Objects(Reflect.ownKeys(fields).map((key)=>{return new PropertySignature(key,fields[key].ast)}),[],annotations,checks)}function getAST(self){return self.ast}function tuple(elements,checks=undefined){return new Arrays(false,elements.map((e)=>e.ast),[],undefined,checks)}function union(members,options,checks){return new Union(members.map(getAST),options,undefined,checks)}var toCandidate=memoizeIdempotent((ast)=>{while(true){if(isSuspend(ast))return unknown;const encoding=ast.encoding;if(!encoding){return ast.recur?.(toCandidate,identity)??ast}if(encoding.some((link)=>link.transformation._tag==="Middleware"&&link.transformation.decode!==identity))return unknown;ast=encoding[encoding.length-1].to}});function getCandidateTypes(ast){switch(ast._tag){case"Null":return["null"];case"Undefined":return["undefined"];case"String":case"TemplateLiteral":return["string"];case"Number":return["number"];case"Boolean":return["boolean"];case"Symbol":case"UniqueSymbol":return["symbol"];case"BigInt":return["bigint"];case"Arrays":return["array"];case"ObjectKeyword":return["object","array","function"];case"Objects":return ast.propertySignatures.length||ast.indexSignatures.length?["object"]:["string","number","boolean","symbol","bigint","object","array","function"];case"Enum":return Array.from(new Set(ast.enums.map(([,v])=>typeof v)));case"Literal":return[typeof ast.literal];case"Union":return Array.from(new Set(ast.types.flatMap(getCandidateTypes)));default:return["null","undefined","string","number","boolean","symbol","bigint","object","array","function"]}}function collectSentinels(ast){switch(ast._tag){default:return[];case"Declaration":{const s=ast.annotations?.[SENTINELS_ANNOTATION_KEY];return Array.isArray(s)?s:[]}case"Objects":return ast.propertySignatures.flatMap((ps)=>{const type=ps.type;if(!isOptional(type)){if(isLiteral(type)){return[{key:ps.name,literal:type.literal}]}if(isUniqueSymbol(type)){return[{key:ps.name,literal:type.symbol}]}}return[]});case"Arrays":return ast.elements.flatMap((e,i)=>{if(!isOptional(e)){if(isLiteral(e)){return[{key:i,literal:e.literal}]}if(isUniqueSymbol(e)){return[{key:i,literal:e.symbol}]}}return[]});case"Union":{if(ast.types.length===0)return[];const members=ast.types.map((type)=>collectSentinels(toCandidate(type)));return members[0].filter((s)=>members.every((sentinels)=>sentinels.some((o)=>o.key===s.key&&o.literal===s.literal)))}case"Suspend":return collectSentinels(ast.thunk())}}var candidateIndexCache=new WeakMap;var emptyCandidates=Object.freeze([]);var getRuntimeType=(input)=>input===null?"null":Array.isArray(input)?"array":typeof input;var hasPropertySignature=(input,key)=>key==="__proto__"?Object.hasOwn(input,key):(key in input);function getCandidateIndex(types){let index=candidateIndexCache.get(types);if(index)return index;let bySentinel;let sentinelCandidateCount=0;let otherwise;let literalCandidates;let onlyLiterals=true;const literalOf=[];for(let i=0;i<types.length;i++){const a=types[i];const encoded=toCandidate(a);if(isNever2(encoded))continue;if(isLiteral(encoded)||isUniqueSymbol(encoded)){literalCandidates??=new Map;const literal=isLiteral(encoded)?encoded.literal:encoded.symbol;literalOf[i]=literal;let arr=literalCandidates.get(literal);if(!arr)literalCandidates.set(literal,arr=[]);arr.push(i)}else{onlyLiterals=false}const sentinels=collectSentinels(encoded);if(sentinels.length){bySentinel??=new Map;sentinelCandidateCount++;for(const{key,literal}of sentinels){let entry=bySentinel.get(key);if(!entry)bySentinel.set(key,entry=[new Map,new Set]);entry[1].add(i);let indexes=entry[0].get(literal);if(!indexes)entry[0].set(literal,indexes=new Set);indexes.add(i)}}else{otherwise??={};const candidateTypes=getCandidateTypes(encoded);for(const t of candidateTypes)(otherwise[t]??=[]).push(i)}}const fallbacks={};const getFallback=(type)=>fallbacks[type]??=Object.freeze(otherwise?.[type]??emptyCandidates);if(onlyLiterals&&literalCandidates){literalCandidates.forEach(Object.freeze);index=(input)=>literalCandidates.get(input)??emptyCandidates}else if(bySentinel?.size===1&&!otherwise){const[key,[byValue]]=bySentinel.entries().next().value;const candidates=new Map;for(const[literal,indexes]of byValue){candidates.set(literal,Object.freeze(Array.from(indexes)))}const all=Object.freeze(types.map((_,i)=>i));index=(input,isConstructor)=>{if(isObjectKeyword(input)){const value=hasPropertySignature(input,key)?input[key]:undefined;if(value!==undefined)return candidates.get(value)??emptyCandidates;if(isConstructor)return all}return emptyCandidates}}else if(bySentinel){let commonSentinel;for(const entry of bySentinel){if((!commonSentinel||entry[1][0].size>commonSentinel[1][0].size)&&entry[1][1].size===sentinelCandidateCount){commonSentinel=entry}}index=(input,isConstructor)=>{const runtimeType=getRuntimeType(input);if(!isObjectKeyword(input))return getFallback(runtimeType);const selected=new Set(otherwise?.[runtimeType]);let directKey;if(commonSentinel){const[key,[byValue]]=commonSentinel;const hasKey=hasPropertySignature(input,key);const value=hasKey?input[key]:undefined;if(hasKey&&(!isConstructor||value!==undefined)){const match=byValue.get(value);if(!match)return getFallback(runtimeType);for(const i of match)selected.add(i);directKey=key}}if(directKey===undefined){for(const[key,[byValue,all]]of bySentinel){const hasKey=hasPropertySignature(input,key);const value=hasKey?input[key]:undefined;if(hasKey&&(!isConstructor||value!==undefined)){const match=byValue.get(value);if(match){for(const i of match)selected.add(i)}}else if(isConstructor){for(const i of all)selected.add(i)}}}for(const[key,[byValue,all]]of bySentinel){if(key===directKey)continue;const hasKey=hasPropertySignature(input,key);const value=hasKey?input[key]:undefined;if(hasKey&&(!isConstructor||value!==undefined)){const match=byValue.get(value);for(const i of selected){if(all.has(i)&&!match?.has(i))selected.delete(i)}}}return Array.from(selected).sort((a,b)=>a-b)}}else{index=(input)=>{const fallback=getFallback(getRuntimeType(input));return literalCandidates?fallback.filter((i)=>literalOf[i]===undefined||literalOf[i]===input):fallback}}candidateIndexCache.set(types,index);return index}var Union=class extends ASTNodeImpl{_tag="Union";types;options;encodingChecks;constructor(types,options,annotations,checks,encoding,context,encodingChecks){super(annotations,checks,encoding,context);this.types=types;this.options=options;this.encodingChecks=encodingChecks}getParser(compile,compileField){const ast=this;const isConstructor=compileField!==undefined;const parsers=[];const parser=(i)=>parsers[i]??=compile(ast.types[i]);let index;return(input,options)=>{if(input===missing){return missingExit}const candidates=(index??=getCandidateIndex(ast.types))(input,isConstructor);if(candidates.length===0){return fail6(new AnyOf(ast,[],input,options))}if(candidates.length===1){const result=parser(candidates[0])(input,options);if(result._tag==="Success")return result;return effectIsExit(result)?failSingleUnionCandidate(ast,result.cause,input,options):catchSingleUnionCandidate(ast,result,input,options)}return parseUnionCandidates(ast,parser,candidates,input,options)}}_rebuild(recur,checks,encodingChecks){const types=mapOrSame(this.types,recur);return types===this.types&&checks===this.checks&&encodingChecks===this.encodingChecks?this:new Union(types,this.options,this.annotations,checks,undefined,this.context,encodingChecks)}recur(recur){return this._rebuild(recur,this.checks,this.encodingChecks)}flip(recur){return this._rebuild(recur,this.encodingChecks,this.checks)}matchPart(s,options){for(const type of this.types){const out=type.matchPart(s,options);if(out!==undefined)return out}return}getExpected(getExpected){const expected=this.annotations?.expected;if(typeof expected==="string")return expected;if(this.types.length===0)return"never";const types=this.types.map((type)=>{const encoded=toEncoded(type);switch(encoded._tag){case"Arrays":{const literals=encoded.elements.filter(isLiteral);if(literals.length>0){return`${formatIsMutable(encoded.isMutable)}[ ${literals.map((e)=>getExpected(e)+formatIsOptional(e.context?.isOptional)).join(", ")}, ... ]`}break}case"Objects":{const literals=encoded.propertySignatures.filter((ps)=>isLiteral(ps.type));if(literals.length>0){return`{ ${literals.map((ps)=>`${formatIsMutable(ps.type.context?.isMutable)}${formatPropertyKey(ps.name)}${formatIsOptional(ps.type.context?.isOptional)}: ${getExpected(ps.type)}`).join(", ")}, ... }`}break}}return getExpected(encoded)});return Array.from(new Set(types)).join(" | ")}};function failSingleUnionCandidate(ast,cause,input,options){const issue=getSchemaIssue(cause);if(!issue)return failCause2(cause);return fail5(new AnyOf(ast,[issue],input,options))}function catchSingleUnionCandidate(ast,result,input,options){return catchCause2(result,(cause)=>failSingleUnionCandidate(ast,cause,input,options))}function parseUnionCandidates(ast,parser,candidates,input,options){const state={ast,parser,input,out:undefined,successes:ast.options?.mode==="oneOf"?[]:undefined,issues:undefined,options};const eff=parseUnion(state,candidates);if(!eff){if(state.out)return state.out;return fail6(new AnyOf(ast,state.issues??[],input,options))}return resumeUnion(eff,state)}function resumeUnion(eff,state){return flatMapEager2(eff,(_)=>{if(state.out===sameExit)return succeed6(state.input);if(state.out)return state.out;return fail6(new AnyOf(state.ast,state.issues??[],state.input,state.options))})}var parseUnion=iterateEager()({onItem(s,i){return s.parser(i)(s.input,s.options)},step(s,i,exit){if(exit._tag==="Failure"){const issue=getSchemaIssue(exit.cause);if(issue===undefined){return exit}if(s.issues)s.issues.push(issue);else s.issues=[issue]}else{if(s.out&&s.successes){s.successes.push(s.ast.types[i]);return fail5(new OneOf(s.ast,s.successes,s.input,s.options))}s.out=exit;if(s.successes){s.successes.push(s.ast.types[i])}else{return void_2}}}});var nonFiniteLiterals=new Union([new Literal("Infinity"),new Literal("-Infinity"),new Literal("NaN")]);function formatIsMutable(isMutable){return isMutable?"":"readonly "}function formatIsOptional(isOptional){return isOptional?"?":""}var Filter2=class extends Class{_tag="Filter";run;annotations;aborted;constructor(run,annotations=undefined,aborted=false){super();this.run=run;this.annotations=annotations;this.aborted=aborted}annotate(annotations){return new Filter2(this.run,{...this.annotations,...annotations},this.aborted)}abort(){return new Filter2(this.run,this.annotations,true)}and(other,annotations){return new FilterGroup([this,other],annotations)}};var FilterGroup=class extends Class{_tag="FilterGroup";checks;annotations;constructor(checks,annotations=undefined){super();this.checks=checks;this.annotations=annotations}annotate(annotations){return new FilterGroup(this.checks,{...this.annotations,...annotations})}and(other,annotations){return new FilterGroup([this,other],annotations)}};function makeFilter(filter,annotations,aborted=false){return new Filter2((input,ast,options)=>normalizeFilterOutput(ast,filter(input,ast,options),input,options),annotations,aborted)}function isFinite(annotations){return makeFilter((n)=>globalThis.Number.isFinite(n),{expected:"a finite number",representation:{id:"effect/schema/isFinite",payload:null},toJsonSchema:()=>({type:"number"}),toCode:()=>({runtime:"Schema.isFinite()"}),arbitraryConstraint:{number:"finite"},...annotations})}var finite=appendChecks(number2,[isFinite()]);var numberToJson=new Link(new Union([finite,nonFiniteLiterals]),new Transformation(Number3(),transform((n)=>globalThis.Number.isFinite(n)?n:globalThis.String(n))));function isPattern(regExp,annotations){const copy=new globalThis.RegExp(regExp);const payload={source:copy.source,flags:copy.flags};return makeFilter((s)=>{copy.lastIndex=0;return copy.test(s)},{expected:`a string matching the RegExp ${payload.source}`,representation:{id:"effect/schema/isPattern",payload},toJsonSchema:()=>[{},true],arbitraryConstraint:{patterns:[payload]},...annotations})}var bodyOwners=new WeakMap;function copy2(ast,changes){const out=Object.assign(Object.create(Object.getPrototypeOf(ast)),ast,changes);if(Reflect.ownKeys(changes).every((key)=>key==="context"||key==="encoding")){bodyOwners.set(out,getContextOwner(ast))}return out}function getContextOwner(ast){const existing=bodyOwners.get(ast);if(existing!==undefined)return existing;if(ast.encoding===undefined)return ast;const owner=Object.assign(Object.create(Object.getPrototypeOf(ast)),ast,{encoding:undefined});bodyOwners.set(ast,owner);return owner}function replaceEncoding(ast,encoding){return ast.encoding===encoding?ast:copy2(ast,{encoding})}function replaceContext(ast,context){if(ast.context===context){return ast}const owner=getContextOwner(ast);if(owner.context===context&&owner.encoding===ast.encoding){return owner}return copy2(ast,{context})}function getLastEncoding(ast){return ast.encoding?getLastEncoding(ast.encoding[ast.encoding.length-1].to):ast}function annotate(ast,annotations){if(ast.checks){const last=ast.checks[ast.checks.length-1];return replaceChecks(ast,append(ast.checks.slice(0,-1),last.annotate(annotations)))}return copy2(ast,{annotations:{...ast.annotations,...annotations}})}function replaceChecks(ast,checks){if(ast._tag==="Suspend"&&checks){throw new Error("Cannot add checks to Suspend")}if(ast.checks===checks){return ast}return copy2(ast,{checks})}function appendChecks(ast,checks){return replaceChecks(ast,combineChecks(ast.checks,checks))}function mapLink(link,f){const to=f(link.to);return to===link.to?link:new Link(to,link.transformation)}function updateLastLink(encoding,f){const links=encoding;const last=links[links.length-1];const out=mapLink(last,f);return out===last?encoding:append(encoding.slice(0,encoding.length-1),out)}function applyToLastLink(f){return(ast)=>ast.encoding?replaceEncoding(ast,updateLastLink(ast.encoding,f)):ast}function replaceContextLastLink(ast,context){return applyToLastLink((ast)=>replaceContext(ast,context))(ast)}function applyToSelfOrLastLinkEncoding(f){function out(ast){return ast.encoding?replaceEncoding(ast,updateLastLink(ast.encoding,out)):f(ast)}return memoize(out)}function applyToSelfOrLastLinkEncodingIdempotent(f,options){function out(ast){if(ast.encoding){const last=ast.encoding[ast.encoding.length-1];return options?.stopAt?.(last)?ast:replaceEncoding(ast,updateLastLink(ast.encoding,out))}return f(ast)}return memoizeIdempotent(out)}function appendTransformation(from,transformation,to){const link=new Link(from,transformation);return replaceEncoding(to,to.encoding?[...to.encoding,link]:[link])}function mapOrSame(as,f){let out;for(let i=0;i<as.length;i++){const a=as[i];const fa=f(a);if(out){out[i]=fa}else if(fa!==a){out=new Array(as.length);for(let j=0;j<i;j++){out[j]=as[j]}out[i]=fa}}return out??as}function annotateKey(ast,annotations){const context=ast.context?new Context(ast.context.isOptional,ast.context.isMutable,ast.context.constructorDefault,{...ast.context.annotations,...annotations}):new Context(false,false,undefined,annotations);return replaceContext(ast,context)}var optionalKey=memoizeIdempotent((ast)=>{const context=ast.context?ast.context.isOptional===false?new Context(true,ast.context.isMutable,ast.context.constructorDefault,ast.context.annotations):ast.context:new Context(true,false);return optionalKeyLastLink(replaceContext(ast,context))});var optionalKeyLastLink=applyToLastLink(optionalKey);var optional=memoize((ast)=>optionalKey(new Union([ast,undefined_2])));function withConstructorDefault(ast,defaultValue){const context=ast.context?new Context(ast.context.isOptional,ast.context.isMutable,defaultValue,ast.context.annotations):new Context(false,false,defaultValue);return replaceContext(ast,context)}function decodeTo(from,to,transformation){return appendTransformation(from,transformation,to)}function parseParameter(ast){const literals=[];const parameters=[];function go(ast){switch(ast._tag){case"Literal":if(isPropertyKey(ast.literal)&&!literals.includes(ast.literal)){literals.push(ast.literal)}return;case"UniqueSymbol":if(!literals.includes(ast.symbol)){literals.push(ast.symbol)}return;case"Never":return;case"Union":for(let i=0;i<ast.types.length;i++){go(ast.types[i])}return;default:parameters.push(ast)}}go(ast);return{literals,parameters}}function record(key,value){const{literals,parameters:indexSignatures}=parseParameter(key);return new Objects(literals.map((literal)=>new PropertySignature(literal,value)),indexSignatures.map((parameter)=>new IndexSignature(parameter,value)))}function isOptional(ast){return ast.context?.isOptional??false}function isStructuralCheck(check){return check.annotations?.[STRUCTURAL_ANNOTATION_KEY]===true||check._tag==="FilterGroup"&&check.checks.every(isStructuralCheck)}function extractStructuralChecks(checks){function extract(check){if(isStructuralCheck(check))return[check];return check._tag==="FilterGroup"?check.checks.flatMap(extract):[]}const out=checks.flatMap(extract);return isArrayNonEmpty2(out)?out:undefined}function canPreserveEncodingChecks(ast){let preserve=true;function visit(child){preserve=preserve&&!child.encoding&&!isSuspend(child);if(preserve&&"recur"in child)child.recur(visit);return child}if("recur"in ast)ast.recur(visit);return preserve}var toType=memoizeIdempotent((ast)=>{const owner=getContextOwner(ast);if(owner!==ast){const type=toType(owner);return type===owner&&ast.encoding===undefined?ast:replaceContext(type,ast.context)}const type="recur"in ast?ast.recur(toType):ast;if("encodingChecks"in type&&type.encodingChecks){const checks=canPreserveEncodingChecks(ast)?type.encodingChecks:isArrays(type)||isObjects(type)||isDeclaration(type)&&type.typeParameters.length>0?extractStructuralChecks(type.encodingChecks):undefined;return copy2(type,{encodingChecks:undefined,checks:combineChecks(type.checks,checks)})}return type});var toEncoded=memoizeIdempotent((ast)=>{return toType(flip2(ast))});function flipEncoding(ast,encoding){const links=encoding;const len=links.length;const last=links[len-1];const ls=[new Link(flip2(replaceEncoding(ast,undefined)),links[0].transformation.flip())];for(let i=1;i<len;i++){ls.unshift(new Link(flip2(links[i-1].to),links[i].transformation.flip()))}const to=flip2(last.to);if(to.encoding){return replaceEncoding(to,[...to.encoding,...ls])}else{return replaceEncoding(to,ls)}}var flip2=memoize((ast)=>{if(ast.encoding){return flipEncoding(ast,ast.encoding)}const owner=getContextOwner(ast);if(owner!==ast){const flipped=flip2(owner);return flipped===owner?ast:replaceContext(flipped,ast.context)}return"flip"in ast?ast.flip(flip2):("recur"in ast)?ast.recur(flip2):ast});function containsUndefined(ast){switch(ast._tag){case"Undefined":return true;case"Union":return ast.types.some(containsUndefined);default:return false}}function fromConst(ast,value){const succeed=value===0?sameExit:succeed8(value);return(input,options)=>{if(input===missing)return missingExit;if(input===value)return succeed;return fail6(new InvalidType(ast,input,options))}}function fromRefinement(ast,refinement){return(input,options)=>{if(input===missing)return missingExit;if(refinement(input))return sameExit;return fail6(new InvalidType(ast,input,options))}}var parameterFromPropertyKey=applyToSelfOrLastLinkEncodingIdempotent((ast)=>{switch(ast._tag){default:return ast;case"Number":return ast.toCodecStringTree();case"Union":return ast.recur(parameterFromPropertyKey)}});var parameterFromString=applyToSelfOrLastLinkEncodingIdempotent((ast)=>{switch(ast._tag){default:return ast;case"Symbol":case"UniqueSymbol":return ast.toCodecStringTree();case"Union":return ast.recur(parameterFromString)}});var isStringFiniteRegExp=new globalThis.RegExp(`^${FINITE_PATTERN}$`);var isStringNumberRegExp=new globalThis.RegExp(`^(?:${FINITE_PATTERN}|Infinity|-Infinity|NaN)$`);function isStringFinite(annotations){return isPattern(isStringFiniteRegExp,{expected:"a string representing a finite number",representation:{id:"effect/schema/isStringFinite",payload:null},toJsonSchema:()=>({pattern:isStringFiniteRegExp.source}),...annotations})}var finiteString=appendChecks(string2,[isStringFinite()]);var finiteToString=new Link(finiteString,numberFromString);var numberToString=new Link(new Union([finiteString,nonFiniteLiterals]),numberFromString);var BIGINT_PATTERN="-?\\d+";var isStringBigIntRegExp=new globalThis.RegExp(`^${BIGINT_PATTERN}$`);var REGEXP_PATTERN="Symbol\\(([\\s\\S]*)\\)";var isStringSymbolRegExp=new globalThis.RegExp(`^${REGEXP_PATTERN}$`);function collectIssues(checks,value,issues,ast,options){for(let i=0;i<checks.length;i++){const check=checks[i];if(check._tag==="FilterGroup"){issues=collectIssues(check.checks,value,issues,ast,options);if(issues&&(options.errors!=="all"||issues[issues.length-1].filter.aborted)){return issues}}else{const issue=check.run(value,ast,options);if(issue){const filter=new Filter(check,issue,value,options);if(issues)issues.push(filter);else issues=[filter];if(options.errors!=="all"||check.aborted){return issues}}}}return issues}function getConstructorDescriptor(ast){if(!isDeclaration(ast))return;const getDescriptor=ast.annotations?.[CONSTRUCTOR_ANNOTATION_KEY];return isFunction(getDescriptor)?getDescriptor(ast.typeParameters):undefined}function isJsonLeaf(u){return u===null||typeof u==="string"||typeof u==="boolean"||typeof u==="number"&&globalThis.Number.isFinite(u)}function isStringTreeLeaf(u){return u===undefined||typeof u==="string"}function isTree(u,isLeaf){const cache=new WeakMap;const stack=[];outer:while(true){if(typeof u!=="object"||u===null){if(!isLeaf(u)){return false}}else{const value=u;const cached=cache.get(value);if(cached===false){return false}if(cached===undefined){const isArray=Array.isArray(value);if(!isArray){const prototype=Object.getPrototypeOf(value);if(prototype!==null&&prototype!==Object.prototype&&Object.getPrototypeOf(prototype)!==null){return false}}cache.set(value,false);stack.push({value,keys:isArray?value.length:Object.keys(value),index:0})}}while(stack.length>0){const frame=stack[stack.length-1];const keys=frame.keys;if(typeof keys==="number"){if(frame.index<keys){u=frame.value[frame.index++];continue outer}}else if(frame.index<keys.length){u=frame.value[keys[frame.index++]];continue outer}cache.set(frame.value,true);stack.pop()}return true}}function isJson(u){return isTree(u,isJsonLeaf)}var Json=new Declaration([],()=>(input,ast,options)=>isJson(input)?sameExit:fail6(new InvalidType(ast,input,options)),{representation:{id:"effect/schema/Json",payload:null},expected:"JSON value",toCodecJson:()=>{return},toCodecStringTree:()=>unknownToStringTree});function isStringTree(u){return isTree(u,isStringTreeLeaf)}var StringTree=new Declaration([],()=>(input,ast,options)=>isStringTree(input)?sameExit:fail6(new InvalidType(ast,input,options)),{expected:"StringTree",toCodecStringTree:()=>{return}});var unknownToStringTree=new Link(StringTree,passthrough2());var flatMapTransformation=(result,current,f)=>result===sameExit?f(current):flatMapEager2(result,f);function compileTransformation(transformation){if(transformation._tag==="Middleware"){return(result,current,options)=>{const transformed=result===sameExit?transformation.decode(succeed8(toOption(current)),options):transformation.decode(mapEager2(result,toOption),options);return fromOptionalEffect(transformed)}}const getter=transformation.decode;switch(getter._tag){case"Passthrough":return(result,current)=>result===sameExit?succeed8(current):result;case"Transform":{const transform=(value)=>value===missing?missingExit:succeed8(getter.transform(value));return(result,current)=>flatMapTransformation(result,current,transform)}case"TransformOptional":{const transform=(value)=>fromOptionExit(getter.transform(toOption(value)));return(result,current)=>flatMapTransformation(result,current,transform)}case"TransformEffect":return(result,current,options)=>flatMapTransformation(result,current,(value)=>value===missing?missingExit:getter.transform(value,options));case"TransformOptionalEffect":return(result,current,options)=>flatMapTransformation(result,current,(value)=>fromOptionalEffect(getter.transform(toOption(value),options)))}}var fromOptionalEffect=(effect)=>flatMapEager2(effect,fromOptionExit);var wrapEncoding=(ast,input,options,effect)=>catchCause2(effect,(cause)=>failCauseSync2(()=>map3(cause,(issue)=>new Encoding(ast,issue,input,options))));function makeConstructorParser(descriptor,compile){const transform=compileTransformation(descriptor.link.transformation);let sourceParser;return(input,options)=>{if(input===missing)return missingExit;if(descriptor.isConstructed(input))return sameExit;const result=(sourceParser??=compile(descriptor.link.to))(input,options);return transform(result,input,options)}}function withDefault(ast,parser){const defaultValue=ast.context.constructorDefault;return(input,options)=>{if(input!==missing&&input!==undefined)return parser(input,options);const result=defaultValue;if(effectIsExit(result)&&result._tag==="Success"){const local=parser(result[args],options);return local===sameExit?result:local}return flatMapEager2(wrapEncoding(ast,input,options,result),(value)=>{const local=parser(value,options);return local===sameExit?succeed8(value):local})}}function compileField(ast,compile){const parser=compile(ast);return ast.context?.constructorDefault===undefined?parser:withDefault(ast,parser)}function compile(ast,compile,compileField,base,specialize){if(ast._tag==="Declaration"){for(const parameter of ast.typeParameters)compile(parameter)}const descriptor=compileField?getConstructorDescriptor(ast):undefined;const parser=descriptor?makeConstructorParser(descriptor,compile):base??ast.getParser(compile,compileField);const checks=ast.checks;const links=ast.encoding;const transformations=links?.map((link)=>compileTransformation(link.transformation));const encodingChecks=ast.encodingChecks;if(!links&&!checks&&!encodingChecks){return parser}let encodingParsers;const parseChecks=(input,options)=>{let result=parser(input,options);if(encodingChecks&&!options.disableChecks){if(effectIsExit(result)){if(result._tag==="Success"){const output=result===sameExit?input:result[args];if(input!==missing&&output!==missing){const issues=collectIssues(encodingChecks,input,undefined,ast,options);if(issues){result=fail6(new Composite(ast,issues,input,options))}}}}else{result=flatMap3(result,(value)=>{if(input!==missing&&value!==missing){const issues=collectIssues(encodingChecks,input,undefined,ast,options);if(issues){return fail6(new Composite(ast,issues,input,options))}}return succeed6(value)})}}if(checks&&!options.disableChecks){if(effectIsExit(result)){if(result._tag==="Success"){const value=result===sameExit?input:result[args];if(value===missing)return result;const issues=collectIssues(checks,value,undefined,ast,options);if(issues){result=fail6(new Composite(ast,issues,value,options))}}}else{result=flatMap3(result,(value)=>{if(value!==missing){const issues=collectIssues(checks,value,undefined,ast,options);if(issues){return fail6(new Composite(ast,issues,value,options))}}return succeed6(value)})}}return result};const parseLocal=specialize===undefined?parseChecks:specialize(parseChecks);if(!links){return parseLocal}return(input,options)=>{const parsers=encodingParsers??=links.map((link)=>compile(link.to));let current=input;let result=parsers[parsers.length-1](input,options);for(let i=links.length-1;i>=0;i--){result=transformations[i](result,current,options);if(i!==0){const next=parsers[i-1];if(result._tag==="Success"){current=result[args];result=next(current,options)}else{result=flatMapEager2(result,(value)=>{const nextResult=next(value,options);return nextResult===sameExit?succeed8(value):nextResult})}}}if(result._tag==="Success"){const value=result[args];const local=parseLocal(value,options);return local===sameExit?result:local}result=wrapEncoding(ast,input,options,result);return flatMapEager2(result,(value)=>{const local=parseLocal(value,options);return local===sameExit?succeed8(value):local})}}var invalid3=Symbol();var cache=new WeakMap;var compiler;var compilerAdaptersEnabled=false;var decodeChild=(ast)=>compilerAdaptersEnabled?lazyParser(resolve4,ast,"parser"):resolve4(ast).parser;var makeChild=(ast)=>compilerAdaptersEnabled?lazyParser(resolve4,ast,"makeEffect"):resolve4(ast).makeEffect;var makeField=(ast)=>compileField(ast,makeChild);class InterpretedEntry{ast;constructor(ast){this.ast=ast}get decodeEffect(){return this.cachedDecodeEffect??=compile(this.ast,decodeChild)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=compile(this.ast,makeChild,makeField)}}class CompilerEntry extends InterpretedEntry{compiled;resolve;constructor(ast,compiled,resolve){super(ast);this.compiled=compiled;this.resolve=resolve}save(key,value){Object.defineProperty(this,key,{value});return value}operation(key){const compiled=this.compiled;return typeof compiled==="function"?compiled(this.ast,this.resolve,key):compiled?.[key]}get is(){return this.save("is",this.operation("is"))}get decode(){return this.save("decode",this.operation("decode"))}get make(){return this.save("make",this.operation("make"))}get decodeEffect(){return this.save("decodeEffect",this.operation("decodeEffect")??compile(this.ast,(ast)=>lazyParser(this.resolve,ast,"parser")))}get parser(){const decode=this.decode;return decode===undefined?this.decodeEffect:this.save("parser",withDecode(decode,()=>this.decodeEffect))}get makeEffect(){const makeEffect=this.operation("makeEffect");if(makeEffect!==undefined)return this.save("makeEffect",makeEffect);const child=(ast)=>lazyParser(this.resolve,ast,"makeEffect");return this.save("makeEffect",compile(this.ast,child,(ast)=>compileField(ast,child)))}}function withDecode(fastDecode,decodeEffect){let detailed;return(input,options)=>{if(input!==missing){try{const value=fastDecode(input,options);if(value!==invalid3)return value===input?sameExit:succeed8(value)}catch(error){return die3(error)}}return(detailed??=decodeEffect())(input,options)}}function lazyParser(resolve,ast,operation){const entry=resolve(ast);if(entry.compiled===undefined||Object.hasOwn(entry,operation)){return entry[operation]}let parser;return(input,options)=>(parser??=entry[operation])(input,options)}function resolve4(ast){const cached=cache.get(ast);if(cached!==undefined)return cached;const entry=compiler===undefined?new InterpretedEntry(ast):new CompilerEntry(ast,compiler(ast,resolve4),resolve4);cache.set(ast,entry);return entry}function makeEffect(schema){const ast=schema.ast;let parser;return(input,options)=>{return(parser??=runWithCompiler(constructorCompiler,toType(ast)))(input,options?.disableChecks?options?.parseOptions?{...options.parseOptions,disableChecks:true}:{disableChecks:true}:options?.parseOptions)}}function makeOption(schema){const parser=makeEffect(schema);return(input,options)=>{const exit=runSyncExit2(parser(input,options));if(isSuccess3(exit)){return some2(exit.value)}getSchemaIssueOrThrow(exit.cause,"Option adapter can only return none for schema issues");return none2()}}function make11(schema){return makeConstructorSync(toType(schema.ast))}function is(schema){return _is(schema.ast)}function makeIs(ast){if(!compilerAdaptersEnabled){const parser=asExit(run(ast));return(input)=>{const exit=parser(input,defaultParseOptions);if(isSuccess3(exit))return true;getSchemaIssueOrThrow(exit.cause,"Type guard adapter can only return false for schema issues");return false}}const entry=resolve4(ast);const guard=entry.is;if(guard!==undefined){return(input)=>{try{return guard(input,defaultParseOptions)}catch(error){getSchemaIssueOrThrow(die2(error),"Type guard adapter can only return false for schema issues");return false}}}const parser=entry.parser;return(input)=>{const exit=runSyncExit2(parserResult(parser(input,defaultParseOptions),input));if(isSuccess3(exit))return true;getSchemaIssueOrThrow(exit.cause,"Type guard adapter can only return false for schema issues");return false}}function _is(ast){const typeAST=toType(ast);let guard=(input)=>{guard=makeIs(typeAST);return guard(input)};return(input)=>{return guard(input)}}function decodeUnknownEffect(schema,options){const parser=run(schema.ast);return options===undefined?parser:(input,overrideOptions)=>parser(input,mergeParseOptions(options,overrideOptions))}function encodeUnknownEffect(schema,options){const parser=run(flip2(schema.ast));return options===undefined?parser:(input,overrideOptions)=>parser(input,mergeParseOptions(options,overrideOptions))}var mergeParseOptions=(options,overrideOptions)=>overrideOptions?{...options,...overrideOptions}:options;var getValue=(value)=>{if(value===missing){return fail6(new InvalidValue)}return succeed6(value)};function run(ast){return runWithCompiler(normalCompiler,ast)}function parserResult(result,input){if(result===sameExit){return succeed6(input)}if(!effectIsExit(result)){return flatMapEager2(result,getValue)}return result[args]===missing?getValue(missing):result}function runWithCompiler(compiler,ast){let parser;return(input,options)=>{const result=(parser??=compiler(ast))(input,options??defaultParseOptions);if(result===sameExit){return succeed6(input)}if(!effectIsExit(result)){return flatMapEager2(result,getValue)}return result[args]===missing?getValue(missing):result}}function asExit(parser){return(input,options)=>runSyncExit2(parser(input,options))}function runSync3(effect,message){const exit=runSyncExit2(effect);if(isSuccess3(exit)){return exit.value}const issue=getSchemaIssueOrThrow(exit.cause,message);throw new Error("Schema validation failed",{cause:issue})}function makeConstructorSync(ast){let entry;let parser;return(input,options)=>{entry??=resolve4(ast);const parseOptions=options?.disableChecks?options.parseOptions?{...options.parseOptions,disableChecks:true}:{disableChecks:true}:options?.parseOptions??defaultParseOptions;const make=entry.make;if(make!==undefined&&input!==missing){let output;try{output=make(input,parseOptions)}catch(error){getSchemaIssueOrThrow(die2(error),"Constructor adapter can only throw schema issues");throw error}if(output!==invalid3&&output!==missing)return output}const result=(parser??=entry.makeEffect)(input,parseOptions);return runSync3(parserResult(result,input),"Constructor adapter can only throw schema issues")}}var normalCompiler=(ast)=>resolve4(ast).parser;var constructorCompiler=(ast)=>resolve4(ast).makeEffect;var TypeId18="~effect/Schema/Schema";var RebuildOptions=Symbol();var SchemaProto={[TypeId18]:TypeId18,get make(){const value=make11(this);Object.defineProperty(this,"make",{value,enumerable:true});return value},get makeEffect(){const value=makeEffect(this);Object.defineProperty(this,"makeEffect",{value,enumerable:true});return value},get makeOption(){const value=makeOption(this);Object.defineProperty(this,"makeOption",{value,enumerable:true});return value},pipe(){return pipeArguments(this,arguments)},annotate(annotations){return this.rebuild(annotate(this.ast,annotations))},annotateKey(annotations){return this.rebuild(annotateKey(this.ast,annotations))},check(...checks){return this.rebuild(appendChecks(this.ast,checks))},rebuild(ast){return make12(ast,this[RebuildOptions])}};function make12(ast,options){function Schema(){}const self=Object.setPrototypeOf(Schema,SchemaProto);if(options&&(Object.hasOwn(options,"name")||Object.hasOwn(options,"length")||Object.hasOwn(options,"__proto__"))){Object.defineProperties(self,Object.getOwnPropertyDescriptors({...options}))}else{Object.assign(self,options)}self[RebuildOptions]=options;self.ast=ast;return self}function withoutConstructorDefault(context){return context.constructorDefault===undefined?context:new Context(context.isOptional,context.isMutable,undefined,context.annotations)}function validateCanonicalObjectPropertyNames(ast){if(ast.propertySignatures.some((ps)=>typeof ps.name!=="string")){throw new globalThis.Error("Objects property names must be strings",{cause:ast})}}function makeReorder(getPriority){return(types)=>{const sortedTypes=[...types].sort((a,b)=>getPriority(toEncoded(a))-getPriority(toEncoded(b)));const orderChanged=sortedTypes.some((ast,index)=>ast!==types[index]);if(!orderChanged)return types;return sortedTypes}}function toCodecStringTree(schema){return make12(toCodecStringTreeAST(schema.ast),{schema})}var toStringTreeReorder=makeReorder((ast)=>{switch(ast._tag){case"Null":case"Boolean":case"Number":case"BigInt":case"Symbol":case"UniqueSymbol":return 0;default:return 1}});function toCodecStringTreeASTStep(ast,recur,onMissingAnnotation){switch(ast._tag){case"Declaration":{const typeParameters=ast.typeParameters.map((tp)=>make12(recur(toEncoded(tp))));const getStringTreeLink=ast.annotations?.toCodecStringTree;if(isFunction(getStringTreeLink)){const link=getStringTreeLink(typeParameters);if(link===undefined)return ast;return replaceEncoding(ast,[mapLink(link,recur)])}const getJsonLink=ast.annotations?.toCodecJson;const jsonLink=isFunction(getJsonLink)?getJsonLink(typeParameters):undefined;const getLink=jsonLink===undefined?ast.annotations?.toCodec:undefined;const link=jsonLink??(isFunction(getLink)?getLink(typeParameters):undefined);return link===undefined?onMissingAnnotation(ast):replaceEncoding(ast,[mapLink(link,recur)])}case"Null":return replaceEncoding(ast,[nullToString]);case"Boolean":return replaceEncoding(ast,[booleanToString]);case"Unknown":case"ObjectKeyword":return replaceEncoding(ast,[unknownToStringTree]);case"Enum":case"Number":case"Literal":case"UniqueSymbol":case"Symbol":case"BigInt":return ast.toCodecStringTree();case"Objects":{validateCanonicalObjectPropertyNames(ast);return ast.recur(recur,parameterFromString)}case"Union":{const sortedTypes=toStringTreeReorder(ast.types);if(sortedTypes!==ast.types){return new Union(sortedTypes,ast.options,ast.annotations,ast.checks,ast.encoding,ast.context,ast.encodingChecks).recur(recur)}return ast.recur(recur)}case"Arrays":case"Suspend":return ast.recur(recur)}return ast}var nullToString=new Link(new Literal("null"),new Transformation(transform(()=>null),transform(()=>"null")));var booleanToString=new Link(new Union([new Literal("true"),new Literal("false")]),new Transformation(transform((s)=>s==="true"),String2()));var arrayFromSingleTransformation=new Transformation(transform((input)=>typeof input==="string"?[input]:input),passthrough());var isCodecArrayFromSingleLink=(link)=>link.transformation===arrayFromSingleTransformation;var toCodecStringTreeAST=applyToSelfOrLastLinkEncodingIdempotent((ast)=>{const out=toCodecStringTreeASTStep(ast,toCodecStringTreeAST,(ast)=>{throw new globalThis.Error("Missing structural codec for StringTree",{cause:ast})});if(out!==ast&&ast.context!==undefined){return replaceContextLastLink(out,withoutConstructorDefault(ast.context))}return out},{stopAt:isCodecArrayFromSingleLink});var lambda=(f)=>f;var SchemaErrorTypeId="~effect/Schema/SchemaError";function isSchemaError(u){return hasProperty(u,SchemaErrorTypeId)&&u[SchemaErrorTypeId]===SchemaErrorTypeId}var TypeId19=TypeId18;function declareConstructor(){return(typeParameters,run,annotations)=>{return make13(new Declaration(typeParameters.map(getAST),(typeParameters)=>run(typeParameters.map((ast)=>make13(ast))),annotations))}}function declare(is,annotations){return declareConstructor()([],()=>(input,ast,options)=>is(input)?succeed6(input):fail6(new InvalidType(ast,input,options)),annotations)}class SchemaError extends TaggedError2("SchemaError"){[SchemaErrorTypeId]=SchemaErrorTypeId;constructor(issue){const stackTraceLimit=getStackTraceLimit();setStackTraceLimit(0);try{super({issue})}finally{setStackTraceLimit(stackTraceLimit)}}get message(){return defaultFormatter(this.issue)}toString(){return`SchemaError(${this.message})`}}function isSchemaError2(u){return isSchemaError(u)}function fromIssueEffect(self){if(effectIsExit(self)){return fromIssueExit(self)}return catchCause2(self,(cause)=>failCauseSync2(()=>map3(cause,(issue)=>new SchemaError(issue))))}function fromIssueExit(exit){return isSuccess3(exit)?exit:failCause2(map3(exit.cause,(issue)=>new SchemaError(issue)))}function getSchemaErrorOrThrow(cause,message){let schemaError;for(const reason of cause.reasons){if(!isFailReason2(reason)||!isSchemaError2(reason.error)){throw new globalThis.Error(message,{cause})}schemaError??=reason.error}if(schemaError===undefined){throw new globalThis.Error(message,{cause})}return schemaError}function runSchemaErrorPromise(self){return runPromiseExit2(self).then((exit)=>{if(isSuccess3(exit)){return exit.value}throw getSchemaErrorOrThrow(exit.cause,"Promise adapter can only reject schema errors")})}function runSchemaErrorSync(self){const exit=runSyncExit2(self);if(isSuccess3(exit)){return exit.value}throw getSchemaErrorOrThrow(exit.cause,"Sync adapter can only throw schema errors")}var is2=is;function decodeUnknownEffect2(schema,options){const parser=decodeUnknownEffect(schema,options);return(input,options)=>{return fromIssueEffect(parser(input,options))}}function decodeUnknownPromise(schema,options){const parser=decodeUnknownEffect2(schema,options);return(input,options)=>{return runSchemaErrorPromise(parser(input,options))}}var decodePromise=decodeUnknownPromise;function decodeUnknownSync(schema,options){const parser=decodeUnknownEffect2(schema,options);return(input,options)=>{return runSchemaErrorSync(parser(input,options))}}var decodeSync=decodeUnknownSync;function encodeUnknownEffect2(schema,options){const parser=encodeUnknownEffect(schema,options);return(input,options)=>{return fromIssueEffect(parser(input,options))}}var encodeEffect=encodeUnknownEffect2;function encodeUnknownSync(schema,options){const parser=encodeUnknownEffect2(schema,options);return(input,options)=>{return runSchemaErrorSync(parser(input,options))}}var encodeSync=encodeUnknownSync;var make13=make12;function isSchema(u){return hasProperty(u,TypeId19)&&u[TypeId19]===TypeId19}var optionalKey2=lambda((schema)=>make13(optionalKey(schema.ast),{schema}));var optional2=lambda((self)=>{const schema=UndefinedOr(self);return make13(optional(self.ast),{schema})});function Literal2(literal){const out=make13(new Literal(literal),{literal,transform(to){return out.pipe(decodeTo2(Literal2(to),{decode:transform(()=>to),encode:transform(()=>literal)}))}});return out}var Unknown2=make13(unknown);var Undefined2=make13(undefined_2);var String4=make13(string2);var Number5=make13(number2);var Boolean3=make13(boolean);function makeStruct(ast,fields){return make13(ast,{fields,mapFields(f,options){const fields=f(this.fields);return makeStruct(struct(fields,options?.unsafePreserveChecks?this.ast.checks:undefined),fields)}})}function Struct(fields){return makeStruct(struct(fields,undefined),fields)}function Record(key,value){return make13(record(key.ast,value.ast),{key,value})}function makeTuple(ast,elements){return make13(ast,{elements,mapElements(f,options){const elements=f(this.elements);return makeTuple(tuple(elements,options?.unsafePreserveChecks?this.ast.checks:undefined),elements)}})}function Tuple(elements){return makeTuple(tuple(elements),elements)}var ArraySchema=lambda((schema)=>make13(new Arrays(false,[],[schema.ast]),{value:schema}));function makeUnion(ast,members){return make13(ast,{members,mapMembers(f,options){const members=f(this.members);return makeUnion(union(members,this.ast.options,options?.unsafePreserveChecks?this.ast.checks:undefined),members)}})}function Union2(members,options){return makeUnion(union(members,options,undefined),members)}function Literals(literals){const members=literals.map(Literal2);return make13(union(members,undefined,undefined),{literals,members,mapMembers(f){return Union2(f(this.members))},pick(literals){return Literals(literals)},transform(to){return Union2(members.map((member,index)=>member.transform(to[index])))}})}var UndefinedOr=lambda((self)=>Union2([self,Undefined2]));function decodeTo2(to,transformation){return(from)=>{return make13(decodeTo(from.ast,to.ast,transformation?makeTransformation(transformation):passthrough2()),{from,to})}}function withConstructorDefault2(defaultValue){return(schema)=>make13(withConstructorDefault(schema.ast,defaultValue),{schema})}function tag(literal){return Literal2(literal).pipe(withConstructorDefault2(succeed6(literal)))}function TaggedStruct(value,fields){return Struct({_tag:tag(value),...fields})}function instanceOf(constructor,annotations){return declare((u)=>u instanceof constructor,annotations)}function link3(){return(encodeTo,transformation)=>{return new Link(encodeTo.ast,makeTransformation(transformation))}}var makeFilter2=makeFilter;function isPattern2(regExp,annotations){const source=regExp.source;const flags=regExp.flags;const canExport=/^[dg]*uy?$/.test(flags);const runtimeRegExp=flags===""?`new RegExp(${format(source)})`:`new RegExp(${format(source)}, ${format(flags)})`;return isPattern(regExp,{toJsonSchema:()=>canExport?{pattern:flags.endsWith("y")?`^(?:${source})`:source}:[{},true],toCode:()=>({runtime:`Schema.isPattern(${runtimeRegExp})`}),...annotations})}function isBase64(annotations){const regExp=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;return isPattern2(regExp,{expected:"a base64 encoded string",representation:{id:"effect/schema/isBase64",payload:null},toJsonSchema:()=>({pattern:regExp.source}),toCode:()=>({runtime:"Schema.isBase64()"}),...annotations})}var Finite=make13(finite);function isInt(annotations){return makeFilter2((n)=>globalThis.Number.isSafeInteger(n),{expected:"an integer",representation:{id:"effect/schema/isInt",payload:null},toJsonSchema:()=>[{type:"integer"},true],toCode:()=>({runtime:"Schema.isInt()"}),arbitraryConstraint:{number:"integer"},...annotations})}var Int=Number5.check(isInt());function isMinLength(minLength,annotations){minLength=normalizeCardinality(minLength);return makeIsMinLength(minLength,Math.ceil(minLength/2),annotations)}function makeIsMinLength(minLength,minCodePoints,annotations){return makeFilter2((input)=>input.length>=minLength,{expected:`a value with a length of at least ${minLength}`,representation:{id:"effect/schema/isMinLength",payload:{minLength}},toJsonSchema:({type})=>type==="string"?minLength<=1?{minLength:minCodePoints}:[{minLength:minCodePoints},true]:type==="array"?{minItems:minLength}:type===undefined?[{minLength:minCodePoints,minItems:minLength},true]:[{},true],toCode:()=>({runtime:`Schema.isMinLength(${minLength})`}),[STRUCTURAL_ANNOTATION_KEY]:true,arbitraryConstraint:{minLength},...annotations})}function normalizeCardinality(value){if(!globalThis.Number.isFinite(value)){throw new globalThis.RangeError(`Expected a finite number, got ${value}`)}return Math.max(0,Math.floor(value))}var RegExp2=instanceOf(globalThis.RegExp,{representation:{id:"effect/schema/RegExp",payload:null},toCode:()=>({runtime:`Schema.RegExp`,Type:`globalThis.RegExp`}),expected:"RegExp",toCodecJson:()=>link3()(Struct({source:String4,flags:String4}),transformEffect2({decode:(e,options)=>try_2({try:()=>new globalThis.RegExp(e.source,e.flags),catch:()=>new InvalidValue({expected:"valid RegExp source and flags"},e,options)}),encode:(regExp)=>succeed6({source:regExp.source,flags:regExp.flags})}))});var URLString=String4.annotate({expected:"a string that will be decoded as a URL"});var URL2=instanceOf(globalThis.URL,{representation:{id:"effect/schema/URL",payload:null},toCode:()=>({runtime:`Schema.URL`,Type:`globalThis.URL`}),expected:"URL",toCodecJson:()=>link3()(URLString,urlFromString)});var JsonString=String4.annotate({expected:"a string that will be decoded as JSON",contentMediaType:"application/json"});function fromJsonString2(schema,options){return JsonString.pipe(decodeTo2(schema,fromJsonString(options)))}var File=instanceOf(globalThis.File,{representation:{id:"effect/schema/File",payload:null},toCode:()=>({runtime:`Schema.File`,Type:`globalThis.File`}),expected:"File",toCodecJson:()=>link3()(Struct({data:String4.check(isBase64()),type:String4,name:String4,lastModified:Int}),transformEffect2({decode:(e,options)=>match2(decode(e.data),{onFailure:()=>fail6(new InvalidValue({expected:"a valid Base64 string"},e.data,options)),onSuccess:(bytes)=>{const buffer=new globalThis.Uint8Array(bytes);return succeed6(new globalThis.File([buffer],e.name,{type:e.type,lastModified:e.lastModified}))}}),encode:(file,options)=>tryPromise2({try:async()=>{const bytes=new globalThis.Uint8Array(await file.arrayBuffer());return{data:encode(bytes),type:file.type,name:file.name,lastModified:file.lastModified}},catch:()=>new InvalidValue({expected:"a readable File"},file,options)})}))});var FormData2=instanceOf(globalThis.FormData,{representation:{id:"effect/schema/FormData",payload:null},toCode:()=>({runtime:`Schema.FormData`,Type:`globalThis.FormData`}),expected:"FormData",toCodecJson:()=>link3()(ArraySchema(Tuple([String4,Union2([Struct({_tag:tag("String"),value:String4}),Struct({_tag:tag("File"),value:File})])])),transformEffect2({decode:(e)=>{const out=new globalThis.FormData;for(const[key,entry]of e){out.append(key,entry.value)}return succeed6(out)},encode:(formData)=>{return succeed6(globalThis.Array.from(formData.entries()).map(([key,value])=>{if(typeof value==="string"){return[key,{_tag:"String",value}]}else{return[key,{_tag:"File",value}]}}))}}))});var URLSearchParams2=instanceOf(globalThis.URLSearchParams,{representation:{id:"effect/schema/URLSearchParams",payload:null},toCode:()=>({runtime:`Schema.URLSearchParams`,Type:`globalThis.URLSearchParams`}),expected:"URLSearchParams",toCodecJson:()=>link3()(String4.annotate({expected:"a query string that will be decoded as URLSearchParams"}),transform2({decode:(e)=>new globalThis.URLSearchParams(e),encode:(params)=>params.toString()}))});var Base64String=String4.annotate({expected:"a base64 encoded string that will be decoded as Uint8Array",format:"byte",contentEncoding:"base64"});var Uint8Array2=instanceOf(globalThis.Uint8Array,{representation:{id:"effect/schema/Uint8Array",payload:null},toCode:()=>({runtime:`Schema.Uint8Array`,Type:`globalThis.Uint8Array`}),expected:"Uint8Array",toCodecJson:()=>link3()(Base64String,uint8ArrayFromBase64String)});var arbitraryMinimumDateTimestamp=-8640000000000000;var arbitraryMaximumDateTimestamp=8640000000000000;var arbitraryMinimumZonedDateTimeTimestamp=arbitraryMinimumDateTimestamp+14*60*60*1000;var arbitraryMaximumZonedDateTimeTimestamp=arbitraryMaximumDateTimestamp-14*60*60*1000;var arbitraryMinimumTimeZoneOffset=-12*60*60*1000;var arbitraryMaximumTimeZoneOffset=14*60*60*1000;function Redacted(value,options){const label=typeof options?.label==="string"?options.label:undefined;const disallowJsonEncode=options?.disallowJsonEncode===true;const normalizedOptions=label!==undefined?disallowJsonEncode?{label,disallowJsonEncode:true}:{label}:disallowJsonEncode?{disallowJsonEncode:true}:undefined;const decodeLabel=label!==undefined?decodeUnknownEffect(Literal2(label)):undefined;const schema=declareConstructor()([value],([value])=>(input,ast,poptions)=>{if(isRedacted(input)){const label=decodeLabel!==undefined?mapErrorEager2(decodeLabel(input.label,poptions),(issue)=>new Pointer(["label"],issue)):void_3;return flatMapEager2(label,()=>mapBothEager2(decodeUnknownEffect(value)(value2(input),poptions),{onSuccess:(value)=>make10(value,{label:input.label}),onFailure:()=>{return new Composite(ast,[new Pointer(["value"],new InvalidValue(undefined,input,poptions))],input,poptions)}}))}return fail6(new InvalidType(ast,input,poptions))},{representation:{id:"effect/schema/Redacted",payload:normalizedOptions??null},toCode:({typeParameters})=>({runtime:normalizedOptions!==undefined?`Schema.Redacted(${typeParameters[0].runtime}, ${format(normalizedOptions)})`:`Schema.Redacted(${typeParameters[0].runtime})`,Type:`Redacted.Redacted<${typeParameters[0].Type}>`,importDeclarations:[`import * as Redacted from "effect/Redacted"`]}),expected:"Redacted",toCodecJson:([value])=>link3()(value,{decode:transform((e)=>make10(e,{label})),encode:disallowJsonEncode?forbidden((oe)=>"Cannot serialize Redacted"+(isSome2(oe)&&typeof oe.value.label==="string"?` with label: "${oe.value.label}"`:"")):transform(value2)}),toEquivalence:([value])=>makeEquivalence(value)});return make13(schema.ast,{value})}var immerable=globalThis.Symbol.for("immer-draftable");var payloadToken={};function makeClass(Inherited,identifier,struct2,annotations,proto){const getClassSchema=getClassSchemaFactory(struct2,identifier,annotations);const ClassTypeId=getClassTypeId(identifier);const out=class extends Inherited{constructor(...[input,options]){const internalOptions=options;const payload=internalOptions?.["~payload"];const value=payload?.token===payloadToken?payload.value:struct2.make(input??{},options);super(value,{...options,disableChecks:true,"~payload":{token:payloadToken,value}})}static[TypeId19]=TypeId19;get[ClassTypeId](){return ClassTypeId}static[immerable]=true;static identifier=identifier;static fields=struct2.fields;static get ast(){return getClassSchema(this).ast}static pipe(){return pipeArguments(this,arguments)}static rebuild(ast){return getClassSchema(this).rebuild(ast)}static make(input,options){return make11(getClassSchema(this))(input??{},options)}static makeOption(input,options){return makeOption(getClassSchema(this))(input??{},options)}static makeEffect(input,options){return getClassSchema(this).makeEffect(input??{},options)}static annotate(annotations){return this.rebuild(annotate(this.ast,annotations))}static annotateKey(annotations){return this.rebuild(annotateKey(this.ast,annotations))}static check(...checks){return this.rebuild(appendChecks(this.ast,checks))}static extend(identifier2){return(schema,annotations)=>{const extension=isStruct(schema)?schema:Struct(schema);const fields={...struct2.fields,...extension.fields};const ast=struct(fields,struct2.ast.checks,{identifier:identifier2});return makeClass(this,identifier2,makeStruct(appendChecks(ast,extension.ast.checks),fields),annotations,proto)}}static mapFields(f,options){return struct2.mapFields(f,options)}};if(proto!==undefined){Object.assign(out.prototype,proto(identifier))}return out}function getClassTransformation(self){return new Transformation(transform((input)=>new self(input,{"~payload":{token:payloadToken,value:input}})),passthrough())}function getClassTypeId(identifier){return`~effect/Schema/Class/${identifier}`}function getClassSchemaFactory(from,identifier,annotations){let memo;return(self)=>{if(memo!==undefined){return memo}const ClassTypeId=getClassTypeId(identifier);const isClassValue=(input)=>input instanceof self||hasProperty(input,ClassTypeId);const transformation=getClassTransformation(self);const to=make13(new Declaration([from.ast],()=>(input,ast,options)=>{return isClassValue(input)?succeed6(input):fail6(new InvalidType(ast,input,options))},{identifier,[CONSTRUCTOR_ANNOTATION_KEY]:([from])=>({isConstructed:isClassValue,link:new Link(from,transformation)}),toCodec:([from])=>new Link(from.ast,transformation),toEquivalence:([from])=>from,toFormatter:([from])=>(t)=>`${self.identifier}(${from(t)})`,[SENTINELS_ANNOTATION_KEY]:collectSentinels(from.ast),...annotations}));return memo=decodeTo2(to,transformation)(from)}}function isStruct(schema){return isSchema(schema)}var Error4=(identifier)=>(schema,annotations)=>{const struct=isStruct(schema)?schema:Struct(schema);const self=makeClass(Error2,identifier,struct,annotations,(identifier)=>({name:identifier}));return self};var TaggedError3=(identifier)=>{return(tagValue,schema,annotations)=>{const struct=isStruct(schema)?schema.mapFields((fields)=>({_tag:tag(tagValue),...fields}),{unsafePreserveChecks:true}):TaggedStruct(tagValue,schema);return Error4(identifier??tagValue)(struct,annotations)}};var toCodecStringTree2=toCodecStringTree;var Json2=make13(annotate(Json,{toCode:()=>({runtime:"Schema.Json",Type:"Schema.Json"})}));var JsonObject=Record(String4,Json2);import{chmodSync as chmodSync2,existsSync as existsSync10,readFileSync as readFileSync8,realpathSync as realpathSync5,renameSync as renameSync2,statSync as statSync3,writeFileSync as writeFileSync6}from"fs";import{hostname}from"os";import{createInterface}from"readline/promises";import{pathToFileURL as pathToFileURL5}from"url";var name="@collective-intelligence/cli";var version="0.1.8";var jsonBodySerializer={bodySerializer:(body)=>JSON.stringify(body,(_key,value)=>typeof value==="bigint"?value.toString():value)};function createSseClient({onRequest,onSseError,onSseEvent,responseTransformer,responseValidator,sseDefaultRetryDelay,sseMaxRetryAttempts,sseMaxRetryDelay,sseSleepFn,url,...options}){let lastEventId;const sleep=sseSleepFn??((ms)=>new Promise((resolve)=>setTimeout(resolve,ms)));const createStream=async function*(){let retryDelay=sseDefaultRetryDelay??3000;let attempt=0;const signal=options.signal??new AbortController().signal;while(true){if(signal.aborted)break;attempt++;const headers=options.headers instanceof Headers?options.headers:new Headers(options.headers);if(lastEventId!==undefined){headers.set("Last-Event-ID",lastEventId)}try{const requestInit={redirect:"follow",...options,body:options.serializedBody??null,headers,signal};let request=new Request(url,requestInit);if(onRequest){request=await onRequest(url,requestInit)}const _fetch=options.fetch??globalThis.fetch;const response=await _fetch(request);if(!response.ok)throw new Error(`SSE failed: ${response.status} ${response.statusText}`);if(!response.body)throw new Error("No body in SSE response");const reader=response.body.pipeThrough(new TextDecoderStream).getReader();let buffer="";const abortHandler=()=>{try{reader.cancel()}catch{}};signal.addEventListener("abort",abortHandler);try{while(true){const{done,value}=await reader.read();if(done)break;buffer+=value;buffer=buffer.replace(/\r\n?/g,`
|
|
240
240
|
`);const chunks=buffer.split(`
|
|
241
241
|
|
|
242
242
|
`);buffer=chunks.pop()??"";for(const chunk of chunks){const lines=chunk.split(`
|
|
@@ -262,7 +262,7 @@ ${prefix}}`}return stack};var FiberTypeId="~effect/Fiber";var fiberVariance={_A:
|
|
|
262
262
|
`}`).join("")};class EnvFileError extends TaggedError3()("EnvFileError",{cause:Unknown2,message:String4}){}var readEnvFileContent=(dependencies,envFile)=>try_2({catch:(cause)=>new EnvFileError({cause,message:`Could not read ${envFile??""}`}),try:()=>envFile===undefined?undefined:dependencies.readEnvFile(envFile)});var writeConnectionValues=(dependencies,output,values)=>gen2(function*writeConnectionValuesEffect(){const{envFile,prefix}=output;if(envFile!==undefined){const current=yield*readEnvFileContent(dependencies,envFile);yield*try_2({catch:(cause)=>new EnvFileError({cause,message:`Could not write ${envFile}`}),try:()=>{dependencies.writeEnvFile(envFile,mergeEnvFile(current,prefix,values))}});dependencies.writeDiagnostic(`Wrote ${values.length} keys to ${envFile}
|
|
263
263
|
`)}return yield*sync2(()=>{if(output.json){dependencies.writeOutput(renderJson(prefix,values))}else if(envFile===undefined){dependencies.writeOutput(renderDotenv(prefix,values))}})});class AppsEnrollCommandError extends TaggedError3()("AppsEnrollCommandError",{cause:optional2(Unknown2),message:String4}){}var EnrollmentRejected=TaggedStruct("ExternalAppEnrollmentRejected",{message:String4,reason:Literals(["application_type_changed","disabled","package_owned"])});var fail12=(message)=>new AppsEnrollCommandError({message});var enrollmentFailure=(fqn)=>(error)=>{if(error.status!==409||!is2(EnrollmentRejected)(error.body)){return fail6(error)}const reasons={application_type_changed:`External App ${fqn} cannot change its type: ${error.body.message}`,disabled:`External App ${fqn} is disabled; re-run ci apps enroll with --enable to enable it`,package_owned:`External App ${fqn} is package-owned; change it through its Extension Package`};return fail6(fail12(reasons[error.body.reason]))};var parseEnrollment=(args)=>gen2(function*parseEnrollmentEffect(){const options=yield*parseCommandOptionsEffect(args,{repeatable:["allowed-origin","post-logout-redirect-uri","redirect-uri","scopes"],switches:["enable","json","rotate-secret"],values:[...targetOptions,"audience","env-file","fqn","name","prefix","primary-redirect-uri","type"]});const fqn=optionValue2(options,"fqn");const redirectUris=optionValues(options,"redirect-uri");const scopes=optionValues(options,"scopes").flatMap((value)=>value.split(/[\s,]+/u).filter((scope)=>scope!==""));if(fqn===undefined){return yield*fail12("Missing required option --fqn; the CLI never derives an FQN")}if(redirectUris.length===0){return yield*fail12("Missing required option --redirect-uri")}if(scopes.length===0){return yield*fail12("Missing required option --scopes")}const type=optionValue2(options,"type")??"public";if(type!=="public"&&type!=="confidential"){return yield*fail12("--type must be public or confidential")}if(type==="public"&&options.switches.has("rotate-secret")){return yield*fail12("--rotate-secret applies to confidential applications only")}const applicationType=type==="confidential"?"confidential":"public";const prefix=optionValue2(options,"prefix")??"CI_";if(!isEnvPrefix(prefix)){return yield*fail12("--prefix must be an environment variable name prefix such as CI_")}const origins=yield*try_2({catch:()=>fail12(`Invalid --redirect-uri in ${redirectUris.join(", ")}`),try:()=>redirectUris.map((uri)=>new URL(uri).origin)});const primaryRedirectUri=optionValue2(options,"primary-redirect-uri");if(primaryRedirectUri!==undefined&&!redirectUris.includes(primaryRedirectUri)){return yield*fail12(`--primary-redirect-uri ${primaryRedirectUri} must be one of the --redirect-uri values`)}const allowedOrigins=optionValues(options,"allowed-origin");const originProblem=allowedOrigins.map((origin)=>exactUrlProblem(origin,"origin")).find((problem)=>problem!==undefined);if(originProblem!==undefined){return yield*fail12(`Invalid --allowed-origin: ${originProblem}`)}const body={allowedOrigins:[...new Set(allowedOrigins.length>0?allowedOrigins:origins)],applicationType,audience:optionValue2(options,"audience")??origins[0]??"",enable:options.switches.has("enable"),name:optionValue2(options,"name")??fqn,postLogoutRedirectUris:[...optionValues(options,"post-logout-redirect-uri")],redirectUris:[...redirectUris],scopes};return{body:primaryRedirectUri===undefined?body:{...body,primaryRedirectUri},envFile:optionValue2(options,"env-file"),fqn,json:options.switches.has("json"),prefix,rotateSecret:options.switches.has("rotate-secret")}});var preflightFailure=(checks)=>fail12(`Enrollment preflight failed; no connection values were written: ${checks.filter((entry)=>!entry.passed).map((entry)=>entry.detail).join("; ")}`);var appsEnrollCommandEffect=(args,dependencies)=>gen2(function*appsEnrollCommand(){const enrollment=yield*parseEnrollment(args);const context=yield*resolveOrganizationContext({args,environment:dependencies.environment,fetch:dependencies.fetch});const request={client:context.client,headers:{"x-organization-id":context.organizationId}};const explainForbidden=explainOrganizationForbidden(context,context.organizationId);const tenant=yield*runTenantPreflight({context,fetch:dependencies.fetch});const{discovery}=tenant;if(tenant.checks.some((entry)=>!entry.passed)||discovery===undefined){dependencies.writeDiagnostic(renderPreflight(tenant.checks));return yield*preflightFailure(tenant.checks)}yield*readEnvFileContent(dependencies,enrollment.envFile);const enrolled=yield*managementData("Enrollment",organizationExternalAppsEnroll,{...request,body:enrollment.body,path:{fqn:enrollment.fqn}}).pipe(catchTag2("ManagementRequestError",enrollmentFailure(enrollment.fqn)),catchTag2("ManagementRequestError",explainForbidden));const{application}=enrolled;dependencies.writeDiagnostic(`${enrolled.created?"Created":"Updated"} External App ${application.fqn}: Application Id ${application.id}, Client Id ${application.clientId}
|
|
264
264
|
`);const redirect=yield*runRedirectPreflight({context,fqn:application.fqn,redirectUris:application.redirectUris});if(!redirect.passed){dependencies.writeDiagnostic(renderPreflight([redirect]));return yield*preflightFailure([redirect])}const secretKey=`${enrollment.prefix}CLIENT_SECRET`;const existingContent=yield*readEnvFileContent(dependencies,enrollment.envFile);const confidentialSecret=gen2(function*confidentialSecretEffect(){if(enrolled.clientSecret!==undefined){return enrolled.clientSecret}if(enrollment.rotateSecret){const rotated=yield*managementData("Client secret rotation",organizationExternalAppsRotateCredential,{...request,path:{id:application.id}}).pipe(catchTag2("ManagementRequestError",explainForbidden));return rotated.clientSecret}const savedSecret=envFileValue(existingContent,secretKey);const envFileName=enrollment.envFile??"an --env-file";if(savedSecret===undefined){return yield*fail12(`External App ${application.fqn} is confidential and ${secretKey} is not in ${envFileName}; re-run with --rotate-secret to issue a new client secret`)}if(!savedSecretMatches(existingContent,enrollment.prefix,{clientId:application.clientId,issuer:discovery.issuer})){return yield*fail12(`External App ${application.fqn} is confidential and the ${secretKey} in ${envFileName} is not for Client Id ${application.clientId} at ${discovery.issuer}; re-run with --rotate-secret to issue a new client secret`)}return savedSecret});const clientSecret=application.applicationType==="confidential"?yield*confidentialSecret:undefined;return yield*writeConnectionValues(dependencies,{envFile:enrollment.envFile,json:enrollment.json,prefix:enrollment.prefix},connectionValues({application,clientSecret,discovery,organizationId:context.organizationId}))}).pipe(mapError2((cause)=>is2(AppsEnrollCommandError)(cause)?cause:new AppsEnrollCommandError({cause,message:cause.message})));class AppsEnvCommandError extends TaggedError3()("AppsEnvCommandError",{cause:optional2(Unknown2),message:String4}){}var usage3="Usage: ci apps env <application> [--env-file <path>] [--prefix <PREFIX_>] [--json] (<application> is an Application Id or FQN)";var fail13=(message)=>new AppsEnvCommandError({message});var parseEnv=(args)=>gen2(function*parseEnvEffect(){const options=yield*parseCommandOptionsEffect(args,{positionals:1,switches:["json"],values:[...targetOptions,"env-file","prefix"]});const[reference]=options.positionals;if(reference===undefined){return yield*fail13(usage3)}const prefix=optionValue2(options,"prefix")??"CI_";if(!isEnvPrefix(prefix)){return yield*fail13("--prefix must be an environment variable name prefix such as CI_")}return{envFile:optionValue2(options,"env-file"),json:options.switches.has("json"),prefix,reference}});var appsEnvCommandEffect=(args,dependencies)=>gen2(function*appsEnvCommand(){const command=yield*parseEnv(args);const{envFile,prefix}=command;const context=yield*resolveOrganizationContext({args,environment:dependencies.environment,fetch:dependencies.fetch});const application=yield*readApplication(context,command.reference).pipe(catchTag2("ManagementRequestError",explainOrganizationForbidden(context,context.organizationId)));const discovery=yield*readTenantDiscovery(dependencies.fetch,context.target.apiOrigin);const existingContent=yield*readEnvFileContent(dependencies,envFile);const secretKey=`${prefix}CLIENT_SECRET`;const confidential=application.applicationType==="confidential";const savedSecret=confidential?envFileValue(existingContent,secretKey):undefined;if(savedSecret!==undefined&&!savedSecretMatches(existingContent,prefix,{clientId:application.clientId,issuer:discovery.issuer})){return yield*fail13(`The ${secretKey} in ${envFile??"the --env-file"} is not for Client Id ${application.clientId} at ${discovery.issuer}; nothing was written. Remove it or choose another --env-file`)}if(confidential&&savedSecret===undefined){dependencies.writeDiagnostic(`External App ${application.fqn} is confidential: ${secretKey} is not included, because a client secret is shown only once. Use the secret you saved, or run ci apps rotate-secret ${application.id} to issue a new one
|
|
265
|
-
`)}return yield*writeConnectionValues(dependencies,{envFile,json:command.json,prefix},connectionValues({application,clientSecret:savedSecret,discovery,organizationId:context.organizationId}))}).pipe(mapError2((cause)=>is2(AppsEnvCommandError)(cause)?cause:new AppsEnvCommandError({cause,message:cause.message})));var compareCodePoints=(left,right)=>{const leftPoints=Array.from(left,(character)=>character.codePointAt(0)??0);const rightPoints=Array.from(right,(character)=>character.codePointAt(0)??0);const length=Math.min(leftPoints.length,rightPoints.length);for(let index=0;index<length;index+=1){const difference=leftPoints[index]-rightPoints[index];if(difference!==0){return difference}}return leftPoints.length-rightPoints.length};var insertSortedKey=(keys,key)=>{let index=0;while(index<keys.length&&compareCodePoints(keys[index]??"",key)<=0){index+=1}keys.splice(index,0,key)};var isJsonObject=(value)=>Object.prototype.toString.call(value)==="[object Object]"&&!Array.isArray(value)&&(Object.getPrototypeOf(value)===Object.prototype||Object.getPrototypeOf(value)===null);var isJsonArray=(value)=>Array.isArray(value);var canonicalize=(value,ancestors,_valueType)=>{if(value===null){return"null"}if(isJsonArray(value)){if(ancestors.has(value)){throw new TypeError("package declarations cannot contain cyclic values")}ancestors.add(value);try{return`[${value.map((item)=>canonicalize(item,ancestors)).join(",")}]`}finally{ancestors.delete(value)}}if(isJsonObject(value)){if(ancestors.has(value)){throw new TypeError("package declarations cannot contain cyclic values")}ancestors.add(value);try{const record=value;const keys=[];for(const key of Object.keys(record)){insertSortedKey(keys,key)}return`{${keys.map((key)=>`${JSON.stringify(key)}:${canonicalize(record[key],ancestors)}`).join(",")}}`}finally{ancestors.delete(value)}}if(value instanceof Object){throw new TypeError("package declarations must contain JSON-compatible values")}switch(Object.prototype.toString.call(value)){case"[object Boolean]":{return value===true?"true":"false"}case"[object Number]":{const number=Number(value);if(!Number.isFinite(number)){throw new TypeError("package declarations cannot contain non-finite numbers")}return JSON.stringify(number)}case"[object String]":{return JSON.stringify(String(value))}default:{throw new TypeError("package declarations must contain JSON-compatible values")}}};var canonicalJson=(value,..._typeEvidence)=>canonicalize(value,new WeakSet);var parseJsonObject=(source)=>{const value=JSON.parse(source);if(!isJsonObject(value)){throw new TypeError("expected a JSON object")}return value};var compareUtf16CodeUnits=(left,right)=>{const length=Math.min(left.length,right.length);for(let index=0;index<length;index+=1){const difference=left.charCodeAt(index)-right.charCodeAt(index);if(difference!==0){return difference}}return left.length-right.length};var plainFormWidgets=["checkbox","color","date","date_range","datetime","email","file","hidden","number","password","structured_file_preview","switch","text","textarea","variable_references"];var selectFormWidgets=["folders_explorer","multi_select","radio","select"];var invalid4=(path)=>{throw new TypeError(`Invalid package manifest at ${path}`)};var string3=(v,p)=>typeof v==="string"?v:invalid4(p);var identity2=(v,p)=>{const s=string3(v,p);return s.trim()===""?invalid4(p):s};var hostedIdentity=(value,path)=>{const text=identity2(value,path);return text===text.trim()?text:invalid4(path)};var assertDenseArrays=(value,path,seen)=>{if(typeof value!=="object"||value===null||seen.has(value)){return}seen.add(value);if(Array.isArray(value)){for(let index=0;index<value.length;index+=1){if(!Object.hasOwn(value,index)){invalid4(`${path}/${index}`)}}}for(const[key,child]of Object.entries(value)){assertDenseArrays(child,`${path}/${key}`,seen)}};var boolean2=(v,p)=>typeof v==="boolean"?v:invalid4(p);var number3=(v,p)=>typeof v==="number"&&Number.isFinite(v)?v:invalid4(p);var positiveSafeInteger=(value,path)=>{const parsed=number3(value,path);return Number.isSafeInteger(parsed)&&parsed>0?parsed:invalid4(path)};var optional3=(read)=>(v,p)=>v===undefined?undefined:read(v,p);var nullable=(read)=>(v,p)=>v===null?null:read(v,p);var literal=(...values)=>(v,p)=>{for(const value of values){if(v===value){return value}}return invalid4(p)};var array2=(read)=>(v,p)=>{if(!Array.isArray(v)){return invalid4(p)}return v.map((item,index)=>read(item,`${p}/${index}`))};var record2=(read)=>(v,p)=>{if(typeof v!=="object"||v===null||Array.isArray(v)){return invalid4(p)}return Object.fromEntries(Object.entries(v).map(([key,value])=>[key,read(value,`${p}/${key}`)]))};var object=(fields)=>(v,p)=>{if(typeof v!=="object"||v===null||Array.isArray(v)){return invalid4(p)}const entries=Object.entries(v);for(const key in fields){if(!Object.hasOwn(fields,key)){continue}fields[key](entries.find(([name])=>name===key)?.[1],`${p}/${key}`)}return v};var refine=(read,violation)=>(v,p)=>{const value=read(v,p);return violation(value)===undefined?value:invalid4(p)};var strings=array2(string3);var optString=optional3(string3);var optBoolean=optional3(boolean2);var optNumber=optional3(number3);var optStrings=optional3(strings);var json=(v)=>parseJsonObject(canonicalJson({value:v})).value;var jsonObject=record2(json);var base={description:optString,displayName:string3,fqn:identity2,icon:optString,tags:optStrings,version:string3};var union2=(left,right)=>(v,p)=>{try{return left(v,p)}catch(error){if(!(error instanceof TypeError)){throw error}return right(v,p)}};var schemaDocument=(v,p)=>{const doc=jsonObject(v,p);const schemaType=literal("array","boolean","integer","null","number","object","string");const fields={$anchor:optString,$comment:optString,$defs:optional3(record2(schemaDocument)),$dynamicAnchor:optString,$dynamicRef:optString,$id:optString,$ref:optString,$schema:optional3(literal("https://json-schema.org/draft/2020-12/schema")),additionalProperties:optional3(union2(boolean2,schemaDocument)),allOf:optional3(array2(schemaDocument)),anyOf:optional3(array2(schemaDocument)),const:optional3(json),contains:optional3(schemaDocument),default:optional3(json),dependentRequired:optional3(record2(strings)),description:optString,else:optional3(schemaDocument),enum:optional3(array2(json)),exclusiveMaximum:optNumber,exclusiveMinimum:optNumber,format:optString,if:optional3(schemaDocument),items:optional3(schemaDocument),maxItems:optNumber,maxLength:optNumber,maxProperties:optNumber,maximum:optNumber,minItems:optNumber,minLength:optNumber,minProperties:optNumber,minimum:optNumber,multipleOf:optNumber,not:optional3(schemaDocument),oneOf:optional3(array2(schemaDocument)),pattern:optString,patternProperties:optional3(record2(schemaDocument)),prefixItems:optional3(array2(schemaDocument)),properties:optional3(record2(schemaDocument)),required:optStrings,then:optional3(schemaDocument),title:optString,type:optional3(union2(schemaType,array2(schemaType))),unevaluatedItems:optional3(union2(boolean2,schemaDocument)),unevaluatedProperties:optional3(union2(boolean2,schemaDocument)),uniqueItems:optBoolean};return object(fields)(doc,p)};var schema2=object({dialect:literal("https://json-schema.org/draft/2020-12/schema"),document:schemaDocument,fidelity:literal("exact","structural")});var visibility=object({equals:optional3(json),field:string3,in:optional3(array2(json)),isNotSet:optBoolean,isSet:optBoolean,notEquals:optional3(json),notIn:optional3(array2(json))});var visibilityRule=object({logic:optional3(literal("and","or")),visibleWhen:union2(visibility,array2(visibility))});var validationRule=(v,p)=>{const{type}=object({type:string3})(v,p);const messages={code:optString,message:optString};switch(type){case"min_length":case"max_length":case"min":case"max":{return object({...messages,type:literal(type),value:number3})(v,p)}case"pattern":{return object({...messages,type:literal(type),value:string3})(v,p)}case"required":{return object({...messages,type:literal("required")})(v,p)}default:{return object({...messages,type:literal("integer","json","non_empty_array")})(v,p)}}};var selectOption=object({label:optString,locked:optBoolean,value:string3});var selectOptions=object({aiFill:optional3(object({buttonLabel:optString,prompt:string3,retryable:optBoolean})),allowClear:optBoolean,allowCustom:optBoolean,dataSource:optString,dependencies:optStrings,options:optional3(array2(union2(string3,selectOption))),preventSaveWhenEmpty:optBoolean,readonlyOnUpdate:optBoolean,searchable:optBoolean,selectionMetadataField:optString,submit:optBoolean});var fieldUiBase={"ui:disabled":optBoolean,"ui:help":optString,"ui:order":optNumber,"ui:placeholder":optString,"ui:readonly":optBoolean,"ui:suggestedName":optString,"ui:validation":optional3(array2(validationRule))};var absent=(v,p)=>v===undefined?undefined:invalid4(p);var plainFieldUi=object({...fieldUiBase,"ui:options":absent,"ui:widget":literal(...plainFormWidgets)});var selectFieldUi=object({...fieldUiBase,"ui:options":optional3(selectOptions),"ui:widget":optional3(literal(...selectFormWidgets))});var structuredFileUploadFieldUi=object({...fieldUiBase,"ui:options":optional3(object({formatField:optString})),"ui:widget":literal("structured_file_upload")});var structuredFileBrowserFieldUi=object({...fieldUiBase,"ui:options":object({contribution:object({componentFqn:string3,connectionSlot:string3}),formatField:optString,label:optString}),"ui:widget":literal("structured_file_browser")});var fieldUi=union2(union2(plainFieldUi,selectFieldUi),union2(structuredFileUploadFieldUi,structuredFileBrowserFieldUi));var formItems=array2(union2(string3,object({md:string3})));var form=object({createSteps:optional3(array2(object({description:optional3(nullable(string3)),id:string3,includeInBasicInfo:optional3(nullable(boolean2)),items:formItems,title:string3,visibility:optional3(nullable(visibilityRule))}))),layout:optional3(literal("stacked","two_column")),schema:schema2,uiSchema:optional3(record2(fieldUi)),updateSections:optional3(array2(object({description:optional3(nullable(string3)),items:formItems,layout:optional3(nullable(literal("stacked","two_column"))),title:optional3(nullable(string3))}))),visibility:optional3(record2(visibilityRule))});var closedGatewayObject=(fields)=>refine(object(fields),(value)=>Object.keys(value).some((key)=>!Object.hasOwn(fields,key))?"unexpected Gateway field":undefined);var identifier2=refine(string3,(value)=>/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/u.test(value)?undefined:"invalid identifier");var version2=refine(string3,(value)=>value.length>0&&value.length<=128&&value.trim()===value?undefined:"invalid version");var bounded2=(maximum,minimum=1)=>refine(number3,(value)=>Number.isSafeInteger(value)&&value>=minimum&&value<=maximum?undefined:"invalid limit");var unique=(read,key)=>refine(read,(values)=>new Set(values.map(key)).size===values.length?undefined:"duplicate identifier");var projection=refine(schema2,(value)=>(value.fidelity==="exact"||value.fidelity==="structural")&&Object.keys(value).every((key)=>key==="dialect"||key==="document"||key==="fidelity")?undefined:"unsupported Gateway projection");var authorization=closedGatewayObject({delegatedSubject:literal("allowed","forbidden","required"),organization:literal("required"),principalKinds:refine(unique(array2(literal("detached_user","service_principal")),(kind)=>kind),(values)=>values.length>0?undefined:"empty principalKinds"),scopes:unique(array2(refine(string3,(value)=>value.length>0&&value.length<=256?undefined:"invalid scope")),(scope)=>scope)});var operationFields={authorization,description:string3,effects:literal("external_side_effect","read","write"),execution:closedGatewayObject({mode:literal("synchronous"),timeoutMs:bounded2(3600000)}),id:identifier2,idempotency:literal("idempotent","requires_key","safe"),input:projection,limits:closedGatewayObject({maxRequestBytes:bounded2(16777216),maxResponseBytes:bounded2(16777216)}),output:projection,retry:union2(closedGatewayObject({mode:literal("never")}),closedGatewayObject({maxAttempts:bounded2(10,2),mode:literal("idempotent_only")})),title:string3,version:version2};var operationReader=closedGatewayObject(operationFields);var domainFields={description:optional3(string3),displayOrder:optional3(number3),icon:optional3(string3),id:identifier2,tags:optional3(strings),title:string3};var domainsReader=unique(array2(closedGatewayObject({...domainFields,operations:unique(array2(operationReader),(operation)=>operation.id)})),(domain)=>domain.id);var inputReader=closedGatewayObject({id:identifier2,operationDomains:domainsReader,version:version2});var empty4=refine(array2(identity2),(values)=>values.length===0?undefined:"operation-only Gateway required");var emptyReader=(value,path)=>{empty4(value,path);return[]};var disabled=(value,path)=>boolean2(value,path)===false?false:invalid4(path);var contractReader=closedGatewayObject({capabilities:closedGatewayObject({resources:disabled}),datasets:emptyReader,id:identifier2,knowledge:emptyReader,operationDomains:unique(array2(closedGatewayObject({...domainFields,operations:unique(array2(closedGatewayObject({...operationFields,canonicalReference:string3})),(operation)=>operation.id)})),(domain)=>domain.id),organizationBinding:closedGatewayObject({mode:literal("installed_organization")}),protocolVersion:literal("2"),version:version2});var buildOperationGatewayContract=(input)=>{assertDenseArrays(input,"gateway",new WeakSet);canonicalJson(input);const admitted=inputReader(input,"gateway");return{capabilities:{resources:false},datasets:[],id:admitted.id,knowledge:[],operationDomains:admitted.operationDomains.map((domain)=>({...domain,operations:domain.operations.map((operation)=>({...operation,canonicalReference:`${admitted.id}/${domain.id}/${operation.id}@${operation.version}`})).sort((a,b)=>compareUtf16CodeUnits(a.id,b.id))})).sort((a,b)=>compareUtf16CodeUnits(a.id,b.id)),organizationBinding:{mode:"installed_organization"},protocolVersion:"2",version:admitted.version}};var readOperationGatewayContract=(value,path)=>{assertDenseArrays(value,path,new WeakSet);const admitted=contractReader(value,path);const normalized=buildOperationGatewayContract({id:admitted.id,operationDomains:admitted.operationDomains.map((domain)=>({...domain,operations:domain.operations.map(({canonicalReference:_reference,...operation})=>operation)})),version:admitted.version});if(canonicalJson(admitted)!==canonicalJson(normalized)){invalid4(path)}return normalized};var deepFreeze=(value)=>{if(value!==null&&typeof value==="object"&&!Object.isFrozen(value)){Object.freeze(value);for(const child of Object.values(value)){deepFreeze(child)}}return value};var SchemaConsumerProfiles=Object.freeze({automationGraphInput:"workflow_value",automationGraphOutput:"workflow_value",connectionCredential:"interactive_form",connectorSettings:"interactive_form",form:"interactive_form",knowledgeEntity:"knowledge_record",knowledgeRelation:"knowledge_record",notificationCredential:"interactive_form",studioComponentProps:"studio_props",toolInput:"ai_function_input",toolOutput:"runtime_json",toolSettings:"interactive_form",workflowConfiguration:"workflow_value",workflowFieldValue:"workflow_value",workflowInput:"workflow_value",workflowOutput:"workflow_value",workflowPortValue:"workflow_value"});var annotationKeywords=["$anchor","$comment","$id","$schema","$vocabulary","deprecated","description","examples","readOnly","title","writeOnly"];var structuralKeywords=["$defs","$ref","additionalProperties","const","enum","items","properties","required","type"];var boundKeywords=["exclusiveMaximum","exclusiveMinimum","maxItems","maxLength","maxProperties","maximum","minItems","minLength","minProperties","minimum","multipleOf","pattern","uniqueItems"];var UnrestrictedScopeKeyword="x-unrestricted-scope";var baseProfileKeywords=[...annotationKeywords,...structuralKeywords,...boundKeywords];var ConsumerProfiles=deepFreeze({ai_function_input:{allowedFidelity:["exact","structural"],allowedKeywords:[...baseProfileKeywords,"anyOf"],id:"ai_function_input",rootObject:true,unsupportedKeywords:["$dynamicRef","$dynamicAnchor","allOf","oneOf","not","patternProperties","prefixItems","contains","dependentRequired","if","then","else","unevaluatedItems","unevaluatedProperties"]},interactive_form:{allowedFidelity:["exact"],allowedKeywords:[...baseProfileKeywords,"anyOf","default","format",UnrestrictedScopeKeyword],id:"interactive_form",rootObject:true,unsupportedKeywords:["$dynamicRef","$dynamicAnchor","allOf","oneOf","not","patternProperties","contains","dependentRequired","if","then","else","prefixItems","unevaluatedItems","unevaluatedProperties"]},knowledge_record:{allowedFidelity:["exact","structural"],allowedKeywords:[...baseProfileKeywords,"format"],id:"knowledge_record",rootObject:true,unsupportedKeywords:["$dynamicRef","$dynamicAnchor","allOf","anyOf","oneOf","not","patternProperties","prefixItems","contains","dependentRequired","if","then","else","unevaluatedItems","unevaluatedProperties"]},runtime_json:{allowedFidelity:["exact","structural"],allowedKeywords:null,id:"runtime_json",rootObject:false,unsupportedKeywords:["$dynamicRef","$dynamicAnchor"]},studio_props:{allowedFidelity:["exact"],allowedKeywords:[...baseProfileKeywords,"anyOf","default","format"],id:"studio_props",rootObject:true,unsupportedKeywords:["$dynamicRef","$dynamicAnchor","allOf","oneOf","not","patternProperties","contains","dependentRequired","if","then","else","prefixItems","unevaluatedItems","unevaluatedProperties"]},workflow_value:{allowedFidelity:["exact","structural"],allowedKeywords:[...baseProfileKeywords,"default","format","oneOf"],id:"workflow_value",rootObject:false,unsupportedKeywords:["$dynamicRef","$dynamicAnchor","allOf","anyOf","not","unevaluatedItems","unevaluatedProperties"]}});var knownVocabularies=new Set(["https://json-schema.org/draft/2020-12/vocab/applicator","https://json-schema.org/draft/2020-12/vocab/content","https://json-schema.org/draft/2020-12/vocab/core","https://json-schema.org/draft/2020-12/vocab/format-annotation","https://json-schema.org/draft/2020-12/vocab/format-assertion","https://json-schema.org/draft/2020-12/vocab/meta-data","https://json-schema.org/draft/2020-12/vocab/unevaluated","https://json-schema.org/draft/2020-12/vocab/validation"]);var schemaArrayKeywords=new Set(["allOf","anyOf","oneOf","prefixItems"]);var schemaMapKeywords=new Set(["$defs","patternProperties","properties"]);var schemaValueKeywords=new Set(["additionalProperties","contains","else","if","items","not","then","unevaluatedItems","unevaluatedProperties"]);var workflowBindingKey=(binding)=>canonicalJson({path:binding.path,target:binding.target});var renderWorkflowBinding=(binding)=>`${binding.target}:${binding.path.join(".")}`;var isConnectionCount=(value)=>value===undefined||value===null||Number.isSafeInteger(value)&&value>=0;var workflowPortPolicyViolation=(port)=>{if(!isConnectionCount(port.minConnections)||!isConnectionCount(port.maxConnections)){return"connection counts must be non-negative integers"}const max=port.maxConnections===undefined?1:port.maxConnections;if(max!==null&&(port.minConnections??0)>max){return"minConnections cannot exceed maxConnections"}if(port.allowedTemplateKinds?.length===0){return"allowedTemplateKinds cannot be empty"}if(port.allowedTemplateFqns?.length===0){return"allowedTemplateFqns cannot be empty"}if(port.schemaResolution?.variants.length===0){return"schemaResolution requires variants"}return};var firstDuplicate=(values)=>values.find((value,index)=>values.indexOf(value)!==index);var workflowEditorViolation=(editor)=>{const sections=editor.form?.sections??[];const duplicateSection=firstDuplicate(sections.flatMap((section)=>section.id===undefined?[]:[section.id]));if(duplicateSection!==undefined){return`workflow editor section id '${duplicateSection}' is not unique`}const fields=sections.flatMap((section)=>section.fields??[]);const keys=fields.map((field)=>workflowBindingKey(field.binding));const duplicateField=fields.find((field,index)=>keys.indexOf(workflowBindingKey(field.binding))!==index);if(duplicateField!==undefined){return`workflow editor binding ${renderWorkflowBinding(duplicateField.binding)} is not unique`}for(const field of fields){const references=[...(field.visibleWhen??[]).map((rule)=>rule.binding),...field.optionSource?.kind==="remote"?field.optionSource.dependsOn:[]];const dangling=references.find((reference)=>!keys.includes(workflowBindingKey(reference)));if(dangling!==undefined){return`workflow editor field ${renderWorkflowBinding(field.binding)} references unknown binding ${renderWorkflowBinding(dangling)}`}}return};var metadata=object({available:boolean2,label:string3});var connection=object({...base,compatibility:optional3(object({auth:optString,dialect:optString,extensions:optional3(jsonObject),provider:optString})),creationMode:optional3(literal("self_service","registration_only")),credential:form,defaultConnectionName:string3,discoveryMetadata:optional3(metadata),kind:literal("connection"),providerFamily:string3,secretFields:optStrings,testMetadata:optional3(metadata)});var pathParts=array2(union2(string3,number3));var bindingModes=array2(literal("external","managed"));var syncModes=array2(literal("delta","full"));var bindingScopes=array2(literal("organization","tenant"));var mutationPolicy=literal("always","connector_backed","never");var extraProps=literal("ignore","import","inline");var outboundStrategy=literal("local_first","remote_first");var updateMode=literal("full","partial");var localized=object({fallbackLocale:string3,values:record2(string3)});var catalogTags=optional3(record2(strings));var connectionRefs=optional3(array2(object({catalogCollection:optString,connectionTemplateFqn:string3,label:string3,required:optBoolean,slot:string3,visibleWhen:optional3(visibility)})));var fieldMap=(v,p)=>{const common={direction:literal("both","inbound","outbound"),local:string3,skipIfNull:boolean2};const{op}=object({op:string3})(v,p);switch(op){case"path":{return object({...common,op:literal(op),remote:string3})(v,p)}case"cast":{return object({...common,falseValues:optStrings,op:literal(op),remote:string3,trueValues:optStrings})(v,p)}case"default":{return object({...common,op:literal(op),remote:optString,value:json})(v,p)}case"concat":{return object({...common,op:literal(op),remote:strings,separator:optString})(v,p)}case"split":{return object({...common,discardEmpty:optBoolean,op:literal(op),remote:string3,separators:optStrings,trimItems:optBoolean,uniqueItems:optBoolean})(v,p)}case"coordinates":{return object({...common,latitudeKey:optString,longitudeKey:optString,op:literal(op),remote:(value,location)=>{const parts=strings(value,location);if(parts.length!==2){return invalid4(location)}return[string3(parts[0],location),string3(parts[1],location)]}})(v,p)}case"transform":{return object({...common,op:literal(op),remote:string3,transformerId:string3})(v,p)}default:{return invalid4(`${p}/op`)}}};var predefinedExtras=optional3(array2(object({displayName:nullable(string3),enabled:boolean2,id:string3,includeInEntityEmbedding:boolean2,kind:literal("linked_text","file_source"),slotKey:string3,source:jsonObject})));var predefinedSchedules=optional3(array2(object({cronExpression:string3,enabled:optBoolean,importMode:optional3(literal("delta","full")),label:optString,rationale:optString,timezone:optString})));var schemaCapability={extraPropsMode:optional3(extraProps),fieldMap:optional3(array2(fieldMap)),fqn:string3,outboundStrategy:optional3(outboundStrategy),predefinedBindingExtras:predefinedExtras,predefinedBindingKey:optString,predefinedBindingMode:optional3(literal("external","managed")),predefinedBindingRemoteCollectionId:optString,predefinedBindingRemoteCollectionName:optString,predefinedSchedules,supportedSyncModes:optional3(syncModes),supportsInbound:optBoolean,supportsOutbound:optBoolean,syncIntervalSeconds:optional3(nullable(number3)),updateMode:optional3(updateMode)};var entityCapability=object({...schemaCapability,predefinedBindingParentKey:optString,supportedBindingModes:optional3(bindingModes)});var relationCapability=object({...schemaCapability,predefinedBindingParentEntityKey:optString,predefinedBindingRelationImportMode:optional3(literal("child_binding","relation_only")),predefinedBindingSourceEntityKey:optString,predefinedBindingTargetEntityKey:optString});var discoveryDefaults=object({extraPropsMode:extraProps,outboundStrategy,supportedBindingModes:bindingModes,supportedSyncModes:syncModes,supportsInbound:boolean2,supportsOutbound:boolean2,syncIntervalSeconds:nullable(number3),updateMode});var datasetCapabilities=object({aggregates:array2(literal("count","count_distinct","sum","min","max","avg")),definitionRefresh:boolean2,grouping:boolean2,intents:array2(literal("records","aggregate","time_series")),limits:object({maxBytes:number3,maxPageRows:number3,maxRows:number3,timeoutMs:number3}),ordering:boolean2,pagination:boolean2,predicates:array2(literal("eq","ne","lt","lte","gt","gte","in","not_in","is_null","is_not_null","contains","starts_with"))});var fieldSemantics=object({defaultSearch:optBoolean,embedded:optBoolean,faceted:optBoolean,indexContent:optBoolean,indexOverview:optBoolean,indexed:optBoolean,managedProjectionSource:optional3(literal("organization_group","organization_user")),queryGuidance:optString,unique:optBoolean});var managedProjection=object({connectorPolicy:literal("allow","deny_schema"),genericMutationPolicy:literal("deny_managed_fields","deny_schema"),kind:literal("directory_person","directory_person_in_group","directory_group","directory_group_parent"),source:literal("organization_group","organization_group_hierarchy","organization_group_membership","organization_user")});var fieldLocalization=object({description:optional3(localized),help:optional3(localized),label:optional3(localized),placeholder:optional3(localized)});var fieldPresentation=object({copyable:optBoolean,editor:optString,editorOptions:optional3(object({accepts:optStrings,allowCustomValues:optBoolean,autocomplete:optString,clearable:optBoolean,falseLabel:optString,multiple:optBoolean,options:optional3(array2(object({label:string3,value:string3}))),rows:optNumber,searchable:optBoolean,showButtons:optBoolean,spellcheck:optBoolean,step:optNumber,trueLabel:optString})),emptyLabel:optString,falseLabel:optString,hidden:optBoolean,layout:optional3(object({column:optNumber,labelPlacement:optional3(literal("left","top")),order:optNumber,row:optNumber,width:optional3(union2(number3,literal("full")))})),maxLines:optNumber,readOnly:optBoolean,renderer:optString,trueLabel:optString});var lifecycle=object({deployMode:literal("init_only","upsert"),readonly:boolean2});var autocompleteConfiguration=object({autocompleteFields:array2(object({field:string3,scope:literal("data","entity")})),defaultAutocompleteFields:array2(object({field:string3,scope:literal("data","entity")}))});var knowledgeSchema={catalogTags,domainFqn:string3,fieldLocalization:optional3(record2(fieldLocalization)),fieldPresentation:optional3(record2(fieldPresentation)),fieldSemantics:optional3(record2(fieldSemantics)),localMutationPolicy:optional3(mutationPolicy),managedProjection:optional3(managedProjection),schema:schema2};var policyRef=(value,path)=>{const{kind}=object({kind:string3})(value,path);return kind==="literal"?object({kind:literal("literal"),value:json})(value,path):object({kind:literal("subject","resource"),path:strings})(value,path)};var uuid=(value,path)=>{const parsed=identity2(value,path);return/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu.test(parsed)?parsed:invalid4(path)};var policyPredicate=(value,path)=>{const{op}=object({op:string3})(value,path);switch(op){case"eq":case"neq":case"lt":case"lte":case"gt":case"gte":{return object({left:policyRef,op:literal("eq","neq","lt","lte","gt","gte"),right:policyRef})(value,path)}case"in":{return object({op:literal("in"),set:policyRef,value:policyRef})(value,path)}case"exists":case"is_null":{return object({op:literal("exists","is_null"),ref:policyRef})(value,path)}case"contains":case"starts_with":{return object({op:literal("contains","starts_with"),ref:policyRef,value:policyRef})(value,path)}case"const":{return object({op:literal("const"),value:boolean2})(value,path)}case"not":{return object({arg:policyPredicate,op:literal("not")})(value,path)}case"and":case"or":{return object({args:array2(policyPredicate),op:literal("and","or")})(value,path)}case"relation_exists":{return object({direction:literal("out","in"),op:literal("relation_exists"),relationSchemaId:uuid})(value,path)}case"relation_field":{return object({direction:literal("out","in"),inner:policyPredicate,op:literal("relation_field"),relationSchemaId:uuid})(value,path)}default:{return invalid4(`${path}/op`)}}};var policyBody=object({rule:optional3(policyPredicate),subjectMatch:policyPredicate});var policyFields={effect:literal("allow","deny"),policyBody,policyType:literal("filter","gate"),targetFqn:identity2,targetKind:literal("entity_domain","entity_schema","relation_domain","relation_schema")};var connection2=refine(object({setupKey:identity2}),(value)=>Object.keys(value).some((key)=>key!=="setupKey")?"install-only input":undefined);var bindingFields={executionRole:optional3(literal("root","child")),extraPropsMode:optional3(literal("ignore","import","inline")),extras:refine(predefinedExtras,(extras)=>extras?.some((extra)=>!/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu.test(extra.id))?"invalid extra UUID":undefined),fieldMap:optional3(array2(fieldMap)),key:identity2,outboundStrategy:optional3(literal("local_first","remote_first")),parentKey:optional3(nullable(identity2)),remoteCollectionId:optional3(nullable(string3)),remoteCollectionName:optional3(nullable(string3)),supportedSyncModes:optional3(array2(literal("delta","full"))),supportsInbound:optBoolean,supportsOutbound:optBoolean,syncIntervalSeconds:optional3(nullable(positiveSafeInteger)),updateMode:optional3(literal("full","partial"))};var entityBinding=object({...bindingFields,bindingMode:literal("managed","external"),missingConnectorFieldsBehavior:optional3(literal("prune","retain")),pushEntityMatch:optional3(literal("remote_ref","unique_fields")),schemaFqn:identity2,supportedBindingModes:optional3(array2(literal("managed","external"))),suppressEntityEvents:optBoolean});var relationBinding=object({...bindingFields,bindingMode:optional3(literal("managed")),relationImportMode:optional3(literal("child_binding","relation_only")),relationSchemaFqn:identity2,sourceEntityKey:optional3(nullable(identity2)),targetEntityKey:optional3(nullable(identity2))});var schedule2=object({cronExpression:identity2,enabled:optBoolean,importMode:optional3(literal("delta","full")),key:identity2,timezone:optString});var positive=refine(number3,(n)=>n>0?undefined:"positive");var budget=optional3(nullable(positiveSafeInteger));var pipeline=object({definition:object({budgets:optional3(object({maxPagesPerRun:budget,maxRemoteItemsPerRun:budget,maxRootWorkUnitsPerRun:budget,maxSecondsPerRun:optional3(nullable(positive))})),steps:refine(array2(object({tasks:array2(object({bindingKey:identity2,kind:literal("entity","relation"),modeOverride:optional3(nullable(literal("delta","full")))}))})),(steps)=>steps.length>0?undefined:"empty")}),enabled:optBoolean,key:identity2,name:optString,schedules:optional3(array2(schedule2))});var uniqueKeys=(values,path)=>{const seen=new Set;for(const[index,value]of values.entries()){if(seen.has(value.key)){invalid4(`${path}/${index}/key`)}seen.add(value.key)}};var knowledge=object({...base,connections:optional3(record2(connection2)),dataPolicies:optional3(array2(object({...policyFields,fqn:identity2,priority:optNumber}))),enabled:optBoolean,entityBindings:optional3(array2(entityBinding)),kind:literal("knowledgeConnectorInstance"),lifecycle,pipelines:optional3(array2(pipeline)),relationBindings:optional3(array2(relationBinding)),remoteFilters:optional3(record2(object({mode:literal("all","only_selected","all_except_selected"),selected_ids:strings}))),settings:optional3(record2(object({type:literal("inline","linked"),value:json}))),templateFqn:identity2});var assertEntityParents=(entities,path)=>{const parents=new Map(entities.map((b)=>[b.key,b.parentKey]));for(const binding of entities){const seen=new Set([binding.key]);let parent=binding.parentKey;while(parent){if(seen.has(parent)){invalid4(`${path}/entityBindings/parentKey`)}seen.add(parent);parent=parents.get(parent)}}};var assertPolicyLifecycle=(policies,path)=>{for(const[index,policy]of policies.entries()){if(Object.keys(policy).some((key)=>key==="lifecycle"||key==="deployMode"||key==="readonly")){invalid4(`${path}/dataPolicies/${index}/lifecycle`)}}};var knowledgeConnectorInstance=(value,path)=>{const parsed=knowledge(value,path);assertPolicyLifecycle(parsed.dataPolicies??[],path);const entities=parsed.entityBindings??[];const relations=parsed.relationBindings??[];const pipelines=parsed.pipelines??[];uniqueKeys(entities,`${path}/entityBindings`);uniqueKeys(relations,`${path}/relationBindings`);uniqueKeys(pipelines,`${path}/pipelines`);const entityKeys=new Set(entities.map((b)=>b.key));const relationKeys=new Set(relations.map((b)=>b.key));assertEntityParents(entities,path);for(const[index,binding]of[...entities,...relations].entries()){if(binding.parentKey&&(!entityKeys.has(binding.parentKey)||binding.parentKey===binding.key)){invalid4(`${path}/bindings/${index}/parentKey`)}}for(const[index,relation]of relations.entries()){for(const key of[relation.sourceEntityKey,relation.targetEntityKey]){if(key&&!entityKeys.has(key)){invalid4(`${path}/relationBindings/${index}`)}}}for(const[index,item]of pipelines.entries()){uniqueKeys(item.schedules??[],`${path}/pipelines/${index}/schedules`);const tasks=new Set;for(const step of item.definition.steps){for(const task of step.tasks){const keys=task.kind==="entity"?entityKeys:relationKeys;const key=`${task.kind}:${task.bindingKey}`;if(!keys.has(task.bindingKey)||tasks.has(key)){invalid4(`${path}/pipelines/${index}/definition/steps`)}tasks.add(key)}}}return parsed};var scalar=literal("boolean","string","int64","float64","decimal","date","timestamp","duration","json");var datasetDefinition=object({fields:array2(object({id:identity2,name:string3,nullable:boolean2,semantic:optString,type:scalar})),measures:array2(object({id:identity2,name:string3,resultType:scalar})),relationships:array2(object({cardinality:literal("one_to_one","one_to_many","many_to_one","many_to_many"),fromFieldId:identity2,id:identity2,toFieldId:identity2})),version:literal(1)});var location=(value,path)=>{const{segments}=object({segments:array2(object({kind:literal("container","dataset"),label:string3,opaqueId:identity2}))})(value,path);const[first]=segments;if(!first||first.kind!=="container"){return invalid4(`${path}/segments/0`)}return{segments:[{...first,kind:"container"},...segments.slice(1)]}};var datasetValue=(value,path)=>{const{kind}=object({kind:string3})(value,path);switch(kind){case"null":{return object({kind:literal("null")})(value,path)}case"boolean":{return object({kind:literal("boolean"),value:boolean2})(value,path)}case"float64":{return object({kind:literal("float64"),value:number3})(value,path)}case"json":{return object({kind:literal("json"),value:json})(value,path)}default:{return object({kind:literal("string","int64","decimal","date","timestamp","duration"),value:string3})(value,path)}}};var datasetFilter=(value,path)=>{const{kind}=object({kind:string3})(value,path);if(kind==="not"){return object({filter:datasetFilter,kind:literal("not")})(value,path)}if(kind==="and"||kind==="or"){return object({filters:array2(datasetFilter),kind:literal("and","or")})(value,path)}return object({fieldId:identity2,kind:literal("predicate"),operator:literal("eq","ne","lt","lte","gt","gte","in","not_in","is_null","is_not_null","contains","starts_with"),values:array2(datasetValue)})(value,path)};var datasetFields={...base,connection:optional3(connection2),dataPolicy:optional3(object({allowedFields:strings,allowedOperations:array2(literal("describe","records","aggregate","time_series")),maxBytes:budget,maxRows:budget,maxTimeoutMs:budget,principals:array2(object({id:identity2,kind:literal("user","service")})),rowFilter:optional3(nullable(datasetFilter)),sensitiveFields:optional3(strings)})),kind:literal("datasetConnectorInstance"),lifecycle,providerFqn:identity2,schedules:optional3(array2(object({action:literal("health","refresh_definition"),cronExpression:identity2,enabled:optBoolean,key:identity2,timezone:optString}))),settings:optional3(jsonObject)};var datasetConnectorInstance=(value,path)=>{const parsed=union2(object({...datasetFields,bindingMode:literal("managed"),definition:datasetDefinition,sourceLocation:optional3(location),templateConfig:optional3(object({variant:identity2,version:literal(1)})),templateFqn:optional3(identity2)}),object({...datasetFields,bindingMode:literal("external"),definition:optional3(datasetDefinition),gatewayBindingKey:optString,sourceLocation:location,sourceMapping:optional3(object({effectiveAtFieldId:optString,entityIdFieldId:identity2,historySemantics:optional3(literal("append_history")),kind:literal("entity_snapshot","status_update"),statusFieldId:optString,version:literal(1)}))}))(value,path);uniqueKeys(parsed.schedules??[],`${path}/schedules`);return parsed};var datasetParserFormat=(value,path)=>{if(typeof value!=="string"||value.length>128||value==="external"||!/^[a-z][a-z0-9._-]*$/u.test(value)){throw new TypeError(`Invalid dataset parser format at ${path}`)}return value};var datasetParserVersion=(value,path)=>{if(typeof value!=="string"||value.trim()===""||value.length>96){throw new TypeError(`Invalid dataset parser version at ${path}`)}return value};var readExternalAppGateway=closedGatewayObject({...base,expectedContract:readOperationGatewayContract,kind:literal("externalAppGateway")});var roleKey=/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/u;var resourceAction=/^[^:]+:[^:]+$/u;var isOwnAncestor=({key,parent},declared)=>{const seen=new Set;let ancestor=parent;while(ancestor!==undefined&&ancestor!==key&&!seen.has(ancestor)){seen.add(ancestor);ancestor=declared.get(ancestor)?.parent}return ancestor===key};var rolesViolation=(roles=[])=>{const declared=new Map;for(const role of roles){const{key,permissions}=role;if(key.length>64||!roleKey.test(key)){return`role key '${key}' must match ${roleKey.source} and hold at most 64 characters`}if(declared.has(key)){return`role key '${key}' is declared more than once`}declared.set(key,role);const malformed=permissions.find((permission)=>!resourceAction.test(permission));if(malformed!==undefined){return`permission '${malformed}' of role '${key}' must be 'resource:action'`}}for(const role of roles){const{key,parent,permissions,replaces}=role;if(replaces!==undefined){if(declared.has(replaces)){return`role '${key}' replaces '${replaces}', which this release declares`}const first=roles.find((other)=>other.replaces===replaces)?.key;if(first!==key){return`roles '${first}' and '${key}' replace the same role '${replaces}'`}}if(parent===undefined){continue}const held=declared.get(parent)?.permissions;if(held===undefined){return`parent '${parent}' of role '${key}' is not a declared role`}const missing=permissions.find((permission)=>!held.includes(permission));if(missing!==undefined){return`role '${parent}' must hold permission '${missing}' of its child role '${key}'`}if(isOwnAncestor(role,declared)){return`role '${key}' is its own ancestor`}}return};var grantsViolation=(grants=[],roles=[])=>{for(const[index,{group,role}]of grants.entries()){if(group.trim()===""){return`the Grant of role '${role}' must name a Group`}if(!roles.some(({key})=>key===role)){return`role '${role}' of the Grant to Group '${group}' is not a declared role`}const first=grants.findIndex((other)=>other.group===group&&other.role===role);if(first!==index){return`the Grant of role '${role}' to Group '${group}' is declared more than once`}}return};var externalApplicationViolation=({admits,grants,primaryRedirectUri,redirectUris,roles})=>{if(primaryRedirectUri!==undefined&&!redirectUris.includes(primaryRedirectUri)){return"primaryRedirectUri must be one of redirectUris"}if(admits?.length===0){return"admits must name at least one User Class"}const repeated=admits?.find((userClass,index)=>admits.indexOf(userClass)!==index);if(repeated!==undefined){return`admits names '${repeated}' more than once`}return rolesViolation(roles)??grantsViolation(grants,roles)};var subgroupKey=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;var organizationGroupFqnMaxLength=320;var fqnViolation=(fqn)=>{const characters=[...fqn];if(characters.length<=organizationGroupFqnMaxLength){return}const shortened=`${characters.slice(0,40).join("")}...${characters.slice(-40).join("")}`;return`Group FQN '${shortened}' holds ${characters.length} characters; the limit is ${organizationGroupFqnMaxLength}`};var subgroupsViolation=(parentFqn,subgroups=[])=>{const keys=new Set;for(const{key,subgroups:nested}of subgroups){if(!subgroupKey.test(key)){return`subgroup key '${key}' of '${parentFqn}' must match ${subgroupKey.source}`}if(keys.has(key)){return`subgroup key '${key}' is declared more than once in '${parentFqn}'`}keys.add(key);const fqn=`${parentFqn}.${key}`;const violation=fqnViolation(fqn)??subgroupsViolation(fqn,nested);if(violation!==undefined){return violation}}return};var organizationGroupViolation=({fqn,subgroups})=>fqnViolation(fqn)??subgroupsViolation(fqn,subgroups);var identifier22=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/u;var fields=new Set(["category","defaultVisibility","description","displayName","fqn","gatewayRef","icon","kind","operationReferences","tags","version"]);var referencesGateway=(reference,gatewayId)=>{const separator=reference.indexOf("@");if(separator===-1){return false}const[gateway,domain,operation,...rest]=reference.slice(0,separator).split("/");const version=reference.slice(separator+1);return identifier22.test(gatewayId)&&gateway===gatewayId&&domain!==undefined&&identifier22.test(domain)&&operation!==undefined&&identifier22.test(operation)&&rest.length===0&&version.length>0&&version.length<=128&&version.trim()===version};var remoteToolCollectionViolation=(declaration)=>{const unknownField=Object.keys(declaration).find((key)=>!fields.has(key));if(unknownField!==undefined){return`unsupported remote metadata field '${unknownField}'`}const{gatewayRef,operationReferences}=declaration;if(gatewayRef===undefined||gatewayRef.trim()===""||gatewayRef.trim()!==gatewayRef){return"gatewayRef must be a nonempty FQN"}if(operationReferences.length===0||new Set(operationReferences).size!==operationReferences.length||operationReferences.some((reference)=>!referencesGateway(reference,reference.split("/")[0]??""))){return"operationReferences must name unique versioned Gateway operations"}return};var readPin=object({fqn:hostedIdentity,releaseDigest:(value,path)=>{const digest=hostedIdentity(value,path);return/^[\da-f]{64}$/u.test(digest)?digest:invalid4(path)},releaseId:hostedIdentity});var parsePackageDependencyPins=(value)=>{const pins=array2(readPin)(value,"/dependencies");const identities=new Set;for(const pin of pins){if(Object.keys(pin).some((key)=>!["fqn","releaseId","releaseDigest"].includes(key))){throw new TypeError(`package dependency '${pin.fqn}' has unexpected fields`)}if(identities.has(pin.fqn)){throw new TypeError(`duplicate package dependency '${pin.fqn}'`)}identities.add(pin.fqn)}return[...pins].sort((left,right)=>compareUtf16CodeUnits(left.fqn,right.fqn))};var PackageManifestVersion="v4";var legacyFixedDestinationTargets=new Set(["fixed-email","channel-destination","telegram-chat","whatsapp-destination"]);var uuid2=/^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/iu;var placeholder=/\{(?<name>[^{}]*)\}/gu;var placeholders={remoteId:(remoteId)=>encodeURIComponent(remoteId),remoteIdUuidHex:(remoteId)=>uuid2.test(remoteId)?remoteId.replaceAll("-","").toLowerCase():null};var isPlaceholderName=(name)=>Object.hasOwn(placeholders,name);var resolver=(name)=>isPlaceholderName(name)?placeholders[name]:undefined;var knowledgeRemoteReferenceUrlTemplate=(value,path)=>{if(typeof value!=="string"||!value.startsWith("https://")||/[{}]/u.test(value.replaceAll(placeholder,(match,name)=>resolver(name)===undefined?match:""))){throw new TypeError(`Invalid remote reference URL template at ${path}`)}return value};var HOSTS=["backend","dashboard","studio"];var FRONTEND_CATALOG_CONTRACT="frontend-catalog/v1";var FRONTEND_CATALOG_EXPORT_NAME="loadFrontendCatalog";var BACKEND_EXECUTION_LANES=["interactive","job"];var packageManifestJson=(definition)=>parseJsonObject(canonicalJson(definition.manifest));var canonicalPackageManifest=(definition)=>canonicalJson(packageManifestJson(definition));var toolBindingDeclaration=(entry)=>typeof entry==="string"?{tool:entry}:entry;var duplicateToolBinding=(tools)=>{const seen=new Set;for(const entry of tools){const binding=toolBindingDeclaration(entry);const key=JSON.stringify([binding.tool,binding.name??null]);if(seen.has(key)){return binding}seen.add(key)}return};var agentAudienceViolation=(audience)=>{const applications=audience.applications??[];if(audience.anonymous===true&&applications.length===0){return"anonymous visitors need an application in audience.applications"}const repeated=applications.find((fqn,index)=>applications.indexOf(fqn)!==index);return repeated===undefined?undefined:`audience application '${repeated}' is listed more than once`};var agentModelTiers=["complex","balanced","fast","super_fast"];var notificationDefinition=object({capabilities:object({extensionReadyProviders:strings,recipientTargets:strings,supportsActionLink:boolean2,supportsAttachments:boolean2,supportsFixedDestinations:optBoolean,supportsHtml:boolean2,supportsMarkdown:boolean2,supportsMentions:boolean2,supportsReadReceipts:boolean2,supportsRouteDestinations:boolean2,supportsThreads:boolean2}),credentialProfileKey:optString,family:literal("email","im","internal"),key:string3,provider:string3,setup:object({docsUrl:nullable(string3),healthCheck:object({available:boolean2,label:optString}),instructions:string3,liveTest:object({available:boolean2,label:optString}),secretFields:strings,setupForm:nullable(form)})});var studioPage=object({fullWidth:optBoolean,icon:optString,kind:literal("predefined"),label:string3,orderIndex:number3,predefinedPageRef:string3,routeSegment:string3,slug:string3});var studioSection=object({description:optString,icon:optString,label:string3,orderIndex:number3,pages:array2(studioPage),slug:string3});var studioApp=object({color:optString,description:optString,icon:optString,isDefaultTemplate:optBoolean,name:string3,sections:array2(studioSection),slug:string3});var datasetScalarType=literal("boolean","string","int64","float64","decimal","date","timestamp","duration","json");var datasetDefinition2=object({fields:array2(object({id:string3,name:string3,nullable:boolean2,semantic:optional3(string3),type:datasetScalarType})),measures:array2(object({id:string3,name:string3,resultType:datasetScalarType})),relationships:array2(object({cardinality:literal("one_to_one","one_to_many","many_to_one","many_to_many"),fromFieldId:string3,id:string3,toFieldId:string3})),version:literal(1)});var datasetBlueprint=object({...base,blueprintVersion:positiveSafeInteger,configuration:optional3(jsonObject),definition:datasetDefinition2,kind:literal("datasetBlueprint"),templateFqn:identity2});var semanticRole=literal("dimension","effective_time","entity_reference","event_time","identity","measure","status");var hint=object({role:semanticRole});var datasetTableTemplate=object({...base,admittedIngestionModes:array2(literal("append","replace","upsert")),compatibleProviderFqns:strings,configuration:schema2,identity:object({keyRoles:array2(semanticRole),uniqueness:literal("append_only","key","none")}),indexHints:array2(hint),kind:literal("datasetTableTemplate"),partitionHints:array2(hint),physicalCode:literal("evt","fact","gen","snap","stat","ts"),requirements:schema2,semanticRoles:array2(semanticRole)});var WorkflowEditorWidgets=["checkbox","code","condition_builder","credential_selector","key_value","list","mapping_builder","multi_select","number","resource_selector","schedule_builder","schema_builder","select","text","textarea"];var WorkflowTemplateKinds=["action_node","input_node","output_node","trigger_node"];var WorkflowTriggerLifecycleAdapterIds=Object.freeze({externalApplication:"builtin.core.workflows.lifecycle.external-application",mcpOperation:"builtin.core.workflows.lifecycle.mcp-operation"});var dynamicPort=object({configPath:string3,defaultIdPath:optString,idPath:string3,requiredPath:optString,schemaPath:optString});var fieldBinding=object({path:pathParts,target:literal("input_binding","parameter")});var nonNegativeInteger=(value,path)=>{const parsed=number3(value,path);return Number.isSafeInteger(parsed)&&parsed>=0?parsed:invalid4(path)};var optionSource=union2(object({kind:literal("static"),options:array2(object({label:localized,value:json}))}),object({clearOnDependencyChange:boolean2,dependsOn:array2(fieldBinding),kind:literal("remote"),operationId:string3,searchable:boolean2}));var editorField=object({binding:fieldBinding,fieldConfig:optional3(jsonObject),fieldFqn:optString,fieldVersion:optString,help:optional3(localized),label:optional3(localized),optionSource:optional3(optionSource),order:optNumber,placeholder:optional3(localized),readOnly:optBoolean,required:optBoolean,resolutionPhase:literal("runtime","structural"),sensitive:optBoolean,valueSources:array2(literal("expression","fixed","literal","mapping","model","system")),visibleWhen:optional3(array2(object({binding:fieldBinding,operator:literal("equals","in","is_not_set","is_set","not_equals"),value:optional3(json)}))),widget:optional3(literal(...WorkflowEditorWidgets))});var templateKind=literal(...WorkflowTemplateKinds);var nodePort=refine(object({allowedTemplateFqns:optStrings,allowedTemplateKinds:optional3(array2(templateKind)),direction:literal("input","output"),key:string3,maxConnections:optional3(nullable(nonNegativeInteger)),minConnections:optional3(nonNegativeInteger),schemaResolution:optional3(object({configPath:pathParts,variants:array2(object({schema:schema2,schemaInjections:optional3(array2(object({configPath:pathParts,schemaPath:pathParts}))),when:json}))})),valueSchema:schema2}),workflowPortPolicyViolation);var eventSelectorProjection=union2(object({required:optBoolean,sourcePath:pathParts,targetPath:pathParts}),object({targetPath:pathParts,value:json}));var eventIngress=object({acquisitionMode:string3,callbackPathPath:optional3(pathParts),connectionIdPath:optional3(pathParts),eventKind:string3,listener:object({fqn:string3,version:string3}),requiredConfigPaths:optional3(array2(pathParts)),requiredListener:optBoolean,selector:array2(eventSelectorProjection)});var triggerActivation=union2(object({eventIngress,kind:literal("event")}),union2(object({invocationRole:optional3(literal("application","user")),kind:literal("manual"),lifecycleAdapterId:optString,triggerRefPath:optional3(pathParts)}),object({kind:literal("schedule")})));var parseWorkflowReusableDependency=(value)=>object({inputContractPath:pathParts,modePath:optional3(pathParts),targetWorkflowFqnPath:optional3(pathParts),targetWorkflowIdPath:pathParts})(value,"/reusableDependency");var nodeContract=object({capabilityComposition:optional3(object({capability:string3,fragments:strings,selector:object({path:pathParts,target:literal("parameter")})})),configSchema:optional3(schema2),connectionRequirements:optional3(array2(object({cardinality:literal("many","one"),connectionTemplateFqns:refine(strings,(fqns)=>fqns.length===0?"connectionTemplateFqns cannot be empty":undefined),key:string3,required:boolean2,selector:object({path:pathParts,target:literal("parameter")})}))),dynamicPorts:optional3(object({input:optional3(dynamicPort),output:optional3(dynamicPort)})),editor:optional3(refine(object({form:optional3(object({sections:optional3(array2(object({fields:optional3(array2(editorField)),id:optString,order:optNumber,title:optString})))}))}),workflowEditorViolation)),execution:optional3(object({itemModes:optional3(array2(literal("all_items","each_item","single"))),mainOutputPort:optString,repeatable:optBoolean,resumable:optBoolean,sideEffect:literal("external","none","read","write"),testable:optBoolean})),implementationId:string3,inputSchema:optional3(schema2),instancePolicy:optional3(object({maxInstances:optNumber,minInstances:optNumber,onWorkflowCreate:optBoolean})),nodeCollectionFqn:optString,nodeCollectionVersion:optString,outputChannels:optional3(array2(object({adapterId:string3,cardinality:literal("many","one"),deliveryMode:literal("asynchronous","synchronous"),key:string3,required:boolean2,valueSchema:schema2}))),outputSchema:optional3(schema2),ports:optional3(array2(nodePort)),reusableDependency:optional3(parseWorkflowReusableDependency),triggerActivation:optional3(triggerActivation)});var fieldContract=object({availableForInput:optBoolean,availableForOutput:optBoolean,clearOnDependencyChange:optBoolean,optionDependencies:optional3(array2(object({path:pathParts,target:literal("parameter","part","value")}))),valueSchema:optional3(schema2)});var graphSchema=object({bindings:optional3(array2(object({extensions:jsonObject}))),fieldProjections:array2(object({source:pathParts,target:pathParts})),schema:schema2});var graphBoundary=object({templateFqn:string3,templateVersion:string3});var graph=object({edges:array2(object({extensions:optional3(jsonObject),id:string3,source:string3,target:string3})),inputBoundary:graphBoundary,inputContract:graphSchema,metadata:object({description:nullable(string3),tags:strings,templateSource:nullable(string3)}),nodes:array2(object({extensions:optional3(jsonObject),id:string3,templateFqn:string3,templateVersion:string3})),outputBoundary:graphBoundary,outputContract:graphSchema,triggers:array2(object({config:object({extensions:optional3(jsonObject)}),id:string3,inputBindings:record2(string3),invocation:object({mode:literal("attach","detach"),timeoutMs:nullable(number3)}),metadata:object({fieldDisplayValues:record2(string3)}),settings:object({enabled:boolean2}),templateFqn:string3,templateVersion:string3})),version:literal(1)});var uiLayout=object({edges:record2(object({extensions:optional3(jsonObject)})),nodes:record2(object({position:optional3(object({x:number3,y:number3}))})),version:literal(1),viewport:nullable(object({x:number3,y:number3,zoom:number3}))});var bindingSpan=object({end:number3,start:number3});var bindingSource=object({kind:literal("input","loop_index","loop_item","merge_output","node_output","port_arrival","run","scope","trigger"),mergeId:optional3(nullable(string3)),nodeId:optional3(nullable(string3)),portId:optional3(nullable(string3)),selection:optional3(nullable(object({ancestry:literal("nearest_dominating_ancestor"),iteration:literal("aggregate","previous_iteration","same_iteration")})))});var bindingExpression=(value,path)=>{const{kind}=object({kind:string3})(value,path);switch(kind){case"array":{return object({items:array2(bindingExpression),kind:literal("array")})(value,path)}case"call":{return object({args:array2(bindingExpression),kind:literal("call"),name:string3})(value,path)}case"interpolation":{return object({kind:literal("interpolation"),parts:array2(bindingExpression),span:optional3(nullable(bindingSpan))})(value,path)}case"literal":{return object({kind:literal("literal"),value:json})(value,path)}case"object":{return object({fields:record2(bindingExpression),kind:literal("object")})(value,path)}case"operator":{return object({args:array2(bindingExpression),kind:literal("operator"),op:string3})(value,path)}case"ref":{return object({kind:literal("ref"),onUnavailable:object({kind:literal("error","fallback","null"),value:optional3(nullable(bindingExpression))}),path:pathParts,source:bindingSource,span:optional3(nullable(bindingSpan))})(value,path)}default:{return invalid4(`${path}/kind`)}}};var authoredValue=union2(object({mode:literal("fixed"),value:json}),object({compiled:optional3(nullable(bindingExpression)),languageVersion:literal(1),mode:literal("expression"),source:string3}));var nodeExecutionSettings=object({dryRun:optional3(object({mode:literal("allow","block_side_effects")})),idempotencyKey:optional3(nullable(bindingExpression)),onError:optional3(object({mode:literal("continue","fail_run")})),retry:optional3(object({backoffMs:optional3(nullable(number3)),maxAttempts:optional3(nullable(number3)),mode:literal("disabled","exponential","fixed")})),timeoutMs:optional3(nullable(number3))});var authoringTemplateRef=object({templateFqn:string3,templateVersion:string3});var authoringFieldProjection=object({fieldConfig:optional3(jsonObject),fieldFqn:string3,fieldVersion:string3,path:strings});var authoringInputContract=object({fieldProjections:optional3(array2(authoringFieldProjection)),jsonSchema:jsonObject});var authoringOutputContract=object({bindings:array2(object({key:string3,kind:literal("artifact","value"),value:bindingExpression})),fieldProjections:optional3(array2(authoringFieldProjection)),jsonSchema:jsonObject});var inputEndpoint=object({kind:literal("input_node"),portId:string3});var actionEndpoint=object({kind:literal("action_node"),nodeId:string3,portId:string3});var triggerEndpoint=object({kind:literal("trigger_node"),portId:string3,triggerId:string3});var outputEndpoint=object({kind:literal("output_node"),portId:string3});var authoringDefinition=object({edges:array2(object({id:string3,source:union2(union2(actionEndpoint,inputEndpoint),triggerEndpoint),target:union2(union2(actionEndpoint,inputEndpoint),outputEndpoint)})),inputBoundary:authoringTemplateRef,inputContract:authoringInputContract,metadata:jsonObject,nodes:array2(object({config:record2(authoredValue),extensions:optional3(jsonObject),id:string3,inputs:record2(authoredValue),metadata:jsonObject,settings:nodeExecutionSettings,templateFqn:string3,templateVersion:string3,uid:optString})),outputBoundary:authoringTemplateRef,outputContract:authoringOutputContract,triggers:array2(object({config:jsonObject,id:string3,inputBindings:record2(object({overridePolicy:literal("caller_may_override","locked"),value:authoredValue})),invocation:object({mode:literal("attach","await_result","detach"),timeoutMs:optional3(nullable(number3))}),metadata:jsonObject,settings:jsonObject,templateFqn:string3,templateVersion:string3})),version:literal(1)});var knowledgeSelection=optional3(object({exclude:optional3(array2(identity2)),include:optional3(array2(identity2))}));var toolBindings2=refine(array2(union2(identity2,object({approval:optional3(union2(literal("always","never"),object({rule:identity2}))),knowledge:optional3(object({domains:knowledgeSelection,entitySchemas:knowledgeSelection,relationSchemas:knowledgeSelection,unrestricted:optBoolean})),name:optional3(identity2),settings:optional3(jsonObject),tool:identity2}))),(tools)=>duplicateToolBinding(tools)===undefined?undefined:"duplicate tool binding");var agentAudience2=refine(object({anonymous:optBoolean,applications:optional3(array2(identity2)),members:optional3(literal("all","none","selected")),organizationGroups:optional3(literal("none","selected"))}),(audience)=>("organizationTeams"in audience)?"organizationTeams":agentAudienceViolation(audience));var withoutRetiredAgentFields=(agent)=>["invokingApplicationFqns","modelPreset"].find((field)=>(field in agent));var webhookHandshake=union2(object({kind:literal("echo_query_parameter"),parameter:identity2}),union2(object({kind:literal("echo_query_parameter_with_verify_token"),parameter:identity2,tokenParameter:identity2}),object({field:identity2,kind:literal("echo_json_body_field"),when:object({equals:string3,field:identity2})})));var subgroups=(value,path)=>optional3(array2(object({description:optString,displayName:string3,key:string3,subgroups})))(value,path);var primitives={agent:refine(object({...base,activity:optional3(object({heartbeat:boolean2,schedule:boolean2})),audience:optional3(agentAudience2),behavioralBoundaries:strings,kind:literal("agent"),lifecycle,maxSteps:optional3(positiveSafeInteger),modelTier:optional3(literal(...agentModelTiers)),objectives:strings,operatingInstructions:string3,output:optional3(object({schema:schema2})),responsibility:string3,skills:array2(identity2),tools:toolBindings2}),withoutRetiredAgentFields),connection,datasetBlueprint,datasetConnectorInstance,datasetParser:object({...base,extensions:array2(identity2),format:datasetParserFormat,kind:literal("datasetParser"),mediaTypes:array2(identity2),parserVersion:datasetParserVersion}),datasetTableTemplate,documentsConnector:object({...base,connectionRefs,kind:literal("documentsConnector"),providerDisplayName:optional3(identity2),providerFamily:identity2}),domain:object({...base,kind:literal("domain"),lifecycle,localMutationPolicy:optional3(mutationPolicy),versioningEnabled:nullable(boolean2)}),domainTemplate:object({...base,catalogTags,domainFqn:string3,domainName:string3,entitySchemaFqns:strings,kind:literal("domainTemplate"),relationSchemaFqns:strings}),emailProvider:object({...base,connectionTemplateFqn:identity2,deploymentIdentity:optional3(literal("aws")),kind:literal("emailProvider"),senderKind:literal("address","mailbox")}),eventListener:object({...base,capabilities:array2(literal("internal","poll","webhook")),eventKind:string3,kind:literal("eventListener"),manualWebhookState:optional3(object({keyFamily:identity2,stateKey:identity2})),messaging:optional3(object({connectionTemplateFqn:identity2,contractVersion:literal(1),service:identity2})),receiveModeField:optional3(identity2),runtimeState:optional3(array2(object({keyFamily:string3,stateKey:string3}))),safeOccurrenceFields:optStrings,safeSelectorFields:optStrings,sourceScope:optional3(literal("connection","selector")),webhookAcknowledgement:optional3(object({status:literal(200,204)})),webhookHandshake:optional3(webhookHandshake),webhookRegistration:optional3(literal("listener"))}),externalAppGateway:readExternalAppGateway,externalApplication:refine(object({...base,admits:optional3(array2(literal("internal","external"))),allowedOrigins:strings,applicationType:literal("confidential","public"),audience:string3,grants:optional3(array2(object({group:string3,lifecycle,role:string3}))),kind:literal("externalApplication"),lifecycle,postLogoutRedirectUris:strings,primaryRedirectUri:optString,redirectUris:strings,roles:optional3(array2(object({key:string3,parent:optString,permissions:strings,replaces:optString}))),scopes:strings,setupInstructions:optString}),externalApplicationViolation),externalDatasetProvider:object({...base,capabilities:datasetCapabilities,connectionTemplateFqns:strings,kind:literal("externalDatasetProvider"),sourceCapabilities:optional3(array2(object({capabilities:datasetCapabilities,datasetOpaqueIdPrefix:string3})))}),fieldTransformer:object({...base,kind:literal("fieldTransformer"),sourceFieldType:string3,targetFieldType:string3}),knowledgeConnector:object({...base,autoActivate:optBoolean,autoInstantiate:optBoolean,bindingScopes:optional3(bindingScopes),connectionRefs,contributions:optional3(array2(object({capabilityFqn:string3,connectionSlot:string3,connectionTemplateFqn:string3,controlFqn:optString,displayName:string3,fqn:identity2,metadata:optional3(jsonObject)}))),defaultOutboundStrategy:optional3(outboundStrategy),defaultUpdateMode:optional3(updateMode),discoveryDefaults:optional3(discoveryDefaults),entityIdentityMode:optional3(literal("adapter","item_metadata")),entitySchemaCapabilities:optional3(array2(entityCapability)),isSingleton:optBoolean,kind:literal("knowledgeConnector"),outboundCapability:optional3(literal("declared_and_enablable","none")),recommendedImportSchedules:predefinedSchedules,relationSchemaCapabilities:optional3(array2(relationCapability)),remoteReference:optional3(object({providerKey:identity2,urlTemplate:knowledgeRemoteReferenceUrlTemplate})),settings:optional3(form),supportedBindingModes:optional3(bindingModes)}),knowledgeConnectorInstance,knowledgeConnectorOauth:object({...base,connectorFqn:string3,kind:literal("knowledgeConnectorOauth")}),knowledgeEntityAdapter:object({...base,connectorFqn:string3,entitySchemaFqn:string3,kind:literal("knowledgeEntityAdapter"),normalizesFieldMapValues:optBoolean,normalizesImportedData:optBoolean}),knowledgeEntitySchema:object({...base,...knowledgeSchema,autocompleteConfiguration,defaultSyncDirection:optString,deletionMode:optString,displayDefaults:optional3(object({collections:optStrings,details:optStrings})),displayNameExpression:nullable(string3),embedEntities:optBoolean,embeddingConfig:nullable(jsonObject),extendsSchemaFqn:optString,kind:literal("knowledgeEntitySchema"),lifecycle,maxVersionsExpirationDays:optional3(nullable(number3)),persistFullFieldContributions:boolean2,relationFields:optional3(array2(object({cardinality:literal("many","one"),field:string3,id:string3,nullable:boolean2,reference:literal("external_id"),targetEntityId:string3,targetSchemaFqn:string3}))),syncable:optBoolean,usableAsDocumentScope:boolean2,versioned:optBoolean,versioningEnabled:nullable(boolean2)}),knowledgePolicy:object({...base,...policyFields,kind:literal("knowledgePolicy"),priority:optNumber}),knowledgeRelationAdapter:object({...base,connectorFqn:string3,kind:literal("knowledgeRelationAdapter"),relationSchemaFqn:string3}),knowledgeRelationSchema:object({...base,...knowledgeSchema,kind:literal("knowledgeRelationSchema"),lifecycle:optional3(lifecycle),sourceSchemaFqn:string3,targetSchemaFqn:string3}),managedDatasetProvider:object({...base,capabilities:datasetCapabilities,connectionTemplateFqns:strings,kind:literal("managedDatasetProvider")}),notificationChannel:object({...base,credential:optional3(form),definition:notificationDefinition,kind:literal("notificationChannel")}),organizationGroup:refine(object({...base,kind:literal("organizationGroup"),lifecycle,parent:optional3(identity2),subgroups}),organizationGroupViolation),organizationSso:object({...base,connectionTemplateFqn:string3,kind:literal("organizationSso"),providerId:string3,requiredCredentialFields:strings,secretCredentialFields:optStrings,setupGuide:optional3(array2(object({locale:string3,markdown:string3})))}),outboundMessagingProvider:object({...base,connectionTemplateFqn:identity2,kind:literal("outboundMessagingProvider"),service:identity2}),remoteToolCollection:refine(object({...base,category:optString,defaultVisibility:optional3(array2(object({effect:literal("allow","deny"),subject:literal("organization")}))),gatewayRef:identity2,kind:literal("remoteToolCollection"),operationReferences:strings}),remoteToolCollectionViolation),skill:object({...base,instructions:string3,kind:literal("skill"),lifecycle,tools:toolBindings2}),skillTemplate:object({...base,catalogTags,kind:literal("skillTemplate"),lifecycle:optional3(lifecycle),name:string3}),studioApp:object({...base,definition:studioApp,kind:literal("studioApp")}),studioComponent:object({...base,category:literal("layout","page","primitive","view","widget"),composition:optional3(object({extensions:optional3(jsonObject),slotSource:literal("props","static"),slots:array2(object({extensions:optional3(jsonObject),key:string3,label:optional3(localized)}))})),kind:literal("studioComponent"),propsSchema:schema2,sourceRef:string3}),tool:object({...base,allowMultipleSkillBindings:optBoolean,autoActivate:optBoolean,autoInstantiate:optBoolean,bindingScopes:optional3(bindingScopes),bindingSettings:optional3(form),capabilityType:optional3(literal("delegate","external","read","write")),category:optString,connectionRefs,effectKind:optional3(literal("mutation","read_only")),extraLoaders:optional3(array2(object({bindingName:string3,inheritBindingSettings:optBoolean,toolFqn:string3}))),healthCheck:optional3(object({capabilities:optStrings,description:string3})),input:schema2,isSingleton:optBoolean,kind:literal("tool"),output:schema2,settings:optional3(form),setupInstructions:optional3(object({links:strings,markdown:string3})),toolCollectionFqns:optStrings,toolGuidance:optional3(object({inputRequirementsSummary:optString,useWhen:optString})),usageScopes:optional3(array2(literal("automation","chat","skill")))}),toolCollection:object({...base,category:optString,defaultVisibility:optional3(array2(object({effect:literal("allow","deny"),subject:literal("organization")}))),kind:literal("toolCollection"),toolFqns:strings}),toolSettingsOptions:object({...base,catalogCollection:optString,catalogConnectionSlots:optStrings,connectionSlots:optStrings,dependencies:optStrings,fieldKey:string3,formTarget:optional3(literal("binding","settings")),includeUnavailableSelectedOptions:optBoolean,kind:literal("toolSettingsOptions"),toolFqn:string3}),workflow:object({...base,definition:authoringDefinition,kind:literal("workflow"),lifecycle,name:string3,slug:string3}),workflowField:object({...base,collectionFqn:string3,collectionVersion:string3,contract:fieldContract,kind:literal("workflowField"),presentation:optional3(object({placeholder:optString,widget:optString}))}),workflowFieldCollection:object({...base,contract:object({weight:number3}),kind:literal("workflowFieldCollection"),presentation:optional3(object({categoryPath:strings,label:localized}))}),workflowNode:object({...base,contract:nodeContract,kind:literal("workflowNode"),nodeKind:literal("action","input","output","trigger"),presentation:optional3(object({categoryPath:optStrings,tags:optStrings}))}),workflowNodeCollection:object({...base,contract:object({collection:optional3(object({parentFqn:string3,parentVersion:string3,weight:number3}))}),kind:literal("workflowNodeCollection"),presentation:optional3(object({categoryPath:strings}))}),workflowTemplate:object({...base,catalogTags,category:string3,definition:graph,kind:literal("workflowTemplate"),lifecycle,name:string3,requiredSkills:strings,requiredTools:strings,skillSlots:strings,slug:string3,uiLayout:nullable(uiLayout)})};var primitive=(v,p)=>{const{kind}=object({kind:string3})(v,p);for(const[name,read]of Object.entries(primitives)){if(name===kind){return read(v,p)}}return invalid4(`${p}/kind`)};var readHostedContribution=(value,path)=>{const shared=object({compatibility:optional3(record2(string3)),contract:optString,execution:optional3(literal("interactive","job")),exportName:hostedIdentity,fqn:hostedIdentity,host:literal("backend","dashboard","studio")})(value,path);if(shared.host==="backend"){return{...shared.compatibility===undefined?undefined:{compatibility:shared.compatibility},...shared.contract===undefined?undefined:{contract:shared.contract},...shared.execution===undefined?undefined:{execution:shared.execution},exportName:shared.exportName,fqn:shared.fqn,host:shared.host}}if(shared.execution!==undefined){throw new TypeError(`Invalid package manifest at ${path}/execution: frontend contributions cannot declare an execution lane`)}if(shared.contract!==FRONTEND_CATALOG_CONTRACT){throw new TypeError(`Invalid package manifest at ${path}/contract: frontend contribution contract must be '${FRONTEND_CATALOG_CONTRACT}'`)}if(shared.exportName!==FRONTEND_CATALOG_EXPORT_NAME){throw new TypeError(`Invalid package manifest at ${path}/exportName: frontend contribution export must be '${FRONTEND_CATALOG_EXPORT_NAME}'`)}return{...shared.compatibility===undefined?undefined:{compatibility:shared.compatibility},contract:FRONTEND_CATALOG_CONTRACT,exportName:FRONTEND_CATALOG_EXPORT_NAME,fqn:shared.fqn,host:shared.host}};var readManifest=object({apiVersion:literal(PackageManifestVersion),author:optString,autoInstallable:optBoolean,bindingScopes:optional3(array2(literal("organization","tenant"))),category:optString,dependencies:optional3(parsePackageDependencyPins),description:optString,documentation:optString,fqn:identity2,homepage:optString,hostedContributions:optional3(array2(readHostedContribution)),icon:optString,installationWizard:optional3(object({size:optional3(literal("lg","md","xl")),steps:array2(object({description:optString,kind:literal("connector_instance","tool_instance"),optional:optBoolean,ref:string3,title:optString}))})),name:string3,primitives:array2(primitive),requiredEnvironmentVariables:optStrings,tags:optStrings,tenantMandatory:optBoolean,tenantStandard:optBoolean,version:string3});var parsePackageManifest=(value)=>{assertDenseArrays(value,"",new WeakSet);const manifest=readManifest(parseJsonObject(canonicalJson(value)),"");return manifest.dependencies===undefined?manifest:{...manifest,dependencies:parsePackageDependencyPins(manifest.dependencies)}};var assertArchivePath=(path)=>{if(path===""||path.startsWith("/")||path.includes("\\")||path.split("/").some((part)=>part===""||part==="."||part==="..")){throw new TypeError(`Extension Release archive has unsafe path '${path}'`)}};var assertRuntimeAssetPath=(path)=>{if(!/^artifacts\/(?:backend|dashboard|studio)\/.+/u.test(path)){throw new TypeError(`Extension Release archive entry '${path}' is not a runtime asset path`)}};var PackageManifestArchivePath="package-manifest.json";var assertReleaseArchiveEntryPath=(path)=>{assertArchivePath(path);if(path!==PackageManifestArchivePath){assertRuntimeAssetPath(path)}};var ExtensionReleaseManifestVersion="v2";var sha256Pattern=/^[\da-f]{64}$/u;var isExtensionHost=(value)=>value==="backend"||value==="dashboard"||value==="studio";var isRecord=(value)=>value!==null&&typeof value==="object"&&!Array.isArray(value);var assertExactKeys=(value,allowedKeys,label)=>{const allowed=new Set(allowedKeys);const unexpected=Object.keys(value).find((key)=>!allowed.has(key));if(unexpected!==undefined){throw new TypeError(`${label} has unexpected field '${unexpected}'`)}};var requireRecord=(value,label)=>{if(!isRecord(value)){throw new TypeError(`${label} must be an object`)}return value};var requireString=(value,label)=>{if(typeof value!=="string"||value.trim()===""){throw new TypeError(`${label} must be a non-empty string`)}return value};var requireDigest=(value,label)=>{const digest=requireString(value,label);if(!sha256Pattern.test(digest)){throw new TypeError(`${label} must be a lowercase SHA-256 digest`)}return digest};var requireSize=(value,label)=>{if(typeof value!=="number"||!Number.isSafeInteger(value)||value<0){throw new TypeError(`${label} must be a non-negative safe integer`)}return value};var requireHost=(value,label)=>{if(typeof value!=="string"||!isExtensionHost(value)){throw new TypeError(`${label} must identify a supported Host`)}return value};var assertUniqueSorted=(values,keyOf,label)=>{let previous;for(const value of values){const current=keyOf(value);if(previous!==undefined&¤t<=previous){throw new TypeError(`${label} must be unique and sorted`)}previous=current}};var parsePrivateSourceMap=(value,label)=>{const sourceMap=requireRecord(value,label);assertExactKeys(sourceMap,["digest","size"],label);return{digest:requireDigest(sourceMap.digest,`${label}.digest`),size:requireSize(sourceMap.size,`${label}.size`)}};var parseAsset=(value,index)=>{const label=`Extension Release asset ${index}`;const asset=requireRecord(value,label);assertExactKeys(asset,["digest","host","path","privateSourceMap","size"],label);const path=requireString(asset.path,`${label}.path`);assertArchivePath(path);assertRuntimeAssetPath(path);const host=requireHost(asset.host,`${label}.host`);if(!path.startsWith(`artifacts/${host}/`)){throw new TypeError(`Extension Release asset '${path}' does not match Host '${host}'`)}return{digest:requireDigest(asset.digest,`${label}.digest`),host,path,...asset.privateSourceMap===undefined?undefined:{privateSourceMap:parsePrivateSourceMap(asset.privateSourceMap,`${label}.privateSourceMap`)},size:requireSize(asset.size,`${label}.size`)}};var parseContribution=(value,index)=>{const label=`Extension Release contribution ${index}`;const contribution=requireRecord(value,label);assertExactKeys(contribution,["assetPath","contract","digest","execution","exportName","fqn","host","size"],label);const assetPath=requireString(contribution.assetPath,`${label}.assetPath`);assertArchivePath(assetPath);const host=requireHost(contribution.host,`${label}.host`);const exportName=requireString(contribution.exportName,`${label}.exportName`);const contract=contribution.contract===undefined?undefined:requireString(contribution.contract,`${label}.contract`);const execution=contribution.execution===undefined?undefined:BACKEND_EXECUTION_LANES.find((lane)=>lane===contribution.execution);if(contribution.execution!==undefined&&execution===undefined){throw new TypeError(`${label}.execution must be 'interactive' or 'job'`)}const common={assetPath,digest:requireDigest(contribution.digest,`${label}.digest`),fqn:requireString(contribution.fqn,`${label}.fqn`),size:requireSize(contribution.size,`${label}.size`)};if(host==="backend"){return{...common,...contract===undefined?undefined:{contract},...execution===undefined?undefined:{execution},exportName,host}}if(execution!==undefined){throw new TypeError(`${label}.execution is only valid for backend`)}if(contract!==FRONTEND_CATALOG_CONTRACT){throw new TypeError(`${label}.contract must be '${FRONTEND_CATALOG_CONTRACT}'`)}if(exportName!==FRONTEND_CATALOG_EXPORT_NAME){throw new TypeError(`${label}.exportName must be '${FRONTEND_CATALOG_EXPORT_NAME}'`)}return{...common,contract:FRONTEND_CATALOG_CONTRACT,exportName:FRONTEND_CATALOG_EXPORT_NAME,host}};var parseExtensionReleaseManifest=(value)=>{const manifest=requireRecord(value,"Extension Release manifest");assertExactKeys(manifest,["apiVersion","assets","compatibility","contributions","package","packageManifest","releaseDigest"],"Extension Release manifest");if(manifest.apiVersion!==ExtensionReleaseManifestVersion){throw new TypeError("Extension Release manifest has unsupported apiVersion")}if(!Array.isArray(manifest.assets)){throw new TypeError("Extension Release manifest assets must be an array")}if(!Array.isArray(manifest.contributions)){throw new TypeError("Extension Release manifest contributions must be an array")}const compatibilityInput=requireRecord(manifest.compatibility,"Extension Release manifest compatibility");const compatibility=Object.fromEntries(Object.entries(compatibilityInput).map(([runtime,range])=>[requireString(runtime,"Extension Release compatibility runtime"),requireString(range,`Extension Release compatibility '${runtime}'`)]));const packageInput=requireRecord(manifest.package,"Extension Release manifest package");assertExactKeys(packageInput,["fqn","version"],"Extension Release package");const packageManifest=manifest.packageManifest===undefined?undefined:parsePackageManifest(manifest.packageManifest);if(packageManifest!==undefined&&(packageManifest.fqn!==packageInput.fqn||packageManifest.version!==packageInput.version)){throw new TypeError("Extension Release retained declarations do not match package identity")}const assets=manifest.assets.map(parseAsset);const contributions=manifest.contributions.map(parseContribution);assertUniqueSorted(assets,({path})=>path,"Extension Release manifest assets");assertUniqueSorted(contributions,({fqn,host})=>`${host}\x00${fqn}`,"Extension Release manifest contributions");const assetByPath=new Map(assets.map((asset)=>[asset.path,asset]));for(const contribution of contributions){const asset=assetByPath.get(contribution.assetPath);if(asset===undefined||asset.digest!==contribution.digest||asset.host!==contribution.host||asset.size!==contribution.size){throw new TypeError(`Extension Release contribution '${contribution.fqn}' does not match its declared runtime asset`)}}return{apiVersion:ExtensionReleaseManifestVersion,assets,compatibility,contributions,package:{fqn:requireString(packageInput.fqn,"Extension Release package.fqn"),version:requireString(packageInput.version,"Extension Release package.version")},...packageManifest===undefined?undefined:{packageManifest},releaseDigest:requireDigest(manifest.releaseDigest,"Extension Release manifest.releaseDigest")}};var canonicalExtensionReleaseManifest=(manifest)=>canonicalJson(manifest);var archiveBlockSize=512;var isZeroBlock=(bytes)=>bytes.every((value)=>value===0);var decodeCanonicalTextField=(bytes,label)=>{const terminator=bytes.indexOf(0);const contentEnd=terminator===-1?bytes.byteLength:terminator;if(bytes.subarray(0,contentEnd).some((byte)=>byte>127)||terminator!==-1&&!isZeroBlock(bytes.subarray(terminator))){throw new TypeError(`Extension Release archive has non-canonical ${label}`)}return String.fromCodePoint(...bytes.subarray(0,contentEnd))};var parseCanonicalOctalField=(bytes,label)=>{const digits=bytes.subarray(0,bytes.byteLength-1);if(bytes.at(-1)!==0||digits.some((byte)=>byte<48||byte>55)){throw new TypeError(`Extension Release archive has non-canonical ${label}`)}return Number.parseInt(String.fromCodePoint(...digits),8)};var assertHeaderChecksum=(header)=>{const checksum=header.subarray(148,156);const checksumDigits=checksum.subarray(0,6);if(checksum[6]!==0||checksum[7]!==32||checksumDigits.some((byte)=>byte<48||byte>55)){throw new TypeError("Extension Release archive has non-canonical header checksum")}const declared=Number.parseInt(String.fromCodePoint(...checksumDigits),8);let actual=0;for(let index=0;index<header.byteLength;index+=1){actual+=index>=148&&index<156?32:header[index]??0}if(actual!==declared){throw new TypeError("Extension Release archive has invalid header checksum")}};var decodeCanonicalUstarHeader=(header)=>{assertHeaderChecksum(header);if(parseCanonicalOctalField(header.subarray(100,108),"file mode")!==420){throw new TypeError("Extension Release archive has non-canonical file mode")}if(parseCanonicalOctalField(header.subarray(108,116),"owner ID")!==0||parseCanonicalOctalField(header.subarray(116,124),"group ID")!==0||parseCanonicalOctalField(header.subarray(136,148),"modification time")!==0){throw new TypeError("Extension Release archive has non-canonical ownership or time")}if(decodeCanonicalTextField(header.subarray(257,263),"ustar magic")!=="ustar"){throw new TypeError("Extension Release archive is not ustar")}if(header[263]!==48||header[264]!==48){throw new TypeError("Extension Release archive has non-canonical ustar version")}if(header[156]!==48){throw new TypeError("Extension Release archive may contain files only")}if(!isZeroBlock(header.subarray(265,345))||!isZeroBlock(header.subarray(500,512))){throw new TypeError("Extension Release archive has non-canonical metadata")}return{name:decodeCanonicalTextField(header.subarray(0,100),"name"),prefix:decodeCanonicalTextField(header.subarray(345,500),"prefix"),size:parseCanonicalOctalField(header.subarray(124,136),"file size")}};var parseExtensionReleaseArchive=(archiveBytes)=>{const entries=[];const paths=new Set;let offset=0;let previousPath="";while(offset+archiveBlockSize<=archiveBytes.byteLength){const header=archiveBytes.subarray(offset,offset+archiveBlockSize);if(isZeroBlock(header)){const trailer=archiveBytes.subarray(offset+archiveBlockSize,offset+archiveBlockSize*2);if(trailer.byteLength!==archiveBlockSize||!isZeroBlock(trailer)){throw new TypeError("Extension Release archive has an invalid trailer")}if(offset+archiveBlockSize*2!==archiveBytes.byteLength){throw new TypeError("Extension Release archive has trailing bytes")}return entries}const{name,prefix,size}=decodeCanonicalUstarHeader(header);const path=prefix===""?name:`${prefix}/${name}`;assertReleaseArchiveEntryPath(path);if(paths.has(path)||compareUtf16CodeUnits(path,previousPath)<0){throw new TypeError("Extension Release archive paths must be unique and sorted")}const bodyOffset=offset+archiveBlockSize;const bodyEnd=bodyOffset+size;if(bodyEnd>archiveBytes.byteLength){throw new TypeError("Extension Release archive entry is truncated")}const paddedBodyEnd=bodyOffset+Math.ceil(size/archiveBlockSize)*archiveBlockSize;if(!isZeroBlock(archiveBytes.subarray(bodyEnd,paddedBodyEnd))){throw new TypeError("Extension Release archive has non-zero entry padding")}entries.push({bytes:archiveBytes.slice(bodyOffset,bodyEnd),path});paths.add(path);previousPath=path;offset=paddedBodyEnd}throw new TypeError("Extension Release archive has no canonical trailer")};var validateExtensionReleaseArchiveMetadata=(entries,manifest)=>{const metadata=entries.filter(({path})=>path===PackageManifestArchivePath);if(manifest.packageManifest===undefined){if(metadata.length!==0){throw new TypeError("Extension Release declaration metadata has no retained package manifest")}return entries}const expected=new TextEncoder().encode(canonicalJson(manifest.packageManifest));const actual=metadata[0]?.bytes;if(metadata.length!==1||actual===undefined||actual.byteLength!==expected.byteLength||!actual.every((byte,index)=>byte===expected[index])){throw new TypeError("Extension Release declaration metadata does not match its retained package manifest")}return entries.filter(({path})=>path!==PackageManifestArchivePath)};var retiredPrimitiveKinds=new Map(Object.entries({dataset_blueprint:"datasetBlueprint",dataset_parser:"datasetParser",dataset_table_template:"datasetTableTemplate",documents_connector:"documentsConnector",domain_template:"domainTemplate",event_listener:"eventListener",external_application:"externalApplication",external_dataset_provider:"externalDatasetProvider",field_transformer:"fieldTransformer",knowledge_connector:"knowledgeConnector",knowledge_connector_oauth:"knowledgeConnectorOauth",knowledge_entity_adapter:"knowledgeEntityAdapter",knowledge_entity_schema:"knowledgeEntitySchema",knowledge_policy:"knowledgePolicy",knowledge_relation_adapter:"knowledgeRelationAdapter",knowledge_relation_schema:"knowledgeRelationSchema",managed_dataset_provider:"managedDatasetProvider","notification-channel":"notificationChannel",organization_sso:"organizationSso",skill_template:"skillTemplate",studio_app:"studioApp",studio_component:"studioComponent",tool_collection:"toolCollection",tool_settings_options:"toolSettingsOptions",workflow_field:"workflowField",workflow_field_collection:"workflowFieldCollection",workflow_node:"workflowNode",workflow_node_collection:"workflowNodeCollection",workflow_template:"workflowTemplate"}));var retiredGroupNames=new Map(Object.entries({directory_person_in_team:"directory_person_in_group",directory_team:"directory_group",directory_team_parent:"directory_group_parent",organization_team:"organization_group",organization_team_hierarchy:"organization_group_hierarchy",organization_team_membership:"organization_group_membership"}));var util;(function(util){util.assertEqual=(_)=>{};function assertIs(_arg){}util.assertIs=assertIs;function assertNever(_x){throw new Error}util.assertNever=assertNever;util.arrayToEnum=(items)=>{const obj={};for(const item of items){obj[item]=item}return obj};util.getValidEnumValues=(obj)=>{const validKeys=util.objectKeys(obj).filter((k)=>typeof obj[obj[k]]!=="number");const filtered={};for(const k of validKeys){filtered[k]=obj[k]}return util.objectValues(filtered)};util.objectValues=(obj)=>{return util.objectKeys(obj).map(function(e){return obj[e]})};util.objectKeys=typeof Object.keys==="function"?(obj)=>Object.keys(obj):(object)=>{const keys=[];for(const key in object){if(Object.prototype.hasOwnProperty.call(object,key)){keys.push(key)}}return keys};util.find=(arr,checker)=>{for(const item of arr){if(checker(item))return item}return};util.isInteger=typeof Number.isInteger==="function"?(val)=>Number.isInteger(val):(val)=>typeof val==="number"&&Number.isFinite(val)&&Math.floor(val)===val;function joinValues(array,separator=" | "){return array.map((val)=>typeof val==="string"?`'${val}'`:val).join(separator)}util.joinValues=joinValues;util.jsonStringifyReplacer=(_,value)=>{if(typeof value==="bigint"){return value.toString()}return value}})(util||(util={}));var objectUtil;(function(objectUtil){objectUtil.mergeShapes=(first,second)=>{return{...first,...second}}})(objectUtil||(objectUtil={}));var ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var getParsedType=(data)=>{const t=typeof data;switch(t){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN(data)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":if(Array.isArray(data)){return ZodParsedType.array}if(data===null){return ZodParsedType.null}if(data.then&&typeof data.then==="function"&&data.catch&&typeof data.catch==="function"){return ZodParsedType.promise}if(typeof Map!=="undefined"&&data instanceof Map){return ZodParsedType.map}if(typeof Set!=="undefined"&&data instanceof Set){return ZodParsedType.set}if(typeof Date!=="undefined"&&data instanceof Date){return ZodParsedType.date}return ZodParsedType.object;default:return ZodParsedType.unknown}};var ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ZodError extends Error{get errors(){return this.issues}constructor(issues){super();this.issues=[];this.addIssue=(sub)=>{this.issues=[...this.issues,sub]};this.addIssues=(subs=[])=>{this.issues=[...this.issues,...subs]};const actualProto=new.target.prototype;if(Object.setPrototypeOf){Object.setPrototypeOf(this,actualProto)}else{this.__proto__=actualProto}this.name="ZodError";this.issues=issues}format(_mapper){const mapper=_mapper||function(issue){return issue.message};const fieldErrors={_errors:[]};const processError=(error)=>{for(const issue of error.issues){if(issue.code==="invalid_union"){issue.unionErrors.map(processError)}else if(issue.code==="invalid_return_type"){processError(issue.returnTypeError)}else if(issue.code==="invalid_arguments"){processError(issue.argumentsError)}else if(issue.path.length===0){fieldErrors._errors.push(mapper(issue))}else{let curr=fieldErrors;let i=0;while(i<issue.path.length){const el=issue.path[i];const terminal=i===issue.path.length-1;if(!terminal){curr[el]=curr[el]||{_errors:[]}}else{curr[el]=curr[el]||{_errors:[]};curr[el]._errors.push(mapper(issue))}curr=curr[el];i++}}}};processError(this);return fieldErrors}static assert(value){if(!(value instanceof ZodError)){throw new Error(`Not a ZodError: ${value}`)}}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(mapper=(issue)=>issue.message){const fieldErrors={};const formErrors=[];for(const sub of this.issues){if(sub.path.length>0){const firstEl=sub.path[0];fieldErrors[firstEl]=fieldErrors[firstEl]||[];fieldErrors[firstEl].push(mapper(sub))}else{formErrors.push(mapper(sub))}}return{formErrors,fieldErrors}}get formErrors(){return this.flatten()}}ZodError.create=(issues)=>{const error=new ZodError(issues);return error};var errorMap=(issue,_ctx)=>{let message;switch(issue.code){case ZodIssueCode.invalid_type:if(issue.received===ZodParsedType.undefined){message="Required"}else{message=`Expected ${issue.expected}, received ${issue.received}`}break;case ZodIssueCode.invalid_literal:message=`Invalid literal value, expected ${JSON.stringify(issue.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:message=`Unrecognized key(s) in object: ${util.joinValues(issue.keys,", ")}`;break;case ZodIssueCode.invalid_union:message=`Invalid input`;break;case ZodIssueCode.invalid_union_discriminator:message=`Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;break;case ZodIssueCode.invalid_enum_value:message=`Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;break;case ZodIssueCode.invalid_arguments:message=`Invalid function arguments`;break;case ZodIssueCode.invalid_return_type:message=`Invalid function return type`;break;case ZodIssueCode.invalid_date:message=`Invalid date`;break;case ZodIssueCode.invalid_string:if(typeof issue.validation==="object"){if("includes"in issue.validation){message=`Invalid input: must include "${issue.validation.includes}"`;if(typeof issue.validation.position==="number"){message=`${message} at one or more positions greater than or equal to ${issue.validation.position}`}}else if("startsWith"in issue.validation){message=`Invalid input: must start with "${issue.validation.startsWith}"`}else if("endsWith"in issue.validation){message=`Invalid input: must end with "${issue.validation.endsWith}"`}else{util.assertNever(issue.validation)}}else if(issue.validation!=="regex"){message=`Invalid ${issue.validation}`}else{message="Invalid"}break;case ZodIssueCode.too_small:if(issue.type==="array")message=`Array must contain ${issue.exact?"exactly":issue.inclusive?`at least`:`more than`} ${issue.minimum} element(s)`;else if(issue.type==="string")message=`String must contain ${issue.exact?"exactly":issue.inclusive?`at least`:`over`} ${issue.minimum} character(s)`;else if(issue.type==="number")message=`Number must be ${issue.exact?`exactly equal to `:issue.inclusive?`greater than or equal to `:`greater than `}${issue.minimum}`;else if(issue.type==="bigint")message=`Number must be ${issue.exact?`exactly equal to `:issue.inclusive?`greater than or equal to `:`greater than `}${issue.minimum}`;else if(issue.type==="date")message=`Date must be ${issue.exact?`exactly equal to `:issue.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(issue.minimum))}`;else message="Invalid input";break;case ZodIssueCode.too_big:if(issue.type==="array")message=`Array must contain ${issue.exact?`exactly`:issue.inclusive?`at most`:`less than`} ${issue.maximum} element(s)`;else if(issue.type==="string")message=`String must contain ${issue.exact?`exactly`:issue.inclusive?`at most`:`under`} ${issue.maximum} character(s)`;else if(issue.type==="number")message=`Number must be ${issue.exact?`exactly`:issue.inclusive?`less than or equal to`:`less than`} ${issue.maximum}`;else if(issue.type==="bigint")message=`BigInt must be ${issue.exact?`exactly`:issue.inclusive?`less than or equal to`:`less than`} ${issue.maximum}`;else if(issue.type==="date")message=`Date must be ${issue.exact?`exactly`:issue.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(issue.maximum))}`;else message="Invalid input";break;case ZodIssueCode.custom:message=`Invalid input`;break;case ZodIssueCode.invalid_intersection_types:message=`Intersection results could not be merged`;break;case ZodIssueCode.not_multiple_of:message=`Number must be a multiple of ${issue.multipleOf}`;break;case ZodIssueCode.not_finite:message="Number must be finite";break;default:message=_ctx.defaultError;util.assertNever(issue)}return{message}};var en_default=errorMap;var overrideErrorMap=en_default;function getErrorMap(){return overrideErrorMap}var makeIssue=(params)=>{const{data,path,errorMaps,issueData}=params;const fullPath=[...path,...issueData.path||[]];const fullIssue={...issueData,path:fullPath};if(issueData.message!==undefined){return{...issueData,path:fullPath,message:issueData.message}}let errorMessage="";const maps=errorMaps.filter((m)=>!!m).slice().reverse();for(const map of maps){errorMessage=map(fullIssue,{data,defaultError:errorMessage}).message}return{...issueData,path:fullPath,message:errorMessage}};function addIssueToContext(ctx,issueData){const overrideMap=getErrorMap();const issue=makeIssue({issueData,data:ctx.data,path:ctx.path,errorMaps:[ctx.common.contextualErrorMap,ctx.schemaErrorMap,overrideMap,overrideMap===en_default?undefined:en_default].filter((x)=>!!x)});ctx.common.issues.push(issue)}class ParseStatus{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(status,results){const arrayValue=[];for(const s of results){if(s.status==="aborted")return INVALID;if(s.status==="dirty")status.dirty();arrayValue.push(s.value)}return{status:status.value,value:arrayValue}}static async mergeObjectAsync(status,pairs){const syncPairs=[];for(const pair of pairs){const key=await pair.key;const value=await pair.value;syncPairs.push({key,value})}return ParseStatus.mergeObjectSync(status,syncPairs)}static mergeObjectSync(status,pairs){const finalObject={};for(const pair of pairs){const{key,value}=pair;if(key.status==="aborted")return INVALID;if(value.status==="aborted")return INVALID;if(key.status==="dirty")status.dirty();if(value.status==="dirty")status.dirty();if(key.value!=="__proto__"&&(typeof value.value!=="undefined"||pair.alwaysSet)){finalObject[key.value]=value.value}}return{status:status.value,value:finalObject}}}var INVALID=Object.freeze({status:"aborted"});var DIRTY=(value)=>({status:"dirty",value});var OK=(value)=>({status:"valid",value});var isAborted=(x)=>x.status==="aborted";var isDirty=(x)=>x.status==="dirty";var isValid=(x)=>x.status==="valid";var isAsync=(x)=>typeof Promise!=="undefined"&&x instanceof Promise;var errorUtil;(function(errorUtil){errorUtil.errToObj=(message)=>typeof message==="string"?{message}:message||{};errorUtil.toString=(message)=>typeof message==="string"?message:message?.message})(errorUtil||(errorUtil={}));class ParseInputLazyPath{constructor(parent,value,path,key){this._cachedPath=[];this.parent=parent;this.data=value;this._path=path;this._key=key}get path(){if(!this._cachedPath.length){if(Array.isArray(this._key)){this._cachedPath.push(...this._path,...this._key)}else{this._cachedPath.push(...this._path,this._key)}}return this._cachedPath}}var handleResult=(ctx,result)=>{if(isValid(result)){return{success:true,data:result.value}}else{if(!ctx.common.issues.length){throw new Error("Validation failed but no issues detected.")}return{success:false,get error(){if(this._error)return this._error;const error=new ZodError(ctx.common.issues);this._error=error;return this._error}}}};function processCreateParams(params){if(!params)return{};const{errorMap,invalid_type_error,required_error,description}=params;if(errorMap&&(invalid_type_error||required_error)){throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`)}if(errorMap)return{errorMap,description};const customMap=(iss,ctx)=>{const{message}=params;if(iss.code==="invalid_enum_value"){return{message:message??ctx.defaultError}}if(typeof ctx.data==="undefined"){return{message:message??required_error??ctx.defaultError}}if(iss.code!=="invalid_type")return{message:ctx.defaultError};return{message:message??invalid_type_error??ctx.defaultError}};return{errorMap:customMap,description}}class ZodType{get description(){return this._def.description}_getType(input){return getParsedType(input.data)}_getOrReturnCtx(input,ctx){return ctx||{common:input.parent.common,data:input.data,parsedType:getParsedType(input.data),schemaErrorMap:this._def.errorMap,path:input.path,parent:input.parent}}_processInputParams(input){return{status:new ParseStatus,ctx:{common:input.parent.common,data:input.data,parsedType:getParsedType(input.data),schemaErrorMap:this._def.errorMap,path:input.path,parent:input.parent}}}_parseSync(input){const result=this._parse(input);if(isAsync(result)){throw new Error("Synchronous parse encountered promise.")}return result}_parseAsync(input){const result=this._parse(input);return Promise.resolve(result)}parse(data,params){const result=this.safeParse(data,params);if(result.success)return result.data;throw result.error}safeParse(data,params){const ctx={common:{issues:[],async:params?.async??false,contextualErrorMap:params?.errorMap},path:params?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data,parsedType:getParsedType(data)};const result=this._parseSync({data,path:ctx.path,parent:ctx});return handleResult(ctx,result)}"~validate"(data){const ctx={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data,parsedType:getParsedType(data)};if(!this["~standard"].async){try{const result=this._parseSync({data,path:[],parent:ctx});return isValid(result)?{value:result.value}:{issues:ctx.common.issues}}catch(err){if(err?.message?.toLowerCase()?.includes("encountered")){this["~standard"].async=true}ctx.common={issues:[],async:true}}}return this._parseAsync({data,path:[],parent:ctx}).then((result)=>isValid(result)?{value:result.value}:{issues:ctx.common.issues})}async parseAsync(data,params){const result=await this.safeParseAsync(data,params);if(result.success)return result.data;throw result.error}async safeParseAsync(data,params){const ctx={common:{issues:[],contextualErrorMap:params?.errorMap,async:true},path:params?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data,parsedType:getParsedType(data)};const maybeAsyncResult=this._parse({data,path:ctx.path,parent:ctx});const result=await(isAsync(maybeAsyncResult)?maybeAsyncResult:Promise.resolve(maybeAsyncResult));return handleResult(ctx,result)}refine(check,message){const getIssueProperties=(val)=>{if(typeof message==="string"||typeof message==="undefined"){return{message}}else if(typeof message==="function"){return message(val)}else{return message}};return this._refinement((val,ctx)=>{const result=check(val);const setError=()=>ctx.addIssue({code:ZodIssueCode.custom,...getIssueProperties(val)});if(typeof Promise!=="undefined"&&result instanceof Promise){return result.then((data)=>{if(!data){setError();return false}else{return true}})}if(!result){setError();return false}else{return true}})}refinement(check,refinementData){return this._refinement((val,ctx)=>{if(!check(val)){ctx.addIssue(typeof refinementData==="function"?refinementData(val,ctx):refinementData);return false}else{return true}})}_refinement(refinement){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement}})}superRefine(refinement){return this._refinement(refinement)}constructor(def){this.spa=this.safeParseAsync;this._def=def;this.parse=this.parse.bind(this);this.safeParse=this.safeParse.bind(this);this.parseAsync=this.parseAsync.bind(this);this.safeParseAsync=this.safeParseAsync.bind(this);this.spa=this.spa.bind(this);this.refine=this.refine.bind(this);this.refinement=this.refinement.bind(this);this.superRefine=this.superRefine.bind(this);this.optional=this.optional.bind(this);this.nullable=this.nullable.bind(this);this.nullish=this.nullish.bind(this);this.array=this.array.bind(this);this.promise=this.promise.bind(this);this.or=this.or.bind(this);this.and=this.and.bind(this);this.transform=this.transform.bind(this);this.brand=this.brand.bind(this);this.default=this.default.bind(this);this.catch=this.catch.bind(this);this.describe=this.describe.bind(this);this.pipe=this.pipe.bind(this);this.readonly=this.readonly.bind(this);this.isNullable=this.isNullable.bind(this);this.isOptional=this.isOptional.bind(this);this["~standard"]={version:1,vendor:"zod",validate:(data)=>this["~validate"](data)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(option){return ZodUnion.create([this,option],this._def)}and(incoming){return ZodIntersection.create(this,incoming,this._def)}transform(transform){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform}})}default(def){const defaultValueFunc=typeof def==="function"?def:()=>def;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:defaultValueFunc,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(def){const catchValueFunc=typeof def==="function"?def:()=>def;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:catchValueFunc,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(description){const This=this.constructor;return new This({...this._def,description})}pipe(target){return ZodPipeline.create(this,target)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(undefined).success}isNullable(){return this.safeParse(null).success}}var cuidRegex=/^c[^\s-]{8,}$/i;var cuid2Regex=/^[0-9a-z]+$/;var ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i;var uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;var nanoidRegex=/^[a-z0-9_-]{21}$/i;var jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;var durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;var emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;var _emojiRegex=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;var emojiRegex;var ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;var ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;var ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;var ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;var base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;var base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;var dateRegexSource=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;var dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(args){let secondsRegexSource=`[0-5]\\d`;if(args.precision){secondsRegexSource=`${secondsRegexSource}\\.\\d{${args.precision}}`}else if(args.precision==null){secondsRegexSource=`${secondsRegexSource}(\\.\\d+)?`}const secondsQuantifier=args.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`}function timeRegex(args){return new RegExp(`^${timeRegexSource(args)}$`)}function datetimeRegex(args){let regex=`${dateRegexSource}T${timeRegexSource(args)}`;const opts=[];opts.push(args.local?`Z?`:`Z`);if(args.offset)opts.push(`([+-]\\d{2}:?\\d{2})`);regex=`${regex}(${opts.join("|")})`;return new RegExp(`^${regex}$`)}function isValidIP(ip,version){if((version==="v4"||!version)&&ipv4Regex.test(ip)){return true}if((version==="v6"||!version)&&ipv6Regex.test(ip)){return true}return false}function isValidJWT(jwt,alg){if(!jwtRegex.test(jwt))return false;try{const[header]=jwt.split(".");if(!header)return false;const base64=header.replace(/-/g,"+").replace(/_/g,"/").padEnd(header.length+(4-header.length%4)%4,"=");const decoded=JSON.parse(atob(base64));if(typeof decoded!=="object"||decoded===null)return false;if("typ"in decoded&&decoded?.typ!=="JWT")return false;if(!decoded.alg)return false;if(alg&&decoded.alg!==alg)return false;return true}catch{return false}}function isValidCidr(ip,version){if((version==="v4"||!version)&&ipv4CidrRegex.test(ip)){return true}if((version==="v6"||!version)&&ipv6CidrRegex.test(ip)){return true}return false}class ZodString extends ZodType{_parse(input){if(this._def.coerce){input.data=String(input.data)}const parsedType=this._getType(input);if(parsedType!==ZodParsedType.string){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:ctx.parsedType});return INVALID}const status=new ParseStatus;let ctx=undefined;for(const check of this._def.checks){if(check.kind==="min"){if(input.data.length<check.value){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check.value,type:"string",inclusive:true,exact:false,message:check.message});status.dirty()}}else if(check.kind==="max"){if(input.data.length>check.value){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check.value,type:"string",inclusive:true,exact:false,message:check.message});status.dirty()}}else if(check.kind==="length"){const tooBig=input.data.length>check.value;const tooSmall=input.data.length<check.value;if(tooBig||tooSmall){ctx=this._getOrReturnCtx(input,ctx);if(tooBig){addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check.value,type:"string",inclusive:true,exact:true,message:check.message})}else if(tooSmall){addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check.value,type:"string",inclusive:true,exact:true,message:check.message})}status.dirty()}}else if(check.kind==="email"){if(!emailRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"email",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="emoji"){if(!emojiRegex){emojiRegex=new RegExp(_emojiRegex,"u")}if(!emojiRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"emoji",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="uuid"){if(!uuidRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"uuid",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="nanoid"){if(!nanoidRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="cuid"){if(!cuidRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"cuid",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="cuid2"){if(!cuid2Regex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="ulid"){if(!ulidRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"ulid",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="url"){try{new URL(input.data)}catch{ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"url",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="regex"){check.regex.lastIndex=0;const testResult=check.regex.test(input.data);if(!testResult){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"regex",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="trim"){input.data=input.data.trim()}else if(check.kind==="includes"){if(!input.data.includes(check.value,check.position)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{includes:check.value,position:check.position},message:check.message});status.dirty()}}else if(check.kind==="toLowerCase"){input.data=input.data.toLowerCase()}else if(check.kind==="toUpperCase"){input.data=input.data.toUpperCase()}else if(check.kind==="startsWith"){if(!input.data.startsWith(check.value)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{startsWith:check.value},message:check.message});status.dirty()}}else if(check.kind==="endsWith"){if(!input.data.endsWith(check.value)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{endsWith:check.value},message:check.message});status.dirty()}}else if(check.kind==="datetime"){const regex=datetimeRegex(check);if(!regex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"datetime",message:check.message});status.dirty()}}else if(check.kind==="date"){const regex=dateRegex;if(!regex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"date",message:check.message});status.dirty()}}else if(check.kind==="time"){const regex=timeRegex(check);if(!regex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"time",message:check.message});status.dirty()}}else if(check.kind==="duration"){if(!durationRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"duration",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="ip"){if(!isValidIP(input.data,check.version)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"ip",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="jwt"){if(!isValidJWT(input.data,check.alg)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"jwt",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="cidr"){if(!isValidCidr(input.data,check.version)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"cidr",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="base64"){if(!base64Regex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"base64",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="base64url"){if(!base64urlRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"base64url",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else{util.assertNever(check)}}return{status:status.value,value:input.data}}_regex(regex,validation,message){return this.refinement((data)=>regex.test(data),{validation,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(message)})}_addCheck(check){return new ZodString({...this._def,checks:[...this._def.checks,check]})}email(message){return this._addCheck({kind:"email",...errorUtil.errToObj(message)})}url(message){return this._addCheck({kind:"url",...errorUtil.errToObj(message)})}emoji(message){return this._addCheck({kind:"emoji",...errorUtil.errToObj(message)})}uuid(message){return this._addCheck({kind:"uuid",...errorUtil.errToObj(message)})}nanoid(message){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(message)})}cuid(message){return this._addCheck({kind:"cuid",...errorUtil.errToObj(message)})}cuid2(message){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(message)})}ulid(message){return this._addCheck({kind:"ulid",...errorUtil.errToObj(message)})}base64(message){return this._addCheck({kind:"base64",...errorUtil.errToObj(message)})}base64url(message){return this._addCheck({kind:"base64url",...errorUtil.errToObj(message)})}jwt(options){return this._addCheck({kind:"jwt",...errorUtil.errToObj(options)})}ip(options){return this._addCheck({kind:"ip",...errorUtil.errToObj(options)})}cidr(options){return this._addCheck({kind:"cidr",...errorUtil.errToObj(options)})}datetime(options){if(typeof options==="string"){return this._addCheck({kind:"datetime",precision:null,offset:false,local:false,message:options})}return this._addCheck({kind:"datetime",precision:typeof options?.precision==="undefined"?null:options?.precision,offset:options?.offset??false,local:options?.local??false,...errorUtil.errToObj(options?.message)})}date(message){return this._addCheck({kind:"date",message})}time(options){if(typeof options==="string"){return this._addCheck({kind:"time",precision:null,message:options})}return this._addCheck({kind:"time",precision:typeof options?.precision==="undefined"?null:options?.precision,...errorUtil.errToObj(options?.message)})}duration(message){return this._addCheck({kind:"duration",...errorUtil.errToObj(message)})}regex(regex,message){return this._addCheck({kind:"regex",regex,...errorUtil.errToObj(message)})}includes(value,options){return this._addCheck({kind:"includes",value,position:options?.position,...errorUtil.errToObj(options?.message)})}startsWith(value,message){return this._addCheck({kind:"startsWith",value,...errorUtil.errToObj(message)})}endsWith(value,message){return this._addCheck({kind:"endsWith",value,...errorUtil.errToObj(message)})}min(minLength,message){return this._addCheck({kind:"min",value:minLength,...errorUtil.errToObj(message)})}max(maxLength,message){return this._addCheck({kind:"max",value:maxLength,...errorUtil.errToObj(message)})}length(len,message){return this._addCheck({kind:"length",value:len,...errorUtil.errToObj(message)})}nonempty(message){return this.min(1,errorUtil.errToObj(message))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((ch)=>ch.kind==="datetime")}get isDate(){return!!this._def.checks.find((ch)=>ch.kind==="date")}get isTime(){return!!this._def.checks.find((ch)=>ch.kind==="time")}get isDuration(){return!!this._def.checks.find((ch)=>ch.kind==="duration")}get isEmail(){return!!this._def.checks.find((ch)=>ch.kind==="email")}get isURL(){return!!this._def.checks.find((ch)=>ch.kind==="url")}get isEmoji(){return!!this._def.checks.find((ch)=>ch.kind==="emoji")}get isUUID(){return!!this._def.checks.find((ch)=>ch.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((ch)=>ch.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((ch)=>ch.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((ch)=>ch.kind==="cuid2")}get isULID(){return!!this._def.checks.find((ch)=>ch.kind==="ulid")}get isIP(){return!!this._def.checks.find((ch)=>ch.kind==="ip")}get isCIDR(){return!!this._def.checks.find((ch)=>ch.kind==="cidr")}get isBase64(){return!!this._def.checks.find((ch)=>ch.kind==="base64")}get isBase64url(){return!!this._def.checks.find((ch)=>ch.kind==="base64url")}get minLength(){let min=null;for(const ch of this._def.checks){if(ch.kind==="min"){if(min===null||ch.value>min)min=ch.value}}return min}get maxLength(){let max=null;for(const ch of this._def.checks){if(ch.kind==="max"){if(max===null||ch.value<max)max=ch.value}}return max}}ZodString.create=(params)=>{return new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:params?.coerce??false,...processCreateParams(params)})};function floatSafeRemainder(val,step){const valDecCount=(val.toString().split(".")[1]||"").length;const stepDecCount=(step.toString().split(".")[1]||"").length;const decCount=valDecCount>stepDecCount?valDecCount:stepDecCount;const valInt=Number.parseInt(val.toFixed(decCount).replace(".",""));const stepInt=Number.parseInt(step.toFixed(decCount).replace(".",""));return valInt%stepInt/10**decCount}class ZodNumber extends ZodType{constructor(){super(...arguments);this.min=this.gte;this.max=this.lte;this.step=this.multipleOf}_parse(input){if(this._def.coerce){input.data=Number(input.data)}const parsedType=this._getType(input);if(parsedType!==ZodParsedType.number){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:ctx.parsedType});return INVALID}let ctx=undefined;const status=new ParseStatus;for(const check of this._def.checks){if(check.kind==="int"){if(!util.isInteger(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:check.message});status.dirty()}}else if(check.kind==="min"){const tooSmall=check.inclusive?input.data<check.value:input.data<=check.value;if(tooSmall){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check.value,type:"number",inclusive:check.inclusive,exact:false,message:check.message});status.dirty()}}else if(check.kind==="max"){const tooBig=check.inclusive?input.data>check.value:input.data>=check.value;if(tooBig){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check.value,type:"number",inclusive:check.inclusive,exact:false,message:check.message});status.dirty()}}else if(check.kind==="multipleOf"){if(floatSafeRemainder(input.data,check.value)!==0){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.not_multiple_of,multipleOf:check.value,message:check.message});status.dirty()}}else if(check.kind==="finite"){if(!Number.isFinite(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.not_finite,message:check.message});status.dirty()}}else{util.assertNever(check)}}return{status:status.value,value:input.data}}gte(value,message){return this.setLimit("min",value,true,errorUtil.toString(message))}gt(value,message){return this.setLimit("min",value,false,errorUtil.toString(message))}lte(value,message){return this.setLimit("max",value,true,errorUtil.toString(message))}lt(value,message){return this.setLimit("max",value,false,errorUtil.toString(message))}setLimit(kind,value,inclusive,message){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind,value,inclusive,message:errorUtil.toString(message)}]})}_addCheck(check){return new ZodNumber({...this._def,checks:[...this._def.checks,check]})}int(message){return this._addCheck({kind:"int",message:errorUtil.toString(message)})}positive(message){return this._addCheck({kind:"min",value:0,inclusive:false,message:errorUtil.toString(message)})}negative(message){return this._addCheck({kind:"max",value:0,inclusive:false,message:errorUtil.toString(message)})}nonpositive(message){return this._addCheck({kind:"max",value:0,inclusive:true,message:errorUtil.toString(message)})}nonnegative(message){return this._addCheck({kind:"min",value:0,inclusive:true,message:errorUtil.toString(message)})}multipleOf(value,message){return this._addCheck({kind:"multipleOf",value,message:errorUtil.toString(message)})}finite(message){return this._addCheck({kind:"finite",message:errorUtil.toString(message)})}safe(message){return this._addCheck({kind:"min",inclusive:true,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(message)})._addCheck({kind:"max",inclusive:true,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(message)})}get minValue(){let min=null;for(const ch of this._def.checks){if(ch.kind==="min"){if(min===null||ch.value>min)min=ch.value}}return min}get maxValue(){let max=null;for(const ch of this._def.checks){if(ch.kind==="max"){if(max===null||ch.value<max)max=ch.value}}return max}get isInt(){return!!this._def.checks.find((ch)=>ch.kind==="int"||ch.kind==="multipleOf"&&util.isInteger(ch.value))}get isFinite(){let max=null;let min=null;for(const ch of this._def.checks){if(ch.kind==="finite"||ch.kind==="int"||ch.kind==="multipleOf"){return true}else if(ch.kind==="min"){if(min===null||ch.value>min)min=ch.value}else if(ch.kind==="max"){if(max===null||ch.value<max)max=ch.value}}return Number.isFinite(min)&&Number.isFinite(max)}}ZodNumber.create=(params)=>{return new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:params?.coerce||false,...processCreateParams(params)})};class ZodBigInt extends ZodType{constructor(){super(...arguments);this.min=this.gte;this.max=this.lte}_parse(input){if(this._def.coerce){try{input.data=BigInt(input.data)}catch{return this._getInvalidInput(input)}}const parsedType=this._getType(input);if(parsedType!==ZodParsedType.bigint){return this._getInvalidInput(input)}let ctx=undefined;const status=new ParseStatus;for(const check of this._def.checks){if(check.kind==="min"){const tooSmall=check.inclusive?input.data<check.value:input.data<=check.value;if(tooSmall){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_small,type:"bigint",minimum:check.value,inclusive:check.inclusive,message:check.message});status.dirty()}}else if(check.kind==="max"){const tooBig=check.inclusive?input.data>check.value:input.data>=check.value;if(tooBig){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_big,type:"bigint",maximum:check.value,inclusive:check.inclusive,message:check.message});status.dirty()}}else if(check.kind==="multipleOf"){if(input.data%check.value!==BigInt(0)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.not_multiple_of,multipleOf:check.value,message:check.message});status.dirty()}}else{util.assertNever(check)}}return{status:status.value,value:input.data}}_getInvalidInput(input){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:ctx.parsedType});return INVALID}gte(value,message){return this.setLimit("min",value,true,errorUtil.toString(message))}gt(value,message){return this.setLimit("min",value,false,errorUtil.toString(message))}lte(value,message){return this.setLimit("max",value,true,errorUtil.toString(message))}lt(value,message){return this.setLimit("max",value,false,errorUtil.toString(message))}setLimit(kind,value,inclusive,message){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind,value,inclusive,message:errorUtil.toString(message)}]})}_addCheck(check){return new ZodBigInt({...this._def,checks:[...this._def.checks,check]})}positive(message){return this._addCheck({kind:"min",value:BigInt(0),inclusive:false,message:errorUtil.toString(message)})}negative(message){return this._addCheck({kind:"max",value:BigInt(0),inclusive:false,message:errorUtil.toString(message)})}nonpositive(message){return this._addCheck({kind:"max",value:BigInt(0),inclusive:true,message:errorUtil.toString(message)})}nonnegative(message){return this._addCheck({kind:"min",value:BigInt(0),inclusive:true,message:errorUtil.toString(message)})}multipleOf(value,message){return this._addCheck({kind:"multipleOf",value,message:errorUtil.toString(message)})}get minValue(){let min=null;for(const ch of this._def.checks){if(ch.kind==="min"){if(min===null||ch.value>min)min=ch.value}}return min}get maxValue(){let max=null;for(const ch of this._def.checks){if(ch.kind==="max"){if(max===null||ch.value<max)max=ch.value}}return max}}ZodBigInt.create=(params)=>{return new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:params?.coerce??false,...processCreateParams(params)})};class ZodBoolean extends ZodType{_parse(input){if(this._def.coerce){input.data=Boolean(input.data)}const parsedType=this._getType(input);if(parsedType!==ZodParsedType.boolean){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:ctx.parsedType});return INVALID}return OK(input.data)}}ZodBoolean.create=(params)=>{return new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:params?.coerce||false,...processCreateParams(params)})};class ZodDate extends ZodType{_parse(input){if(this._def.coerce){input.data=new Date(input.data)}const parsedType=this._getType(input);if(parsedType!==ZodParsedType.date){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:ctx.parsedType});return INVALID}if(Number.isNaN(input.data.getTime())){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{code:ZodIssueCode.invalid_date});return INVALID}const status=new ParseStatus;let ctx=undefined;for(const check of this._def.checks){if(check.kind==="min"){if(input.data.getTime()<check.value){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_small,message:check.message,inclusive:true,exact:false,minimum:check.value,type:"date"});status.dirty()}}else if(check.kind==="max"){if(input.data.getTime()>check.value){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_big,message:check.message,inclusive:true,exact:false,maximum:check.value,type:"date"});status.dirty()}}else{util.assertNever(check)}}return{status:status.value,value:new Date(input.data.getTime())}}_addCheck(check){return new ZodDate({...this._def,checks:[...this._def.checks,check]})}min(minDate,message){return this._addCheck({kind:"min",value:minDate.getTime(),message:errorUtil.toString(message)})}max(maxDate,message){return this._addCheck({kind:"max",value:maxDate.getTime(),message:errorUtil.toString(message)})}get minDate(){let min=null;for(const ch of this._def.checks){if(ch.kind==="min"){if(min===null||ch.value>min)min=ch.value}}return min!=null?new Date(min):null}get maxDate(){let max=null;for(const ch of this._def.checks){if(ch.kind==="max"){if(max===null||ch.value<max)max=ch.value}}return max!=null?new Date(max):null}}ZodDate.create=(params)=>{return new ZodDate({checks:[],coerce:params?.coerce||false,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(params)})};class ZodSymbol extends ZodType{_parse(input){const parsedType=this._getType(input);if(parsedType!==ZodParsedType.symbol){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:ctx.parsedType});return INVALID}return OK(input.data)}}ZodSymbol.create=(params)=>{return new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(params)})};class ZodUndefined extends ZodType{_parse(input){const parsedType=this._getType(input);if(parsedType!==ZodParsedType.undefined){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:ctx.parsedType});return INVALID}return OK(input.data)}}ZodUndefined.create=(params)=>{return new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(params)})};class ZodNull extends ZodType{_parse(input){const parsedType=this._getType(input);if(parsedType!==ZodParsedType.null){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:ctx.parsedType});return INVALID}return OK(input.data)}}ZodNull.create=(params)=>{return new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(params)})};class ZodAny extends ZodType{constructor(){super(...arguments);this._any=true}_parse(input){return OK(input.data)}}ZodAny.create=(params)=>{return new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(params)})};class ZodUnknown extends ZodType{constructor(){super(...arguments);this._unknown=true}_parse(input){return OK(input.data)}}ZodUnknown.create=(params)=>{return new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(params)})};class ZodNever extends ZodType{_parse(input){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:ctx.parsedType});return INVALID}}ZodNever.create=(params)=>{return new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(params)})};class ZodVoid extends ZodType{_parse(input){const parsedType=this._getType(input);if(parsedType!==ZodParsedType.undefined){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:ctx.parsedType});return INVALID}return OK(input.data)}}ZodVoid.create=(params)=>{return new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(params)})};class ZodArray extends ZodType{_parse(input){const{ctx,status}=this._processInputParams(input);const def=this._def;if(ctx.parsedType!==ZodParsedType.array){addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:ctx.parsedType});return INVALID}if(def.exactLength!==null){const tooBig=ctx.data.length>def.exactLength.value;const tooSmall=ctx.data.length<def.exactLength.value;if(tooBig||tooSmall){addIssueToContext(ctx,{code:tooBig?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:tooSmall?def.exactLength.value:undefined,maximum:tooBig?def.exactLength.value:undefined,type:"array",inclusive:true,exact:true,message:def.exactLength.message});status.dirty()}}if(def.minLength!==null){if(ctx.data.length<def.minLength.value){addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:def.minLength.value,type:"array",inclusive:true,exact:false,message:def.minLength.message});status.dirty()}}if(def.maxLength!==null){if(ctx.data.length>def.maxLength.value){addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:def.maxLength.value,type:"array",inclusive:true,exact:false,message:def.maxLength.message});status.dirty()}}if(ctx.common.async){return Promise.all([...ctx.data].map((item,i)=>{return def.type._parseAsync(new ParseInputLazyPath(ctx,item,ctx.path,i))})).then((result)=>{return ParseStatus.mergeArray(status,result)})}const result=[...ctx.data].map((item,i)=>{return def.type._parseSync(new ParseInputLazyPath(ctx,item,ctx.path,i))});return ParseStatus.mergeArray(status,result)}get element(){return this._def.type}min(minLength,message){return new ZodArray({...this._def,minLength:{value:minLength,message:errorUtil.toString(message)}})}max(maxLength,message){return new ZodArray({...this._def,maxLength:{value:maxLength,message:errorUtil.toString(message)}})}length(len,message){return new ZodArray({...this._def,exactLength:{value:len,message:errorUtil.toString(message)}})}nonempty(message){return this.min(1,message)}}ZodArray.create=(schema,params)=>{return new ZodArray({type:schema,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(params)})};function deepPartialify(schema){if(schema instanceof ZodObject){const newShape={};for(const key in schema.shape){const fieldSchema=schema.shape[key];newShape[key]=ZodOptional.create(deepPartialify(fieldSchema))}return new ZodObject({...schema._def,shape:()=>newShape})}else if(schema instanceof ZodArray){return new ZodArray({...schema._def,type:deepPartialify(schema.element)})}else if(schema instanceof ZodOptional){return ZodOptional.create(deepPartialify(schema.unwrap()))}else if(schema instanceof ZodNullable){return ZodNullable.create(deepPartialify(schema.unwrap()))}else if(schema instanceof ZodTuple){return ZodTuple.create(schema.items.map((item)=>deepPartialify(item)))}else{return schema}}class ZodObject extends ZodType{constructor(){super(...arguments);this._cached=null;this.nonstrict=this.passthrough;this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const shape=this._def.shape();const keys=util.objectKeys(shape);this._cached={shape,keys};return this._cached}_parse(input){const parsedType=this._getType(input);if(parsedType!==ZodParsedType.object){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ctx.parsedType});return INVALID}const{status,ctx}=this._processInputParams(input);const{shape,keys:shapeKeys}=this._getCached();const extraKeys=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip")){for(const key in ctx.data){if(!shapeKeys.includes(key)){extraKeys.push(key)}}}const pairs=[];for(const key of shapeKeys){const keyValidator=shape[key];const value=ctx.data[key];pairs.push({key:{status:"valid",value:key},value:keyValidator._parse(new ParseInputLazyPath(ctx,value,ctx.path,key)),alwaysSet:key in ctx.data})}if(this._def.catchall instanceof ZodNever){const unknownKeys=this._def.unknownKeys;if(unknownKeys==="passthrough"){for(const key of extraKeys){pairs.push({key:{status:"valid",value:key},value:{status:"valid",value:ctx.data[key]}})}}else if(unknownKeys==="strict"){if(extraKeys.length>0){addIssueToContext(ctx,{code:ZodIssueCode.unrecognized_keys,keys:extraKeys});status.dirty()}}else if(unknownKeys==="strip"){}else{throw new Error(`Internal ZodObject error: invalid unknownKeys value.`)}}else{const catchall=this._def.catchall;for(const key of extraKeys){const value=ctx.data[key];pairs.push({key:{status:"valid",value:key},value:catchall._parse(new ParseInputLazyPath(ctx,value,ctx.path,key)),alwaysSet:key in ctx.data})}}if(ctx.common.async){return Promise.resolve().then(async()=>{const syncPairs=[];for(const pair of pairs){const key=await pair.key;const value=await pair.value;syncPairs.push({key,value,alwaysSet:pair.alwaysSet})}return syncPairs}).then((syncPairs)=>{return ParseStatus.mergeObjectSync(status,syncPairs)})}else{return ParseStatus.mergeObjectSync(status,pairs)}}get shape(){return this._def.shape()}strict(message){errorUtil.errToObj;return new ZodObject({...this._def,unknownKeys:"strict",...message!==undefined?{errorMap:(issue,ctx)=>{const defaultError=this._def.errorMap?.(issue,ctx).message??ctx.defaultError;if(issue.code==="unrecognized_keys")return{message:errorUtil.errToObj(message).message??defaultError};return{message:defaultError}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(augmentation){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...augmentation})})}merge(merging){const merged=new ZodObject({unknownKeys:merging._def.unknownKeys,catchall:merging._def.catchall,shape:()=>({...this._def.shape(),...merging._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject});return merged}setKey(key,schema){return this.augment({[key]:schema})}catchall(index){return new ZodObject({...this._def,catchall:index})}pick(mask){const shape={};for(const key of util.objectKeys(mask)){if(mask[key]&&this.shape[key]){shape[key]=this.shape[key]}}return new ZodObject({...this._def,shape:()=>shape})}omit(mask){const shape={};for(const key of util.objectKeys(this.shape)){if(!mask[key]){shape[key]=this.shape[key]}}return new ZodObject({...this._def,shape:()=>shape})}deepPartial(){return deepPartialify(this)}partial(mask){const newShape={};for(const key of util.objectKeys(this.shape)){const fieldSchema=this.shape[key];if(mask&&!mask[key]){newShape[key]=fieldSchema}else{newShape[key]=fieldSchema.optional()}}return new ZodObject({...this._def,shape:()=>newShape})}required(mask){const newShape={};for(const key of util.objectKeys(this.shape)){if(mask&&!mask[key]){newShape[key]=this.shape[key]}else{const fieldSchema=this.shape[key];let newField=fieldSchema;while(newField instanceof ZodOptional){newField=newField._def.innerType}newShape[key]=newField}}return new ZodObject({...this._def,shape:()=>newShape})}keyof(){return createZodEnum(util.objectKeys(this.shape))}}ZodObject.create=(shape,params)=>{return new ZodObject({shape:()=>shape,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(params)})};ZodObject.strictCreate=(shape,params)=>{return new ZodObject({shape:()=>shape,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(params)})};ZodObject.lazycreate=(shape,params)=>{return new ZodObject({shape,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(params)})};class ZodUnion extends ZodType{_parse(input){const{ctx}=this._processInputParams(input);const options=this._def.options;function handleResults(results){for(const result of results){if(result.result.status==="valid"){return result.result}}for(const result of results){if(result.result.status==="dirty"){ctx.common.issues.push(...result.ctx.common.issues);return result.result}}const unionErrors=results.map((result)=>new ZodError(result.ctx.common.issues));addIssueToContext(ctx,{code:ZodIssueCode.invalid_union,unionErrors});return INVALID}if(ctx.common.async){return Promise.all(options.map(async(option)=>{const childCtx={...ctx,common:{...ctx.common,issues:[]},parent:null};return{result:await option._parseAsync({data:ctx.data,path:ctx.path,parent:childCtx}),ctx:childCtx}})).then(handleResults)}else{let dirty=undefined;const issues=[];for(const option of options){const childCtx={...ctx,common:{...ctx.common,issues:[]},parent:null};const result=option._parseSync({data:ctx.data,path:ctx.path,parent:childCtx});if(result.status==="valid"){return result}else if(result.status==="dirty"&&!dirty){dirty={result,ctx:childCtx}}if(childCtx.common.issues.length){issues.push(childCtx.common.issues)}}if(dirty){ctx.common.issues.push(...dirty.ctx.common.issues);return dirty.result}const unionErrors=issues.map((issues)=>new ZodError(issues));addIssueToContext(ctx,{code:ZodIssueCode.invalid_union,unionErrors});return INVALID}}get options(){return this._def.options}}ZodUnion.create=(types,params)=>{return new ZodUnion({options:types,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(params)})};var getDiscriminator=(type)=>{if(type instanceof ZodLazy){return getDiscriminator(type.schema)}else if(type instanceof ZodEffects){return getDiscriminator(type.innerType())}else if(type instanceof ZodLiteral){return[type.value]}else if(type instanceof ZodEnum){return type.options}else if(type instanceof ZodNativeEnum){return util.objectValues(type.enum)}else if(type instanceof ZodDefault){return getDiscriminator(type._def.innerType)}else if(type instanceof ZodUndefined){return[undefined]}else if(type instanceof ZodNull){return[null]}else if(type instanceof ZodOptional){return[undefined,...getDiscriminator(type.unwrap())]}else if(type instanceof ZodNullable){return[null,...getDiscriminator(type.unwrap())]}else if(type instanceof ZodBranded){return getDiscriminator(type.unwrap())}else if(type instanceof ZodReadonly){return getDiscriminator(type.unwrap())}else if(type instanceof ZodCatch){return getDiscriminator(type._def.innerType)}else{return[]}};class ZodDiscriminatedUnion extends ZodType{_parse(input){const{ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.object){addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ctx.parsedType});return INVALID}const discriminator=this.discriminator;const discriminatorValue=ctx.data[discriminator];const option=this.optionsMap.get(discriminatorValue);if(!option){addIssueToContext(ctx,{code:ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[discriminator]});return INVALID}if(ctx.common.async){return option._parseAsync({data:ctx.data,path:ctx.path,parent:ctx})}else{return option._parseSync({data:ctx.data,path:ctx.path,parent:ctx})}}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(discriminator,options,params){const optionsMap=new Map;for(const type of options){const discriminatorValues=getDiscriminator(type.shape[discriminator]);if(!discriminatorValues.length){throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`)}for(const value of discriminatorValues){if(optionsMap.has(value)){throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`)}optionsMap.set(value,type)}}return new ZodDiscriminatedUnion({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator,options,optionsMap,...processCreateParams(params)})}}function mergeValues(a,b){const aType=getParsedType(a);const bType=getParsedType(b);if(a===b){return{valid:true,data:a}}else if(aType===ZodParsedType.object&&bType===ZodParsedType.object){const bKeys=util.objectKeys(b);const sharedKeys=util.objectKeys(a).filter((key)=>bKeys.indexOf(key)!==-1);const newObj={...a,...b};for(const key of sharedKeys){const sharedValue=mergeValues(a[key],b[key]);if(!sharedValue.valid){return{valid:false}}newObj[key]=sharedValue.data}return{valid:true,data:newObj}}else if(aType===ZodParsedType.array&&bType===ZodParsedType.array){if(a.length!==b.length){return{valid:false}}const newArray=[];for(let index=0;index<a.length;index++){const itemA=a[index];const itemB=b[index];const sharedValue=mergeValues(itemA,itemB);if(!sharedValue.valid){return{valid:false}}newArray.push(sharedValue.data)}return{valid:true,data:newArray}}else if(aType===ZodParsedType.date&&bType===ZodParsedType.date&&+a===+b){return{valid:true,data:a}}else{return{valid:false}}}class ZodIntersection extends ZodType{_parse(input){const{status,ctx}=this._processInputParams(input);const handleParsed=(parsedLeft,parsedRight)=>{if(isAborted(parsedLeft)||isAborted(parsedRight)){return INVALID}const merged=mergeValues(parsedLeft.value,parsedRight.value);if(!merged.valid){addIssueToContext(ctx,{code:ZodIssueCode.invalid_intersection_types});return INVALID}if(isDirty(parsedLeft)||isDirty(parsedRight)){status.dirty()}return{status:status.value,value:merged.data}};if(ctx.common.async){return Promise.all([this._def.left._parseAsync({data:ctx.data,path:ctx.path,parent:ctx}),this._def.right._parseAsync({data:ctx.data,path:ctx.path,parent:ctx})]).then(([left,right])=>handleParsed(left,right))}else{return handleParsed(this._def.left._parseSync({data:ctx.data,path:ctx.path,parent:ctx}),this._def.right._parseSync({data:ctx.data,path:ctx.path,parent:ctx}))}}}ZodIntersection.create=(left,right,params)=>{return new ZodIntersection({left,right,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(params)})};class ZodTuple extends ZodType{_parse(input){const{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.array){addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:ctx.parsedType});return INVALID}if(ctx.data.length<this._def.items.length){addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:true,exact:false,type:"array"});return INVALID}const rest=this._def.rest;if(!rest&&ctx.data.length>this._def.items.length){addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:true,exact:false,type:"array"});status.dirty()}const items=[...ctx.data].map((item,itemIndex)=>{const schema=this._def.items[itemIndex]||this._def.rest;if(!schema)return null;return schema._parse(new ParseInputLazyPath(ctx,item,ctx.path,itemIndex))}).filter((x)=>!!x);if(ctx.common.async){return Promise.all(items).then((results)=>{return ParseStatus.mergeArray(status,results)})}else{return ParseStatus.mergeArray(status,items)}}get items(){return this._def.items}rest(rest){return new ZodTuple({...this._def,rest})}}ZodTuple.create=(schemas,params)=>{if(!Array.isArray(schemas)){throw new Error("You must pass an array of schemas to z.tuple([ ... ])")}return new ZodTuple({items:schemas,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(params)})};class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(input){const{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.object){addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ctx.parsedType});return INVALID}const pairs=[];const keyType=this._def.keyType;const valueType=this._def.valueType;for(const key in ctx.data){pairs.push({key:keyType._parse(new ParseInputLazyPath(ctx,key,ctx.path,key)),value:valueType._parse(new ParseInputLazyPath(ctx,ctx.data[key],ctx.path,key)),alwaysSet:key in ctx.data})}if(ctx.common.async){return ParseStatus.mergeObjectAsync(status,pairs)}else{return ParseStatus.mergeObjectSync(status,pairs)}}get element(){return this._def.valueType}static create(first,second,third){if(second instanceof ZodType){return new ZodRecord({keyType:first,valueType:second,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(third)})}return new ZodRecord({keyType:ZodString.create(),valueType:first,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(second)})}}class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(input){const{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.map){addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:ctx.parsedType});return INVALID}const keyType=this._def.keyType;const valueType=this._def.valueType;const pairs=[...ctx.data.entries()].map(([key,value],index)=>{return{key:keyType._parse(new ParseInputLazyPath(ctx,key,ctx.path,[index,"key"])),value:valueType._parse(new ParseInputLazyPath(ctx,value,ctx.path,[index,"value"]))}});if(ctx.common.async){const finalMap=new Map;return Promise.resolve().then(async()=>{for(const pair of pairs){const key=await pair.key;const value=await pair.value;if(key.status==="aborted"||value.status==="aborted"){return INVALID}if(key.status==="dirty"||value.status==="dirty"){status.dirty()}finalMap.set(key.value,value.value)}return{status:status.value,value:finalMap}})}else{const finalMap=new Map;for(const pair of pairs){const key=pair.key;const value=pair.value;if(key.status==="aborted"||value.status==="aborted"){return INVALID}if(key.status==="dirty"||value.status==="dirty"){status.dirty()}finalMap.set(key.value,value.value)}return{status:status.value,value:finalMap}}}}ZodMap.create=(keyType,valueType,params)=>{return new ZodMap({valueType,keyType,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(params)})};class ZodSet extends ZodType{_parse(input){const{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.set){addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:ctx.parsedType});return INVALID}const def=this._def;if(def.minSize!==null){if(ctx.data.size<def.minSize.value){addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:def.minSize.value,type:"set",inclusive:true,exact:false,message:def.minSize.message});status.dirty()}}if(def.maxSize!==null){if(ctx.data.size>def.maxSize.value){addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:def.maxSize.value,type:"set",inclusive:true,exact:false,message:def.maxSize.message});status.dirty()}}const valueType=this._def.valueType;function finalizeSet(elements){const parsedSet=new Set;for(const element of elements){if(element.status==="aborted")return INVALID;if(element.status==="dirty")status.dirty();parsedSet.add(element.value)}return{status:status.value,value:parsedSet}}const elements=[...ctx.data.values()].map((item,i)=>valueType._parse(new ParseInputLazyPath(ctx,item,ctx.path,i)));if(ctx.common.async){return Promise.all(elements).then((elements)=>finalizeSet(elements))}else{return finalizeSet(elements)}}min(minSize,message){return new ZodSet({...this._def,minSize:{value:minSize,message:errorUtil.toString(message)}})}max(maxSize,message){return new ZodSet({...this._def,maxSize:{value:maxSize,message:errorUtil.toString(message)}})}size(size,message){return this.min(size,message).max(size,message)}nonempty(message){return this.min(1,message)}}ZodSet.create=(valueType,params)=>{return new ZodSet({valueType,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(params)})};class ZodFunction extends ZodType{constructor(){super(...arguments);this.validate=this.implement}_parse(input){const{ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.function){addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.function,received:ctx.parsedType});return INVALID}function makeArgsIssue(args,error){return makeIssue({data:args,path:ctx.path,errorMaps:[ctx.common.contextualErrorMap,ctx.schemaErrorMap,getErrorMap(),en_default].filter((x)=>!!x),issueData:{code:ZodIssueCode.invalid_arguments,argumentsError:error}})}function makeReturnsIssue(returns,error){return makeIssue({data:returns,path:ctx.path,errorMaps:[ctx.common.contextualErrorMap,ctx.schemaErrorMap,getErrorMap(),en_default].filter((x)=>!!x),issueData:{code:ZodIssueCode.invalid_return_type,returnTypeError:error}})}const params={errorMap:ctx.common.contextualErrorMap};const fn=ctx.data;if(this._def.returns instanceof ZodPromise){const me=this;return OK(async function(...args){const error=new ZodError([]);const parsedArgs=await me._def.args.parseAsync(args,params).catch((e)=>{error.addIssue(makeArgsIssue(args,e));throw error});const result=await Reflect.apply(fn,this,parsedArgs);const parsedReturns=await me._def.returns._def.type.parseAsync(result,params).catch((e)=>{error.addIssue(makeReturnsIssue(result,e));throw error});return parsedReturns})}else{const me=this;return OK(function(...args){const parsedArgs=me._def.args.safeParse(args,params);if(!parsedArgs.success){throw new ZodError([makeArgsIssue(args,parsedArgs.error)])}const result=Reflect.apply(fn,this,parsedArgs.data);const parsedReturns=me._def.returns.safeParse(result,params);if(!parsedReturns.success){throw new ZodError([makeReturnsIssue(result,parsedReturns.error)])}return parsedReturns.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...items){return new ZodFunction({...this._def,args:ZodTuple.create(items).rest(ZodUnknown.create())})}returns(returnType){return new ZodFunction({...this._def,returns:returnType})}implement(func){const validatedFunc=this.parse(func);return validatedFunc}strictImplement(func){const validatedFunc=this.parse(func);return validatedFunc}static create(args,returns,params){return new ZodFunction({args:args?args:ZodTuple.create([]).rest(ZodUnknown.create()),returns:returns||ZodUnknown.create(),typeName:ZodFirstPartyTypeKind.ZodFunction,...processCreateParams(params)})}}class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(input){const{ctx}=this._processInputParams(input);const lazySchema=this._def.getter();return lazySchema._parse({data:ctx.data,path:ctx.path,parent:ctx})}}ZodLazy.create=(getter,params)=>{return new ZodLazy({getter,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(params)})};class ZodLiteral extends ZodType{_parse(input){if(input.data!==this._def.value){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{received:ctx.data,code:ZodIssueCode.invalid_literal,expected:this._def.value});return INVALID}return{status:"valid",value:input.data}}get value(){return this._def.value}}ZodLiteral.create=(value,params)=>{return new ZodLiteral({value,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(params)})};function createZodEnum(values,params){return new ZodEnum({values,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(params)})}class ZodEnum extends ZodType{_parse(input){if(typeof input.data!=="string"){const ctx=this._getOrReturnCtx(input);const expectedValues=this._def.values;addIssueToContext(ctx,{expected:util.joinValues(expectedValues),received:ctx.parsedType,code:ZodIssueCode.invalid_type});return INVALID}if(!this._cache){this._cache=new Set(this._def.values)}if(!this._cache.has(input.data)){const ctx=this._getOrReturnCtx(input);const expectedValues=this._def.values;addIssueToContext(ctx,{received:ctx.data,code:ZodIssueCode.invalid_enum_value,options:expectedValues});return INVALID}return OK(input.data)}get options(){return this._def.values}get enum(){const enumValues={};for(const val of this._def.values){enumValues[val]=val}return enumValues}get Values(){const enumValues={};for(const val of this._def.values){enumValues[val]=val}return enumValues}get Enum(){const enumValues={};for(const val of this._def.values){enumValues[val]=val}return enumValues}extract(values,newDef=this._def){return ZodEnum.create(values,{...this._def,...newDef})}exclude(values,newDef=this._def){return ZodEnum.create(this.options.filter((opt)=>!values.includes(opt)),{...this._def,...newDef})}}ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{_parse(input){const nativeEnumValues=util.getValidEnumValues(this._def.values);const ctx=this._getOrReturnCtx(input);if(ctx.parsedType!==ZodParsedType.string&&ctx.parsedType!==ZodParsedType.number){const expectedValues=util.objectValues(nativeEnumValues);addIssueToContext(ctx,{expected:util.joinValues(expectedValues),received:ctx.parsedType,code:ZodIssueCode.invalid_type});return INVALID}if(!this._cache){this._cache=new Set(util.getValidEnumValues(this._def.values))}if(!this._cache.has(input.data)){const expectedValues=util.objectValues(nativeEnumValues);addIssueToContext(ctx,{received:ctx.data,code:ZodIssueCode.invalid_enum_value,options:expectedValues});return INVALID}return OK(input.data)}get enum(){return this._def.values}}ZodNativeEnum.create=(values,params)=>{return new ZodNativeEnum({values,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(params)})};class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(input){const{ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.promise&&ctx.common.async===false){addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:ctx.parsedType});return INVALID}const promisified=ctx.parsedType===ZodParsedType.promise?ctx.data:Promise.resolve(ctx.data);return OK(promisified.then((data)=>{return this._def.type.parseAsync(data,{path:ctx.path,errorMap:ctx.common.contextualErrorMap})}))}}ZodPromise.create=(schema,params)=>{return new ZodPromise({type:schema,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(params)})};class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(input){const{status,ctx}=this._processInputParams(input);const effect=this._def.effect||null;const checkCtx={addIssue:(arg)=>{addIssueToContext(ctx,arg);if(arg.fatal){status.abort()}else{status.dirty()}},get path(){return ctx.path}};checkCtx.addIssue=checkCtx.addIssue.bind(checkCtx);if(effect.type==="preprocess"){const processed=effect.transform(ctx.data,checkCtx);if(ctx.common.async){return Promise.resolve(processed).then(async(processed)=>{if(status.value==="aborted")return INVALID;const result=await this._def.schema._parseAsync({data:processed,path:ctx.path,parent:ctx});if(result.status==="aborted")return INVALID;if(result.status==="dirty")return DIRTY(result.value);if(status.value==="dirty")return DIRTY(result.value);return result})}else{if(status.value==="aborted")return INVALID;const result=this._def.schema._parseSync({data:processed,path:ctx.path,parent:ctx});if(result.status==="aborted")return INVALID;if(result.status==="dirty")return DIRTY(result.value);if(status.value==="dirty")return DIRTY(result.value);return result}}if(effect.type==="refinement"){const executeRefinement=(acc)=>{const result=effect.refinement(acc,checkCtx);if(ctx.common.async){return Promise.resolve(result)}if(result instanceof Promise){throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.")}return acc};if(ctx.common.async===false){const inner=this._def.schema._parseSync({data:ctx.data,path:ctx.path,parent:ctx});if(inner.status==="aborted")return INVALID;if(inner.status==="dirty")status.dirty();executeRefinement(inner.value);return{status:status.value,value:inner.value}}else{return this._def.schema._parseAsync({data:ctx.data,path:ctx.path,parent:ctx}).then((inner)=>{if(inner.status==="aborted")return INVALID;if(inner.status==="dirty")status.dirty();return executeRefinement(inner.value).then(()=>{return{status:status.value,value:inner.value}})})}}if(effect.type==="transform"){if(ctx.common.async===false){const base=this._def.schema._parseSync({data:ctx.data,path:ctx.path,parent:ctx});if(!isValid(base))return INVALID;const result=effect.transform(base.value,checkCtx);if(result instanceof Promise){throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`)}return{status:status.value,value:result}}else{return this._def.schema._parseAsync({data:ctx.data,path:ctx.path,parent:ctx}).then((base)=>{if(!isValid(base))return INVALID;return Promise.resolve(effect.transform(base.value,checkCtx)).then((result)=>({status:status.value,value:result}))})}}util.assertNever(effect)}}ZodEffects.create=(schema,effect,params)=>{return new ZodEffects({schema,typeName:ZodFirstPartyTypeKind.ZodEffects,effect,...processCreateParams(params)})};ZodEffects.createWithPreprocess=(preprocess,schema,params)=>{return new ZodEffects({schema,effect:{type:"preprocess",transform:preprocess},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(params)})};class ZodOptional extends ZodType{_parse(input){const parsedType=this._getType(input);if(parsedType===ZodParsedType.undefined){return OK(undefined)}return this._def.innerType._parse(input)}unwrap(){return this._def.innerType}}ZodOptional.create=(type,params)=>{return new ZodOptional({innerType:type,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(params)})};class ZodNullable extends ZodType{_parse(input){const parsedType=this._getType(input);if(parsedType===ZodParsedType.null){return OK(null)}return this._def.innerType._parse(input)}unwrap(){return this._def.innerType}}ZodNullable.create=(type,params)=>{return new ZodNullable({innerType:type,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(params)})};class ZodDefault extends ZodType{_parse(input){const{ctx}=this._processInputParams(input);let data=ctx.data;if(ctx.parsedType===ZodParsedType.undefined){data=this._def.defaultValue()}return this._def.innerType._parse({data,path:ctx.path,parent:ctx})}removeDefault(){return this._def.innerType}}ZodDefault.create=(type,params)=>{return new ZodDefault({innerType:type,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof params.default==="function"?params.default:()=>params.default,...processCreateParams(params)})};class ZodCatch extends ZodType{_parse(input){const{ctx}=this._processInputParams(input);const newCtx={...ctx,common:{...ctx.common,issues:[]}};const result=this._def.innerType._parse({data:newCtx.data,path:newCtx.path,parent:{...newCtx}});if(isAsync(result)){return result.then((result)=>{return{status:"valid",value:result.status==="valid"?result.value:this._def.catchValue({get error(){return new ZodError(newCtx.common.issues)},input:newCtx.data})}})}else{return{status:"valid",value:result.status==="valid"?result.value:this._def.catchValue({get error(){return new ZodError(newCtx.common.issues)},input:newCtx.data})}}}removeCatch(){return this._def.innerType}}ZodCatch.create=(type,params)=>{return new ZodCatch({innerType:type,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof params.catch==="function"?params.catch:()=>params.catch,...processCreateParams(params)})};class ZodNaN extends ZodType{_parse(input){const parsedType=this._getType(input);if(parsedType!==ZodParsedType.nan){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:ctx.parsedType});return INVALID}return{status:"valid",value:input.data}}}ZodNaN.create=(params)=>{return new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(params)})};var BRAND=Symbol("zod_brand");class ZodBranded extends ZodType{_parse(input){const{ctx}=this._processInputParams(input);const data=ctx.data;return this._def.type._parse({data,path:ctx.path,parent:ctx})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(input){const{status,ctx}=this._processInputParams(input);if(ctx.common.async){const handleAsync=async()=>{const inResult=await this._def.in._parseAsync({data:ctx.data,path:ctx.path,parent:ctx});if(inResult.status==="aborted")return INVALID;if(inResult.status==="dirty"){status.dirty();return DIRTY(inResult.value)}else{return this._def.out._parseAsync({data:inResult.value,path:ctx.path,parent:ctx})}};return handleAsync()}else{const inResult=this._def.in._parseSync({data:ctx.data,path:ctx.path,parent:ctx});if(inResult.status==="aborted")return INVALID;if(inResult.status==="dirty"){status.dirty();return{status:"dirty",value:inResult.value}}else{return this._def.out._parseSync({data:inResult.value,path:ctx.path,parent:ctx})}}}static create(a,b){return new ZodPipeline({in:a,out:b,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(input){const result=this._def.innerType._parse(input);const freeze=(data)=>{if(isValid(data)){data.value=Object.freeze(data.value)}return data};return isAsync(result)?result.then((data)=>freeze(data)):freeze(result)}unwrap(){return this._def.innerType}}ZodReadonly.create=(type,params)=>{return new ZodReadonly({innerType:type,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(params)})};var late={object:ZodObject.lazycreate};var ZodFirstPartyTypeKind;(function(ZodFirstPartyTypeKind){ZodFirstPartyTypeKind["ZodString"]="ZodString";ZodFirstPartyTypeKind["ZodNumber"]="ZodNumber";ZodFirstPartyTypeKind["ZodNaN"]="ZodNaN";ZodFirstPartyTypeKind["ZodBigInt"]="ZodBigInt";ZodFirstPartyTypeKind["ZodBoolean"]="ZodBoolean";ZodFirstPartyTypeKind["ZodDate"]="ZodDate";ZodFirstPartyTypeKind["ZodSymbol"]="ZodSymbol";ZodFirstPartyTypeKind["ZodUndefined"]="ZodUndefined";ZodFirstPartyTypeKind["ZodNull"]="ZodNull";ZodFirstPartyTypeKind["ZodAny"]="ZodAny";ZodFirstPartyTypeKind["ZodUnknown"]="ZodUnknown";ZodFirstPartyTypeKind["ZodNever"]="ZodNever";ZodFirstPartyTypeKind["ZodVoid"]="ZodVoid";ZodFirstPartyTypeKind["ZodArray"]="ZodArray";ZodFirstPartyTypeKind["ZodObject"]="ZodObject";ZodFirstPartyTypeKind["ZodUnion"]="ZodUnion";ZodFirstPartyTypeKind["ZodDiscriminatedUnion"]="ZodDiscriminatedUnion";ZodFirstPartyTypeKind["ZodIntersection"]="ZodIntersection";ZodFirstPartyTypeKind["ZodTuple"]="ZodTuple";ZodFirstPartyTypeKind["ZodRecord"]="ZodRecord";ZodFirstPartyTypeKind["ZodMap"]="ZodMap";ZodFirstPartyTypeKind["ZodSet"]="ZodSet";ZodFirstPartyTypeKind["ZodFunction"]="ZodFunction";ZodFirstPartyTypeKind["ZodLazy"]="ZodLazy";ZodFirstPartyTypeKind["ZodLiteral"]="ZodLiteral";ZodFirstPartyTypeKind["ZodEnum"]="ZodEnum";ZodFirstPartyTypeKind["ZodEffects"]="ZodEffects";ZodFirstPartyTypeKind["ZodNativeEnum"]="ZodNativeEnum";ZodFirstPartyTypeKind["ZodOptional"]="ZodOptional";ZodFirstPartyTypeKind["ZodNullable"]="ZodNullable";ZodFirstPartyTypeKind["ZodDefault"]="ZodDefault";ZodFirstPartyTypeKind["ZodCatch"]="ZodCatch";ZodFirstPartyTypeKind["ZodPromise"]="ZodPromise";ZodFirstPartyTypeKind["ZodBranded"]="ZodBranded";ZodFirstPartyTypeKind["ZodPipeline"]="ZodPipeline";ZodFirstPartyTypeKind["ZodReadonly"]="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));var stringType=ZodString.create;var numberType=ZodNumber.create;var nanType=ZodNaN.create;var bigIntType=ZodBigInt.create;var booleanType=ZodBoolean.create;var dateType=ZodDate.create;var symbolType=ZodSymbol.create;var undefinedType=ZodUndefined.create;var nullType=ZodNull.create;var anyType=ZodAny.create;var unknownType=ZodUnknown.create;var neverType=ZodNever.create;var voidType=ZodVoid.create;var arrayType=ZodArray.create;var objectType=ZodObject.create;var strictObjectType=ZodObject.strictCreate;var unionType=ZodUnion.create;var discriminatedUnionType=ZodDiscriminatedUnion.create;var intersectionType=ZodIntersection.create;var tupleType=ZodTuple.create;var recordType=ZodRecord.create;var mapType=ZodMap.create;var setType=ZodSet.create;var functionType=ZodFunction.create;var lazyType=ZodLazy.create;var literalType=ZodLiteral.create;var enumType=ZodEnum.create;var nativeEnumType=ZodNativeEnum.create;var promiseType=ZodPromise.create;var effectsType=ZodEffects.create;var optionalType=ZodOptional.create;var nullableType=ZodNullable.create;var preprocessType=ZodEffects.createWithPreprocess;var pipelineType=ZodPipeline.create;var nonBlankString=stringType().min(1);var selectionIdSchema=nonBlankString.refine((value)=>value.trim().length>0,"Expected a non-blank selection ID");var packageOperationRecoverySchema=enumType(["explicit_continuation","retry_safe"]);var packageOperationCommandSchema=unionType([objectType({kind:literalType("install"),packageFqn:nonBlankString,recovery:packageOperationRecoverySchema}),objectType({kind:literalType("promote"),packageId:nonBlankString,recovery:packageOperationRecoverySchema,releaseId:nonBlankString}),objectType({kind:literalType("publish"),packageFqn:nonBlankString,recovery:packageOperationRecoverySchema}),objectType({installationId:nonBlankString,kind:literalType("rollback"),packageId:nonBlankString,recovery:packageOperationRecoverySchema,releaseId:nonBlankString}),objectType({installationId:nonBlankString,kind:literalType("update"),packageId:nonBlankString,recovery:packageOperationRecoverySchema,releaseId:nonBlankString}),objectType({kind:literalType("update"),mode:literalType("sync"),packageFqn:nonBlankString,recovery:packageOperationRecoverySchema})]);var packageOperationStatusSchema=enumType(["awaiting_continuation","failed","pending","running","succeeded"]);var releaseDigestSchema=stringType().regex(/^[\da-f]{64}$/u);var releaseSelectionSchema=objectType({generation:stringType().regex(/^(?:0|[1-9][0-9]*)$/u),releaseDigest:releaseDigestSchema,releaseId:selectionIdSchema});var graphMemberSchema=releaseSelectionSchema.extend({installationId:selectionIdSchema,packageFqn:selectionIdSchema,packageId:selectionIdSchema});var pinSchema=objectType({fqn:nonBlankString,releaseDigest:releaseDigestSchema,releaseId:nonBlankString});var dependencyPathsSchema=arrayType(arrayType(stringType()));var blockerMessageSchema=stringType();var knownBlockerSchema=unionType([objectType({_tag:literalType("manual_prerequisite"),message:blockerMessageSchema,observed:pinSchema.nullable(),path:arrayType(pinSchema),paths:arrayType(arrayType(pinSchema)),required:pinSchema}),objectType({_tag:literalType("authority_denied"),boundary:enumType(["principal","publication","promotion"]),message:blockerMessageSchema,paths:dependencyPathsSchema}),objectType({_tag:enumType(["dirty_readonly","definition_rejected"]),definitions:arrayType(objectType({fqn:nonBlankString,kind:enumType(["workflow","agent","skill","remote_tool_collection","knowledge_connector_instance","dataset_connector_instance","organization_group","application_grant","external_app"])})),message:blockerMessageSchema,paths:dependencyPathsSchema}),objectType({_tag:enumType(["release_unavailable","release_identity_mismatch","conflicting_pins","cycle","installation_identity_mismatch","retained_requirement_conflict","package_identity_conflict"]),message:blockerMessageSchema,paths:dependencyPathsSchema})]);var preflightDiagnosticSchema=unionType([knownBlockerSchema,objectType({_tag:nonBlankString,message:blockerMessageSchema.optional(),paths:dependencyPathsSchema.optional()}).transform(({_tag,message,paths})=>({_tag:"unknown",message:message??`Blocked by ${_tag}.`,paths:paths??[],tag:_tag}))]);var appliedGraphFields={applicationId:nonBlankString,members:arrayType(graphMemberSchema)};var applicationStageSchema=unionType([objectType({state:enumType(["not_required","pending"])}),objectType({blocker:preflightDiagnosticSchema.optional(),state:literalType("not_applied")}).transform(({blocker,state})=>blocker===undefined?{state}:{blocker,state}),objectType({...appliedGraphFields,state:literalType("applied")})]);var hostOutcomeFieldsSchema=objectType({diagnosticId:nonBlankString.optional(),member:graphMemberSchema,observed:objectType({desired:releaseSelectionSchema.nullable(),serving:releaseSelectionSchema.nullable()}),result:enumType(["failed","pending","serving","stale"])});var hostOutcome=({diagnosticId,...outcome})=>diagnosticId===undefined?outcome:{...outcome,diagnosticId};var cleanupCandidateSchema=objectType({installationId:selectionIdSchema,packageFqn:selectionIdSchema,packageId:selectionIdSchema,releaseDigest:releaseDigestSchema,releaseId:selectionIdSchema});var cleanupProtectionSchema=unionType([objectType({dependent:pinSchema,kind:literalType("required_by"),protection:enumType(["desired","serving"])}),objectType({dependent:pinSchema,kind:literalType("unknown_requirement")}),objectType({kind:enumType(["built_in","explicit_intent","selection_changed","unknown_intent"])}),objectType({kind:literalType("workflow_use"),state:enumType(["published","draft_head","working_copy"]),template:objectType({fqn:nonBlankString,kind:nonBlankString,version:nonBlankString}),workflowId:nonBlankString}),objectType({bindingKind:enumType(["tool_instance","connection","knowledge_connector"]),id:nonBlankString,kind:literalType("live_binding")})]);var cleanupStageSchema=objectType({candidates:arrayType(cleanupCandidateSchema.extend({protections:arrayType(cleanupProtectionSchema).optional(),result:enumType(["pending","removed","retained"])}).transform(({protections,...candidate})=>protections===undefined?candidate:{...candidate,protections})),state:enumType(["pending","completed","failed"])});var failureSchema=objectType({message:nonBlankString,reason:enumType(["credential_not_found","credential_permission_denied","credential_scope_denied","credential_verification_unavailable","execution_failed","invalid_artifact","release_not_found","release_package_mismatch"])});var eventOutcomeSchema=unionType([objectType({...appliedGraphFields,kind:literalType("graph_applied")}),objectType({blocker:preflightDiagnosticSchema,kind:literalType("graph_not_applied")}),hostOutcomeFieldsSchema.extend({kind:literalType("host")}).transform(({kind,...outcome})=>({...hostOutcome(outcome),kind})),objectType({kind:literalType("retry_requested")}),failureSchema.extend({kind:literalType("command_failed")}),objectType({candidate:cleanupCandidateSchema,kind:literalType("cleanup_removed")}),objectType({candidate:cleanupCandidateSchema,kind:literalType("cleanup_retained"),protections:arrayType(cleanupProtectionSchema)})]);var packageOperationSnapshotSchema=objectType({application:applicationStageSchema,cleanup:cleanupStageSchema.optional(),command:packageOperationCommandSchema,continuationOf:nonBlankString.optional(),createdAt:stringType().datetime({offset:true}),failure:failureSchema.optional(),hosts:arrayType(hostOutcomeFieldsSchema.transform(hostOutcome)),id:nonBlankString,idempotencyKey:nonBlankString,lastEventSequence:numberType().int().nonnegative(),nextAction:enumType(["continue","none","retry","wait"]),organizationId:nonBlankString,packageFqn:nonBlankString,principal:unionType([objectType({kind:literalType("administrator"),userId:nonBlankString}),objectType({credentialId:nonBlankString,kind:literalType("publisher")}),objectType({actor:literalType("bootstrap"),kind:literalType("system")})]),publication:objectType({packageId:selectionIdSchema,releaseDigest:releaseDigestSchema,releaseId:selectionIdSchema}).optional(),recoveryReason:literalType("selection_outcome_unavailable").optional(),selection:objectType({generation:numberType().int().positive(),installationId:selectionIdSchema,releaseId:selectionIdSchema}).optional(),status:packageOperationStatusSchema,updatedAt:stringType().datetime({offset:true})});var packageOperationEventSchema=objectType({createdAt:stringType().datetime({offset:true}),operationId:nonBlankString,outcome:eventOutcomeSchema.optional(),sequence:numberType().int().nonnegative(),status:packageOperationStatusSchema});var decodePackageOperationEvent=(data)=>{const{outcome,...event}=packageOperationEventSchema.parse(JSON.parse(data));return outcome===undefined?event:{...event,outcome}};var decodePackageOperationSnapshot=(snapshot)=>{const decoded=packageOperationSnapshotSchema.parse(snapshot);const{cleanup,continuationOf,failure,publication,recoveryReason,selection,...required}=decoded;const snapshotDto=required;if(cleanup!==undefined){snapshotDto.cleanup=cleanup}if(continuationOf!==undefined){snapshotDto.continuationOf=continuationOf}if(failure!==undefined){snapshotDto.failure=failure}if(recoveryReason!==undefined){snapshotDto.recoveryReason=recoveryReason}if(publication!==undefined){snapshotDto.publication=publication}if(selection!==undefined){snapshotDto.selection=selection}return snapshotDto};import{createHash as createHash3}from"crypto";import{readFile as readFile3}from"fs/promises";var nonempty=String4.check(isMinLength(1),makeFilter2((value)=>value.trim().length>0));var uuid3=String4.check(isPattern2(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu));var connectorSetup=Struct({adoptions:optionalKey2(Record(nonempty,Struct({instanceId:uuid3}))),connections:optionalKey2(Record(nonempty,Union2([Struct({connectionId:uuid3}),Struct({newConnection:Struct({fields:JsonObject,name:nonempty})})])))});var parseConnectorSetup=(text)=>{try{return decodeUnknownSync(connectorSetup,{onExcessProperty:"error"})(JSON.parse(text))}catch{throw new TypeError("Invalid connector setup file; expected connections/adoptions with UUID references or newConnection name/fields")}};var readConnectorSetup=async(path,readBytes=readFile3)=>{let bytes;try{bytes=await readBytes(path)}catch{throw new TypeError("Could not read connector setup file")}return parseConnectorSetup(new TextDecoder().decode(bytes))};var installPackage=async(input)=>{const request={client:input.client,headers:{"idempotency-key":input.idempotencyKey,"x-organization-id":input.organizationId},path:{fqn:input.packageFqn},throwOnError:true};if(input.body!==undefined){request.body=input.body}if(input.signal!==undefined){request.signal=input.signal}const response=await extensionPackagesInstall(request);return response.data};var updatePackage=async(input)=>{const request={body:input.body,client:input.client,headers:{"idempotency-key":input.idempotencyKey,"x-organization-id":input.organizationId},throwOnError:true};if(input.signal!==undefined){request.signal=input.signal}const response=await packageReleasesUpdateInstallation(request);return response.data};var publishPackage=async(input)=>{const request={body:input.body,client:input.client,headers:{"idempotency-key":input.idempotencyKey},throwOnError:true};if(input.signal!==undefined){request.signal=input.signal}const response=await packageReleasesPublish(request);return response.data};var promotePackage=async(input)=>{const request={body:input.body,client:input.client,headers:{"idempotency-key":input.idempotencyKey},throwOnError:true};if(input.signal!==undefined){request.signal=input.signal}const response=await packageReleasesPromote(request);return response.data};import{createHash}from"crypto";import{build as viteBuild,esmExternalRequirePlugin}from"vite";import{fileURLToPath as fileURLToPath2}from"url";var nodePath=runSync2(provide3(Path2,layer5));var literalLazyImport=(declarationSpecifier,identity)=>{const loaderSource=Function.prototype.toString.call(identity.load).trim();const arrowMatch=/^(?:async\s*)?\(\s*\)\s*=>\s*(?:await\s*)?(?:import|__vite_ssr_dynamic_import__)\(\s*(?<quote>["'])(?<specifier>[^"'\\\r\n]+)\k<quote>\s*\)$/u.exec(loaderSource);const functionMatch=/^function(?:\s+\w+)?\s*\(\s*\)\s*\{\s*return\s+(?:import|__vite_ssr_dynamic_import__)\(\s*(?<quote>["'])(?<specifier>[^"'\\\r\n]+)\k<quote>\s*\)\s*;?\s*\}$/u.exec(loaderSource);const wrappedImportMatch=/(?:import|__vite_ssr_dynamic_import__)\(\s*(?<quote>["'])(?<specifier>[^"'\\\r\n]+)\k<quote>\s*\)/u.exec(loaderSource);const specifier=arrowMatch?.groups?.specifier??functionMatch?.groups?.specifier??wrappedImportMatch?.groups?.specifier;if(specifier===undefined){throw new TypeError(`${identity.subject} load must be a direct literal lazy import`)}if(specifier.startsWith("/@fs/")){return specifier.slice(4)}if(specifier.startsWith("file:")){return fileURLToPath2(specifier)}if(specifier.startsWith("/")){if(!declarationSpecifier.startsWith("file:")){throw new TypeError(`${identity.subject} root-relative load requires a file declaration`)}const declarationDirectory=nodePath.dirname(fileURLToPath2(declarationSpecifier));const workspaceCandidate=nodePath.resolve(process.cwd(),specifier.slice(1));const workspaceRelation=nodePath.relative(declarationDirectory,workspaceCandidate);return workspaceRelation!==""&&!workspaceRelation.startsWith("..")&&!nodePath.isAbsolute(workspaceRelation)?workspaceCandidate:nodePath.resolve(declarationDirectory,specifier.slice(1))}if(specifier.startsWith(".")){if(!declarationSpecifier.startsWith("file:")){throw new TypeError(`${identity.subject} relative load requires a file declaration`)}return nodePath.resolve(nodePath.dirname(fileURLToPath2(declarationSpecifier)),specifier)}return specifier};var resolveLazyImportModule=(declarationSpecifier,entry)=>{const specifier=literalLazyImport(declarationSpecifier,entry);if(!nodePath.isAbsolute(specifier)){return specifier}try{return Bun.resolveSync(specifier,nodePath.dirname(specifier))}catch(error){throw new TypeError(`${entry.subject} module could not be resolved: ${specifier}`,{cause:error})}};var resolveHostedContributionEntry=(declarationSpecifier,identity)=>resolveLazyImportModule(declarationSpecifier,{load:identity.load,subject:`Hosted Contribution '${identity.fqn}'`});import{fileURLToPath as fileURLToPath3,pathToFileURL as pathToFileURL2}from"url";import{createServer}from"vite";var WORKSPACE_SOURCE_CONDITION="ci-source";var conditionsFromArgument=(argument,nextArgument)=>{if(argument==="--conditions"){return nextArgument===undefined?[]:nextArgument.split(",")}if(argument.startsWith("--conditions=")){return argument.slice("--conditions=".length).split(",")}return[]};var workspaceSourceConditions=(execArgv)=>{for(const[index,argument]of execArgv.entries()){if(conditionsFromArgument(argument,execArgv[index+1]).includes(WORKSPACE_SOURCE_CONDITION)){return[WORKSPACE_SOURCE_CONDITION]}}return[]};var workspaceSourceResolve=(execArgv)=>{const conditions=workspaceSourceConditions(execArgv);return conditions.length>0?{conditions:[...conditions]}:{}};var workspaceSourceSsrResolve=(execArgv)=>{const conditions=workspaceSourceConditions(execArgv);return conditions.length>0?{resolve:{conditions:[...conditions]}}:{}};class PackageDeclarationError extends TaggedError2("PackageDeclarationError"){}var path2=runSync2(provide3(Path2,layer5));var isRecord2=(value)=>value!==null&&typeof value==="object";var isPackageDefinition=(value)=>{if(!isRecord2(value)||!isRecord2(value.manifest)){return false}return value.manifest.apiVersion==="v4"&&typeof value.manifest.fqn==="string"&&Array.isArray(value.components)&&(value.hostedContributions===undefined||Array.isArray(value.hostedContributions))&&Array.isArray(value.schemaSidecars)};var normalizePackageDefinition=(definition,packageLoader)=>({...definition,hostedContributions:definition.hostedContributions??[],...packageLoader===undefined?undefined:{packageLoader}});var isPackageLoader=(value)=>typeof value==="function";var packageLoaderMap=(loaders,definitions)=>{if(loaders===undefined){return}const fqns=definitions.map(({manifest})=>manifest.fqn);if(!isRecord2(loaders)){throw new TypeError("Declaration packageLoaders must be an object")}const entries=Object.entries(loaders);if(entries.length!==fqns.length||!fqns.every((fqn)=>Object.hasOwn(loaders,fqn))||!entries.every(([,loader])=>isPackageLoader(loader))){throw new TypeError(`Declaration packageLoaders must map exactly the declared packages (${fqns.join(", ")}) to lazy import functions`)}return new Map(entries.flatMap(([fqn,loader])=>isPackageLoader(loader)?[[fqn,loader]]:[]))};var declarationSpecifier=(specifier)=>{if(specifier.startsWith("data:")||specifier.startsWith("file:")||specifier.startsWith("http:")||specifier.startsWith("https:")||!specifier.startsWith(".")&&!specifier.startsWith("/")){return specifier}return pathToFileURL2(path2.resolve(process.cwd(),specifier)).href};var normalizeModuleDeclarations=(loaded)=>{const exported=loaded.packageDefinitions??loaded.packageDefinition??loaded.default;const candidate=isRecord2(exported)&&"default"in exported?exported.default:exported;const values=Array.isArray(candidate)?candidate:[candidate];if(values.length===0||!values.every(isPackageDefinition)){throw new TypeError(`Declaration module must export a PackageDefinition or PackageDefinition array; received ${JSON.stringify(candidate)}`)}const loaders=packageLoaderMap(loaded.packageLoaders,values);return values.map((definition)=>normalizePackageDefinition(definition,loaders?.get(definition.manifest.fqn)))};var loadPackageDeclarations=flow((specifier)=>tryPromise2(()=>import(declarationSpecifier(specifier))).pipe(map4((loaded)=>isRecord2(loaded)?loaded:undefined),flatMap3((loaded)=>loaded===undefined?fail6(new PackageDeclarationError({message:"Declaration module did not expose module exports"})):succeed6(normalizeModuleDeclarations(loaded)))),runPromise2);var loadFreshPackageDeclarations=flow((specifier)=>{const resolved=declarationSpecifier(specifier);if(!resolved.startsWith("file:")){return promise2(()=>loadPackageDeclarations(resolved))}const sourcePath=fileURLToPath3(resolved);const root=path2.dirname(sourcePath);return acquireUseRelease2(tryPromise2(()=>createServer({appType:"custom",configFile:false,logLevel:"silent",resolve:workspaceSourceResolve(process.execArgv),root,server:{middlewareMode:true},ssr:workspaceSourceSsrResolve(process.execArgv)})),(server)=>tryPromise2(()=>server.ssrLoadModule(`/${encodeURIComponent(path2.basename(sourcePath))}`)).pipe(flatMap3((loaded)=>isRecord2(loaded)?succeed6(normalizeModuleDeclarations(loaded)):fail6(new PackageDeclarationError({message:"Declaration module did not expose module exports"})))),(server)=>promise2(()=>server.close()))},runPromise2);var compareCanonicalText=(left,right)=>{if(left===right){return 0}return left<right?-1:1};var blockSize=512;var isAscii=(value)=>{for(const character of value){if((character.codePointAt(0)??128)>127){return false}}return true};var writeAscii=(target,offset,length,value)=>{if(value.length>length||!isAscii(value)){throw new TypeError(`Value does not fit deterministic ustar field: ${value}`)}for(let index=0;index<value.length;index+=1){target[offset+index]=value.codePointAt(index)??0}};var writeOctal=(target,offset,length,value)=>{const source=value.toString(8).padStart(length-1,"0");if(source.length>=length){throw new TypeError(`Value does not fit deterministic ustar number: ${value}`)}writeAscii(target,offset,length-1,source)};var splitArchivePath=(path)=>{if(path===""||path.startsWith("/")||path.includes("\\")||path.split("/").some((part)=>part===""||part==="."||part==="..")){throw new TypeError(`Unsafe Extension Release archive path '${path}'`)}if(path.length<=100){return{name:path,prefix:""}}const separator=path.lastIndexOf("/");const prefix=path.slice(0,separator);const name=path.slice(separator+1);if(separator===-1||name.length>100||prefix.length>155){throw new TypeError(`Extension Release archive path is too long: ${path}`)}return{name,prefix}};var headerFor=(entry)=>{const header=new Uint8Array(blockSize);const{name,prefix}=splitArchivePath(entry.path);writeAscii(header,0,100,name);writeOctal(header,100,8,420);writeOctal(header,108,8,0);writeOctal(header,116,8,0);writeOctal(header,124,12,entry.bytes.byteLength);writeOctal(header,136,12,0);header.fill(32,148,156);header[156]=48;writeAscii(header,257,6,"ustar\x00");writeAscii(header,263,2,"00");writeAscii(header,345,155,prefix);const checksum=header.reduce((total,value)=>total+value,0);writeAscii(header,148,8,`${checksum.toString(8).padStart(6,"0")}\x00 `);return header};var createExtensionReleaseArchive=(sourceEntries)=>{const entries=sourceEntries.toSorted((left,right)=>compareCanonicalText(left.path,right.path));if(new Set(entries.map(({path})=>path)).size!==entries.length){throw new TypeError("Extension Release archive paths must be unique")}const size=entries.reduce((total,entry)=>total+blockSize+Math.ceil(entry.bytes.byteLength/blockSize)*blockSize,0)+blockSize*2;const archive=new Uint8Array(size);let offset=0;for(const entry of entries){archive.set(headerFor(entry),offset);offset+=blockSize;archive.set(entry.bytes,offset);offset+=Math.ceil(entry.bytes.byteLength/blockSize)*blockSize}return archive};var backendHostProvidedModules=["@collective-intelligence/extensions-sdk","@collective-intelligence/extensions-sdk-backend"];var frontendModules=["@collective-intelligence/extensions-sdk","@collective-intelligence/extensions-sdk-frontend-react","@collective-intelligence/extensions-sdk-frontend-react/workflow","@collective-intelligence/ui-react","@collective-intelligence/ui-react/icons","@collective-intelligence/ui-react/ui","@collective-intelligence/ui-react/ui-extensions","@tanstack/react-query","react","react-dom","react-dom/client","react/jsx-dev-runtime","react/jsx-runtime"];var modulesByHost={backend:backendHostProvidedModules,dashboard:[...frontendModules,"@xyflow/react"],studio:frontendModules};var FRONTEND_HOSTS=HOSTS.filter((host)=>host!=="backend");var hostProvidedModulesFor=(host)=>modulesByHost[host];var frontendHostProvidedModules=[...new Set(FRONTEND_HOSTS.flatMap(hostProvidedModulesFor))];var isHostProvidedModule=(host,specifier)=>modulesByHost[host].some((moduleName)=>moduleName===specifier);import{fileURLToPath as fileURLToPath4}from"url";var backendPackageEntry=(definition)=>{if(!definition.components.some((component)=>("implementation"in component))&&definition.schemaSidecars.length===0){return}const fqn=`${definition.manifest.fqn}.backend.package-runtime`;if(definition.hostedContributions.some(({manifest})=>manifest.fqn===fqn)){throw new TypeError(`Hosted Contribution '${fqn}' collides with the reserved Backend package runtime entry`)}return{exportName:"createPackageRuntime",fqn,host:"backend"}};var backendArtifactContributions=(definition)=>{const entry=backendPackageEntry(definition);return[...definition.hostedContributions.map(({manifest})=>manifest),...entry===undefined?[]:[entry]]};var backendPackageEntrySource=(packageFqn)=>`
|
|
265
|
+
`)}return yield*writeConnectionValues(dependencies,{envFile,json:command.json,prefix},connectionValues({application,clientSecret:savedSecret,discovery,organizationId:context.organizationId}))}).pipe(mapError2((cause)=>is2(AppsEnvCommandError)(cause)?cause:new AppsEnvCommandError({cause,message:cause.message})));var compareCodePoints=(left,right)=>{const leftPoints=Array.from(left,(character)=>character.codePointAt(0)??0);const rightPoints=Array.from(right,(character)=>character.codePointAt(0)??0);const length=Math.min(leftPoints.length,rightPoints.length);for(let index=0;index<length;index+=1){const difference=leftPoints[index]-rightPoints[index];if(difference!==0){return difference}}return leftPoints.length-rightPoints.length};var insertSortedKey=(keys,key)=>{let index=0;while(index<keys.length&&compareCodePoints(keys[index]??"",key)<=0){index+=1}keys.splice(index,0,key)};var isJsonObject=(value)=>Object.prototype.toString.call(value)==="[object Object]"&&!Array.isArray(value)&&(Object.getPrototypeOf(value)===Object.prototype||Object.getPrototypeOf(value)===null);var isJsonArray=(value)=>Array.isArray(value);var canonicalize=(value,ancestors,_valueType)=>{if(value===null){return"null"}if(isJsonArray(value)){if(ancestors.has(value)){throw new TypeError("package declarations cannot contain cyclic values")}ancestors.add(value);try{return`[${value.map((item)=>canonicalize(item,ancestors)).join(",")}]`}finally{ancestors.delete(value)}}if(isJsonObject(value)){if(ancestors.has(value)){throw new TypeError("package declarations cannot contain cyclic values")}ancestors.add(value);try{const record=value;const keys=[];for(const key of Object.keys(record)){insertSortedKey(keys,key)}return`{${keys.map((key)=>`${JSON.stringify(key)}:${canonicalize(record[key],ancestors)}`).join(",")}}`}finally{ancestors.delete(value)}}if(value instanceof Object){throw new TypeError("package declarations must contain JSON-compatible values")}switch(Object.prototype.toString.call(value)){case"[object Boolean]":{return value===true?"true":"false"}case"[object Number]":{const number=Number(value);if(!Number.isFinite(number)){throw new TypeError("package declarations cannot contain non-finite numbers")}return JSON.stringify(number)}case"[object String]":{return JSON.stringify(String(value))}default:{throw new TypeError("package declarations must contain JSON-compatible values")}}};var canonicalJson=(value,..._typeEvidence)=>canonicalize(value,new WeakSet);var parseJsonObject=(source)=>{const value=JSON.parse(source);if(!isJsonObject(value)){throw new TypeError("expected a JSON object")}return value};var compareUtf16CodeUnits=(left,right)=>{const length=Math.min(left.length,right.length);for(let index=0;index<length;index+=1){const difference=left.charCodeAt(index)-right.charCodeAt(index);if(difference!==0){return difference}}return left.length-right.length};var plainFormWidgets=["checkbox","color","date","date_range","datetime","email","file","hidden","number","password","structured_file_preview","switch","text","textarea","variable_references"];var selectFormWidgets=["folders_explorer","multi_select","radio","select"];var packageVariableTypes=["string","number","boolean","string[]","json","secret"];var isVariableReference=(value)=>typeof value==="object"&&value!==null&&!Array.isArray(value)&&Object.keys(value).length===1&&("$variable"in value)&&typeof value.$variable==="string";var isString2=(value)=>String(value)===value;var holdsType=(type,value)=>{switch(type){case"boolean":{return Boolean(value)===value}case"json":{return true}case"number":{return Number(value)===value}case"string[]":{return Array.isArray(value)&&value.every(isString2)}default:{return isString2(value)}}};var packageVariableViolation=(name,declaration)=>{if(!packageVariableTypes.includes(declaration.type)){return`variable '${name}' has the unknown type '${declaration.type}'`}if(!("default"in declaration)||declaration.default===undefined){return}if(declaration.type==="secret"){return`variable '${name}' is a secret and cannot declare a default`}if(!holdsType(declaration.type,declaration.default)){return`variable '${name}' declares a default outside its type '${declaration.type}'`}return};var invalid4=(path)=>{throw new TypeError(`Invalid package manifest at ${path}`)};var string3=(v,p)=>typeof v==="string"?v:invalid4(p);var identity2=(v,p)=>{const s=string3(v,p);return s.trim()===""?invalid4(p):s};var hostedIdentity=(value,path)=>{const text=identity2(value,path);return text===text.trim()?text:invalid4(path)};var assertDenseArrays=(value,path,seen)=>{if(typeof value!=="object"||value===null||seen.has(value)){return}seen.add(value);if(Array.isArray(value)){for(let index=0;index<value.length;index+=1){if(!Object.hasOwn(value,index)){invalid4(`${path}/${index}`)}}}for(const[key,child]of Object.entries(value)){assertDenseArrays(child,`${path}/${key}`,seen)}};var boolean2=(v,p)=>typeof v==="boolean"?v:invalid4(p);var number3=(v,p)=>typeof v==="number"&&Number.isFinite(v)?v:invalid4(p);var positiveSafeInteger=(value,path)=>{const parsed=number3(value,path);return Number.isSafeInteger(parsed)&&parsed>0?parsed:invalid4(path)};var optional3=(read)=>(v,p)=>v===undefined?undefined:read(v,p);var nullable=(read)=>(v,p)=>v===null?null:read(v,p);var literal=(...values)=>(v,p)=>{for(const value of values){if(v===value){return value}}return invalid4(p)};var array2=(read)=>(v,p)=>{if(!Array.isArray(v)){return invalid4(p)}return v.map((item,index)=>read(item,`${p}/${index}`))};var record2=(read)=>(v,p)=>{if(typeof v!=="object"||v===null||Array.isArray(v)){return invalid4(p)}return Object.fromEntries(Object.entries(v).map(([key,value])=>[key,read(value,`${p}/${key}`)]))};var object=(fields)=>(v,p)=>{if(typeof v!=="object"||v===null||Array.isArray(v)){return invalid4(p)}const entries=Object.entries(v);for(const key in fields){if(!Object.hasOwn(fields,key)){continue}fields[key](entries.find(([name])=>name===key)?.[1],`${p}/${key}`)}return v};var varying=(read)=>(v,p)=>isVariableReference(v)?v:read(v,p);var varyingStructure=(read)=>(v,p)=>isVariableReference(v)?v:read(v,p);var varyingArray=(read)=>array2(varying(read));var varyingStrings=varyingArray(string3);var excludedKey=/^(?:fqn|kind|lifecycle|version)$|Fqn$/u;var varyingFields=(fields)=>{const wrapped=Object.fromEntries(Object.entries(fields).map(([key,read])=>[key,excludedKey.test(key)?read:varying(read)]));return wrapped};var varyingObject=(fields)=>object(varyingFields(fields));var substituted=(read)=>(v,p)=>read(v,p);var refine=(read,violation)=>(v,p)=>{const value=read(v,p);return violation(value)===undefined?value:invalid4(p)};var strings=array2(string3);var optString=optional3(string3);var optBoolean=optional3(boolean2);var optNumber=optional3(number3);var optStrings=optional3(strings);var json=(v)=>parseJsonObject(canonicalJson({value:v})).value;var jsonObject=record2(json);var base={description:optString,displayName:string3,fqn:identity2,icon:optString,tags:optStrings,version:string3};var union2=(left,right)=>(v,p)=>{try{return left(v,p)}catch(error){if(!(error instanceof TypeError)){throw error}return right(v,p)}};var schemaDocument=(v,p)=>{const doc=jsonObject(v,p);const schemaType=literal("array","boolean","integer","null","number","object","string");const fields={$anchor:optString,$comment:optString,$defs:optional3(record2(schemaDocument)),$dynamicAnchor:optString,$dynamicRef:optString,$id:optString,$ref:optString,$schema:optional3(literal("https://json-schema.org/draft/2020-12/schema")),additionalProperties:optional3(union2(boolean2,schemaDocument)),allOf:optional3(array2(schemaDocument)),anyOf:optional3(array2(schemaDocument)),const:optional3(json),contains:optional3(schemaDocument),default:optional3(json),dependentRequired:optional3(record2(strings)),description:optString,else:optional3(schemaDocument),enum:optional3(array2(json)),exclusiveMaximum:optNumber,exclusiveMinimum:optNumber,format:optString,if:optional3(schemaDocument),items:optional3(schemaDocument),maxItems:optNumber,maxLength:optNumber,maxProperties:optNumber,maximum:optNumber,minItems:optNumber,minLength:optNumber,minProperties:optNumber,minimum:optNumber,multipleOf:optNumber,not:optional3(schemaDocument),oneOf:optional3(array2(schemaDocument)),pattern:optString,patternProperties:optional3(record2(schemaDocument)),prefixItems:optional3(array2(schemaDocument)),properties:optional3(record2(schemaDocument)),required:optStrings,then:optional3(schemaDocument),title:optString,type:optional3(union2(schemaType,array2(schemaType))),unevaluatedItems:optional3(union2(boolean2,schemaDocument)),unevaluatedProperties:optional3(union2(boolean2,schemaDocument)),uniqueItems:optBoolean};return object(fields)(doc,p)};var schema2=object({dialect:literal("https://json-schema.org/draft/2020-12/schema"),document:schemaDocument,fidelity:literal("exact","structural")});var visibility=object({equals:optional3(json),field:string3,in:optional3(array2(json)),isNotSet:optBoolean,isSet:optBoolean,notEquals:optional3(json),notIn:optional3(array2(json))});var visibilityRule=object({logic:optional3(literal("and","or")),visibleWhen:union2(visibility,array2(visibility))});var validationRule=(v,p)=>{const{type}=object({type:string3})(v,p);const messages={code:optString,message:optString};switch(type){case"min_length":case"max_length":case"min":case"max":{return object({...messages,type:literal(type),value:number3})(v,p)}case"pattern":{return object({...messages,type:literal(type),value:string3})(v,p)}case"required":{return object({...messages,type:literal("required")})(v,p)}default:{return object({...messages,type:literal("integer","json","non_empty_array")})(v,p)}}};var selectOption=object({label:optString,locked:optBoolean,value:string3});var selectOptions=object({aiFill:optional3(object({buttonLabel:optString,prompt:string3,retryable:optBoolean})),allowClear:optBoolean,allowCustom:optBoolean,dataSource:optString,dependencies:optStrings,options:optional3(array2(union2(string3,selectOption))),preventSaveWhenEmpty:optBoolean,readonlyOnUpdate:optBoolean,searchable:optBoolean,selectionMetadataField:optString,submit:optBoolean});var fieldUiBase={"ui:disabled":optBoolean,"ui:help":optString,"ui:order":optNumber,"ui:placeholder":optString,"ui:readonly":optBoolean,"ui:suggestedName":optString,"ui:validation":optional3(array2(validationRule))};var absent=(v,p)=>v===undefined?undefined:invalid4(p);var plainFieldUi=object({...fieldUiBase,"ui:options":absent,"ui:widget":literal(...plainFormWidgets)});var selectFieldUi=object({...fieldUiBase,"ui:options":optional3(selectOptions),"ui:widget":optional3(literal(...selectFormWidgets))});var structuredFileUploadFieldUi=object({...fieldUiBase,"ui:options":optional3(object({formatField:optString})),"ui:widget":literal("structured_file_upload")});var structuredFileBrowserFieldUi=object({...fieldUiBase,"ui:options":object({contribution:object({componentFqn:string3,connectionSlot:string3}),formatField:optString,label:optString}),"ui:widget":literal("structured_file_browser")});var fieldUi=union2(union2(plainFieldUi,selectFieldUi),union2(structuredFileUploadFieldUi,structuredFileBrowserFieldUi));var formItems=array2(union2(string3,object({md:string3})));var form=object({createSteps:optional3(array2(object({description:optional3(nullable(string3)),id:string3,includeInBasicInfo:optional3(nullable(boolean2)),items:formItems,title:string3,visibility:optional3(nullable(visibilityRule))}))),layout:optional3(literal("stacked","two_column")),schema:schema2,uiSchema:optional3(record2(fieldUi)),updateSections:optional3(array2(object({description:optional3(nullable(string3)),items:formItems,layout:optional3(nullable(literal("stacked","two_column"))),title:optional3(nullable(string3))}))),visibility:optional3(record2(visibilityRule))});var closedGatewayObject=(fields)=>refine(object(fields),(value)=>Object.keys(value).some((key)=>!Object.hasOwn(fields,key))?"unexpected Gateway field":undefined);var identifier2=refine(string3,(value)=>/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/u.test(value)?undefined:"invalid identifier");var version2=refine(string3,(value)=>value.length>0&&value.length<=128&&value.trim()===value?undefined:"invalid version");var bounded2=(maximum,minimum=1)=>refine(number3,(value)=>Number.isSafeInteger(value)&&value>=minimum&&value<=maximum?undefined:"invalid limit");var unique=(read,key)=>refine(read,(values)=>new Set(values.map(key)).size===values.length?undefined:"duplicate identifier");var projection=refine(schema2,(value)=>(value.fidelity==="exact"||value.fidelity==="structural")&&Object.keys(value).every((key)=>key==="dialect"||key==="document"||key==="fidelity")?undefined:"unsupported Gateway projection");var authorization=closedGatewayObject({delegatedSubject:literal("allowed","forbidden","required"),organization:literal("required"),principalKinds:refine(unique(array2(literal("detached_user","service_principal")),(kind)=>kind),(values)=>values.length>0?undefined:"empty principalKinds"),scopes:unique(array2(refine(string3,(value)=>value.length>0&&value.length<=256?undefined:"invalid scope")),(scope)=>scope)});var operationFields={authorization,description:string3,effects:literal("external_side_effect","read","write"),execution:closedGatewayObject({mode:literal("synchronous"),timeoutMs:bounded2(3600000)}),id:identifier2,idempotency:literal("idempotent","requires_key","safe"),input:projection,limits:closedGatewayObject({maxRequestBytes:bounded2(16777216),maxResponseBytes:bounded2(16777216)}),output:projection,retry:union2(closedGatewayObject({mode:literal("never")}),closedGatewayObject({maxAttempts:bounded2(10,2),mode:literal("idempotent_only")})),title:string3,version:version2};var operationReader=closedGatewayObject(operationFields);var domainFields={description:optional3(string3),displayOrder:optional3(number3),icon:optional3(string3),id:identifier2,tags:optional3(strings),title:string3};var domainsReader=unique(array2(closedGatewayObject({...domainFields,operations:unique(array2(operationReader),(operation)=>operation.id)})),(domain)=>domain.id);var inputReader=closedGatewayObject({id:identifier2,operationDomains:domainsReader,version:version2});var empty4=refine(array2(identity2),(values)=>values.length===0?undefined:"operation-only Gateway required");var emptyReader=(value,path)=>{empty4(value,path);return[]};var disabled=(value,path)=>boolean2(value,path)===false?false:invalid4(path);var contractReader=closedGatewayObject({capabilities:closedGatewayObject({resources:disabled}),datasets:emptyReader,id:identifier2,knowledge:emptyReader,operationDomains:unique(array2(closedGatewayObject({...domainFields,operations:unique(array2(closedGatewayObject({...operationFields,canonicalReference:string3})),(operation)=>operation.id)})),(domain)=>domain.id),organizationBinding:closedGatewayObject({mode:literal("installed_organization")}),protocolVersion:literal("2"),version:version2});var buildOperationGatewayContract=(input)=>{assertDenseArrays(input,"gateway",new WeakSet);canonicalJson(input);const admitted=inputReader(input,"gateway");return{capabilities:{resources:false},datasets:[],id:admitted.id,knowledge:[],operationDomains:admitted.operationDomains.map((domain)=>({...domain,operations:domain.operations.map((operation)=>({...operation,canonicalReference:`${admitted.id}/${domain.id}/${operation.id}@${operation.version}`})).sort((a,b)=>compareUtf16CodeUnits(a.id,b.id))})).sort((a,b)=>compareUtf16CodeUnits(a.id,b.id)),organizationBinding:{mode:"installed_organization"},protocolVersion:"2",version:admitted.version}};var readOperationGatewayContract=(value,path)=>{assertDenseArrays(value,path,new WeakSet);const admitted=contractReader(value,path);const normalized=buildOperationGatewayContract({id:admitted.id,operationDomains:admitted.operationDomains.map((domain)=>({...domain,operations:domain.operations.map(({canonicalReference:_reference,...operation})=>operation)})),version:admitted.version});if(canonicalJson(admitted)!==canonicalJson(normalized)){invalid4(path)}return normalized};var deepFreeze=(value)=>{if(value!==null&&typeof value==="object"&&!Object.isFrozen(value)){Object.freeze(value);for(const child of Object.values(value)){deepFreeze(child)}}return value};var SchemaConsumerProfiles=Object.freeze({automationGraphInput:"workflow_value",automationGraphOutput:"workflow_value",connectionCredential:"interactive_form",connectorSettings:"interactive_form",form:"interactive_form",knowledgeEntity:"knowledge_record",knowledgeRelation:"knowledge_record",notificationCredential:"interactive_form",studioComponentProps:"studio_props",toolInput:"ai_function_input",toolOutput:"runtime_json",toolSettings:"interactive_form",workflowConfiguration:"workflow_value",workflowFieldValue:"workflow_value",workflowInput:"workflow_value",workflowOutput:"workflow_value",workflowPortValue:"workflow_value"});var annotationKeywords=["$anchor","$comment","$id","$schema","$vocabulary","deprecated","description","examples","readOnly","title","writeOnly"];var structuralKeywords=["$defs","$ref","additionalProperties","const","enum","items","properties","required","type"];var boundKeywords=["exclusiveMaximum","exclusiveMinimum","maxItems","maxLength","maxProperties","maximum","minItems","minLength","minProperties","minimum","multipleOf","pattern","uniqueItems"];var UnrestrictedScopeKeyword="x-unrestricted-scope";var baseProfileKeywords=[...annotationKeywords,...structuralKeywords,...boundKeywords];var ConsumerProfiles=deepFreeze({ai_function_input:{allowedFidelity:["exact","structural"],allowedKeywords:[...baseProfileKeywords,"anyOf"],id:"ai_function_input",rootObject:true,unsupportedKeywords:["$dynamicRef","$dynamicAnchor","allOf","oneOf","not","patternProperties","prefixItems","contains","dependentRequired","if","then","else","unevaluatedItems","unevaluatedProperties"]},interactive_form:{allowedFidelity:["exact"],allowedKeywords:[...baseProfileKeywords,"anyOf","default","format",UnrestrictedScopeKeyword],id:"interactive_form",rootObject:true,unsupportedKeywords:["$dynamicRef","$dynamicAnchor","allOf","oneOf","not","patternProperties","contains","dependentRequired","if","then","else","prefixItems","unevaluatedItems","unevaluatedProperties"]},knowledge_record:{allowedFidelity:["exact","structural"],allowedKeywords:[...baseProfileKeywords,"format"],id:"knowledge_record",rootObject:true,unsupportedKeywords:["$dynamicRef","$dynamicAnchor","allOf","anyOf","oneOf","not","patternProperties","prefixItems","contains","dependentRequired","if","then","else","unevaluatedItems","unevaluatedProperties"]},runtime_json:{allowedFidelity:["exact","structural"],allowedKeywords:null,id:"runtime_json",rootObject:false,unsupportedKeywords:["$dynamicRef","$dynamicAnchor"]},studio_props:{allowedFidelity:["exact"],allowedKeywords:[...baseProfileKeywords,"anyOf","default","format"],id:"studio_props",rootObject:true,unsupportedKeywords:["$dynamicRef","$dynamicAnchor","allOf","oneOf","not","patternProperties","contains","dependentRequired","if","then","else","prefixItems","unevaluatedItems","unevaluatedProperties"]},workflow_value:{allowedFidelity:["exact","structural"],allowedKeywords:[...baseProfileKeywords,"default","format","oneOf"],id:"workflow_value",rootObject:false,unsupportedKeywords:["$dynamicRef","$dynamicAnchor","allOf","anyOf","not","unevaluatedItems","unevaluatedProperties"]}});var knownVocabularies=new Set(["https://json-schema.org/draft/2020-12/vocab/applicator","https://json-schema.org/draft/2020-12/vocab/content","https://json-schema.org/draft/2020-12/vocab/core","https://json-schema.org/draft/2020-12/vocab/format-annotation","https://json-schema.org/draft/2020-12/vocab/format-assertion","https://json-schema.org/draft/2020-12/vocab/meta-data","https://json-schema.org/draft/2020-12/vocab/unevaluated","https://json-schema.org/draft/2020-12/vocab/validation"]);var schemaArrayKeywords=new Set(["allOf","anyOf","oneOf","prefixItems"]);var schemaMapKeywords=new Set(["$defs","patternProperties","properties"]);var schemaValueKeywords=new Set(["additionalProperties","contains","else","if","items","not","then","unevaluatedItems","unevaluatedProperties"]);var workflowBindingKey=(binding)=>canonicalJson({path:binding.path,target:binding.target});var renderWorkflowBinding=(binding)=>`${binding.target}:${binding.path.join(".")}`;var isConnectionCount=(value)=>value===undefined||value===null||Number.isSafeInteger(value)&&value>=0;var workflowPortPolicyViolation=(port)=>{if(!isConnectionCount(port.minConnections)||!isConnectionCount(port.maxConnections)){return"connection counts must be non-negative integers"}const max=port.maxConnections===undefined?1:port.maxConnections;if(max!==null&&(port.minConnections??0)>max){return"minConnections cannot exceed maxConnections"}if(port.allowedTemplateKinds?.length===0){return"allowedTemplateKinds cannot be empty"}if(port.allowedTemplateFqns?.length===0){return"allowedTemplateFqns cannot be empty"}if(port.schemaResolution?.variants.length===0){return"schemaResolution requires variants"}return};var firstDuplicate=(values)=>values.find((value,index)=>values.indexOf(value)!==index);var workflowEditorViolation=(editor)=>{const sections=editor.form?.sections??[];const duplicateSection=firstDuplicate(sections.flatMap((section)=>section.id===undefined?[]:[section.id]));if(duplicateSection!==undefined){return`workflow editor section id '${duplicateSection}' is not unique`}const fields=sections.flatMap((section)=>section.fields??[]);const keys=fields.map((field)=>workflowBindingKey(field.binding));const duplicateField=fields.find((field,index)=>keys.indexOf(workflowBindingKey(field.binding))!==index);if(duplicateField!==undefined){return`workflow editor binding ${renderWorkflowBinding(duplicateField.binding)} is not unique`}for(const field of fields){const references=[...(field.visibleWhen??[]).map((rule)=>rule.binding),...field.optionSource?.kind==="remote"?field.optionSource.dependsOn:[]];const dangling=references.find((reference)=>!keys.includes(workflowBindingKey(reference)));if(dangling!==undefined){return`workflow editor field ${renderWorkflowBinding(field.binding)} references unknown binding ${renderWorkflowBinding(dangling)}`}}return};var metadata=object({available:boolean2,label:string3});var connection=object({...base,compatibility:optional3(object({auth:optString,dialect:optString,extensions:optional3(jsonObject),provider:optString})),creationMode:optional3(literal("self_service","registration_only")),credential:form,defaultConnectionName:string3,discoveryMetadata:optional3(metadata),kind:literal("connection"),providerFamily:string3,secretFields:optStrings,testMetadata:optional3(metadata)});var pathParts=array2(union2(string3,number3));var bindingModes=array2(literal("external","managed"));var syncModes=array2(literal("delta","full"));var bindingScopes=array2(literal("organization","tenant"));var mutationPolicy=literal("always","connector_backed","never");var extraProps=literal("ignore","import","inline");var outboundStrategy=literal("local_first","remote_first");var updateMode=literal("full","partial");var localized=object({fallbackLocale:string3,values:record2(string3)});var catalogTags=optional3(record2(strings));var connectionRefs=optional3(array2(object({catalogCollection:optString,connectionTemplateFqn:string3,label:string3,required:optBoolean,slot:string3,visibleWhen:optional3(visibility)})));var fieldMap=(v,p)=>{const common={direction:literal("both","inbound","outbound"),local:string3,skipIfNull:boolean2};const{op}=object({op:string3})(v,p);switch(op){case"path":{return object({...common,op:literal(op),remote:string3})(v,p)}case"cast":{return object({...common,falseValues:optStrings,op:literal(op),remote:string3,trueValues:optStrings})(v,p)}case"default":{return object({...common,op:literal(op),remote:optString,value:json})(v,p)}case"concat":{return object({...common,op:literal(op),remote:strings,separator:optString})(v,p)}case"split":{return object({...common,discardEmpty:optBoolean,op:literal(op),remote:string3,separators:optStrings,trimItems:optBoolean,uniqueItems:optBoolean})(v,p)}case"coordinates":{return object({...common,latitudeKey:optString,longitudeKey:optString,op:literal(op),remote:(value,location)=>{const parts=strings(value,location);if(parts.length!==2){return invalid4(location)}return[string3(parts[0],location),string3(parts[1],location)]}})(v,p)}case"transform":{return object({...common,op:literal(op),remote:string3,transformerId:string3})(v,p)}default:{return invalid4(`${p}/op`)}}};var predefinedExtras=optional3(array2(object({displayName:nullable(string3),enabled:boolean2,id:string3,includeInEntityEmbedding:boolean2,kind:literal("linked_text","file_source"),slotKey:string3,source:jsonObject})));var predefinedSchedules=optional3(array2(object({cronExpression:string3,enabled:optBoolean,importMode:optional3(literal("delta","full")),label:optString,rationale:optString,timezone:optString})));var schemaCapability={extraPropsMode:optional3(extraProps),fieldMap:optional3(array2(fieldMap)),fqn:string3,outboundStrategy:optional3(outboundStrategy),predefinedBindingExtras:predefinedExtras,predefinedBindingKey:optString,predefinedBindingMode:optional3(literal("external","managed")),predefinedBindingRemoteCollectionId:optString,predefinedBindingRemoteCollectionName:optString,predefinedSchedules,supportedSyncModes:optional3(syncModes),supportsInbound:optBoolean,supportsOutbound:optBoolean,syncIntervalSeconds:optional3(nullable(number3)),updateMode:optional3(updateMode)};var entityCapability=object({...schemaCapability,predefinedBindingParentKey:optString,supportedBindingModes:optional3(bindingModes)});var relationCapability=object({...schemaCapability,predefinedBindingParentEntityKey:optString,predefinedBindingRelationImportMode:optional3(literal("child_binding","relation_only")),predefinedBindingSourceEntityKey:optString,predefinedBindingTargetEntityKey:optString});var discoveryDefaults=object({extraPropsMode:extraProps,outboundStrategy,supportedBindingModes:bindingModes,supportedSyncModes:syncModes,supportsInbound:boolean2,supportsOutbound:boolean2,syncIntervalSeconds:nullable(number3),updateMode});var datasetCapabilities=object({aggregates:array2(literal("count","count_distinct","sum","min","max","avg")),definitionRefresh:boolean2,grouping:boolean2,intents:array2(literal("records","aggregate","time_series")),limits:object({maxBytes:number3,maxPageRows:number3,maxRows:number3,timeoutMs:number3}),ordering:boolean2,pagination:boolean2,predicates:array2(literal("eq","ne","lt","lte","gt","gte","in","not_in","is_null","is_not_null","contains","starts_with"))});var fieldSemantics=object({defaultSearch:optBoolean,embedded:optBoolean,faceted:optBoolean,indexContent:optBoolean,indexOverview:optBoolean,indexed:optBoolean,managedProjectionSource:optional3(literal("organization_group","organization_user")),mediaVisibility:optional3(literal("private","protected","public")),queryGuidance:optString,unique:optBoolean});var managedProjection=object({connectorPolicy:literal("allow","deny_schema"),genericMutationPolicy:literal("deny_managed_fields","deny_schema"),kind:literal("directory_person","directory_person_in_group","directory_group","directory_group_parent"),source:literal("organization_group","organization_group_hierarchy","organization_group_membership","organization_user")});var fieldLocalization=object({description:optional3(localized),help:optional3(localized),label:optional3(localized),placeholder:optional3(localized)});var fieldPresentation=object({copyable:optBoolean,editor:optString,editorOptions:optional3(object({accepts:optStrings,allowCustomValues:optBoolean,autocomplete:optString,clearable:optBoolean,falseLabel:optString,multiple:optBoolean,options:optional3(array2(object({label:string3,value:string3}))),rows:optNumber,searchable:optBoolean,showButtons:optBoolean,spellcheck:optBoolean,step:optNumber,trueLabel:optString})),emptyLabel:optString,falseLabel:optString,hidden:optBoolean,layout:optional3(object({column:optNumber,labelPlacement:optional3(literal("left","top")),order:optNumber,row:optNumber,width:optional3(union2(number3,literal("full")))})),maxLines:optNumber,readOnly:optBoolean,renderer:optString,trueLabel:optString});var lifecycle=object({deployMode:literal("init_only","upsert"),readonly:boolean2});var autocompleteConfiguration=object({autocompleteFields:array2(object({field:string3,scope:literal("data","entity")})),defaultAutocompleteFields:array2(object({field:string3,scope:literal("data","entity")}))});var knowledgeSchema={catalogTags,domainFqn:string3,fieldLocalization:optional3(record2(fieldLocalization)),fieldPresentation:optional3(record2(fieldPresentation)),fieldSemantics:optional3(record2(fieldSemantics)),localMutationPolicy:optional3(mutationPolicy),managedProjection:optional3(managedProjection),schema:schema2};var policyRef=(value,path)=>{const{kind}=object({kind:string3})(value,path);return kind==="literal"?object({kind:literal("literal"),value:json})(value,path):object({kind:literal("subject","resource"),path:strings})(value,path)};var uuid=(value,path)=>{const parsed=identity2(value,path);return/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu.test(parsed)?parsed:invalid4(path)};var policyPredicate=(value,path)=>{const{op}=object({op:string3})(value,path);switch(op){case"eq":case"neq":case"lt":case"lte":case"gt":case"gte":{return object({left:policyRef,op:literal("eq","neq","lt","lte","gt","gte"),right:policyRef})(value,path)}case"in":{return object({op:literal("in"),set:policyRef,value:policyRef})(value,path)}case"exists":case"is_null":{return object({op:literal("exists","is_null"),ref:policyRef})(value,path)}case"contains":case"starts_with":{return object({op:literal("contains","starts_with"),ref:policyRef,value:policyRef})(value,path)}case"const":{return object({op:literal("const"),value:boolean2})(value,path)}case"not":{return object({arg:policyPredicate,op:literal("not")})(value,path)}case"and":case"or":{return object({args:array2(policyPredicate),op:literal("and","or")})(value,path)}case"relation_exists":{return object({direction:literal("out","in"),op:literal("relation_exists"),relationSchemaId:uuid})(value,path)}case"relation_field":{return object({direction:literal("out","in"),inner:policyPredicate,op:literal("relation_field"),relationSchemaId:uuid})(value,path)}default:{return invalid4(`${path}/op`)}}};var policyBody=object({rule:optional3(policyPredicate),subjectMatch:policyPredicate});var policyFields={effect:literal("allow","deny"),policyBody,policyType:literal("filter","gate"),targetFqn:identity2,targetKind:literal("entity_domain","entity_schema","relation_domain","relation_schema")};var concrete=(list)=>list===undefined||isVariableReference(list)?[]:list.filter((item)=>!isVariableReference(item));var spelled=(key)=>key===null||isVariableReference(key)?undefined:key;var knownKeys=(list)=>{if(isVariableReference(list)){return}const keys=new Set;for(const item of list??[]){const key=isVariableReference(item)?undefined:spelled(item.key);if(key===undefined){return}keys.add(key)}return keys};var connection2=refine(varyingObject({setupKey:identity2}),(value)=>Object.keys(value).some((key)=>key!=="setupKey")?"install-only input":undefined);var bindingFields={executionRole:optional3(literal("root","child")),extraPropsMode:optional3(literal("ignore","import","inline")),extras:refine(predefinedExtras,(extras)=>extras?.some((extra)=>!/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu.test(extra.id))?"invalid extra UUID":undefined),fieldMap:optional3(array2(fieldMap)),key:identity2,outboundStrategy:optional3(literal("local_first","remote_first")),parentKey:optional3(nullable(identity2)),remoteCollectionId:optional3(nullable(string3)),remoteCollectionName:optional3(nullable(string3)),supportedSyncModes:optional3(varyingArray(literal("delta","full"))),supportsInbound:optBoolean,supportsOutbound:optBoolean,syncIntervalSeconds:optional3(nullable(positiveSafeInteger)),updateMode:optional3(literal("full","partial"))};var entityBinding=varyingObject({...bindingFields,bindingMode:literal("managed","external"),missingConnectorFieldsBehavior:optional3(literal("prune","retain")),pushEntityMatch:optional3(literal("remote_ref","unique_fields")),schemaFqn:identity2,supportedBindingModes:optional3(varyingArray(literal("managed","external"))),suppressEntityEvents:optBoolean});var relationBinding=varyingObject({...bindingFields,bindingMode:optional3(literal("managed")),relationImportMode:optional3(literal("child_binding","relation_only")),relationSchemaFqn:identity2,sourceEntityKey:optional3(nullable(identity2)),targetEntityKey:optional3(nullable(identity2))});var schedule2=varyingObject({cronExpression:identity2,enabled:optBoolean,importMode:optional3(literal("delta","full")),key:identity2,timezone:optString});var positive=refine(number3,(n)=>n>0?undefined:"positive");var budget=optional3(nullable(positiveSafeInteger));var pipeline=varyingObject({definition:varyingObject({budgets:optional3(varyingObject({maxPagesPerRun:budget,maxRemoteItemsPerRun:budget,maxRootWorkUnitsPerRun:budget,maxSecondsPerRun:optional3(nullable(positive))})),steps:refine(varyingArray(varyingObject({tasks:varyingArray(varyingObject({bindingKey:identity2,kind:literal("entity","relation"),modeOverride:optional3(nullable(literal("delta","full")))}))})),(steps)=>steps.length>0?undefined:"empty")}),enabled:optBoolean,key:identity2,name:optString,schedules:optional3(varyingArray(schedule2))});var uniqueKeys=(values,path)=>{const seen=new Set;for(const[index,value]of values.entries()){const key=spelled(value.key);if(key===undefined){continue}if(seen.has(key)){invalid4(`${path}/${index}/key`)}seen.add(key)}};var knowledge=varyingObject({...base,connections:optional3(record2(connection2)),dataPolicies:optional3(varyingArray(varyingObject({...policyFields,fqn:identity2,priority:optNumber}))),enabled:optBoolean,entityBindings:optional3(varyingArray(entityBinding)),kind:literal("knowledgeConnectorInstance"),lifecycle,pipelines:optional3(varyingArray(pipeline)),relationBindings:optional3(varyingArray(relationBinding)),remoteFilters:optional3(record2(varyingObject({mode:literal("all","only_selected","all_except_selected"),selected_ids:varyingStrings}))),settings:optional3(record2(varyingObject({type:literal("inline","linked"),value:json}))),templateFqn:identity2});var assertEntityParents=(entities,path)=>{const parents=new Map(entities.map((b)=>[spelled(b.key),spelled(b.parentKey)]));for(const binding of entities){const key=spelled(binding.key);if(key===undefined){continue}const seen=new Set([key]);let parent=spelled(binding.parentKey);while(parent!==undefined){if(seen.has(parent)){invalid4(`${path}/entityBindings/parentKey`)}seen.add(parent);parent=parents.get(parent)}}};var assertPolicyLifecycle=(policies,path)=>{for(const[index,policy]of policies.entries()){if(Object.keys(policy).some((key)=>key==="lifecycle"||key==="deployMode"||key==="readonly")){invalid4(`${path}/dataPolicies/${index}/lifecycle`)}}};var assertPipelineTasks=(item,bindingKeys,path)=>{const tasks=new Set;const definition=isVariableReference(item.definition)?undefined:item.definition;for(const step of concrete(definition?.steps)){for(const task of concrete(step.tasks)){const bindingKey=spelled(task.bindingKey);if(bindingKey===undefined){continue}const key=`${task.kind}:${bindingKey}`;if(bindingKeys[task.kind]?.has(bindingKey)===false||tasks.has(key)){invalid4(`${path}/definition/steps`)}tasks.add(key)}}};var knowledgeConnectorInstance=(value,path)=>{const parsed=knowledge(value,path);assertPolicyLifecycle(concrete(parsed.dataPolicies),path);const entities=concrete(parsed.entityBindings);const relations=concrete(parsed.relationBindings);const pipelines=concrete(parsed.pipelines);uniqueKeys(entities,`${path}/entityBindings`);uniqueKeys(relations,`${path}/relationBindings`);uniqueKeys(pipelines,`${path}/pipelines`);const entityKeys=knownKeys(parsed.entityBindings);const bindingKeys={entity:entityKeys,relation:knownKeys(parsed.relationBindings)};assertEntityParents(entities,path);for(const[index,binding]of[...entities,...relations].entries()){const parentKey=spelled(binding.parentKey);if(parentKey!==undefined&&(entityKeys?.has(parentKey)===false||parentKey===spelled(binding.key))){invalid4(`${path}/bindings/${index}/parentKey`)}}for(const[index,relation]of relations.entries()){for(const key of[relation.sourceEntityKey,relation.targetEntityKey]){const entityKey=spelled(key);if(entityKey!==undefined&&entityKeys?.has(entityKey)===false){invalid4(`${path}/relationBindings/${index}`)}}}for(const[index,item]of pipelines.entries()){uniqueKeys(concrete(item.schedules),`${path}/pipelines/${index}/schedules`);assertPipelineTasks(item,bindingKeys,`${path}/pipelines/${index}`)}return parsed};var scalar=literal("boolean","string","int64","float64","decimal","date","timestamp","duration","json");var datasetDefinition=varyingObject({fields:varyingArray(varyingObject({id:identity2,name:string3,nullable:boolean2,semantic:optString,type:scalar})),measures:varyingArray(varyingObject({id:identity2,name:string3,resultType:scalar})),relationships:varyingArray(varyingObject({cardinality:literal("one_to_one","one_to_many","many_to_one","many_to_many"),fromFieldId:identity2,id:identity2,toFieldId:identity2})),version:literal(1)});var location=(value,path)=>{const parsed=varyingObject({segments:varyingArray(varyingObject({kind:literal("container","dataset"),label:string3,opaqueId:identity2}))})(value,path);if(isVariableReference(parsed.segments)){return parsed}const[first]=parsed.segments;if(first===undefined||!isVariableReference(first)&&first.kind!=="container"){return invalid4(`${path}/segments/0`)}return parsed};var datasetValue=(value,path)=>{const{kind}=object({kind:string3})(value,path);switch(kind){case"null":{return varyingObject({kind:literal("null")})(value,path)}case"boolean":{return varyingObject({kind:literal("boolean"),value:boolean2})(value,path)}case"float64":{return varyingObject({kind:literal("float64"),value:number3})(value,path)}case"json":{return varyingObject({kind:literal("json"),value:json})(value,path)}default:{return varyingObject({kind:literal("string","int64","decimal","date","timestamp","duration"),value:string3})(value,path)}}};var datasetFilter=(value,path)=>{const{kind}=object({kind:string3})(value,path);if(kind==="not"){return varyingObject({filter:datasetFilter,kind:literal("not")})(value,path)}if(kind==="and"||kind==="or"){return varyingObject({filters:varyingArray(datasetFilter),kind:literal("and","or")})(value,path)}return varyingObject({fieldId:identity2,kind:literal("predicate"),operator:literal("eq","ne","lt","lte","gt","gte","in","not_in","is_null","is_not_null","contains","starts_with"),values:varyingArray(datasetValue)})(value,path)};var datasetFields={...base,connection:optional3(connection2),dataPolicy:optional3(varyingObject({allowedFields:varyingStrings,allowedOperations:varyingArray(literal("describe","records","aggregate","time_series")),maxBytes:budget,maxRows:budget,maxTimeoutMs:budget,principals:varyingArray(varyingObject({id:identity2,kind:literal("user","service")})),rowFilter:optional3(nullable(datasetFilter)),sensitiveFields:optional3(varyingStrings)})),kind:literal("datasetConnectorInstance"),lifecycle,providerFqn:identity2,schedules:optional3(varyingArray(varyingObject({action:literal("health","refresh_definition"),cronExpression:identity2,enabled:optBoolean,key:identity2,timezone:optString}))),settings:optional3(jsonObject)};var datasetConnectorInstance=(value,path)=>{const parsed=union2(varyingObject({...datasetFields,bindingMode:literal("managed"),definition:datasetDefinition,sourceLocation:optional3(location),templateConfig:optional3(varyingObject({variant:identity2,version:literal(1)})),templateFqn:optional3(identity2)}),varyingObject({...datasetFields,bindingMode:literal("external"),definition:optional3(datasetDefinition),gatewayBindingKey:optString,sourceLocation:location,sourceMapping:optional3(varyingObject({effectiveAtFieldId:optString,entityIdFieldId:identity2,historySemantics:optional3(literal("append_history")),kind:literal("entity_snapshot","status_update"),statusFieldId:optString,version:literal(1)}))}))(value,path);uniqueKeys(concrete(parsed.schedules),`${path}/schedules`);return parsed};var datasetParserFormat=(value,path)=>{if(typeof value!=="string"||value.length>128||value==="external"||!/^[a-z][a-z0-9._-]*$/u.test(value)){throw new TypeError(`Invalid dataset parser format at ${path}`)}return value};var datasetParserVersion=(value,path)=>{if(typeof value!=="string"||value.trim()===""||value.length>96){throw new TypeError(`Invalid dataset parser version at ${path}`)}return value};var readExternalAppGateway=closedGatewayObject({...base,expectedContract:readOperationGatewayContract,kind:literal("externalAppGateway")});var externalApplicationConsents=["inherit","ask","skip"];var roleKey=/^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/u;var resourceAction=/^[^:]+:[^:]+$/u;var isOwnAncestor=({key,parent},declared)=>{const seen=new Set;let ancestor=parent;while(ancestor!==undefined&&ancestor!==key&&!seen.has(ancestor)){seen.add(ancestor);ancestor=declared.get(ancestor)?.parent}return ancestor===key};var rolesViolation=(roles=[])=>{const declared=new Map;for(const role of roles){const{key,permissions}=role;if(key.length>64||!roleKey.test(key)){return`role key '${key}' must match ${roleKey.source} and hold at most 64 characters`}if(declared.has(key)){return`role key '${key}' is declared more than once`}declared.set(key,role);const malformed=permissions.find((permission)=>!resourceAction.test(permission));if(malformed!==undefined){return`permission '${malformed}' of role '${key}' must be 'resource:action'`}}for(const role of roles){const{key,parent,permissions,replaces}=role;if(replaces!==undefined){if(declared.has(replaces)){return`role '${key}' replaces '${replaces}', which this release declares`}const first=roles.find((other)=>other.replaces===replaces)?.key;if(first!==key){return`roles '${first}' and '${key}' replace the same role '${replaces}'`}}if(parent===undefined){continue}const held=declared.get(parent)?.permissions;if(held===undefined){return`parent '${parent}' of role '${key}' is not a declared role`}const missing=permissions.find((permission)=>!held.includes(permission));if(missing!==undefined){return`role '${parent}' must hold permission '${missing}' of its child role '${key}'`}if(isOwnAncestor(role,declared)){return`role '${key}' is its own ancestor`}}return};var grantsViolation=(grants=[],roles=[])=>{for(const[index,{group,role}]of grants.entries()){if(group.trim()===""){return`the Grant of role '${role}' must name a Group`}if(!roles.some(({key})=>key===role)){return`role '${role}' of the Grant to Group '${group}' is not a declared role`}const first=grants.findIndex((other)=>other.group===group&&other.role===role);if(first!==index){return`the Grant of role '${role}' to Group '${group}' is declared more than once`}}return};var externalApplicationViolation=({admits,applicationConsent,grants,primaryRedirectUri,redirectUris,roles})=>{if(primaryRedirectUri!==undefined&&!isVariableReference(primaryRedirectUri)&&!isVariableReference(redirectUris)&&!redirectUris.some(isVariableReference)&&!redirectUris.includes(primaryRedirectUri)){return"primaryRedirectUri must be one of redirectUris"}if(applicationConsent!==undefined&&!isVariableReference(applicationConsent)&&!externalApplicationConsents.includes(applicationConsent)){return"applicationConsent must be 'inherit', 'ask' or 'skip'"}if(admits?.length===0){return"admits must name at least one User Class"}const repeated=admits?.find((userClass,index)=>admits.indexOf(userClass)!==index);if(repeated!==undefined){return`admits names '${repeated}' more than once`}return rolesViolation(roles)??grantsViolation(grants,roles)};var subgroupKey=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;var organizationGroupFqnMaxLength=320;var fqnViolation=(fqn)=>{const characters=[...fqn];if(characters.length<=organizationGroupFqnMaxLength){return}const shortened=`${characters.slice(0,40).join("")}...${characters.slice(-40).join("")}`;return`Group FQN '${shortened}' holds ${characters.length} characters; the limit is ${organizationGroupFqnMaxLength}`};var subgroupsViolation=(parentFqn,subgroups=[])=>{const keys=new Set;for(const{key,subgroups:nested}of subgroups){if(!subgroupKey.test(key)){return`subgroup key '${key}' of '${parentFqn}' must match ${subgroupKey.source}`}if(keys.has(key)){return`subgroup key '${key}' is declared more than once in '${parentFqn}'`}keys.add(key);const fqn=`${parentFqn}.${key}`;const violation=fqnViolation(fqn)??subgroupsViolation(fqn,nested);if(violation!==undefined){return violation}}return};var organizationGroupViolation=({fqn,subgroups})=>fqnViolation(fqn)??subgroupsViolation(fqn,subgroups);var sections=["authentication","branding","governance","identity","locale"];var mediaPath=/^media\/[^/]+$/u;var brandingViolation=(branding)=>{if(branding===undefined||isVariableReference(branding)){return}const paths=new Set;for(const key of["cover","icon","logo"]){const reference=branding[key];const media=isVariableReference(reference)?undefined:reference?.media;if(media===undefined||isVariableReference(media)){continue}if(!mediaPath.test(media)){return`branding.${key} media path '${media}' must be media/<file>`}if(paths.has(media)){return`branding.${key} media path '${media}' is used by two branding keys`}paths.add(media)}return};var authenticationViolation=(authentication)=>{if(authentication===undefined||isVariableReference(authentication)){return}for(const method of["otp","password"]){const local=authentication[method];if(local===undefined||isVariableReference(local)){continue}const{domains,enabled}=local;if(enabled===true&&!isVariableReference(domains)&&(domains??[]).length===0){return`authentication.${method} is enabled and needs at least one domain`}}const consent=authentication.applicationConsent;if(consent!==undefined&&!isVariableReference(consent)&&consent!=="ask"&&consent!=="skip"){return"authentication.applicationConsent must be 'ask' or 'skip'"}return};var organizationSettingsViolation=(definition)=>{if(!sections.some((section)=>Object.keys(definition[section]??{}).length>0)){return"at least one setting is required"}if(definition.identity!==undefined&&"slug"in definition.identity){return"identity.slug is not declarable"}return brandingViolation(definition.branding)??authenticationViolation(definition.authentication)};var identifier22=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/u;var fields=new Set(["category","defaultVisibility","description","displayName","fqn","gatewayRef","icon","kind","operationReferences","tags","version"]);var referencesGateway=(reference,gatewayId)=>{const separator=reference.indexOf("@");if(separator===-1){return false}const[gateway,domain,operation,...rest]=reference.slice(0,separator).split("/");const version=reference.slice(separator+1);return identifier22.test(gatewayId)&&gateway===gatewayId&&domain!==undefined&&identifier22.test(domain)&&operation!==undefined&&identifier22.test(operation)&&rest.length===0&&version.length>0&&version.length<=128&&version.trim()===version};var remoteToolCollectionViolation=(declaration)=>{const unknownField=Object.keys(declaration).find((key)=>!fields.has(key));if(unknownField!==undefined){return`unsupported remote metadata field '${unknownField}'`}const{gatewayRef,operationReferences}=declaration;if(gatewayRef===undefined||gatewayRef.trim()===""||gatewayRef.trim()!==gatewayRef){return"gatewayRef must be a nonempty FQN"}if(operationReferences.length===0||new Set(operationReferences).size!==operationReferences.length||operationReferences.some((reference)=>!referencesGateway(reference,reference.split("/")[0]??""))){return"operationReferences must name unique versioned Gateway operations"}return};var readPin=object({fqn:hostedIdentity,releaseDigest:(value,path)=>{const digest=hostedIdentity(value,path);return/^[\da-f]{64}$/u.test(digest)?digest:invalid4(path)},releaseId:hostedIdentity});var parsePackageDependencyPins=(value)=>{const pins=array2(readPin)(value,"/dependencies");const identities=new Set;for(const pin of pins){if(Object.keys(pin).some((key)=>!["fqn","releaseId","releaseDigest"].includes(key))){throw new TypeError(`package dependency '${pin.fqn}' has unexpected fields`)}if(identities.has(pin.fqn)){throw new TypeError(`duplicate package dependency '${pin.fqn}'`)}identities.add(pin.fqn)}return[...pins].sort((left,right)=>compareUtf16CodeUnits(left.fqn,right.fqn))};var PackageManifestVersion="v4";var legacyFixedDestinationTargets=new Set(["fixed-email","channel-destination","telegram-chat","whatsapp-destination"]);var uuid2=/^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/iu;var placeholder=/\{(?<name>[^{}]*)\}/gu;var placeholders={remoteId:(remoteId)=>encodeURIComponent(remoteId),remoteIdUuidHex:(remoteId)=>uuid2.test(remoteId)?remoteId.replaceAll("-","").toLowerCase():null};var isPlaceholderName=(name)=>Object.hasOwn(placeholders,name);var resolver=(name)=>isPlaceholderName(name)?placeholders[name]:undefined;var knowledgeRemoteReferenceUrlTemplate=(value,path)=>{if(typeof value!=="string"||!value.startsWith("https://")||/[{}]/u.test(value.replaceAll(placeholder,(match,name)=>resolver(name)===undefined?match:""))){throw new TypeError(`Invalid remote reference URL template at ${path}`)}return value};var HOSTS=["backend","dashboard","studio"];var FRONTEND_CATALOG_CONTRACT="frontend-catalog/v1";var FRONTEND_CATALOG_EXPORT_NAME="loadFrontendCatalog";var BACKEND_EXECUTION_LANES=["interactive","job"];var packageManifestJson=(definition)=>parseJsonObject(canonicalJson(definition.manifest));var canonicalPackageManifest=(definition)=>canonicalJson(packageManifestJson(definition));var toolBindingDeclaration=(entry)=>typeof entry==="string"?{tool:entry}:entry;var duplicateToolBinding=(tools)=>{const seen=new Set;for(const entry of tools){const binding=toolBindingDeclaration(entry);const key=JSON.stringify([binding.tool,binding.name??null]);if(seen.has(key)){return binding}seen.add(key)}return};var agentAudienceViolation=(audience)=>{const applications=audience.applications??[];if(audience.anonymous===true&&applications.length===0){return"anonymous visitors need an application in audience.applications"}const repeated=applications.find((fqn,index)=>applications.indexOf(fqn)!==index);return repeated===undefined?undefined:`audience application '${repeated}' is listed more than once`};var agentModelTiers=["complex","balanced","fast","super_fast"];var notificationDefinition=object({capabilities:object({extensionReadyProviders:strings,recipientTargets:strings,supportsActionLink:boolean2,supportsAttachments:boolean2,supportsFixedDestinations:optBoolean,supportsHtml:boolean2,supportsMarkdown:boolean2,supportsMentions:boolean2,supportsReadReceipts:boolean2,supportsRouteDestinations:boolean2,supportsThreads:boolean2}),credentialProfileKey:optString,family:literal("email","im","internal"),key:string3,provider:string3,setup:object({docsUrl:nullable(string3),healthCheck:object({available:boolean2,label:optString}),instructions:string3,liveTest:object({available:boolean2,label:optString}),secretFields:strings,setupForm:nullable(form)})});var studioPage=object({fullWidth:optBoolean,icon:optString,kind:literal("predefined"),label:string3,orderIndex:number3,predefinedPageRef:string3,routeSegment:string3,slug:string3});var studioSection=object({description:optString,icon:optString,label:string3,orderIndex:number3,pages:array2(studioPage),slug:string3});var studioApp=object({color:optString,description:optString,icon:optString,isDefaultTemplate:optBoolean,name:string3,sections:array2(studioSection),slug:string3});var datasetScalarType=literal("boolean","string","int64","float64","decimal","date","timestamp","duration","json");var datasetDefinition2=object({fields:array2(object({id:string3,name:string3,nullable:boolean2,semantic:optional3(string3),type:datasetScalarType})),measures:array2(object({id:string3,name:string3,resultType:datasetScalarType})),relationships:array2(object({cardinality:literal("one_to_one","one_to_many","many_to_one","many_to_many"),fromFieldId:string3,id:string3,toFieldId:string3})),version:literal(1)});var datasetBlueprint=object({...base,blueprintVersion:positiveSafeInteger,configuration:optional3(jsonObject),definition:datasetDefinition2,kind:literal("datasetBlueprint"),templateFqn:identity2});var semanticRole=literal("dimension","effective_time","entity_reference","event_time","identity","measure","status");var hint=object({role:semanticRole});var datasetTableTemplate=object({...base,admittedIngestionModes:array2(literal("append","replace","upsert")),compatibleProviderFqns:strings,configuration:schema2,identity:object({keyRoles:array2(semanticRole),uniqueness:literal("append_only","key","none")}),indexHints:array2(hint),kind:literal("datasetTableTemplate"),partitionHints:array2(hint),physicalCode:literal("evt","fact","gen","snap","stat","ts"),requirements:schema2,semanticRoles:array2(semanticRole)});var WorkflowEditorWidgets=["checkbox","code","condition_builder","credential_selector","key_value","list","mapping_builder","multi_select","number","resource_selector","schedule_builder","schema_builder","select","text","textarea"];var WorkflowTemplateKinds=["action_node","input_node","output_node","trigger_node"];var WorkflowTriggerLifecycleAdapterIds=Object.freeze({externalApplication:"builtin.core.workflows.lifecycle.external-application",mcpOperation:"builtin.core.workflows.lifecycle.mcp-operation"});var dynamicPort=object({configPath:string3,defaultIdPath:optString,idPath:string3,requiredPath:optString,schemaPath:optString});var fieldBinding=object({path:pathParts,target:literal("input_binding","parameter")});var nonNegativeInteger=(value,path)=>{const parsed=number3(value,path);return Number.isSafeInteger(parsed)&&parsed>=0?parsed:invalid4(path)};var optionSource=union2(object({kind:literal("static"),options:array2(object({label:localized,value:json}))}),object({clearOnDependencyChange:boolean2,dependsOn:array2(fieldBinding),kind:literal("remote"),operationId:string3,searchable:boolean2}));var editorField=object({binding:fieldBinding,fieldConfig:optional3(jsonObject),fieldFqn:optString,fieldVersion:optString,help:optional3(localized),label:optional3(localized),optionSource:optional3(optionSource),order:optNumber,placeholder:optional3(localized),readOnly:optBoolean,required:optBoolean,resolutionPhase:literal("runtime","structural"),sensitive:optBoolean,valueSources:array2(literal("expression","fixed","literal","mapping","model","system")),visibleWhen:optional3(array2(object({binding:fieldBinding,operator:literal("equals","in","is_not_set","is_set","not_equals"),value:optional3(json)}))),widget:optional3(literal(...WorkflowEditorWidgets))});var templateKind=literal(...WorkflowTemplateKinds);var nodePort=refine(object({allowedTemplateFqns:optStrings,allowedTemplateKinds:optional3(array2(templateKind)),direction:literal("input","output"),key:string3,maxConnections:optional3(nullable(nonNegativeInteger)),minConnections:optional3(nonNegativeInteger),schemaResolution:optional3(object({configPath:pathParts,variants:array2(object({schema:schema2,schemaInjections:optional3(array2(object({configPath:pathParts,schemaPath:pathParts}))),when:json}))})),valueSchema:schema2}),workflowPortPolicyViolation);var eventSelectorProjection=union2(object({required:optBoolean,sourcePath:pathParts,targetPath:pathParts}),object({targetPath:pathParts,value:json}));var eventIngress=object({acquisitionMode:string3,callbackPathPath:optional3(pathParts),connectionIdPath:optional3(pathParts),eventKind:string3,listener:object({fqn:string3,version:string3}),requiredConfigPaths:optional3(array2(pathParts)),requiredListener:optBoolean,selector:array2(eventSelectorProjection)});var triggerActivation=union2(object({eventIngress,kind:literal("event")}),union2(object({invocationRole:optional3(literal("application","user")),kind:literal("manual"),lifecycleAdapterId:optString,triggerRefPath:optional3(pathParts)}),object({kind:literal("schedule")})));var parseWorkflowReusableDependency=(value)=>object({inputContractPath:pathParts,modePath:optional3(pathParts),targetWorkflowFqnPath:optional3(pathParts),targetWorkflowIdPath:pathParts})(value,"/reusableDependency");var nodeContract=object({capabilityComposition:optional3(object({capability:string3,fragments:strings,selector:object({path:pathParts,target:literal("parameter")})})),configSchema:optional3(schema2),connectionRequirements:optional3(array2(object({cardinality:literal("many","one"),connectionTemplateFqns:refine(strings,(fqns)=>fqns.length===0?"connectionTemplateFqns cannot be empty":undefined),key:string3,required:boolean2,selector:object({path:pathParts,target:literal("parameter")})}))),dynamicPorts:optional3(object({input:optional3(dynamicPort),output:optional3(dynamicPort)})),editor:optional3(refine(object({form:optional3(object({sections:optional3(array2(object({fields:optional3(array2(editorField)),id:optString,order:optNumber,title:optString})))}))}),workflowEditorViolation)),execution:optional3(object({itemModes:optional3(array2(literal("all_items","each_item","single"))),mainOutputPort:optString,repeatable:optBoolean,resumable:optBoolean,sideEffect:literal("external","none","read","write"),testable:optBoolean})),implementationId:string3,inputSchema:optional3(schema2),instancePolicy:optional3(object({maxInstances:optNumber,minInstances:optNumber,onWorkflowCreate:optBoolean})),nodeCollectionFqn:optString,nodeCollectionVersion:optString,outputChannels:optional3(array2(object({adapterId:string3,cardinality:literal("many","one"),deliveryMode:literal("asynchronous","synchronous"),key:string3,required:boolean2,valueSchema:schema2}))),outputSchema:optional3(schema2),ports:optional3(array2(nodePort)),reusableDependency:optional3(parseWorkflowReusableDependency),triggerActivation:optional3(triggerActivation)});var fieldContract=object({availableForInput:optBoolean,availableForOutput:optBoolean,clearOnDependencyChange:optBoolean,optionDependencies:optional3(array2(object({path:pathParts,target:literal("parameter","part","value")}))),valueSchema:optional3(schema2)});var graphSchema=object({bindings:optional3(array2(object({extensions:jsonObject}))),fieldProjections:array2(object({source:pathParts,target:pathParts})),schema:schema2});var graphBoundary=object({templateFqn:string3,templateVersion:string3});var graph=object({edges:array2(object({extensions:optional3(jsonObject),id:string3,source:string3,target:string3})),inputBoundary:graphBoundary,inputContract:graphSchema,metadata:object({description:nullable(string3),tags:strings,templateSource:nullable(string3)}),nodes:array2(object({extensions:optional3(jsonObject),id:string3,templateFqn:string3,templateVersion:string3})),outputBoundary:graphBoundary,outputContract:graphSchema,triggers:array2(object({config:object({extensions:optional3(jsonObject)}),id:string3,inputBindings:record2(string3),invocation:object({mode:literal("attach","detach"),timeoutMs:nullable(number3)}),metadata:object({fieldDisplayValues:record2(string3)}),settings:object({enabled:boolean2}),templateFqn:string3,templateVersion:string3})),version:literal(1)});var uiLayout=object({edges:record2(object({extensions:optional3(jsonObject)})),nodes:record2(object({position:optional3(object({x:number3,y:number3}))})),version:literal(1),viewport:nullable(object({x:number3,y:number3,zoom:number3}))});var bindingSpan=object({end:number3,start:number3});var bindingSource=object({kind:literal("input","loop_index","loop_item","merge_output","node_output","port_arrival","run","scope","trigger"),mergeId:optional3(nullable(string3)),nodeId:optional3(nullable(string3)),portId:optional3(nullable(string3)),selection:optional3(nullable(object({ancestry:literal("nearest_dominating_ancestor"),iteration:literal("aggregate","previous_iteration","same_iteration")})))});var bindingExpression=(value,path)=>{const{kind}=object({kind:string3})(value,path);switch(kind){case"array":{return object({items:array2(bindingExpression),kind:literal("array")})(value,path)}case"call":{return object({args:array2(bindingExpression),kind:literal("call"),name:string3})(value,path)}case"interpolation":{return object({kind:literal("interpolation"),parts:array2(bindingExpression),span:optional3(nullable(bindingSpan))})(value,path)}case"literal":{return object({kind:literal("literal"),value:json})(value,path)}case"object":{return object({fields:record2(bindingExpression),kind:literal("object")})(value,path)}case"operator":{return object({args:array2(bindingExpression),kind:literal("operator"),op:string3})(value,path)}case"ref":{return object({kind:literal("ref"),onUnavailable:object({kind:literal("error","fallback","null"),value:optional3(nullable(bindingExpression))}),path:pathParts,source:bindingSource,span:optional3(nullable(bindingSpan))})(value,path)}default:{return invalid4(`${path}/kind`)}}};var authoredValue=union2(object({mode:literal("fixed"),value:json}),object({compiled:optional3(nullable(bindingExpression)),languageVersion:literal(1),mode:literal("expression"),source:string3}));var nodeExecutionSettings=object({dryRun:optional3(object({mode:literal("allow","block_side_effects")})),idempotencyKey:optional3(nullable(bindingExpression)),onError:optional3(object({mode:literal("continue","fail_run")})),retry:optional3(object({backoffMs:optional3(nullable(number3)),maxAttempts:optional3(nullable(number3)),mode:literal("disabled","exponential","fixed")})),timeoutMs:optional3(nullable(number3))});var authoringTemplateRef=object({templateFqn:string3,templateVersion:string3});var authoringFieldProjection=object({fieldConfig:optional3(jsonObject),fieldFqn:string3,fieldVersion:string3,path:strings});var authoringInputContract=object({fieldProjections:optional3(array2(authoringFieldProjection)),jsonSchema:jsonObject});var authoringOutputContract=object({bindings:array2(object({key:string3,kind:literal("artifact","value"),value:bindingExpression})),fieldProjections:optional3(array2(authoringFieldProjection)),jsonSchema:jsonObject});var inputEndpoint=object({kind:literal("input_node"),portId:string3});var actionEndpoint=object({kind:literal("action_node"),nodeId:string3,portId:string3});var triggerEndpoint=object({kind:literal("trigger_node"),portId:string3,triggerId:string3});var outputEndpoint=object({kind:literal("output_node"),portId:string3});var authoringDefinition=object({edges:array2(object({id:string3,source:union2(union2(actionEndpoint,inputEndpoint),triggerEndpoint),target:union2(union2(actionEndpoint,inputEndpoint),outputEndpoint)})),inputBoundary:authoringTemplateRef,inputContract:authoringInputContract,metadata:jsonObject,nodes:array2(object({config:record2(authoredValue),extensions:optional3(jsonObject),id:string3,inputs:record2(authoredValue),metadata:jsonObject,settings:nodeExecutionSettings,templateFqn:string3,templateVersion:string3,uid:optString})),outputBoundary:authoringTemplateRef,outputContract:authoringOutputContract,triggers:array2(object({config:jsonObject,id:string3,inputBindings:record2(object({overridePolicy:literal("caller_may_override","locked"),value:authoredValue})),invocation:object({mode:literal("attach","await_result","detach"),timeoutMs:optional3(nullable(number3))}),metadata:jsonObject,settings:jsonObject,templateFqn:string3,templateVersion:string3})),version:literal(1)});var knowledgeSelection=optional3(object({exclude:optional3(array2(identity2)),include:optional3(array2(identity2))}));var toolBindings2=refine(array2(union2(identity2,object({approval:optional3(union2(literal("always","never"),object({rule:identity2}))),knowledge:optional3(object({domains:knowledgeSelection,entitySchemas:knowledgeSelection,relationSchemas:knowledgeSelection,unrestricted:optBoolean})),name:optional3(identity2),settings:optional3(jsonObject),tool:identity2}))),(tools)=>duplicateToolBinding(tools)===undefined?undefined:"duplicate tool binding");var agentAudience2=refine(object({anonymous:optBoolean,applications:optional3(array2(identity2)),members:optional3(literal("all","none","selected")),organizationGroups:optional3(literal("none","selected"))}),(audience)=>("organizationTeams"in audience)?"organizationTeams":agentAudienceViolation(audience));var withoutRetiredAgentFields=(agent)=>["invokingApplicationFqns","modelPreset"].find((field)=>(field in agent));var webhookHandshake=union2(object({kind:literal("echo_query_parameter"),parameter:identity2}),union2(object({kind:literal("echo_query_parameter_with_verify_token"),parameter:identity2,tokenParameter:identity2}),object({field:identity2,kind:literal("echo_json_body_field"),when:object({equals:string3,field:identity2})})));var localMethod=varyingObject({domains:optional3(varyingStrings),enabled:boolean2});var media=varyingObject({media:string3});var organizationSettingsSso=object({...varyingFields({connection:varyingObject({setupKey:identity2}),defaultRole:literal("organization_admin","organization_user"),domains:varyingStrings,enabled:boolean2,provisionMembers:boolean2}),provider:union2(object({fqn:identity2}),varyingObject({providerId:identity2}))});var organizationSettings=object({...varyingFields({...base,branding:optional3(varyingObject({cover:optional3(media),icon:optional3(media),logo:optional3(media)})),governance:optional3(varyingObject({accessAuditRetentionMonths:optional3(positiveSafeInteger),maxGroupHierarchyDepth:optional3(positiveSafeInteger)})),identity:optional3(varyingObject({companyDomains:optional3(varyingStrings),name:optString})),kind:literal("organizationSettings"),lifecycle,locale:optional3(varyingObject({defaultLanguage:optString,languages:optional3(varyingStrings),timezone:optString}))}),authentication:varyingStructure(optional3(object({...varyingFields({applicationConsent:optional3(literal("ask","skip")),otp:optional3(localMethod),password:optional3(localMethod)}),sso:varyingStructure(optional3(array2(varyingStructure(organizationSettingsSso))))})))});var subgroups=(value,path)=>optional3(array2(object({description:optString,displayName:string3,key:string3,subgroups})))(value,path);var primitives={agent:refine(object({...base,activity:optional3(object({heartbeat:boolean2,schedule:boolean2})),audience:optional3(agentAudience2),behavioralBoundaries:strings,kind:literal("agent"),lifecycle,maxSteps:optional3(positiveSafeInteger),modelTier:optional3(literal(...agentModelTiers)),objectives:strings,operatingInstructions:string3,output:optional3(object({schema:schema2})),responsibility:string3,skills:array2(identity2),tools:toolBindings2}),withoutRetiredAgentFields),connection,datasetBlueprint,datasetConnectorInstance,datasetParser:object({...base,extensions:array2(identity2),format:datasetParserFormat,kind:literal("datasetParser"),mediaTypes:array2(identity2),parserVersion:datasetParserVersion}),datasetTableTemplate,documentsConnector:object({...base,connectionRefs,kind:literal("documentsConnector"),providerDisplayName:optional3(identity2),providerFamily:identity2}),domain:object({...base,kind:literal("domain"),lifecycle,localMutationPolicy:optional3(mutationPolicy),versioningEnabled:nullable(boolean2)}),domainTemplate:object({...base,catalogTags,domainFqn:string3,domainName:string3,entitySchemaFqns:strings,kind:literal("domainTemplate"),relationSchemaFqns:strings}),emailProvider:object({...base,connectionTemplateFqn:identity2,deploymentIdentity:optional3(literal("aws")),kind:literal("emailProvider"),senderKind:literal("address","mailbox")}),eventListener:object({...base,capabilities:array2(literal("internal","poll","webhook")),eventKind:string3,kind:literal("eventListener"),manualWebhookState:optional3(object({keyFamily:identity2,stateKey:identity2})),messaging:optional3(object({connectionTemplateFqn:identity2,contractVersion:literal(1),service:identity2})),receiveModeField:optional3(identity2),runtimeState:optional3(array2(object({keyFamily:string3,stateKey:string3}))),safeOccurrenceFields:optStrings,safeSelectorFields:optStrings,sourceScope:optional3(literal("connection","selector")),webhookAcknowledgement:optional3(object({status:literal(200,204)})),webhookHandshake:optional3(webhookHandshake),webhookRegistration:optional3(literal("listener"))}),externalAppGateway:readExternalAppGateway,externalApplication:substituted(refine(object({...varyingFields({...base,allowedOrigins:varyingStrings,applicationConsent:optional3(literal(...externalApplicationConsents)),applicationType:literal("confidential","public"),audience:string3,kind:literal("externalApplication"),lifecycle,postLogoutRedirectUris:varyingStrings,primaryRedirectUri:optString,redirectUris:varyingStrings,scopes:varyingStrings,setupInstructions:optString}),admits:optional3(array2(literal("internal","external"))),grants:optional3(array2(object({group:string3,lifecycle,role:string3}))),roles:optional3(array2(object({key:string3,parent:optString,permissions:strings,replaces:optString})))}),externalApplicationViolation)),externalDatasetProvider:object({...base,capabilities:datasetCapabilities,connectionTemplateFqns:strings,kind:literal("externalDatasetProvider"),sourceCapabilities:optional3(array2(object({capabilities:datasetCapabilities,datasetOpaqueIdPrefix:string3})))}),fieldTransformer:object({...base,kind:literal("fieldTransformer"),sourceFieldType:string3,targetFieldType:string3}),knowledgeConnector:object({...base,autoActivate:optBoolean,autoInstantiate:optBoolean,bindingScopes:optional3(bindingScopes),connectionRefs,contributions:optional3(array2(object({capabilityFqn:string3,connectionSlot:string3,connectionTemplateFqn:string3,controlFqn:optString,displayName:string3,fqn:identity2,metadata:optional3(jsonObject)}))),defaultOutboundStrategy:optional3(outboundStrategy),defaultUpdateMode:optional3(updateMode),discoveryDefaults:optional3(discoveryDefaults),entityIdentityMode:optional3(literal("adapter","item_metadata")),entitySchemaCapabilities:optional3(array2(entityCapability)),isSingleton:optBoolean,kind:literal("knowledgeConnector"),outboundCapability:optional3(literal("declared_and_enablable","none")),recommendedImportSchedules:predefinedSchedules,relationSchemaCapabilities:optional3(array2(relationCapability)),remoteReference:optional3(object({providerKey:identity2,urlTemplate:knowledgeRemoteReferenceUrlTemplate})),settings:optional3(form),supportedBindingModes:optional3(bindingModes)}),knowledgeConnectorInstance,knowledgeConnectorOauth:object({...base,connectorFqn:string3,kind:literal("knowledgeConnectorOauth")}),knowledgeEntityAdapter:object({...base,connectorFqn:string3,entitySchemaFqn:string3,kind:literal("knowledgeEntityAdapter"),normalizesFieldMapValues:optBoolean,normalizesImportedData:optBoolean}),knowledgeEntitySchema:object({...base,...knowledgeSchema,autocompleteConfiguration,defaultSyncDirection:optString,deletionMode:optString,displayDefaults:optional3(object({collections:optStrings,details:optStrings})),displayNameExpression:nullable(string3),embedEntities:optBoolean,embeddingConfig:nullable(jsonObject),extendsSchemaFqn:optString,kind:literal("knowledgeEntitySchema"),lifecycle,maxVersionsExpirationDays:optional3(nullable(number3)),persistFullFieldContributions:boolean2,relationFields:optional3(array2(object({cardinality:literal("many","one"),field:string3,id:string3,nullable:boolean2,reference:literal("external_id"),targetEntityId:string3,targetSchemaFqn:string3}))),syncable:optBoolean,usableAsDocumentScope:boolean2,versioned:optBoolean,versioningEnabled:nullable(boolean2)}),knowledgePolicy:object({...base,...policyFields,kind:literal("knowledgePolicy"),priority:optNumber}),knowledgeRelationAdapter:object({...base,connectorFqn:string3,kind:literal("knowledgeRelationAdapter"),relationSchemaFqn:string3}),knowledgeRelationSchema:object({...base,...knowledgeSchema,kind:literal("knowledgeRelationSchema"),lifecycle:optional3(lifecycle),sourceSchemaFqn:string3,targetSchemaFqn:string3}),managedDatasetProvider:object({...base,capabilities:datasetCapabilities,connectionTemplateFqns:strings,kind:literal("managedDatasetProvider")}),notificationChannel:object({...base,credential:optional3(form),definition:notificationDefinition,kind:literal("notificationChannel")}),organizationGroup:refine(object({...base,kind:literal("organizationGroup"),lifecycle,parent:optional3(identity2),subgroups}),organizationGroupViolation),organizationSettings:substituted(refine(organizationSettings,organizationSettingsViolation)),organizationSso:object({...base,connectionTemplateFqn:string3,kind:literal("organizationSso"),providerId:string3,requiredCredentialFields:strings,secretCredentialFields:optStrings,setupGuide:optional3(array2(object({locale:string3,markdown:string3})))}),outboundMessagingProvider:object({...base,connectionTemplateFqn:identity2,kind:literal("outboundMessagingProvider"),service:identity2}),remoteToolCollection:refine(object({...base,category:optString,defaultVisibility:optional3(array2(object({effect:literal("allow","deny"),subject:literal("organization")}))),gatewayRef:identity2,kind:literal("remoteToolCollection"),operationReferences:strings}),remoteToolCollectionViolation),skill:object({...base,instructions:string3,kind:literal("skill"),lifecycle,tools:toolBindings2}),skillTemplate:object({...base,catalogTags,kind:literal("skillTemplate"),lifecycle:optional3(lifecycle),name:string3}),studioApp:object({...base,definition:studioApp,kind:literal("studioApp")}),studioComponent:object({...base,category:literal("layout","page","primitive","view","widget"),composition:optional3(object({extensions:optional3(jsonObject),slotSource:literal("props","static"),slots:array2(object({extensions:optional3(jsonObject),key:string3,label:optional3(localized)}))})),kind:literal("studioComponent"),propsSchema:schema2,sourceRef:string3}),tool:object({...base,allowMultipleSkillBindings:optBoolean,autoActivate:optBoolean,autoInstantiate:optBoolean,bindingScopes:optional3(bindingScopes),bindingSettings:optional3(form),capabilityType:optional3(literal("delegate","external","read","write")),category:optString,connectionRefs,effectKind:optional3(literal("mutation","read_only")),extraLoaders:optional3(array2(object({bindingName:string3,inheritBindingSettings:optBoolean,toolFqn:string3}))),healthCheck:optional3(object({capabilities:optStrings,description:string3})),input:schema2,isSingleton:optBoolean,kind:literal("tool"),output:schema2,settings:optional3(form),setupInstructions:optional3(object({links:strings,markdown:string3})),toolCollectionFqns:optStrings,toolGuidance:optional3(object({inputRequirementsSummary:optString,useWhen:optString})),usageScopes:optional3(array2(literal("automation","chat","skill")))}),toolCollection:object({...base,category:optString,defaultVisibility:optional3(array2(object({effect:literal("allow","deny"),subject:literal("organization")}))),kind:literal("toolCollection"),toolFqns:strings}),toolSettingsOptions:object({...base,catalogCollection:optString,catalogConnectionSlots:optStrings,connectionSlots:optStrings,dependencies:optStrings,fieldKey:string3,formTarget:optional3(literal("binding","settings")),includeUnavailableSelectedOptions:optBoolean,kind:literal("toolSettingsOptions"),toolFqn:string3}),workflow:object({...base,definition:authoringDefinition,kind:literal("workflow"),lifecycle,name:string3,slug:string3}),workflowField:object({...base,collectionFqn:string3,collectionVersion:string3,contract:fieldContract,kind:literal("workflowField"),presentation:optional3(object({placeholder:optString,widget:optString}))}),workflowFieldCollection:object({...base,contract:object({weight:number3}),kind:literal("workflowFieldCollection"),presentation:optional3(object({categoryPath:strings,label:localized}))}),workflowNode:object({...base,contract:nodeContract,kind:literal("workflowNode"),nodeKind:literal("action","input","output","trigger"),presentation:optional3(object({categoryPath:optStrings,tags:optStrings}))}),workflowNodeCollection:object({...base,contract:object({collection:optional3(object({parentFqn:string3,parentVersion:string3,weight:number3}))}),kind:literal("workflowNodeCollection"),presentation:optional3(object({categoryPath:strings}))}),workflowTemplate:object({...base,catalogTags,category:string3,definition:graph,kind:literal("workflowTemplate"),lifecycle,name:string3,requiredSkills:strings,requiredTools:strings,skillSlots:strings,slug:string3,uiLayout:nullable(uiLayout)})};var primitive=(v,p)=>{const{kind}=object({kind:string3})(v,p);for(const[name,read]of Object.entries(primitives)){if(name===kind){return read(v,p)}}return invalid4(`${p}/kind`)};var packageVariable=(value,path)=>{const declared=object({default:optional3(json),description:optString,type:literal(...packageVariableTypes)})(value,path);const name=path.slice(path.lastIndexOf("/")+1);if(packageVariableViolation(name,declared)!==undefined){return invalid4(path)}return declared};var readHostedContribution=(value,path)=>{const shared=object({compatibility:optional3(record2(string3)),contract:optString,execution:optional3(literal("interactive","job")),exportName:hostedIdentity,fqn:hostedIdentity,host:literal("backend","dashboard","studio")})(value,path);if(shared.host==="backend"){return{...shared.compatibility===undefined?undefined:{compatibility:shared.compatibility},...shared.contract===undefined?undefined:{contract:shared.contract},...shared.execution===undefined?undefined:{execution:shared.execution},exportName:shared.exportName,fqn:shared.fqn,host:shared.host}}if(shared.execution!==undefined){throw new TypeError(`Invalid package manifest at ${path}/execution: frontend contributions cannot declare an execution lane`)}if(shared.contract!==FRONTEND_CATALOG_CONTRACT){throw new TypeError(`Invalid package manifest at ${path}/contract: frontend contribution contract must be '${FRONTEND_CATALOG_CONTRACT}'`)}if(shared.exportName!==FRONTEND_CATALOG_EXPORT_NAME){throw new TypeError(`Invalid package manifest at ${path}/exportName: frontend contribution export must be '${FRONTEND_CATALOG_EXPORT_NAME}'`)}return{...shared.compatibility===undefined?undefined:{compatibility:shared.compatibility},contract:FRONTEND_CATALOG_CONTRACT,exportName:FRONTEND_CATALOG_EXPORT_NAME,fqn:shared.fqn,host:shared.host}};var readManifest=object({apiVersion:literal(PackageManifestVersion),author:optString,autoInstallable:optBoolean,bindingScopes:optional3(array2(literal("organization","tenant"))),category:optString,dependencies:optional3(parsePackageDependencyPins),description:optString,documentation:optString,fqn:identity2,homepage:optString,hostedContributions:optional3(array2(readHostedContribution)),icon:optString,installationWizard:optional3(object({size:optional3(literal("lg","md","xl")),steps:array2(object({description:optString,kind:literal("connector_instance","tool_instance"),optional:optBoolean,ref:string3,title:optString}))})),name:string3,primitives:array2(primitive),requiredEnvironmentVariables:optStrings,tags:optStrings,tenantMandatory:optBoolean,tenantStandard:optBoolean,variables:optional3(record2(packageVariable)),version:string3});var parsePackageManifest=(value)=>{assertDenseArrays(value,"",new WeakSet);const manifest=readManifest(parseJsonObject(canonicalJson(value)),"");return manifest.dependencies===undefined?manifest:{...manifest,dependencies:parsePackageDependencyPins(manifest.dependencies)}};var assertArchivePath=(path)=>{if(path===""||path.startsWith("/")||path.includes("\\")||path.split("/").some((part)=>part===""||part==="."||part==="..")){throw new TypeError(`Extension Release archive has unsafe path '${path}'`)}};var assertRuntimeAssetPath=(path)=>{if(!/^artifacts\/(?:(?:backend|dashboard|studio)\/.+|media\/[^/]+)$/u.test(path)){throw new TypeError(`Extension Release archive entry '${path}' is not a runtime asset path`)}};var PackageManifestArchivePath="package-manifest.json";var assertReleaseArchiveEntryPath=(path)=>{assertArchivePath(path);if(path!==PackageManifestArchivePath){assertRuntimeAssetPath(path)}};var ExtensionReleaseManifestVersion="v2";var PACKAGE_MEDIA_SIZE_LIMIT_BYTES=2*1024*1024;var PackageMediaArchivePrefix="artifacts/media/";var sha256Pattern=/^[\da-f]{64}$/u;var isExtensionHost=(value)=>value==="backend"||value==="dashboard"||value==="studio";var isRecord=(value)=>value!==null&&typeof value==="object"&&!Array.isArray(value);var assertExactKeys=(value,allowedKeys,label)=>{const allowed=new Set(allowedKeys);const unexpected=Object.keys(value).find((key)=>!allowed.has(key));if(unexpected!==undefined){throw new TypeError(`${label} has unexpected field '${unexpected}'`)}};var requireRecord=(value,label)=>{if(!isRecord(value)){throw new TypeError(`${label} must be an object`)}return value};var requireString=(value,label)=>{if(typeof value!=="string"||value.trim()===""){throw new TypeError(`${label} must be a non-empty string`)}return value};var requireDigest=(value,label)=>{const digest=requireString(value,label);if(!sha256Pattern.test(digest)){throw new TypeError(`${label} must be a lowercase SHA-256 digest`)}return digest};var requireSize=(value,label)=>{if(typeof value!=="number"||!Number.isSafeInteger(value)||value<0){throw new TypeError(`${label} must be a non-negative safe integer`)}return value};var requireHost=(value,label)=>{if(typeof value!=="string"||!isExtensionHost(value)){throw new TypeError(`${label} must identify a supported Host`)}return value};var assertUniqueSorted=(values,keyOf,label)=>{let previous;for(const value of values){const current=keyOf(value);if(previous!==undefined&¤t<=previous){throw new TypeError(`${label} must be unique and sorted`)}previous=current}};var parsePrivateSourceMap=(value,label)=>{const sourceMap=requireRecord(value,label);assertExactKeys(sourceMap,["digest","size"],label);return{digest:requireDigest(sourceMap.digest,`${label}.digest`),size:requireSize(sourceMap.size,`${label}.size`)}};var parseAsset=(value,index)=>{const label=`Extension Release asset ${index}`;const asset=requireRecord(value,label);assertExactKeys(asset,["digest","host","path","privateSourceMap","size"],label);const path=requireString(asset.path,`${label}.path`);assertArchivePath(path);assertRuntimeAssetPath(path);const host=requireHost(asset.host,`${label}.host`);if(!path.startsWith(`artifacts/${host}/`)){throw new TypeError(`Extension Release asset '${path}' does not match Host '${host}'`)}return{digest:requireDigest(asset.digest,`${label}.digest`),host,path,...asset.privateSourceMap===undefined?undefined:{privateSourceMap:parsePrivateSourceMap(asset.privateSourceMap,`${label}.privateSourceMap`)},size:requireSize(asset.size,`${label}.size`)}};var parseMedia=(value,index)=>{const label=`Extension Release media ${index}`;const media=requireRecord(value,label);assertExactKeys(media,["digest","path","size"],label);const path=requireString(media.path,`${label}.path`);assertArchivePath(path);if(!path.startsWith(PackageMediaArchivePrefix)||path.slice(PackageMediaArchivePrefix.length).includes("/")){throw new TypeError(`Extension Release media '${path}' is not a Package Media path`)}const size=requireSize(media.size,`${label}.size`);if(size>PACKAGE_MEDIA_SIZE_LIMIT_BYTES){throw new TypeError(`${label}.size exceeds the Package Media limit of ${PACKAGE_MEDIA_SIZE_LIMIT_BYTES} bytes`)}return{digest:requireDigest(media.digest,`${label}.digest`),path,size}};var parseContribution=(value,index)=>{const label=`Extension Release contribution ${index}`;const contribution=requireRecord(value,label);assertExactKeys(contribution,["assetPath","contract","digest","execution","exportName","fqn","host","size"],label);const assetPath=requireString(contribution.assetPath,`${label}.assetPath`);assertArchivePath(assetPath);const host=requireHost(contribution.host,`${label}.host`);const exportName=requireString(contribution.exportName,`${label}.exportName`);const contract=contribution.contract===undefined?undefined:requireString(contribution.contract,`${label}.contract`);const execution=contribution.execution===undefined?undefined:BACKEND_EXECUTION_LANES.find((lane)=>lane===contribution.execution);if(contribution.execution!==undefined&&execution===undefined){throw new TypeError(`${label}.execution must be 'interactive' or 'job'`)}const common={assetPath,digest:requireDigest(contribution.digest,`${label}.digest`),fqn:requireString(contribution.fqn,`${label}.fqn`),size:requireSize(contribution.size,`${label}.size`)};if(host==="backend"){return{...common,...contract===undefined?undefined:{contract},...execution===undefined?undefined:{execution},exportName,host}}if(execution!==undefined){throw new TypeError(`${label}.execution is only valid for backend`)}if(contract!==FRONTEND_CATALOG_CONTRACT){throw new TypeError(`${label}.contract must be '${FRONTEND_CATALOG_CONTRACT}'`)}if(exportName!==FRONTEND_CATALOG_EXPORT_NAME){throw new TypeError(`${label}.exportName must be '${FRONTEND_CATALOG_EXPORT_NAME}'`)}return{...common,contract:FRONTEND_CATALOG_CONTRACT,exportName:FRONTEND_CATALOG_EXPORT_NAME,host}};var parseExtensionReleaseManifest=(value)=>{const manifest=requireRecord(value,"Extension Release manifest");assertExactKeys(manifest,["apiVersion","assets","compatibility","contributions","media","package","packageManifest","releaseDigest"],"Extension Release manifest");if(manifest.apiVersion!==ExtensionReleaseManifestVersion){throw new TypeError("Extension Release manifest has unsupported apiVersion")}if(!Array.isArray(manifest.assets)){throw new TypeError("Extension Release manifest assets must be an array")}if(!Array.isArray(manifest.contributions)){throw new TypeError("Extension Release manifest contributions must be an array")}if(manifest.media!==undefined&&!Array.isArray(manifest.media)){throw new TypeError("Extension Release manifest media must be an array")}const compatibilityInput=requireRecord(manifest.compatibility,"Extension Release manifest compatibility");const compatibility=Object.fromEntries(Object.entries(compatibilityInput).map(([runtime,range])=>[requireString(runtime,"Extension Release compatibility runtime"),requireString(range,`Extension Release compatibility '${runtime}'`)]));const packageInput=requireRecord(manifest.package,"Extension Release manifest package");assertExactKeys(packageInput,["fqn","version"],"Extension Release package");const packageManifest=manifest.packageManifest===undefined?undefined:parsePackageManifest(manifest.packageManifest);if(packageManifest!==undefined&&(packageManifest.fqn!==packageInput.fqn||packageManifest.version!==packageInput.version)){throw new TypeError("Extension Release retained declarations do not match package identity")}const assets=manifest.assets.map(parseAsset);const contributions=manifest.contributions.map(parseContribution);const media=manifest.media===undefined?undefined:manifest.media.map(parseMedia);assertUniqueSorted(assets,({path})=>path,"Extension Release manifest assets");if(media!==undefined){assertUniqueSorted(media,({path})=>path,"Extension Release manifest media")}assertUniqueSorted(contributions,({fqn,host})=>`${host}\x00${fqn}`,"Extension Release manifest contributions");const assetByPath=new Map(assets.map((asset)=>[asset.path,asset]));for(const contribution of contributions){const asset=assetByPath.get(contribution.assetPath);if(asset===undefined||asset.digest!==contribution.digest||asset.host!==contribution.host||asset.size!==contribution.size){throw new TypeError(`Extension Release contribution '${contribution.fqn}' does not match its declared runtime asset`)}}return{apiVersion:ExtensionReleaseManifestVersion,assets,compatibility,contributions,...media===undefined?undefined:{media},package:{fqn:requireString(packageInput.fqn,"Extension Release package.fqn"),version:requireString(packageInput.version,"Extension Release package.version")},...packageManifest===undefined?undefined:{packageManifest},releaseDigest:requireDigest(manifest.releaseDigest,"Extension Release manifest.releaseDigest")}};var canonicalExtensionReleaseManifest=(manifest)=>canonicalJson(manifest);var archiveBlockSize=512;var isZeroBlock=(bytes)=>bytes.every((value)=>value===0);var decodeCanonicalTextField=(bytes,label)=>{const terminator=bytes.indexOf(0);const contentEnd=terminator===-1?bytes.byteLength:terminator;if(bytes.subarray(0,contentEnd).some((byte)=>byte>127)||terminator!==-1&&!isZeroBlock(bytes.subarray(terminator))){throw new TypeError(`Extension Release archive has non-canonical ${label}`)}return String.fromCodePoint(...bytes.subarray(0,contentEnd))};var parseCanonicalOctalField=(bytes,label)=>{const digits=bytes.subarray(0,bytes.byteLength-1);if(bytes.at(-1)!==0||digits.some((byte)=>byte<48||byte>55)){throw new TypeError(`Extension Release archive has non-canonical ${label}`)}return Number.parseInt(String.fromCodePoint(...digits),8)};var assertHeaderChecksum=(header)=>{const checksum=header.subarray(148,156);const checksumDigits=checksum.subarray(0,6);if(checksum[6]!==0||checksum[7]!==32||checksumDigits.some((byte)=>byte<48||byte>55)){throw new TypeError("Extension Release archive has non-canonical header checksum")}const declared=Number.parseInt(String.fromCodePoint(...checksumDigits),8);let actual=0;for(let index=0;index<header.byteLength;index+=1){actual+=index>=148&&index<156?32:header[index]??0}if(actual!==declared){throw new TypeError("Extension Release archive has invalid header checksum")}};var decodeCanonicalUstarHeader=(header)=>{assertHeaderChecksum(header);if(parseCanonicalOctalField(header.subarray(100,108),"file mode")!==420){throw new TypeError("Extension Release archive has non-canonical file mode")}if(parseCanonicalOctalField(header.subarray(108,116),"owner ID")!==0||parseCanonicalOctalField(header.subarray(116,124),"group ID")!==0||parseCanonicalOctalField(header.subarray(136,148),"modification time")!==0){throw new TypeError("Extension Release archive has non-canonical ownership or time")}if(decodeCanonicalTextField(header.subarray(257,263),"ustar magic")!=="ustar"){throw new TypeError("Extension Release archive is not ustar")}if(header[263]!==48||header[264]!==48){throw new TypeError("Extension Release archive has non-canonical ustar version")}if(header[156]!==48){throw new TypeError("Extension Release archive may contain files only")}if(!isZeroBlock(header.subarray(265,345))||!isZeroBlock(header.subarray(500,512))){throw new TypeError("Extension Release archive has non-canonical metadata")}return{name:decodeCanonicalTextField(header.subarray(0,100),"name"),prefix:decodeCanonicalTextField(header.subarray(345,500),"prefix"),size:parseCanonicalOctalField(header.subarray(124,136),"file size")}};var parseExtensionReleaseArchive=(archiveBytes)=>{const entries=[];const paths=new Set;let offset=0;let previousPath="";while(offset+archiveBlockSize<=archiveBytes.byteLength){const header=archiveBytes.subarray(offset,offset+archiveBlockSize);if(isZeroBlock(header)){const trailer=archiveBytes.subarray(offset+archiveBlockSize,offset+archiveBlockSize*2);if(trailer.byteLength!==archiveBlockSize||!isZeroBlock(trailer)){throw new TypeError("Extension Release archive has an invalid trailer")}if(offset+archiveBlockSize*2!==archiveBytes.byteLength){throw new TypeError("Extension Release archive has trailing bytes")}return entries}const{name,prefix,size}=decodeCanonicalUstarHeader(header);const path=prefix===""?name:`${prefix}/${name}`;assertReleaseArchiveEntryPath(path);if(paths.has(path)||compareUtf16CodeUnits(path,previousPath)<0){throw new TypeError("Extension Release archive paths must be unique and sorted")}const bodyOffset=offset+archiveBlockSize;const bodyEnd=bodyOffset+size;if(bodyEnd>archiveBytes.byteLength){throw new TypeError("Extension Release archive entry is truncated")}const paddedBodyEnd=bodyOffset+Math.ceil(size/archiveBlockSize)*archiveBlockSize;if(!isZeroBlock(archiveBytes.subarray(bodyEnd,paddedBodyEnd))){throw new TypeError("Extension Release archive has non-zero entry padding")}entries.push({bytes:archiveBytes.slice(bodyOffset,bodyEnd),path});paths.add(path);previousPath=path;offset=paddedBodyEnd}throw new TypeError("Extension Release archive has no canonical trailer")};var validateExtensionReleaseArchiveMetadata=(entries,manifest)=>{const metadata=entries.filter(({path})=>path===PackageManifestArchivePath);if(manifest.packageManifest===undefined){if(metadata.length!==0){throw new TypeError("Extension Release declaration metadata has no retained package manifest")}return entries}const expected=new TextEncoder().encode(canonicalJson(manifest.packageManifest));const actual=metadata[0]?.bytes;if(metadata.length!==1||actual===undefined||actual.byteLength!==expected.byteLength||!actual.every((byte,index)=>byte===expected[index])){throw new TypeError("Extension Release declaration metadata does not match its retained package manifest")}return entries.filter(({path})=>path!==PackageManifestArchivePath)};var retiredPrimitiveKinds=new Map(Object.entries({dataset_blueprint:"datasetBlueprint",dataset_parser:"datasetParser",dataset_table_template:"datasetTableTemplate",documents_connector:"documentsConnector",domain_template:"domainTemplate",event_listener:"eventListener",external_application:"externalApplication",external_dataset_provider:"externalDatasetProvider",field_transformer:"fieldTransformer",knowledge_connector:"knowledgeConnector",knowledge_connector_oauth:"knowledgeConnectorOauth",knowledge_entity_adapter:"knowledgeEntityAdapter",knowledge_entity_schema:"knowledgeEntitySchema",knowledge_policy:"knowledgePolicy",knowledge_relation_adapter:"knowledgeRelationAdapter",knowledge_relation_schema:"knowledgeRelationSchema",managed_dataset_provider:"managedDatasetProvider","notification-channel":"notificationChannel",organization_sso:"organizationSso",skill_template:"skillTemplate",studio_app:"studioApp",studio_component:"studioComponent",tool_collection:"toolCollection",tool_settings_options:"toolSettingsOptions",workflow_field:"workflowField",workflow_field_collection:"workflowFieldCollection",workflow_node:"workflowNode",workflow_node_collection:"workflowNodeCollection",workflow_template:"workflowTemplate"}));var retiredGroupNames=new Map(Object.entries({directory_person_in_team:"directory_person_in_group",directory_team:"directory_group",directory_team_parent:"directory_group_parent",organization_team:"organization_group",organization_team_hierarchy:"organization_group_hierarchy",organization_team_membership:"organization_group_membership"}));var util;(function(util){util.assertEqual=(_)=>{};function assertIs(_arg){}util.assertIs=assertIs;function assertNever(_x){throw new Error}util.assertNever=assertNever;util.arrayToEnum=(items)=>{const obj={};for(const item of items){obj[item]=item}return obj};util.getValidEnumValues=(obj)=>{const validKeys=util.objectKeys(obj).filter((k)=>typeof obj[obj[k]]!=="number");const filtered={};for(const k of validKeys){filtered[k]=obj[k]}return util.objectValues(filtered)};util.objectValues=(obj)=>{return util.objectKeys(obj).map(function(e){return obj[e]})};util.objectKeys=typeof Object.keys==="function"?(obj)=>Object.keys(obj):(object)=>{const keys=[];for(const key in object){if(Object.prototype.hasOwnProperty.call(object,key)){keys.push(key)}}return keys};util.find=(arr,checker)=>{for(const item of arr){if(checker(item))return item}return};util.isInteger=typeof Number.isInteger==="function"?(val)=>Number.isInteger(val):(val)=>typeof val==="number"&&Number.isFinite(val)&&Math.floor(val)===val;function joinValues(array,separator=" | "){return array.map((val)=>typeof val==="string"?`'${val}'`:val).join(separator)}util.joinValues=joinValues;util.jsonStringifyReplacer=(_,value)=>{if(typeof value==="bigint"){return value.toString()}return value}})(util||(util={}));var objectUtil;(function(objectUtil){objectUtil.mergeShapes=(first,second)=>{return{...first,...second}}})(objectUtil||(objectUtil={}));var ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]);var getParsedType=(data)=>{const t=typeof data;switch(t){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return Number.isNaN(data)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":if(Array.isArray(data)){return ZodParsedType.array}if(data===null){return ZodParsedType.null}if(data.then&&typeof data.then==="function"&&data.catch&&typeof data.catch==="function"){return ZodParsedType.promise}if(typeof Map!=="undefined"&&data instanceof Map){return ZodParsedType.map}if(typeof Set!=="undefined"&&data instanceof Set){return ZodParsedType.set}if(typeof Date!=="undefined"&&data instanceof Date){return ZodParsedType.date}return ZodParsedType.object;default:return ZodParsedType.unknown}};var ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ZodError extends Error{get errors(){return this.issues}constructor(issues){super();this.issues=[];this.addIssue=(sub)=>{this.issues=[...this.issues,sub]};this.addIssues=(subs=[])=>{this.issues=[...this.issues,...subs]};const actualProto=new.target.prototype;if(Object.setPrototypeOf){Object.setPrototypeOf(this,actualProto)}else{this.__proto__=actualProto}this.name="ZodError";this.issues=issues}format(_mapper){const mapper=_mapper||function(issue){return issue.message};const fieldErrors={_errors:[]};const processError=(error)=>{for(const issue of error.issues){if(issue.code==="invalid_union"){issue.unionErrors.map(processError)}else if(issue.code==="invalid_return_type"){processError(issue.returnTypeError)}else if(issue.code==="invalid_arguments"){processError(issue.argumentsError)}else if(issue.path.length===0){fieldErrors._errors.push(mapper(issue))}else{let curr=fieldErrors;let i=0;while(i<issue.path.length){const el=issue.path[i];const terminal=i===issue.path.length-1;if(!terminal){curr[el]=curr[el]||{_errors:[]}}else{curr[el]=curr[el]||{_errors:[]};curr[el]._errors.push(mapper(issue))}curr=curr[el];i++}}}};processError(this);return fieldErrors}static assert(value){if(!(value instanceof ZodError)){throw new Error(`Not a ZodError: ${value}`)}}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(mapper=(issue)=>issue.message){const fieldErrors={};const formErrors=[];for(const sub of this.issues){if(sub.path.length>0){const firstEl=sub.path[0];fieldErrors[firstEl]=fieldErrors[firstEl]||[];fieldErrors[firstEl].push(mapper(sub))}else{formErrors.push(mapper(sub))}}return{formErrors,fieldErrors}}get formErrors(){return this.flatten()}}ZodError.create=(issues)=>{const error=new ZodError(issues);return error};var errorMap=(issue,_ctx)=>{let message;switch(issue.code){case ZodIssueCode.invalid_type:if(issue.received===ZodParsedType.undefined){message="Required"}else{message=`Expected ${issue.expected}, received ${issue.received}`}break;case ZodIssueCode.invalid_literal:message=`Invalid literal value, expected ${JSON.stringify(issue.expected,util.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:message=`Unrecognized key(s) in object: ${util.joinValues(issue.keys,", ")}`;break;case ZodIssueCode.invalid_union:message=`Invalid input`;break;case ZodIssueCode.invalid_union_discriminator:message=`Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;break;case ZodIssueCode.invalid_enum_value:message=`Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;break;case ZodIssueCode.invalid_arguments:message=`Invalid function arguments`;break;case ZodIssueCode.invalid_return_type:message=`Invalid function return type`;break;case ZodIssueCode.invalid_date:message=`Invalid date`;break;case ZodIssueCode.invalid_string:if(typeof issue.validation==="object"){if("includes"in issue.validation){message=`Invalid input: must include "${issue.validation.includes}"`;if(typeof issue.validation.position==="number"){message=`${message} at one or more positions greater than or equal to ${issue.validation.position}`}}else if("startsWith"in issue.validation){message=`Invalid input: must start with "${issue.validation.startsWith}"`}else if("endsWith"in issue.validation){message=`Invalid input: must end with "${issue.validation.endsWith}"`}else{util.assertNever(issue.validation)}}else if(issue.validation!=="regex"){message=`Invalid ${issue.validation}`}else{message="Invalid"}break;case ZodIssueCode.too_small:if(issue.type==="array")message=`Array must contain ${issue.exact?"exactly":issue.inclusive?`at least`:`more than`} ${issue.minimum} element(s)`;else if(issue.type==="string")message=`String must contain ${issue.exact?"exactly":issue.inclusive?`at least`:`over`} ${issue.minimum} character(s)`;else if(issue.type==="number")message=`Number must be ${issue.exact?`exactly equal to `:issue.inclusive?`greater than or equal to `:`greater than `}${issue.minimum}`;else if(issue.type==="bigint")message=`Number must be ${issue.exact?`exactly equal to `:issue.inclusive?`greater than or equal to `:`greater than `}${issue.minimum}`;else if(issue.type==="date")message=`Date must be ${issue.exact?`exactly equal to `:issue.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(issue.minimum))}`;else message="Invalid input";break;case ZodIssueCode.too_big:if(issue.type==="array")message=`Array must contain ${issue.exact?`exactly`:issue.inclusive?`at most`:`less than`} ${issue.maximum} element(s)`;else if(issue.type==="string")message=`String must contain ${issue.exact?`exactly`:issue.inclusive?`at most`:`under`} ${issue.maximum} character(s)`;else if(issue.type==="number")message=`Number must be ${issue.exact?`exactly`:issue.inclusive?`less than or equal to`:`less than`} ${issue.maximum}`;else if(issue.type==="bigint")message=`BigInt must be ${issue.exact?`exactly`:issue.inclusive?`less than or equal to`:`less than`} ${issue.maximum}`;else if(issue.type==="date")message=`Date must be ${issue.exact?`exactly`:issue.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(issue.maximum))}`;else message="Invalid input";break;case ZodIssueCode.custom:message=`Invalid input`;break;case ZodIssueCode.invalid_intersection_types:message=`Intersection results could not be merged`;break;case ZodIssueCode.not_multiple_of:message=`Number must be a multiple of ${issue.multipleOf}`;break;case ZodIssueCode.not_finite:message="Number must be finite";break;default:message=_ctx.defaultError;util.assertNever(issue)}return{message}};var en_default=errorMap;var overrideErrorMap=en_default;function getErrorMap(){return overrideErrorMap}var makeIssue=(params)=>{const{data,path,errorMaps,issueData}=params;const fullPath=[...path,...issueData.path||[]];const fullIssue={...issueData,path:fullPath};if(issueData.message!==undefined){return{...issueData,path:fullPath,message:issueData.message}}let errorMessage="";const maps=errorMaps.filter((m)=>!!m).slice().reverse();for(const map of maps){errorMessage=map(fullIssue,{data,defaultError:errorMessage}).message}return{...issueData,path:fullPath,message:errorMessage}};function addIssueToContext(ctx,issueData){const overrideMap=getErrorMap();const issue=makeIssue({issueData,data:ctx.data,path:ctx.path,errorMaps:[ctx.common.contextualErrorMap,ctx.schemaErrorMap,overrideMap,overrideMap===en_default?undefined:en_default].filter((x)=>!!x)});ctx.common.issues.push(issue)}class ParseStatus{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(status,results){const arrayValue=[];for(const s of results){if(s.status==="aborted")return INVALID;if(s.status==="dirty")status.dirty();arrayValue.push(s.value)}return{status:status.value,value:arrayValue}}static async mergeObjectAsync(status,pairs){const syncPairs=[];for(const pair of pairs){const key=await pair.key;const value=await pair.value;syncPairs.push({key,value})}return ParseStatus.mergeObjectSync(status,syncPairs)}static mergeObjectSync(status,pairs){const finalObject={};for(const pair of pairs){const{key,value}=pair;if(key.status==="aborted")return INVALID;if(value.status==="aborted")return INVALID;if(key.status==="dirty")status.dirty();if(value.status==="dirty")status.dirty();if(key.value!=="__proto__"&&(typeof value.value!=="undefined"||pair.alwaysSet)){finalObject[key.value]=value.value}}return{status:status.value,value:finalObject}}}var INVALID=Object.freeze({status:"aborted"});var DIRTY=(value)=>({status:"dirty",value});var OK=(value)=>({status:"valid",value});var isAborted=(x)=>x.status==="aborted";var isDirty=(x)=>x.status==="dirty";var isValid=(x)=>x.status==="valid";var isAsync=(x)=>typeof Promise!=="undefined"&&x instanceof Promise;var errorUtil;(function(errorUtil){errorUtil.errToObj=(message)=>typeof message==="string"?{message}:message||{};errorUtil.toString=(message)=>typeof message==="string"?message:message?.message})(errorUtil||(errorUtil={}));class ParseInputLazyPath{constructor(parent,value,path,key){this._cachedPath=[];this.parent=parent;this.data=value;this._path=path;this._key=key}get path(){if(!this._cachedPath.length){if(Array.isArray(this._key)){this._cachedPath.push(...this._path,...this._key)}else{this._cachedPath.push(...this._path,this._key)}}return this._cachedPath}}var handleResult=(ctx,result)=>{if(isValid(result)){return{success:true,data:result.value}}else{if(!ctx.common.issues.length){throw new Error("Validation failed but no issues detected.")}return{success:false,get error(){if(this._error)return this._error;const error=new ZodError(ctx.common.issues);this._error=error;return this._error}}}};function processCreateParams(params){if(!params)return{};const{errorMap,invalid_type_error,required_error,description}=params;if(errorMap&&(invalid_type_error||required_error)){throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`)}if(errorMap)return{errorMap,description};const customMap=(iss,ctx)=>{const{message}=params;if(iss.code==="invalid_enum_value"){return{message:message??ctx.defaultError}}if(typeof ctx.data==="undefined"){return{message:message??required_error??ctx.defaultError}}if(iss.code!=="invalid_type")return{message:ctx.defaultError};return{message:message??invalid_type_error??ctx.defaultError}};return{errorMap:customMap,description}}class ZodType{get description(){return this._def.description}_getType(input){return getParsedType(input.data)}_getOrReturnCtx(input,ctx){return ctx||{common:input.parent.common,data:input.data,parsedType:getParsedType(input.data),schemaErrorMap:this._def.errorMap,path:input.path,parent:input.parent}}_processInputParams(input){return{status:new ParseStatus,ctx:{common:input.parent.common,data:input.data,parsedType:getParsedType(input.data),schemaErrorMap:this._def.errorMap,path:input.path,parent:input.parent}}}_parseSync(input){const result=this._parse(input);if(isAsync(result)){throw new Error("Synchronous parse encountered promise.")}return result}_parseAsync(input){const result=this._parse(input);return Promise.resolve(result)}parse(data,params){const result=this.safeParse(data,params);if(result.success)return result.data;throw result.error}safeParse(data,params){const ctx={common:{issues:[],async:params?.async??false,contextualErrorMap:params?.errorMap},path:params?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data,parsedType:getParsedType(data)};const result=this._parseSync({data,path:ctx.path,parent:ctx});return handleResult(ctx,result)}"~validate"(data){const ctx={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data,parsedType:getParsedType(data)};if(!this["~standard"].async){try{const result=this._parseSync({data,path:[],parent:ctx});return isValid(result)?{value:result.value}:{issues:ctx.common.issues}}catch(err){if(err?.message?.toLowerCase()?.includes("encountered")){this["~standard"].async=true}ctx.common={issues:[],async:true}}}return this._parseAsync({data,path:[],parent:ctx}).then((result)=>isValid(result)?{value:result.value}:{issues:ctx.common.issues})}async parseAsync(data,params){const result=await this.safeParseAsync(data,params);if(result.success)return result.data;throw result.error}async safeParseAsync(data,params){const ctx={common:{issues:[],contextualErrorMap:params?.errorMap,async:true},path:params?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data,parsedType:getParsedType(data)};const maybeAsyncResult=this._parse({data,path:ctx.path,parent:ctx});const result=await(isAsync(maybeAsyncResult)?maybeAsyncResult:Promise.resolve(maybeAsyncResult));return handleResult(ctx,result)}refine(check,message){const getIssueProperties=(val)=>{if(typeof message==="string"||typeof message==="undefined"){return{message}}else if(typeof message==="function"){return message(val)}else{return message}};return this._refinement((val,ctx)=>{const result=check(val);const setError=()=>ctx.addIssue({code:ZodIssueCode.custom,...getIssueProperties(val)});if(typeof Promise!=="undefined"&&result instanceof Promise){return result.then((data)=>{if(!data){setError();return false}else{return true}})}if(!result){setError();return false}else{return true}})}refinement(check,refinementData){return this._refinement((val,ctx)=>{if(!check(val)){ctx.addIssue(typeof refinementData==="function"?refinementData(val,ctx):refinementData);return false}else{return true}})}_refinement(refinement){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement}})}superRefine(refinement){return this._refinement(refinement)}constructor(def){this.spa=this.safeParseAsync;this._def=def;this.parse=this.parse.bind(this);this.safeParse=this.safeParse.bind(this);this.parseAsync=this.parseAsync.bind(this);this.safeParseAsync=this.safeParseAsync.bind(this);this.spa=this.spa.bind(this);this.refine=this.refine.bind(this);this.refinement=this.refinement.bind(this);this.superRefine=this.superRefine.bind(this);this.optional=this.optional.bind(this);this.nullable=this.nullable.bind(this);this.nullish=this.nullish.bind(this);this.array=this.array.bind(this);this.promise=this.promise.bind(this);this.or=this.or.bind(this);this.and=this.and.bind(this);this.transform=this.transform.bind(this);this.brand=this.brand.bind(this);this.default=this.default.bind(this);this.catch=this.catch.bind(this);this.describe=this.describe.bind(this);this.pipe=this.pipe.bind(this);this.readonly=this.readonly.bind(this);this.isNullable=this.isNullable.bind(this);this.isOptional=this.isOptional.bind(this);this["~standard"]={version:1,vendor:"zod",validate:(data)=>this["~validate"](data)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(option){return ZodUnion.create([this,option],this._def)}and(incoming){return ZodIntersection.create(this,incoming,this._def)}transform(transform){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform}})}default(def){const defaultValueFunc=typeof def==="function"?def:()=>def;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:defaultValueFunc,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(def){const catchValueFunc=typeof def==="function"?def:()=>def;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:catchValueFunc,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(description){const This=this.constructor;return new This({...this._def,description})}pipe(target){return ZodPipeline.create(this,target)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(undefined).success}isNullable(){return this.safeParse(null).success}}var cuidRegex=/^c[^\s-]{8,}$/i;var cuid2Regex=/^[0-9a-z]+$/;var ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i;var uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;var nanoidRegex=/^[a-z0-9_-]{21}$/i;var jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;var durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;var emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;var _emojiRegex=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;var emojiRegex;var ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;var ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;var ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;var ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;var base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;var base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;var dateRegexSource=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;var dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(args){let secondsRegexSource=`[0-5]\\d`;if(args.precision){secondsRegexSource=`${secondsRegexSource}\\.\\d{${args.precision}}`}else if(args.precision==null){secondsRegexSource=`${secondsRegexSource}(\\.\\d+)?`}const secondsQuantifier=args.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`}function timeRegex(args){return new RegExp(`^${timeRegexSource(args)}$`)}function datetimeRegex(args){let regex=`${dateRegexSource}T${timeRegexSource(args)}`;const opts=[];opts.push(args.local?`Z?`:`Z`);if(args.offset)opts.push(`([+-]\\d{2}:?\\d{2})`);regex=`${regex}(${opts.join("|")})`;return new RegExp(`^${regex}$`)}function isValidIP(ip,version){if((version==="v4"||!version)&&ipv4Regex.test(ip)){return true}if((version==="v6"||!version)&&ipv6Regex.test(ip)){return true}return false}function isValidJWT(jwt,alg){if(!jwtRegex.test(jwt))return false;try{const[header]=jwt.split(".");if(!header)return false;const base64=header.replace(/-/g,"+").replace(/_/g,"/").padEnd(header.length+(4-header.length%4)%4,"=");const decoded=JSON.parse(atob(base64));if(typeof decoded!=="object"||decoded===null)return false;if("typ"in decoded&&decoded?.typ!=="JWT")return false;if(!decoded.alg)return false;if(alg&&decoded.alg!==alg)return false;return true}catch{return false}}function isValidCidr(ip,version){if((version==="v4"||!version)&&ipv4CidrRegex.test(ip)){return true}if((version==="v6"||!version)&&ipv6CidrRegex.test(ip)){return true}return false}class ZodString extends ZodType{_parse(input){if(this._def.coerce){input.data=String(input.data)}const parsedType=this._getType(input);if(parsedType!==ZodParsedType.string){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:ctx.parsedType});return INVALID}const status=new ParseStatus;let ctx=undefined;for(const check of this._def.checks){if(check.kind==="min"){if(input.data.length<check.value){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check.value,type:"string",inclusive:true,exact:false,message:check.message});status.dirty()}}else if(check.kind==="max"){if(input.data.length>check.value){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check.value,type:"string",inclusive:true,exact:false,message:check.message});status.dirty()}}else if(check.kind==="length"){const tooBig=input.data.length>check.value;const tooSmall=input.data.length<check.value;if(tooBig||tooSmall){ctx=this._getOrReturnCtx(input,ctx);if(tooBig){addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check.value,type:"string",inclusive:true,exact:true,message:check.message})}else if(tooSmall){addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check.value,type:"string",inclusive:true,exact:true,message:check.message})}status.dirty()}}else if(check.kind==="email"){if(!emailRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"email",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="emoji"){if(!emojiRegex){emojiRegex=new RegExp(_emojiRegex,"u")}if(!emojiRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"emoji",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="uuid"){if(!uuidRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"uuid",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="nanoid"){if(!nanoidRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="cuid"){if(!cuidRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"cuid",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="cuid2"){if(!cuid2Regex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="ulid"){if(!ulidRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"ulid",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="url"){try{new URL(input.data)}catch{ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"url",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="regex"){check.regex.lastIndex=0;const testResult=check.regex.test(input.data);if(!testResult){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"regex",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="trim"){input.data=input.data.trim()}else if(check.kind==="includes"){if(!input.data.includes(check.value,check.position)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{includes:check.value,position:check.position},message:check.message});status.dirty()}}else if(check.kind==="toLowerCase"){input.data=input.data.toLowerCase()}else if(check.kind==="toUpperCase"){input.data=input.data.toUpperCase()}else if(check.kind==="startsWith"){if(!input.data.startsWith(check.value)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{startsWith:check.value},message:check.message});status.dirty()}}else if(check.kind==="endsWith"){if(!input.data.endsWith(check.value)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{endsWith:check.value},message:check.message});status.dirty()}}else if(check.kind==="datetime"){const regex=datetimeRegex(check);if(!regex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"datetime",message:check.message});status.dirty()}}else if(check.kind==="date"){const regex=dateRegex;if(!regex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"date",message:check.message});status.dirty()}}else if(check.kind==="time"){const regex=timeRegex(check);if(!regex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"time",message:check.message});status.dirty()}}else if(check.kind==="duration"){if(!durationRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"duration",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="ip"){if(!isValidIP(input.data,check.version)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"ip",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="jwt"){if(!isValidJWT(input.data,check.alg)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"jwt",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="cidr"){if(!isValidCidr(input.data,check.version)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"cidr",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="base64"){if(!base64Regex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"base64",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else if(check.kind==="base64url"){if(!base64urlRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"base64url",code:ZodIssueCode.invalid_string,message:check.message});status.dirty()}}else{util.assertNever(check)}}return{status:status.value,value:input.data}}_regex(regex,validation,message){return this.refinement((data)=>regex.test(data),{validation,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(message)})}_addCheck(check){return new ZodString({...this._def,checks:[...this._def.checks,check]})}email(message){return this._addCheck({kind:"email",...errorUtil.errToObj(message)})}url(message){return this._addCheck({kind:"url",...errorUtil.errToObj(message)})}emoji(message){return this._addCheck({kind:"emoji",...errorUtil.errToObj(message)})}uuid(message){return this._addCheck({kind:"uuid",...errorUtil.errToObj(message)})}nanoid(message){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(message)})}cuid(message){return this._addCheck({kind:"cuid",...errorUtil.errToObj(message)})}cuid2(message){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(message)})}ulid(message){return this._addCheck({kind:"ulid",...errorUtil.errToObj(message)})}base64(message){return this._addCheck({kind:"base64",...errorUtil.errToObj(message)})}base64url(message){return this._addCheck({kind:"base64url",...errorUtil.errToObj(message)})}jwt(options){return this._addCheck({kind:"jwt",...errorUtil.errToObj(options)})}ip(options){return this._addCheck({kind:"ip",...errorUtil.errToObj(options)})}cidr(options){return this._addCheck({kind:"cidr",...errorUtil.errToObj(options)})}datetime(options){if(typeof options==="string"){return this._addCheck({kind:"datetime",precision:null,offset:false,local:false,message:options})}return this._addCheck({kind:"datetime",precision:typeof options?.precision==="undefined"?null:options?.precision,offset:options?.offset??false,local:options?.local??false,...errorUtil.errToObj(options?.message)})}date(message){return this._addCheck({kind:"date",message})}time(options){if(typeof options==="string"){return this._addCheck({kind:"time",precision:null,message:options})}return this._addCheck({kind:"time",precision:typeof options?.precision==="undefined"?null:options?.precision,...errorUtil.errToObj(options?.message)})}duration(message){return this._addCheck({kind:"duration",...errorUtil.errToObj(message)})}regex(regex,message){return this._addCheck({kind:"regex",regex,...errorUtil.errToObj(message)})}includes(value,options){return this._addCheck({kind:"includes",value,position:options?.position,...errorUtil.errToObj(options?.message)})}startsWith(value,message){return this._addCheck({kind:"startsWith",value,...errorUtil.errToObj(message)})}endsWith(value,message){return this._addCheck({kind:"endsWith",value,...errorUtil.errToObj(message)})}min(minLength,message){return this._addCheck({kind:"min",value:minLength,...errorUtil.errToObj(message)})}max(maxLength,message){return this._addCheck({kind:"max",value:maxLength,...errorUtil.errToObj(message)})}length(len,message){return this._addCheck({kind:"length",value:len,...errorUtil.errToObj(message)})}nonempty(message){return this.min(1,errorUtil.errToObj(message))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((ch)=>ch.kind==="datetime")}get isDate(){return!!this._def.checks.find((ch)=>ch.kind==="date")}get isTime(){return!!this._def.checks.find((ch)=>ch.kind==="time")}get isDuration(){return!!this._def.checks.find((ch)=>ch.kind==="duration")}get isEmail(){return!!this._def.checks.find((ch)=>ch.kind==="email")}get isURL(){return!!this._def.checks.find((ch)=>ch.kind==="url")}get isEmoji(){return!!this._def.checks.find((ch)=>ch.kind==="emoji")}get isUUID(){return!!this._def.checks.find((ch)=>ch.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((ch)=>ch.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((ch)=>ch.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((ch)=>ch.kind==="cuid2")}get isULID(){return!!this._def.checks.find((ch)=>ch.kind==="ulid")}get isIP(){return!!this._def.checks.find((ch)=>ch.kind==="ip")}get isCIDR(){return!!this._def.checks.find((ch)=>ch.kind==="cidr")}get isBase64(){return!!this._def.checks.find((ch)=>ch.kind==="base64")}get isBase64url(){return!!this._def.checks.find((ch)=>ch.kind==="base64url")}get minLength(){let min=null;for(const ch of this._def.checks){if(ch.kind==="min"){if(min===null||ch.value>min)min=ch.value}}return min}get maxLength(){let max=null;for(const ch of this._def.checks){if(ch.kind==="max"){if(max===null||ch.value<max)max=ch.value}}return max}}ZodString.create=(params)=>{return new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:params?.coerce??false,...processCreateParams(params)})};function floatSafeRemainder(val,step){const valDecCount=(val.toString().split(".")[1]||"").length;const stepDecCount=(step.toString().split(".")[1]||"").length;const decCount=valDecCount>stepDecCount?valDecCount:stepDecCount;const valInt=Number.parseInt(val.toFixed(decCount).replace(".",""));const stepInt=Number.parseInt(step.toFixed(decCount).replace(".",""));return valInt%stepInt/10**decCount}class ZodNumber extends ZodType{constructor(){super(...arguments);this.min=this.gte;this.max=this.lte;this.step=this.multipleOf}_parse(input){if(this._def.coerce){input.data=Number(input.data)}const parsedType=this._getType(input);if(parsedType!==ZodParsedType.number){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:ctx.parsedType});return INVALID}let ctx=undefined;const status=new ParseStatus;for(const check of this._def.checks){if(check.kind==="int"){if(!util.isInteger(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:check.message});status.dirty()}}else if(check.kind==="min"){const tooSmall=check.inclusive?input.data<check.value:input.data<=check.value;if(tooSmall){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check.value,type:"number",inclusive:check.inclusive,exact:false,message:check.message});status.dirty()}}else if(check.kind==="max"){const tooBig=check.inclusive?input.data>check.value:input.data>=check.value;if(tooBig){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check.value,type:"number",inclusive:check.inclusive,exact:false,message:check.message});status.dirty()}}else if(check.kind==="multipleOf"){if(floatSafeRemainder(input.data,check.value)!==0){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.not_multiple_of,multipleOf:check.value,message:check.message});status.dirty()}}else if(check.kind==="finite"){if(!Number.isFinite(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.not_finite,message:check.message});status.dirty()}}else{util.assertNever(check)}}return{status:status.value,value:input.data}}gte(value,message){return this.setLimit("min",value,true,errorUtil.toString(message))}gt(value,message){return this.setLimit("min",value,false,errorUtil.toString(message))}lte(value,message){return this.setLimit("max",value,true,errorUtil.toString(message))}lt(value,message){return this.setLimit("max",value,false,errorUtil.toString(message))}setLimit(kind,value,inclusive,message){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind,value,inclusive,message:errorUtil.toString(message)}]})}_addCheck(check){return new ZodNumber({...this._def,checks:[...this._def.checks,check]})}int(message){return this._addCheck({kind:"int",message:errorUtil.toString(message)})}positive(message){return this._addCheck({kind:"min",value:0,inclusive:false,message:errorUtil.toString(message)})}negative(message){return this._addCheck({kind:"max",value:0,inclusive:false,message:errorUtil.toString(message)})}nonpositive(message){return this._addCheck({kind:"max",value:0,inclusive:true,message:errorUtil.toString(message)})}nonnegative(message){return this._addCheck({kind:"min",value:0,inclusive:true,message:errorUtil.toString(message)})}multipleOf(value,message){return this._addCheck({kind:"multipleOf",value,message:errorUtil.toString(message)})}finite(message){return this._addCheck({kind:"finite",message:errorUtil.toString(message)})}safe(message){return this._addCheck({kind:"min",inclusive:true,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(message)})._addCheck({kind:"max",inclusive:true,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(message)})}get minValue(){let min=null;for(const ch of this._def.checks){if(ch.kind==="min"){if(min===null||ch.value>min)min=ch.value}}return min}get maxValue(){let max=null;for(const ch of this._def.checks){if(ch.kind==="max"){if(max===null||ch.value<max)max=ch.value}}return max}get isInt(){return!!this._def.checks.find((ch)=>ch.kind==="int"||ch.kind==="multipleOf"&&util.isInteger(ch.value))}get isFinite(){let max=null;let min=null;for(const ch of this._def.checks){if(ch.kind==="finite"||ch.kind==="int"||ch.kind==="multipleOf"){return true}else if(ch.kind==="min"){if(min===null||ch.value>min)min=ch.value}else if(ch.kind==="max"){if(max===null||ch.value<max)max=ch.value}}return Number.isFinite(min)&&Number.isFinite(max)}}ZodNumber.create=(params)=>{return new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:params?.coerce||false,...processCreateParams(params)})};class ZodBigInt extends ZodType{constructor(){super(...arguments);this.min=this.gte;this.max=this.lte}_parse(input){if(this._def.coerce){try{input.data=BigInt(input.data)}catch{return this._getInvalidInput(input)}}const parsedType=this._getType(input);if(parsedType!==ZodParsedType.bigint){return this._getInvalidInput(input)}let ctx=undefined;const status=new ParseStatus;for(const check of this._def.checks){if(check.kind==="min"){const tooSmall=check.inclusive?input.data<check.value:input.data<=check.value;if(tooSmall){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_small,type:"bigint",minimum:check.value,inclusive:check.inclusive,message:check.message});status.dirty()}}else if(check.kind==="max"){const tooBig=check.inclusive?input.data>check.value:input.data>=check.value;if(tooBig){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_big,type:"bigint",maximum:check.value,inclusive:check.inclusive,message:check.message});status.dirty()}}else if(check.kind==="multipleOf"){if(input.data%check.value!==BigInt(0)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.not_multiple_of,multipleOf:check.value,message:check.message});status.dirty()}}else{util.assertNever(check)}}return{status:status.value,value:input.data}}_getInvalidInput(input){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:ctx.parsedType});return INVALID}gte(value,message){return this.setLimit("min",value,true,errorUtil.toString(message))}gt(value,message){return this.setLimit("min",value,false,errorUtil.toString(message))}lte(value,message){return this.setLimit("max",value,true,errorUtil.toString(message))}lt(value,message){return this.setLimit("max",value,false,errorUtil.toString(message))}setLimit(kind,value,inclusive,message){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind,value,inclusive,message:errorUtil.toString(message)}]})}_addCheck(check){return new ZodBigInt({...this._def,checks:[...this._def.checks,check]})}positive(message){return this._addCheck({kind:"min",value:BigInt(0),inclusive:false,message:errorUtil.toString(message)})}negative(message){return this._addCheck({kind:"max",value:BigInt(0),inclusive:false,message:errorUtil.toString(message)})}nonpositive(message){return this._addCheck({kind:"max",value:BigInt(0),inclusive:true,message:errorUtil.toString(message)})}nonnegative(message){return this._addCheck({kind:"min",value:BigInt(0),inclusive:true,message:errorUtil.toString(message)})}multipleOf(value,message){return this._addCheck({kind:"multipleOf",value,message:errorUtil.toString(message)})}get minValue(){let min=null;for(const ch of this._def.checks){if(ch.kind==="min"){if(min===null||ch.value>min)min=ch.value}}return min}get maxValue(){let max=null;for(const ch of this._def.checks){if(ch.kind==="max"){if(max===null||ch.value<max)max=ch.value}}return max}}ZodBigInt.create=(params)=>{return new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:params?.coerce??false,...processCreateParams(params)})};class ZodBoolean extends ZodType{_parse(input){if(this._def.coerce){input.data=Boolean(input.data)}const parsedType=this._getType(input);if(parsedType!==ZodParsedType.boolean){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:ctx.parsedType});return INVALID}return OK(input.data)}}ZodBoolean.create=(params)=>{return new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:params?.coerce||false,...processCreateParams(params)})};class ZodDate extends ZodType{_parse(input){if(this._def.coerce){input.data=new Date(input.data)}const parsedType=this._getType(input);if(parsedType!==ZodParsedType.date){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:ctx.parsedType});return INVALID}if(Number.isNaN(input.data.getTime())){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{code:ZodIssueCode.invalid_date});return INVALID}const status=new ParseStatus;let ctx=undefined;for(const check of this._def.checks){if(check.kind==="min"){if(input.data.getTime()<check.value){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_small,message:check.message,inclusive:true,exact:false,minimum:check.value,type:"date"});status.dirty()}}else if(check.kind==="max"){if(input.data.getTime()>check.value){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_big,message:check.message,inclusive:true,exact:false,maximum:check.value,type:"date"});status.dirty()}}else{util.assertNever(check)}}return{status:status.value,value:new Date(input.data.getTime())}}_addCheck(check){return new ZodDate({...this._def,checks:[...this._def.checks,check]})}min(minDate,message){return this._addCheck({kind:"min",value:minDate.getTime(),message:errorUtil.toString(message)})}max(maxDate,message){return this._addCheck({kind:"max",value:maxDate.getTime(),message:errorUtil.toString(message)})}get minDate(){let min=null;for(const ch of this._def.checks){if(ch.kind==="min"){if(min===null||ch.value>min)min=ch.value}}return min!=null?new Date(min):null}get maxDate(){let max=null;for(const ch of this._def.checks){if(ch.kind==="max"){if(max===null||ch.value<max)max=ch.value}}return max!=null?new Date(max):null}}ZodDate.create=(params)=>{return new ZodDate({checks:[],coerce:params?.coerce||false,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(params)})};class ZodSymbol extends ZodType{_parse(input){const parsedType=this._getType(input);if(parsedType!==ZodParsedType.symbol){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:ctx.parsedType});return INVALID}return OK(input.data)}}ZodSymbol.create=(params)=>{return new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(params)})};class ZodUndefined extends ZodType{_parse(input){const parsedType=this._getType(input);if(parsedType!==ZodParsedType.undefined){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:ctx.parsedType});return INVALID}return OK(input.data)}}ZodUndefined.create=(params)=>{return new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(params)})};class ZodNull extends ZodType{_parse(input){const parsedType=this._getType(input);if(parsedType!==ZodParsedType.null){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:ctx.parsedType});return INVALID}return OK(input.data)}}ZodNull.create=(params)=>{return new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(params)})};class ZodAny extends ZodType{constructor(){super(...arguments);this._any=true}_parse(input){return OK(input.data)}}ZodAny.create=(params)=>{return new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(params)})};class ZodUnknown extends ZodType{constructor(){super(...arguments);this._unknown=true}_parse(input){return OK(input.data)}}ZodUnknown.create=(params)=>{return new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(params)})};class ZodNever extends ZodType{_parse(input){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:ctx.parsedType});return INVALID}}ZodNever.create=(params)=>{return new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(params)})};class ZodVoid extends ZodType{_parse(input){const parsedType=this._getType(input);if(parsedType!==ZodParsedType.undefined){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:ctx.parsedType});return INVALID}return OK(input.data)}}ZodVoid.create=(params)=>{return new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(params)})};class ZodArray extends ZodType{_parse(input){const{ctx,status}=this._processInputParams(input);const def=this._def;if(ctx.parsedType!==ZodParsedType.array){addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:ctx.parsedType});return INVALID}if(def.exactLength!==null){const tooBig=ctx.data.length>def.exactLength.value;const tooSmall=ctx.data.length<def.exactLength.value;if(tooBig||tooSmall){addIssueToContext(ctx,{code:tooBig?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:tooSmall?def.exactLength.value:undefined,maximum:tooBig?def.exactLength.value:undefined,type:"array",inclusive:true,exact:true,message:def.exactLength.message});status.dirty()}}if(def.minLength!==null){if(ctx.data.length<def.minLength.value){addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:def.minLength.value,type:"array",inclusive:true,exact:false,message:def.minLength.message});status.dirty()}}if(def.maxLength!==null){if(ctx.data.length>def.maxLength.value){addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:def.maxLength.value,type:"array",inclusive:true,exact:false,message:def.maxLength.message});status.dirty()}}if(ctx.common.async){return Promise.all([...ctx.data].map((item,i)=>{return def.type._parseAsync(new ParseInputLazyPath(ctx,item,ctx.path,i))})).then((result)=>{return ParseStatus.mergeArray(status,result)})}const result=[...ctx.data].map((item,i)=>{return def.type._parseSync(new ParseInputLazyPath(ctx,item,ctx.path,i))});return ParseStatus.mergeArray(status,result)}get element(){return this._def.type}min(minLength,message){return new ZodArray({...this._def,minLength:{value:minLength,message:errorUtil.toString(message)}})}max(maxLength,message){return new ZodArray({...this._def,maxLength:{value:maxLength,message:errorUtil.toString(message)}})}length(len,message){return new ZodArray({...this._def,exactLength:{value:len,message:errorUtil.toString(message)}})}nonempty(message){return this.min(1,message)}}ZodArray.create=(schema,params)=>{return new ZodArray({type:schema,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(params)})};function deepPartialify(schema){if(schema instanceof ZodObject){const newShape={};for(const key in schema.shape){const fieldSchema=schema.shape[key];newShape[key]=ZodOptional.create(deepPartialify(fieldSchema))}return new ZodObject({...schema._def,shape:()=>newShape})}else if(schema instanceof ZodArray){return new ZodArray({...schema._def,type:deepPartialify(schema.element)})}else if(schema instanceof ZodOptional){return ZodOptional.create(deepPartialify(schema.unwrap()))}else if(schema instanceof ZodNullable){return ZodNullable.create(deepPartialify(schema.unwrap()))}else if(schema instanceof ZodTuple){return ZodTuple.create(schema.items.map((item)=>deepPartialify(item)))}else{return schema}}class ZodObject extends ZodType{constructor(){super(...arguments);this._cached=null;this.nonstrict=this.passthrough;this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const shape=this._def.shape();const keys=util.objectKeys(shape);this._cached={shape,keys};return this._cached}_parse(input){const parsedType=this._getType(input);if(parsedType!==ZodParsedType.object){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ctx.parsedType});return INVALID}const{status,ctx}=this._processInputParams(input);const{shape,keys:shapeKeys}=this._getCached();const extraKeys=[];if(!(this._def.catchall instanceof ZodNever&&this._def.unknownKeys==="strip")){for(const key in ctx.data){if(!shapeKeys.includes(key)){extraKeys.push(key)}}}const pairs=[];for(const key of shapeKeys){const keyValidator=shape[key];const value=ctx.data[key];pairs.push({key:{status:"valid",value:key},value:keyValidator._parse(new ParseInputLazyPath(ctx,value,ctx.path,key)),alwaysSet:key in ctx.data})}if(this._def.catchall instanceof ZodNever){const unknownKeys=this._def.unknownKeys;if(unknownKeys==="passthrough"){for(const key of extraKeys){pairs.push({key:{status:"valid",value:key},value:{status:"valid",value:ctx.data[key]}})}}else if(unknownKeys==="strict"){if(extraKeys.length>0){addIssueToContext(ctx,{code:ZodIssueCode.unrecognized_keys,keys:extraKeys});status.dirty()}}else if(unknownKeys==="strip"){}else{throw new Error(`Internal ZodObject error: invalid unknownKeys value.`)}}else{const catchall=this._def.catchall;for(const key of extraKeys){const value=ctx.data[key];pairs.push({key:{status:"valid",value:key},value:catchall._parse(new ParseInputLazyPath(ctx,value,ctx.path,key)),alwaysSet:key in ctx.data})}}if(ctx.common.async){return Promise.resolve().then(async()=>{const syncPairs=[];for(const pair of pairs){const key=await pair.key;const value=await pair.value;syncPairs.push({key,value,alwaysSet:pair.alwaysSet})}return syncPairs}).then((syncPairs)=>{return ParseStatus.mergeObjectSync(status,syncPairs)})}else{return ParseStatus.mergeObjectSync(status,pairs)}}get shape(){return this._def.shape()}strict(message){errorUtil.errToObj;return new ZodObject({...this._def,unknownKeys:"strict",...message!==undefined?{errorMap:(issue,ctx)=>{const defaultError=this._def.errorMap?.(issue,ctx).message??ctx.defaultError;if(issue.code==="unrecognized_keys")return{message:errorUtil.errToObj(message).message??defaultError};return{message:defaultError}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(augmentation){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...augmentation})})}merge(merging){const merged=new ZodObject({unknownKeys:merging._def.unknownKeys,catchall:merging._def.catchall,shape:()=>({...this._def.shape(),...merging._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject});return merged}setKey(key,schema){return this.augment({[key]:schema})}catchall(index){return new ZodObject({...this._def,catchall:index})}pick(mask){const shape={};for(const key of util.objectKeys(mask)){if(mask[key]&&this.shape[key]){shape[key]=this.shape[key]}}return new ZodObject({...this._def,shape:()=>shape})}omit(mask){const shape={};for(const key of util.objectKeys(this.shape)){if(!mask[key]){shape[key]=this.shape[key]}}return new ZodObject({...this._def,shape:()=>shape})}deepPartial(){return deepPartialify(this)}partial(mask){const newShape={};for(const key of util.objectKeys(this.shape)){const fieldSchema=this.shape[key];if(mask&&!mask[key]){newShape[key]=fieldSchema}else{newShape[key]=fieldSchema.optional()}}return new ZodObject({...this._def,shape:()=>newShape})}required(mask){const newShape={};for(const key of util.objectKeys(this.shape)){if(mask&&!mask[key]){newShape[key]=this.shape[key]}else{const fieldSchema=this.shape[key];let newField=fieldSchema;while(newField instanceof ZodOptional){newField=newField._def.innerType}newShape[key]=newField}}return new ZodObject({...this._def,shape:()=>newShape})}keyof(){return createZodEnum(util.objectKeys(this.shape))}}ZodObject.create=(shape,params)=>{return new ZodObject({shape:()=>shape,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(params)})};ZodObject.strictCreate=(shape,params)=>{return new ZodObject({shape:()=>shape,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(params)})};ZodObject.lazycreate=(shape,params)=>{return new ZodObject({shape,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(params)})};class ZodUnion extends ZodType{_parse(input){const{ctx}=this._processInputParams(input);const options=this._def.options;function handleResults(results){for(const result of results){if(result.result.status==="valid"){return result.result}}for(const result of results){if(result.result.status==="dirty"){ctx.common.issues.push(...result.ctx.common.issues);return result.result}}const unionErrors=results.map((result)=>new ZodError(result.ctx.common.issues));addIssueToContext(ctx,{code:ZodIssueCode.invalid_union,unionErrors});return INVALID}if(ctx.common.async){return Promise.all(options.map(async(option)=>{const childCtx={...ctx,common:{...ctx.common,issues:[]},parent:null};return{result:await option._parseAsync({data:ctx.data,path:ctx.path,parent:childCtx}),ctx:childCtx}})).then(handleResults)}else{let dirty=undefined;const issues=[];for(const option of options){const childCtx={...ctx,common:{...ctx.common,issues:[]},parent:null};const result=option._parseSync({data:ctx.data,path:ctx.path,parent:childCtx});if(result.status==="valid"){return result}else if(result.status==="dirty"&&!dirty){dirty={result,ctx:childCtx}}if(childCtx.common.issues.length){issues.push(childCtx.common.issues)}}if(dirty){ctx.common.issues.push(...dirty.ctx.common.issues);return dirty.result}const unionErrors=issues.map((issues)=>new ZodError(issues));addIssueToContext(ctx,{code:ZodIssueCode.invalid_union,unionErrors});return INVALID}}get options(){return this._def.options}}ZodUnion.create=(types,params)=>{return new ZodUnion({options:types,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(params)})};var getDiscriminator=(type)=>{if(type instanceof ZodLazy){return getDiscriminator(type.schema)}else if(type instanceof ZodEffects){return getDiscriminator(type.innerType())}else if(type instanceof ZodLiteral){return[type.value]}else if(type instanceof ZodEnum){return type.options}else if(type instanceof ZodNativeEnum){return util.objectValues(type.enum)}else if(type instanceof ZodDefault){return getDiscriminator(type._def.innerType)}else if(type instanceof ZodUndefined){return[undefined]}else if(type instanceof ZodNull){return[null]}else if(type instanceof ZodOptional){return[undefined,...getDiscriminator(type.unwrap())]}else if(type instanceof ZodNullable){return[null,...getDiscriminator(type.unwrap())]}else if(type instanceof ZodBranded){return getDiscriminator(type.unwrap())}else if(type instanceof ZodReadonly){return getDiscriminator(type.unwrap())}else if(type instanceof ZodCatch){return getDiscriminator(type._def.innerType)}else{return[]}};class ZodDiscriminatedUnion extends ZodType{_parse(input){const{ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.object){addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ctx.parsedType});return INVALID}const discriminator=this.discriminator;const discriminatorValue=ctx.data[discriminator];const option=this.optionsMap.get(discriminatorValue);if(!option){addIssueToContext(ctx,{code:ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[discriminator]});return INVALID}if(ctx.common.async){return option._parseAsync({data:ctx.data,path:ctx.path,parent:ctx})}else{return option._parseSync({data:ctx.data,path:ctx.path,parent:ctx})}}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(discriminator,options,params){const optionsMap=new Map;for(const type of options){const discriminatorValues=getDiscriminator(type.shape[discriminator]);if(!discriminatorValues.length){throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`)}for(const value of discriminatorValues){if(optionsMap.has(value)){throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`)}optionsMap.set(value,type)}}return new ZodDiscriminatedUnion({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator,options,optionsMap,...processCreateParams(params)})}}function mergeValues(a,b){const aType=getParsedType(a);const bType=getParsedType(b);if(a===b){return{valid:true,data:a}}else if(aType===ZodParsedType.object&&bType===ZodParsedType.object){const bKeys=util.objectKeys(b);const sharedKeys=util.objectKeys(a).filter((key)=>bKeys.indexOf(key)!==-1);const newObj={...a,...b};for(const key of sharedKeys){const sharedValue=mergeValues(a[key],b[key]);if(!sharedValue.valid){return{valid:false}}newObj[key]=sharedValue.data}return{valid:true,data:newObj}}else if(aType===ZodParsedType.array&&bType===ZodParsedType.array){if(a.length!==b.length){return{valid:false}}const newArray=[];for(let index=0;index<a.length;index++){const itemA=a[index];const itemB=b[index];const sharedValue=mergeValues(itemA,itemB);if(!sharedValue.valid){return{valid:false}}newArray.push(sharedValue.data)}return{valid:true,data:newArray}}else if(aType===ZodParsedType.date&&bType===ZodParsedType.date&&+a===+b){return{valid:true,data:a}}else{return{valid:false}}}class ZodIntersection extends ZodType{_parse(input){const{status,ctx}=this._processInputParams(input);const handleParsed=(parsedLeft,parsedRight)=>{if(isAborted(parsedLeft)||isAborted(parsedRight)){return INVALID}const merged=mergeValues(parsedLeft.value,parsedRight.value);if(!merged.valid){addIssueToContext(ctx,{code:ZodIssueCode.invalid_intersection_types});return INVALID}if(isDirty(parsedLeft)||isDirty(parsedRight)){status.dirty()}return{status:status.value,value:merged.data}};if(ctx.common.async){return Promise.all([this._def.left._parseAsync({data:ctx.data,path:ctx.path,parent:ctx}),this._def.right._parseAsync({data:ctx.data,path:ctx.path,parent:ctx})]).then(([left,right])=>handleParsed(left,right))}else{return handleParsed(this._def.left._parseSync({data:ctx.data,path:ctx.path,parent:ctx}),this._def.right._parseSync({data:ctx.data,path:ctx.path,parent:ctx}))}}}ZodIntersection.create=(left,right,params)=>{return new ZodIntersection({left,right,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(params)})};class ZodTuple extends ZodType{_parse(input){const{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.array){addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:ctx.parsedType});return INVALID}if(ctx.data.length<this._def.items.length){addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:true,exact:false,type:"array"});return INVALID}const rest=this._def.rest;if(!rest&&ctx.data.length>this._def.items.length){addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:true,exact:false,type:"array"});status.dirty()}const items=[...ctx.data].map((item,itemIndex)=>{const schema=this._def.items[itemIndex]||this._def.rest;if(!schema)return null;return schema._parse(new ParseInputLazyPath(ctx,item,ctx.path,itemIndex))}).filter((x)=>!!x);if(ctx.common.async){return Promise.all(items).then((results)=>{return ParseStatus.mergeArray(status,results)})}else{return ParseStatus.mergeArray(status,items)}}get items(){return this._def.items}rest(rest){return new ZodTuple({...this._def,rest})}}ZodTuple.create=(schemas,params)=>{if(!Array.isArray(schemas)){throw new Error("You must pass an array of schemas to z.tuple([ ... ])")}return new ZodTuple({items:schemas,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(params)})};class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(input){const{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.object){addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ctx.parsedType});return INVALID}const pairs=[];const keyType=this._def.keyType;const valueType=this._def.valueType;for(const key in ctx.data){pairs.push({key:keyType._parse(new ParseInputLazyPath(ctx,key,ctx.path,key)),value:valueType._parse(new ParseInputLazyPath(ctx,ctx.data[key],ctx.path,key)),alwaysSet:key in ctx.data})}if(ctx.common.async){return ParseStatus.mergeObjectAsync(status,pairs)}else{return ParseStatus.mergeObjectSync(status,pairs)}}get element(){return this._def.valueType}static create(first,second,third){if(second instanceof ZodType){return new ZodRecord({keyType:first,valueType:second,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(third)})}return new ZodRecord({keyType:ZodString.create(),valueType:first,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(second)})}}class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(input){const{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.map){addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:ctx.parsedType});return INVALID}const keyType=this._def.keyType;const valueType=this._def.valueType;const pairs=[...ctx.data.entries()].map(([key,value],index)=>{return{key:keyType._parse(new ParseInputLazyPath(ctx,key,ctx.path,[index,"key"])),value:valueType._parse(new ParseInputLazyPath(ctx,value,ctx.path,[index,"value"]))}});if(ctx.common.async){const finalMap=new Map;return Promise.resolve().then(async()=>{for(const pair of pairs){const key=await pair.key;const value=await pair.value;if(key.status==="aborted"||value.status==="aborted"){return INVALID}if(key.status==="dirty"||value.status==="dirty"){status.dirty()}finalMap.set(key.value,value.value)}return{status:status.value,value:finalMap}})}else{const finalMap=new Map;for(const pair of pairs){const key=pair.key;const value=pair.value;if(key.status==="aborted"||value.status==="aborted"){return INVALID}if(key.status==="dirty"||value.status==="dirty"){status.dirty()}finalMap.set(key.value,value.value)}return{status:status.value,value:finalMap}}}}ZodMap.create=(keyType,valueType,params)=>{return new ZodMap({valueType,keyType,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(params)})};class ZodSet extends ZodType{_parse(input){const{status,ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.set){addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:ctx.parsedType});return INVALID}const def=this._def;if(def.minSize!==null){if(ctx.data.size<def.minSize.value){addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:def.minSize.value,type:"set",inclusive:true,exact:false,message:def.minSize.message});status.dirty()}}if(def.maxSize!==null){if(ctx.data.size>def.maxSize.value){addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:def.maxSize.value,type:"set",inclusive:true,exact:false,message:def.maxSize.message});status.dirty()}}const valueType=this._def.valueType;function finalizeSet(elements){const parsedSet=new Set;for(const element of elements){if(element.status==="aborted")return INVALID;if(element.status==="dirty")status.dirty();parsedSet.add(element.value)}return{status:status.value,value:parsedSet}}const elements=[...ctx.data.values()].map((item,i)=>valueType._parse(new ParseInputLazyPath(ctx,item,ctx.path,i)));if(ctx.common.async){return Promise.all(elements).then((elements)=>finalizeSet(elements))}else{return finalizeSet(elements)}}min(minSize,message){return new ZodSet({...this._def,minSize:{value:minSize,message:errorUtil.toString(message)}})}max(maxSize,message){return new ZodSet({...this._def,maxSize:{value:maxSize,message:errorUtil.toString(message)}})}size(size,message){return this.min(size,message).max(size,message)}nonempty(message){return this.min(1,message)}}ZodSet.create=(valueType,params)=>{return new ZodSet({valueType,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(params)})};class ZodFunction extends ZodType{constructor(){super(...arguments);this.validate=this.implement}_parse(input){const{ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.function){addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.function,received:ctx.parsedType});return INVALID}function makeArgsIssue(args,error){return makeIssue({data:args,path:ctx.path,errorMaps:[ctx.common.contextualErrorMap,ctx.schemaErrorMap,getErrorMap(),en_default].filter((x)=>!!x),issueData:{code:ZodIssueCode.invalid_arguments,argumentsError:error}})}function makeReturnsIssue(returns,error){return makeIssue({data:returns,path:ctx.path,errorMaps:[ctx.common.contextualErrorMap,ctx.schemaErrorMap,getErrorMap(),en_default].filter((x)=>!!x),issueData:{code:ZodIssueCode.invalid_return_type,returnTypeError:error}})}const params={errorMap:ctx.common.contextualErrorMap};const fn=ctx.data;if(this._def.returns instanceof ZodPromise){const me=this;return OK(async function(...args){const error=new ZodError([]);const parsedArgs=await me._def.args.parseAsync(args,params).catch((e)=>{error.addIssue(makeArgsIssue(args,e));throw error});const result=await Reflect.apply(fn,this,parsedArgs);const parsedReturns=await me._def.returns._def.type.parseAsync(result,params).catch((e)=>{error.addIssue(makeReturnsIssue(result,e));throw error});return parsedReturns})}else{const me=this;return OK(function(...args){const parsedArgs=me._def.args.safeParse(args,params);if(!parsedArgs.success){throw new ZodError([makeArgsIssue(args,parsedArgs.error)])}const result=Reflect.apply(fn,this,parsedArgs.data);const parsedReturns=me._def.returns.safeParse(result,params);if(!parsedReturns.success){throw new ZodError([makeReturnsIssue(result,parsedReturns.error)])}return parsedReturns.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...items){return new ZodFunction({...this._def,args:ZodTuple.create(items).rest(ZodUnknown.create())})}returns(returnType){return new ZodFunction({...this._def,returns:returnType})}implement(func){const validatedFunc=this.parse(func);return validatedFunc}strictImplement(func){const validatedFunc=this.parse(func);return validatedFunc}static create(args,returns,params){return new ZodFunction({args:args?args:ZodTuple.create([]).rest(ZodUnknown.create()),returns:returns||ZodUnknown.create(),typeName:ZodFirstPartyTypeKind.ZodFunction,...processCreateParams(params)})}}class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(input){const{ctx}=this._processInputParams(input);const lazySchema=this._def.getter();return lazySchema._parse({data:ctx.data,path:ctx.path,parent:ctx})}}ZodLazy.create=(getter,params)=>{return new ZodLazy({getter,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(params)})};class ZodLiteral extends ZodType{_parse(input){if(input.data!==this._def.value){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{received:ctx.data,code:ZodIssueCode.invalid_literal,expected:this._def.value});return INVALID}return{status:"valid",value:input.data}}get value(){return this._def.value}}ZodLiteral.create=(value,params)=>{return new ZodLiteral({value,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(params)})};function createZodEnum(values,params){return new ZodEnum({values,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(params)})}class ZodEnum extends ZodType{_parse(input){if(typeof input.data!=="string"){const ctx=this._getOrReturnCtx(input);const expectedValues=this._def.values;addIssueToContext(ctx,{expected:util.joinValues(expectedValues),received:ctx.parsedType,code:ZodIssueCode.invalid_type});return INVALID}if(!this._cache){this._cache=new Set(this._def.values)}if(!this._cache.has(input.data)){const ctx=this._getOrReturnCtx(input);const expectedValues=this._def.values;addIssueToContext(ctx,{received:ctx.data,code:ZodIssueCode.invalid_enum_value,options:expectedValues});return INVALID}return OK(input.data)}get options(){return this._def.values}get enum(){const enumValues={};for(const val of this._def.values){enumValues[val]=val}return enumValues}get Values(){const enumValues={};for(const val of this._def.values){enumValues[val]=val}return enumValues}get Enum(){const enumValues={};for(const val of this._def.values){enumValues[val]=val}return enumValues}extract(values,newDef=this._def){return ZodEnum.create(values,{...this._def,...newDef})}exclude(values,newDef=this._def){return ZodEnum.create(this.options.filter((opt)=>!values.includes(opt)),{...this._def,...newDef})}}ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{_parse(input){const nativeEnumValues=util.getValidEnumValues(this._def.values);const ctx=this._getOrReturnCtx(input);if(ctx.parsedType!==ZodParsedType.string&&ctx.parsedType!==ZodParsedType.number){const expectedValues=util.objectValues(nativeEnumValues);addIssueToContext(ctx,{expected:util.joinValues(expectedValues),received:ctx.parsedType,code:ZodIssueCode.invalid_type});return INVALID}if(!this._cache){this._cache=new Set(util.getValidEnumValues(this._def.values))}if(!this._cache.has(input.data)){const expectedValues=util.objectValues(nativeEnumValues);addIssueToContext(ctx,{received:ctx.data,code:ZodIssueCode.invalid_enum_value,options:expectedValues});return INVALID}return OK(input.data)}get enum(){return this._def.values}}ZodNativeEnum.create=(values,params)=>{return new ZodNativeEnum({values,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(params)})};class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(input){const{ctx}=this._processInputParams(input);if(ctx.parsedType!==ZodParsedType.promise&&ctx.common.async===false){addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:ctx.parsedType});return INVALID}const promisified=ctx.parsedType===ZodParsedType.promise?ctx.data:Promise.resolve(ctx.data);return OK(promisified.then((data)=>{return this._def.type.parseAsync(data,{path:ctx.path,errorMap:ctx.common.contextualErrorMap})}))}}ZodPromise.create=(schema,params)=>{return new ZodPromise({type:schema,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(params)})};class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(input){const{status,ctx}=this._processInputParams(input);const effect=this._def.effect||null;const checkCtx={addIssue:(arg)=>{addIssueToContext(ctx,arg);if(arg.fatal){status.abort()}else{status.dirty()}},get path(){return ctx.path}};checkCtx.addIssue=checkCtx.addIssue.bind(checkCtx);if(effect.type==="preprocess"){const processed=effect.transform(ctx.data,checkCtx);if(ctx.common.async){return Promise.resolve(processed).then(async(processed)=>{if(status.value==="aborted")return INVALID;const result=await this._def.schema._parseAsync({data:processed,path:ctx.path,parent:ctx});if(result.status==="aborted")return INVALID;if(result.status==="dirty")return DIRTY(result.value);if(status.value==="dirty")return DIRTY(result.value);return result})}else{if(status.value==="aborted")return INVALID;const result=this._def.schema._parseSync({data:processed,path:ctx.path,parent:ctx});if(result.status==="aborted")return INVALID;if(result.status==="dirty")return DIRTY(result.value);if(status.value==="dirty")return DIRTY(result.value);return result}}if(effect.type==="refinement"){const executeRefinement=(acc)=>{const result=effect.refinement(acc,checkCtx);if(ctx.common.async){return Promise.resolve(result)}if(result instanceof Promise){throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.")}return acc};if(ctx.common.async===false){const inner=this._def.schema._parseSync({data:ctx.data,path:ctx.path,parent:ctx});if(inner.status==="aborted")return INVALID;if(inner.status==="dirty")status.dirty();executeRefinement(inner.value);return{status:status.value,value:inner.value}}else{return this._def.schema._parseAsync({data:ctx.data,path:ctx.path,parent:ctx}).then((inner)=>{if(inner.status==="aborted")return INVALID;if(inner.status==="dirty")status.dirty();return executeRefinement(inner.value).then(()=>{return{status:status.value,value:inner.value}})})}}if(effect.type==="transform"){if(ctx.common.async===false){const base=this._def.schema._parseSync({data:ctx.data,path:ctx.path,parent:ctx});if(!isValid(base))return INVALID;const result=effect.transform(base.value,checkCtx);if(result instanceof Promise){throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`)}return{status:status.value,value:result}}else{return this._def.schema._parseAsync({data:ctx.data,path:ctx.path,parent:ctx}).then((base)=>{if(!isValid(base))return INVALID;return Promise.resolve(effect.transform(base.value,checkCtx)).then((result)=>({status:status.value,value:result}))})}}util.assertNever(effect)}}ZodEffects.create=(schema,effect,params)=>{return new ZodEffects({schema,typeName:ZodFirstPartyTypeKind.ZodEffects,effect,...processCreateParams(params)})};ZodEffects.createWithPreprocess=(preprocess,schema,params)=>{return new ZodEffects({schema,effect:{type:"preprocess",transform:preprocess},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(params)})};class ZodOptional extends ZodType{_parse(input){const parsedType=this._getType(input);if(parsedType===ZodParsedType.undefined){return OK(undefined)}return this._def.innerType._parse(input)}unwrap(){return this._def.innerType}}ZodOptional.create=(type,params)=>{return new ZodOptional({innerType:type,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(params)})};class ZodNullable extends ZodType{_parse(input){const parsedType=this._getType(input);if(parsedType===ZodParsedType.null){return OK(null)}return this._def.innerType._parse(input)}unwrap(){return this._def.innerType}}ZodNullable.create=(type,params)=>{return new ZodNullable({innerType:type,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(params)})};class ZodDefault extends ZodType{_parse(input){const{ctx}=this._processInputParams(input);let data=ctx.data;if(ctx.parsedType===ZodParsedType.undefined){data=this._def.defaultValue()}return this._def.innerType._parse({data,path:ctx.path,parent:ctx})}removeDefault(){return this._def.innerType}}ZodDefault.create=(type,params)=>{return new ZodDefault({innerType:type,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:typeof params.default==="function"?params.default:()=>params.default,...processCreateParams(params)})};class ZodCatch extends ZodType{_parse(input){const{ctx}=this._processInputParams(input);const newCtx={...ctx,common:{...ctx.common,issues:[]}};const result=this._def.innerType._parse({data:newCtx.data,path:newCtx.path,parent:{...newCtx}});if(isAsync(result)){return result.then((result)=>{return{status:"valid",value:result.status==="valid"?result.value:this._def.catchValue({get error(){return new ZodError(newCtx.common.issues)},input:newCtx.data})}})}else{return{status:"valid",value:result.status==="valid"?result.value:this._def.catchValue({get error(){return new ZodError(newCtx.common.issues)},input:newCtx.data})}}}removeCatch(){return this._def.innerType}}ZodCatch.create=(type,params)=>{return new ZodCatch({innerType:type,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:typeof params.catch==="function"?params.catch:()=>params.catch,...processCreateParams(params)})};class ZodNaN extends ZodType{_parse(input){const parsedType=this._getType(input);if(parsedType!==ZodParsedType.nan){const ctx=this._getOrReturnCtx(input);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:ctx.parsedType});return INVALID}return{status:"valid",value:input.data}}}ZodNaN.create=(params)=>{return new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(params)})};var BRAND=Symbol("zod_brand");class ZodBranded extends ZodType{_parse(input){const{ctx}=this._processInputParams(input);const data=ctx.data;return this._def.type._parse({data,path:ctx.path,parent:ctx})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(input){const{status,ctx}=this._processInputParams(input);if(ctx.common.async){const handleAsync=async()=>{const inResult=await this._def.in._parseAsync({data:ctx.data,path:ctx.path,parent:ctx});if(inResult.status==="aborted")return INVALID;if(inResult.status==="dirty"){status.dirty();return DIRTY(inResult.value)}else{return this._def.out._parseAsync({data:inResult.value,path:ctx.path,parent:ctx})}};return handleAsync()}else{const inResult=this._def.in._parseSync({data:ctx.data,path:ctx.path,parent:ctx});if(inResult.status==="aborted")return INVALID;if(inResult.status==="dirty"){status.dirty();return{status:"dirty",value:inResult.value}}else{return this._def.out._parseSync({data:inResult.value,path:ctx.path,parent:ctx})}}}static create(a,b){return new ZodPipeline({in:a,out:b,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(input){const result=this._def.innerType._parse(input);const freeze=(data)=>{if(isValid(data)){data.value=Object.freeze(data.value)}return data};return isAsync(result)?result.then((data)=>freeze(data)):freeze(result)}unwrap(){return this._def.innerType}}ZodReadonly.create=(type,params)=>{return new ZodReadonly({innerType:type,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(params)})};var late={object:ZodObject.lazycreate};var ZodFirstPartyTypeKind;(function(ZodFirstPartyTypeKind){ZodFirstPartyTypeKind["ZodString"]="ZodString";ZodFirstPartyTypeKind["ZodNumber"]="ZodNumber";ZodFirstPartyTypeKind["ZodNaN"]="ZodNaN";ZodFirstPartyTypeKind["ZodBigInt"]="ZodBigInt";ZodFirstPartyTypeKind["ZodBoolean"]="ZodBoolean";ZodFirstPartyTypeKind["ZodDate"]="ZodDate";ZodFirstPartyTypeKind["ZodSymbol"]="ZodSymbol";ZodFirstPartyTypeKind["ZodUndefined"]="ZodUndefined";ZodFirstPartyTypeKind["ZodNull"]="ZodNull";ZodFirstPartyTypeKind["ZodAny"]="ZodAny";ZodFirstPartyTypeKind["ZodUnknown"]="ZodUnknown";ZodFirstPartyTypeKind["ZodNever"]="ZodNever";ZodFirstPartyTypeKind["ZodVoid"]="ZodVoid";ZodFirstPartyTypeKind["ZodArray"]="ZodArray";ZodFirstPartyTypeKind["ZodObject"]="ZodObject";ZodFirstPartyTypeKind["ZodUnion"]="ZodUnion";ZodFirstPartyTypeKind["ZodDiscriminatedUnion"]="ZodDiscriminatedUnion";ZodFirstPartyTypeKind["ZodIntersection"]="ZodIntersection";ZodFirstPartyTypeKind["ZodTuple"]="ZodTuple";ZodFirstPartyTypeKind["ZodRecord"]="ZodRecord";ZodFirstPartyTypeKind["ZodMap"]="ZodMap";ZodFirstPartyTypeKind["ZodSet"]="ZodSet";ZodFirstPartyTypeKind["ZodFunction"]="ZodFunction";ZodFirstPartyTypeKind["ZodLazy"]="ZodLazy";ZodFirstPartyTypeKind["ZodLiteral"]="ZodLiteral";ZodFirstPartyTypeKind["ZodEnum"]="ZodEnum";ZodFirstPartyTypeKind["ZodEffects"]="ZodEffects";ZodFirstPartyTypeKind["ZodNativeEnum"]="ZodNativeEnum";ZodFirstPartyTypeKind["ZodOptional"]="ZodOptional";ZodFirstPartyTypeKind["ZodNullable"]="ZodNullable";ZodFirstPartyTypeKind["ZodDefault"]="ZodDefault";ZodFirstPartyTypeKind["ZodCatch"]="ZodCatch";ZodFirstPartyTypeKind["ZodPromise"]="ZodPromise";ZodFirstPartyTypeKind["ZodBranded"]="ZodBranded";ZodFirstPartyTypeKind["ZodPipeline"]="ZodPipeline";ZodFirstPartyTypeKind["ZodReadonly"]="ZodReadonly"})(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));var stringType=ZodString.create;var numberType=ZodNumber.create;var nanType=ZodNaN.create;var bigIntType=ZodBigInt.create;var booleanType=ZodBoolean.create;var dateType=ZodDate.create;var symbolType=ZodSymbol.create;var undefinedType=ZodUndefined.create;var nullType=ZodNull.create;var anyType=ZodAny.create;var unknownType=ZodUnknown.create;var neverType=ZodNever.create;var voidType=ZodVoid.create;var arrayType=ZodArray.create;var objectType=ZodObject.create;var strictObjectType=ZodObject.strictCreate;var unionType=ZodUnion.create;var discriminatedUnionType=ZodDiscriminatedUnion.create;var intersectionType=ZodIntersection.create;var tupleType=ZodTuple.create;var recordType=ZodRecord.create;var mapType=ZodMap.create;var setType=ZodSet.create;var functionType=ZodFunction.create;var lazyType=ZodLazy.create;var literalType=ZodLiteral.create;var enumType=ZodEnum.create;var nativeEnumType=ZodNativeEnum.create;var promiseType=ZodPromise.create;var effectsType=ZodEffects.create;var optionalType=ZodOptional.create;var nullableType=ZodNullable.create;var preprocessType=ZodEffects.createWithPreprocess;var pipelineType=ZodPipeline.create;var nonBlankString=stringType().min(1);var selectionIdSchema=nonBlankString.refine((value)=>value.trim().length>0,"Expected a non-blank selection ID");var packageOperationRecoverySchema=enumType(["explicit_continuation","retry_safe"]);var packageOperationCommandSchema=unionType([objectType({kind:literalType("install"),packageFqn:nonBlankString,recovery:packageOperationRecoverySchema}),objectType({kind:literalType("promote"),packageId:nonBlankString,recovery:packageOperationRecoverySchema,releaseId:nonBlankString}),objectType({kind:literalType("publish"),packageFqn:nonBlankString,recovery:packageOperationRecoverySchema}),objectType({installationId:nonBlankString,kind:literalType("rollback"),packageId:nonBlankString,recovery:packageOperationRecoverySchema,releaseId:nonBlankString}),objectType({installationId:nonBlankString,kind:literalType("update"),packageId:nonBlankString,recovery:packageOperationRecoverySchema,releaseId:nonBlankString}),objectType({kind:literalType("update"),mode:literalType("sync"),packageFqn:nonBlankString,recovery:packageOperationRecoverySchema})]);var packageOperationStatusSchema=enumType(["awaiting_continuation","failed","pending","running","succeeded"]);var releaseDigestSchema=stringType().regex(/^[\da-f]{64}$/u);var releaseSelectionSchema=objectType({generation:stringType().regex(/^(?:0|[1-9][0-9]*)$/u),releaseDigest:releaseDigestSchema,releaseId:selectionIdSchema});var graphMemberSchema=releaseSelectionSchema.extend({installationId:selectionIdSchema,packageFqn:selectionIdSchema,packageId:selectionIdSchema});var pinSchema=objectType({fqn:nonBlankString,releaseDigest:releaseDigestSchema,releaseId:nonBlankString});var dependencyPathsSchema=arrayType(arrayType(stringType()));var blockerMessageSchema=stringType();var knownBlockerSchema=unionType([objectType({_tag:literalType("manual_prerequisite"),message:blockerMessageSchema,observed:pinSchema.nullable(),path:arrayType(pinSchema),paths:arrayType(arrayType(pinSchema)),required:pinSchema}),objectType({_tag:literalType("authority_denied"),boundary:enumType(["principal","publication","promotion"]),message:blockerMessageSchema,paths:dependencyPathsSchema}),objectType({_tag:enumType(["dirty_readonly","definition_rejected"]),definitions:arrayType(objectType({fqn:nonBlankString,kind:enumType(["workflow","agent","skill","remote_tool_collection","knowledge_connector_instance","dataset_connector_instance","organization_group","application_grant","external_app"])})),message:blockerMessageSchema,paths:dependencyPathsSchema}),objectType({_tag:enumType(["release_unavailable","release_identity_mismatch","conflicting_pins","cycle","installation_identity_mismatch","retained_requirement_conflict","package_identity_conflict"]),message:blockerMessageSchema,paths:dependencyPathsSchema})]);var preflightDiagnosticSchema=unionType([knownBlockerSchema,objectType({_tag:nonBlankString,message:blockerMessageSchema.optional(),paths:dependencyPathsSchema.optional()}).transform(({_tag,message,paths})=>({_tag:"unknown",message:message??`Blocked by ${_tag}.`,paths:paths??[],tag:_tag}))]);var appliedGraphFields={applicationId:nonBlankString,members:arrayType(graphMemberSchema)};var applicationStageSchema=unionType([objectType({state:enumType(["not_required","pending"])}),objectType({blocker:preflightDiagnosticSchema.optional(),state:literalType("not_applied")}).transform(({blocker,state})=>blocker===undefined?{state}:{blocker,state}),objectType({...appliedGraphFields,state:literalType("applied")})]);var hostOutcomeFieldsSchema=objectType({diagnosticId:nonBlankString.optional(),member:graphMemberSchema,observed:objectType({desired:releaseSelectionSchema.nullable(),serving:releaseSelectionSchema.nullable()}),result:enumType(["failed","pending","serving","stale"])});var hostOutcome=({diagnosticId,...outcome})=>diagnosticId===undefined?outcome:{...outcome,diagnosticId};var cleanupCandidateSchema=objectType({installationId:selectionIdSchema,packageFqn:selectionIdSchema,packageId:selectionIdSchema,releaseDigest:releaseDigestSchema,releaseId:selectionIdSchema});var cleanupProtectionSchema=unionType([objectType({dependent:pinSchema,kind:literalType("required_by"),protection:enumType(["desired","serving"])}),objectType({dependent:pinSchema,kind:literalType("unknown_requirement")}),objectType({kind:enumType(["built_in","explicit_intent","selection_changed","unknown_intent"])}),objectType({kind:literalType("workflow_use"),state:enumType(["published","draft_head","working_copy"]),template:objectType({fqn:nonBlankString,kind:nonBlankString,version:nonBlankString}),workflowId:nonBlankString}),objectType({bindingKind:enumType(["tool_instance","connection","knowledge_connector"]),id:nonBlankString,kind:literalType("live_binding")})]);var cleanupStageSchema=objectType({candidates:arrayType(cleanupCandidateSchema.extend({protections:arrayType(cleanupProtectionSchema).optional(),result:enumType(["pending","removed","retained"])}).transform(({protections,...candidate})=>protections===undefined?candidate:{...candidate,protections})),state:enumType(["pending","completed","failed"])});var failureSchema=objectType({message:nonBlankString,reason:enumType(["credential_not_found","credential_permission_denied","credential_scope_denied","credential_verification_unavailable","execution_failed","invalid_artifact","release_not_found","release_package_mismatch"])});var eventOutcomeSchema=unionType([objectType({...appliedGraphFields,kind:literalType("graph_applied")}),objectType({blocker:preflightDiagnosticSchema,kind:literalType("graph_not_applied")}),hostOutcomeFieldsSchema.extend({kind:literalType("host")}).transform(({kind,...outcome})=>({...hostOutcome(outcome),kind})),objectType({kind:literalType("retry_requested")}),failureSchema.extend({kind:literalType("command_failed")}),objectType({candidate:cleanupCandidateSchema,kind:literalType("cleanup_removed")}),objectType({candidate:cleanupCandidateSchema,kind:literalType("cleanup_retained"),protections:arrayType(cleanupProtectionSchema)})]);var packageOperationSnapshotSchema=objectType({application:applicationStageSchema,cleanup:cleanupStageSchema.optional(),command:packageOperationCommandSchema,continuationOf:nonBlankString.optional(),createdAt:stringType().datetime({offset:true}),failure:failureSchema.optional(),hosts:arrayType(hostOutcomeFieldsSchema.transform(hostOutcome)),id:nonBlankString,idempotencyKey:nonBlankString,lastEventSequence:numberType().int().nonnegative(),nextAction:enumType(["continue","none","retry","wait"]),organizationId:nonBlankString,packageFqn:nonBlankString,principal:unionType([objectType({kind:literalType("administrator"),userId:nonBlankString}),objectType({credentialId:nonBlankString,kind:literalType("publisher")}),objectType({actor:literalType("bootstrap"),kind:literalType("system")})]),publication:objectType({packageId:selectionIdSchema,releaseDigest:releaseDigestSchema,releaseId:selectionIdSchema}).optional(),recoveryReason:literalType("selection_outcome_unavailable").optional(),selection:objectType({generation:numberType().int().positive(),installationId:selectionIdSchema,releaseId:selectionIdSchema}).optional(),status:packageOperationStatusSchema,updatedAt:stringType().datetime({offset:true})});var packageOperationEventSchema=objectType({createdAt:stringType().datetime({offset:true}),operationId:nonBlankString,outcome:eventOutcomeSchema.optional(),sequence:numberType().int().nonnegative(),status:packageOperationStatusSchema});var decodePackageOperationEvent=(data)=>{const{outcome,...event}=packageOperationEventSchema.parse(JSON.parse(data));return outcome===undefined?event:{...event,outcome}};var decodePackageOperationSnapshot=(snapshot)=>{const decoded=packageOperationSnapshotSchema.parse(snapshot);const{cleanup,continuationOf,failure,publication,recoveryReason,selection,...required}=decoded;const snapshotDto=required;if(cleanup!==undefined){snapshotDto.cleanup=cleanup}if(continuationOf!==undefined){snapshotDto.continuationOf=continuationOf}if(failure!==undefined){snapshotDto.failure=failure}if(recoveryReason!==undefined){snapshotDto.recoveryReason=recoveryReason}if(publication!==undefined){snapshotDto.publication=publication}if(selection!==undefined){snapshotDto.selection=selection}return snapshotDto};import{createHash as createHash4}from"crypto";var installPackage=async(input)=>{const request={client:input.client,headers:{"idempotency-key":input.idempotencyKey,"x-organization-id":input.organizationId},path:{fqn:input.packageFqn},throwOnError:true};if(input.body!==undefined){request.body=input.body}if(input.signal!==undefined){request.signal=input.signal}const response=await extensionPackagesInstall(request);return response.data};var updatePackage=async(input)=>{const request={body:input.body,client:input.client,headers:{"idempotency-key":input.idempotencyKey,"x-organization-id":input.organizationId},throwOnError:true};if(input.signal!==undefined){request.signal=input.signal}const response=await packageReleasesUpdateInstallation(request);return response.data};var publishPackage=async(input)=>{const request={body:input.body,client:input.client,headers:{"idempotency-key":input.idempotencyKey},throwOnError:true};if(input.signal!==undefined){request.signal=input.signal}const response=await packageReleasesPublish(request);return response.data};var promotePackage=async(input)=>{const request={body:input.body,client:input.client,headers:{"idempotency-key":input.idempotencyKey},throwOnError:true};if(input.signal!==undefined){request.signal=input.signal}const response=await packageReleasesPromote(request);return response.data};import{createHash as createHash2}from"crypto";import{build as viteBuild,esmExternalRequirePlugin}from"vite";import{fileURLToPath as fileURLToPath2}from"url";var nodePath=runSync2(provide3(Path2,layer5));var literalLazyImport=(declarationSpecifier,identity)=>{const loaderSource=Function.prototype.toString.call(identity.load).trim();const arrowMatch=/^(?:async\s*)?\(\s*\)\s*=>\s*(?:await\s*)?(?:import|__vite_ssr_dynamic_import__)\(\s*(?<quote>["'])(?<specifier>[^"'\\\r\n]+)\k<quote>\s*\)$/u.exec(loaderSource);const functionMatch=/^function(?:\s+\w+)?\s*\(\s*\)\s*\{\s*return\s+(?:import|__vite_ssr_dynamic_import__)\(\s*(?<quote>["'])(?<specifier>[^"'\\\r\n]+)\k<quote>\s*\)\s*;?\s*\}$/u.exec(loaderSource);const wrappedImportMatch=/(?:import|__vite_ssr_dynamic_import__)\(\s*(?<quote>["'])(?<specifier>[^"'\\\r\n]+)\k<quote>\s*\)/u.exec(loaderSource);const specifier=arrowMatch?.groups?.specifier??functionMatch?.groups?.specifier??wrappedImportMatch?.groups?.specifier;if(specifier===undefined){throw new TypeError(`${identity.subject} load must be a direct literal lazy import`)}if(specifier.startsWith("/@fs/")){return specifier.slice(4)}if(specifier.startsWith("file:")){return fileURLToPath2(specifier)}if(specifier.startsWith("/")){if(!declarationSpecifier.startsWith("file:")){throw new TypeError(`${identity.subject} root-relative load requires a file declaration`)}const declarationDirectory=nodePath.dirname(fileURLToPath2(declarationSpecifier));const workspaceCandidate=nodePath.resolve(process.cwd(),specifier.slice(1));const workspaceRelation=nodePath.relative(declarationDirectory,workspaceCandidate);return workspaceRelation!==""&&!workspaceRelation.startsWith("..")&&!nodePath.isAbsolute(workspaceRelation)?workspaceCandidate:nodePath.resolve(declarationDirectory,specifier.slice(1))}if(specifier.startsWith(".")){if(!declarationSpecifier.startsWith("file:")){throw new TypeError(`${identity.subject} relative load requires a file declaration`)}return nodePath.resolve(nodePath.dirname(fileURLToPath2(declarationSpecifier)),specifier)}return specifier};var resolveLazyImportModule=(declarationSpecifier,entry)=>{const specifier=literalLazyImport(declarationSpecifier,entry);if(!nodePath.isAbsolute(specifier)){return specifier}try{return Bun.resolveSync(specifier,nodePath.dirname(specifier))}catch(error){throw new TypeError(`${entry.subject} module could not be resolved: ${specifier}`,{cause:error})}};var resolveHostedContributionEntry=(declarationSpecifier,identity)=>resolveLazyImportModule(declarationSpecifier,{load:identity.load,subject:`Hosted Contribution '${identity.fqn}'`});import{fileURLToPath as fileURLToPath3,pathToFileURL as pathToFileURL2}from"url";import{createServer}from"vite";var WORKSPACE_SOURCE_CONDITION="ci-source";var conditionsFromArgument=(argument,nextArgument)=>{if(argument==="--conditions"){return nextArgument===undefined?[]:nextArgument.split(",")}if(argument.startsWith("--conditions=")){return argument.slice("--conditions=".length).split(",")}return[]};var workspaceSourceConditions=(execArgv)=>{for(const[index,argument]of execArgv.entries()){if(conditionsFromArgument(argument,execArgv[index+1]).includes(WORKSPACE_SOURCE_CONDITION)){return[WORKSPACE_SOURCE_CONDITION]}}return[]};var workspaceSourceResolve=(execArgv)=>{const conditions=workspaceSourceConditions(execArgv);return conditions.length>0?{conditions:[...conditions]}:{}};var workspaceSourceSsrResolve=(execArgv)=>{const conditions=workspaceSourceConditions(execArgv);return conditions.length>0?{resolve:{conditions:[...conditions]}}:{}};class PackageDeclarationError extends TaggedError2("PackageDeclarationError"){}var path2=runSync2(provide3(Path2,layer5));var isRecord2=(value)=>value!==null&&typeof value==="object";var isPackageDefinition=(value)=>{if(!isRecord2(value)||!isRecord2(value.manifest)){return false}return value.manifest.apiVersion==="v4"&&typeof value.manifest.fqn==="string"&&Array.isArray(value.components)&&(value.hostedContributions===undefined||Array.isArray(value.hostedContributions))&&Array.isArray(value.schemaSidecars)};var normalizePackageDefinition=(definition,packageLoader)=>({...definition,hostedContributions:definition.hostedContributions??[],...packageLoader===undefined?undefined:{packageLoader}});var isPackageLoader=(value)=>typeof value==="function";var packageLoaderMap=(loaders,definitions)=>{if(loaders===undefined){return}const fqns=definitions.map(({manifest})=>manifest.fqn);if(!isRecord2(loaders)){throw new TypeError("Declaration packageLoaders must be an object")}const entries=Object.entries(loaders);if(entries.length!==fqns.length||!fqns.every((fqn)=>Object.hasOwn(loaders,fqn))||!entries.every(([,loader])=>isPackageLoader(loader))){throw new TypeError(`Declaration packageLoaders must map exactly the declared packages (${fqns.join(", ")}) to lazy import functions`)}return new Map(entries.flatMap(([fqn,loader])=>isPackageLoader(loader)?[[fqn,loader]]:[]))};var declarationSpecifier=(specifier)=>{if(specifier.startsWith("data:")||specifier.startsWith("file:")||specifier.startsWith("http:")||specifier.startsWith("https:")||!specifier.startsWith(".")&&!specifier.startsWith("/")){return specifier}return pathToFileURL2(path2.resolve(process.cwd(),specifier)).href};var normalizeModuleDeclarations=(loaded)=>{const exported=loaded.packageDefinitions??loaded.packageDefinition??loaded.default;const candidate=isRecord2(exported)&&"default"in exported?exported.default:exported;const values=Array.isArray(candidate)?candidate:[candidate];if(values.length===0||!values.every(isPackageDefinition)){throw new TypeError(`Declaration module must export a PackageDefinition or PackageDefinition array; received ${JSON.stringify(candidate)}`)}const loaders=packageLoaderMap(loaded.packageLoaders,values);return values.map((definition)=>normalizePackageDefinition(definition,loaders?.get(definition.manifest.fqn)))};var loadPackageDeclarations=flow((specifier)=>tryPromise2(()=>import(declarationSpecifier(specifier))).pipe(map4((loaded)=>isRecord2(loaded)?loaded:undefined),flatMap3((loaded)=>loaded===undefined?fail6(new PackageDeclarationError({message:"Declaration module did not expose module exports"})):succeed6(normalizeModuleDeclarations(loaded)))),runPromise2);var loadFreshPackageDeclarations=flow((specifier)=>{const resolved=declarationSpecifier(specifier);if(!resolved.startsWith("file:")){return promise2(()=>loadPackageDeclarations(resolved))}const sourcePath=fileURLToPath3(resolved);const root=path2.dirname(sourcePath);return acquireUseRelease2(tryPromise2(()=>createServer({appType:"custom",configFile:false,logLevel:"silent",resolve:workspaceSourceResolve(process.execArgv),root,server:{middlewareMode:true},ssr:workspaceSourceSsrResolve(process.execArgv)})),(server)=>tryPromise2(()=>server.ssrLoadModule(`/${encodeURIComponent(path2.basename(sourcePath))}`)).pipe(flatMap3((loaded)=>isRecord2(loaded)?succeed6(normalizeModuleDeclarations(loaded)):fail6(new PackageDeclarationError({message:"Declaration module did not expose module exports"})))),(server)=>promise2(()=>server.close()))},runPromise2);var compareCanonicalText=(left,right)=>{if(left===right){return 0}return left<right?-1:1};var blockSize=512;var isAscii=(value)=>{for(const character of value){if((character.codePointAt(0)??128)>127){return false}}return true};var writeAscii=(target,offset,length,value)=>{if(value.length>length||!isAscii(value)){throw new TypeError(`Value does not fit deterministic ustar field: ${value}`)}for(let index=0;index<value.length;index+=1){target[offset+index]=value.codePointAt(index)??0}};var writeOctal=(target,offset,length,value)=>{const source=value.toString(8).padStart(length-1,"0");if(source.length>=length){throw new TypeError(`Value does not fit deterministic ustar number: ${value}`)}writeAscii(target,offset,length-1,source)};var splitArchivePath=(path)=>{if(path===""||path.startsWith("/")||path.includes("\\")||path.split("/").some((part)=>part===""||part==="."||part==="..")){throw new TypeError(`Unsafe Extension Release archive path '${path}'`)}if(path.length<=100){return{name:path,prefix:""}}const separator=path.lastIndexOf("/");const prefix=path.slice(0,separator);const name=path.slice(separator+1);if(separator===-1||name.length>100||prefix.length>155){throw new TypeError(`Extension Release archive path is too long: ${path}`)}return{name,prefix}};var headerFor=(entry)=>{const header=new Uint8Array(blockSize);const{name,prefix}=splitArchivePath(entry.path);writeAscii(header,0,100,name);writeOctal(header,100,8,420);writeOctal(header,108,8,0);writeOctal(header,116,8,0);writeOctal(header,124,12,entry.bytes.byteLength);writeOctal(header,136,12,0);header.fill(32,148,156);header[156]=48;writeAscii(header,257,6,"ustar\x00");writeAscii(header,263,2,"00");writeAscii(header,345,155,prefix);const checksum=header.reduce((total,value)=>total+value,0);writeAscii(header,148,8,`${checksum.toString(8).padStart(6,"0")}\x00 `);return header};var createExtensionReleaseArchive=(sourceEntries)=>{const entries=sourceEntries.toSorted((left,right)=>compareCanonicalText(left.path,right.path));if(new Set(entries.map(({path})=>path)).size!==entries.length){throw new TypeError("Extension Release archive paths must be unique")}const size=entries.reduce((total,entry)=>total+blockSize+Math.ceil(entry.bytes.byteLength/blockSize)*blockSize,0)+blockSize*2;const archive=new Uint8Array(size);let offset=0;for(const entry of entries){archive.set(headerFor(entry),offset);offset+=blockSize;archive.set(entry.bytes,offset);offset+=Math.ceil(entry.bytes.byteLength/blockSize)*blockSize}return archive};var backendHostProvidedModules=["@collective-intelligence/extensions-sdk","@collective-intelligence/extensions-sdk-backend"];var frontendModules=["@collective-intelligence/extensions-sdk","@collective-intelligence/extensions-sdk-frontend-react","@collective-intelligence/extensions-sdk-frontend-react/workflow","@collective-intelligence/ui-react","@collective-intelligence/ui-react/icons","@collective-intelligence/ui-react/ui","@collective-intelligence/ui-react/ui-extensions","@tanstack/react-query","react","react-dom","react-dom/client","react/jsx-dev-runtime","react/jsx-runtime"];var modulesByHost={backend:backendHostProvidedModules,dashboard:[...frontendModules,"@xyflow/react"],studio:frontendModules};var FRONTEND_HOSTS=HOSTS.filter((host)=>host!=="backend");var hostProvidedModulesFor=(host)=>modulesByHost[host];var frontendHostProvidedModules=[...new Set(FRONTEND_HOSTS.flatMap(hostProvidedModulesFor))];var isHostProvidedModule=(host,specifier)=>modulesByHost[host].some((moduleName)=>moduleName===specifier);import{fileURLToPath as fileURLToPath4}from"url";var backendPackageEntry=(definition)=>{if(!definition.components.some((component)=>("implementation"in component))&&definition.schemaSidecars.length===0){return}const fqn=`${definition.manifest.fqn}.backend.package-runtime`;if(definition.hostedContributions.some(({manifest})=>manifest.fqn===fqn)){throw new TypeError(`Hosted Contribution '${fqn}' collides with the reserved Backend package runtime entry`)}return{exportName:"createPackageRuntime",fqn,host:"backend"}};var backendArtifactContributions=(definition)=>{const entry=backendPackageEntry(definition);return[...definition.hostedContributions.map(({manifest})=>manifest),...entry===undefined?[]:[entry]]};var backendPackageEntrySource=(packageFqn)=>`
|
|
266
266
|
import { createBackendPackageRuntime } from "@collective-intelligence/extensions-sdk-backend";
|
|
267
267
|
import * as declaration from "ci-package-declaration";
|
|
268
268
|
export function createPackageRuntime() {
|
|
@@ -290,15 +290,16 @@ Defaulting to 2020, but this will stop working in the future.`)}options.ecmaVers
|
|
|
290
290
|
`);if(lines.length>1){for(let i=0;i<lines.length-1;i++){this.generatedCodeLine++;this.raw[this.generatedCodeLine]=this.rawSegments=[]}this.generatedCodeColumn=0}this.generatedCodeColumn+=lines[lines.length-1].length}}var n=`
|
|
291
291
|
`;var warned={insertLeft:false,insertRight:false,storeName:false};class MagicString{constructor(string,options={}){const chunk=new Chunk(0,string.length,string);Object.defineProperties(this,{original:{writable:true,value:string},outro:{writable:true,value:""},intro:{writable:true,value:""},firstChunk:{writable:true,value:chunk},lastChunk:{writable:true,value:chunk},lastSearchedChunk:{writable:true,value:chunk},byStart:{writable:true,value:{}},byEnd:{writable:true,value:{}},filename:{writable:true,value:options.filename},indentExclusionRanges:{writable:true,value:options.indentExclusionRanges},sourcemapLocations:{writable:true,value:new BitSet},storedNames:{writable:true,value:{}},indentStr:{writable:true,value:undefined},ignoreList:{writable:true,value:options.ignoreList},offset:{writable:true,value:options.offset||0}});this.byStart[0]=chunk;this.byEnd[string.length]=chunk}addSourcemapLocation(char){this.sourcemapLocations.add(char)}append(content){if(typeof content!=="string")throw new TypeError("outro content must be a string");this.outro+=content;return this}appendLeft(index,content){index=index+this.offset;if(typeof content!=="string")throw new TypeError("inserted content must be a string");this._split(index);const chunk=this.byEnd[index];if(chunk){chunk.appendLeft(content)}else{this.intro+=content}return this}appendRight(index,content){index=index+this.offset;if(typeof content!=="string")throw new TypeError("inserted content must be a string");this._split(index);const chunk=this.byStart[index];if(chunk){chunk.appendRight(content)}else{this.outro+=content}return this}clone(){const cloned=new MagicString(this.original,{filename:this.filename,offset:this.offset});let originalChunk=this.firstChunk;let clonedChunk=cloned.firstChunk=cloned.lastSearchedChunk=originalChunk.clone();while(originalChunk){cloned.byStart[clonedChunk.start]=clonedChunk;cloned.byEnd[clonedChunk.end]=clonedChunk;const nextOriginalChunk=originalChunk.next;const nextClonedChunk=nextOriginalChunk&&nextOriginalChunk.clone();if(nextClonedChunk){clonedChunk.next=nextClonedChunk;nextClonedChunk.previous=clonedChunk;clonedChunk=nextClonedChunk}originalChunk=nextOriginalChunk}cloned.lastChunk=clonedChunk;if(this.indentExclusionRanges){cloned.indentExclusionRanges=this.indentExclusionRanges.slice()}cloned.sourcemapLocations=new BitSet(this.sourcemapLocations);cloned.intro=this.intro;cloned.outro=this.outro;return cloned}generateDecodedMap(options){options=options||{};const sourceIndex=0;const names=Object.keys(this.storedNames);const mappings=new Mappings(options.hires);const locate=getLocator(this.original);if(this.intro){mappings.advance(this.intro)}this.firstChunk.eachNext((chunk)=>{const loc=locate(chunk.start);if(chunk.intro.length)mappings.advance(chunk.intro);if(chunk.edited){mappings.addEdit(sourceIndex,chunk.content,loc,chunk.storeName?names.indexOf(chunk.original):-1)}else{mappings.addUneditedChunk(sourceIndex,chunk,this.original,loc,this.sourcemapLocations)}if(chunk.outro.length)mappings.advance(chunk.outro)});if(this.outro){mappings.advance(this.outro)}return{file:options.file?options.file.split(/[/\\]/).pop():undefined,sources:[options.source?getRelativePath(options.file||"",options.source):options.file||""],sourcesContent:options.includeContent?[this.original]:undefined,names,mappings:mappings.raw,x_google_ignoreList:this.ignoreList?[sourceIndex]:undefined}}generateMap(options){return new SourceMap(this.generateDecodedMap(options))}_ensureindentStr(){if(this.indentStr===undefined){this.indentStr=guessIndent(this.original)}}_getRawIndentString(){this._ensureindentStr();return this.indentStr}getIndentString(){this._ensureindentStr();return this.indentStr===null?"\t":this.indentStr}indent(indentStr,options){const pattern=/^[^\r\n]/gm;if(isObject2(indentStr)){options=indentStr;indentStr=undefined}if(indentStr===undefined){this._ensureindentStr();indentStr=this.indentStr||"\t"}if(indentStr==="")return this;options=options||{};const isExcluded={};if(options.exclude){const exclusions=typeof options.exclude[0]==="number"?[options.exclude]:options.exclude;exclusions.forEach((exclusion)=>{for(let i=exclusion[0];i<exclusion[1];i+=1){isExcluded[i]=true}})}let shouldIndentNextCharacter=options.indentStart!==false;const replacer=(match)=>{if(shouldIndentNextCharacter)return`${indentStr}${match}`;shouldIndentNextCharacter=true;return match};this.intro=this.intro.replace(pattern,replacer);let charIndex=0;let chunk=this.firstChunk;while(chunk){const end=chunk.end;if(chunk.edited){if(!isExcluded[charIndex]){chunk.content=chunk.content.replace(pattern,replacer);if(chunk.content.length){shouldIndentNextCharacter=chunk.content[chunk.content.length-1]===`
|
|
292
292
|
`}}}else{charIndex=chunk.start;while(charIndex<end){if(!isExcluded[charIndex]){const char=this.original[charIndex];if(char===`
|
|
293
|
-
`){shouldIndentNextCharacter=true}else if(char!=="\r"&&shouldIndentNextCharacter){shouldIndentNextCharacter=false;if(charIndex===chunk.start){chunk.prependRight(indentStr)}else{this._splitChunk(chunk,charIndex);chunk=chunk.next;chunk.prependRight(indentStr)}}}charIndex+=1}}charIndex=chunk.end;chunk=chunk.next}this.outro=this.outro.replace(pattern,replacer);return this}insert(){throw new Error("magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)")}insertLeft(index,content){if(!warned.insertLeft){console.warn("magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead");warned.insertLeft=true}return this.appendLeft(index,content)}insertRight(index,content){if(!warned.insertRight){console.warn("magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead");warned.insertRight=true}return this.prependRight(index,content)}move(start,end,index){start=start+this.offset;end=end+this.offset;index=index+this.offset;if(index>=start&&index<=end)throw new Error("Cannot move a selection inside itself");this._split(start);this._split(end);this._split(index);const first=this.byStart[start];const last=this.byEnd[end];const oldLeft=first.previous;const oldRight=last.next;const newRight=this.byStart[index];if(!newRight&&last===this.lastChunk)return this;const newLeft=newRight?newRight.previous:this.lastChunk;if(oldLeft)oldLeft.next=oldRight;if(oldRight)oldRight.previous=oldLeft;if(newLeft)newLeft.next=first;if(newRight)newRight.previous=last;if(!first.previous)this.firstChunk=last.next;if(!last.next){this.lastChunk=first.previous;this.lastChunk.next=null}first.previous=newLeft;last.next=newRight||null;if(!newLeft)this.firstChunk=first;if(!newRight)this.lastChunk=last;return this}overwrite(start,end,content,options){options=options||{};return this.update(start,end,content,{...options,overwrite:!options.contentOnly})}update(start,end,content,options){start=start+this.offset;end=end+this.offset;if(typeof content!=="string")throw new TypeError("replacement content must be a string");if(this.original.length!==0){while(start<0)start+=this.original.length;while(end<0)end+=this.original.length}if(end>this.original.length)throw new Error("end is out of bounds");if(start===end)throw new Error("Cannot overwrite a zero-length range \u2013 use appendLeft or prependRight instead");this._split(start);this._split(end);if(options===true){if(!warned.storeName){console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string");warned.storeName=true}options={storeName:true}}const storeName=options!==undefined?options.storeName:false;const overwrite=options!==undefined?options.overwrite:false;if(storeName){const original=this.original.slice(start,end);Object.defineProperty(this.storedNames,original,{writable:true,value:true,enumerable:true})}const first=this.byStart[start];const last=this.byEnd[end];if(first){let chunk=first;while(chunk!==last){if(chunk.next!==this.byStart[chunk.end]){throw new Error("Cannot overwrite across a split point")}chunk=chunk.next;chunk.edit("",false)}first.edit(content,storeName,!overwrite)}else{const newChunk=new Chunk(start,end,"").edit(content,storeName);last.next=newChunk;newChunk.previous=last}return this}prepend(content){if(typeof content!=="string")throw new TypeError("outro content must be a string");this.intro=content+this.intro;return this}prependLeft(index,content){index=index+this.offset;if(typeof content!=="string")throw new TypeError("inserted content must be a string");this._split(index);const chunk=this.byEnd[index];if(chunk){chunk.prependLeft(content)}else{this.intro=content+this.intro}return this}prependRight(index,content){index=index+this.offset;if(typeof content!=="string")throw new TypeError("inserted content must be a string");this._split(index);const chunk=this.byStart[index];if(chunk){chunk.prependRight(content)}else{this.outro=content+this.outro}return this}remove(start,end){start=start+this.offset;end=end+this.offset;if(this.original.length!==0){while(start<0)start+=this.original.length;while(end<0)end+=this.original.length}if(start===end)return this;if(start<0||end>this.original.length)throw new Error("Character is out of bounds");if(start>end)throw new Error("end must be greater than start");this._split(start);this._split(end);let chunk=this.byStart[start];while(chunk){chunk.intro="";chunk.outro="";chunk.edit("");chunk=end>chunk.end?this.byStart[chunk.end]:null}return this}reset(start,end){start=start+this.offset;end=end+this.offset;if(this.original.length!==0){while(start<0)start+=this.original.length;while(end<0)end+=this.original.length}if(start===end)return this;if(start<0||end>this.original.length)throw new Error("Character is out of bounds");if(start>end)throw new Error("end must be greater than start");this._split(start);this._split(end);let chunk=this.byStart[start];while(chunk){chunk.reset();chunk=end>chunk.end?this.byStart[chunk.end]:null}return this}lastChar(){if(this.outro.length)return this.outro[this.outro.length-1];let chunk=this.lastChunk;do{if(chunk.outro.length)return chunk.outro[chunk.outro.length-1];if(chunk.content.length)return chunk.content[chunk.content.length-1];if(chunk.intro.length)return chunk.intro[chunk.intro.length-1]}while(chunk=chunk.previous);if(this.intro.length)return this.intro[this.intro.length-1];return""}lastLine(){let lineIndex=this.outro.lastIndexOf(n);if(lineIndex!==-1)return this.outro.substr(lineIndex+1);let lineStr=this.outro;let chunk=this.lastChunk;do{if(chunk.outro.length>0){lineIndex=chunk.outro.lastIndexOf(n);if(lineIndex!==-1)return chunk.outro.substr(lineIndex+1)+lineStr;lineStr=chunk.outro+lineStr}if(chunk.content.length>0){lineIndex=chunk.content.lastIndexOf(n);if(lineIndex!==-1)return chunk.content.substr(lineIndex+1)+lineStr;lineStr=chunk.content+lineStr}if(chunk.intro.length>0){lineIndex=chunk.intro.lastIndexOf(n);if(lineIndex!==-1)return chunk.intro.substr(lineIndex+1)+lineStr;lineStr=chunk.intro+lineStr}}while(chunk=chunk.previous);lineIndex=this.intro.lastIndexOf(n);if(lineIndex!==-1)return this.intro.substr(lineIndex+1)+lineStr;return this.intro+lineStr}slice(start=0,end=this.original.length-this.offset){start=start+this.offset;end=end+this.offset;if(this.original.length!==0){while(start<0)start+=this.original.length;while(end<0)end+=this.original.length}let result="";let chunk=this.firstChunk;while(chunk&&(chunk.start>start||chunk.end<=start)){if(chunk.start<end&&chunk.end>=end){return result}chunk=chunk.next}if(chunk&&chunk.edited&&chunk.start!==start)throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);const startChunk=chunk;while(chunk){if(chunk.intro&&(startChunk!==chunk||chunk.start===start)){result+=chunk.intro}const containsEnd=chunk.start<end&&chunk.end>=end;if(containsEnd&&chunk.edited&&chunk.end!==end)throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);const sliceStart=startChunk===chunk?start-chunk.start:0;const sliceEnd=containsEnd?chunk.content.length+end-chunk.end:chunk.content.length;result+=chunk.content.slice(sliceStart,sliceEnd);if(chunk.outro&&(!containsEnd||chunk.end===end)){result+=chunk.outro}if(containsEnd){break}chunk=chunk.next}return result}snip(start,end){const clone=this.clone();clone.remove(0,start);clone.remove(end,clone.original.length);return clone}_split(index){if(this.byStart[index]||this.byEnd[index])return;let chunk=this.lastSearchedChunk;let previousChunk=chunk;const searchForward=index>chunk.end;while(chunk){if(chunk.contains(index))return this._splitChunk(chunk,index);chunk=searchForward?this.byStart[chunk.end]:this.byEnd[chunk.start];if(chunk===previousChunk)return;previousChunk=chunk}}_splitChunk(chunk,index){if(chunk.edited&&chunk.content.length){const loc=getLocator(this.original)(index);throw new Error(`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} \u2013 "${chunk.original}")`)}const newChunk=chunk.split(index);this.byEnd[index]=chunk;this.byStart[index]=newChunk;this.byEnd[newChunk.end]=newChunk;if(chunk===this.lastChunk)this.lastChunk=newChunk;this.lastSearchedChunk=chunk;return true}toString(){let str=this.intro;let chunk=this.firstChunk;while(chunk){str+=chunk.toString();chunk=chunk.next}return str+this.outro}isEmpty(){let chunk=this.firstChunk;do{if(chunk.intro.length&&chunk.intro.trim()||chunk.content.length&&chunk.content.trim()||chunk.outro.length&&chunk.outro.trim())return false}while(chunk=chunk.next);return true}length(){let chunk=this.firstChunk;let length=0;do{length+=chunk.intro.length+chunk.content.length+chunk.outro.length}while(chunk=chunk.next);return length}trimLines(){return this.trim("[\\r\\n]")}trim(charType){return this.trimStart(charType).trimEnd(charType)}trimEndAborted(charType){const rx=new RegExp((charType||"\\s")+"+$");this.outro=this.outro.replace(rx,"");if(this.outro.length)return true;let chunk=this.lastChunk;do{const end=chunk.end;const aborted=chunk.trimEnd(rx);if(chunk.end!==end){if(this.lastChunk===chunk){this.lastChunk=chunk.next}this.byEnd[chunk.end]=chunk;this.byStart[chunk.next.start]=chunk.next;this.byEnd[chunk.next.end]=chunk.next}if(aborted)return true;chunk=chunk.previous}while(chunk);return false}trimEnd(charType){this.trimEndAborted(charType);return this}trimStartAborted(charType){const rx=new RegExp("^"+(charType||"\\s")+"+");this.intro=this.intro.replace(rx,"");if(this.intro.length)return true;let chunk=this.firstChunk;do{const end=chunk.end;const aborted=chunk.trimStart(rx);if(chunk.end!==end){if(chunk===this.lastChunk)this.lastChunk=chunk.next;this.byEnd[chunk.end]=chunk;this.byStart[chunk.next.start]=chunk.next;this.byEnd[chunk.next.end]=chunk.next}if(aborted)return true;chunk=chunk.next}while(chunk);return false}trimStart(charType){this.trimStartAborted(charType);return this}hasChanged(){return this.original!==this.toString()}_replaceRegexp(searchValue,replacement){function getReplacement(match,str){if(typeof replacement==="string"){return replacement.replace(/\$(\$|&|\d+)/g,(_,i)=>{if(i==="$")return"$";if(i==="&")return match[0];const num=+i;if(num<match.length)return match[+i];return`$${i}`})}else{return replacement(...match,match.index,str,match.groups)}}function matchAll(re,str){let match;const matches=[];while(match=re.exec(str)){matches.push(match)}return matches}if(searchValue.global){const matches=matchAll(searchValue,this.original);matches.forEach((match)=>{if(match.index!=null){const replacement=getReplacement(match,this.original);if(replacement!==match[0]){this.overwrite(match.index,match.index+match[0].length,replacement)}}})}else{const match=this.original.match(searchValue);if(match&&match.index!=null){const replacement=getReplacement(match,this.original);if(replacement!==match[0]){this.overwrite(match.index,match.index+match[0].length,replacement)}}}return this}_replaceString(string,replacement){const{original}=this;const index=original.indexOf(string);if(index!==-1){if(typeof replacement==="function"){replacement=replacement(string,index,original)}if(string!==replacement){this.overwrite(index,index+string.length,replacement)}}return this}replace(searchValue,replacement){if(typeof searchValue==="string"){return this._replaceString(searchValue,replacement)}return this._replaceRegexp(searchValue,replacement)}_replaceAllString(string,replacement){const{original}=this;const stringLength=string.length;for(let index=original.indexOf(string);index!==-1;index=original.indexOf(string,index+stringLength)){const previous=original.slice(index,index+stringLength);let _replacement=replacement;if(typeof replacement==="function"){_replacement=replacement(previous,index,original)}if(previous!==_replacement)this.overwrite(index,index+stringLength,_replacement)}return this}replaceAll(searchValue,replacement){if(typeof searchValue==="string"){return this._replaceAllString(searchValue,replacement)}if(!searchValue.global){throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument")}return this._replaceRegexp(searchValue,replacement)}}var stableFrontendChunk=(code,host)=>{const edited=new MagicString(code);for(const match of code.matchAll(/^\/\/#region .*$/gmu)){if(match.index!==undefined){edited.overwrite(match.index,match.index+match[0].length,"//#region")}}if(host==="dashboard"){const scanner=tokenizer(code,{ecmaVersion:"latest",sourceType:"module"});const tokens=[];for(let token=scanner.getToken();token.type.label!=="eof";token=scanner.getToken()){tokens.push(token)}const tokenText=(token)=>token===undefined?undefined:code.slice(token.start,token.end);const importsReactNamespace=tokens.some((token,index)=>token.type.label==="import"&&tokens[index+1]?.type.label==="*"&&tokenText(tokens[index+2])==="as"&&tokenText(tokens[index+3])==="React$1"&&tokenText(tokens[index+4])==="from"&&/^(?:"react"|'react')$/u.test(tokenText(tokens[index+5])??""));if(importsReactNamespace){if(tokens.some((token)=>token.type.label==="name"&&tokenText(token)==="React2")){throw new Error("Hosted React namespace collides with React2")}for(const token of tokens){if(token.type.label==="name"&&tokenText(token)==="React$1"){edited.overwrite(token.start,token.end,"React2")}}}}return{code:edited.toString(),map:edited.generateMap({hires:true,includeContent:true})}};var encoder2=new TextEncoder;var nodePath2=runSync2(provide3(Path2,layer5));var jsonString=encodeSync(fromJsonString2(Unknown2));var writerEffect=(write)=>sync2(write).pipe(flatMap3((result)=>promise2(constant(Promise.resolve(result)))));var viteAssetBytes=(source)=>typeof source==="string"?encoder2.encode(source):source;var digest=(bytes)=>createHash("sha256").update(bytes).digest("hex");var runtimeModuleBytes=(code,host,relativePath)=>encoder2.encode(`${code.trimEnd()}
|
|
293
|
+
`){shouldIndentNextCharacter=true}else if(char!=="\r"&&shouldIndentNextCharacter){shouldIndentNextCharacter=false;if(charIndex===chunk.start){chunk.prependRight(indentStr)}else{this._splitChunk(chunk,charIndex);chunk=chunk.next;chunk.prependRight(indentStr)}}}charIndex+=1}}charIndex=chunk.end;chunk=chunk.next}this.outro=this.outro.replace(pattern,replacer);return this}insert(){throw new Error("magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)")}insertLeft(index,content){if(!warned.insertLeft){console.warn("magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead");warned.insertLeft=true}return this.appendLeft(index,content)}insertRight(index,content){if(!warned.insertRight){console.warn("magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead");warned.insertRight=true}return this.prependRight(index,content)}move(start,end,index){start=start+this.offset;end=end+this.offset;index=index+this.offset;if(index>=start&&index<=end)throw new Error("Cannot move a selection inside itself");this._split(start);this._split(end);this._split(index);const first=this.byStart[start];const last=this.byEnd[end];const oldLeft=first.previous;const oldRight=last.next;const newRight=this.byStart[index];if(!newRight&&last===this.lastChunk)return this;const newLeft=newRight?newRight.previous:this.lastChunk;if(oldLeft)oldLeft.next=oldRight;if(oldRight)oldRight.previous=oldLeft;if(newLeft)newLeft.next=first;if(newRight)newRight.previous=last;if(!first.previous)this.firstChunk=last.next;if(!last.next){this.lastChunk=first.previous;this.lastChunk.next=null}first.previous=newLeft;last.next=newRight||null;if(!newLeft)this.firstChunk=first;if(!newRight)this.lastChunk=last;return this}overwrite(start,end,content,options){options=options||{};return this.update(start,end,content,{...options,overwrite:!options.contentOnly})}update(start,end,content,options){start=start+this.offset;end=end+this.offset;if(typeof content!=="string")throw new TypeError("replacement content must be a string");if(this.original.length!==0){while(start<0)start+=this.original.length;while(end<0)end+=this.original.length}if(end>this.original.length)throw new Error("end is out of bounds");if(start===end)throw new Error("Cannot overwrite a zero-length range \u2013 use appendLeft or prependRight instead");this._split(start);this._split(end);if(options===true){if(!warned.storeName){console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string");warned.storeName=true}options={storeName:true}}const storeName=options!==undefined?options.storeName:false;const overwrite=options!==undefined?options.overwrite:false;if(storeName){const original=this.original.slice(start,end);Object.defineProperty(this.storedNames,original,{writable:true,value:true,enumerable:true})}const first=this.byStart[start];const last=this.byEnd[end];if(first){let chunk=first;while(chunk!==last){if(chunk.next!==this.byStart[chunk.end]){throw new Error("Cannot overwrite across a split point")}chunk=chunk.next;chunk.edit("",false)}first.edit(content,storeName,!overwrite)}else{const newChunk=new Chunk(start,end,"").edit(content,storeName);last.next=newChunk;newChunk.previous=last}return this}prepend(content){if(typeof content!=="string")throw new TypeError("outro content must be a string");this.intro=content+this.intro;return this}prependLeft(index,content){index=index+this.offset;if(typeof content!=="string")throw new TypeError("inserted content must be a string");this._split(index);const chunk=this.byEnd[index];if(chunk){chunk.prependLeft(content)}else{this.intro=content+this.intro}return this}prependRight(index,content){index=index+this.offset;if(typeof content!=="string")throw new TypeError("inserted content must be a string");this._split(index);const chunk=this.byStart[index];if(chunk){chunk.prependRight(content)}else{this.outro=content+this.outro}return this}remove(start,end){start=start+this.offset;end=end+this.offset;if(this.original.length!==0){while(start<0)start+=this.original.length;while(end<0)end+=this.original.length}if(start===end)return this;if(start<0||end>this.original.length)throw new Error("Character is out of bounds");if(start>end)throw new Error("end must be greater than start");this._split(start);this._split(end);let chunk=this.byStart[start];while(chunk){chunk.intro="";chunk.outro="";chunk.edit("");chunk=end>chunk.end?this.byStart[chunk.end]:null}return this}reset(start,end){start=start+this.offset;end=end+this.offset;if(this.original.length!==0){while(start<0)start+=this.original.length;while(end<0)end+=this.original.length}if(start===end)return this;if(start<0||end>this.original.length)throw new Error("Character is out of bounds");if(start>end)throw new Error("end must be greater than start");this._split(start);this._split(end);let chunk=this.byStart[start];while(chunk){chunk.reset();chunk=end>chunk.end?this.byStart[chunk.end]:null}return this}lastChar(){if(this.outro.length)return this.outro[this.outro.length-1];let chunk=this.lastChunk;do{if(chunk.outro.length)return chunk.outro[chunk.outro.length-1];if(chunk.content.length)return chunk.content[chunk.content.length-1];if(chunk.intro.length)return chunk.intro[chunk.intro.length-1]}while(chunk=chunk.previous);if(this.intro.length)return this.intro[this.intro.length-1];return""}lastLine(){let lineIndex=this.outro.lastIndexOf(n);if(lineIndex!==-1)return this.outro.substr(lineIndex+1);let lineStr=this.outro;let chunk=this.lastChunk;do{if(chunk.outro.length>0){lineIndex=chunk.outro.lastIndexOf(n);if(lineIndex!==-1)return chunk.outro.substr(lineIndex+1)+lineStr;lineStr=chunk.outro+lineStr}if(chunk.content.length>0){lineIndex=chunk.content.lastIndexOf(n);if(lineIndex!==-1)return chunk.content.substr(lineIndex+1)+lineStr;lineStr=chunk.content+lineStr}if(chunk.intro.length>0){lineIndex=chunk.intro.lastIndexOf(n);if(lineIndex!==-1)return chunk.intro.substr(lineIndex+1)+lineStr;lineStr=chunk.intro+lineStr}}while(chunk=chunk.previous);lineIndex=this.intro.lastIndexOf(n);if(lineIndex!==-1)return this.intro.substr(lineIndex+1)+lineStr;return this.intro+lineStr}slice(start=0,end=this.original.length-this.offset){start=start+this.offset;end=end+this.offset;if(this.original.length!==0){while(start<0)start+=this.original.length;while(end<0)end+=this.original.length}let result="";let chunk=this.firstChunk;while(chunk&&(chunk.start>start||chunk.end<=start)){if(chunk.start<end&&chunk.end>=end){return result}chunk=chunk.next}if(chunk&&chunk.edited&&chunk.start!==start)throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);const startChunk=chunk;while(chunk){if(chunk.intro&&(startChunk!==chunk||chunk.start===start)){result+=chunk.intro}const containsEnd=chunk.start<end&&chunk.end>=end;if(containsEnd&&chunk.edited&&chunk.end!==end)throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);const sliceStart=startChunk===chunk?start-chunk.start:0;const sliceEnd=containsEnd?chunk.content.length+end-chunk.end:chunk.content.length;result+=chunk.content.slice(sliceStart,sliceEnd);if(chunk.outro&&(!containsEnd||chunk.end===end)){result+=chunk.outro}if(containsEnd){break}chunk=chunk.next}return result}snip(start,end){const clone=this.clone();clone.remove(0,start);clone.remove(end,clone.original.length);return clone}_split(index){if(this.byStart[index]||this.byEnd[index])return;let chunk=this.lastSearchedChunk;let previousChunk=chunk;const searchForward=index>chunk.end;while(chunk){if(chunk.contains(index))return this._splitChunk(chunk,index);chunk=searchForward?this.byStart[chunk.end]:this.byEnd[chunk.start];if(chunk===previousChunk)return;previousChunk=chunk}}_splitChunk(chunk,index){if(chunk.edited&&chunk.content.length){const loc=getLocator(this.original)(index);throw new Error(`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} \u2013 "${chunk.original}")`)}const newChunk=chunk.split(index);this.byEnd[index]=chunk;this.byStart[index]=newChunk;this.byEnd[newChunk.end]=newChunk;if(chunk===this.lastChunk)this.lastChunk=newChunk;this.lastSearchedChunk=chunk;return true}toString(){let str=this.intro;let chunk=this.firstChunk;while(chunk){str+=chunk.toString();chunk=chunk.next}return str+this.outro}isEmpty(){let chunk=this.firstChunk;do{if(chunk.intro.length&&chunk.intro.trim()||chunk.content.length&&chunk.content.trim()||chunk.outro.length&&chunk.outro.trim())return false}while(chunk=chunk.next);return true}length(){let chunk=this.firstChunk;let length=0;do{length+=chunk.intro.length+chunk.content.length+chunk.outro.length}while(chunk=chunk.next);return length}trimLines(){return this.trim("[\\r\\n]")}trim(charType){return this.trimStart(charType).trimEnd(charType)}trimEndAborted(charType){const rx=new RegExp((charType||"\\s")+"+$");this.outro=this.outro.replace(rx,"");if(this.outro.length)return true;let chunk=this.lastChunk;do{const end=chunk.end;const aborted=chunk.trimEnd(rx);if(chunk.end!==end){if(this.lastChunk===chunk){this.lastChunk=chunk.next}this.byEnd[chunk.end]=chunk;this.byStart[chunk.next.start]=chunk.next;this.byEnd[chunk.next.end]=chunk.next}if(aborted)return true;chunk=chunk.previous}while(chunk);return false}trimEnd(charType){this.trimEndAborted(charType);return this}trimStartAborted(charType){const rx=new RegExp("^"+(charType||"\\s")+"+");this.intro=this.intro.replace(rx,"");if(this.intro.length)return true;let chunk=this.firstChunk;do{const end=chunk.end;const aborted=chunk.trimStart(rx);if(chunk.end!==end){if(chunk===this.lastChunk)this.lastChunk=chunk.next;this.byEnd[chunk.end]=chunk;this.byStart[chunk.next.start]=chunk.next;this.byEnd[chunk.next.end]=chunk.next}if(aborted)return true;chunk=chunk.next}while(chunk);return false}trimStart(charType){this.trimStartAborted(charType);return this}hasChanged(){return this.original!==this.toString()}_replaceRegexp(searchValue,replacement){function getReplacement(match,str){if(typeof replacement==="string"){return replacement.replace(/\$(\$|&|\d+)/g,(_,i)=>{if(i==="$")return"$";if(i==="&")return match[0];const num=+i;if(num<match.length)return match[+i];return`$${i}`})}else{return replacement(...match,match.index,str,match.groups)}}function matchAll(re,str){let match;const matches=[];while(match=re.exec(str)){matches.push(match)}return matches}if(searchValue.global){const matches=matchAll(searchValue,this.original);matches.forEach((match)=>{if(match.index!=null){const replacement=getReplacement(match,this.original);if(replacement!==match[0]){this.overwrite(match.index,match.index+match[0].length,replacement)}}})}else{const match=this.original.match(searchValue);if(match&&match.index!=null){const replacement=getReplacement(match,this.original);if(replacement!==match[0]){this.overwrite(match.index,match.index+match[0].length,replacement)}}}return this}_replaceString(string,replacement){const{original}=this;const index=original.indexOf(string);if(index!==-1){if(typeof replacement==="function"){replacement=replacement(string,index,original)}if(string!==replacement){this.overwrite(index,index+string.length,replacement)}}return this}replace(searchValue,replacement){if(typeof searchValue==="string"){return this._replaceString(searchValue,replacement)}return this._replaceRegexp(searchValue,replacement)}_replaceAllString(string,replacement){const{original}=this;const stringLength=string.length;for(let index=original.indexOf(string);index!==-1;index=original.indexOf(string,index+stringLength)){const previous=original.slice(index,index+stringLength);let _replacement=replacement;if(typeof replacement==="function"){_replacement=replacement(previous,index,original)}if(previous!==_replacement)this.overwrite(index,index+stringLength,_replacement)}return this}replaceAll(searchValue,replacement){if(typeof searchValue==="string"){return this._replaceAllString(searchValue,replacement)}if(!searchValue.global){throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument")}return this._replaceRegexp(searchValue,replacement)}}var stableFrontendChunk=(code,host)=>{const edited=new MagicString(code);for(const match of code.matchAll(/^\/\/#region .*$/gmu)){if(match.index!==undefined){edited.overwrite(match.index,match.index+match[0].length,"//#region")}}if(host==="dashboard"){const scanner=tokenizer(code,{ecmaVersion:"latest",sourceType:"module"});const tokens=[];for(let token=scanner.getToken();token.type.label!=="eof";token=scanner.getToken()){tokens.push(token)}const tokenText=(token)=>token===undefined?undefined:code.slice(token.start,token.end);const importsReactNamespace=tokens.some((token,index)=>token.type.label==="import"&&tokens[index+1]?.type.label==="*"&&tokenText(tokens[index+2])==="as"&&tokenText(tokens[index+3])==="React$1"&&tokenText(tokens[index+4])==="from"&&/^(?:"react"|'react')$/u.test(tokenText(tokens[index+5])??""));if(importsReactNamespace){if(tokens.some((token)=>token.type.label==="name"&&tokenText(token)==="React2")){throw new Error("Hosted React namespace collides with React2")}for(const token of tokens){if(token.type.label==="name"&&tokenText(token)==="React$1"){edited.overwrite(token.start,token.end,"React2")}}}}return{code:edited.toString(),map:edited.generateMap({hires:true,includeContent:true})}};import{createHash}from"crypto";class PackageMediaBuildError extends TaggedError3()("PackageMediaBuildError",{mediaPath:String4,message:String4,reason:Literals(["missing","oversize"])}){}var nodePath2=runSync2(provide3(Path2,layer5));var brandingKeys=["cover","icon","logo"];var mediaDirectory="media/";var archivePathOf=(mediaPath)=>`${PackageMediaArchivePrefix}${mediaPath.slice(mediaDirectory.length)}`;var packageMediaPaths=(definition)=>{const paths=new Set;for(const primitive of definition.manifest.primitives){if(primitive.kind!=="organizationSettings"){continue}const{branding}=primitive;if(branding===undefined||isVariableReference(branding)){continue}for(const key of brandingKeys){const reference=branding[key];if(reference!==undefined&&!isVariableReference(reference)&&!isVariableReference(reference.media)){paths.add(reference.media)}}}return[...paths].toSorted(compareCanonicalText)};var packPackageMedia=(files)=>gen2(function*packPackageMediaEffect(){const sorted=files.toSorted((left,right)=>compareCanonicalText(left.mediaPath,right.mediaPath));const entries=[];const media=[];for(const file of sorted){if(file.bytes.byteLength>PACKAGE_MEDIA_SIZE_LIMIT_BYTES){return yield*new PackageMediaBuildError({mediaPath:file.mediaPath,message:`Package Media '${file.mediaPath}' is ${file.bytes.byteLength} bytes; the limit is ${PACKAGE_MEDIA_SIZE_LIMIT_BYTES} bytes`,reason:"oversize"})}const path=archivePathOf(file.mediaPath);entries.push({bytes:file.bytes,path});media.push({digest:createHash("sha256").update(file.bytes).digest("hex"),path,size:file.bytes.byteLength})}return{entries,media}});var readPackageMedia=(input)=>gen2(function*readPackageMediaEffect(){const files=[];for(const mediaPath of packageMediaPaths(input.definition)){const filePath=nodePath2.join(input.directory,mediaPath);const file=Bun.file(filePath);if(!(yield*promise2(file.exists.bind(file)))){return yield*new PackageMediaBuildError({mediaPath,message:`Package Media '${mediaPath}' was not found at ${filePath}`,reason:"missing"})}files.push({bytes:yield*promise2(file.bytes.bind(file)),mediaPath})}return yield*packPackageMedia(files)});var encoder2=new TextEncoder;var nodePath3=runSync2(provide3(Path2,layer5));var jsonString=encodeSync(fromJsonString2(Unknown2));var writerEffect=(write)=>sync2(write).pipe(flatMap3((result)=>promise2(constant(Promise.resolve(result)))));var viteAssetBytes=(source)=>typeof source==="string"?encoder2.encode(source):source;var digest=(bytes)=>createHash2("sha256").update(bytes).digest("hex");var runtimeModuleBytes=(code,host,relativePath)=>encoder2.encode(`${code.trimEnd()}
|
|
294
294
|
//# sourceURL=extension://${host}/${encodeURIComponent(relativePath)}
|
|
295
|
-
`);var moduleExport=(exportName)=>{if(!/^[$A-Z_a-z][$\w]*$/u.test(exportName)){throw new TypeError(`Hosted Contribution export '${exportName}' is not a JavaScript identifier`)}return exportName};var sanitizeSourceMap=(sourceMapText,assetName)=>{const parsed=decodeSync(fromJsonString2(Unknown2))(sourceMapText);if(parsed===null||typeof parsed!=="object"||!("sources"in parsed)||!Array.isArray(parsed.sources)||!("sourcesContent"in parsed)||!Array.isArray(parsed.sourcesContent)||parsed.sources.length!==parsed.sourcesContent.length){throw new Error(`Build emitted an invalid private source map for ${assetName}`)}if(parsed.sources.length===0){return}const stableFields=Object.fromEntries(Object.entries(parsed).filter(([key])=>key!=="debugId"));return encoder2.encode(jsonString({...stableFields,file:assetName,sourceRoot:"",sources:parsed.sources.map((_source,index)=>`extension://release/${encodeURIComponent(assetName)}/source-${index}.ts`)}))};var contributionIdentities=(definition,host)=>definition.hostedContributions.flatMap(({load,manifest})=>manifest.host===host?[{exportName:manifest.exportName,fqn:manifest.fqn,host,load}]:[]);var buildBackend=flow((input)=>gen2(function*buildBackendEffect(){const packageEntry=backendPackageEntry(input.definition);const identities=[...contributionIdentities(input.definition,"backend"),...packageEntry===undefined?[]:[packageEntry]];if(identities.length===0){return[]}const entrypoints=identities.map((_identity,index)=>`ci-release-backend-entry-${index}`);const entryByPath=new Map(entrypoints.map((entrypoint,index)=>[entrypoint,identities[index]]));const result=yield*tryPromise2(Bun.build.bind(Bun,{...workspaceSourceResolve(process.execArgv),define:{"process.env.NODE_ENV":jsonString("production")},entrypoints,external:[...hostProvidedModulesFor("backend")],format:"esm",minify:{identifiers:false,syntax:true,whitespace:true},naming:{asset:"assets/[name]-[hash].[ext]",chunk:"chunks/[name]-[hash].mjs",entry:"modules/[name].mjs"},plugins:[{name:"ci-release-backend-entries",setup(builder){builder.onResolve({filter:/^ci-package-declaration$/u},()=>({path:backendPackageModulePath(input.declarationSpecifier,input.definition)}));builder.onResolve({filter:/^ci-release-backend-entry-/u},(args)=>({namespace:"ci-release-backend-entry",path:args.path}));builder.onLoad({filter:/.*/u,namespace:"ci-release-backend-entry"},(args)=>{const identity=entryByPath.get(args.path);if(identity===undefined){throw new Error(`Unknown Backend release entry '${args.path}'`)}if(!("load"in identity)){return{contents:backendPackageEntrySource(input.definition.manifest.fqn),loader:"ts"}}const contributionImport=resolveHostedContributionEntry(input.declarationSpecifier,identity);return{contents:`export { ${moduleExport(identity.exportName)} } from ${jsonString(contributionImport)}`,loader:"ts"}})}}],sourcemap:"external",splitting:true,target:"bun"}));if(!result.success){throw new AggregateError(result.logs,"Failed to build Backend release assets")}const outputByName=new Map(result.outputs.map((artifact)=>[nodePath2.basename(artifact.path),artifact]));const runtimeFiles=[];for(const artifact of result.outputs.filter(({path})=>!path.endsWith(".map"))){runtimeFiles.push(yield*gen2(function*readBackendArtifact(){const relativePath=artifact.path.replace(/^\.\//u,"").replace(/^\/+/u,"");const rawCode=yield*tryPromise2(artifact.text.bind(artifact));const code=rawCode.replaceAll(/\/\/# (?:debugId|sourceMappingURL)=.*$/gmu,"");const bytes=runtimeModuleBytes(code,"backend",relativePath);const mapArtifact=outputByName.get(`${nodePath2.basename(artifact.path)}.map`);const entryMatch=/^ci-release-backend-entry-(?<index>\d+)\.mjs$/u.exec(nodePath2.basename(artifact.path));const contributionFqn=entryMatch?.groups?.index===undefined?undefined:identities[Number(entryMatch.groups.index)]?.fqn;const sourceMapBytes=mapArtifact===undefined?undefined:sanitizeSourceMap(yield*tryPromise2(mapArtifact.text.bind(mapArtifact)),relativePath);return{bytes,...contributionFqn===undefined?undefined:{contributionFqn},host:"backend",path:`artifacts/backend/${relativePath}`,...sourceMapBytes===undefined?undefined:{sourceMapBytes}}}))}return runtimeFiles}),runPromise2);var viteOutputList=(output)=>{if(!Array.isArray(output)&&"close"in output){throw new Error("Vite unexpectedly returned a watcher for a release build")}return Array.isArray(output)?output:[output]};var buildFrontend=flow((input)=>gen2(function*buildFrontendEffect(){const identities=contributionIdentities(input.definition,input.host);if(identities.length===0){return[]}const entries=new Map;const entryNames={};for(const[index,identity]of identities.entries()){const id=`virtual:ci-release-${input.host}-entry-${index}`;const contributionImport=resolveHostedContributionEntry(input.declarationSpecifier,identity);entries.set(`\x00${id}`,{contributionImport,identity,source:`export { ${moduleExport(identity.exportName)} } from ${jsonString(contributionImport)}; export * from ${jsonString(contributionImport)}`});entryNames[`contribution-${index}`]=id}const virtualEntries={load:flow(function loadFrontendEntry(id){const resolve=this.resolve.bind(this);return gen2(function*loadFrontendEntryEffect(){const entry=entries.get(id);if(entry===undefined){return null}const resolved=yield*promise2(flow(constant(entry.contributionImport),resolve));if(resolved===null){return yield*die3(new Error(`Frontend catalog module could not be resolved: ${entry.contributionImport}`))}const file=Bun.file(resolved.id);const source=yield*promise2(file.text.bind(file));const{exports}=new Bun.Transpiler({loader:/\.[jt]sx$/u.test(resolved.id)?"tsx":"ts"}).scan(source);return exports.includes("default")?`${entry.source}; export { default } from ${jsonString(entry.contributionImport)}`:entry.source})},runPromise2),name:"ci-hosted-release-entries",resolveId:(id)=>id.startsWith("virtual:ci-release-")?`\x00${id}`:null};const stableRegionLabels={name:"ci-hosted-release-stable-region-labels",renderChunk:(code)=>stableFrontendChunk(code,input.host)};const hostReactRequireId="\x00virtual:ci-host-react-require";const hostReactRequire={enforce:"pre",load:(id)=>id===hostReactRequireId?'import React from "react"; module.exports = React;':null,name:"ci-host-react-require",resolveId:{handler:(source,_importer,options)=>source==="react"&&options.kind==="require-call"?hostReactRequireId:null,order:"pre"}};const output=yield*tryPromise2(viteBuild.bind(undefined,{build:{assetsInlineLimit:0,cssCodeSplit:true,emptyOutDir:false,minify:false,modulePreload:false,rolldownOptions:{input:entryNames,output:{assetFileNames:"assets/[name]-[hash][extname]",chunkFileNames:"chunks/[name]-[hash].mjs",entryFileNames:"modules/[name].mjs"},preserveEntrySignatures:"strict"},sourcemap:"hidden",target:"esnext",write:false},configFile:false,define:{"process.env.NODE_ENV":jsonString("production")},logLevel:"silent",mode:"production",oxc:{jsx:{development:false}},plugins:[virtualEntries,hostReactRequire,esmExternalRequirePlugin({external:[...hostProvidedModulesFor(input.host)]}),stableRegionLabels],resolve:workspaceSourceResolve(process.execArgv),root:process.cwd(),ssr:workspaceSourceSsrResolve(process.execArgv)})).pipe(catch_2((error)=>die3(error.cause instanceof Error?error.cause:new Error("Frontend catalog build failed",{cause:error.cause}))));const files=[];for(const result of viteOutputList(output)){for(const artifact of result.output){if(artifact.type==="asset"){if(!artifact.fileName.endsWith(".map")){files.push({bytes:viteAssetBytes(artifact.source),host:input.host,path:`artifacts/${input.host}/${artifact.fileName}`})}continue}const entry=artifact.facadeModuleId===null?undefined:entries.get(artifact.facadeModuleId);const sourceMapBytes=artifact.map===null?undefined:sanitizeSourceMap(artifact.map.toString(),artifact.fileName);files.push({bytes:runtimeModuleBytes(artifact.code,input.host,artifact.fileName),...entry===undefined?undefined:{contributionFqn:entry.identity.fqn},host:input.host,path:`artifacts/${input.host}/${artifact.fileName}`,...sourceMapBytes===undefined?undefined:{sourceMapBytes}})}}return files}),runPromise2);var mergeCompatibility=(definition)=>{const compatibility={};for(const{manifest}of definition.hostedContributions){for(const[runtime,range]of Object.entries(manifest.compatibility??{})){const existing=compatibility[runtime];if(existing!==undefined&&existing!==range){throw new TypeError(`Hosted Contributions declare conflicting ${runtime} compatibility ranges`)}compatibility[runtime]=range}}return Object.fromEntries(Object.entries(compatibility).toSorted(([left],[right])=>compareCanonicalText(left,right)))};var buildPackageRelease=flow((input)=>gen2(function*buildPackageReleaseEffect(){const definitions=yield*promise2(loadPackageDeclarations.bind(undefined,input.declarationSpecifier));if(definitions.length!==1){throw new TypeError("An Extension Release build requires exactly one package")}const[definition]=definitions;if(definition===undefined){throw new TypeError("Extension Package declaration was not found")}const hostFiles=yield*all2([promise2(buildBackend.bind(undefined,{declarationSpecifier:input.declarationSpecifier,definition})),...FRONTEND_HOSTS.map((host)=>promise2(buildFrontend.bind(undefined,{declarationSpecifier:input.declarationSpecifier,definition,host})))]);const files=hostFiles.flat();const assets=[];const privateSourceMaps=[];const privateMapByRuntimeDigest=new Map;for(const file of files){const runtimeDigest=digest(file.bytes);const sourceMap=file.sourceMapBytes;const privateSourceMap=sourceMap===undefined?undefined:{digest:digest(sourceMap),size:sourceMap.byteLength};assets.push({digest:runtimeDigest,host:file.host,path:file.path,...privateSourceMap===undefined?undefined:{privateSourceMap},size:file.bytes.byteLength});if(sourceMap!==undefined&&privateSourceMap!==undefined){const existing=privateMapByRuntimeDigest.get(runtimeDigest);if(existing!==undefined&&existing.digest!==privateSourceMap.digest){throw new Error(`Runtime asset '${runtimeDigest}' produced conflicting private source maps`)}if(existing===undefined){const sidecar={bytes:sourceMap,digest:privateSourceMap.digest,runtimeAssetDigest:runtimeDigest,size:privateSourceMap.size};privateMapByRuntimeDigest.set(runtimeDigest,sidecar);privateSourceMaps.push(sidecar)}}}const assetByPath=new Map(assets.map((asset)=>[asset.path,asset]));const pathByContribution=new Map(files.flatMap((file)=>file.contributionFqn===undefined?[]:[[`${file.host}:${file.contributionFqn}`,file.path]]));const contributions=backendArtifactContributions(definition).map((contribution)=>{const assetPath=pathByContribution.get(`${contribution.host}:${contribution.fqn}`);const asset=assetPath===undefined?undefined:assetByPath.get(assetPath);if(asset===undefined||assetPath===undefined){throw new Error(`No release entry asset was built for ${contribution.fqn}`)}const common={assetPath,digest:asset.digest,exportName:contribution.exportName,fqn:contribution.fqn,size:asset.size};return contribution.host==="backend"?{...common,...contribution.contract===undefined?undefined:{contract:contribution.contract},...contribution.execution===undefined?undefined:{execution:contribution.execution},exportName:contribution.exportName,host:contribution.host}:{...common,contract:contribution.contract,exportName:contribution.exportName,host:contribution.host}});const packageManifestBytes=encoder2.encode(canonicalPackageManifest(definition));const archiveBytes=createExtensionReleaseArchive([...files.map(({bytes,path})=>({bytes,path})),{bytes:packageManifestBytes,path:"package-manifest.json"}]);const releaseDigest=digest(archiveBytes);const manifest={apiVersion:"v2",assets:assets.toSorted((left,right)=>compareCanonicalText(left.path,right.path)),compatibility:mergeCompatibility(definition),contributions:contributions.toSorted((left,right)=>compareCanonicalText(left.host,right.host)||compareCanonicalText(left.fqn,right.fqn)),package:{fqn:definition.manifest.fqn,version:definition.manifest.version},packageManifest:definition.manifest,releaseDigest};return{archiveBytes,manifest,manifestBytes:encoder2.encode(canonicalExtensionReleaseManifest(manifest)),packageManifest:definition.manifest,packageManifestBytes,privateSourceMaps:privateSourceMaps.toSorted((left,right)=>compareCanonicalText(left.runtimeAssetDigest,right.runtimeAssetDigest)),releaseDigest}}),runPromise2);var materializePackageRelease=flow((input,dependencies)=>gen2(function*materializePackageReleaseEffect(){const release=yield*promise2(buildPackageRelease.bind(undefined,{declarationSpecifier:input.declarationSpecifier}));const privateMapDirectory=nodePath2.join(input.outputDirectory,"private-source-maps");yield*writerEffect(dependencies.makeDirectory.bind(dependencies,privateMapDirectory));yield*all2([writerEffect(dependencies.writeBytes.bind(dependencies,nodePath2.join(input.outputDirectory,"release.tar"),release.archiveBytes)),writerEffect(dependencies.writeBytes.bind(dependencies,nodePath2.join(input.outputDirectory,"manifest.json"),release.manifestBytes)),writerEffect(dependencies.writeBytes.bind(dependencies,nodePath2.join(input.outputDirectory,"package-manifest.json"),release.packageManifestBytes)),...release.privateSourceMaps.map((sourceMap)=>writerEffect(dependencies.writeBytes.bind(dependencies,nodePath2.join(privateMapDirectory,`${sourceMap.runtimeAssetDigest}.map`),sourceMap.bytes)))]);return{archive:nodePath2.join(input.outputDirectory,"release.tar"),manifest:nodePath2.join(input.outputDirectory,"manifest.json"),packageManifest:nodePath2.join(input.outputDirectory,"package-manifest.json"),privateSourceMaps:privateMapDirectory,releaseDigest:release.releaseDigest}}),runPromise2);var optionValue3=(args,name)=>{const index=args.lastIndexOf(`--${name}`);const value=index===-1?undefined:args[index+1];if(value===undefined||value===""){throw new TypeError(`Missing option --${name}`)}return value};var runPackageBuildCommand=flow((args,dependencies)=>gen2(function*runPackageBuildCommandEffect(){const outputDirectory=optionValue3(args,"out");const release=yield*promise2(materializePackageRelease.bind(undefined,{declarationSpecifier:dependencies.resolveDeclarationSpecifier(optionValue3(args,"declaration")),outputDirectory},dependencies));return yield*encodeEffect(fromJsonString2(Unknown2))({archive:release.archive,manifest:release.manifest,packageManifest:release.packageManifest,privateSourceMaps:release.privateSourceMaps,releaseDigest:release.releaseDigest})}),runPromise2);class EventStreamHttpError extends Error{status;constructor(status,statusText){super(`Event stream request failed with HTTP ${status} ${statusText}`.trimEnd());this.name="EventStreamHttpError";this.status=status}}var singleConnectionSseOptions={onSseError:(cause)=>{throw cause},sseMaxRetryAttempts:1};var eventStreamFetch=(fetch2=globalThis.fetch)=>Object.assign(async(input,init)=>{const response=await fetch2(input,init);if(!response.ok){throw new EventStreamHttpError(response.status,response.statusText)}return response},{preconnect:()=>{}});var isRetryableEventStreamError=(cause)=>!(cause instanceof EventStreamHttpError)||cause.status>=500||cause.status===408||cause.status===425||cause.status===429;class EventStreamRetriesExhaustedError extends Error{attempts;lastEventId;constructor(input){super(input.cause===undefined?"Event stream kept closing without progress":"Event stream kept failing without progress",{cause:input.cause});this.name="EventStreamRetriesExhaustedError";this.attempts=input.attempts;this.lastEventId=input.lastEventId}}var DEFAULT_INITIAL_RETRY_DELAY_MS=1000;var DEFAULT_MAX_RETRY_DELAY_MS=30000;var DEFAULT_MIN_HEALTHY_CONNECTION_MS=30000;var abortableSleep=async(milliseconds,signal)=>{if(signal.aborted){return}await new Promise((resolve)=>{const settled=new AbortController;const timeout=globalThis.setTimeout(()=>{settled.abort();resolve()},milliseconds);signal.addEventListener("abort",()=>{globalThis.clearTimeout(timeout);resolve()},{once:true,signal:settled.signal})})};var asError=(cause)=>cause instanceof Error?cause:new Error(String(cause),{cause});var followEventStream=async(options)=>{const signal=options.signal??new AbortController().signal;const sleep=options.sleep??abortableSleep;const initialDelay=options.initialRetryDelayMs??DEFAULT_INITIAL_RETRY_DELAY_MS;const maxDelay=options.maxRetryDelayMs??DEFAULT_MAX_RETRY_DELAY_MS;const minHealthyConnectionMs=options.minHealthyConnectionMs??DEFAULT_MIN_HEALTHY_CONNECTION_MS;const now=options.now??Date.now;let{lastEventId}=options;let attempt=0;while(!signal.aborted){const connection=new AbortController;const stopConnection=()=>{connection.abort()};signal.addEventListener("abort",stopConnection,{once:true});let terminal=false;let failure;const openedAt=now();try{const events=await options.connect({lastEventId,signal:connection.signal});for await(const event of events){await options.onEvent(event);const nextEventId=options.eventId===undefined?lastEventId:options.eventId(event);if(options.eventId===undefined||nextEventId!==lastEventId){attempt=0}lastEventId=nextEventId;if(options.isTerminal?.(event)===true){terminal=true;break}}}catch(error){failure=asError(error)}finally{signal.removeEventListener("abort",stopConnection);connection.abort()}if(terminal){return{lastEventId,reason:"terminal"}}if(signal.aborted){break}if(failure!==undefined&&options.isRetryableError!==undefined&&!options.isRetryableError(failure)){throw failure}if(failure===undefined&&now()-openedAt>=minHealthyConnectionMs){attempt=0}attempt+=1;if(options.maxRetries!==undefined&&attempt>options.maxRetries){throw new EventStreamRetriesExhaustedError({attempts:attempt,cause:failure,lastEventId})}const delayMs=Math.min(initialDelay*2**(attempt-1),maxDelay);options.onReconnect?.({attempt,cause:failure,delayMs,lastEventId});await sleep(delayMs,signal)}return{lastEventId,reason:"aborted"}};var awaitValue=(value)=>promise2(constant(Promise.resolve(value)));var encodeJson3=encodeSync(fromJsonString2(Unknown2));class PackageOperationCommandError extends TaggedError3()("PackageOperationCommandError",{cause:optional2(Unknown2),message:String4}){}var requireOption=(options,name)=>{const value=options.get(name);if(value===undefined||value===""){throw new PackageOperationCommandError({message:`Missing required option --${name}`})}return value};var parseOptions=(args)=>{const options=new Map;for(let index=1;index<args.length;index+=2){const flag=args[index];const value=args[index+1];if(!flag?.startsWith("--")||!value||value.startsWith("--")){throw new PackageOperationCommandError({message:"Options must be supplied as --name value pairs"})}options.set(flag.slice(2),value)}return options};var isPackageOperationComplete=(status)=>status!=="pending"&&status!=="running";var parseLastEventId=(options)=>{const value=options.get("last-event-id")??"0";if(!/^\d+$/u.test(value)){throw new PackageOperationCommandError({message:"--last-event-id must be a non-negative event sequence"})}const sequence=Number(value);if(!Number.isSafeInteger(sequence)){throw new PackageOperationCommandError({message:"--last-event-id must be a non-negative event sequence"})}return sequence};var fetchSnapshot=flow((dependencies,organizationId,operationId,signal)=>gen2(function*nativeAssetStep1(){const request={client:dependencies.client,headers:{"x-organization-id":organizationId},path:{operationId},throwOnError:true};if(signal!==undefined){request.signal=signal}const response=yield*awaitValue(packageOperationsSnapshot(request));return decodePackageOperationSnapshot(response.data)}),runPromise2);var executeSnapshot=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageOperationCommandError)(cause)?cause:new PackageOperationCommandError({cause,message:"Could not inspect package operation"}),try:async()=>({kind:"snapshot",snapshot:await fetchSnapshot(dependencies,requireOption(options,"organization"),requireOption(options,"operation"))})});var executeContinuation=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageOperationCommandError)(cause)?cause:new PackageOperationCommandError({cause,message:"Could not continue package operation"}),try:async()=>{const accepted=await packageOperationsContinueOperation({client:dependencies.client,headers:{"idempotency-key":requireOption(options,"idempotency-key"),"x-organization-id":requireOption(options,"organization")},path:{operationId:requireOption(options,"operation")},throwOnError:true});return{kind:"operation_accepted",operationId:accepted.data.operationId}}});var MAX_RECONNECTS_WITHOUT_PROGRESS=3;var isCommandError=is2(PackageOperationCommandError);var decodeOperationEvent=(wireEvent)=>{try{return decodePackageOperationEvent(encodeJson3(wireEvent))}catch(error){throw new PackageOperationCommandError({cause:error,message:"Package operation event did not match the Backend contract"})}};var followPackageOperationEffect=(input,dependencies)=>tryPromise2({catch:(cause)=>isCommandError(cause)?cause:new PackageOperationCommandError({cause,message:"Could not reconnect to package operation"}),try:async(signal)=>{let lastSequence=input.afterSequence??0;const{operationId,organizationId}=input;const snapshot=await fetchSnapshot(dependencies,organizationId,operationId,signal);if(isPackageOperationComplete(snapshot.status)&&(input.replay!==true||lastSequence>=snapshot.lastEventSequence)){return{kind:"snapshot",snapshot}}let lastEventId=input.afterSequence===undefined?undefined:String(lastSequence);let observed;try{await followEventStream({connect:async(connection)=>{const events=await packageOperationsEvents({...singleConnectionSseOptions,client:dependencies.client,fetch:eventStreamFetch(dependencies.client.getConfig().fetch),headers:{...connection.lastEventId===undefined?undefined:{"last-event-id":connection.lastEventId},"x-organization-id":organizationId},path:{operationId},signal:connection.signal,throwOnError:true});return events.stream},eventId:()=>lastEventId,isRetryableError:(error)=>!isCommandError(error)&&isRetryableEventStreamError(error),isTerminal:()=>observed!==undefined&&observed.sequence===lastSequence&&isPackageOperationComplete(observed.status),...lastEventId===undefined?undefined:{lastEventId},maxRetries:MAX_RECONNECTS_WITHOUT_PROGRESS,onEvent:(wireEvent)=>{const event=decodeOperationEvent(wireEvent);observed=event;if(event.sequence<=lastSequence){return}if(event.sequence!==lastSequence+1){throw new PackageOperationCommandError({message:`Package operation event sequence jumped from ${lastSequence} to ${event.sequence}`})}dependencies.writeEvent(encodeJson3(event));lastSequence=event.sequence;lastEventId=String(event.sequence)},signal,...dependencies.sleep===undefined?undefined:{sleep:dependencies.sleep}})}catch(error){if(error instanceof EventStreamHttpError){throw new PackageOperationCommandError({cause:error,message:`Package operation event stream was rejected with HTTP ${error.status}`})}if(error instanceof EventStreamRetriesExhaustedError){throw new PackageOperationCommandError({cause:error.cause??error,message:`Package operation event stream disconnected; reconnect with --last-event-id ${lastSequence}`})}throw error}return{kind:"snapshot",snapshot:await fetchSnapshot(dependencies,organizationId,operationId,signal)}}});var packageOperationCommandEffect=(args,dependencies)=>{const[command]=args;const options=parseOptions(args);if(command==="continue"){return executeContinuation(options,dependencies)}if(command==="reconnect"){return followPackageOperationEffect({afterSequence:options.has("last-event-id")?parseLastEventId(options):undefined,operationId:requireOption(options,"operation"),organizationId:requireOption(options,"organization"),replay:true},dependencies)}if(command==="snapshot"){return executeSnapshot(options,dependencies)}return fail6(new PackageOperationCommandError({message:"Expected one of: package operation snapshot, package operation reconnect, package operation continue"}))};var renderPin=(pin)=>`${pin.fqn}@${pin.releaseId}`;var renderSelection=(selection)=>selection===null?"none":`${selection.releaseId} generation ${selection.generation}`;var renderBlocker=(blocker)=>{if(blocker._tag==="manual_prerequisite"){const observed=blocker.observed===null?"none":renderPin(blocker.observed);return`Blocker ManualPrerequisite: ${blocker.message}; requires ${renderPin(blocker.required)}, observed ${observed}; path ${blocker.path.map(renderPin).join(" -> ")}`}let label=blocker._tag;if(blocker._tag==="authority_denied"){label=`AuthorityDenied (${blocker.boundary})`}else if(blocker._tag==="unknown"){label=blocker.tag}const details=[blocker.message,..."definitions"in blocker?[`definitions ${blocker.definitions.map((definition)=>`${definition.kind} ${definition.fqn}`).join(", ")}`]:[],...blocker.paths.map((path)=>`path ${path.join(" -> ")}`)];return`Blocker ${label}: ${details.join("; ")}`};var renderProtection=(protection)=>{if(protection.kind==="required_by"){return`requiredBy ${renderPin(protection.dependent)} (${protection.protection})`}if(protection.kind==="unknown_requirement"){return`unknownRequirement ${renderPin(protection.dependent)}`}if(protection.kind==="workflow_use"){const{template}=protection;return`workflowUse ${protection.workflowId} (${protection.state}, template ${template.fqn}@${template.version})`}if(protection.kind==="live_binding"){return`liveBinding ${protection.bindingKind} ${protection.id}`}return protection.kind};var renderCleanupCandidate=(candidate)=>{const subject=`Cleanup ${candidate.packageFqn}@${candidate.releaseId} (${candidate.installationId}) ${candidate.result}`;const protections=candidate.protections??[];return protections.length===0?`${subject}.`:`${subject}: ${protections.map(renderProtection).join("; ")}.`};var renderCleanup=(cleanup)=>[`Cleanup ${cleanup.state}.`,...cleanup.candidates.map(renderCleanupCandidate)];var renderHost=(host,snapshot)=>{const{member,observed}=host;const outcome=`Host ${member.packageFqn} (${member.installationId}) ${host.result}: expected ${member.releaseId} generation ${member.generation}; observed Desired ${renderSelection(observed.desired)}, Serving ${renderSelection(observed.serving)}.`;return host.diagnosticId===undefined?outcome:`${outcome} Diagnostic ID ${host.diagnosticId}: ci package diagnostics trace --organization ${snapshot.organizationId} --diagnostic ${host.diagnosticId}`};var renderNextAction=(snapshot)=>{const scope=`--organization ${snapshot.organizationId} --operation ${snapshot.id}`;const continueCommand=`ci package operation continue ${scope} --idempotency-key <key>`;const hints={continue:`continue. Start a linked new operation with a new Operation ID: ${continueCommand}`,none:"none.",retry:`retry. Resume this same operation with its accepted plan and Operation ID: ${continueCommand}`,wait:`wait. Follow progress: ci package operation reconnect ${scope} --last-event-id ${snapshot.lastEventSequence}`};return`Next action: ${hints[snapshot.nextAction]}`};var renderPackageOperationSummary=(snapshot)=>{const{application,failure}=snapshot;const lines=[`Package operation ${snapshot.id} is ${snapshot.status}.`,...application.state==="not_applied"&&application.blocker!==undefined?[renderBlocker(application.blocker)]:[],...snapshot.hosts.map((host)=>renderHost(host,snapshot)),...snapshot.cleanup===undefined?[]:renderCleanup(snapshot.cleanup),...failure===undefined?[]:[`Failure ${failure.reason}: ${failure.message}`],renderNextAction(snapshot)];return`${lines.join(`
|
|
295
|
+
`);var moduleExport=(exportName)=>{if(!/^[$A-Z_a-z][$\w]*$/u.test(exportName)){throw new TypeError(`Hosted Contribution export '${exportName}' is not a JavaScript identifier`)}return exportName};var sanitizeSourceMap=(sourceMapText,assetName)=>{const parsed=decodeSync(fromJsonString2(Unknown2))(sourceMapText);if(parsed===null||typeof parsed!=="object"||!("sources"in parsed)||!Array.isArray(parsed.sources)||!("sourcesContent"in parsed)||!Array.isArray(parsed.sourcesContent)||parsed.sources.length!==parsed.sourcesContent.length){throw new Error(`Build emitted an invalid private source map for ${assetName}`)}if(parsed.sources.length===0){return}const stableFields=Object.fromEntries(Object.entries(parsed).filter(([key])=>key!=="debugId"));return encoder2.encode(jsonString({...stableFields,file:assetName,sourceRoot:"",sources:parsed.sources.map((_source,index)=>`extension://release/${encodeURIComponent(assetName)}/source-${index}.ts`)}))};var contributionIdentities=(definition,host)=>definition.hostedContributions.flatMap(({load,manifest})=>manifest.host===host?[{exportName:manifest.exportName,fqn:manifest.fqn,host,load}]:[]);var buildBackend=flow((input)=>gen2(function*buildBackendEffect(){const packageEntry=backendPackageEntry(input.definition);const identities=[...contributionIdentities(input.definition,"backend"),...packageEntry===undefined?[]:[packageEntry]];if(identities.length===0){return[]}const entrypoints=identities.map((_identity,index)=>`ci-release-backend-entry-${index}`);const entryByPath=new Map(entrypoints.map((entrypoint,index)=>[entrypoint,identities[index]]));const result=yield*tryPromise2(Bun.build.bind(Bun,{...workspaceSourceResolve(process.execArgv),define:{"process.env.NODE_ENV":jsonString("production")},entrypoints,external:[...hostProvidedModulesFor("backend")],format:"esm",minify:{identifiers:false,syntax:true,whitespace:true},naming:{asset:"assets/[name]-[hash].[ext]",chunk:"chunks/[name]-[hash].mjs",entry:"modules/[name].mjs"},plugins:[{name:"ci-release-backend-entries",setup(builder){builder.onResolve({filter:/^ci-package-declaration$/u},()=>({path:backendPackageModulePath(input.declarationSpecifier,input.definition)}));builder.onResolve({filter:/^ci-release-backend-entry-/u},(args)=>({namespace:"ci-release-backend-entry",path:args.path}));builder.onLoad({filter:/.*/u,namespace:"ci-release-backend-entry"},(args)=>{const identity=entryByPath.get(args.path);if(identity===undefined){throw new Error(`Unknown Backend release entry '${args.path}'`)}if(!("load"in identity)){return{contents:backendPackageEntrySource(input.definition.manifest.fqn),loader:"ts"}}const contributionImport=resolveHostedContributionEntry(input.declarationSpecifier,identity);return{contents:`export { ${moduleExport(identity.exportName)} } from ${jsonString(contributionImport)}`,loader:"ts"}})}}],sourcemap:"external",splitting:true,target:"bun"}));if(!result.success){throw new AggregateError(result.logs,"Failed to build Backend release assets")}const outputByName=new Map(result.outputs.map((artifact)=>[nodePath3.basename(artifact.path),artifact]));const runtimeFiles=[];for(const artifact of result.outputs.filter(({path})=>!path.endsWith(".map"))){runtimeFiles.push(yield*gen2(function*readBackendArtifact(){const relativePath=artifact.path.replace(/^\.\//u,"").replace(/^\/+/u,"");const rawCode=yield*tryPromise2(artifact.text.bind(artifact));const code=rawCode.replaceAll(/\/\/# (?:debugId|sourceMappingURL)=.*$/gmu,"");const bytes=runtimeModuleBytes(code,"backend",relativePath);const mapArtifact=outputByName.get(`${nodePath3.basename(artifact.path)}.map`);const entryMatch=/^ci-release-backend-entry-(?<index>\d+)\.mjs$/u.exec(nodePath3.basename(artifact.path));const contributionFqn=entryMatch?.groups?.index===undefined?undefined:identities[Number(entryMatch.groups.index)]?.fqn;const sourceMapBytes=mapArtifact===undefined?undefined:sanitizeSourceMap(yield*tryPromise2(mapArtifact.text.bind(mapArtifact)),relativePath);return{bytes,...contributionFqn===undefined?undefined:{contributionFqn},host:"backend",path:`artifacts/backend/${relativePath}`,...sourceMapBytes===undefined?undefined:{sourceMapBytes}}}))}return runtimeFiles}),runPromise2);var viteOutputList=(output)=>{if(!Array.isArray(output)&&"close"in output){throw new Error("Vite unexpectedly returned a watcher for a release build")}return Array.isArray(output)?output:[output]};var buildFrontend=flow((input)=>gen2(function*buildFrontendEffect(){const identities=contributionIdentities(input.definition,input.host);if(identities.length===0){return[]}const entries=new Map;const entryNames={};for(const[index,identity]of identities.entries()){const id=`virtual:ci-release-${input.host}-entry-${index}`;const contributionImport=resolveHostedContributionEntry(input.declarationSpecifier,identity);entries.set(`\x00${id}`,{contributionImport,identity,source:`export { ${moduleExport(identity.exportName)} } from ${jsonString(contributionImport)}; export * from ${jsonString(contributionImport)}`});entryNames[`contribution-${index}`]=id}const virtualEntries={load:flow(function loadFrontendEntry(id){const resolve=this.resolve.bind(this);return gen2(function*loadFrontendEntryEffect(){const entry=entries.get(id);if(entry===undefined){return null}const resolved=yield*promise2(flow(constant(entry.contributionImport),resolve));if(resolved===null){return yield*die3(new Error(`Frontend catalog module could not be resolved: ${entry.contributionImport}`))}const file=Bun.file(resolved.id);const source=yield*promise2(file.text.bind(file));const{exports}=new Bun.Transpiler({loader:/\.[jt]sx$/u.test(resolved.id)?"tsx":"ts"}).scan(source);return exports.includes("default")?`${entry.source}; export { default } from ${jsonString(entry.contributionImport)}`:entry.source})},runPromise2),name:"ci-hosted-release-entries",resolveId:(id)=>id.startsWith("virtual:ci-release-")?`\x00${id}`:null};const stableRegionLabels={name:"ci-hosted-release-stable-region-labels",renderChunk:(code)=>stableFrontendChunk(code,input.host)};const hostReactRequireId="\x00virtual:ci-host-react-require";const hostReactRequire={enforce:"pre",load:(id)=>id===hostReactRequireId?'import React from "react"; module.exports = React;':null,name:"ci-host-react-require",resolveId:{handler:(source,_importer,options)=>source==="react"&&options.kind==="require-call"?hostReactRequireId:null,order:"pre"}};const output=yield*tryPromise2(viteBuild.bind(undefined,{build:{assetsInlineLimit:0,cssCodeSplit:true,emptyOutDir:false,minify:false,modulePreload:false,rolldownOptions:{input:entryNames,output:{assetFileNames:"assets/[name]-[hash][extname]",chunkFileNames:"chunks/[name]-[hash].mjs",entryFileNames:"modules/[name].mjs"},preserveEntrySignatures:"strict"},sourcemap:"hidden",target:"esnext",write:false},configFile:false,define:{"process.env.NODE_ENV":jsonString("production")},logLevel:"silent",mode:"production",oxc:{jsx:{development:false}},plugins:[virtualEntries,hostReactRequire,esmExternalRequirePlugin({external:[...hostProvidedModulesFor(input.host)]}),stableRegionLabels],resolve:workspaceSourceResolve(process.execArgv),root:process.cwd(),ssr:workspaceSourceSsrResolve(process.execArgv)})).pipe(catch_2((error)=>die3(error.cause instanceof Error?error.cause:new Error("Frontend catalog build failed",{cause:error.cause}))));const files=[];for(const result of viteOutputList(output)){for(const artifact of result.output){if(artifact.type==="asset"){if(!artifact.fileName.endsWith(".map")){files.push({bytes:viteAssetBytes(artifact.source),host:input.host,path:`artifacts/${input.host}/${artifact.fileName}`})}continue}const entry=artifact.facadeModuleId===null?undefined:entries.get(artifact.facadeModuleId);const sourceMapBytes=artifact.map===null?undefined:sanitizeSourceMap(artifact.map.toString(),artifact.fileName);files.push({bytes:runtimeModuleBytes(artifact.code,input.host,artifact.fileName),...entry===undefined?undefined:{contributionFqn:entry.identity.fqn},host:input.host,path:`artifacts/${input.host}/${artifact.fileName}`,...sourceMapBytes===undefined?undefined:{sourceMapBytes}})}}return files}),runPromise2);var mergeCompatibility=(definition)=>{const compatibility={};for(const{manifest}of definition.hostedContributions){for(const[runtime,range]of Object.entries(manifest.compatibility??{})){const existing=compatibility[runtime];if(existing!==undefined&&existing!==range){throw new TypeError(`Hosted Contributions declare conflicting ${runtime} compatibility ranges`)}compatibility[runtime]=range}}return Object.fromEntries(Object.entries(compatibility).toSorted(([left],[right])=>compareCanonicalText(left,right)))};var buildPackageRelease=flow((input)=>gen2(function*buildPackageReleaseEffect(){const definitions=yield*promise2(loadPackageDeclarations.bind(undefined,input.declarationSpecifier));if(definitions.length!==1){throw new TypeError("An Extension Release build requires exactly one package")}const[definition]=definitions;if(definition===undefined){throw new TypeError("Extension Package declaration was not found")}const hostFiles=yield*all2([promise2(buildBackend.bind(undefined,{declarationSpecifier:input.declarationSpecifier,definition})),...FRONTEND_HOSTS.map((host)=>promise2(buildFrontend.bind(undefined,{declarationSpecifier:input.declarationSpecifier,definition,host})))]);const files=hostFiles.flat();const media=yield*readPackageMedia({definition,directory:nodePath3.dirname(backendPackageModulePath(input.declarationSpecifier,definition))});const assets=[];const privateSourceMaps=[];const privateMapByRuntimeDigest=new Map;for(const file of files){const runtimeDigest=digest(file.bytes);const sourceMap=file.sourceMapBytes;const privateSourceMap=sourceMap===undefined?undefined:{digest:digest(sourceMap),size:sourceMap.byteLength};assets.push({digest:runtimeDigest,host:file.host,path:file.path,...privateSourceMap===undefined?undefined:{privateSourceMap},size:file.bytes.byteLength});if(sourceMap!==undefined&&privateSourceMap!==undefined){const existing=privateMapByRuntimeDigest.get(runtimeDigest);if(existing!==undefined&&existing.digest!==privateSourceMap.digest){throw new Error(`Runtime asset '${runtimeDigest}' produced conflicting private source maps`)}if(existing===undefined){const sidecar={bytes:sourceMap,digest:privateSourceMap.digest,runtimeAssetDigest:runtimeDigest,size:privateSourceMap.size};privateMapByRuntimeDigest.set(runtimeDigest,sidecar);privateSourceMaps.push(sidecar)}}}const assetByPath=new Map(assets.map((asset)=>[asset.path,asset]));const pathByContribution=new Map(files.flatMap((file)=>file.contributionFqn===undefined?[]:[[`${file.host}:${file.contributionFqn}`,file.path]]));const contributions=backendArtifactContributions(definition).map((contribution)=>{const assetPath=pathByContribution.get(`${contribution.host}:${contribution.fqn}`);const asset=assetPath===undefined?undefined:assetByPath.get(assetPath);if(asset===undefined||assetPath===undefined){throw new Error(`No release entry asset was built for ${contribution.fqn}`)}const common={assetPath,digest:asset.digest,exportName:contribution.exportName,fqn:contribution.fqn,size:asset.size};return contribution.host==="backend"?{...common,...contribution.contract===undefined?undefined:{contract:contribution.contract},...contribution.execution===undefined?undefined:{execution:contribution.execution},exportName:contribution.exportName,host:contribution.host}:{...common,contract:contribution.contract,exportName:contribution.exportName,host:contribution.host}});const packageManifestBytes=encoder2.encode(canonicalPackageManifest(definition));const archiveBytes=createExtensionReleaseArchive([...files.map(({bytes,path})=>({bytes,path})),...media.entries,{bytes:packageManifestBytes,path:"package-manifest.json"}]);const releaseDigest=digest(archiveBytes);const manifest={apiVersion:"v2",assets:assets.toSorted((left,right)=>compareCanonicalText(left.path,right.path)),compatibility:mergeCompatibility(definition),contributions:contributions.toSorted((left,right)=>compareCanonicalText(left.host,right.host)||compareCanonicalText(left.fqn,right.fqn)),...media.media.length===0?undefined:{media:media.media},package:{fqn:definition.manifest.fqn,version:definition.manifest.version},packageManifest:definition.manifest,releaseDigest};return{archiveBytes,manifest,manifestBytes:encoder2.encode(canonicalExtensionReleaseManifest(manifest)),packageManifest:definition.manifest,packageManifestBytes,privateSourceMaps:privateSourceMaps.toSorted((left,right)=>compareCanonicalText(left.runtimeAssetDigest,right.runtimeAssetDigest)),releaseDigest}}),runPromise2);var materializePackageRelease=flow((input,dependencies)=>gen2(function*materializePackageReleaseEffect(){const release=yield*promise2(buildPackageRelease.bind(undefined,{declarationSpecifier:input.declarationSpecifier}));const privateMapDirectory=nodePath3.join(input.outputDirectory,"private-source-maps");yield*writerEffect(dependencies.makeDirectory.bind(dependencies,privateMapDirectory));yield*all2([writerEffect(dependencies.writeBytes.bind(dependencies,nodePath3.join(input.outputDirectory,"release.tar"),release.archiveBytes)),writerEffect(dependencies.writeBytes.bind(dependencies,nodePath3.join(input.outputDirectory,"manifest.json"),release.manifestBytes)),writerEffect(dependencies.writeBytes.bind(dependencies,nodePath3.join(input.outputDirectory,"package-manifest.json"),release.packageManifestBytes)),...release.privateSourceMaps.map((sourceMap)=>writerEffect(dependencies.writeBytes.bind(dependencies,nodePath3.join(privateMapDirectory,`${sourceMap.runtimeAssetDigest}.map`),sourceMap.bytes)))]);return{archive:nodePath3.join(input.outputDirectory,"release.tar"),manifest:nodePath3.join(input.outputDirectory,"manifest.json"),packageManifest:nodePath3.join(input.outputDirectory,"package-manifest.json"),privateSourceMaps:privateMapDirectory,releaseDigest:release.releaseDigest}}),runPromise2);var optionValue3=(args,name)=>{const index=args.lastIndexOf(`--${name}`);const value=index===-1?undefined:args[index+1];if(value===undefined||value===""){throw new TypeError(`Missing option --${name}`)}return value};var runPackageBuildCommand=flow((args,dependencies)=>gen2(function*runPackageBuildCommandEffect(){const outputDirectory=optionValue3(args,"out");const release=yield*promise2(materializePackageRelease.bind(undefined,{declarationSpecifier:dependencies.resolveDeclarationSpecifier(optionValue3(args,"declaration")),outputDirectory},dependencies));return yield*encodeEffect(fromJsonString2(Unknown2))({archive:release.archive,manifest:release.manifest,packageManifest:release.packageManifest,privateSourceMaps:release.privateSourceMaps,releaseDigest:release.releaseDigest})}),runPromise2);class EventStreamHttpError extends Error{status;constructor(status,statusText){super(`Event stream request failed with HTTP ${status} ${statusText}`.trimEnd());this.name="EventStreamHttpError";this.status=status}}var singleConnectionSseOptions={onSseError:(cause)=>{throw cause},sseMaxRetryAttempts:1};var eventStreamFetch=(fetch2=globalThis.fetch)=>Object.assign(async(input,init)=>{const response=await fetch2(input,init);if(!response.ok){throw new EventStreamHttpError(response.status,response.statusText)}return response},{preconnect:()=>{}});var isRetryableEventStreamError=(cause)=>!(cause instanceof EventStreamHttpError)||cause.status>=500||cause.status===408||cause.status===425||cause.status===429;class EventStreamRetriesExhaustedError extends Error{attempts;lastEventId;constructor(input){super(input.cause===undefined?"Event stream kept closing without progress":"Event stream kept failing without progress",{cause:input.cause});this.name="EventStreamRetriesExhaustedError";this.attempts=input.attempts;this.lastEventId=input.lastEventId}}var DEFAULT_INITIAL_RETRY_DELAY_MS=1000;var DEFAULT_MAX_RETRY_DELAY_MS=30000;var DEFAULT_MIN_HEALTHY_CONNECTION_MS=30000;var abortableSleep=async(milliseconds,signal)=>{if(signal.aborted){return}await new Promise((resolve)=>{const settled=new AbortController;const timeout=globalThis.setTimeout(()=>{settled.abort();resolve()},milliseconds);signal.addEventListener("abort",()=>{globalThis.clearTimeout(timeout);resolve()},{once:true,signal:settled.signal})})};var asError=(cause)=>cause instanceof Error?cause:new Error(String(cause),{cause});var followEventStream=async(options)=>{const signal=options.signal??new AbortController().signal;const sleep=options.sleep??abortableSleep;const initialDelay=options.initialRetryDelayMs??DEFAULT_INITIAL_RETRY_DELAY_MS;const maxDelay=options.maxRetryDelayMs??DEFAULT_MAX_RETRY_DELAY_MS;const minHealthyConnectionMs=options.minHealthyConnectionMs??DEFAULT_MIN_HEALTHY_CONNECTION_MS;const now=options.now??Date.now;let{lastEventId}=options;let attempt=0;while(!signal.aborted){const connection=new AbortController;const stopConnection=()=>{connection.abort()};signal.addEventListener("abort",stopConnection,{once:true});let terminal=false;let failure;const openedAt=now();try{const events=await options.connect({lastEventId,signal:connection.signal});for await(const event of events){await options.onEvent(event);const nextEventId=options.eventId===undefined?lastEventId:options.eventId(event);if(options.eventId===undefined||nextEventId!==lastEventId){attempt=0}lastEventId=nextEventId;if(options.isTerminal?.(event)===true){terminal=true;break}}}catch(error){failure=asError(error)}finally{signal.removeEventListener("abort",stopConnection);connection.abort()}if(terminal){return{lastEventId,reason:"terminal"}}if(signal.aborted){break}if(failure!==undefined&&options.isRetryableError!==undefined&&!options.isRetryableError(failure)){throw failure}if(failure===undefined&&now()-openedAt>=minHealthyConnectionMs){attempt=0}attempt+=1;if(options.maxRetries!==undefined&&attempt>options.maxRetries){throw new EventStreamRetriesExhaustedError({attempts:attempt,cause:failure,lastEventId})}const delayMs=Math.min(initialDelay*2**(attempt-1),maxDelay);options.onReconnect?.({attempt,cause:failure,delayMs,lastEventId});await sleep(delayMs,signal)}return{lastEventId,reason:"aborted"}};var awaitValue=(value)=>promise2(constant(Promise.resolve(value)));var encodeJson3=encodeSync(fromJsonString2(Unknown2));class PackageOperationCommandError extends TaggedError3()("PackageOperationCommandError",{cause:optional2(Unknown2),message:String4}){}var requireOption=(options,name)=>{const value=options.get(name);if(value===undefined||value===""){throw new PackageOperationCommandError({message:`Missing required option --${name}`})}return value};var parseOptions=(args)=>{const options=new Map;for(let index=1;index<args.length;index+=2){const flag=args[index];const value=args[index+1];if(!flag?.startsWith("--")||!value||value.startsWith("--")){throw new PackageOperationCommandError({message:"Options must be supplied as --name value pairs"})}options.set(flag.slice(2),value)}return options};var isPackageOperationComplete=(status)=>status!=="pending"&&status!=="running";var parseLastEventId=(options)=>{const value=options.get("last-event-id")??"0";if(!/^\d+$/u.test(value)){throw new PackageOperationCommandError({message:"--last-event-id must be a non-negative event sequence"})}const sequence=Number(value);if(!Number.isSafeInteger(sequence)){throw new PackageOperationCommandError({message:"--last-event-id must be a non-negative event sequence"})}return sequence};var fetchSnapshot=flow((dependencies,organizationId,operationId,signal)=>gen2(function*nativeAssetStep1(){const request={client:dependencies.client,headers:{"x-organization-id":organizationId},path:{operationId},throwOnError:true};if(signal!==undefined){request.signal=signal}const response=yield*awaitValue(packageOperationsSnapshot(request));return decodePackageOperationSnapshot(response.data)}),runPromise2);var executeSnapshot=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageOperationCommandError)(cause)?cause:new PackageOperationCommandError({cause,message:"Could not inspect package operation"}),try:async()=>({kind:"snapshot",snapshot:await fetchSnapshot(dependencies,requireOption(options,"organization"),requireOption(options,"operation"))})});var executeContinuation=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageOperationCommandError)(cause)?cause:new PackageOperationCommandError({cause,message:"Could not continue package operation"}),try:async()=>{const accepted=await packageOperationsContinueOperation({client:dependencies.client,headers:{"idempotency-key":requireOption(options,"idempotency-key"),"x-organization-id":requireOption(options,"organization")},path:{operationId:requireOption(options,"operation")},throwOnError:true});return{kind:"operation_accepted",operationId:accepted.data.operationId}}});var MAX_RECONNECTS_WITHOUT_PROGRESS=3;var isCommandError=is2(PackageOperationCommandError);var decodeOperationEvent=(wireEvent)=>{try{return decodePackageOperationEvent(encodeJson3(wireEvent))}catch(error){throw new PackageOperationCommandError({cause:error,message:"Package operation event did not match the Backend contract"})}};var followPackageOperationEffect=(input,dependencies)=>tryPromise2({catch:(cause)=>isCommandError(cause)?cause:new PackageOperationCommandError({cause,message:"Could not reconnect to package operation"}),try:async(signal)=>{let lastSequence=input.afterSequence??0;const{operationId,organizationId}=input;const snapshot=await fetchSnapshot(dependencies,organizationId,operationId,signal);if(isPackageOperationComplete(snapshot.status)&&(input.replay!==true||lastSequence>=snapshot.lastEventSequence)){return{kind:"snapshot",snapshot}}let lastEventId=input.afterSequence===undefined?undefined:String(lastSequence);let observed;try{await followEventStream({connect:async(connection)=>{const events=await packageOperationsEvents({...singleConnectionSseOptions,client:dependencies.client,fetch:eventStreamFetch(dependencies.client.getConfig().fetch),headers:{...connection.lastEventId===undefined?undefined:{"last-event-id":connection.lastEventId},"x-organization-id":organizationId},path:{operationId},signal:connection.signal,throwOnError:true});return events.stream},eventId:()=>lastEventId,isRetryableError:(error)=>!isCommandError(error)&&isRetryableEventStreamError(error),isTerminal:()=>observed!==undefined&&observed.sequence===lastSequence&&isPackageOperationComplete(observed.status),...lastEventId===undefined?undefined:{lastEventId},maxRetries:MAX_RECONNECTS_WITHOUT_PROGRESS,onEvent:(wireEvent)=>{const event=decodeOperationEvent(wireEvent);observed=event;if(event.sequence<=lastSequence){return}if(event.sequence!==lastSequence+1){throw new PackageOperationCommandError({message:`Package operation event sequence jumped from ${lastSequence} to ${event.sequence}`})}dependencies.writeEvent(encodeJson3(event));lastSequence=event.sequence;lastEventId=String(event.sequence)},signal,...dependencies.sleep===undefined?undefined:{sleep:dependencies.sleep}})}catch(error){if(error instanceof EventStreamHttpError){throw new PackageOperationCommandError({cause:error,message:`Package operation event stream was rejected with HTTP ${error.status}`})}if(error instanceof EventStreamRetriesExhaustedError){throw new PackageOperationCommandError({cause:error.cause??error,message:`Package operation event stream disconnected; reconnect with --last-event-id ${lastSequence}`})}throw error}return{kind:"snapshot",snapshot:await fetchSnapshot(dependencies,organizationId,operationId,signal)}}});var packageOperationCommandEffect=(args,dependencies)=>{const[command]=args;const options=parseOptions(args);if(command==="continue"){return executeContinuation(options,dependencies)}if(command==="reconnect"){return followPackageOperationEffect({afterSequence:options.has("last-event-id")?parseLastEventId(options):undefined,operationId:requireOption(options,"operation"),organizationId:requireOption(options,"organization"),replay:true},dependencies)}if(command==="snapshot"){return executeSnapshot(options,dependencies)}return fail6(new PackageOperationCommandError({message:"Expected one of: package operation snapshot, package operation reconnect, package operation continue"}))};var renderPin=(pin)=>`${pin.fqn}@${pin.releaseId}`;var renderSelection=(selection)=>selection===null?"none":`${selection.releaseId} generation ${selection.generation}`;var renderBlocker=(blocker)=>{if(blocker._tag==="manual_prerequisite"){const observed=blocker.observed===null?"none":renderPin(blocker.observed);return`Blocker ManualPrerequisite: ${blocker.message}; requires ${renderPin(blocker.required)}, observed ${observed}; path ${blocker.path.map(renderPin).join(" -> ")}`}let label=blocker._tag;if(blocker._tag==="authority_denied"){label=`AuthorityDenied (${blocker.boundary})`}else if(blocker._tag==="unknown"){label=blocker.tag}const details=[blocker.message,..."definitions"in blocker?[`definitions ${blocker.definitions.map((definition)=>`${definition.kind} ${definition.fqn}`).join(", ")}`]:[],...blocker.paths.map((path)=>`path ${path.join(" -> ")}`)];return`Blocker ${label}: ${details.join("; ")}`};var renderProtection=(protection)=>{if(protection.kind==="required_by"){return`requiredBy ${renderPin(protection.dependent)} (${protection.protection})`}if(protection.kind==="unknown_requirement"){return`unknownRequirement ${renderPin(protection.dependent)}`}if(protection.kind==="workflow_use"){const{template}=protection;return`workflowUse ${protection.workflowId} (${protection.state}, template ${template.fqn}@${template.version})`}if(protection.kind==="live_binding"){return`liveBinding ${protection.bindingKind} ${protection.id}`}return protection.kind};var renderCleanupCandidate=(candidate)=>{const subject=`Cleanup ${candidate.packageFqn}@${candidate.releaseId} (${candidate.installationId}) ${candidate.result}`;const protections=candidate.protections??[];return protections.length===0?`${subject}.`:`${subject}: ${protections.map(renderProtection).join("; ")}.`};var renderCleanup=(cleanup)=>[`Cleanup ${cleanup.state}.`,...cleanup.candidates.map(renderCleanupCandidate)];var renderHost=(host,snapshot)=>{const{member,observed}=host;const outcome=`Host ${member.packageFqn} (${member.installationId}) ${host.result}: expected ${member.releaseId} generation ${member.generation}; observed Desired ${renderSelection(observed.desired)}, Serving ${renderSelection(observed.serving)}.`;return host.diagnosticId===undefined?outcome:`${outcome} Diagnostic ID ${host.diagnosticId}: ci package diagnostics trace --organization ${snapshot.organizationId} --diagnostic ${host.diagnosticId}`};var renderNextAction=(snapshot)=>{const scope=`--organization ${snapshot.organizationId} --operation ${snapshot.id}`;const continueCommand=`ci package operation continue ${scope} --idempotency-key <key>`;const hints={continue:`continue. Start a linked new operation with a new Operation ID: ${continueCommand}`,none:"none.",retry:`retry. Resume this same operation with its accepted plan and Operation ID: ${continueCommand}`,wait:`wait. Follow progress: ci package operation reconnect ${scope} --last-event-id ${snapshot.lastEventSequence}`};return`Next action: ${hints[snapshot.nextAction]}`};var renderPackageOperationSummary=(snapshot)=>{const{application,failure}=snapshot;const lines=[`Package operation ${snapshot.id} is ${snapshot.status}.`,...application.state==="not_applied"&&application.blocker!==undefined?[renderBlocker(application.blocker)]:[],...snapshot.hosts.map((host)=>renderHost(host,snapshot)),...snapshot.cleanup===undefined?[]:renderCleanup(snapshot.cleanup),...failure===undefined?[]:[`Failure ${failure.reason}: ${failure.message}`],renderNextAction(snapshot)];return`${lines.join(`
|
|
296
296
|
`)}
|
|
297
297
|
`};var ImportType=function(A){return A[A.Static=1]="Static",A[A.Dynamic=2]="Dynamic",A[A.ImportMeta=3]="ImportMeta",A[A.StaticSourcePhase=4]="StaticSourcePhase",A[A.DynamicSourcePhase=5]="DynamicSourcePhase",A[A.StaticDeferPhase=6]="StaticDeferPhase",A[A.DynamicDeferPhase=7]="DynamicDeferPhase",A}({});var A=new Uint8Array(new Uint16Array([1]).buffer)[0]===1;function parse(C,g="@"){if(!E)return init.then(()=>parse(C,g));const I=C.length+1,w=(E.__heap_base.value||E.__heap_base)+4*I-E.memory.buffer.byteLength;w>0&&E.memory.grow(Math.ceil(w/65536));const D=E.sa(I-1);if(typeof Buffer!="undefined"?Buffer.from(E.memory.buffer,D,2*(I-1)).write(C,"utf16le"):(A?Q:B)(C,new Uint16Array(E.memory.buffer,D,I)),!E.parse())throw Object.assign(new Error(`Parse error ${g}:${C.slice(0,E.e()).split(`
|
|
298
298
|
`).length}:${E.e()-C.lastIndexOf(`
|
|
299
|
-
`,E.e()-1)}`),{idx:E.e()});const o=[],G=[];for(;E.ri();){const A=E.is(),B=E.ie(),Q=E.it(),g=E.ai(),I=E.id(),w=E.ss(),D=E.se();let G;E.ip()&&(G=i(C.slice(I===-1?A-1:A,I===-1?B+1:B)));let J=null;for(J=[],E.rsa();E.ra();){const A=E.aks(),B=E.ake(),Q=E.avs(),g=E.ave();J.push([s(C.slice(A,B)),s(C.slice(Q,g))])}J.length===0&&(J=null),o.push({n:G,t:Q,s:A,e:B,ss:w,se:D,d:I,a:g,at:J})}for(;E.re();){const A=E.es(),B=E.ee(),Q=E.els(),g=E.ele(),I=Q<0?undefined:s(C.slice(Q,g)),w=s(C.slice(A,B));G.push({s:A,e:B,ls:Q,le:g,ss:E.ess(),n:w,ln:I})}function i(A){try{return(0,eval)(A)}catch(A){}}function s(A){if(!A)return A;const B=A[0];return(B==='"'||B==="'")&&i(A)||A}return[o,G,!!E.f(),!!E.ms()]}function B(A,B){const Q=A.length;let E=0;for(;E<Q;){const Q=A.charCodeAt(E);B[E++]=(255&Q)<<8|Q>>>8}}function Q(A,B){const Q=A.length;let E=0;for(;E<Q;)B[E]=A.charCodeAt(E++)}var E;var C=()=>{return A="AGFzbQEAAAABKwhgAAF/YAF/AX9gAABgAn9/AX9gBH9/f38AYAN/f38Bf2ABfwBgA39/fwADPj0CAgEEBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgABBQICAgYBAQYBAQEFAQEBAQECAgIBAQEDAQEHAQMDBAUBcAECAgUHAQGCAoCAAgYPAn8BQaCLBAt/AEGgiwQLB80BHgZtZW1vcnkCAAJzYQACAWUABQJpcwAGAmllAAcCc3MACAJzZQAJAml0AAoCYWkACwJpZAAMAmlwAA0CZXMADgJlZQAPA2VscwAQA2VsZQARA2VzcwASAnJpABMCcmUAFAFmABUCbXMAFgJyYQAXA2FrcwAYA2FrZQAZA2F2cwAaA2F2ZQAbA3JzYQAcBXBhcnNlAB0LX19oZWFwX2Jhc2UDAQtfaW5pdGlhbGl6ZQABGV9faW5kaXJlY3RfZnVuY3Rpb25fdGFibGUBAAkHAQBBAQsBAAwBAQrZVz0oAEHYCkGAwAA2AgBB0ApBoIsENgIAQbgKQSo2AgBB1ApBgIAENgIACwQAEAALWQBB6AkgADYCACAAQQF0IgBBADsBoIsEQewJIABBoosEajYCAEHECUEANgIAQdQJQQA2AgBBzAlBADYCAEHICUEANgIAQdwJQQA2AgBB0AlBADYCAEGgiwQLuAEBAn9B7AlB7AkoAgAiBEEoajYCAAJAQdQJKAIAIgVFBEBBxAkgBDYCAAwBCyAFIAQ2AiQLQdQJIAQ2AgBB2AkgBTYCACAEIAA2AgggBEIANwIgIAQgA0EBRiIAOgAYIAQgAzYCFCAEQQA2AhAgBCACNgIEIAQgATYCACAEQQNBAUECIAAbIANBAkYiARs2AhwgBCACIAJBAmpBACAAGyABGzYCDCADQQFrQQFNBEBB8AlBAToAAAsLdwECf0HsCUHsCSgCACIEQRhqNgIAAkBB3AkoAgAiBUUEQEHICSAENgIADAELIAUgBDYCFAtB3AkgBDYCACAEIAM2AgwgBCACNgIIIAQgATYCBCAEIAA2AgBB4AkoAgAhACAEQQA2AhQgBCAANgIQQfAJQQE6AAALCABB9AkoAgALEwBBzAkoAgAoAgBBoIsEa0EBdQscAQF/QcwJKAIAKAIEIgBBoIsEa0EBdUF/IAAbCxMAQcwJKAIAKAIIQaCLBGtBAXULHAEBf0HMCSgCACgCDCIAQaCLBGtBAXVBfyAAGwsLAEHMCSgCACgCHAscAQF/QcwJKAIAKAIQIgBBoIsEa0EBdUF/IAAbCzUBAn9BfyEAAkACQAJAQcwJKAIAKAIUIgFBAWsOAgIBAAsgAUGgiwRrQQF1DwtBfiEACyAACwsAQcwJKAIALQAYCxMAQdAJKAIAKAIAQaCLBGtBAXULEwBB0AkoAgAoAgRBoIsEa0EBdQscAQF/QdAJKAIAKAIIIgBBoIsEa0EBdUF/IAAbCxwBAX9B0AkoAgAoAgwiAEGgiwRrQQF1QX8gABsLEwBB0AkoAgAoAhBBoIsEa0EBdQslAQF/QcwJQcwJKAIAIgBBJGpBxAkgABsoAgAiADYCACAAQQBHCyUBAX9B0AlB0AkoAgAiAEEUakHICSAAGygCACIANgIAIABBAEcLCABB+AktAAALCABB8AktAAALKwEBf0H8CUH8CSgCACIAQRBqQcwJKAIAQSBqIAAbKAIAIgA2AgAgAEEARwsTAEH8CSgCACgCAEGgiwRrQQF1CxMAQfwJKAIAKAIEQaCLBGtBAXULEwBB/AkoAgAoAghBoIsEa0EBdQsTAEH8CSgCACgCDEGgiwRrQQF1CwoAQfwJQQA2AgAL3g8BBn8jAEGA0ABrIgQkAEH4CUEBOgAAQYAIIQBBhApBgAg2AgBBnApBnosEIgJB6AkoAgBBAXRqIgU2AgBB8AlBADoAAEGACkEAOwEAQYIKQQA7AQBBiApBADoAAEH0CUEANgIAQeQJQQA6AABBjAogBEGAEGo2AgBBkAogBDYCAEGUCkEAOgAAA0AgACEBQZgKIAJBAmoiADYCAAJAAkACfwJAAkAgAiAFSQRAIAAvAQAiA0EJa0EFSQ0EAkACQAJAAkACQCADQeUAaw4FAQYGBgIACyADQSBGDQggA0EvRg0DIANBO0YNAgwFC0GCCi8BAA0BIAAQHkUNASACQQRqQYIIQQoQHw0BECBBmAooAgAhAEH4CS0AAA0BQYQKIAA2AgAgACIBIQIMBQsgAi8BBEHtAEcNACAAEB5FDQAgAikABkLwgLyDoI6AOlINABAhQZgKKAIAIQALQYQKIAA2AgAMBgsgAi8BBCIAQSpHBEAgAEEvRw0CECIMBQtBARAjDAQLIAAhAkEAQeQJLQAADQIaDAELQfgJQQA6AAALA0ACQEGYCiACQQJqIgA2AgACQAJAAkACQCACIAVJBEACQAJAAkACQAJAAkACQAJAAkACQAJAIAAvAQAiA0Egaw4QDwgFCAgICAUKAggIAQgIBgALAkACQAJAAkACQAJAIANB2wBrDg8EDQUNDQwNDQMNAQ0NDQIACyADQQlrQQVJDRMgA0H7AGsOAwcMCAwLQYIKLwEADQwgABAeRQ0MIAJBBGpBgghBChAfDQwQIAwRCyACLwEEQe0ARw0LIAAQHkUNCyACKQAGQvCAvIOgjoA6Ug0LECEMEAsgAi8BBEHsAEcNCiAAEB5FDQogAkEGakGyCEEGEB8NCiACLwEMECRFDQpBlApBAToAAAwKC0GCCkGCCi8BACIAQQFqOwEAIARBgBBqIABBA3RqIgBBCDYCACAAIAE2AgQMDgtBggovAQAiAEUND0GCCiAAQQFrOwEADA0LQYAKLwEAIgBFDQxBggovAQAiA0UNDCADQQN0IARqQfgPaigCAEEFRw0MIAQgAEECdGpBBGsoAgAiACgCBA0MIAAgAUECajYCBEGYCiACQQRqNgIAQQEQJRogAEGYCigCACIANgIQQZgKIABBAms2AgAMDAtBggovAQAiAEUNDUGCCiAAQQFrIgM7AQBBgAovAQAiAEUNCyAEQYAQaiADQf//A3FBA3RqKAIAQQVHDQsgBCAAQQJ0akEEaygCACIDKAIERQRAIAMgAUECajYCBAsgAyACQQRqNgIMQYAKIABBAWs7AQAMCwsCQCABLwEAQSlHDQBB1AkoAgAiAEUNACAAKAIMIAFBAmpHDQBB1AlB2AkoAgAiADYCACAABEAgAEEANgIkDAELQcQJQQA2AgALQYIKQYIKLwEAIgBBAWo7AQAgBEGAEGogAEEDdGoiAEEGQQJBlAotAAAbNgIAIAAgATYCBEGUCkEAOgAADAoLQYIKLwEAIgBFDQtBggogAEEBayIAOwEAIARBgBBqIABB//8DcUEDdGooAgBBBEcNCQwICyADECYMCAsCQCACLwEEIgBBKkcEQCAAQS9HDQEQIgwKC0EBECMMCQsCQCABLwEAIgAQJwRAAkACQAJAIABBK2sOBAEKAgAKCyABQQJrLwEAQTBrQf//A3FBCkkNAwwJCyABQQJrLwEAQStGDQIMCAsgAUECay8BAEEtRg0BDAcLIABBKUcNACAEQYAQakGCCi8BAEEDdGooAgQQKA0GCwJAAkBBggovAQAiAkUgAEHmAEdyDQAgBEGAEGogAkEDdGoiA0EIaygCAEEBRw0AIAFBAmsvAQBB7wBHDQEgAUEEaxApRQ0BIANBBGsoAgBBnglBAxAqRQ0BDAcLIABB/QBHDQAgBEGAEGogAkEDdGoiAigCBBArDQYgAigCAEEGRg0GCyABECwNBUGICi0AACAAQS9GcSAAQQBHc0UNBQJAQdwJKAIAIgJFDQAgASACKAIASQ0AIAEgAigCBE0NBgsDQCABQaCLBEsEQEGECiABQQJrIgE2AgAgAS8BACIAEC1FDQELCyAAQf//A3EQLgRAA0AgAUGgiwRLBEBBhAogAUECayIBNgIAIAEvAQAQLg0BCwsgARAvDQYLQYgKQQE6AAAMBwtBggpBggovAQAiAEEBajsBACAEQYAQaiAAQQN0aiIAIAE2AgQgAEEDNgIADAULIANBMGtB//8DcUEKSSADQSByQeEAa0H//wNxQRpJcg0AAkACQCADQdwAaw4EAgEBAgALIANBJEYNAQsgA0GgAUYgA0GAAUlyDQULA0AgAC8BAiIBQSByQeEAayECAkAgAUEwa0H//wNxQQpJIAJB//8DcUEaSXINAAJAAkAgAUHcAGsOBAIBAQIACyABQSRGDQELIAFBoAFGIAFBgAFJcg0GC0GYCiAAQQJqIgA2AgAMAAsAC0GCCkGCCi8BACIAQQFqOwEAIARBgBBqIABBA3RqIgBBATYCACAAIAE2AgQMAwtBgAovAQBFQYIKLwEARUHkCS0AAEF/c3FxDAYLEDBBiApBADoAAAwBCxAxC0GECkGYCigCACIBNgIAC0GYCigCACECDAELCxAyQQALIQMgBEGA0ABqJAAgAw8LIAEhAAtBmAooAgAhAgwACwALFgAgAEGgiwRGBEBBAQ8LIABBAmsQMwtDAQN/AkAgAkUNAANAIAAtAAAiBCABLQAAIgVGBEAgAUEBaiEBIABBAWohACACQQFrIgINAQwCCwsgBCAFayEDCyADC9IIAQV/QZgKQZgKKAIAIgRBDGoiATYCAEHcCSgCACEDQQEQJSECAkACQAJAAkACQAJAIAFBmAooAgAiAEYEQCACEDRFDQELQeAJIAQ2AgACQAJAAkAgAkEqRwRAIAJB+wBHDQFBmAogAEECajYCAEEBECUhAkGcCigCACEBQZgKKAIAIQADQAJAIAJB//8DcSICQSJGIAJBJ0ZyRQRAIAIQNRpBmAooAgAhAgwBCyACECZBmApBmAooAgBBAmoiAjYCAAtBARAlGiAAIAIQNiICQSxGBEBBmApBmAooAgBBAmo2AgBBARAlIQILIAJB/QBGDQMgAEGYCigCACIARg0IIAAgAU0NAAsMBwtBmAogAEECajYCAEEBECUaQZgKKAIAIgAgABA2GgwCC0H4CUEAOgAAAkACQAJAAkACQAJAIAJB4QBrDgwCCAQBCAMICAgICAUACyACQfYARg0EDAcLQZgKIABBDmoiBDYCAAJAAkACQAJAQQEQJUHhAGsOBgAMAgwMAQwLQZgKKAIAIgEpAAJC84Dkg+CNwDFSDQsgAS8BChAuRQ0LQZgKIAFBCmo2AgBBABAlGgtBmAooAgAiA0ECakGiCEEOEB8NCgJAIAMvARAiARAkDQAgAUEoaw4DAAsACwtBmAogA0EQajYCAEEBECUiAUEqRgRAQZgKQZgKKAIAQQJqNgIAQQEQJSEBCyABQShHDQEMCgtBmAooAgAiAykAAkLsgISDsI7AOVINCSADLwEKIgEQJEUgAUH7AEdxDQlBmAogA0EKajYCAEEBECUiAUH7AEYNCQtBmAooAgAhAyABEDUaQZgKKAIAIgEgA00NCCAAIAQgAyABEAQMCgtBmAogAEEKajYCAEEAECUaQZgKKAIAIQALQZgKIABBEGo2AgBBARAlIgBBKkYEQEGYCkGYCigCAEECajYCAEEBECUhAAsMCQsCQCAAKQACQuyAhIOwjsA5Ug0AIAAvAQoQLUUNAEGYCiAAQQpqNgIAQQEQJSEADAkLIABBBGohAAtBmAogAEEGajYCAEGcCigCACEDA0BBARAlIQBBmAooAgAiASADSw0HIAAQNyECQZgKKAIAIgAgAUYNBCACQT1GBEBBARA4IQJBmAooAgAhAAsgAkEsRw0EQZgKIABBAmo2AgAMAAsAC0HwCUEBOgAAQZgKQZgKKAIAQQJqNgIAC0EBECUhAEGYCigCACEBAkAgAEHmAEcNACABQQJqQZwIQQYQHw0AQZgKIAFBCGo2AgAgBEEBECVBABA5IANBFGpByAkgAxshAgNAIAIoAgAiAEUNAiAAQgA3AgggAEEUaiECDAALAAtBmAogAUECazYCAAsPCyAAIQEMAgsgACAEQQBBABAEQZgKIABBDGo2AgAPCxAyDwtBmAogAUECazYCAA8LQZgKKAIAIQEgABA1GiABQZgKKAIAIgAgASAAEARBmAogAEECazYCAAuKCwEKf0GYCkGYCigCACIGQQxqIgk2AgBBARAlIQBBmAooAgAhAgJAAkACQAJAAkACQAJ/IABBLkYEQEGYCiACQQJqNgIAQQEQJSIAQeQARwRAIABB8wBHBEAgAEHtAEcNB0GYCigCACIAQQJqQYwIQQYQHw0HQYQKKAIAIgEQOkUEQCABLwEAQS5GDQgLIAYgBiAAQQhqQQIQAw8LQZgKKAIAIgBBAmpBkghBChAfDQZBhAooAgAiARA6RQRAIAEvAQBBLkYNBwtBmAogAEEMajYCAEEBIQhBBSEEQQEQJSEAQQEMAgtBmAooAgAiACkAAkLlgJiD0IyAOVINBUGECigCACIBEDpFBEAgAS8BAEEuRg0GC0GYCiAAQQpqNgIAQQchBEEBIQVBARAlIQBBASEIQQIMAQsCQAJAIABB8wBHIAIgCU1yRQRAQfMAIQAgAkECakGSCEEKEB8NASACLwEMECRFDQFBmAogAkEMaiIANgIAQQEhCEEBECUhASAAQZgKKAIAIgRHBEBB5gAhACABQeYARwRAQQUhBCABIQBBAQwFC0EBIQMgBEECakGcCEEGEB8NBSAELwEIEC1FDQULQZgKIAI2AgBBByEEQQEhB0EAIQggASEAQQAMAwtBByEEQQEhByAAQeQARyACIAZBCmpNcg0BQeQAIQAgAikAAkLlgJiD0IyAOVINACACLwEKECRFDQBBmAogAkEKajYCAEEqIQBBASEFQQIhA0EBECUiAUEqRg0EQZgKIAI2AgBBACEFIAEhAEEADAILIAIhBAwCC0EACyEDIABBKEYEQEGMCigCAEGCCi8BACIFQQN0aiIAQQU2AgBBggogBUEBajsBACAAQZgKKAIAIgI2AgRBhAooAgAvAQBBLkYNBEGYCiACQQJqNgIAQQEQJSEAIAZBmAooAgAiAUEAIAIQA0HUCSgCACEDIAgEQCADIAQ2AhwLQYAKQYAKLwEAIgRBAWo7AQBBkAooAgAgBEECdGogAzYCAAJAIABBIkYgAEEnRnJFBEACQCAAQeAARw0AQZwKKAIAIQYgASEAA0AgACICIAZPDQECQAJAIABBAmoiAC8BACIHQdwAaw4FAAICAgUBCyACQQRqIQAMAQsgB0EkRw0AIAIvAQRB+wBHDQALC0GYCiABQQJrNgIADwsgABAmQZgKKAIAIQALQZgKIABBAmoiADYCAAJAAkACQEEBECVBKWsOBAECAgACC0GYCkGYCigCAEECajYCAEEBECUaIAMgADYCBEGYCigCACEAIANBAToAGCADIAA2AhAMCAtBggogBTsBACADIAA2AgRBmAooAgAhACADQQE6ABggAyAAQQJqNgIMQYAKIAQ7AQAPC0GYCkGYCigCAEECazYCAA8LIAdFIABB+wBHckUEQEGYCigCACEAQYIKLwEADQZBnAooAgAhAQNAAkACQCAAIAFJBEBBARAlIgBBIkYgAEEnRnINASAAQf0ARw0CQZgKQZgKKAIAQQJqNgIAC0EBECUhAUGYCigCACEAIAFB5gBGBEAgAEECakGcCEEGEB8NBwtBmAogAEEIajYCAEEBECUiAEEiRyAAQSdHcQ0GIAYgAEEAEDkPCyAAECYLQZgKQZgKKAIAQQJqIgA2AgAMAAsACwJAAkAgAEEnaw4EAwEBAwALIABBIkYNAgtBmAooAgAhBAsgBCAJRw0AQZgKIARBAms2AgAPCyAAQSpHIAVxDQJBggovAQANAkGYCigCACEAQZwKKAIAIQIDQCAAIAJPDQEgAC8BACIBQSdHIAFBIkdxBEBBmAogAEECaiIANgIADAEFIAYgASADEDkPCwALAAsQMgsPC0GYCkGYCigCAEECazYCAA8LQZgKIABBAms2AgALQwEDf0GYCigCACEAQZwKKAIAIQIDQAJAIABBAmohASAAIAJPDQAgASEAIAEvAQBBCmsOBAABAQABCwtBmAogATYCAAtwAQR/QZgKKAIAQQJqIQFBnAooAgAhBAJAA0AgASICQQJqIQEgAiAETw0BIAEvAQAhAwJAIABFBEAgA0EqRg0BIANBCmsOBAMCAgMCCyADQSpHDQELIAIvAQRBL0cNAAsgAkEEaiEBC0GYCiABNgIACwsAIABBn4CABBA8C30BBH9BnAooAgAhA0GYCigCACEBA0ACQAJAAkAgAS8BACICQS9GBEAgAS8BAiIBQSpHBEAgAUEvRg0CQS8PCyAAECMMAgsgAARAIAIQJA0CDAMLIAIQLg0BDAILECILQZgKQZgKKAIAIgRBAmoiATYCACADIARLDQELCyACC4YBAQR/QZgKKAIAIQFBnAooAgAhBAJAA0ACQCABIgJBAmohASACIARPDQAgAS8BACIDIABGDQIgA0HcAEcEQCADQQprDgQBAgIBAgsgAkEEaiEBIAIvAQRBDUcNASACQQZqIAEgAi8BBkEKRhshAQwBCwtBmAogATYCABAyDwtBmAogATYCAAtuAQF/AkAgAEEpRyAAQShrQf//A3FBB0lxIABBIWsiAUEFTUEAQQEgAXRBMXEbckUEQCAAQTprIgFB//8DcUElT0K/gICAoAIgAa2Ip0EBcUVyDQELQQEPCyAAQf0ARyAAQfsAa0H//wNxQQRJcQsuAQF/QQEhAQJAIABBlAlBBRAqDQAgAEGeCUEDECoNACAAQaQJQQIQKiEBCyABC28BAX8CfyAALwEAIgEQJCABQSlGciABQf0ARnJFBEBBACABQd0ARw0BGgsDQAJAIABBoIsETQ0AIAEQJEUNACAAQQJrIgAvAQAhAQwBCwtBASABQSlGIAFB3QBGciABQf0ARnINABogARA0QQFzCws+AQJ/AkAgACACQQF0IgJrIgRBAmoiAEGgiwRJDQAgACABIAIQHw0AIABBoIsERgRAQQEPCyAEEDMhAwsgAwuDAQECf0EBIQICQAJAAkACQAJAAkAgAC8BACIBQTtrDgQFBAQBAAsCQCABQeUAaw4EAwQEAgALIAFBKUYNBCABQfkARw0DIABBAmtBsAlBBhAqDwsgAEECay8BAEE9Rg8LIABBAmtBqAlBBBAqDwsgAEECa0G8CUEDECoPC0EAIQILIAILqgMBAn8CQAJAAkACQAJAAkACQAJAAkACQCAALwEAQeQAaw4UAAECCQkJCQMJCQQFCQkGCQcJCQgJCwJAAkAgAEECay8BAEHpAGsOBAAKCgEKCyAAQQRrQbgIQQIQKg8LIABBBGtBvAhBAxAqDwsCQAJAAkAgAEECay8BAEHzAGsOAwABAgoLIABBBGsvAQAiAUHhAEcEQCABQewARw0KIABBBmtB5QAQOw8LIABBBmtB4wAQOw8LIABBBGtBwghBBBAqDwsgAEEEa0HKCEEGECoPCyAAQQJrLwEAQe8ARw0GIABBBGsvAQBB5QBHDQYgAEEGay8BACIBQfAARwRAIAFB4wBHDQcgAEEIa0HWCEEGECoPCyAAQQhrQeIIQQIQKg8LIABBAmtB5ghBBBAqDwtBASECIABBAmsiAEHpABA7DQQgAEHuCEEFECoPCyAAQQJrQeQAEDsPCyAAQQJrQfgIQQcQKg8LIABBAmtBhglBBBAqDwsgAEECay8BACIBQe8ARwRAIAFB5QBHDQEgAEEEa0HuABA7DwsgAEEEa0GOCUEDECohAgsgAgs0AQF/IABBoAFGIABBCWsiAUEXTUEAQQEgAXRBn4CABHEbckUEQCAAEDQgAEEuR3EPC0EBCwsAIABBjYCABBA8C0gBAn8CQCAALwEAIgJB5QBHBEAgAkHrAEcNASAAQQJrQeYIQQQQKg8LIABBAmsvAQBB9QBHDQAgAEEEa0HKCEEGECohAQsgAQvbAQEEf0GYCigCACEAQZwKKAIAIQMDQCAAQQJqIQECQAJAIAAgA08NAAJAAkACQCABLwEAIgJB2wBrDgIBAgALIAEhACACQQprDgQCBAQCAwsCQANAAkAgAUECaiEAIAEgA08NAAJAAkAgAC8BACICQdwAaw4CAAQBCyABQQRqIQEMAgsgACEBIAJBCmsOBAABAQABCwtBmAogADYCABAyQZgKKAIAIQAMBAtBmAogADYCAAwDCyAAQQRqIQAMAgtBmAogATYCABAyDwsgAkEvRw0AC0GYCiAANgIAC94BAQR/QZgKKAIAIQBBnAooAgAhAwJAAkADQAJAIAAiAUECaiEAIAEgA08NAAJAAkACQCAALwEAIgJB3ABrDgUCBAQEAQALIAJBJEcNAyABLwEEQfsARw0DQZgKIAFBBGoiAjYCAEGMCigCAEGCCi8BACIAQQN0aiIBQQQ2AgBBggogAEEBajsBACABIAI2AgQPC0GYCiAANgIAQYIKQYIKLwEAQQFrIgE7AQBBjAooAgAgAUH//wNxQQN0aigCAEEDRw0DDAQLIAFBBGohAAwBCwtBmAogADYCAAsQMgsLMwEBf0HkCUEBOgAAQZgKKAIAIQBBmApBnAooAgBBAmo2AgBB9AkgAEGgiwRrQQF1NgIACz0BAX8Cf0EBIAAvAQAiAUEJa0H//wNxQQVJIAFBgAFyQaABRnINABpBACABEDRFDQAaIAAQOiABQS5HcgsLXgEBfwJAIABB+P8DcUEoRiAAQSFrIgFBBU1BAEEBIAF0QTFxG3JFBEAgAEE6ayIBQf//A3FBJU9Cv4CAgKADIAGtiKdBAXFFcg0BC0EBDwsgAEH7AGtB//8DcUEESQtXAQN/QZgKKAIAIQEDQAJAIABB//8DcSICECQEQCAAIQMMAQsgACEDIAIQNA0AQQAhA0GYCiABQQJqIgI2AgAgAS8BAiEAIAIhASAADQELCyADQf//A3ELpQEBBH8CQEGYCigCACIDLwEAIgVB4QBHBEAgASECIAAhBAwBC0GYCiADQQRqNgIAQQEQJSECQZgKKAIAIQQCQCACQSJGIAJBJ0ZyRQRAIAIQNRpBmAooAgAhAgwBCyACECZBmApBmAooAgBBAmoiAjYCAAtBARAlIQVBmAooAgAhAwsgAyAERwRAIAQgAkEAIAAgACABRiIAG0EAIAEgABsQBAsgBQvTBAEHf0GYCigCACEBAkAgAEHf/wNxQdsARgRAIAEvAQAhBUGYCiABQQJqNgIAQf0AQd0AIAVB+wBGGyEGQQEQJSEDQZwKKAIAIQcDQAJAIAYgA0H//wNxIgJGQZgKKAIAIgEgB0tyDQACQCACQS5HDQAgAS8BAkEuRw0AIAEvAQRBLkcNAEGYCiABQQZqNgIAQQEQJRA3IQMMAgsCQAJ/AkAgBUH7AEYEQAJAIAJBIkYgAkEnRnJFBEAgAkHbAEcNAUEAEDgaQZgKQZgKKAIAQQJqNgIAIAEMBAsgAhAmQZgKQZgKKAIAQQJqNgIAIAEMAwsgASEAIANBMGtB//8DcUEJSw0BA0AgACICQQJqIQAgAi8BAiIDQTBrQf//A3FBCkkNACADQcEAayIEQR5NQQBBASAEdEG/gIGEBHEbDQAgA0HhAGsiBEEXTUEAQQEgBHRBv8CBBHEbDQACQAJAIANBK2sOBAABAAIBCyACLwEAQSByQeUARg0BCwtBmAogADYCACABDAILIAJBLEYEQEGYCiABQQJqNgIAQQEQJSEDDAULIAIQNyECDAILIAIQNRpBmAooAgALIQBBARAlIgJBOkYEQEGYCkGYCigCAEECajYCAEEBECUQNyECDAELIAAgAU0NACABIAAgASAAEAQLIAJBPUYEQEEAEDghAgtBmAooAgAhASACQSxHDQBBmAogAUECajYCAEEBECUhAwwBCwtBmAogAUECajYCAAwBCyAAEDUaQZgKKAIAIgAgAU0NACABIAAgASAAEAQLQQEQJQvgDgEMf0GECkGYCigCACIBNgIAQZAKKAIAIQpBjAooAgAhB0GcCigCACEMQYIKLwEAIQsgASIDIQUCQANAQZgKIAVBAmoiBDYCACAFIAxPBEBBACEIDAILAkACQCAELwEAIgIQLg0AAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQEGCCi8BACIGIAtHDQAgAiEIAkACQCACQSlrDgQcAQEcAAsgAkE7RiACQd0ARnIgAkH9AEZyDRkLIAAgCXFBAUcNAAJAIAJBImsODgsODg4OCxAIDg4HDg4MAAsCQCACQdsAaw4PBQ4GDg4NDg4EDgIODg4DAAsCQCACQfsAaw4DCQ4KAAsgAkEKaw4EGg0NGg0LAkAgAkEiaw4OCg0NDQ0KDwcNDQYNDQsACwJAIAJB2wBrDg8EDQUNDQwNDQMNAQ0NDQIACwJAIAJBCmsOBBcNDRcACyACQfsAaw4DBwwIDAsgBg0MIAQQHkUNDCAFQQRqQYIIQQoQHw0MECAMEgsgBS8BBEHtAEcNCyAEEB5FDQsgBSkABkLwgLyDoI6AOlINCxAhDBELIAUvAQRB7ABHDQogBBAeRQ0KIAVBBmpBsghBBhAfDQogBS8BDBAkRQ0KQZQKQQE6AAAMCgsgByAGQQN0aiIBQQg2AgBBggogBkEBajsBACABIAM2AgQMDwsgBkUND0GCCiAGQQFrOwEADA4LIAZFDQ1BgAovAQAiAUUNDSAHIAZBA3RqQQhrKAIAQQVHDQ0gCiABQQJ0akEEaygCACIBKAIEDQ0gASADQQJqNgIEQZgKIAVBBGo2AgBBARAlGiABQZgKKAIAIgE2AhBBmAogAUECazYCAAwNCyAGRQ0NQYIKIAZBAWsiBDsBAEGACi8BACIBRQ0MIAcgBEH//wNxQQN0aigCAEEFRw0MIAogAUECdGpBBGsoAgAiBCgCBEUEQCAEIANBAmo2AgQLIAQgBUEEajYCDEGACiABQQFrOwEADAwLAkAgAy8BAEEpRw0AQdQJKAIAIgFFDQAgASgCDCADQQJqRw0AQdQJQdgJKAIAIgE2AgAgAQRAIAFBADYCJAwBC0HECUEANgIACyAHIAZBA3RqIgFBBkECQZQKLQAAGzYCAEGCCiAGQQFqOwEAIAEgAzYCBEGUCkEAOgAADAsLIAZFDQtBggogBkEBayIBOwEAIAcgAUH//wNxQQN0aigCAEEERw0KDAkLIAIQJgwJCwJAIAUvAQQiBEEqRwRAIARBL0cNARAiDAwLQQEQIwwLCwJAIAMvAQAiBRAnBEACQAJAAkAgBUEraw4EAQsCAAsLIANBAmsvAQBBMGtB//8DcUEKSQ0DDAoLIANBAmsvAQBBK0YNAgwJCyADQQJrLwEAQS1GDQEMCAsgBUEpRw0AIAcgBkEDdGooAgQQKA0HCwJAAkAgBkUgBUHmAEdyDQAgByAGQQN0aiIBQQhrKAIAQQFHDQAgA0ECay8BAEHvAEcNASADQQRrEClFDQEgAUEEaygCAEGeCUEDECpFDQEMCAsgBUH9AEcNACAHIAZBA3RqIgEoAgQQKw0HIAEoAgBBBkYNBwsgAxAsDQZBiAotAAAgBUEvRnEgBUEAR3NFDQZB3AkoAgAiAUUNBCADIAEoAgBJDQQgAyEEIAMgASgCBE0NBgwFCyAHIAZBA3RqIgEgAzYCBEGCCiAGQQFqOwEAIAFBAzYCAAwGCyACQTBrQf//A3FBCkkgAkEgckHhAGtB//8DcUEaSXINAAJAAkAgAkHcAGsOBAIBAQIACyACQSRGDQELIAJBoAFGIAJBgAFJcg0GCwNAIAQvAQIiAUEgckHhAGshCAJAIAFBMGtB//8DcUEKSSAIQf//A3FBGklyDQACQAJAIAFB3ABrDgQCAQECAAsgAUEkRg0BCyABQaABRiABQYABSXINBwtBmAogBEECaiIENgIADAALAAsgByAGQQN0aiIBQQE2AgBBggogBkEBajsBACABIAM2AgQMBAsgAyEECwNAIARBoIsESwRAIARBAmsiBC8BACIFEC1FDQELCyAFQf//A3EQLgRAA0AgBEGgiwRLBEBBhAogBEECayIENgIAIAQvAQAQLg0BCwsgBBAvDQELQYgKQQE6AAAMAgsQMEGICkEAOgAADAELEDELQYQKQZgKKAIAIgE2AgAMAQsQMgtBACEIQeQJLQAADQMCQCABIANGBEAgAEUNAUGCCi8BACALRiAJcUUNAUEBIQkgASEDQZgKKAIALwEAIghBCmsOBAUCAgUCCyACQS9GBEBBiAotAABBAXMhCQwBC0EBIQkgAkEwa0H//wNxQQpJIAJB3/8DcUHBAGtB//8DcUEaSXIgAkEkRiACQd8ARnJyIAJB/wBLcg0AIAEhAwJAAkAgAkEnaw4DAwEDAAsCQCACQd0Aaw4EAwEBAwALIAJBIkYgAkH9AEZyDQELQQAhCQsgASEDC0GYCigCACEFDAELCyACDwsgCAuvBAEHfyABQSJGIAFBJ0ZyRQRAEDIPC0GYCigCACEDIAEQJiAAIANBAmpBmAooAgBBARADIAIEQEHUCSgCAEEEQQYgAkEBRhs2AhwLQZgKQZgKKAIAQQJqNgIAQQAQJSEAQZgKKAIAIQQCQAJAIABB9wBHDQAgBC8BAkHpAEcNACAELwEEQfQARw0AIAQvAQZB6ABGDQELQZgKIARBAms2AgAPC0GYCiAEQQhqNgIAAkBBARAlQfsARwRADAELQewJKAIAIQNB1AkoAgAhBUGYCigCACIGIQBBACECA0AgAyEBQZgKIABBAmo2AgBBARAlIQBBmAooAgAhBwJAAkACQCAAQSJHBEAgAEEnRw0BQScQJgwCC0EiECYMAQsgABA1IQNBmAooAgAhAAwBC0GYCigCAEECaiEAQZgKIAA2AgBBARAlIQMLIANBOkcEQAwCC0GYCkGYCigCAEECajYCAEEBECUiA0EiRiADQSdGckUEQAwCC0GYCigCACEIIAMQJkHsCSABQRRqIgM2AgBBmAooAgAhCSABQQA2AhAgASAINgIIIAEgADYCBCABIAc2AgAgASAJQQJqIgA2AgwCQCACRQRAIAUgATYCIAwBCyACIAE2AhALQZgKIAA2AgACQEEBECUiAEEsRwRAIABB/QBGDQEMAwtBmApBmAooAgBBAmoiADYCACABIQIMAQsLIAUgBjYCECAFQZgKKAIAQQJqNgIMDwtBmAogBDYCAAstAQF/AkAgAC8BAEEuRw0AIABBAmsvAQBBLkcNACAAQQRrLwEAQS5GIQELIAELNQEBfwJAIABBoIsESQ0AIAAvAQAgAUcNACAAQaCLBEYEQEEBDwsgAEECay8BABAtIQILIAILKQEBfyAAQaABRiAAQQlrIgJBF01BAEEBIAJ0IAFxG3JFBEBBAA8LQQELC8cBAQBBgggLvwF4AHAAbwByAHQAZQB0AGEAbwB1AHIAYwBlAHIAbwBtAHUAbgBjAHQAaQBvAG4AbABhAHMAcwB2AG8AeQBpAGUAZABlAGwAZQBjAG8AbgB0AGkAbgBpAG4AcwB0AGEAbgB0AHkAYgByAGUAYQByAGUAdAB1AHIAZABlAGIAdQBnAGcAZQBhAHcAYQBpAHQAaAByAHcAaABpAGwAZQBmAG8AcgBpAGYAYwBhAHQAYwBmAGkAbgBhAGwAbABlAGwAcw==",typeof Buffer!="undefined"?Buffer.from(A,"base64"):Uint8Array.from(atob(A),(A)=>A.charCodeAt(0));var A};var init=WebAssembly.compile(C()).then(WebAssembly.instantiate).then(({exports:A})=>{E=A});var initSync=()=>{if(E)return;const A=new WebAssembly.Module(C());E=new WebAssembly.Instance(A).exports};import{createHash as createHash2}from"crypto";import{builtinModules}from"module";var awaitValue2=(value)=>promise2(constant(Promise.resolve(value)));var decoder=new TextDecoder("utf-8",{fatal:true});var path3=runSync2(provide3(Path2,layer5));initSync();var nodeBuiltinModules=new Set(builtinModules.map((specifier)=>specifier.replace(/^node:/u,"")));var digest2=(bytes)=>createHash2("sha256").update(bytes).digest("hex");var isEffectModuleSpecifier=(specifier)=>specifier==="effect"||/^effect(?:\/[A-Za-z0-9][\w.-]*)+$/u.test(specifier);var isNodeBuiltinModuleSpecifier=(specifier)=>nodeBuiltinModules.has(specifier.replace(/^node:/u,""));var moduleSpecifiers=(source)=>parse(source)[0].flatMap(({n:specifier})=>specifier===undefined?[]:[specifier]);var assertClosedRuntimeGraph=(entries)=>{const declaredPaths=new Set(entries.map(({path:entryPath})=>entryPath));for(const entry of entries){if(!entry.path.endsWith(".mjs")){continue}const source=decoder.decode(entry.bytes);const host=HOSTS.find((candidate)=>entry.path.startsWith(`artifacts/${candidate}/`));if(source.includes("sourceMappingURL=")){throw new TypeError(`Extension Release runtime asset '${entry.path}' exposes a public source map location`)}for(const specifier of moduleSpecifiers(source)){if(specifier.startsWith(".")){const dependencyPath=path3.normalize(path3.join(path3.dirname(entry.path),specifier));if(!declaredPaths.has(dependencyPath)){throw new TypeError(`Extension Release runtime asset '${entry.path}' has undeclared runtime dependency '${specifier}'`)}continue}if(host!==undefined&&isHostProvidedModule(host,specifier)||entry.path.startsWith("artifacts/backend/")&&(isNodeBuiltinModuleSpecifier(specifier)||isEffectModuleSpecifier(specifier))){continue}throw new TypeError(`Extension Release runtime asset '${entry.path}' has undeclared runtime dependency '${specifier}'`)}}};var assertPackageReleaseContract=(packageManifest,releaseManifest)=>{if(packageManifest.fqn!==releaseManifest.package.fqn||packageManifest.version!==releaseManifest.package.version){throw new TypeError("Extension Package and Release manifests must identify the same package FQN and version")}const declared=new Map((packageManifest.hostedContributions??[]).map((contribution)=>[`${contribution.host}\x00${contribution.fqn}`,contribution]));for(const contribution of releaseManifest.contributions){const key=`${contribution.host}\x00${contribution.fqn}`;const descriptor=declared.get(key);const syntheticPackageRuntime=contribution.host==="backend"&&contribution.fqn===`${packageManifest.fqn}.backend.package-runtime`&&contribution.exportName==="createPackageRuntime";if(descriptor===undefined){if(syntheticPackageRuntime){continue}throw new TypeError(`Extension Release contribution '${contribution.fqn}' is absent from the Package manifest`)}if(descriptor.exportName!==contribution.exportName||descriptor.contract!==contribution.contract){throw new TypeError(`Extension Release contribution '${contribution.fqn}' contract or export does not match the Package manifest`)}declared.delete(key)}if(declared.size>0){throw new TypeError(`Extension Release is missing declared contribution '${declared.values().next().value?.fqn??"unknown"}'`)}};var assertExactPrivateSourceMapInventory=(manifest,maps,mapByRuntimeDigest)=>{const declaredRuntimeDigests=new Set(manifest.assets.flatMap((asset)=>asset.privateSourceMap===undefined?[]:[asset.digest]));const hasMissingMap=[...declaredRuntimeDigests].some((runtimeDigest)=>!mapByRuntimeDigest.has(runtimeDigest));const hasExtraMap=maps.some(({runtimeAssetDigest})=>!declaredRuntimeDigests.has(runtimeAssetDigest));if(mapByRuntimeDigest.size!==declaredRuntimeDigests.size||hasMissingMap||hasExtraMap){throw new TypeError("Extension Release private source-map inventory must exactly match manifest descriptors")}};var assertPackageManifestMatchesRelease=(packageManifestBytes,releaseManifest)=>{const packageManifestText=decoder.decode(packageManifestBytes);const packageManifest=parsePackageManifest(JSON.parse(packageManifestText));if(canonicalJson(packageManifest)!==packageManifestText){throw new TypeError("Extension Package manifest is not canonical JSON")}assertPackageReleaseContract(packageManifest,releaseManifest);if(releaseManifest.packageManifest!==undefined&&canonicalJson(releaseManifest.packageManifest)!==packageManifestText){throw new TypeError("Package manifest does not match the archived declaration")}};var validatePackageRelease=(input)=>{if(!(input.packageManifestBytes instanceof Uint8Array)){throw new TypeError("Extension package manifest bytes are required")}const manifestText=decoder.decode(input.manifestBytes);const manifest=parseExtensionReleaseManifest(JSON.parse(manifestText));if(canonicalExtensionReleaseManifest(manifest)!==manifestText){throw new TypeError("Extension Release manifest is not canonical JSON")}if(digest2(input.archiveBytes)!==manifest.releaseDigest){throw new TypeError("Extension Release archive digest does not match releaseDigest")}assertPackageManifestMatchesRelease(input.packageManifestBytes,manifest);const archiveEntries=parseExtensionReleaseArchive(input.archiveBytes);const entries=validateExtensionReleaseArchiveMetadata(archiveEntries,manifest);const entryByPath=new Map(entries.map((entry)=>[entry.path,entry]));if(entryByPath.size!==manifest.assets.length){throw new TypeError("Extension Release archive does not contain exactly the declared runtime assets")}for(const asset of manifest.assets){const entry=entryByPath.get(asset.path);if(entry===undefined||entry.bytes.byteLength!==asset.size||digest2(entry.bytes)!==asset.digest){throw new TypeError(`Extension Release runtime asset '${asset.path}' does not match its manifest integrity`)}}assertClosedRuntimeGraph(entries);const maps=input.privateSourceMaps??[];const mapByRuntimeDigest=new Map(maps.map((sourceMap)=>[sourceMap.runtimeAssetDigest,sourceMap]));if(mapByRuntimeDigest.size!==maps.length){throw new TypeError("Extension Release private source maps must have unique runtime asset digests")}assertExactPrivateSourceMapInventory(manifest,maps,mapByRuntimeDigest);for(const asset of manifest.assets){const declaredMap=asset.privateSourceMap;const sourceMap=mapByRuntimeDigest.get(asset.digest);if(declaredMap===undefined&&sourceMap===undefined){continue}if(declaredMap===undefined||sourceMap===undefined||sourceMap.size!==declaredMap.size||sourceMap.bytes.byteLength!==declaredMap.size||sourceMap.digest!==declaredMap.digest||digest2(sourceMap.bytes)!==declaredMap.digest){throw new TypeError(`Extension Release private source map for runtime asset '${asset.digest}' does not match its manifest integrity`)}}return manifest};var requireOption2=(args,name)=>{const index=args.lastIndexOf(`--${name}`);const value=index===-1?undefined:args[index+1];if(value===undefined||value===""){throw new TypeError(`Missing option --${name}`)}return value};var runPackageValidationCommand=flow((args,dependencies)=>gen2(function*validatePackageReleaseCommand(){if(args.includes("--bundle")){throw new TypeError("--bundle is no longer supported; validate the immutable --archive release artifact")}const archivePath=requireOption2(args,"archive");const manifestPath=requireOption2(args,"manifest");const packageManifestPath=requireOption2(args,"package-manifest");const privateMapDirectory=args.includes("--private-maps")?requireOption2(args,"private-maps"):path3.join(path3.dirname(manifestPath),"private-source-maps");const mapFiles=yield*gen2(function*nativeAssetStep1(){yield*awaitValue2(Promise.resolve());return yield*awaitValue2(dependencies.listFiles(privateMapDirectory))});const privateSourceMaps=[];for(const fileName of mapFiles.toSorted()){privateSourceMaps.push(yield*gen2(function*readPrivateSourceMap(){if(!/^[\da-f]{64}\.map$/u.test(fileName)){throw new TypeError(`Private source-map file '${fileName}' is not keyed by a runtime asset digest`)}const bytes=yield*gen2(function*nativeAssetStep2(){yield*awaitValue2(Promise.resolve());return yield*awaitValue2(dependencies.readBytes(path3.join(privateMapDirectory,fileName)))});return{bytes,digest:digest2(bytes),runtimeAssetDigest:fileName.slice(0,-4),size:bytes.byteLength}}))}const manifest=validatePackageRelease({archiveBytes:yield*gen2(function*nativeAssetStep3(){yield*awaitValue2(Promise.resolve());return yield*awaitValue2(dependencies.readBytes(archivePath))}),manifestBytes:yield*gen2(function*nativeAssetStep4(){yield*awaitValue2(Promise.resolve());return yield*awaitValue2(dependencies.readBytes(manifestPath))}),packageManifestBytes:yield*gen2(function*nativeAssetStep5(){yield*awaitValue2(Promise.resolve());return yield*awaitValue2(dependencies.readBytes(packageManifestPath))}),privateSourceMaps});return yield*encodeEffect(fromJsonString2(Struct({package:String4,releaseDigest:String4,valid:Boolean3})))({package:manifest.package.fqn,releaseDigest:manifest.releaseDigest,valid:true})}),runPromise2);var decoder2=new TextDecoder("utf-8",{fatal:true});var preparePackagePublication=async(input)=>{const{archiveBytes,manifestBytes,packageManifestBytes}=input;const privateSourceMaps=input.privateSourceMaps??[];const manifest=validatePackageRelease({archiveBytes,manifestBytes,packageManifestBytes,privateSourceMaps});const packageManifest=parsePackageManifest(await decodePromise(fromJsonString2(Unknown2))(decoder2.decode(packageManifestBytes)));const encodedManifest={apiVersion:manifest.apiVersion,assets:manifest.assets.map((asset)=>({digest:asset.digest,host:asset.host,path:asset.path,...asset.privateSourceMap===undefined?undefined:{privateSourceMap:{digest:asset.privateSourceMap.digest,size:asset.privateSourceMap.size}},size:asset.size})),compatibility:{...manifest.compatibility},contributions:manifest.contributions.map((contribution)=>({assetPath:contribution.assetPath,...contribution.contract===undefined?undefined:{contract:contribution.contract},digest:contribution.digest,exportName:contribution.exportName,fqn:contribution.fqn,host:contribution.host,size:contribution.size})),package:{...manifest.package},...manifest.packageManifest===undefined?undefined:{packageManifest:manifest.packageManifest},releaseDigest:manifest.releaseDigest};return{artifact:{archiveBase64:Buffer.from(archiveBytes).toString("base64"),privateSourceMaps:privateSourceMaps.map((sourceMap)=>({bytesBase64:Buffer.from(sourceMap.bytes).toString("base64"),digest:sourceMap.digest,runtimeAssetDigest:sourceMap.runtimeAssetDigest,size:sourceMap.size}))},manifest:encodedManifest,packageFqn:manifest.package.fqn,packageManifest,protocolVersion:"v1",version:manifest.package.version}};class DeployCommandError extends TaggedError3()("DeployCommandError",{cause:optional2(Unknown2),json:Boolean3,lastEventId:optional2(Int),message:String4,nextAction:optional2(String4),operationId:optional2(String4),status:optional2(String4)}){}var values=new Set(["backend-url","declaration","organization","gateway-url","profile","setup-file","timeout-ms"]);var switches=new Set(["accept-breaking-changes","non-interactive","json"]);var gatewayOrigin=(value,fqn,reject)=>{let url;try{url=new URL(value)}catch{return reject(`Invalid Gateway URL for '${fqn}'`)}if(url.protocol!=="https:"||url.username!==""||url.password!==""||url.search!==""||url.hash!==""||url.pathname!=="/"){return reject(`Gateway URL for '${fqn}' must be an HTTPS origin without credentials, path, query or fragment`)}return url.origin};var addGatewayBinding=(gatewayUrls,value,reject)=>{const separator=value.indexOf("=");if(separator<=0){reject("--gateway-url must be <GatewayFQN>=<URL>")}const fqn=value.slice(0,separator);if(Object.hasOwn(gatewayUrls,fqn)){reject(`Duplicate Gateway URL binding '${fqn}'`)}Object.defineProperty(gatewayUrls,fqn,{enumerable:true,value:gatewayOrigin(value.slice(separator+1),fqn,reject)})};var parseDeployOptions=(args)=>{const options=new Map;const gatewayUrls={};const json=args.includes("--json");const reject=(message)=>{throw new DeployCommandError({json,message})};for(let index=0;index<args.length;index+=1){const flag=args[index];if(flag===undefined||!flag.startsWith("--")){reject("Expected --name value options or --non-interactive/--json switches")}const name=flag.slice(2);if(!values.has(name)&&!switches.has(name)){reject(`Unknown option ${flag}`)}if(options.has(name)&&name!=="gateway-url"){reject(`Duplicate option ${flag}`)}if(switches.has(name)){options.set(name,"true");continue}const value=args[index+1];if(!value||value.startsWith("--")){reject(`Missing value for ${flag}`)}index+=1;if(name==="gateway-url"){addGatewayBinding(gatewayUrls,value,reject)}else{options.set(name,value)}}const required=(name)=>{const value=options.get(name);return value!==undefined&&value.trim()!==""?value:reject(`Missing required option --${name}`)};const timeoutMs=Number(options.get("timeout-ms")??"300000");if(!Number.isSafeInteger(timeoutMs)||timeoutMs<=0){reject("--timeout-ms must be a positive integer")}return{acceptBreakingChanges:options.has("accept-breaking-changes"),declaration:required("declaration"),gatewayUrls,json,...options.has("setup-file")?{setupFile:required("setup-file")}:undefined,timeoutMs}};var deployCommandEffect=fn2("Deploy.command")(function*deployCommandEffect(options,dependencies){const context=yield*context2();const runFollower=runPromiseWith2(context);const writeProgress=options.json?dependencies.writeOutput:dependencies.writeDiagnostic;let operationId;let lastEventId;return yield*tryPromise2({catch:(cause)=>is2(DeployCommandError)(cause)?cause:new DeployCommandError({cause,json:options.json,lastEventId,message:is2(PackageOperationCommandError)(cause)?cause.message:"Could not deploy package",operationId}),try:async(signal)=>{const setup=options.setupFile===undefined?undefined:await readConnectorSetup(options.setupFile);const release=await buildPackageRelease({declarationSpecifier:dependencies.resolveDeclarationSpecifier(options.declaration)});const publication=await preparePackagePublication(release);const lookupBody={packageFqn:release.manifest.package.fqn,releaseDigest:release.releaseDigest,version:release.manifest.package.version};const lookup=async()=>{const response=await packageReleasesLookupPublished({body:lookupBody,client:dependencies.publisher,signal,throwOnError:true});return response.data.release};let{gatewayUrls}=options;const key=(stage)=>`ci-deploy-${stage}-${createHash3("sha256").update(canonicalJson({...lookupBody,acceptBreakingChanges:options.acceptBreakingChanges,gatewayUrls,organizationId:options.organizationId,...setup===undefined?undefined:{setup}})).digest("hex")}`;const follow=async(acceptedId,client)=>{operationId=acceptedId;lastEventId=0;writeProgress(`${JSON.stringify({kind:"progress",operationId,status:"accepted"})}
|
|
299
|
+
`,E.e()-1)}`),{idx:E.e()});const o=[],G=[];for(;E.ri();){const A=E.is(),B=E.ie(),Q=E.it(),g=E.ai(),I=E.id(),w=E.ss(),D=E.se();let G;E.ip()&&(G=i(C.slice(I===-1?A-1:A,I===-1?B+1:B)));let J=null;for(J=[],E.rsa();E.ra();){const A=E.aks(),B=E.ake(),Q=E.avs(),g=E.ave();J.push([s(C.slice(A,B)),s(C.slice(Q,g))])}J.length===0&&(J=null),o.push({n:G,t:Q,s:A,e:B,ss:w,se:D,d:I,a:g,at:J})}for(;E.re();){const A=E.es(),B=E.ee(),Q=E.els(),g=E.ele(),I=Q<0?undefined:s(C.slice(Q,g)),w=s(C.slice(A,B));G.push({s:A,e:B,ls:Q,le:g,ss:E.ess(),n:w,ln:I})}function i(A){try{return(0,eval)(A)}catch(A){}}function s(A){if(!A)return A;const B=A[0];return(B==='"'||B==="'")&&i(A)||A}return[o,G,!!E.f(),!!E.ms()]}function B(A,B){const Q=A.length;let E=0;for(;E<Q;){const Q=A.charCodeAt(E);B[E++]=(255&Q)<<8|Q>>>8}}function Q(A,B){const Q=A.length;let E=0;for(;E<Q;)B[E]=A.charCodeAt(E++)}var E;var C=()=>{return A="AGFzbQEAAAABKwhgAAF/YAF/AX9gAABgAn9/AX9gBH9/f38AYAN/f38Bf2ABfwBgA39/fwADPj0CAgEEBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgABBQICAgYBAQYBAQEFAQEBAQECAgIBAQEDAQEHAQMDBAUBcAECAgUHAQGCAoCAAgYPAn8BQaCLBAt/AEGgiwQLB80BHgZtZW1vcnkCAAJzYQACAWUABQJpcwAGAmllAAcCc3MACAJzZQAJAml0AAoCYWkACwJpZAAMAmlwAA0CZXMADgJlZQAPA2VscwAQA2VsZQARA2VzcwASAnJpABMCcmUAFAFmABUCbXMAFgJyYQAXA2FrcwAYA2FrZQAZA2F2cwAaA2F2ZQAbA3JzYQAcBXBhcnNlAB0LX19oZWFwX2Jhc2UDAQtfaW5pdGlhbGl6ZQABGV9faW5kaXJlY3RfZnVuY3Rpb25fdGFibGUBAAkHAQBBAQsBAAwBAQrZVz0oAEHYCkGAwAA2AgBB0ApBoIsENgIAQbgKQSo2AgBB1ApBgIAENgIACwQAEAALWQBB6AkgADYCACAAQQF0IgBBADsBoIsEQewJIABBoosEajYCAEHECUEANgIAQdQJQQA2AgBBzAlBADYCAEHICUEANgIAQdwJQQA2AgBB0AlBADYCAEGgiwQLuAEBAn9B7AlB7AkoAgAiBEEoajYCAAJAQdQJKAIAIgVFBEBBxAkgBDYCAAwBCyAFIAQ2AiQLQdQJIAQ2AgBB2AkgBTYCACAEIAA2AgggBEIANwIgIAQgA0EBRiIAOgAYIAQgAzYCFCAEQQA2AhAgBCACNgIEIAQgATYCACAEQQNBAUECIAAbIANBAkYiARs2AhwgBCACIAJBAmpBACAAGyABGzYCDCADQQFrQQFNBEBB8AlBAToAAAsLdwECf0HsCUHsCSgCACIEQRhqNgIAAkBB3AkoAgAiBUUEQEHICSAENgIADAELIAUgBDYCFAtB3AkgBDYCACAEIAM2AgwgBCACNgIIIAQgATYCBCAEIAA2AgBB4AkoAgAhACAEQQA2AhQgBCAANgIQQfAJQQE6AAALCABB9AkoAgALEwBBzAkoAgAoAgBBoIsEa0EBdQscAQF/QcwJKAIAKAIEIgBBoIsEa0EBdUF/IAAbCxMAQcwJKAIAKAIIQaCLBGtBAXULHAEBf0HMCSgCACgCDCIAQaCLBGtBAXVBfyAAGwsLAEHMCSgCACgCHAscAQF/QcwJKAIAKAIQIgBBoIsEa0EBdUF/IAAbCzUBAn9BfyEAAkACQAJAQcwJKAIAKAIUIgFBAWsOAgIBAAsgAUGgiwRrQQF1DwtBfiEACyAACwsAQcwJKAIALQAYCxMAQdAJKAIAKAIAQaCLBGtBAXULEwBB0AkoAgAoAgRBoIsEa0EBdQscAQF/QdAJKAIAKAIIIgBBoIsEa0EBdUF/IAAbCxwBAX9B0AkoAgAoAgwiAEGgiwRrQQF1QX8gABsLEwBB0AkoAgAoAhBBoIsEa0EBdQslAQF/QcwJQcwJKAIAIgBBJGpBxAkgABsoAgAiADYCACAAQQBHCyUBAX9B0AlB0AkoAgAiAEEUakHICSAAGygCACIANgIAIABBAEcLCABB+AktAAALCABB8AktAAALKwEBf0H8CUH8CSgCACIAQRBqQcwJKAIAQSBqIAAbKAIAIgA2AgAgAEEARwsTAEH8CSgCACgCAEGgiwRrQQF1CxMAQfwJKAIAKAIEQaCLBGtBAXULEwBB/AkoAgAoAghBoIsEa0EBdQsTAEH8CSgCACgCDEGgiwRrQQF1CwoAQfwJQQA2AgAL3g8BBn8jAEGA0ABrIgQkAEH4CUEBOgAAQYAIIQBBhApBgAg2AgBBnApBnosEIgJB6AkoAgBBAXRqIgU2AgBB8AlBADoAAEGACkEAOwEAQYIKQQA7AQBBiApBADoAAEH0CUEANgIAQeQJQQA6AABBjAogBEGAEGo2AgBBkAogBDYCAEGUCkEAOgAAA0AgACEBQZgKIAJBAmoiADYCAAJAAkACfwJAAkAgAiAFSQRAIAAvAQAiA0EJa0EFSQ0EAkACQAJAAkACQCADQeUAaw4FAQYGBgIACyADQSBGDQggA0EvRg0DIANBO0YNAgwFC0GCCi8BAA0BIAAQHkUNASACQQRqQYIIQQoQHw0BECBBmAooAgAhAEH4CS0AAA0BQYQKIAA2AgAgACIBIQIMBQsgAi8BBEHtAEcNACAAEB5FDQAgAikABkLwgLyDoI6AOlINABAhQZgKKAIAIQALQYQKIAA2AgAMBgsgAi8BBCIAQSpHBEAgAEEvRw0CECIMBQtBARAjDAQLIAAhAkEAQeQJLQAADQIaDAELQfgJQQA6AAALA0ACQEGYCiACQQJqIgA2AgACQAJAAkACQCACIAVJBEACQAJAAkACQAJAAkACQAJAAkACQAJAIAAvAQAiA0Egaw4QDwgFCAgICAUKAggIAQgIBgALAkACQAJAAkACQAJAIANB2wBrDg8EDQUNDQwNDQMNAQ0NDQIACyADQQlrQQVJDRMgA0H7AGsOAwcMCAwLQYIKLwEADQwgABAeRQ0MIAJBBGpBgghBChAfDQwQIAwRCyACLwEEQe0ARw0LIAAQHkUNCyACKQAGQvCAvIOgjoA6Ug0LECEMEAsgAi8BBEHsAEcNCiAAEB5FDQogAkEGakGyCEEGEB8NCiACLwEMECRFDQpBlApBAToAAAwKC0GCCkGCCi8BACIAQQFqOwEAIARBgBBqIABBA3RqIgBBCDYCACAAIAE2AgQMDgtBggovAQAiAEUND0GCCiAAQQFrOwEADA0LQYAKLwEAIgBFDQxBggovAQAiA0UNDCADQQN0IARqQfgPaigCAEEFRw0MIAQgAEECdGpBBGsoAgAiACgCBA0MIAAgAUECajYCBEGYCiACQQRqNgIAQQEQJRogAEGYCigCACIANgIQQZgKIABBAms2AgAMDAtBggovAQAiAEUNDUGCCiAAQQFrIgM7AQBBgAovAQAiAEUNCyAEQYAQaiADQf//A3FBA3RqKAIAQQVHDQsgBCAAQQJ0akEEaygCACIDKAIERQRAIAMgAUECajYCBAsgAyACQQRqNgIMQYAKIABBAWs7AQAMCwsCQCABLwEAQSlHDQBB1AkoAgAiAEUNACAAKAIMIAFBAmpHDQBB1AlB2AkoAgAiADYCACAABEAgAEEANgIkDAELQcQJQQA2AgALQYIKQYIKLwEAIgBBAWo7AQAgBEGAEGogAEEDdGoiAEEGQQJBlAotAAAbNgIAIAAgATYCBEGUCkEAOgAADAoLQYIKLwEAIgBFDQtBggogAEEBayIAOwEAIARBgBBqIABB//8DcUEDdGooAgBBBEcNCQwICyADECYMCAsCQCACLwEEIgBBKkcEQCAAQS9HDQEQIgwKC0EBECMMCQsCQCABLwEAIgAQJwRAAkACQAJAIABBK2sOBAEKAgAKCyABQQJrLwEAQTBrQf//A3FBCkkNAwwJCyABQQJrLwEAQStGDQIMCAsgAUECay8BAEEtRg0BDAcLIABBKUcNACAEQYAQakGCCi8BAEEDdGooAgQQKA0GCwJAAkBBggovAQAiAkUgAEHmAEdyDQAgBEGAEGogAkEDdGoiA0EIaygCAEEBRw0AIAFBAmsvAQBB7wBHDQEgAUEEaxApRQ0BIANBBGsoAgBBnglBAxAqRQ0BDAcLIABB/QBHDQAgBEGAEGogAkEDdGoiAigCBBArDQYgAigCAEEGRg0GCyABECwNBUGICi0AACAAQS9GcSAAQQBHc0UNBQJAQdwJKAIAIgJFDQAgASACKAIASQ0AIAEgAigCBE0NBgsDQCABQaCLBEsEQEGECiABQQJrIgE2AgAgAS8BACIAEC1FDQELCyAAQf//A3EQLgRAA0AgAUGgiwRLBEBBhAogAUECayIBNgIAIAEvAQAQLg0BCwsgARAvDQYLQYgKQQE6AAAMBwtBggpBggovAQAiAEEBajsBACAEQYAQaiAAQQN0aiIAIAE2AgQgAEEDNgIADAULIANBMGtB//8DcUEKSSADQSByQeEAa0H//wNxQRpJcg0AAkACQCADQdwAaw4EAgEBAgALIANBJEYNAQsgA0GgAUYgA0GAAUlyDQULA0AgAC8BAiIBQSByQeEAayECAkAgAUEwa0H//wNxQQpJIAJB//8DcUEaSXINAAJAAkAgAUHcAGsOBAIBAQIACyABQSRGDQELIAFBoAFGIAFBgAFJcg0GC0GYCiAAQQJqIgA2AgAMAAsAC0GCCkGCCi8BACIAQQFqOwEAIARBgBBqIABBA3RqIgBBATYCACAAIAE2AgQMAwtBgAovAQBFQYIKLwEARUHkCS0AAEF/c3FxDAYLEDBBiApBADoAAAwBCxAxC0GECkGYCigCACIBNgIAC0GYCigCACECDAELCxAyQQALIQMgBEGA0ABqJAAgAw8LIAEhAAtBmAooAgAhAgwACwALFgAgAEGgiwRGBEBBAQ8LIABBAmsQMwtDAQN/AkAgAkUNAANAIAAtAAAiBCABLQAAIgVGBEAgAUEBaiEBIABBAWohACACQQFrIgINAQwCCwsgBCAFayEDCyADC9IIAQV/QZgKQZgKKAIAIgRBDGoiATYCAEHcCSgCACEDQQEQJSECAkACQAJAAkACQAJAIAFBmAooAgAiAEYEQCACEDRFDQELQeAJIAQ2AgACQAJAAkAgAkEqRwRAIAJB+wBHDQFBmAogAEECajYCAEEBECUhAkGcCigCACEBQZgKKAIAIQADQAJAIAJB//8DcSICQSJGIAJBJ0ZyRQRAIAIQNRpBmAooAgAhAgwBCyACECZBmApBmAooAgBBAmoiAjYCAAtBARAlGiAAIAIQNiICQSxGBEBBmApBmAooAgBBAmo2AgBBARAlIQILIAJB/QBGDQMgAEGYCigCACIARg0IIAAgAU0NAAsMBwtBmAogAEECajYCAEEBECUaQZgKKAIAIgAgABA2GgwCC0H4CUEAOgAAAkACQAJAAkACQAJAIAJB4QBrDgwCCAQBCAMICAgICAUACyACQfYARg0EDAcLQZgKIABBDmoiBDYCAAJAAkACQAJAQQEQJUHhAGsOBgAMAgwMAQwLQZgKKAIAIgEpAAJC84Dkg+CNwDFSDQsgAS8BChAuRQ0LQZgKIAFBCmo2AgBBABAlGgtBmAooAgAiA0ECakGiCEEOEB8NCgJAIAMvARAiARAkDQAgAUEoaw4DAAsACwtBmAogA0EQajYCAEEBECUiAUEqRgRAQZgKQZgKKAIAQQJqNgIAQQEQJSEBCyABQShHDQEMCgtBmAooAgAiAykAAkLsgISDsI7AOVINCSADLwEKIgEQJEUgAUH7AEdxDQlBmAogA0EKajYCAEEBECUiAUH7AEYNCQtBmAooAgAhAyABEDUaQZgKKAIAIgEgA00NCCAAIAQgAyABEAQMCgtBmAogAEEKajYCAEEAECUaQZgKKAIAIQALQZgKIABBEGo2AgBBARAlIgBBKkYEQEGYCkGYCigCAEECajYCAEEBECUhAAsMCQsCQCAAKQACQuyAhIOwjsA5Ug0AIAAvAQoQLUUNAEGYCiAAQQpqNgIAQQEQJSEADAkLIABBBGohAAtBmAogAEEGajYCAEGcCigCACEDA0BBARAlIQBBmAooAgAiASADSw0HIAAQNyECQZgKKAIAIgAgAUYNBCACQT1GBEBBARA4IQJBmAooAgAhAAsgAkEsRw0EQZgKIABBAmo2AgAMAAsAC0HwCUEBOgAAQZgKQZgKKAIAQQJqNgIAC0EBECUhAEGYCigCACEBAkAgAEHmAEcNACABQQJqQZwIQQYQHw0AQZgKIAFBCGo2AgAgBEEBECVBABA5IANBFGpByAkgAxshAgNAIAIoAgAiAEUNAiAAQgA3AgggAEEUaiECDAALAAtBmAogAUECazYCAAsPCyAAIQEMAgsgACAEQQBBABAEQZgKIABBDGo2AgAPCxAyDwtBmAogAUECazYCAA8LQZgKKAIAIQEgABA1GiABQZgKKAIAIgAgASAAEARBmAogAEECazYCAAuKCwEKf0GYCkGYCigCACIGQQxqIgk2AgBBARAlIQBBmAooAgAhAgJAAkACQAJAAkACQAJ/IABBLkYEQEGYCiACQQJqNgIAQQEQJSIAQeQARwRAIABB8wBHBEAgAEHtAEcNB0GYCigCACIAQQJqQYwIQQYQHw0HQYQKKAIAIgEQOkUEQCABLwEAQS5GDQgLIAYgBiAAQQhqQQIQAw8LQZgKKAIAIgBBAmpBkghBChAfDQZBhAooAgAiARA6RQRAIAEvAQBBLkYNBwtBmAogAEEMajYCAEEBIQhBBSEEQQEQJSEAQQEMAgtBmAooAgAiACkAAkLlgJiD0IyAOVINBUGECigCACIBEDpFBEAgAS8BAEEuRg0GC0GYCiAAQQpqNgIAQQchBEEBIQVBARAlIQBBASEIQQIMAQsCQAJAIABB8wBHIAIgCU1yRQRAQfMAIQAgAkECakGSCEEKEB8NASACLwEMECRFDQFBmAogAkEMaiIANgIAQQEhCEEBECUhASAAQZgKKAIAIgRHBEBB5gAhACABQeYARwRAQQUhBCABIQBBAQwFC0EBIQMgBEECakGcCEEGEB8NBSAELwEIEC1FDQULQZgKIAI2AgBBByEEQQEhB0EAIQggASEAQQAMAwtBByEEQQEhByAAQeQARyACIAZBCmpNcg0BQeQAIQAgAikAAkLlgJiD0IyAOVINACACLwEKECRFDQBBmAogAkEKajYCAEEqIQBBASEFQQIhA0EBECUiAUEqRg0EQZgKIAI2AgBBACEFIAEhAEEADAILIAIhBAwCC0EACyEDIABBKEYEQEGMCigCAEGCCi8BACIFQQN0aiIAQQU2AgBBggogBUEBajsBACAAQZgKKAIAIgI2AgRBhAooAgAvAQBBLkYNBEGYCiACQQJqNgIAQQEQJSEAIAZBmAooAgAiAUEAIAIQA0HUCSgCACEDIAgEQCADIAQ2AhwLQYAKQYAKLwEAIgRBAWo7AQBBkAooAgAgBEECdGogAzYCAAJAIABBIkYgAEEnRnJFBEACQCAAQeAARw0AQZwKKAIAIQYgASEAA0AgACICIAZPDQECQAJAIABBAmoiAC8BACIHQdwAaw4FAAICAgUBCyACQQRqIQAMAQsgB0EkRw0AIAIvAQRB+wBHDQALC0GYCiABQQJrNgIADwsgABAmQZgKKAIAIQALQZgKIABBAmoiADYCAAJAAkACQEEBECVBKWsOBAECAgACC0GYCkGYCigCAEECajYCAEEBECUaIAMgADYCBEGYCigCACEAIANBAToAGCADIAA2AhAMCAtBggogBTsBACADIAA2AgRBmAooAgAhACADQQE6ABggAyAAQQJqNgIMQYAKIAQ7AQAPC0GYCkGYCigCAEECazYCAA8LIAdFIABB+wBHckUEQEGYCigCACEAQYIKLwEADQZBnAooAgAhAQNAAkACQCAAIAFJBEBBARAlIgBBIkYgAEEnRnINASAAQf0ARw0CQZgKQZgKKAIAQQJqNgIAC0EBECUhAUGYCigCACEAIAFB5gBGBEAgAEECakGcCEEGEB8NBwtBmAogAEEIajYCAEEBECUiAEEiRyAAQSdHcQ0GIAYgAEEAEDkPCyAAECYLQZgKQZgKKAIAQQJqIgA2AgAMAAsACwJAAkAgAEEnaw4EAwEBAwALIABBIkYNAgtBmAooAgAhBAsgBCAJRw0AQZgKIARBAms2AgAPCyAAQSpHIAVxDQJBggovAQANAkGYCigCACEAQZwKKAIAIQIDQCAAIAJPDQEgAC8BACIBQSdHIAFBIkdxBEBBmAogAEECaiIANgIADAEFIAYgASADEDkPCwALAAsQMgsPC0GYCkGYCigCAEECazYCAA8LQZgKIABBAms2AgALQwEDf0GYCigCACEAQZwKKAIAIQIDQAJAIABBAmohASAAIAJPDQAgASEAIAEvAQBBCmsOBAABAQABCwtBmAogATYCAAtwAQR/QZgKKAIAQQJqIQFBnAooAgAhBAJAA0AgASICQQJqIQEgAiAETw0BIAEvAQAhAwJAIABFBEAgA0EqRg0BIANBCmsOBAMCAgMCCyADQSpHDQELIAIvAQRBL0cNAAsgAkEEaiEBC0GYCiABNgIACwsAIABBn4CABBA8C30BBH9BnAooAgAhA0GYCigCACEBA0ACQAJAAkAgAS8BACICQS9GBEAgAS8BAiIBQSpHBEAgAUEvRg0CQS8PCyAAECMMAgsgAARAIAIQJA0CDAMLIAIQLg0BDAILECILQZgKQZgKKAIAIgRBAmoiATYCACADIARLDQELCyACC4YBAQR/QZgKKAIAIQFBnAooAgAhBAJAA0ACQCABIgJBAmohASACIARPDQAgAS8BACIDIABGDQIgA0HcAEcEQCADQQprDgQBAgIBAgsgAkEEaiEBIAIvAQRBDUcNASACQQZqIAEgAi8BBkEKRhshAQwBCwtBmAogATYCABAyDwtBmAogATYCAAtuAQF/AkAgAEEpRyAAQShrQf//A3FBB0lxIABBIWsiAUEFTUEAQQEgAXRBMXEbckUEQCAAQTprIgFB//8DcUElT0K/gICAoAIgAa2Ip0EBcUVyDQELQQEPCyAAQf0ARyAAQfsAa0H//wNxQQRJcQsuAQF/QQEhAQJAIABBlAlBBRAqDQAgAEGeCUEDECoNACAAQaQJQQIQKiEBCyABC28BAX8CfyAALwEAIgEQJCABQSlGciABQf0ARnJFBEBBACABQd0ARw0BGgsDQAJAIABBoIsETQ0AIAEQJEUNACAAQQJrIgAvAQAhAQwBCwtBASABQSlGIAFB3QBGciABQf0ARnINABogARA0QQFzCws+AQJ/AkAgACACQQF0IgJrIgRBAmoiAEGgiwRJDQAgACABIAIQHw0AIABBoIsERgRAQQEPCyAEEDMhAwsgAwuDAQECf0EBIQICQAJAAkACQAJAAkAgAC8BACIBQTtrDgQFBAQBAAsCQCABQeUAaw4EAwQEAgALIAFBKUYNBCABQfkARw0DIABBAmtBsAlBBhAqDwsgAEECay8BAEE9Rg8LIABBAmtBqAlBBBAqDwsgAEECa0G8CUEDECoPC0EAIQILIAILqgMBAn8CQAJAAkACQAJAAkACQAJAAkACQCAALwEAQeQAaw4UAAECCQkJCQMJCQQFCQkGCQcJCQgJCwJAAkAgAEECay8BAEHpAGsOBAAKCgEKCyAAQQRrQbgIQQIQKg8LIABBBGtBvAhBAxAqDwsCQAJAAkAgAEECay8BAEHzAGsOAwABAgoLIABBBGsvAQAiAUHhAEcEQCABQewARw0KIABBBmtB5QAQOw8LIABBBmtB4wAQOw8LIABBBGtBwghBBBAqDwsgAEEEa0HKCEEGECoPCyAAQQJrLwEAQe8ARw0GIABBBGsvAQBB5QBHDQYgAEEGay8BACIBQfAARwRAIAFB4wBHDQcgAEEIa0HWCEEGECoPCyAAQQhrQeIIQQIQKg8LIABBAmtB5ghBBBAqDwtBASECIABBAmsiAEHpABA7DQQgAEHuCEEFECoPCyAAQQJrQeQAEDsPCyAAQQJrQfgIQQcQKg8LIABBAmtBhglBBBAqDwsgAEECay8BACIBQe8ARwRAIAFB5QBHDQEgAEEEa0HuABA7DwsgAEEEa0GOCUEDECohAgsgAgs0AQF/IABBoAFGIABBCWsiAUEXTUEAQQEgAXRBn4CABHEbckUEQCAAEDQgAEEuR3EPC0EBCwsAIABBjYCABBA8C0gBAn8CQCAALwEAIgJB5QBHBEAgAkHrAEcNASAAQQJrQeYIQQQQKg8LIABBAmsvAQBB9QBHDQAgAEEEa0HKCEEGECohAQsgAQvbAQEEf0GYCigCACEAQZwKKAIAIQMDQCAAQQJqIQECQAJAIAAgA08NAAJAAkACQCABLwEAIgJB2wBrDgIBAgALIAEhACACQQprDgQCBAQCAwsCQANAAkAgAUECaiEAIAEgA08NAAJAAkAgAC8BACICQdwAaw4CAAQBCyABQQRqIQEMAgsgACEBIAJBCmsOBAABAQABCwtBmAogADYCABAyQZgKKAIAIQAMBAtBmAogADYCAAwDCyAAQQRqIQAMAgtBmAogATYCABAyDwsgAkEvRw0AC0GYCiAANgIAC94BAQR/QZgKKAIAIQBBnAooAgAhAwJAAkADQAJAIAAiAUECaiEAIAEgA08NAAJAAkACQCAALwEAIgJB3ABrDgUCBAQEAQALIAJBJEcNAyABLwEEQfsARw0DQZgKIAFBBGoiAjYCAEGMCigCAEGCCi8BACIAQQN0aiIBQQQ2AgBBggogAEEBajsBACABIAI2AgQPC0GYCiAANgIAQYIKQYIKLwEAQQFrIgE7AQBBjAooAgAgAUH//wNxQQN0aigCAEEDRw0DDAQLIAFBBGohAAwBCwtBmAogADYCAAsQMgsLMwEBf0HkCUEBOgAAQZgKKAIAIQBBmApBnAooAgBBAmo2AgBB9AkgAEGgiwRrQQF1NgIACz0BAX8Cf0EBIAAvAQAiAUEJa0H//wNxQQVJIAFBgAFyQaABRnINABpBACABEDRFDQAaIAAQOiABQS5HcgsLXgEBfwJAIABB+P8DcUEoRiAAQSFrIgFBBU1BAEEBIAF0QTFxG3JFBEAgAEE6ayIBQf//A3FBJU9Cv4CAgKADIAGtiKdBAXFFcg0BC0EBDwsgAEH7AGtB//8DcUEESQtXAQN/QZgKKAIAIQEDQAJAIABB//8DcSICECQEQCAAIQMMAQsgACEDIAIQNA0AQQAhA0GYCiABQQJqIgI2AgAgAS8BAiEAIAIhASAADQELCyADQf//A3ELpQEBBH8CQEGYCigCACIDLwEAIgVB4QBHBEAgASECIAAhBAwBC0GYCiADQQRqNgIAQQEQJSECQZgKKAIAIQQCQCACQSJGIAJBJ0ZyRQRAIAIQNRpBmAooAgAhAgwBCyACECZBmApBmAooAgBBAmoiAjYCAAtBARAlIQVBmAooAgAhAwsgAyAERwRAIAQgAkEAIAAgACABRiIAG0EAIAEgABsQBAsgBQvTBAEHf0GYCigCACEBAkAgAEHf/wNxQdsARgRAIAEvAQAhBUGYCiABQQJqNgIAQf0AQd0AIAVB+wBGGyEGQQEQJSEDQZwKKAIAIQcDQAJAIAYgA0H//wNxIgJGQZgKKAIAIgEgB0tyDQACQCACQS5HDQAgAS8BAkEuRw0AIAEvAQRBLkcNAEGYCiABQQZqNgIAQQEQJRA3IQMMAgsCQAJ/AkAgBUH7AEYEQAJAIAJBIkYgAkEnRnJFBEAgAkHbAEcNAUEAEDgaQZgKQZgKKAIAQQJqNgIAIAEMBAsgAhAmQZgKQZgKKAIAQQJqNgIAIAEMAwsgASEAIANBMGtB//8DcUEJSw0BA0AgACICQQJqIQAgAi8BAiIDQTBrQf//A3FBCkkNACADQcEAayIEQR5NQQBBASAEdEG/gIGEBHEbDQAgA0HhAGsiBEEXTUEAQQEgBHRBv8CBBHEbDQACQAJAIANBK2sOBAABAAIBCyACLwEAQSByQeUARg0BCwtBmAogADYCACABDAILIAJBLEYEQEGYCiABQQJqNgIAQQEQJSEDDAULIAIQNyECDAILIAIQNRpBmAooAgALIQBBARAlIgJBOkYEQEGYCkGYCigCAEECajYCAEEBECUQNyECDAELIAAgAU0NACABIAAgASAAEAQLIAJBPUYEQEEAEDghAgtBmAooAgAhASACQSxHDQBBmAogAUECajYCAEEBECUhAwwBCwtBmAogAUECajYCAAwBCyAAEDUaQZgKKAIAIgAgAU0NACABIAAgASAAEAQLQQEQJQvgDgEMf0GECkGYCigCACIBNgIAQZAKKAIAIQpBjAooAgAhB0GcCigCACEMQYIKLwEAIQsgASIDIQUCQANAQZgKIAVBAmoiBDYCACAFIAxPBEBBACEIDAILAkACQCAELwEAIgIQLg0AAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQEGCCi8BACIGIAtHDQAgAiEIAkACQCACQSlrDgQcAQEcAAsgAkE7RiACQd0ARnIgAkH9AEZyDRkLIAAgCXFBAUcNAAJAIAJBImsODgsODg4OCxAIDg4HDg4MAAsCQCACQdsAaw4PBQ4GDg4NDg4EDgIODg4DAAsCQCACQfsAaw4DCQ4KAAsgAkEKaw4EGg0NGg0LAkAgAkEiaw4OCg0NDQ0KDwcNDQYNDQsACwJAIAJB2wBrDg8EDQUNDQwNDQMNAQ0NDQIACwJAIAJBCmsOBBcNDRcACyACQfsAaw4DBwwIDAsgBg0MIAQQHkUNDCAFQQRqQYIIQQoQHw0MECAMEgsgBS8BBEHtAEcNCyAEEB5FDQsgBSkABkLwgLyDoI6AOlINCxAhDBELIAUvAQRB7ABHDQogBBAeRQ0KIAVBBmpBsghBBhAfDQogBS8BDBAkRQ0KQZQKQQE6AAAMCgsgByAGQQN0aiIBQQg2AgBBggogBkEBajsBACABIAM2AgQMDwsgBkUND0GCCiAGQQFrOwEADA4LIAZFDQ1BgAovAQAiAUUNDSAHIAZBA3RqQQhrKAIAQQVHDQ0gCiABQQJ0akEEaygCACIBKAIEDQ0gASADQQJqNgIEQZgKIAVBBGo2AgBBARAlGiABQZgKKAIAIgE2AhBBmAogAUECazYCAAwNCyAGRQ0NQYIKIAZBAWsiBDsBAEGACi8BACIBRQ0MIAcgBEH//wNxQQN0aigCAEEFRw0MIAogAUECdGpBBGsoAgAiBCgCBEUEQCAEIANBAmo2AgQLIAQgBUEEajYCDEGACiABQQFrOwEADAwLAkAgAy8BAEEpRw0AQdQJKAIAIgFFDQAgASgCDCADQQJqRw0AQdQJQdgJKAIAIgE2AgAgAQRAIAFBADYCJAwBC0HECUEANgIACyAHIAZBA3RqIgFBBkECQZQKLQAAGzYCAEGCCiAGQQFqOwEAIAEgAzYCBEGUCkEAOgAADAsLIAZFDQtBggogBkEBayIBOwEAIAcgAUH//wNxQQN0aigCAEEERw0KDAkLIAIQJgwJCwJAIAUvAQQiBEEqRwRAIARBL0cNARAiDAwLQQEQIwwLCwJAIAMvAQAiBRAnBEACQAJAAkAgBUEraw4EAQsCAAsLIANBAmsvAQBBMGtB//8DcUEKSQ0DDAoLIANBAmsvAQBBK0YNAgwJCyADQQJrLwEAQS1GDQEMCAsgBUEpRw0AIAcgBkEDdGooAgQQKA0HCwJAAkAgBkUgBUHmAEdyDQAgByAGQQN0aiIBQQhrKAIAQQFHDQAgA0ECay8BAEHvAEcNASADQQRrEClFDQEgAUEEaygCAEGeCUEDECpFDQEMCAsgBUH9AEcNACAHIAZBA3RqIgEoAgQQKw0HIAEoAgBBBkYNBwsgAxAsDQZBiAotAAAgBUEvRnEgBUEAR3NFDQZB3AkoAgAiAUUNBCADIAEoAgBJDQQgAyEEIAMgASgCBE0NBgwFCyAHIAZBA3RqIgEgAzYCBEGCCiAGQQFqOwEAIAFBAzYCAAwGCyACQTBrQf//A3FBCkkgAkEgckHhAGtB//8DcUEaSXINAAJAAkAgAkHcAGsOBAIBAQIACyACQSRGDQELIAJBoAFGIAJBgAFJcg0GCwNAIAQvAQIiAUEgckHhAGshCAJAIAFBMGtB//8DcUEKSSAIQf//A3FBGklyDQACQAJAIAFB3ABrDgQCAQECAAsgAUEkRg0BCyABQaABRiABQYABSXINBwtBmAogBEECaiIENgIADAALAAsgByAGQQN0aiIBQQE2AgBBggogBkEBajsBACABIAM2AgQMBAsgAyEECwNAIARBoIsESwRAIARBAmsiBC8BACIFEC1FDQELCyAFQf//A3EQLgRAA0AgBEGgiwRLBEBBhAogBEECayIENgIAIAQvAQAQLg0BCwsgBBAvDQELQYgKQQE6AAAMAgsQMEGICkEAOgAADAELEDELQYQKQZgKKAIAIgE2AgAMAQsQMgtBACEIQeQJLQAADQMCQCABIANGBEAgAEUNAUGCCi8BACALRiAJcUUNAUEBIQkgASEDQZgKKAIALwEAIghBCmsOBAUCAgUCCyACQS9GBEBBiAotAABBAXMhCQwBC0EBIQkgAkEwa0H//wNxQQpJIAJB3/8DcUHBAGtB//8DcUEaSXIgAkEkRiACQd8ARnJyIAJB/wBLcg0AIAEhAwJAAkAgAkEnaw4DAwEDAAsCQCACQd0Aaw4EAwEBAwALIAJBIkYgAkH9AEZyDQELQQAhCQsgASEDC0GYCigCACEFDAELCyACDwsgCAuvBAEHfyABQSJGIAFBJ0ZyRQRAEDIPC0GYCigCACEDIAEQJiAAIANBAmpBmAooAgBBARADIAIEQEHUCSgCAEEEQQYgAkEBRhs2AhwLQZgKQZgKKAIAQQJqNgIAQQAQJSEAQZgKKAIAIQQCQAJAIABB9wBHDQAgBC8BAkHpAEcNACAELwEEQfQARw0AIAQvAQZB6ABGDQELQZgKIARBAms2AgAPC0GYCiAEQQhqNgIAAkBBARAlQfsARwRADAELQewJKAIAIQNB1AkoAgAhBUGYCigCACIGIQBBACECA0AgAyEBQZgKIABBAmo2AgBBARAlIQBBmAooAgAhBwJAAkACQCAAQSJHBEAgAEEnRw0BQScQJgwCC0EiECYMAQsgABA1IQNBmAooAgAhAAwBC0GYCigCAEECaiEAQZgKIAA2AgBBARAlIQMLIANBOkcEQAwCC0GYCkGYCigCAEECajYCAEEBECUiA0EiRiADQSdGckUEQAwCC0GYCigCACEIIAMQJkHsCSABQRRqIgM2AgBBmAooAgAhCSABQQA2AhAgASAINgIIIAEgADYCBCABIAc2AgAgASAJQQJqIgA2AgwCQCACRQRAIAUgATYCIAwBCyACIAE2AhALQZgKIAA2AgACQEEBECUiAEEsRwRAIABB/QBGDQEMAwtBmApBmAooAgBBAmoiADYCACABIQIMAQsLIAUgBjYCECAFQZgKKAIAQQJqNgIMDwtBmAogBDYCAAstAQF/AkAgAC8BAEEuRw0AIABBAmsvAQBBLkcNACAAQQRrLwEAQS5GIQELIAELNQEBfwJAIABBoIsESQ0AIAAvAQAgAUcNACAAQaCLBEYEQEEBDwsgAEECay8BABAtIQILIAILKQEBfyAAQaABRiAAQQlrIgJBF01BAEEBIAJ0IAFxG3JFBEBBAA8LQQELC8cBAQBBgggLvwF4AHAAbwByAHQAZQB0AGEAbwB1AHIAYwBlAHIAbwBtAHUAbgBjAHQAaQBvAG4AbABhAHMAcwB2AG8AeQBpAGUAZABlAGwAZQBjAG8AbgB0AGkAbgBpAG4AcwB0AGEAbgB0AHkAYgByAGUAYQByAGUAdAB1AHIAZABlAGIAdQBnAGcAZQBhAHcAYQBpAHQAaAByAHcAaABpAGwAZQBmAG8AcgBpAGYAYwBhAHQAYwBmAGkAbgBhAGwAbABlAGwAcw==",typeof Buffer!="undefined"?Buffer.from(A,"base64"):Uint8Array.from(atob(A),(A)=>A.charCodeAt(0));var A};var init=WebAssembly.compile(C()).then(WebAssembly.instantiate).then(({exports:A})=>{E=A});var initSync=()=>{if(E)return;const A=new WebAssembly.Module(C());E=new WebAssembly.Instance(A).exports};import{createHash as createHash3}from"crypto";import{builtinModules}from"module";var awaitValue2=(value)=>promise2(constant(Promise.resolve(value)));var decoder=new TextDecoder("utf-8",{fatal:true});var path3=runSync2(provide3(Path2,layer5));initSync();var nodeBuiltinModules=new Set(builtinModules.map((specifier)=>specifier.replace(/^node:/u,"")));var digest2=(bytes)=>createHash3("sha256").update(bytes).digest("hex");var isEffectModuleSpecifier=(specifier)=>specifier==="effect"||/^effect(?:\/[A-Za-z0-9][\w.-]*)+$/u.test(specifier);var isNodeBuiltinModuleSpecifier=(specifier)=>nodeBuiltinModules.has(specifier.replace(/^node:/u,""));var moduleSpecifiers=(source)=>parse(source)[0].flatMap(({n:specifier})=>specifier===undefined?[]:[specifier]);var assertClosedRuntimeGraph=(entries)=>{const declaredPaths=new Set(entries.map(({path:entryPath})=>entryPath));for(const entry of entries){if(!entry.path.endsWith(".mjs")){continue}const source=decoder.decode(entry.bytes);const host=HOSTS.find((candidate)=>entry.path.startsWith(`artifacts/${candidate}/`));if(source.includes("sourceMappingURL=")){throw new TypeError(`Extension Release runtime asset '${entry.path}' exposes a public source map location`)}for(const specifier of moduleSpecifiers(source)){if(specifier.startsWith(".")){const dependencyPath=path3.normalize(path3.join(path3.dirname(entry.path),specifier));if(!declaredPaths.has(dependencyPath)){throw new TypeError(`Extension Release runtime asset '${entry.path}' has undeclared runtime dependency '${specifier}'`)}continue}if(host!==undefined&&isHostProvidedModule(host,specifier)||entry.path.startsWith("artifacts/backend/")&&(isNodeBuiltinModuleSpecifier(specifier)||isEffectModuleSpecifier(specifier))){continue}throw new TypeError(`Extension Release runtime asset '${entry.path}' has undeclared runtime dependency '${specifier}'`)}}};var assertPackageReleaseContract=(packageManifest,releaseManifest)=>{if(packageManifest.fqn!==releaseManifest.package.fqn||packageManifest.version!==releaseManifest.package.version){throw new TypeError("Extension Package and Release manifests must identify the same package FQN and version")}const declared=new Map((packageManifest.hostedContributions??[]).map((contribution)=>[`${contribution.host}\x00${contribution.fqn}`,contribution]));for(const contribution of releaseManifest.contributions){const key=`${contribution.host}\x00${contribution.fqn}`;const descriptor=declared.get(key);const syntheticPackageRuntime=contribution.host==="backend"&&contribution.fqn===`${packageManifest.fqn}.backend.package-runtime`&&contribution.exportName==="createPackageRuntime";if(descriptor===undefined){if(syntheticPackageRuntime){continue}throw new TypeError(`Extension Release contribution '${contribution.fqn}' is absent from the Package manifest`)}if(descriptor.exportName!==contribution.exportName||descriptor.contract!==contribution.contract){throw new TypeError(`Extension Release contribution '${contribution.fqn}' contract or export does not match the Package manifest`)}declared.delete(key)}if(declared.size>0){throw new TypeError(`Extension Release is missing declared contribution '${declared.values().next().value?.fqn??"unknown"}'`)}};var assertExactPrivateSourceMapInventory=(manifest,maps,mapByRuntimeDigest)=>{const declaredRuntimeDigests=new Set(manifest.assets.flatMap((asset)=>asset.privateSourceMap===undefined?[]:[asset.digest]));const hasMissingMap=[...declaredRuntimeDigests].some((runtimeDigest)=>!mapByRuntimeDigest.has(runtimeDigest));const hasExtraMap=maps.some(({runtimeAssetDigest})=>!declaredRuntimeDigests.has(runtimeAssetDigest));if(mapByRuntimeDigest.size!==declaredRuntimeDigests.size||hasMissingMap||hasExtraMap){throw new TypeError("Extension Release private source-map inventory must exactly match manifest descriptors")}};var assertPackageManifestMatchesRelease=(packageManifestBytes,releaseManifest)=>{const packageManifestText=decoder.decode(packageManifestBytes);const packageManifest=parsePackageManifest(JSON.parse(packageManifestText));if(canonicalJson(packageManifest)!==packageManifestText){throw new TypeError("Extension Package manifest is not canonical JSON")}assertPackageReleaseContract(packageManifest,releaseManifest);if(releaseManifest.packageManifest!==undefined&&canonicalJson(releaseManifest.packageManifest)!==packageManifestText){throw new TypeError("Package manifest does not match the archived declaration")}};var assertEntryIntegrity=(entryByPath,declared,label)=>{for(const file of declared){const entry=entryByPath.get(file.path);if(entry===undefined||entry.bytes.byteLength!==file.size||digest2(entry.bytes)!==file.digest){throw new TypeError(`Extension Release ${label} '${file.path}' does not match its manifest integrity`)}}};var validatePackageRelease=(input)=>{if(!(input.packageManifestBytes instanceof Uint8Array)){throw new TypeError("Extension package manifest bytes are required")}const manifestText=decoder.decode(input.manifestBytes);const manifest=parseExtensionReleaseManifest(JSON.parse(manifestText));if(canonicalExtensionReleaseManifest(manifest)!==manifestText){throw new TypeError("Extension Release manifest is not canonical JSON")}if(digest2(input.archiveBytes)!==manifest.releaseDigest){throw new TypeError("Extension Release archive digest does not match releaseDigest")}assertPackageManifestMatchesRelease(input.packageManifestBytes,manifest);const archiveEntries=parseExtensionReleaseArchive(input.archiveBytes);const entries=validateExtensionReleaseArchiveMetadata(archiveEntries,manifest);const entryByPath=new Map(entries.map((entry)=>[entry.path,entry]));const media=manifest.media??[];if(entryByPath.size!==manifest.assets.length+media.length){throw new TypeError("Extension Release archive does not contain exactly the declared runtime assets and Package Media")}assertEntryIntegrity(entryByPath,manifest.assets,"runtime asset");assertEntryIntegrity(entryByPath,media,"media");assertClosedRuntimeGraph(entries);const maps=input.privateSourceMaps??[];const mapByRuntimeDigest=new Map(maps.map((sourceMap)=>[sourceMap.runtimeAssetDigest,sourceMap]));if(mapByRuntimeDigest.size!==maps.length){throw new TypeError("Extension Release private source maps must have unique runtime asset digests")}assertExactPrivateSourceMapInventory(manifest,maps,mapByRuntimeDigest);for(const asset of manifest.assets){const declaredMap=asset.privateSourceMap;const sourceMap=mapByRuntimeDigest.get(asset.digest);if(declaredMap===undefined&&sourceMap===undefined){continue}if(declaredMap===undefined||sourceMap===undefined||sourceMap.size!==declaredMap.size||sourceMap.bytes.byteLength!==declaredMap.size||sourceMap.digest!==declaredMap.digest||digest2(sourceMap.bytes)!==declaredMap.digest){throw new TypeError(`Extension Release private source map for runtime asset '${asset.digest}' does not match its manifest integrity`)}}return manifest};var requireOption2=(args,name)=>{const index=args.lastIndexOf(`--${name}`);const value=index===-1?undefined:args[index+1];if(value===undefined||value===""){throw new TypeError(`Missing option --${name}`)}return value};var runPackageValidationCommand=flow((args,dependencies)=>gen2(function*validatePackageReleaseCommand(){if(args.includes("--bundle")){throw new TypeError("--bundle is no longer supported; validate the immutable --archive release artifact")}const archivePath=requireOption2(args,"archive");const manifestPath=requireOption2(args,"manifest");const packageManifestPath=requireOption2(args,"package-manifest");const privateMapDirectory=args.includes("--private-maps")?requireOption2(args,"private-maps"):path3.join(path3.dirname(manifestPath),"private-source-maps");const mapFiles=yield*gen2(function*nativeAssetStep1(){yield*awaitValue2(Promise.resolve());return yield*awaitValue2(dependencies.listFiles(privateMapDirectory))});const privateSourceMaps=[];for(const fileName of mapFiles.toSorted()){privateSourceMaps.push(yield*gen2(function*readPrivateSourceMap(){if(!/^[\da-f]{64}\.map$/u.test(fileName)){throw new TypeError(`Private source-map file '${fileName}' is not keyed by a runtime asset digest`)}const bytes=yield*gen2(function*nativeAssetStep2(){yield*awaitValue2(Promise.resolve());return yield*awaitValue2(dependencies.readBytes(path3.join(privateMapDirectory,fileName)))});return{bytes,digest:digest2(bytes),runtimeAssetDigest:fileName.slice(0,-4),size:bytes.byteLength}}))}const manifest=validatePackageRelease({archiveBytes:yield*gen2(function*nativeAssetStep3(){yield*awaitValue2(Promise.resolve());return yield*awaitValue2(dependencies.readBytes(archivePath))}),manifestBytes:yield*gen2(function*nativeAssetStep4(){yield*awaitValue2(Promise.resolve());return yield*awaitValue2(dependencies.readBytes(manifestPath))}),packageManifestBytes:yield*gen2(function*nativeAssetStep5(){yield*awaitValue2(Promise.resolve());return yield*awaitValue2(dependencies.readBytes(packageManifestPath))}),privateSourceMaps});return yield*encodeEffect(fromJsonString2(Struct({package:String4,releaseDigest:String4,valid:Boolean3})))({package:manifest.package.fqn,releaseDigest:manifest.releaseDigest,valid:true})}),runPromise2);var decoder2=new TextDecoder("utf-8",{fatal:true});var preparePackagePublication=async(input)=>{const{archiveBytes,manifestBytes,packageManifestBytes}=input;const privateSourceMaps=input.privateSourceMaps??[];const manifest=validatePackageRelease({archiveBytes,manifestBytes,packageManifestBytes,privateSourceMaps});const packageManifest=parsePackageManifest(await decodePromise(fromJsonString2(Unknown2))(decoder2.decode(packageManifestBytes)));const encodedManifest={apiVersion:manifest.apiVersion,assets:manifest.assets.map((asset)=>({digest:asset.digest,host:asset.host,path:asset.path,...asset.privateSourceMap===undefined?undefined:{privateSourceMap:{digest:asset.privateSourceMap.digest,size:asset.privateSourceMap.size}},size:asset.size})),compatibility:{...manifest.compatibility},contributions:manifest.contributions.map((contribution)=>({assetPath:contribution.assetPath,...contribution.contract===undefined?undefined:{contract:contribution.contract},digest:contribution.digest,exportName:contribution.exportName,fqn:contribution.fqn,host:contribution.host,size:contribution.size})),...manifest.media===undefined?undefined:{media:manifest.media.map(({digest,path,size})=>({digest,path,size}))},package:{...manifest.package},...manifest.packageManifest===undefined?undefined:{packageManifest:manifest.packageManifest},releaseDigest:manifest.releaseDigest};return{artifact:{archiveBase64:Buffer.from(archiveBytes).toString("base64"),privateSourceMaps:privateSourceMaps.map((sourceMap)=>({bytesBase64:Buffer.from(sourceMap.bytes).toString("base64"),digest:sourceMap.digest,runtimeAssetDigest:sourceMap.runtimeAssetDigest,size:sourceMap.size}))},manifest:encodedManifest,packageFqn:manifest.package.fqn,packageManifest,protocolVersion:"v1",version:manifest.package.version}};import{readFile as readFile3}from"fs/promises";var nonempty=String4.check(isMinLength(1),makeFilter2((value)=>value.trim().length>0));var uuid3=String4.check(isPattern2(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu));var link4=Struct({link:nonempty});var hasLinkKey=is2(Struct({link:Unknown2}));var variableInput=Union2([link4,Json2.check(makeFilter2((value)=>!hasLinkKey(value)))]);var inputsFile=Struct({adoptions:optionalKey2(Record(nonempty,Struct({instanceId:uuid3}))),connections:optionalKey2(Record(nonempty,Union2([Struct({connectionId:uuid3}),Struct({newConnection:Struct({fields:JsonObject,name:nonempty})})]))),variables:optionalKey2(Record(nonempty,variableInput))});var isLink=is2(link4);var isUuid=is2(uuid3);var isText=is2(String4);var decodeJson=decodeSync(fromJsonString2(Json2));var decodeInputsFile=decodeUnknownSync(inputsFile,{onExcessProperty:"error"});var parseInputsFile=(text,reject)=>{try{return decodeInputsFile(JSON.parse(text))}catch{return reject("Invalid inputs file; expected variables (JSON values or { link }), connections (UUID references or newConnection name/fields) and adoptions (UUID references)")}};var readInputsFile=async(path,reject,readBytes=readFile3)=>{let bytes;try{bytes=await readBytes(path)}catch{return reject("Could not read inputs file")}return parseInputsFile(new TextDecoder().decode(bytes),reject)};var isLiteral2=(value)=>value!==undefined&&!isVariableReference(value);var slotOf=(connection)=>isLiteral2(connection)?[connection.setupKey]:[];var slotsOf=(primitive)=>{if(primitive.kind==="datasetConnectorInstance"){return slotOf(primitive.connection)}if(primitive.kind==="knowledgeConnectorInstance"){const{connections}=primitive;return isLiteral2(connections)?Object.values(connections).flatMap(slotOf):[]}if(primitive.kind==="organizationSettings"){const{authentication}=primitive;return isLiteral2(authentication)&&isLiteral2(authentication.sso)?authentication.sso.flatMap((entry)=>isLiteral2(entry)?slotOf(entry.connection):[]):[]}return[]};var isRequired=(declaration)=>declaration.default===undefined;var deriveRequiredInputs=(manifest)=>({slots:[...new Set(manifest.primitives.flatMap(slotsOf))].toSorted(compareCanonicalText),variables:manifest.variables??{}});var templateVariable=(declaration)=>({type:declaration.type,...declaration.description===undefined?undefined:{description:declaration.description},...isRequired(declaration)?{required:true}:{default:declaration.default},...declaration.type==="secret"?{link:"<ORG_VARIABLE_KEY>"}:undefined});var renderInputsTemplate=(manifest)=>{const required=deriveRequiredInputs(manifest);return`${JSON.stringify({adoptions:{},connections:Object.fromEntries(required.slots.map((slot)=>[slot,{connectionId:"<connection-id>"}])),variables:Object.fromEntries(Object.entries(required.variables).toSorted(([left],[right])=>compareCanonicalText(left,right)).map(([name,declaration])=>[name,templateVariable(declaration)]))},null,2)}
|
|
300
|
+
`};var linkHint="@ORG_VARIABLE_KEY";var valueHints={boolean:`true or false or ${linkHint}`,json:`JSON or ${linkHint}`,number:`number or ${linkHint}`,secret:linkHint,string:`text or ${linkHint}`,"string[]":`comma-separated or ${linkHint}`};var valueParsers={boolean:(name,raw,reject)=>{if(raw==="true"){return true}return raw==="false"?false:reject(`Variable '${name}' expects true or false`)},json:(name,raw,reject)=>{try{return decodeJson(raw)}catch{return reject(`Variable '${name}' expects JSON`)}},number:(name,raw,reject)=>{const value=Number(raw);return raw.trim()===""||!Number.isFinite(value)?reject(`Variable '${name}' expects a number`):value},secret:(name,_raw,reject)=>reject(`Variable '${name}' is a secret and accepts only a link: --var ${name}=@<ORG_VARIABLE_KEY>`),string:(_name,raw)=>raw,"string[]":(_name,raw)=>raw===""?[]:raw.split(",")};var parseValue=(name,declaration,raw,reject)=>{if(raw.startsWith("@")){const key=raw.slice(1);return key===""?reject(`Variable '${name}' link needs an organization variable key: @<ORG_VARIABLE_KEY>`):{link:key}}return valueParsers[declaration.type](name,raw,reject)};var declarationOf=(declared,name,reject)=>{const declaration=declared[name];if(declaration===undefined){const names=Object.keys(declared).toSorted(compareCanonicalText);return reject(`Unknown variable '${name}'; the package declares ${names.length===0?"no variables":names.join(", ")}`)}return declaration};var parseFlag=(flag,declared,reject)=>{const separator=flag.indexOf("=");if(separator<=0){reject("--var must be <name>=<value> or <name>=@<ORG_VARIABLE_KEY>")}const name=flag.slice(0,separator);return[name,parseValue(name,declarationOf(declared,name,reject),flag.slice(separator+1),reject)]};var hasKeys=(value)=>value!==undefined&&Object.keys(value).length>0;var withInputs=(setup,variables)=>({...hasKeys(setup)?{setup}:undefined,...hasKeys(variables)?{variables}:undefined});var inputsFromFile=(file)=>{const{variables,...setup}=file;return withInputs(setup,variables)};var parseInputs=(input)=>{const{declared,reject}=input;const fileInputs=input.file===undefined?{}:inputsFromFile(input.file);for(const[name,value]of Object.entries(fileInputs.variables??{})){if(declarationOf(declared,name,reject).type==="secret"&&!isLink(value)){reject(`Variable '${name}' is a secret and accepts only { "link": "<ORG_VARIABLE_KEY>" }`)}}return withInputs(fileInputs.setup,{...fileInputs.variables,...Object.fromEntries(input.flags.map((flag)=>parseFlag(flag,declared,reject)))})};var missingInputs=(required,inputs)=>({slots:required.slots.filter((slot)=>inputs.setup?.connections?.[slot]===undefined),variables:Object.entries(required.variables).filter(([name,declaration])=>isRequired(declaration)&&inputs.variables?.[name]===undefined).map(([name])=>name).toSorted(compareCanonicalText)});var promptInputs=async(input)=>{const{declared,inputs,prompt,reject}=input;const variables=[];for(const name of input.missing.variables){const declaration=declarationOf(declared,name,reject);const question=[declaration.type,declaration.description,valueHints[declaration.type]].filter(isText).join("; ");const answer=await prompt(`Variable '${name}' (${question}): `);variables.push([name,parseValue(name,declaration,answer.trim(),reject)])}const connections=[];for(const slot of input.missing.slots){const answer=await prompt(`Connection id for slot '${slot}': `);const connectionId=answer.trim();if(!isUuid(connectionId)){reject(`Connection id for slot '${slot}' must be a UUID`)}connections.push([slot,{connectionId}])}return withInputs(connections.length===0?inputs.setup:{...inputs.setup,connections:{...inputs.setup?.connections,...Object.fromEntries(connections)}},{...inputs.variables,...Object.fromEntries(variables)})};var completeInputs=async(input)=>{const missing=missingInputs(input.required,input.inputs);const names=[...missing.variables.map((name)=>`variable '${name}'`),...missing.slots.map((slot)=>`connection '${slot}'`)];if(names.length===0){return input.inputs}if(input.nonInteractive){input.reject(`Missing required inputs: ${names.join(", ")}; pass --inputs <file> or --var <name>=<value>, see --inputs-template`)}return await promptInputs({declared:input.required.variables,inputs:input.inputs,missing,prompt:input.prompt,reject:input.reject})};class DeployCommandError extends TaggedError3()("DeployCommandError",{cause:optional2(Unknown2),json:Boolean3,lastEventId:optional2(Int),message:String4,nextAction:optional2(String4),operationId:optional2(String4),status:optional2(String4)}){}var values=new Set(["backend-url","declaration","inputs","organization","gateway-url","profile","timeout-ms","var"]);var repeatable=new Set(["gateway-url","var"]);var switches=new Set(["accept-breaking-changes","inputs-template","non-interactive","json"]);var gatewayOrigin=(value,fqn,reject)=>{let url;try{url=new URL(value)}catch{return reject(`Invalid Gateway URL for '${fqn}'`)}if(url.protocol!=="https:"||url.username!==""||url.password!==""||url.search!==""||url.hash!==""||url.pathname!=="/"){return reject(`Gateway URL for '${fqn}' must be an HTTPS origin without credentials, path, query or fragment`)}return url.origin};var addGatewayBinding=(gatewayUrls,value,reject)=>{const separator=value.indexOf("=");if(separator<=0){reject("--gateway-url must be <GatewayFQN>=<URL>")}const fqn=value.slice(0,separator);if(Object.hasOwn(gatewayUrls,fqn)){reject(`Duplicate Gateway URL binding '${fqn}'`)}Object.defineProperty(gatewayUrls,fqn,{enumerable:true,value:gatewayOrigin(value.slice(separator+1),fqn,reject)})};var parseDeployOptions=(args)=>{const options=new Map;const gatewayUrls={};const vars=[];const json=args.includes("--json");const reject=(message)=>{throw new DeployCommandError({json,message})};for(let index=0;index<args.length;index+=1){const flag=args[index];if(flag===undefined||!flag.startsWith("--")){reject("Expected --name value options or --non-interactive/--json switches")}const name=flag.slice(2);if(!values.has(name)&&!switches.has(name)){reject(`Unknown option ${flag}`)}if(options.has(name)&&!repeatable.has(name)){reject(`Duplicate option ${flag}`)}if(switches.has(name)){options.set(name,"true");continue}const value=args[index+1];if(!value||value.startsWith("--")){reject(`Missing value for ${flag}`)}index+=1;if(name==="gateway-url"){addGatewayBinding(gatewayUrls,value,reject)}else if(name==="var"){vars.push(value)}else{options.set(name,value)}}const required=(name)=>{const value=options.get(name);return value!==undefined&&value.trim()!==""?value:reject(`Missing required option --${name}`)};const timeoutMs=Number(options.get("timeout-ms")??"300000");if(!Number.isSafeInteger(timeoutMs)||timeoutMs<=0){reject("--timeout-ms must be a positive integer")}return{acceptBreakingChanges:options.has("accept-breaking-changes"),declaration:required("declaration"),gatewayUrls,...options.has("inputs")?{inputs:required("inputs")}:undefined,inputsTemplate:options.has("inputs-template"),json,nonInteractive:options.has("non-interactive"),timeoutMs,vars}};var buildRelease=async(options,dependencies)=>await buildPackageRelease({declarationSpecifier:dependencies.resolveDeclarationSpecifier(options.declaration)});var reconcileGatewayUrls=(declared,requested,existing,reject)=>{for(const fqn of Object.keys(requested)){if(!declared.includes(fqn)){reject(`Unknown Gateway URL binding '${fqn}'`)}}return Object.fromEntries(declared.map((fqn)=>{const value=requested[fqn]??existing?.gatewayUrls?.[fqn];if(value===undefined){reject(`Missing required Gateway URL binding '${fqn}'`)}return[fqn,gatewayOrigin(value,fqn,reject)]}))};var inputsTemplateEffect=fn2("Deploy.inputsTemplate")(function*inputsTemplateEffect(options,dependencies){const release=yield*tryPromise2({catch:(cause)=>new DeployCommandError({cause,json:options.json,message:"Could not build the package release"}),try:async()=>await buildRelease(options,dependencies)});dependencies.writeOutput(renderInputsTemplate(release.packageManifest))});var deployCommandEffect=fn2("Deploy.command")(function*deployCommandEffect(options,dependencies){const context=yield*context2();const runFollower=runPromiseWith2(context);const writeProgress=options.json?dependencies.writeOutput:dependencies.writeDiagnostic;let operationId;let lastEventId;return yield*tryPromise2({catch:(cause)=>is2(DeployCommandError)(cause)?cause:new DeployCommandError({cause,json:options.json,lastEventId,message:is2(PackageOperationCommandError)(cause)?cause.message:"Could not deploy package",operationId}),try:async(signal)=>{const reject=(message)=>{throw new DeployCommandError({json:options.json,message})};const file=options.inputs===undefined?undefined:await readInputsFile(options.inputs,reject);const release=await buildRelease(options,dependencies);const required=deriveRequiredInputs(release.packageManifest);let inputs=parseInputs({declared:required.variables,file,flags:options.vars,reject});const publication=await preparePackagePublication(release);const lookupBody={packageFqn:release.manifest.package.fqn,releaseDigest:release.releaseDigest,version:release.manifest.package.version};const lookup=async()=>{const response=await packageReleasesLookupPublished({body:lookupBody,client:dependencies.publisher,signal,throwOnError:true});return response.data.release};let{gatewayUrls}=options;const key=(stage)=>`ci-deploy-${stage}-${createHash4("sha256").update(canonicalJson({...lookupBody,acceptBreakingChanges:options.acceptBreakingChanges,gatewayUrls,organizationId:options.organizationId,...inputs})).digest("hex")}`;const follow=async(acceptedId,client)=>{operationId=acceptedId;lastEventId=0;writeProgress(`${JSON.stringify({kind:"progress",operationId,status:"accepted"})}
|
|
300
301
|
`);const followed=await runFollower(followPackageOperationEffect({operationId,organizationId:options.organizationId},{client,writeEvent:(event)=>{const decoded=decodePackageOperationEvent(event);lastEventId=decoded.sequence;writeProgress(`${JSON.stringify({...decoded,kind:"progress"})}
|
|
301
|
-
`)}}),{signal});if(followed.kind!=="snapshot"||followed.snapshot.status!=="succeeded"){throw new DeployCommandError({json:options.json,lastEventId,message:followed.kind==="snapshot"?renderPackageOperationSummary(followed.snapshot).trim():"Deployment operation did not succeed",nextAction:followed.kind==="snapshot"?followed.snapshot.nextAction:undefined,operationId,status:followed.kind==="snapshot"?followed.snapshot.status:"accepted"})}};let exact=await lookup();const installed=await extensionPackagesListInstalled({client:dependencies.organization,headers:{"x-organization-id":options.organizationId},signal,throwOnError:true});const existing=installed.data.find((installation)=>installation.packageFqn===release.manifest.package.fqn&&installation.uninstalledAt===null);
|
|
302
|
+
`)}}),{signal});if(followed.kind!=="snapshot"||followed.snapshot.status!=="succeeded"){throw new DeployCommandError({json:options.json,lastEventId,message:followed.kind==="snapshot"?renderPackageOperationSummary(followed.snapshot).trim():"Deployment operation did not succeed",nextAction:followed.kind==="snapshot"?followed.snapshot.nextAction:undefined,operationId,status:followed.kind==="snapshot"?followed.snapshot.status:"accepted"})}};let exact=await lookup();const installed=await extensionPackagesListInstalled({client:dependencies.organization,headers:{"x-organization-id":options.organizationId},signal,throwOnError:true});const existing=installed.data.find((installation)=>installation.packageFqn===release.manifest.package.fqn&&installation.uninstalledAt===null);gatewayUrls=reconcileGatewayUrls(release.packageManifest.primitives.filter((primitive)=>primitive.kind==="externalAppGateway").map((primitive)=>primitive.fqn).toSorted(),options.gatewayUrls,existing,reject);if(existing===undefined){inputs=await completeInputs({inputs,nonInteractive:options.nonInteractive,prompt:dependencies.prompt,reject,required})}if(exact===null){const accepted=await publishPackage({body:{...publication,deploymentPolicy:"strict"},client:dependencies.publisher,idempotencyKey:key("publish"),signal});await follow(accepted.operationId,dependencies.publisher);exact=await lookup();if(exact===null){throw new DeployCommandError({json:options.json,message:"Publication succeeded without the expected immutable release",operationId:accepted.operationId})}}if(exact.promotion.status==="unpromoted"){const accepted=await promotePackage({body:{protocolVersion:"v1",releaseId:exact.releaseId},client:dependencies.publisher,idempotencyKey:key("promote"),signal});await follow(accepted.operationId,dependencies.publisher)}const unchanged=inputs.setup===undefined&&inputs.variables===undefined&&existing!==undefined&&existing.servingReleaseId===exact.releaseId&&existing.desiredReleaseId===exact.releaseId&&existing.status==="installed"&&existing.error===null&&canonicalJson(existing.gatewayUrls??{})===canonicalJson(gatewayUrls);if(!unchanged){const intent={...inputs,acceptBreakingChanges:options.acceptBreakingChanges,deploymentPolicy:"strict",gatewayUrls,releaseId:exact.releaseId};const accepted=existing===undefined?await installPackage({body:intent,client:dependencies.organization,idempotencyKey:key("install"),organizationId:options.organizationId,packageFqn:release.manifest.package.fqn,signal}):await updatePackage({body:{...intent,installationId:existing.id,protocolVersion:"v1"},client:dependencies.organization,idempotencyKey:key("update"),organizationId:options.organizationId,signal});await follow(accepted.operationId,dependencies.organization)}let action="unchanged";if(!unchanged){action=existing===undefined?"installed":"updated"}dependencies.writeOutput(options.json?`${JSON.stringify({action,kind:"result",packageFqn:release.manifest.package.fqn,releaseDigest:release.releaseDigest,releaseId:exact.releaseId,status:"succeeded"})}
|
|
302
303
|
`:`Deployed ${release.manifest.package.fqn}@${release.manifest.package.version}: ${action} (${exact.releaseId})
|
|
303
304
|
`)}}).pipe(timeoutOrElse2({duration:options.timeoutMs,orElse:()=>fail6(new DeployCommandError({json:options.json,lastEventId,message:"Deployment wait timed out; rerun the same exact deployment intent or reconnect to its operation",operationId,status:"timed_out"}))}))});class DoctorCommandError extends TaggedError3()("DoctorCommandError",{cause:optional2(Unknown2),message:String4}){}var doctorCommandEffect=(args,dependencies)=>gen2(function*doctorCommand(){const options=yield*parseCommandOptionsEffect(args,{repeatable:["redirect-uri"],values:[...targetOptions,"fqn"]});const context=yield*resolveOrganizationContext({args,environment:dependencies.environment,fetch:dependencies.fetch});const report=yield*runPreflight({context,fetch:dependencies.fetch,fqn:optionValue2(options,"fqn"),redirectUris:optionValues(options,"redirect-uri")});dependencies.writeOutput(renderPreflight(report.checks));const failed=report.checks.filter((entry)=>!entry.passed).length;return yield*failed===0?void_3:fail6(new DoctorCommandError({message:`${failed} preflight check(s) failed`}))}).pipe(mapError2((cause)=>is2(DoctorCommandError)(cause)?cause:new DoctorCommandError({cause,message:cause.message})));class LoginCommandError extends TaggedError3()("LoginCommandError",{cause:optional2(Unknown2),message:String4}){}var usage4="Usage: ci login <API URL> [--organization <id>] [--no-browser] [--profile <name>]";var DeviceGrantError=Struct({error:Literals(["access_denied","authorization_pending","expired_token","invalid_grant","invalid_request"])});var terminalGrantMessages={access_denied:"Login was denied in the dashboard; run ci login again",authorization_pending:"Login was not approved in time; run ci login again",expired_token:"The login code expired; run ci login again",invalid_grant:"The login code was already used or is unknown; run ci login again",invalid_request:"The backend rejected the login request; run ci login again"};var loopbackHosts=new Set(["127.0.0.1","[::1]","localhost"]);var openableVerificationUrl=(verificationUrl,dashboardUrl)=>{try{const url=new URL(verificationUrl);const secure=url.protocol==="https:"||url.protocol==="http:"&&loopbackHosts.has(url.hostname)&&url.port!=="";return secure&&url.origin===new URL(dashboardUrl).origin?url.href:undefined}catch{return}};var exchangeDeviceCode=(client,deviceCode)=>managementData("CLI token exchange",authExchangeCliToken,{body:{device_code:deviceCode},client}).pipe(map4((grant)=>some2(grant.access_token)),catchTag2("ManagementRequestError",(failure)=>{if(!is2(DeviceGrantError)(failure.body)){return fail6(failure)}return failure.body.error==="authorization_pending"?succeedNone2:fail6(new LoginCommandError({cause:failure,message:terminalGrantMessages[failure.body.error]}))}));var pollForSession=fn2("Login.pollForSession")(function*pollForSession(input){const attempts=Math.max(1,Math.ceil(input.expiresIn/input.interval));for(let attempt=0;attempt<attempts;attempt+=1){yield*promise2(async()=>{await input.delay(input.interval*1000)});const token=yield*input.exchange();if(isSome2(token)){return token.value}}return yield*new LoginCommandError({message:terminalGrantMessages.authorization_pending})});var loginCommandEffect=(args,dependencies)=>gen2(function*loginCommand(){const options=yield*parseCommandOptionsEffect(args,{positionals:1,switches:["no-browser"],values:["organization","profile"]});const[apiUrl]=options.positionals;if(apiUrl===undefined){return yield*new LoginCommandError({message:usage4})}const discovery=yield*readTenantDiscovery(dependencies.fetch,apiUrl);const anonymous=makeBackendManagementClient({backendUrl:discovery.apiBaseUrl,fetch:dependencies.fetch});const device=yield*managementData("CLI device authorization",authStartCliDevice,{body:{device_name:dependencies.deviceName},client:anonymous});dependencies.writeDiagnostic(`Confirm code ${device.user_code} in the dashboard: ${device.verification_uri_complete}
|
|
304
305
|
`);const openable=openableVerificationUrl(device.verification_uri_complete,discovery.dashboardUrl);if(!options.switches.has("no-browser")&&openable!==undefined){dependencies.openBrowser(openable)}const token=yield*pollForSession({delay:dependencies.delay,exchange:()=>exchangeDeviceCode(anonymous,device.device_code),expiresIn:device.expires_in,interval:device.interval});const identity=yield*managementData("Identity read",authMe,{client:makeBackendManagementClient({backendUrl:discovery.apiBaseUrl,fetch:dependencies.fetch,token})});const name=optionValue2(options,"profile")??profileName(discovery.apiBaseUrl);const organizationId=optionValue2(options,"organization");yield*tryConfiguration(()=>{const store=readProfileStore(dependencies.environment);const previous=Object.hasOwn(store.profiles,name)?store.profiles[name]:undefined;const currentOrganizationId=organizationId??(previous?.apiOrigin===discovery.apiBaseUrl?previous.currentOrganizationId:undefined);const expiresAt=identity.sessionExpiresAt??undefined;const session=expiresAt===undefined?{token}:{expiresAt,token};const profile=currentOrganizationId===undefined?{apiOrigin:discovery.apiBaseUrl,session}:{apiOrigin:discovery.apiBaseUrl,currentOrganizationId,session};writeProfileStore(dependencies.environment,{current:name,profiles:{...store.profiles,[name]:profile}})});return yield*sync2(()=>{dependencies.writeOutput(`Logged in to ${discovery.apiBaseUrl} as ${identity.email??identity.id} (Profile ${name}${organizationId===undefined?"":`, Current Organization ${organizationId}`})
|
|
@@ -307,9 +308,9 @@ Defaulting to 2020, but this will stop working in the future.`)}options.ecmaVers
|
|
|
307
308
|
`:`${organizations.map((organization)=>`${organization.id===target.organizationId?"*":" "} ${organization.id} ${organization.name} ${organization.role}`).join(`
|
|
308
309
|
`)}
|
|
309
310
|
`)})}const[organizationId]=options.positionals;if(command!=="use"||organizationId===undefined){return yield*new OrgsCommandError({message:usage5})}const selected=yield*tryConfiguration(()=>selectedProfile({args:rest,environment:dependencies.environment}));if(selected===undefined){return yield*new OrgsCommandError({message:"ci orgs use stores the Current Organization in a CLI Profile; run ci login first"})}const{organizations}=yield*memberships(rest,dependencies);const organization=organizations.find((candidate)=>candidate.id===organizationId);if(organization===undefined){return yield*new OrgsCommandError({message:`Organization ${organizationId} is not one of your memberships; run ci orgs list`})}const updated=yield*tryConfiguration(()=>updateProfile(dependencies.environment,selected.name,(latest)=>({...latest,currentOrganizationId:organization.id})));if(updated===undefined){return yield*new OrgsCommandError({message:`CLI Profile ${selected.name} was removed; run ci login first`})}return yield*sync2(()=>{dependencies.writeOutput(`Current Organization of Profile ${selected.name}: ${organization.name} (${organization.id})
|
|
310
|
-
`)})}).pipe(mapError2((cause)=>is2(OrgsCommandError)(cause)?cause:new OrgsCommandError({cause,message:cause.message})));import{fileURLToPath as fileURLToPath5}from"url";var awaitValue3=(value)=>promise2(constant(Promise.resolve(value)));var
|
|
311
|
+
`)})}).pipe(mapError2((cause)=>is2(OrgsCommandError)(cause)?cause:new OrgsCommandError({cause,message:cause.message})));import{fileURLToPath as fileURLToPath5}from"url";var awaitValue3=(value)=>promise2(constant(Promise.resolve(value)));var nodePath4=runSync2(provide3(Path2,layer3));var moduleExport2=(exportName)=>{if(!/^[$A-Z_a-z][$\w]*$/u.test(exportName)){throw new TypeError(`Backend Contribution export '${exportName}' is not a JavaScript identifier`)}return exportName};var literalLazyImport2=(declarationSpecifier,identity)=>{if(identity.load===undefined){throw new Error("Package runtime entry has no hosted loader")}const loaderSource=Function.prototype.toString.call(identity.load).trim();const arrowMatch=/^(?:async\s*)?\(\s*\)\s*=>\s*(?:await\s*)?(?:import|__vite_ssr_dynamic_import__)\(\s*(?<quote>["'])(?<specifier>[^"'\\\r\n]+)\k<quote>\s*\)$/u.exec(loaderSource);const functionMatch=/^function(?:\s+\w+)?\s*\(\s*\)\s*\{\s*return\s+(?:import|__vite_ssr_dynamic_import__)\(\s*(?<quote>["'])(?<specifier>[^"'\\\r\n]+)\k<quote>\s*\)\s*;?\s*\}$/u.exec(loaderSource);const specifier=arrowMatch?.groups?.specifier??functionMatch?.groups?.specifier;if(specifier===undefined){throw new TypeError(`Backend Contribution '${identity.contributionFqn}' load must be a direct literal lazy import`)}if(specifier.startsWith("file:")){return fileURLToPath5(specifier)}if(specifier.startsWith("/")){if(!declarationSpecifier.startsWith("file:")){throw new TypeError(`Backend Contribution '${identity.contributionFqn}' root-relative load requires a file declaration`)}const declarationDirectory=nodePath4.dirname(fileURLToPath5(declarationSpecifier));const workspaceCandidate=nodePath4.resolve(process.cwd(),specifier.slice(1));const workspaceRelation=nodePath4.relative(declarationDirectory,workspaceCandidate);return workspaceRelation!==""&&!workspaceRelation.startsWith("..")&&!nodePath4.isAbsolute(workspaceRelation)?workspaceCandidate:nodePath4.resolve(declarationDirectory,specifier.slice(1))}if(specifier.startsWith(".")){if(!declarationSpecifier.startsWith("file:")){throw new TypeError(`Backend Contribution '${identity.contributionFqn}' relative load requires a file declaration`)}return nodePath4.resolve(nodePath4.dirname(fileURLToPath5(declarationSpecifier)),specifier)}return specifier};var entrySource=(identity)=>`export { ${moduleExport2(identity.exportName)} } from "ci-backend-contribution"`;var localModulePath=(specifier,identity)=>{if(!nodePath4.isAbsolute(specifier)){return specifier}try{return Bun.resolveSync(specifier,nodePath4.dirname(specifier))}catch(error){throw new TypeError(`Backend Contribution '${identity.contributionFqn}' module could not be resolved: ${specifier}`,{cause:error})}};var isSourceMapDocument=(value)=>value!==null&&typeof value==="object"&&("sources"in value)&&Array.isArray(value.sources)&&value.sources.every((source)=>typeof source==="string")&&("sourcesContent"in value)&&Array.isArray(value.sourcesContent)&&value.sourcesContent.every((source)=>source===null||typeof source==="string");var sanitizeSourceMap2=(rawSourceMap,identity)=>{const parsed=JSON.parse(rawSourceMap);if(!isSourceMapDocument(parsed)){throw new Error(`Bun emitted an invalid source map for '${identity.contributionFqn}'`)}if(parsed.sources.length!==parsed.sourcesContent.length){throw new Error(`Bun emitted an incomplete source map for '${identity.contributionFqn}'`)}const sourceNamespace=encodeURIComponent(identity.contributionFqn);return JSON.stringify({...parsed,file:`${sourceNamespace}.mjs`,sourceRoot:"",sources:parsed.sources.map((_source,index)=>`extension://${sourceNamespace}/source-${index}.ts`)})};var buildContribution=flow((declarationSpecifier,identity)=>gen2(function*buildAsset(){const contributionImport=identity.load===undefined?undefined:localModulePath(literalLazyImport2(declarationSpecifier,identity),identity);const entrypoint=`ci-backend-entry:${encodeURIComponent(`${identity.packageFqn}:${identity.contributionFqn}`)}`;const result=yield*suspend2(()=>awaitValue3(Bun.build({...workspaceSourceResolve(process.execArgv),entrypoints:[entrypoint],format:"esm",minify:false,plugins:[{name:"ci-backend-development-entry",setup(builder){builder.onResolve({filter:/^ci-package-declaration$/u},()=>({path:backendPackageModulePath(declarationSpecifier,identity.definition)}));builder.onResolve({filter:/^ci-backend-entry:/u},({path:resolvedPath})=>({namespace:"ci-backend-entry",path:resolvedPath}));if(contributionImport!==undefined){builder.onResolve({filter:/^ci-backend-contribution$/u},()=>({path:contributionImport}))}builder.onLoad({filter:/.*/u,namespace:"ci-backend-entry"},()=>({contents:identity.load===undefined?backendPackageEntrySource(identity.packageFqn):entrySource(identity),loader:"ts",resolveDir:import.meta.dir}))}}],sourcemap:"external",target:"bun"})));if(!result.success){throw new AggregateError(result.logs,`Failed to build Backend Contribution '${identity.contributionFqn}'`)}const codeArtifact=result.outputs.find(({path:artifactPath})=>!artifactPath.endsWith(".map"));const mapArtifact=result.outputs.find(({path:artifactPath})=>artifactPath.endsWith(".map"));if(codeArtifact===undefined||mapArtifact===undefined){throw new Error(`Bun did not emit code and source map for '${identity.contributionFqn}'`)}const sourceMap=sanitizeSourceMap2(yield*suspend2(()=>awaitValue3(mapArtifact.text())),identity);const rawBuiltCode=yield*suspend2(()=>awaitValue3(codeArtifact.text()));const builtCode=rawBuiltCode.replaceAll(/\/\/# sourceMappingURL=.*$/gmu,"");return{code:`${builtCode.trimEnd()}
|
|
311
312
|
`,contributionFqn:identity.contributionFqn,exportName:identity.exportName,packageFqn:identity.packageFqn,sourceMap}}),runPromise2);var buildBackendDevelopmentAssets=flow((input)=>gen2(function*nativeAssetStep1(){const identities=input.declarations.flatMap((definition)=>{const entry=backendPackageEntry(definition);return[...entry===undefined?[]:[{contributionFqn:entry.fqn,definition,exportName:entry.exportName,packageFqn:definition.manifest.fqn}],...definition.hostedContributions.flatMap(({load,manifest})=>manifest.host==="backend"?[{contributionFqn:manifest.fqn,definition,exportName:manifest.exportName,load,packageFqn:definition.manifest.fqn}]:[])]});return yield*awaitValue3(Promise.all(identities.map(flow((identity)=>suspend2(()=>awaitValue3(buildContribution(input.declarationSpecifier,identity))),runPromise2))))}),runPromise2);var awaitValue4=(value)=>promise2(constant(Promise.resolve(value)));var contributionKey=(input)=>JSON.stringify([input.packageFqn,input.contributionFqn]);var contentDigest=(asset)=>new Bun.CryptoHasher("sha256").update(asset.code).digest("hex").slice(0,16);var randomUuid=()=>{const bytes=new Uint8Array(16);crypto.getRandomValues(bytes);bytes[6]=bytes[6]%16+64;bytes[8]=bytes[8]%64+128;const hex=[...bytes].map((byte)=>byte.toString(16).padStart(2,"0"));return`${hex.slice(0,4).join("")}-${hex.slice(4,6).join("")}-${hex.slice(6,8).join("")}-${hex.slice(8,10).join("")}-${hex.slice(10).join("")}`};var startBackendDevelopmentAssetServer=flow((input)=>gen2(function*startServer(){const capability=randomUuid().replaceAll("-","");const capabilityPath=`__ci_backend_capability__/${capability}/`;const servedAssets=new Map;const contributionFiles=new Map;const rebuild=flow((declarations)=>gen2(function*rebuildAssets(){const built=yield*suspend2(()=>awaitValue4(buildBackendDevelopmentAssets({declarationSpecifier:input.declarationSpecifier,declarations})));const nextContributionFiles=new Map;for(const asset of built){const fileName=`modules/${encodeURIComponent(asset.contributionFqn)}-${contentDigest(asset)}.mjs`;servedAssets.set(fileName,{content:asset.code,contentType:"text/javascript"});servedAssets.set(`${fileName}.map`,{content:asset.sourceMap,contentType:"application/json"});nextContributionFiles.set(contributionKey(asset),fileName)}contributionFiles.clear();for(const[key,fileName]of nextContributionFiles){contributionFiles.set(key,fileName)}}),runPromiseWith2(empty()));yield*suspend2(()=>awaitValue4(rebuild(input.declarations))).pipe(asVoid2);const attachedOrigins=new Set(input.hostOrigins);const server=Bun.serve({fetch(request){const origin=request.headers.get("origin");const requestUrl=new URL(request.url);const assetPath=requestUrl.pathname.slice(1);const hasCapability=assetPath.startsWith(capabilityPath);const isAuthorized=origin===null?hasCapability:attachedOrigins.has(origin);if(!isAuthorized){return new Response("Host origin is not attached",{status:403})}const asset=servedAssets.get(hasCapability?assetPath.slice(capabilityPath.length):assetPath);if(asset===undefined){return new Response("Not found",{status:404})}const headers=new Headers({"cache-control":"no-store","content-type":asset.contentType});if(origin!==null){headers.set("access-control-allow-origin",origin)}return new Response(asset.content,{headers})},hostname:"127.0.0.1",port:0});return{assetsFor:flow((definition)=>suspend2(()=>awaitValue4(Promise.resolve(backendArtifactContributions(definition).flatMap((manifest)=>{if(manifest.host!=="backend"){return[]}const fileName=contributionFiles.get(contributionKey({contributionFqn:manifest.fqn,packageFqn:definition.manifest.fqn}));if(fileName===undefined){throw new Error(`Backend Contribution asset was not built: ${manifest.fqn}`)}return[{...manifest.compatibility===undefined?undefined:{compatibility:manifest.compatibility},exportName:manifest.exportName,fqn:manifest.fqn,host:manifest.host,moduleUrl:new URL(`${capabilityPath}${fileName}`,server.url).href,sourceMapUrl:new URL(`${capabilityPath}${fileName}.map`,server.url).href}]})))),runPromise2),close:flow(()=>suspend2(()=>awaitValue4(server.stop(true))).pipe(asVoid2),runPromise2),rebuild}}),runPromise2);var awaitValue5=(value)=>promise2(constant(Promise.resolve(value)));var developmentHeartbeatIntervalMs=5000;var ownedRetryInitialMs=1000;var ownedRetryMaxMs=5000;var systemDevelopmentClock={repeatEvery:(intervalMs,tick)=>{const fiber=runFork2(promise2(tick).pipe(delay2(intervalMs),forever2));return()=>{runFork2(interrupt2(fiber))}},sleep:flow((delayMs)=>sleep2(delayMs),runPromise2)};class RuntimeRefreshError extends TaggedError2("RuntimeRefreshError"){}var isRejected=is2(DevelopmentSessionRejectedError);var isSessionNotFound=(failure)=>isRejected(failure.cause)&&failure.cause.reason==="session_not_found";var isSessionOwned=(failure)=>isRejected(failure.cause)&&failure.cause.reason==="session_owned";var messageOf=(cause)=>cause.message;var attempt=(evaluate)=>tryPromise2({catch:(cause)=>new RuntimeRefreshError({cause,message:cause instanceof Error?cause.message:String(cause)}),try:()=>evaluate()});var effectPromise=(evaluate)=>gen2(function*nativeRuntimeStep1(){yield*awaitValue5(Promise.resolve());return yield*awaitValue5(evaluate())});var assertLoopbackAsset=(value)=>{const url=new URL(value);if(url.protocol!=="http:"&&url.protocol!=="https:"||url.hostname!=="127.0.0.1"&&url.hostname!=="::1"&&url.hostname!=="localhost"){throw new TypeError("Development assets must use loopback HTTP URLs")}};var validateAssets=(assets)=>{for(const asset of assets){assertLoopbackAsset(asset.moduleUrl);if(asset.sourceMapUrl!==undefined){assertLoopbackAsset(asset.sourceMapUrl)}}return assets};var assertUniquePackageFqns=(declarations)=>{const packageFqns=new Set;for(const definition of declarations){const packageFqn=definition.manifest.fqn;if(packageFqns.has(packageFqn)){throw new TypeError(`Duplicate Extension Package FQN: ${packageFqn}`)}packageFqns.add(packageFqn)}};var traverse=forEach2;var settleQueue=flow((current)=>tryPromise2(()=>current).pipe(ignore2),runPromise2);var startPackageDevelopmentRuntime=flow((input,dependencies)=>gen2(function*nativeRuntimeStep2(){const clock=dependencies.clock??systemDevelopmentClock;const report=(message)=>{dependencies.reportWarning?.(message)};const sessions=new Map;const graphSignatures=new Map;const closedSignal=Promise.withResolvers();let closed=false;let latestDeclarations=input.declarations;let queue=Promise.resolve();const serialized=flow((work)=>gen2(function*nativeRuntimeStep3(){const previous=queue;const run=flow(()=>gen2(function*nativeRuntimeStep4(){yield*awaitValue5(previous);return yield*awaitValue5(work()).pipe(asVoid2)}),runPromise2);const current=run();queue=settleQueue(current);return yield*awaitValue5(current).pipe(asVoid2)}),runPromise2);const forget=(packageFqn,sessionId)=>{if(sessions.get(packageFqn)?.sessionId===sessionId){sessions.delete(packageFqn);graphSignatures.delete(packageFqn)}};const createSession=(packageFqn,delayMs=ownedRetryInitialMs)=>attempt(()=>dependencies.createDevelopmentSession({hostOrigins:input.hostOrigins,packageFqn})).pipe(catchIf2((error)=>!closed&&isSessionOwned(error),()=>{if(delayMs===ownedRetryInitialMs){report(`Another live \`package dev\` owns ${packageFqn}; stop it or wait ~15 s. Retrying.`)}return suspend2(()=>awaitValue5(Promise.race([clock.sleep(delayMs),closedSignal.promise]))).pipe(andThen2(()=>closed?die3(new Error("Development process is closed")):createSession(packageFqn,Math.min(delayMs*2,ownedRetryMaxMs))))}),mapError2((failure)=>failure.cause),orDie2);const synchronizePackage=(definition)=>gen2(function*synchronizePackageSession(){const packageFqn=definition.manifest.fqn;let session=sessions.get(packageFqn);if(session===undefined){session=yield*createSession(packageFqn);sessions.set(packageFqn,session)}const assets=validateAssets(yield*effectPromise(()=>dependencies.assetsFor(definition)));const signature=`${canonicalPackageManifest(definition)}
|
|
312
|
-
${canonicalJson(assets)}`;if(graphSignatures.get(packageFqn)===signature){return yield*void_3}const publish=(sessionId)=>attempt(()=>dependencies.updateLocalManifest({hostedContributions:assets,sessionId}));const stale=session;const updated=yield*publish(stale.sessionId).pipe(catchIf2(isSessionNotFound,()=>gen2(function*recreateForgottenSession(){forget(packageFqn,stale.sessionId);const replacement=yield*createSession(packageFqn);sessions.set(packageFqn,replacement);return yield*publish(replacement.sessionId)})),mapError2((failure)=>failure.cause),orDie2);sessions.set(packageFqn,updated);graphSignatures.set(packageFqn,signature);return yield*void_3});const recoverSessions=flow((missing)=>suspend2(()=>awaitValue5(serialized(flow(()=>gen2(function*nativeRuntimeStep5(){for(const{packageFqn,sessionId}of missing){forget(packageFqn,sessionId)}const missingFqns=new Set(missing.map(({packageFqn})=>packageFqn));return yield*gen2(function*resynchronizeMissingSessions(){for(const definition of latestDeclarations){if(missingFqns.has(definition.manifest.fqn)){yield*synchronizePackage(definition)}}}).pipe(asVoid2)}),runPromise2)))).pipe(asVoid2),runPromise2);const heartbeat=dependencies.heartbeatDevelopmentSession;let beating=false;const heartbeatRound=flow(()=>suspend2(()=>{if(heartbeat===undefined||closed||beating){return void_3}beating=true;return gen2(function*heartbeatRoundEffect(){const results=yield*traverse([...sessions],([packageFqn,{sessionId}])=>attempt(()=>heartbeat(sessionId)).pipe(as2([]),catch_2((error)=>{if(isSessionNotFound(error)){return succeed6([{packageFqn,sessionId}])}report(`Development session heartbeat failed for ${packageFqn}: ${messageOf(error)}`);return succeed6([])})),{concurrency:"unbounded"});const missing=results.flat();if(missing.length>0&&!closed){yield*awaitValue5(recoverSessions(missing))}}).pipe(catchCause2((cause)=>sync2(()=>{const error=squash(cause);report(`Could not re-create development session: ${messageOf(error instanceof Error?error:{message:String(error)})}`)})),ensuring2(sync2(()=>{beating=false})))}),runPromise2);const stopHeartbeat=heartbeat===undefined?null:clock.repeatEvery(developmentHeartbeatIntervalMs,heartbeatRound);const close=flow(()=>gen2(function*closeRuntime(){closed=true;stopHeartbeat?.();closedSignal.resolve(null);yield*suspend2(()=>awaitValue5(queue)).pipe(asVoid2);const activeSessions=[...sessions.values()];sessions.clear();yield*suspend2(()=>awaitValue5(Promise.all(activeSessions.map(({sessionId})=>dependencies.terminateDevelopmentSession(sessionId)))))}),runPromise2);const refresh=flow((declarations)=>suspend2(()=>awaitValue5(serialized(flow(()=>gen2(function*refreshRuntime(){assertUniquePackageFqns(declarations);latestDeclarations=declarations;const declaredPackageFqns=new Set(declarations.map(({manifest})=>manifest.fqn));for(const[packageFqn,session]of sessions){if(declaredPackageFqns.has(packageFqn)){continue}yield*effectPromise(()=>dependencies.terminateDevelopmentSession(session.sessionId));sessions.delete(packageFqn);graphSignatures.delete(packageFqn)}for(const definition of declarations){yield*synchronizePackage(definition)}}),runPromise2)))).pipe(asVoid2),runPromise2);return yield*gen2(function*startRuntime(){yield*tryPromise2({catch:(error)=>new RuntimeRefreshError({cause:error,message:error instanceof Error?error.message:"Package development refresh failed"}),try:()=>refresh(input.declarations)}).pipe(tapError2(()=>suspend2(()=>awaitValue5(close())).pipe(asVoid2)));return{close,refresh,sessions:()=>[...sessions.values()]}})}),runPromise2);var awaitValue6=(value)=>promise2(constant(Promise.resolve(value)));var runNested=runPromiseWith2(empty());var cleanupAll=flow((steps,timeoutMs)=>gen2(function*cleanResources(){const failures=[];for(const step of steps){const result=yield*tryPromise2(flow(()=>suspend2(()=>awaitValue6(step.run())).pipe(asVoid2),runPromise2)).pipe(timeout2(timeoutMs),result2);if(result._tag==="Failure"){failures.push(new Error(`${step.name} cleanup failed`,{cause:result.failure}))}}if(failures.length>0){throw new AggregateError(failures,"Development cleanup failed")}}),runNested);var isRuntimeRefreshFailure=(error)=>("_tag"in error)&&error._tag==="RuntimeRefreshError"&&("cause"in error);var rethrowRuntimeRefreshCause=(cause)=>{const dieReason=cause.reasons.find(isDieReason2);if(dieReason===undefined){return failCause3(cause)}const{defect}=dieReason;return die3(defect instanceof Error&&isRuntimeRefreshFailure(defect)?defect.cause:defect)};var startPackageDevelopmentProcess=flow((input,dependencies)=>gen2(function*startProcess(){const cleanupTimeoutMs=input.cleanupTimeoutMs??1000;if(!Number.isFinite(cleanupTimeoutMs)||cleanupTimeoutMs<=0||cleanupTimeoutMs>30000){throw new RangeError("cleanupTimeoutMs must be positive and at most 30000")}let stopped=false;const heartbeat=dependencies.heartbeatDevelopmentSession;const declarations=yield*suspend2(()=>awaitValue6(dependencies.loadDeclarations(input.declarationSpecifier)));assertUniquePackageFqns(declarations);const assetInput={declarationSpecifier:input.declarationSpecifier,declarations,hostOrigins:input.hostOrigins};const assets=yield*suspend2(()=>awaitValue6(dependencies.startAssets(assetInput)));const frontendCleanup={name:"frontend",run:flow(()=>suspend2(()=>awaitValue6(assets.close())).pipe(asVoid2),runPromise2)};const backendAssets=yield*suspend2(()=>awaitValue6((dependencies.startBackendAssets??startBackendDevelopmentAssetServer)(assetInput))).pipe(tapDefect2(()=>suspend2(()=>awaitValue6(cleanupAll([frontendCleanup],cleanupTimeoutMs))).pipe(asVoid2)));const assetCleanup=[{name:"backend",run:flow(()=>suspend2(()=>awaitValue6(backendAssets.close())).pipe(asVoid2),runPromise2)},frontendCleanup];const runtime=yield*suspend2(()=>awaitValue6(startPackageDevelopmentRuntime({declarations,hostOrigins:input.hostOrigins},{assetsFor:flow((definition)=>gen2(function*nativeProcessStep1(){const[frontend,backend]=yield*awaitValue6(Promise.all([assets.assetsFor(definition),backendAssets.assetsFor(definition)]));return[...frontend,...backend]}),runPromise2),clock:dependencies.clock,createDevelopmentSession:flow((request)=>gen2(function*createSession(){if(stopped){throw new Error("Development process is closed")}const session=yield*suspend2(()=>awaitValue6(dependencies.createDevelopmentSession(request)));if(stopped){yield*suspend2(()=>awaitValue6(cleanupAll([{name:"late session",run:flow(()=>suspend2(()=>awaitValue6(dependencies.terminateDevelopmentSession(session.sessionId))).pipe(asVoid2),runPromise2)}],cleanupTimeoutMs))).pipe(asVoid2);throw new Error("Development process is closed")}return session}),runNested),heartbeatDevelopmentSession:heartbeat===undefined?undefined:flow((sessionId)=>gen2(function*nativeProcessStep2(){if(!stopped){yield*awaitValue6(heartbeat(sessionId))}}),runPromise2),reportWarning:dependencies.reportWarning,terminateDevelopmentSession:flow((sessionId)=>tryPromise2(flow(()=>suspend2(()=>awaitValue6(dependencies.terminateDevelopmentSession(sessionId))).pipe(asVoid2),runPromise2)).pipe(timeout2(cleanupTimeoutMs),orDie2),runNested),updateLocalManifest:flow((request)=>gen2(function*publishManifest(){if(stopped){throw new Error("Development process is closed")}const session=yield*suspend2(()=>awaitValue6(dependencies.updateLocalManifest(request)));if(stopped){throw new Error("Development process is closed")}return session}),runNested)}))).pipe(tapDefect2(()=>suspend2(()=>awaitValue6(cleanupAll(assetCleanup,cleanupTimeoutMs))).pipe(asVoid2)));let refreshQueue=Promise.resolve();const refresh=flow(()=>gen2(function*nativeProcessStep3(){if(stopped){return yield*void_3}const previous=refreshQueue;refreshQueue=runNested(gen2(function*refreshProcess(){yield*tryPromise2(flow(()=>suspend2(()=>awaitValue6(previous)).pipe(asVoid2),runPromise2)).pipe(ignore2);if(stopped){return yield*void_3}const refreshed=yield*suspend2(()=>awaitValue6(dependencies.loadDeclarations(input.declarationSpecifier)));if(stopped){return yield*void_3}assertUniquePackageFqns(refreshed);yield*suspend2(()=>awaitValue6(assets.rebuild(refreshed))).pipe(asVoid2);if(stopped){return yield*void_3}yield*suspend2(()=>awaitValue6(backendAssets.rebuild(refreshed))).pipe(asVoid2);if(stopped){return yield*void_3}return yield*suspend2(()=>awaitValue6(runtime.refresh(refreshed))).pipe(asVoid2)}));return yield*awaitValue6(refreshQueue).pipe(asVoid2)}),runPromise2);const runtimeCleanup=[{name:"sessions",run:flow(()=>suspend2(()=>awaitValue6(runtime.close())).pipe(asVoid2),runPromise2)},...assetCleanup];const watcher=yield*sync2(()=>dependencies.watchDeclaration(input.declarationSpecifier,refresh)).pipe(tapDefect2(()=>{stopped=true;return suspend2(()=>awaitValue6(cleanupAll(runtimeCleanup,cleanupTimeoutMs))).pipe(asVoid2)}));let closing;return{close:flow(()=>gen2(function*nativeProcessStep4(){stopped=true;closing??=cleanupAll([{name:"watcher",run:flow(()=>suspend2(()=>awaitValue6(watcher.close())).pipe(asVoid2),runPromise2)},{name:"refresh",run:flow(()=>tryPromise2(flow(()=>suspend2(()=>awaitValue6(refreshQueue)).pipe(asVoid2),runPromise2)).pipe(ignore2),runNested)},...runtimeCleanup],cleanupTimeoutMs);return yield*awaitValue6(closing).pipe(asVoid2)}),runPromise2),sessions:runtime.sessions}}).pipe(catchCause2(rethrowRuntimeRefreshCause)),runPromise2);class PackageDevelopmentCommandError extends TaggedError3()("PackageDevelopmentCommandError",{cause:optional2(Unknown2),message:String4}){}var packageDevelopmentFailureMessage=(cause)=>{if(is2(TaggedStruct("Forbidden",{}))(cause)){return"Package development failed: Forbidden. Possible causes include disabled extension development on the dedicated development backend (check APP_EXTENSIONS_DEVELOPMENT_ENABLED=true), or missing human tenant-admin / organization permissions. The backend did not identify which check failed."}return cause instanceof Error?cause.message:"Package development failed"};var packageDevelopmentError=(cause)=>is2(PackageDevelopmentCommandError)(cause)?cause:new PackageDevelopmentCommandError({cause,message:packageDevelopmentFailureMessage(cause)});var parsePackageDevelopmentOptions=(args)=>{const[command,...options]=args;if(command!=="dev"){throw new PackageDevelopmentCommandError({message:"Expected package dev"})}let declaration;const hostOrigins=[];for(let index=0;index<options.length;index+=2){const flag=options[index];const value=options[index+1];if(!flag?.startsWith("--")||value===undefined||value.startsWith("--")){throw new PackageDevelopmentCommandError({message:"Options must be supplied as --name value pairs"})}switch(flag){case"--declaration":{declaration=value;break}case"--host-origin":{hostOrigins.push(value);break}default:{throw new PackageDevelopmentCommandError({message:`Unknown option ${flag}`})}}}if(declaration===undefined||declaration.trim()===""){throw new PackageDevelopmentCommandError({message:"Missing option --declaration"})}if(hostOrigins.length===0){throw new PackageDevelopmentCommandError({message:"At least one --host-origin must be explicitly attached"})}return{declaration,hostOrigins}};var packageDevelopmentCommandEffect=(args,dependencies)=>tryPromise2({catch:packageDevelopmentError,try:async()=>{const options=parsePackageDevelopmentOptions(args);const declarationSpecifier=dependencies.resolveDeclarationSpecifier(options.declaration);const processRuntime=await startPackageDevelopmentProcess({declarationSpecifier,hostOrigins:options.hostOrigins},dependencies);try{dependencies.writeResult(await runPromise2(encodeEffect(fromJsonString2(Unknown2))(processRuntime.sessions().length===1?processRuntime.sessions()[0]:processRuntime.sessions())));await dependencies.awaitTermination()}finally{await processRuntime.close()}}});init_sharedKeyMatcher_Od_nYxJA();init_logger_DOwfTlw5();init_dtsConstants_r5OfegUr();init_dist();import{createRequire as createRequire3}from"module";import*as fs$2 from"fs";import{existsSync as existsSync7,readFileSync as readFileSync5,readdirSync as readdirSync3,realpathSync as realpathSync3,statSync,writeFileSync as writeFileSync4}from"fs";import{createRequire as createRequire$12,isBuiltin}from"module";import*as path$14 from"path";import path9,{basename as basename2}from"path";import{fileURLToPath as fileURLToPath10,pathToFileURL as pathToFileURL4}from"url";import*as vite from"vite";import{parseAst as parseAst2,version as version4}from"vite";import{createHash as createHash5}from"crypto";import*as fs$12 from"fs";import{existsSync as existsSync$1,readFileSync as readFileSync$1}from"fs";import{pathToFileURL as pathToFileURL$1}from"url";import{isIPv6}from"net";import{readFile as readFile5}from"fs/promises";var __filename="/home/runner/_work/ci-app/ci-app/node_modules/.bun/@module-federation+vite@1.23.2+eebbd1cfa443764b/node_modules/@module-federation/vite/lib/index.js";var REGEXP_SPECIAL_CHARS_RE=/[.*+?^${}()|[\]\\]/g;function escapeRegExp(value){return value.replace(REGEXP_SPECIAL_CHARS_RE,"\\$&")}function isOutputChunk$1(chunk){return chunk.type==="chunk"}function isIdentifierReferenced(name,code){return new RegExp(`(?<![$\\w])${escapeRegExp(name)}(?![$\\w])`).test(code)}function getProxyBaseName(fileName){return fileName.replace(/^.*\//,"").replace(/\.js$/,"").replace(/-[A-Za-z0-9_-]+$/,"")}function functionDeclarationRegExp(name){return new RegExp(`function\\s+${escapeRegExp(name)}\\s*\\(`)}function extractFunctionDeclaration(code,functionName){const funcRe=new RegExp(`function\\s+${escapeRegExp(functionName)}\\s*\\([^)]*\\)\\s*\\{`);const funcStart=code.search(funcRe);if(funcStart<0)return;let depth=0;for(let i=code.indexOf("{",funcStart);i<code.length;i++)if(code[i]==="{")depth++;else if(code[i]==="}"){depth--;if(depth===0)return code.slice(funcStart,i+1)}}function resolveProxyAlias(binding,proxyLocal,code,fullImport,claimedLocals=new Set){const codeWithoutImport=code.replace(fullImport,"");const localUsedInCode=isIdentifierReferenced(binding.local,codeWithoutImport);const claimedImportLocals=new Set;const importRe=/import\s*\{([^}]+)\}\s*from\s*["'][^"']+["']\s*;?/g;let match;while((match=importRe.exec(codeWithoutImport))!==null)for(const spec of match[1].split(",")){const parts=spec.trim().split(/\s+as\s+/);claimedImportLocals.add((parts[1]||parts[0]).trim())}const local=!localUsedInCode&&!claimedLocals.has(proxyLocal)&&!claimedImportLocals.has(proxyLocal)?proxyLocal:binding.local;return{imported:binding.imported,local}}function collectLoadShareProxyChunks(bundle,loadShareTag){const proxyChunks=new Map;for(const[fileName,chunk]of Object.entries(bundle)){if(!isOutputChunk$1(chunk))continue;if(fileName.includes(loadShareTag)&&fileName.includes("commonjs-proxy"))proxyChunks.set(fileName,{code:chunk.code,fileName})}return proxyChunks}function collectSystemProxyInfos(proxyChunks,loadShareTag){const systemProxyInfo=new Map;for(const[proxyFileName,proxyInfo]of Array.from(proxyChunks.entries())){const depsMatch=proxyInfo.code.match(/System\.register\(\[([\s\S]*?)\]/);if(!depsMatch)continue;const loadShareDep=Array.from(depsMatch[1].matchAll(/["']([^"']+)["']/g)).map((m)=>m[1]).find((dep)=>dep.includes(loadShareTag)&&!dep.includes("commonjs-proxy"));if(!loadShareDep)continue;const loadShareBindings={};for(const m of proxyInfo.code.matchAll(/([A-Za-z_$][\w$]*)\s*=\s*module\d+\.([A-Za-z_$][\w$]*)/g))loadShareBindings[m[1]]=m[2];const exportMap={};const objectExportMatch=proxyInfo.code.match(/exports\(\s*\{([\s\S]*?)\}\s*\)/);if(objectExportMatch)for(const m of objectExportMatch[1].matchAll(/([A-Za-z_$][\w$]*)\s*:\s*([A-Za-z_$][\w$]*)/g)){const[,exported,local]=m;const funcBody=extractFunctionDeclaration(proxyInfo.code,local);if(funcBody)exportMap[exported]={type:"helper",code:funcBody}}for(const m of proxyInfo.code.matchAll(/exports\(\s*["']([^"']+)["']\s*,([\s\S]*?)\);/g)){const exported=m[1];const expression=m[2];for(const[local,exportName]of Object.entries(loadShareBindings).reverse())if(isIdentifierReferenced(local,expression)){exportMap[exported]={type:"reexport",exportName};break}}if(Object.keys(exportMap).length>0)systemProxyInfo.set(proxyFileName,{loadShareDep,exportMap})}return systemProxyInfo}function rewriteEsmProxyConsumers(code,proxyChunks){let nextCode=code;const claimedLocals=new Set;for(const[proxyFileName,proxyInfo]of Array.from(proxyChunks.entries())){const proxyBaseName=getProxyBaseName(proxyFileName);const importMatch=new RegExp(`import\\s*\\{([^}]+)\\}\\s*from\\s*["']([^"']*${escapeRegExp(proxyBaseName)}[^"']*)["']\\s*;?`).exec(nextCode);if(!importMatch)continue;const fullImport=importMatch[0];const bindings=importMatch[1].split(",").map((s)=>{const parts=s.trim().split(/\s+as\s+/);return{imported:parts[0].trim(),local:(parts[1]||parts[0]).trim()}});const exportMapMatch=proxyInfo.code.match(/export\s*\{([^}]+)\}/);if(!exportMapMatch)continue;const exportMap={};for(const entry of exportMapMatch[1].split(",")){const parts=entry.trim().split(/\s+as\s+/);if(parts.length===2)exportMap[parts[1].trim()]=parts[0].trim()}const inlineable=[];const nonInlineable=[];const pendingLocals=new Set(bindings.map((binding)=>binding.local));for(const b of bindings){pendingLocals.delete(b.local);const proxyLocal=exportMap[b.imported];if(!proxyLocal){claimedLocals.add(b.local);nonInlineable.push(b);continue}const funcBody=extractFunctionDeclaration(proxyInfo.code,proxyLocal);if(funcBody){inlineable.push({local:b.local,funcBody:funcBody.replace(functionDeclarationRegExp(proxyLocal),()=>`function ${b.local}(`)});claimedLocals.add(b.local)}else{const unavailableLocals=new Set(claimedLocals);pendingLocals.forEach((local)=>unavailableLocals.add(local));const resolvedBinding=resolveProxyAlias(b,proxyLocal,nextCode,fullImport,unavailableLocals);claimedLocals.add(resolvedBinding.local);nonInlineable.push(resolvedBinding)}}const hasRenamedAlias=nonInlineable.some((b)=>bindings.find((ob)=>ob.imported===b.imported)?.local!==b.local);if(inlineable.length===0&&!hasRenamedAlias)continue;let replacement="";if(nonInlineable.length>0)replacement=`import{${nonInlineable.map((b)=>b.imported===b.local?b.imported:`${b.imported} as ${b.local}`).join(",")}}from"${importMatch[2]}";`;replacement+=inlineable.map((f)=>f.funcBody).join("");nextCode=nextCode.replace(fullImport,()=>replacement)}return nextCode}function rewriteSystemProxyConsumers(code,systemProxyInfo){if(!code.includes("System.register("))return code;let nextCode=code;for(const[proxyFileName,proxyInfo]of Array.from(systemProxyInfo.entries())){const proxyBaseName=getProxyBaseName(proxyFileName);const depMatch=new RegExp(`["']([^"']*${escapeRegExp(proxyBaseName)}[^"']*)["']`).exec(nextCode);if(!depMatch)continue;let setterIndex=0;const depListMatch=nextCode.match(/System\.register\(\[([\s\S]*?)\]/);if(depListMatch)setterIndex=Array.from(depListMatch[1].matchAll(/["']([^"']+)["']/g)).map((m)=>m[1]).findIndex((dep)=>dep.includes(proxyBaseName));if(setterIndex<0)continue;const settersStart=nextCode.indexOf("setters: [");if(settersStart<0)continue;const setterMatch=Array.from(nextCode.slice(settersStart).matchAll(/\((module\d+)\)\s*=>\s*\{([\s\S]*?)\}/g))[setterIndex];if(!setterMatch)continue;const[fullSetter,moduleLocal,setterBody]=setterMatch;const helpersToInline=[];const nextSetterBody=setterBody.replace(new RegExp(`([A-Za-z_$][\\w$]*)\\s*=\\s*${moduleLocal}\\.([A-Za-z_$][\\w$]*);?`,"g"),(assignment,local,imported)=>{const mapped=proxyInfo.exportMap[imported];if(!mapped)return assignment;if(mapped.type==="helper"){helpersToInline.push(mapped.code.replace(functionDeclarationRegExp(imported),()=>`function ${local}(`));return""}return`${local} = ${moduleLocal}.${mapped.exportName};`});if(nextSetterBody===setterBody&&helpersToInline.length===0)continue;const nextSetter=fullSetter.replace(setterBody,()=>nextSetterBody);nextCode=nextCode.replace(fullSetter,()=>nextSetter);nextCode=nextCode.replace(depMatch[0],JSON.stringify(proxyInfo.loadShareDep));if(helpersToInline.length>0)nextCode=nextCode.replace("execute: (function() {",()=>{return`execute: (function() {${helpersToInline.join("")}`})}return nextCode}function findRemoteEntryFile(filename,bundle){const strippedName=filename.replace(/[\[\]]/g,"_").replace(/\.[^/.]+$/,"");let fallback;for(const fileData of Object.values(bundle)){if(fileData.fileName===filename)return fileData.fileName;if(fallback===undefined&&(strippedName===fileData.name||fileData.name==="remoteEntry"))fallback=fileData.fileName}return fallback}async function mapCodeToCodeWithSourcemap(code){const resolvedCode=await code;if(resolvedCode===undefined)return;return{code:resolvedCode,map:createSourceMap(resolvedCode)}}function getPluginEnvironmentName(ctx){if(ctx==null||typeof ctx!=="object")return;const environment=ctx["environment"];if(environment==null||typeof environment!=="object")return;const name=environment["name"];return typeof name==="string"?name:undefined}function resolveEnvironmentConsumerTarget(ctx){if(ctx==null||typeof ctx!=="object")return;const environment=ctx["environment"];if(environment==null||typeof environment!=="object")return;const consumer=environment.config?.consumer;if(consumer==="client"||consumer==="server")return consumer;const envName=getPluginEnvironmentName(ctx);return!envName||envName==="client"?"client":"server"}function isClientEnvironment(ctx){return resolveEnvironmentConsumerTarget(ctx)!=="server"}function isServerBuildContext(ctx,config){const target=resolveEnvironmentConsumerTarget(ctx);if(target)return target==="server";return Boolean(config?.build?.ssr)}function resolveRemoteConsumer(ctx,hasMultiEnvironment){if(!hasMultiEnvironment)return"unified";return resolveEnvironmentConsumerTarget(ctx)??"client"}var IDENTIFIER=String.raw`[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}]*`;var NAMED_SPECIFIERS=String.raw`\{[^{}]*\}`;var NAMESPACE_SPECIFIER=String.raw`\*\s*as\s+${IDENTIFIER}`;var IMPORT_CLAUSE=String.raw`(?:(?<importType>type)\s+)?(?<importClause>${NAMESPACE_SPECIFIER}|${NAMED_SPECIFIERS}|${IDENTIFIER}(?:\s*,\s*(?:${NAMESPACE_SPECIFIER}|${NAMED_SPECIFIERS}))?)`;var EXPORT_CLAUSE=String.raw`(?:(?<exportType>type)\s+)?(?<exportClause>\*(?:\s*as\s+(?:${IDENTIFIER}|"[^"]*"|'[^']*'))?|${NAMED_SPECIFIERS})`;var SPECIFIER=String.raw`(?<quote>["'])(?<source>[^"'\r\n]*)\k<quote>`;var KEYWORD_BOUNDARY=String.raw`(?<![.$\w])`;var KEYWORD_GAP=String.raw`(?:\s+|(?=[{*]))`;var STATIC_PATTERN=new RegExp(String.raw`${KEYWORD_BOUNDARY}(?:import${KEYWORD_GAP}${IMPORT_CLAUSE}|export${KEYWORD_GAP}${EXPORT_CLAUSE})\s*from\s*${SPECIFIER}`,"gud");var DYNAMIC_PATTERN=new RegExp(String.raw`${KEYWORD_BOUNDARY}import\s*\(\s*${SPECIFIER}`,"gud");var REQUIRE_PATTERN=new RegExp(String.raw`${KEYWORD_BOUNDARY}require\s*\(\s*${SPECIFIER}\s*\)`,"gud");var SIDE_EFFECT_PATTERN=new RegExp(String.raw`${KEYWORD_BOUNDARY}import\s*${SPECIFIER}`,"gud");function blankNonCode(code){const codePositions=createCodePositionMap(code);const chars=code.split("");let index=0;while(index<code.length){if(codePositions[index]){index++;continue}const start=index;while(index<code.length&&!codePositions[index])index++;const quote=code[start];const isString=(quote==='"'||quote==="'")&&index-start>=2&&code[index-1]===quote;for(let position=start;position<index;position++)chars[position]=isString&&(position===start||position===index-1)?quote:code[position]===`
|
|
313
|
+
${canonicalJson(assets)}`;if(graphSignatures.get(packageFqn)===signature){return yield*void_3}const publish=(sessionId)=>attempt(()=>dependencies.updateLocalManifest({hostedContributions:assets,sessionId}));const stale=session;const updated=yield*publish(stale.sessionId).pipe(catchIf2(isSessionNotFound,()=>gen2(function*recreateForgottenSession(){forget(packageFqn,stale.sessionId);const replacement=yield*createSession(packageFqn);sessions.set(packageFqn,replacement);return yield*publish(replacement.sessionId)})),mapError2((failure)=>failure.cause),orDie2);sessions.set(packageFqn,updated);graphSignatures.set(packageFqn,signature);return yield*void_3});const recoverSessions=flow((missing)=>suspend2(()=>awaitValue5(serialized(flow(()=>gen2(function*nativeRuntimeStep5(){for(const{packageFqn,sessionId}of missing){forget(packageFqn,sessionId)}const missingFqns=new Set(missing.map(({packageFqn})=>packageFqn));return yield*gen2(function*resynchronizeMissingSessions(){for(const definition of latestDeclarations){if(missingFqns.has(definition.manifest.fqn)){yield*synchronizePackage(definition)}}}).pipe(asVoid2)}),runPromise2)))).pipe(asVoid2),runPromise2);const heartbeat=dependencies.heartbeatDevelopmentSession;let beating=false;const heartbeatRound=flow(()=>suspend2(()=>{if(heartbeat===undefined||closed||beating){return void_3}beating=true;return gen2(function*heartbeatRoundEffect(){const results=yield*traverse([...sessions],([packageFqn,{sessionId}])=>attempt(()=>heartbeat(sessionId)).pipe(as2([]),catch_2((error)=>{if(isSessionNotFound(error)){return succeed6([{packageFqn,sessionId}])}report(`Development session heartbeat failed for ${packageFqn}: ${messageOf(error)}`);return succeed6([])})),{concurrency:"unbounded"});const missing=results.flat();if(missing.length>0&&!closed){yield*awaitValue5(recoverSessions(missing))}}).pipe(catchCause2((cause)=>sync2(()=>{const error=squash(cause);report(`Could not re-create development session: ${messageOf(error instanceof Error?error:{message:String(error)})}`)})),ensuring2(sync2(()=>{beating=false})))}),runPromise2);const stopHeartbeat=heartbeat===undefined?null:clock.repeatEvery(developmentHeartbeatIntervalMs,heartbeatRound);const close=flow(()=>gen2(function*closeRuntime(){closed=true;stopHeartbeat?.();closedSignal.resolve(null);yield*suspend2(()=>awaitValue5(queue)).pipe(asVoid2);const activeSessions=[...sessions.values()];sessions.clear();yield*suspend2(()=>awaitValue5(Promise.all(activeSessions.map(({sessionId})=>dependencies.terminateDevelopmentSession(sessionId)))))}),runPromise2);const refresh=flow((declarations)=>suspend2(()=>awaitValue5(serialized(flow(()=>gen2(function*refreshRuntime(){assertUniquePackageFqns(declarations);latestDeclarations=declarations;const declaredPackageFqns=new Set(declarations.map(({manifest})=>manifest.fqn));for(const[packageFqn,session]of sessions){if(declaredPackageFqns.has(packageFqn)){continue}yield*effectPromise(()=>dependencies.terminateDevelopmentSession(session.sessionId));sessions.delete(packageFqn);graphSignatures.delete(packageFqn)}for(const definition of declarations){yield*synchronizePackage(definition)}}),runPromise2)))).pipe(asVoid2),runPromise2);return yield*gen2(function*startRuntime(){yield*tryPromise2({catch:(error)=>new RuntimeRefreshError({cause:error,message:error instanceof Error?error.message:"Package development refresh failed"}),try:()=>refresh(input.declarations)}).pipe(tapError2(()=>suspend2(()=>awaitValue5(close())).pipe(asVoid2)));return{close,refresh,sessions:()=>[...sessions.values()]}})}),runPromise2);var awaitValue6=(value)=>promise2(constant(Promise.resolve(value)));var runNested=runPromiseWith2(empty());var cleanupAll=flow((steps,timeoutMs)=>gen2(function*cleanResources(){const failures=[];for(const step of steps){const result=yield*tryPromise2(flow(()=>suspend2(()=>awaitValue6(step.run())).pipe(asVoid2),runPromise2)).pipe(timeout2(timeoutMs),result2);if(result._tag==="Failure"){failures.push(new Error(`${step.name} cleanup failed`,{cause:result.failure}))}}if(failures.length>0){throw new AggregateError(failures,"Development cleanup failed")}}),runNested);var isRuntimeRefreshFailure=(error)=>("_tag"in error)&&error._tag==="RuntimeRefreshError"&&("cause"in error);var rethrowRuntimeRefreshCause=(cause)=>{const dieReason=cause.reasons.find(isDieReason2);if(dieReason===undefined){return failCause3(cause)}const{defect}=dieReason;return die3(defect instanceof Error&&isRuntimeRefreshFailure(defect)?defect.cause:defect)};var startPackageDevelopmentProcess=flow((input,dependencies)=>gen2(function*startProcess(){const cleanupTimeoutMs=input.cleanupTimeoutMs??1000;if(!Number.isFinite(cleanupTimeoutMs)||cleanupTimeoutMs<=0||cleanupTimeoutMs>30000){throw new RangeError("cleanupTimeoutMs must be positive and at most 30000")}let stopped=false;const heartbeat=dependencies.heartbeatDevelopmentSession;const declarations=yield*suspend2(()=>awaitValue6(dependencies.loadDeclarations(input.declarationSpecifier)));assertUniquePackageFqns(declarations);const assetInput={declarationSpecifier:input.declarationSpecifier,declarations,hostOrigins:input.hostOrigins};const assets=yield*suspend2(()=>awaitValue6(dependencies.startAssets(assetInput)));const frontendCleanup={name:"frontend",run:flow(()=>suspend2(()=>awaitValue6(assets.close())).pipe(asVoid2),runPromise2)};const backendAssets=yield*suspend2(()=>awaitValue6((dependencies.startBackendAssets??startBackendDevelopmentAssetServer)(assetInput))).pipe(tapDefect2(()=>suspend2(()=>awaitValue6(cleanupAll([frontendCleanup],cleanupTimeoutMs))).pipe(asVoid2)));const assetCleanup=[{name:"backend",run:flow(()=>suspend2(()=>awaitValue6(backendAssets.close())).pipe(asVoid2),runPromise2)},frontendCleanup];const runtime=yield*suspend2(()=>awaitValue6(startPackageDevelopmentRuntime({declarations,hostOrigins:input.hostOrigins},{assetsFor:flow((definition)=>gen2(function*nativeProcessStep1(){const[frontend,backend]=yield*awaitValue6(Promise.all([assets.assetsFor(definition),backendAssets.assetsFor(definition)]));return[...frontend,...backend]}),runPromise2),clock:dependencies.clock,createDevelopmentSession:flow((request)=>gen2(function*createSession(){if(stopped){throw new Error("Development process is closed")}const session=yield*suspend2(()=>awaitValue6(dependencies.createDevelopmentSession(request)));if(stopped){yield*suspend2(()=>awaitValue6(cleanupAll([{name:"late session",run:flow(()=>suspend2(()=>awaitValue6(dependencies.terminateDevelopmentSession(session.sessionId))).pipe(asVoid2),runPromise2)}],cleanupTimeoutMs))).pipe(asVoid2);throw new Error("Development process is closed")}return session}),runNested),heartbeatDevelopmentSession:heartbeat===undefined?undefined:flow((sessionId)=>gen2(function*nativeProcessStep2(){if(!stopped){yield*awaitValue6(heartbeat(sessionId))}}),runPromise2),reportWarning:dependencies.reportWarning,terminateDevelopmentSession:flow((sessionId)=>tryPromise2(flow(()=>suspend2(()=>awaitValue6(dependencies.terminateDevelopmentSession(sessionId))).pipe(asVoid2),runPromise2)).pipe(timeout2(cleanupTimeoutMs),orDie2),runNested),updateLocalManifest:flow((request)=>gen2(function*publishManifest(){if(stopped){throw new Error("Development process is closed")}const session=yield*suspend2(()=>awaitValue6(dependencies.updateLocalManifest(request)));if(stopped){throw new Error("Development process is closed")}return session}),runNested)}))).pipe(tapDefect2(()=>suspend2(()=>awaitValue6(cleanupAll(assetCleanup,cleanupTimeoutMs))).pipe(asVoid2)));let refreshQueue=Promise.resolve();const refresh=flow(()=>gen2(function*nativeProcessStep3(){if(stopped){return yield*void_3}const previous=refreshQueue;refreshQueue=runNested(gen2(function*refreshProcess(){yield*tryPromise2(flow(()=>suspend2(()=>awaitValue6(previous)).pipe(asVoid2),runPromise2)).pipe(ignore2);if(stopped){return yield*void_3}const refreshed=yield*suspend2(()=>awaitValue6(dependencies.loadDeclarations(input.declarationSpecifier)));if(stopped){return yield*void_3}assertUniquePackageFqns(refreshed);yield*suspend2(()=>awaitValue6(assets.rebuild(refreshed))).pipe(asVoid2);if(stopped){return yield*void_3}yield*suspend2(()=>awaitValue6(backendAssets.rebuild(refreshed))).pipe(asVoid2);if(stopped){return yield*void_3}return yield*suspend2(()=>awaitValue6(runtime.refresh(refreshed))).pipe(asVoid2)}));return yield*awaitValue6(refreshQueue).pipe(asVoid2)}),runPromise2);const runtimeCleanup=[{name:"sessions",run:flow(()=>suspend2(()=>awaitValue6(runtime.close())).pipe(asVoid2),runPromise2)},...assetCleanup];const watcher=yield*sync2(()=>dependencies.watchDeclaration(input.declarationSpecifier,refresh)).pipe(tapDefect2(()=>{stopped=true;return suspend2(()=>awaitValue6(cleanupAll(runtimeCleanup,cleanupTimeoutMs))).pipe(asVoid2)}));let closing;return{close:flow(()=>gen2(function*nativeProcessStep4(){stopped=true;closing??=cleanupAll([{name:"watcher",run:flow(()=>suspend2(()=>awaitValue6(watcher.close())).pipe(asVoid2),runPromise2)},{name:"refresh",run:flow(()=>tryPromise2(flow(()=>suspend2(()=>awaitValue6(refreshQueue)).pipe(asVoid2),runPromise2)).pipe(ignore2),runNested)},...runtimeCleanup],cleanupTimeoutMs);return yield*awaitValue6(closing).pipe(asVoid2)}),runPromise2),sessions:runtime.sessions}}).pipe(catchCause2(rethrowRuntimeRefreshCause)),runPromise2);class PackageDevelopmentCommandError extends TaggedError3()("PackageDevelopmentCommandError",{cause:optional2(Unknown2),message:String4}){}var packageDevelopmentFailureMessage=(cause)=>{if(is2(TaggedStruct("Forbidden",{}))(cause)){return"Package development failed: Forbidden. Possible causes include disabled extension development on the dedicated development backend (check APP_EXTENSIONS_DEVELOPMENT_ENABLED=true), or missing human tenant-admin / organization permissions. The backend did not identify which check failed."}return cause instanceof Error?cause.message:"Package development failed"};var packageDevelopmentError=(cause)=>is2(PackageDevelopmentCommandError)(cause)?cause:new PackageDevelopmentCommandError({cause,message:packageDevelopmentFailureMessage(cause)});var parsePackageDevelopmentOptions=(args)=>{const[command,...options]=args;if(command!=="dev"){throw new PackageDevelopmentCommandError({message:"Expected package dev"})}let declaration;const hostOrigins=[];for(let index=0;index<options.length;index+=2){const flag=options[index];const value=options[index+1];if(!flag?.startsWith("--")||value===undefined||value.startsWith("--")){throw new PackageDevelopmentCommandError({message:"Options must be supplied as --name value pairs"})}switch(flag){case"--declaration":{declaration=value;break}case"--host-origin":{hostOrigins.push(value);break}default:{throw new PackageDevelopmentCommandError({message:`Unknown option ${flag}`})}}}if(declaration===undefined||declaration.trim()===""){throw new PackageDevelopmentCommandError({message:"Missing option --declaration"})}if(hostOrigins.length===0){throw new PackageDevelopmentCommandError({message:"At least one --host-origin must be explicitly attached"})}return{declaration,hostOrigins}};var packageDevelopmentCommandEffect=(args,dependencies)=>tryPromise2({catch:packageDevelopmentError,try:async()=>{const options=parsePackageDevelopmentOptions(args);const declarationSpecifier=dependencies.resolveDeclarationSpecifier(options.declaration);const processRuntime=await startPackageDevelopmentProcess({declarationSpecifier,hostOrigins:options.hostOrigins},dependencies);try{dependencies.writeResult(await runPromise2(encodeEffect(fromJsonString2(Unknown2))(processRuntime.sessions().length===1?processRuntime.sessions()[0]:processRuntime.sessions())));await dependencies.awaitTermination()}finally{await processRuntime.close()}}});init_sharedKeyMatcher_Od_nYxJA();init_logger_DOwfTlw5();init_dtsConstants_r5OfegUr();init_dist();import{createRequire as createRequire3}from"module";import*as fs$2 from"fs";import{existsSync as existsSync7,readFileSync as readFileSync5,readdirSync as readdirSync3,realpathSync as realpathSync3,statSync,writeFileSync as writeFileSync4}from"fs";import{createRequire as createRequire$12,isBuiltin}from"module";import*as path$14 from"path";import path9,{basename as basename2}from"path";import{fileURLToPath as fileURLToPath10,pathToFileURL as pathToFileURL4}from"url";import*as vite from"vite";import{parseAst as parseAst2,version as version4}from"vite";import{createHash as createHash6}from"crypto";import*as fs$12 from"fs";import{existsSync as existsSync$1,readFileSync as readFileSync$1}from"fs";import{pathToFileURL as pathToFileURL$1}from"url";import{isIPv6}from"net";import{readFile as readFile5}from"fs/promises";var __filename="/home/runner/_work/ci-app/ci-app/node_modules/.bun/@module-federation+vite@1.23.2+eebbd1cfa443764b/node_modules/@module-federation/vite/lib/index.js";var REGEXP_SPECIAL_CHARS_RE=/[.*+?^${}()|[\]\\]/g;function escapeRegExp(value){return value.replace(REGEXP_SPECIAL_CHARS_RE,"\\$&")}function isOutputChunk$1(chunk){return chunk.type==="chunk"}function isIdentifierReferenced(name,code){return new RegExp(`(?<![$\\w])${escapeRegExp(name)}(?![$\\w])`).test(code)}function getProxyBaseName(fileName){return fileName.replace(/^.*\//,"").replace(/\.js$/,"").replace(/-[A-Za-z0-9_-]+$/,"")}function functionDeclarationRegExp(name){return new RegExp(`function\\s+${escapeRegExp(name)}\\s*\\(`)}function extractFunctionDeclaration(code,functionName){const funcRe=new RegExp(`function\\s+${escapeRegExp(functionName)}\\s*\\([^)]*\\)\\s*\\{`);const funcStart=code.search(funcRe);if(funcStart<0)return;let depth=0;for(let i=code.indexOf("{",funcStart);i<code.length;i++)if(code[i]==="{")depth++;else if(code[i]==="}"){depth--;if(depth===0)return code.slice(funcStart,i+1)}}function resolveProxyAlias(binding,proxyLocal,code,fullImport,claimedLocals=new Set){const codeWithoutImport=code.replace(fullImport,"");const localUsedInCode=isIdentifierReferenced(binding.local,codeWithoutImport);const claimedImportLocals=new Set;const importRe=/import\s*\{([^}]+)\}\s*from\s*["'][^"']+["']\s*;?/g;let match;while((match=importRe.exec(codeWithoutImport))!==null)for(const spec of match[1].split(",")){const parts=spec.trim().split(/\s+as\s+/);claimedImportLocals.add((parts[1]||parts[0]).trim())}const local=!localUsedInCode&&!claimedLocals.has(proxyLocal)&&!claimedImportLocals.has(proxyLocal)?proxyLocal:binding.local;return{imported:binding.imported,local}}function collectLoadShareProxyChunks(bundle,loadShareTag){const proxyChunks=new Map;for(const[fileName,chunk]of Object.entries(bundle)){if(!isOutputChunk$1(chunk))continue;if(fileName.includes(loadShareTag)&&fileName.includes("commonjs-proxy"))proxyChunks.set(fileName,{code:chunk.code,fileName})}return proxyChunks}function collectSystemProxyInfos(proxyChunks,loadShareTag){const systemProxyInfo=new Map;for(const[proxyFileName,proxyInfo]of Array.from(proxyChunks.entries())){const depsMatch=proxyInfo.code.match(/System\.register\(\[([\s\S]*?)\]/);if(!depsMatch)continue;const loadShareDep=Array.from(depsMatch[1].matchAll(/["']([^"']+)["']/g)).map((m)=>m[1]).find((dep)=>dep.includes(loadShareTag)&&!dep.includes("commonjs-proxy"));if(!loadShareDep)continue;const loadShareBindings={};for(const m of proxyInfo.code.matchAll(/([A-Za-z_$][\w$]*)\s*=\s*module\d+\.([A-Za-z_$][\w$]*)/g))loadShareBindings[m[1]]=m[2];const exportMap={};const objectExportMatch=proxyInfo.code.match(/exports\(\s*\{([\s\S]*?)\}\s*\)/);if(objectExportMatch)for(const m of objectExportMatch[1].matchAll(/([A-Za-z_$][\w$]*)\s*:\s*([A-Za-z_$][\w$]*)/g)){const[,exported,local]=m;const funcBody=extractFunctionDeclaration(proxyInfo.code,local);if(funcBody)exportMap[exported]={type:"helper",code:funcBody}}for(const m of proxyInfo.code.matchAll(/exports\(\s*["']([^"']+)["']\s*,([\s\S]*?)\);/g)){const exported=m[1];const expression=m[2];for(const[local,exportName]of Object.entries(loadShareBindings).reverse())if(isIdentifierReferenced(local,expression)){exportMap[exported]={type:"reexport",exportName};break}}if(Object.keys(exportMap).length>0)systemProxyInfo.set(proxyFileName,{loadShareDep,exportMap})}return systemProxyInfo}function rewriteEsmProxyConsumers(code,proxyChunks){let nextCode=code;const claimedLocals=new Set;for(const[proxyFileName,proxyInfo]of Array.from(proxyChunks.entries())){const proxyBaseName=getProxyBaseName(proxyFileName);const importMatch=new RegExp(`import\\s*\\{([^}]+)\\}\\s*from\\s*["']([^"']*${escapeRegExp(proxyBaseName)}[^"']*)["']\\s*;?`).exec(nextCode);if(!importMatch)continue;const fullImport=importMatch[0];const bindings=importMatch[1].split(",").map((s)=>{const parts=s.trim().split(/\s+as\s+/);return{imported:parts[0].trim(),local:(parts[1]||parts[0]).trim()}});const exportMapMatch=proxyInfo.code.match(/export\s*\{([^}]+)\}/);if(!exportMapMatch)continue;const exportMap={};for(const entry of exportMapMatch[1].split(",")){const parts=entry.trim().split(/\s+as\s+/);if(parts.length===2)exportMap[parts[1].trim()]=parts[0].trim()}const inlineable=[];const nonInlineable=[];const pendingLocals=new Set(bindings.map((binding)=>binding.local));for(const b of bindings){pendingLocals.delete(b.local);const proxyLocal=exportMap[b.imported];if(!proxyLocal){claimedLocals.add(b.local);nonInlineable.push(b);continue}const funcBody=extractFunctionDeclaration(proxyInfo.code,proxyLocal);if(funcBody){inlineable.push({local:b.local,funcBody:funcBody.replace(functionDeclarationRegExp(proxyLocal),()=>`function ${b.local}(`)});claimedLocals.add(b.local)}else{const unavailableLocals=new Set(claimedLocals);pendingLocals.forEach((local)=>unavailableLocals.add(local));const resolvedBinding=resolveProxyAlias(b,proxyLocal,nextCode,fullImport,unavailableLocals);claimedLocals.add(resolvedBinding.local);nonInlineable.push(resolvedBinding)}}const hasRenamedAlias=nonInlineable.some((b)=>bindings.find((ob)=>ob.imported===b.imported)?.local!==b.local);if(inlineable.length===0&&!hasRenamedAlias)continue;let replacement="";if(nonInlineable.length>0)replacement=`import{${nonInlineable.map((b)=>b.imported===b.local?b.imported:`${b.imported} as ${b.local}`).join(",")}}from"${importMatch[2]}";`;replacement+=inlineable.map((f)=>f.funcBody).join("");nextCode=nextCode.replace(fullImport,()=>replacement)}return nextCode}function rewriteSystemProxyConsumers(code,systemProxyInfo){if(!code.includes("System.register("))return code;let nextCode=code;for(const[proxyFileName,proxyInfo]of Array.from(systemProxyInfo.entries())){const proxyBaseName=getProxyBaseName(proxyFileName);const depMatch=new RegExp(`["']([^"']*${escapeRegExp(proxyBaseName)}[^"']*)["']`).exec(nextCode);if(!depMatch)continue;let setterIndex=0;const depListMatch=nextCode.match(/System\.register\(\[([\s\S]*?)\]/);if(depListMatch)setterIndex=Array.from(depListMatch[1].matchAll(/["']([^"']+)["']/g)).map((m)=>m[1]).findIndex((dep)=>dep.includes(proxyBaseName));if(setterIndex<0)continue;const settersStart=nextCode.indexOf("setters: [");if(settersStart<0)continue;const setterMatch=Array.from(nextCode.slice(settersStart).matchAll(/\((module\d+)\)\s*=>\s*\{([\s\S]*?)\}/g))[setterIndex];if(!setterMatch)continue;const[fullSetter,moduleLocal,setterBody]=setterMatch;const helpersToInline=[];const nextSetterBody=setterBody.replace(new RegExp(`([A-Za-z_$][\\w$]*)\\s*=\\s*${moduleLocal}\\.([A-Za-z_$][\\w$]*);?`,"g"),(assignment,local,imported)=>{const mapped=proxyInfo.exportMap[imported];if(!mapped)return assignment;if(mapped.type==="helper"){helpersToInline.push(mapped.code.replace(functionDeclarationRegExp(imported),()=>`function ${local}(`));return""}return`${local} = ${moduleLocal}.${mapped.exportName};`});if(nextSetterBody===setterBody&&helpersToInline.length===0)continue;const nextSetter=fullSetter.replace(setterBody,()=>nextSetterBody);nextCode=nextCode.replace(fullSetter,()=>nextSetter);nextCode=nextCode.replace(depMatch[0],JSON.stringify(proxyInfo.loadShareDep));if(helpersToInline.length>0)nextCode=nextCode.replace("execute: (function() {",()=>{return`execute: (function() {${helpersToInline.join("")}`})}return nextCode}function findRemoteEntryFile(filename,bundle){const strippedName=filename.replace(/[\[\]]/g,"_").replace(/\.[^/.]+$/,"");let fallback;for(const fileData of Object.values(bundle)){if(fileData.fileName===filename)return fileData.fileName;if(fallback===undefined&&(strippedName===fileData.name||fileData.name==="remoteEntry"))fallback=fileData.fileName}return fallback}async function mapCodeToCodeWithSourcemap(code){const resolvedCode=await code;if(resolvedCode===undefined)return;return{code:resolvedCode,map:createSourceMap(resolvedCode)}}function getPluginEnvironmentName(ctx){if(ctx==null||typeof ctx!=="object")return;const environment=ctx["environment"];if(environment==null||typeof environment!=="object")return;const name=environment["name"];return typeof name==="string"?name:undefined}function resolveEnvironmentConsumerTarget(ctx){if(ctx==null||typeof ctx!=="object")return;const environment=ctx["environment"];if(environment==null||typeof environment!=="object")return;const consumer=environment.config?.consumer;if(consumer==="client"||consumer==="server")return consumer;const envName=getPluginEnvironmentName(ctx);return!envName||envName==="client"?"client":"server"}function isClientEnvironment(ctx){return resolveEnvironmentConsumerTarget(ctx)!=="server"}function isServerBuildContext(ctx,config){const target=resolveEnvironmentConsumerTarget(ctx);if(target)return target==="server";return Boolean(config?.build?.ssr)}function resolveRemoteConsumer(ctx,hasMultiEnvironment){if(!hasMultiEnvironment)return"unified";return resolveEnvironmentConsumerTarget(ctx)??"client"}var IDENTIFIER=String.raw`[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}]*`;var NAMED_SPECIFIERS=String.raw`\{[^{}]*\}`;var NAMESPACE_SPECIFIER=String.raw`\*\s*as\s+${IDENTIFIER}`;var IMPORT_CLAUSE=String.raw`(?:(?<importType>type)\s+)?(?<importClause>${NAMESPACE_SPECIFIER}|${NAMED_SPECIFIERS}|${IDENTIFIER}(?:\s*,\s*(?:${NAMESPACE_SPECIFIER}|${NAMED_SPECIFIERS}))?)`;var EXPORT_CLAUSE=String.raw`(?:(?<exportType>type)\s+)?(?<exportClause>\*(?:\s*as\s+(?:${IDENTIFIER}|"[^"]*"|'[^']*'))?|${NAMED_SPECIFIERS})`;var SPECIFIER=String.raw`(?<quote>["'])(?<source>[^"'\r\n]*)\k<quote>`;var KEYWORD_BOUNDARY=String.raw`(?<![.$\w])`;var KEYWORD_GAP=String.raw`(?:\s+|(?=[{*]))`;var STATIC_PATTERN=new RegExp(String.raw`${KEYWORD_BOUNDARY}(?:import${KEYWORD_GAP}${IMPORT_CLAUSE}|export${KEYWORD_GAP}${EXPORT_CLAUSE})\s*from\s*${SPECIFIER}`,"gud");var DYNAMIC_PATTERN=new RegExp(String.raw`${KEYWORD_BOUNDARY}import\s*\(\s*${SPECIFIER}`,"gud");var REQUIRE_PATTERN=new RegExp(String.raw`${KEYWORD_BOUNDARY}require\s*\(\s*${SPECIFIER}\s*\)`,"gud");var SIDE_EFFECT_PATTERN=new RegExp(String.raw`${KEYWORD_BOUNDARY}import\s*${SPECIFIER}`,"gud");function blankNonCode(code){const codePositions=createCodePositionMap(code);const chars=code.split("");let index=0;while(index<code.length){if(codePositions[index]){index++;continue}const start=index;while(index<code.length&&!codePositions[index])index++;const quote=code[start];const isString=(quote==='"'||quote==="'")&&index-start>=2&&code[index-1]===quote;for(let position=start;position<index;position++)chars[position]=isString&&(position===start||position===index-1)?quote:code[position]===`
|
|
313
314
|
`?`
|
|
314
315
|
`:" "}return chars.join("")}function isTypeOnlyNamedClause(clause){const namedSpecifiers=clause.trim().match(/^\{([\s\S]*)\}$/)?.[1];if(namedSpecifiers===undefined)return false;const specifiers=namedSpecifiers.split(",").map((specifier)=>specifier.trim()).filter(Boolean);return specifiers.length>0&&specifiers.every((specifier)=>/^type\s+(?!as(?:\s|$))\S/.test(specifier))}function readSource(code,match){const range=match.indices?.groups?.source;if(!range)return;const source=code.slice(range[0],range[1]);return source.length>0?source:undefined}function findModuleImportDescriptors(code){const blanked=blankNonCode(code);const descriptors=[];for(const match of blanked.matchAll(STATIC_PATTERN)){const source=readSource(code,match);if(!source)continue;const groups=match.groups;const typeOnly=groups.importType!==undefined||groups.exportType!==undefined||isTypeOnlyNamedClause(groups.importClause??groups.exportClause??"");descriptors.push({kind:"static",syntax:"import",source,typeOnly})}for(const match of blanked.matchAll(DYNAMIC_PATTERN)){const source=readSource(code,match);if(source)descriptors.push({kind:"dynamic",syntax:"import",source,typeOnly:false})}for(const match of blanked.matchAll(REQUIRE_PATTERN)){const source=readSource(code,match);if(source)descriptors.push({kind:"dynamic",syntax:"require",source,typeOnly:false})}for(const match of blanked.matchAll(SIDE_EFFECT_PATTERN)){const source=readSource(code,match);if(source)descriptors.push({kind:"static",syntax:"import",source,typeOnly:false})}return descriptors}function getScannableModuleSource(id,code){if(!/\.(?:vue|svelte)(?:\?|$)/.test(id))return code;const blocks=[];for(const match of code.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script(?:\s[^>]*)?>/gi))blocks.push(match[1]);return blocks.join(`
|
|
315
316
|
`)}function findModuleImportSources(code){return Array.from(new Set(findModuleImportDescriptors(code).filter(({syntax,typeOnly})=>syntax==="import"&&!typeOnly).map(({source})=>source)))}function sanitizeDevEntryPath(devEntryPath){return devEntryPath.replace(/\\\\?/g,"/")}function rewriteEntryScripts(html,createProxySrc){return html.replace(/<script\b(?=[^>]*\btype=["']module["'])(?=[^>]*\bsrc=["'][^"']+["'])([^>]*)>/gi,(match,attrs)=>{if(/\svite-ignore(?:\s|=|\/|$)/i.test(attrs))return match;const srcMatch=attrs.match(/\bsrc=["']([^"']+)["']/i);if(!srcMatch)return match;const originalSrc=srcMatch[1];if(originalSrc.includes("@vite/client"))return match;const proxySrc=createProxySrc(originalSrc);return match.replace(srcMatch[0],`src=${JSON.stringify(proxySrc)}`)})}function injectEntryScript(html,initSrc){const src=sanitizeDevEntryPath(initSrc);const script=`<script type="module" src=${JSON.stringify(src)}></script>`;return html.replace(/<head\b[^>]*>/i,(openTag)=>`${openTag}${script}`)}var INTERNAL_NAME_PREFIX="__mfe_internal__";function toInternalModuleFederationName(name){return name.startsWith(INTERNAL_NAME_PREFIX)?name:`${INTERNAL_NAME_PREFIX}${name}`}function warnOnReservedInternalNamePrefix(name,kind){if(!name.startsWith(INTERNAL_NAME_PREFIX))return;mfWarn(`Reserved internal ${kind} prefix "${INTERNAL_NAME_PREFIX}" detected in public ${kind} "${name}". This prefix is reserved for internal module federation names and may cause conflicts.`)}function normalizeExposesItem(item){let importPath="";if(typeof item==="string")importPath=item;if(typeof item==="object")importPath=item.import;return{import:importPath}}function normalizeExposes(exposes){if(!exposes)return{};const res={};Object.keys(exposes).forEach((key)=>{res[key]=normalizeExposesItem(exposes[key])});return res}function normalizeRemotes(remotes,defaultShareScope="default"){if(!remotes)return{};const result={};if(typeof remotes==="object")Object.keys(remotes).forEach((key)=>{result[key]=normalizeRemoteItem(key,remotes[key],defaultShareScope)});return result}function warnOmittedObjectRemoteType(remoteKey){mfWarn(`Remote "${remoteKey}" omits type and defaults to 'var'. Set type: 'module' for Vite ESM remotes, or type: 'var' explicitly to silence this warning.`)}function normalizeRemoteItem(key,remote,defaultShareScope){warnOnReservedInternalNamePrefix(key,"remoteAlias");if(typeof remote==="string"){const separatorIndex=remote.startsWith("@")?remote.indexOf("@",1):remote.indexOf("@");let entryGlobalName;let entry;if(separatorIndex>0){entryGlobalName=remote.slice(0,separatorIndex);entry=remote.slice(separatorIndex+1)}else{entryGlobalName=remote;entry=remote}return{type:"var",name:key,internalName:toInternalModuleFederationName(key),entry,entryGlobalName,shareScope:defaultShareScope}}const typeOmitted=remote.type===undefined||remote.type===null||remote.type==="";if(typeOmitted)warnOmittedObjectRemoteType(key);return Object.assign({type:"var",name:key,internalName:toInternalModuleFederationName(key),shareScope:defaultShareScope,entryGlobalName:key},{...remote,type:typeOmitted?"var":remote.type,internalName:toInternalModuleFederationName(remote.name||key)})}function searchPackageVersion(sharedName,cwd){const version=getInstalledPackageJson(sharedName,{cwd})?.packageJson.version;return typeof version==="string"?version:undefined}function inferVersionFromRequiredVersion(requiredVersion){if(typeof requiredVersion!=="string")return;const isDigit=(char)=>char!==undefined&&char>="0"&&char<="9";const isSuffixChar=(char)=>char!==undefined&&(char>="0"&&char<="9"||char>="A"&&char<="Z"||char>="a"&&char<="z"||char==="."||char==="-");let index=0;while(index<requiredVersion.length){if(!isDigit(requiredVersion[index])){index+=1;continue}const start=index;while(isDigit(requiredVersion[index]))index+=1;if(requiredVersion[index]!==".")continue;index+=1;if(!isDigit(requiredVersion[index]))continue;while(isDigit(requiredVersion[index]))index+=1;if(requiredVersion[index]!==".")continue;index+=1;if(!isDigit(requiredVersion[index]))continue;while(isDigit(requiredVersion[index]))index+=1;if((requiredVersion[index]==="-"||requiredVersion[index]==="+")&&isSuffixChar(requiredVersion[index+1])){index+=1;while(isSuffixChar(requiredVersion[index]))index+=1}return requiredVersion.slice(start,index)}}var PACKAGE_SPECIFIER_PROTOCOL_RE=/^[a-z][a-z\d+.-]*:/i;function isProtocolRequiredVersion(requiredVersion){return PACKAGE_SPECIFIER_PROTOCOL_RE.test(requiredVersion.trim())}var SEMVER_COMPARATOR_RE=/^(?:[<>=~^]*v?(?:\d+|[xX*])(?:\.(?:\d+|[xX*]))*(?:[-+][\w.-]+)?|[<>=~^]+|[xX*]|-)$/;function isSemverRange(range){return range.split("||").every((alternative)=>{const comparators=alternative.trim().split(/\s+/).filter(Boolean);return comparators.length>0&&comparators.every((c)=>SEMVER_COMPARATOR_RE.test(c))})}function isUsableRequiredVersion(requiredVersion){return requiredVersion.trim()!==""&&!isProtocolRequiredVersion(requiredVersion)&&isSemverRange(requiredVersion)}function isBareSpecifier(specifier){return!specifier.startsWith(".")&&!specifier.startsWith("\x00")&&!path$14.isAbsolute(specifier)&&!PACKAGE_SPECIFIER_PROTOCOL_RE.test(specifier)}function readProjectPackageJson(cwd,cache){if(cache.has(cwd))return cache.get(cwd);let packageJson;try{packageJson=JSON.parse(fs$2.readFileSync(path$14.join(cwd,"package.json"),"utf8"))}catch{}cache.set(cwd,packageJson);return packageJson}function getLitExportSubpathShares(sharedName){if(sharedName!=="lit")return[];const exportsField=getInstalledPackageJson(sharedName,{packageName:sharedName})?.packageJson.exports;if(!exportsField||typeof exportsField==="string")return[];return Object.keys(exportsField).filter((key)=>key.startsWith("./")&&key!=="."&&!key.includes("*")).map((key)=>`${sharedName}/${key.slice(2)}`)}var sharedVersionConfigs=new WeakMap;function resolveSharedVersion(key,config,cwd,packageJsonCache=new Map,fallbackVersion){const source=typeof config.import==="string"&&isBareSpecifier(config.import)?config.import:key;const version=config.version||searchPackageVersion(source,cwd)||inferVersionFromRequiredVersion(config.requiredVersion)||fallbackVersion;let requiredVersion=config.requiredVersion;if(requiredVersion===undefined&&!config.version){const packageJson=readProjectPackageJson(cwd,packageJsonCache);const packageName=getPackageName(source);requiredVersion=packageJson?.dependencies?.[packageName]??packageJson?.devDependencies?.[packageName]??packageJson?.peerDependencies?.[packageName]??packageJson?.optionalDependencies?.[packageName]}if(requiredVersion===false||typeof requiredVersion==="string"&&isUsableRequiredVersion(requiredVersion))return{version,requiredVersion};return{version,requiredVersion:config.import===false||config.version?"*":version?`^${version}`:"*"}}function resolveSharedVersions(shared,root){const packageJsonCache=new Map;for(const[key,item]of Object.entries(shared)){const config=sharedVersionConfigs.get(item);if(!config)continue;const{version,requiredVersion}=resolveSharedVersion(key,config,root,packageJsonCache,item.version);item.version=version;item.shareConfig.requiredVersion=requiredVersion}}function normalizeShareItem(key,shareItem,defaultShareScope){const treeShaking=typeof shareItem==="object"?shareItem.treeShaking:undefined;if(treeShaking&&treeShaking.mode!=="server-calc"&&treeShaking.mode!=="runtime-infer")throw createModuleFederationError(`Invalid shared config for "${key}": treeShaking.mode must be either "server-calc" or "runtime-infer".`);if(treeShaking&&typeof shareItem==="object"&&shareItem.eager)throw createModuleFederationError(`Invalid shared config for "${key}": cannot use both "eager: true" and "treeShaking.mode" simultaneously. Choose one strategy.`);if(typeof shareItem==="object"){const request=typeof shareItem.request==="string"?shareItem.request:key;const shareKey=typeof shareItem.shareKey==="string"?shareItem.shareKey:key;if(request.endsWith("/")!==shareKey.endsWith("/"))throw createModuleFederationError(`Invalid shared config for "${key}": "request" and "shareKey" must both end with "/" for a prefix share, or neither. Got request "${request}" and shareKey "${shareKey}".`)}if(treeShaking?.mode==="runtime-infer"&&typeof shareItem==="object"&&shareItem.singleton)mfWarn(`Shared singleton "${key}" uses runtime-infer tree shaking, which may load both a tree-shaken bundle and a full bundle when consumers require different exports. Prefer server-calc for singleton dependencies. If runtime-infer is required, expand usedExports to reduce this risk.`);const config=typeof shareItem==="object"?shareItem:{};const{version,requiredVersion}=resolveSharedVersion(key,config,getPackageDetectionCwd());if(typeof shareItem==="string"){const result={name:shareItem,version,scope:defaultShareScope,from:"",shareConfig:{import:undefined,singleton:false,eager:false,requiredVersion}};sharedVersionConfigs.set(result,{...config});return result}const result={name:key,from:"",version,scope:shareItem.shareScope||defaultShareScope,shareConfig:{import:shareItem.import,singleton:shareItem.singleton||false,eager:shareItem.eager||false,requiredVersion,strictVersion:!!shareItem.strictVersion,...shareItem.request!==undefined?{request:shareItem.request}:{},...shareItem.shareKey!==undefined?{shareKey:shareItem.shareKey}:{},...shareItem.allowNodeModulesSuffixMatch!==undefined?{allowNodeModulesSuffixMatch:shareItem.allowNodeModulesSuffixMatch}:{},...shareItem.suppressMissingImportWarning?{suppressMissingImportWarning:true}:{},...treeShaking?{treeShaking:{...treeShaking}}:{}}};sharedVersionConfigs.set(result,{...config});return result}function normalizeSharedKey(key){if(!key.endsWith("/"))return key;const baseKey=key.slice(0,-1);if(baseKey==="react")return key;return getCommonSharedSubpaths(baseKey).length>0?baseKey:key}function normalizeShared(shared,defaultShareScope="default"){explicitSharedKeys=new Set;if(!shared)return{};const result={};const sourceEntries=[];if(Array.isArray(shared))shared.forEach((key)=>{if(isModuleFederationRuntimePackage(key))return;const normalizedKey=normalizeSharedKey(key);const hadConfiguredPackageSubpath=result[normalizedKey]?.shareConfig?.__mfConfiguredPackageSubpath===true;result[normalizedKey]=normalizeShareItem(normalizedKey,normalizedKey,defaultShareScope);if(key.endsWith("/")||hadConfiguredPackageSubpath)result[normalizedKey].shareConfig.__mfConfiguredPackageSubpath=true;explicitSharedKeys.add(normalizedKey);sourceEntries.push([normalizedKey,normalizedKey])});else if(typeof shared==="object")Object.keys(shared).forEach((key)=>{if(isModuleFederationRuntimePackage(key))return;const normalizedKey=normalizeSharedKey(key);const value=shared[key];const hadConfiguredPackageSubpath=result[normalizedKey]?.shareConfig?.__mfConfiguredPackageSubpath===true;result[normalizedKey]=normalizeShareItem(normalizedKey,value,defaultShareScope);const requestIsPrefix=typeof value?.request==="string"&&value.request.endsWith("/");if(key.endsWith("/")||requestIsPrefix||hadConfiguredPackageSubpath)result[normalizedKey].shareConfig.__mfConfiguredPackageSubpath=true;explicitSharedKeys.add(normalizedKey);sourceEntries.push([normalizedKey,value])});sourceEntries.forEach(([key,value])=>{for(const subpathShare of getLitExportSubpathShares(key)){if(result[subpathShare])continue;result[subpathShare]=normalizeShareItem(subpathShare,value,defaultShareScope)}});return result}function isModuleFederationRuntimePackage(key){return key==="@module-federation/runtime"||key==="@module-federation/runtime-core"}function normalizeLibrary(library){if(!library)return;return library}function normalizeManifest(manifest){if(manifest===undefined)return;if(typeof manifest==="boolean")return manifest;return{...manifest,fileName:manifest.fileName||"mf-manifest.json"}}function normalizeExperiments(experiments){return{externalRuntime:experiments?.externalRuntime===true,provideExternalRuntime:experiments?.provideExternalRuntime===true,ssrMode:experiments?.ssrMode==="ISLAND"?"ISLAND":undefined,hostProvidesAllShared:experiments?.hostProvidesAllShared===true}}function normalizeSsrEntryLoader(ssrEntryLoader){const strategy=ssrEntryLoader?.strategy;if(strategy!=="temp-file"&&strategy!=="vm")return;return{strategy}}var config;var explicitSharedKeys=new Set;var explicitSharedKeysByOptions=new WeakMap;function resolveRuntimeImplementation(){const fallback=resolveImportPath("@module-federation/runtime");try{const packageJsonPath=resolveImportPath("@module-federation/runtime/package.json");const packageJson=JSON.parse(fs$2.readFileSync(packageJsonPath,"utf-8"));const importExport=packageJson.exports?.["."];const exportImport=typeof importExport==="object"?typeof importExport.import==="string"?importExport.import:importExport.import?.default:undefined;const esmEntry=packageJson.module||exportImport;if(esmEntry)return path$14.join(path$14.dirname(packageJsonPath),esmEntry)}catch{}return fallback}function getNormalizeModuleFederationOptions(){return config}function hasRemotes(options=getNormalizeModuleFederationOptions()){return Object.keys(options.remotes||{}).length>0}function hasShared(options=getNormalizeModuleFederationOptions()){return Object.keys(options.shared||{}).length>0}function isRemoteContainer(options=getNormalizeModuleFederationOptions()){return Object.keys(options.exposes||{}).length>0}function isRemoteOnlyContainer(options=getNormalizeModuleFederationOptions()){return isRemoteContainer(options)&&!hasRemotes(options)}function isLocalOnlyContainer(options=getNormalizeModuleFederationOptions()){return!isRemoteContainer(options)&&!hasRemotes(options)}function isExplicitSharedKey(key,options){return(options?explicitSharedKeysByOptions.get(options):explicitSharedKeys)?.has(key)??false}function getNormalizeShareItem(key,options=getNormalizeModuleFederationOptions()){const matchedKey=findSharedKey(key,options.shared);const shareItem=options.shared[key]||(matchedKey?options.shared[matchedKey]:undefined)||options.shared[getPackageName(key)]||options.shared[getPackageName(key)+"/"];if(shareItem)return shareItem;return Object.entries(options.shared).find(([sharedKey,item])=>{const runtimeKey=typeof item.shareConfig.shareKey==="string"?item.shareConfig.shareKey:sharedKey;return runtimeKey.endsWith("/")?key===runtimeKey.slice(0,-1)||key.startsWith(runtimeKey):runtimeKey===key})?.[1]}function normalizeModuleFederationOptions(options){warnOnReservedInternalNamePrefix(options.name,"containerName");if(options.virtualModuleDir&&options.virtualModuleDir.includes("/"))throw createModuleFederationError(`Invalid virtualModuleDir: "${options.virtualModuleDir}". The virtualModuleDir option cannot contain slashes (/). Please use a single directory name like '__mf__virtual__your_app_name'.`);const defaultShareScope=typeof options.shareScope==="string"?options.shareScope:"default";const normalized={exposes:normalizeExposes(options.exposes),filename:options.filename||"remoteEntry-[hash]",ssrFilename:options.ssrFilename||undefined,internalName:toInternalModuleFederationName(options.name),library:normalizeLibrary(options.library),name:options.name,remotes:normalizeRemotes(options.remotes,defaultShareScope),runtime:options.runtime,shareScope:options.shareScope||"default",shared:normalizeShared(options.shared,defaultShareScope),runtimePlugins:options.runtimePlugins||[],implementation:normalizePathForImport(options.implementation||resolveRuntimeImplementation()),manifest:normalizeManifest(options.manifest),dev:options.dev,dts:options.dts,getPublicPath:options.getPublicPath,publicPath:options.publicPath,shareStrategy:options.shareStrategy||"version-first",ignoreOrigin:options.ignoreOrigin||false,virtualModuleDir:options.virtualModuleDir||"__mf__virtual",hostInitInjectLocation:options.hostInitInjectLocation||"html",bundleAllCSS:options.bundleAllCSS||false,treeShakingDir:options.treeShakingDir,injectTreeShakingUsedExports:options.injectTreeShakingUsedExports,treeShakingSharedPlugins:options.treeShakingSharedPlugins,treeShakingSharedExcludePlugins:options.treeShakingSharedExcludePlugins,moduleParseTimeout:options.moduleParseTimeout??10,moduleParseIdleTimeout:options.moduleParseIdleTimeout,varFilename:options.varFilename,target:options.target,ssrExternals:options.ssrExternals,ssrEntryLoader:normalizeSsrEntryLoader(options.ssrEntryLoader),disableRemote:options.disableRemote,disableShared:options.disableShared,disableSnapshot:options.disableSnapshot,experiments:normalizeExperiments(options.experiments)};if(normalized.experiments.ssrMode==="ISLAND"&&Object.hasOwn(normalized.shared,"react"))mfWarn('Island expose generation is disabled because experiments.ssrMode is "ISLAND" and React is configured as shared. Remove "react" from shared to generate island exposes, or remove ssrMode to use standard shared rendering.');explicitSharedKeysByOptions.set(normalized,new Set(explicitSharedKeys));return config=normalized}function getSuffix(name){const base=basename2(name);const dotIndex=base.lastIndexOf(".");if(dotIndex>0&&dotIndex<base.length-1)return base.slice(dotIndex);return".js"}var patternMap={};var cacheMap={};var idCacheMap={};var VITE_ID_PREFIX="/@id/";var VITE_ENCODED_NULL_BYTE_PREFIX=`${VITE_ID_PREFIX}__x00__`;var MF_OWNER_INFIX="__mf_owner__";function createViteEncodedIdPrefixRegExp(sourcePrefix=""){return new RegExp(`^(?:${escapeRegExp(VITE_ENCODED_NULL_BYTE_PREFIX)})?${sourcePrefix}`)}function toViteEncodedId(id){return`${VITE_ENCODED_NULL_BYTE_PREFIX}${id}`}function decodeViteId(id){if(!id.startsWith("/@id/"))return id;const viteId=id.slice(5);return viteId.startsWith("__x00__")?`\x00${viteId.slice(7)}`:viteId}function assertModuleFound(tag,str=""){const module=VirtualModule.findById(str)??VirtualModule.findModule(tag,str);if(!module)throw createModuleFederationError(`Module Federation shared module '${str}' not found. Please ensure it's installed as a dependency in your package.json.`);return module}function normalizeVirtualModuleId(id){const decoded=decodeViteId(id).replace(/^\0+/,"");const queryIndex=decoded.indexOf("?");const hashIndex=decoded.indexOf("#");const endIndex=queryIndex===-1?hashIndex:hashIndex===-1?queryIndex:Math.min(queryIndex,hashIndex);return endIndex===-1?decoded:decoded.slice(0,endIndex)}var VirtualModule=class VirtualModule{name;tag;suffix;inited=false;code;importId;importIdKey;scopeName;static findName(tag,str=""){if(!patternMap[tag])patternMap[tag]=new RegExp(`(.*${packageNameEncode(tag)}(.+?)${packageNameEncode(tag)}.*)`);const moduleName=(normalizeVirtualModuleId(str).match(patternMap[tag])||[])[2];return moduleName?packageNameDecode(moduleName):undefined}static findModule(tag,str=""){const moduleName=VirtualModule.findName(tag,str);return moduleName?cacheMap[tag][moduleName]:undefined}static findById(id){const normalized=normalizeVirtualModuleId(id);return normalized.startsWith("virtual:mf:")?idCacheMap[normalized]:undefined}constructor(name,tag="__mf_v__",suffix="",scopeName){this.name=name;this.tag=tag;this.suffix=suffix||getSuffix(name);this.scopeName=scopeName;if(!cacheMap[this.tag])cacheMap[this.tag]={};cacheMap[this.tag][this.name]=this}getScopeName(){return this.scopeName}getImportId(){const mfName=this.scopeName??getNormalizeModuleFederationOptions().internalName;const importIdKey=`${mfName}${this.tag}${this.name}${this.tag}`;if(this.importId&&this.importIdKey===importIdKey)return this.importId;if(this.importId)delete idCacheMap[this.importId];this.importIdKey=importIdKey;const namePart=packageNameEncode(this.name);const mfNamePart=packageNameEncode(mfName);this.importId=`virtual:mf:${mfNamePart}${this.tag}${namePart}${this.tag}${this.suffix}`;idCacheMap[this.importId]=this;return this.importId}getResolvedId(){return`\x00${this.getImportId()}`}writeSync(code,force){if(!force&&this.inited)return;if(!this.inited)this.inited=true;this.code=code}write(code){this.writeSync(code,true)}};var SERVER_ENV_GUARD="import.meta.env.SSR";var SSR_ENTRY_LOADER_SPECIFIER="@module-federation/vite/ssrEntryLoader";var SSR_ONLY_RUNTIME_PLUGINS=new Set([SSR_ENTRY_LOADER_SPECIFIER]);function isServerEnvironment(name,config){return config?.consumer==="server"||Boolean(config?.build?.ssr)||name==="ssr"||name==="server"}function isSsrConfig(config){if(Boolean(config.build?.ssr))return true;return Object.entries(config.environments??{}).some(([name,environment])=>isServerEnvironment(name,environment))}function getSsrCapabilities(viteMajor,command,hasRemotes,isSsr=false){if(!hasRemotes)return{enableSsrInitBootstrap:false,injectSsrEntryLoader:false};const supported=isSsr&&(command==="build"||command==="serve"&&viteMajor>=8);return{enableSsrInitBootstrap:supported,injectSsrEntryLoader:supported}}var UNSAFE_JS_CHAR_MAP={"<":"\\u003C","\u2028":"\\u2028","\u2029":"\\u2029"};var UNSAFE_JS_CHAR_PATTERN=/[<\u2028\u2029]/g;function toSafeJsLiteral(value){const json=JSON.stringify(value);if(json===undefined)return"undefined";return json.replace(UNSAFE_JS_CHAR_PATTERN,(char)=>UNSAFE_JS_CHAR_MAP[char])}function serializeRuntimeOptions(options){const ancestors=new WeakSet;function valueToCode(val){if(val===null)return"null";const type=typeof val;if(type==="string")return toSafeJsLiteral(val);if(type==="number"||type==="boolean")return String(val);if(type==="undefined")return"undefined";if(type==="symbol")return`Symbol(${toSafeJsLiteral(val.description??"")})`;if(type==="function")return functionToExpression(val);if(val instanceof Date)return`new Date(${toSafeJsLiteral(val.toISOString())})`;if(val instanceof RegExp)return`new RegExp(${toSafeJsLiteral(val.source)}, ${toSafeJsLiteral(val.flags)})`;if(type==="object"){if(ancestors.has(val))return`"__circular__"`;ancestors.add(val);try{if(Array.isArray(val))return`[${val.map(valueToCode).join(", ")}]`;if(val instanceof Map)return`new Map([${Array.from(val.entries()).map(([k,v])=>`[${valueToCode(k)}, ${valueToCode(v)}]`).join(", ")}])`;if(val instanceof Set)return`new Set([${Array.from(val.values()).map(valueToCode).join(", ")}])`;const properties=[];for(const key in val)if(Object.hasOwn(val,key))properties.push(`${toSafeJsLiteral(key)}: ${valueToCode(val[key])}`);return`{${properties.join(", ")}}`}finally{ancestors.delete(val)}}return toSafeJsLiteral(String(val))}const topLevelProps=[];for(const key in options)if(Object.hasOwn(options,key))topLevelProps.push(`${toSafeJsLiteral(key)}: ${valueToCode(options[key])}`);return`{${topLevelProps.join(", ")}}`}var NATIVE_FUNCTION_SOURCE=/\{\s*\[native code\]\s*\}\s*$/;function functionToExpression(fn){let source;try{source=Function.prototype.toString.call(fn).trim()}catch{return"undefined"}if(NATIVE_FUNCTION_SOURCE.test(source)||/^(async\s+)?(?:get|set)\s+/.test(source))return"undefined";if(/^(async\s+)?function\b/.test(source)||/^(async\s*)?\(/.test(source)||/^class\b/.test(source)||/^(async\s+)?[$_\p{ID_Start}][$\p{ID_Continue}]*\s*=>/u.test(source))return isParsableExpression(source)?source:"undefined";for(const[pattern,prefix]of[[/^async\s*\*\s*[$_\p{ID_Start}][$\p{ID_Continue}]*\s*(\([\s\S]*)$/u,"async function* "],[/^\*\s*[$_\p{ID_Start}][$\p{ID_Continue}]*\s*(\([\s\S]*)$/u,"function* "],[/^async\s+[$_\p{ID_Start}][$\p{ID_Continue}]*\s*(\([\s\S]*)$/u,"async function "],[/^[$_\p{ID_Start}][$\p{ID_Continue}]*\s*(\([\s\S]*)$/u,"function "]]){const match=source.match(pattern);if(!match)continue;const expression=`${prefix}${match[1]}`;return isParsableExpression(expression)?expression:"undefined"}return"undefined"}function isParsableExpression(source){try{new Function(`return (${source});`);return true}catch{return false}}function getRuntimePluginSpecifier(plugin){return typeof plugin==="string"?plugin:plugin[0]}function filterRuntimePluginsForTarget(runtimePlugins,ssrOnlySpecifiers,isServer){if(isServer)return[...runtimePlugins];return runtimePlugins.filter((plugin)=>!ssrOnlySpecifiers.has(getRuntimePluginSpecifier(plugin)))}var analysisByBuild=new WeakMap;function getImportAnalysis(build){let analysis=analysisByBuild.get(build);if(!analysis){const importsByCode=new Map;analysis={analyze(code){const cached=importsByCode.get(code);if(cached!==undefined)return cached;const imports=analyzeImports(code);importsByCode.set(code,imports);return imports},clear(){importsByCode.clear()}};analysisByBuild.set(build,analysis)}return analysis}function isRecord3(value){return value!==null&&typeof value==="object"}function getModuleSource(node){if(!isRecord3(node))return;const source=node;if(source.type==="Literal"&&typeof source.value==="string")return source.value;if(source.type==="StringLiteral"&&typeof source.value==="string")return source.value;if(source.type!=="TemplateLiteral")return;const expressions=Array.isArray(source.expressions)?source.expressions:[];const quasis=Array.isArray(source.quasis)?source.quasis:[];if(expressions.length>0||quasis.length!==1)return;const quasi=quasis[0];if(!isRecord3(quasi)||!isRecord3(quasi.value))return;const value=quasi.value;return typeof value.cooked==="string"?value.cooked:typeof value.raw==="string"?value.raw:undefined}function getExportedName(node){if(!isRecord3(node))return;const exported=node;if(exported.type==="Identifier"&&typeof exported.name==="string")return exported.name;if((exported.type==="Literal"||exported.type==="StringLiteral")&&typeof exported.value==="string")return exported.value}function isTypeOnly(node){return node.importKind==="type"||node.exportKind==="type"}function forEachAstNode(root,visit){const stack=[root];const seen=new Set;while(stack.length>0){const value=stack.pop();if(!isRecord3(value))continue;if(seen.has(value))continue;seen.add(value);if(Array.isArray(value)){for(let index=value.length-1;index>=0;index--)stack.push(value[index]);continue}const node=value;if(typeof node.type==="string")visit(node);Object.entries(node).forEach(([key,child])=>{if(key!=="parent"&&key!=="loc")stack.push(child)})}}function collectImportDeclaration(node,source,record,requireAllExports){if(isTypeOnly(node))return;const specifiers=Array.isArray(node.specifiers)?node.specifiers:[];if(specifiers.length===0){requireAllExports(source);return}const names=[];for(const specifier of specifiers){if(!isRecord3(specifier)){requireAllExports(source);return}if(isTypeOnly(specifier))continue;if(specifier.type==="ImportNamespaceSpecifier"){requireAllExports(source);return}if(specifier.type==="ImportDefaultSpecifier"){names.push("default");continue}if(specifier.type==="ImportSpecifier"){const imported=specifier.imported;if(isRecord3(imported)&&(imported.type==="Literal"||imported.type==="StringLiteral")){requireAllExports(source);return}const name=getExportedName(specifier.imported);if(!name){requireAllExports(source);return}names.push(name);continue}requireAllExports(source);return}record(names,source)}function collectReExport(node,source,record,requireAllExports){if(isTypeOnly(node))return;if(node.type==="ExportAllDeclaration"){requireAllExports(source);return}const specifiers=Array.isArray(node.specifiers)?node.specifiers:[];if(specifiers.length===0){requireAllExports(source);return}const names=[];for(const specifier of specifiers){if(!isRecord3(specifier)){requireAllExports(source);return}if(isTypeOnly(specifier))continue;if(specifier.type!=="ExportSpecifier"){requireAllExports(source);return}const local=specifier.local;if(isRecord3(local)&&(local.type==="Literal"||local.type==="StringLiteral")){requireAllExports(source);return}const name=getExportedName(specifier.local);if(!name){requireAllExports(source);return}names.push(name)}record(names,source)}function analyzeImports(code){let ast;try{ast=vite.parseAst(code)}catch{return null}const imports=[];const recordSource=(names,source)=>imports.push({source,usedExports:names});const requireAllExports=(source)=>imports.push({source,usedExports:null});const collectImport=(node)=>{if(node.type==="ImportDeclaration"){const source=getModuleSource(node.source);if(source)collectImportDeclaration(node,source,recordSource,requireAllExports);return}if((node.type==="ExportNamedDeclaration"||node.type==="ExportAllDeclaration")&&node.source){const source=getModuleSource(node.source);if(source)collectReExport(node,source,recordSource,requireAllExports);return}if(node.type==="ImportExpression"){const source=getModuleSource(node.source);if(source)requireAllExports(source);return}if(node.type==="CallExpression"){const callee=node.callee;const args=Array.isArray(node.arguments)?node.arguments:[];if(isRecord3(callee)&&callee.type==="Identifier"&&callee.name==="require"&&args.length>0){const source=getModuleSource(args[0]);if(source)requireAllExports(source)}}};if("Visitor"in vite&&typeof vite.Visitor==="function"){const visit=(node)=>{if(isRecord3(node))collectImport(node)};try{new vite.Visitor({ImportDeclaration:visit,ExportNamedDeclaration:visit,ExportAllDeclaration:visit,ImportExpression:visit,CallExpression:visit}).visit(ast);return imports}catch{imports.length=0}}forEachAstNode(ast,collectImport);return imports}function shouldAnalyzeSharedExports(shareItem){return!!(shareItem&&(shareItem.shareConfig.treeShaking||shareItem.shareConfig.import===false))}var legacyTreeShakingState={inferredUsage:new Map,buildMode:false};var treeShakingStates=new WeakMap;function getTreeShakingState(options){if(!options)return legacyTreeShakingState;let state=treeShakingStates.get(options);if(!state){state={inferredUsage:new Map,buildMode:false};treeShakingStates.set(options,state)}return state}function setTreeShakingBuildMode(enabled,options){getTreeShakingState(options).buildMode=enabled}function resetTreeShakingExports(options){getTreeShakingState(options).inferredUsage.clear()}function getOrCreateExportRecord(sharedKey,request,options){const inferredUsage=getTreeShakingState(options).inferredUsage;let byRequest=inferredUsage.get(sharedKey);if(!byRequest){byRequest=new Map;inferredUsage.set(sharedKey,byRequest)}let record=byRequest.get(request);if(!record){record={requiresFullBundle:false,usedExports:new Set};byRequest.set(request,record)}return record}function recordTreeShakingExports(sharedKey,exports,request=sharedKey,options){const record=getOrCreateExportRecord(sharedKey,request,options);exports.forEach((name)=>record.usedExports.add(name))}function markTreeShakingPackageUnsafe(sharedKey,request=sharedKey,options){getOrCreateExportRecord(sharedKey,request,options).requiresFullBundle=true}function getExportRecords(sharedKey,request,options){const inferredUsage=getTreeShakingState(options).inferredUsage;if(sharedKey){const records=inferredUsage.get(sharedKey);const wildcard=records?.get("*");const exact=records?.get(request);return[wildcard,exact===wildcard?undefined:exact].filter((record)=>!!record)}const records=[];inferredUsage.forEach((byRequest,configuredKey)=>{const wildcard=byRequest.get("*");const exact=byRequest.get(request);const configuredRequest=getSharedRequest(configuredKey,options?.shared?.[configuredKey]);const keyBase=configuredRequest.endsWith("/")?configuredRequest.slice(0,-1):configuredRequest;const requestMatchesConfiguredKey=request===keyBase||request.startsWith(`${keyBase}/`);if(wildcard&&requestMatchesConfiguredKey)records.push(wildcard);if(exact&&exact!==wildcard)records.push(exact)});return records}function getSharedExportUsage(request,shareItem,sharedKey,options){const treeShaking=shareItem?.shareConfig.treeShaking;if(!shouldAnalyzeSharedExports(shareItem)||!getTreeShakingState(options).buildMode)return;const records=getExportRecords(sharedKey,request,options);if(records.some((record)=>record.requiresFullBundle))return{kind:"full"};const configured=treeShaking?.usedExports??[];const result=new Set(configured);records.forEach((record)=>record.usedExports.forEach((name)=>result.add(name)));if(result.size>0)return{kind:"exports",usedExports:[...result].sort()};return records.length>0?{kind:"exports",usedExports:[]}:{kind:"unknown"}}function getTreeShakingExportUsage(request,shareItem,sharedKey,options){if(!shareItem?.shareConfig.treeShaking)return;return getSharedExportUsage(request,shareItem,sharedKey,options)}async function collectTreeShakingImports(code,id,shared,findSharedKey,record,markUnsafe,analysis=getImportAnalysis(shared)){const normalizedId=normalizePathForImport(id);if(normalizedId.includes("__prebuild__")||normalizedId.includes("__loadShare__")||normalizedId.includes("__mf_tree_shaking_graph__"))return;const imports=analysis.analyze(code);if(imports===null){Object.entries(shared).forEach(([sharedKey,shareItem])=>{if(shouldAnalyzeSharedExports(shareItem))markUnsafe(sharedKey,"*")});return}const pending=[];for(const{source,usedExports}of imports){const apply=(key)=>{if(!key||!shouldAnalyzeSharedExports(shared[key]))return;if(usedExports===null)markUnsafe(key,source);else record(key,usedExports,source)};const key=findSharedKey(source,shared);if(key instanceof Promise)pending.push(key.then(apply));else apply(key)}await Promise.all(pending)}var SOURCE_EXTENSIONS$1=[".tsx",".jsx",".ts",".js",".mts",".mjs",".cts",".cjs"];function resolveSourceFile(importPath,root){const cleanImport=stripQueryAndHash(importPath);if(!cleanImport.startsWith(".")&&!path$14.isAbsolute(cleanImport))return;const candidate=path$14.isAbsolute(cleanImport)?cleanImport:path$14.resolve(root,cleanImport);return[candidate,...SOURCE_EXTENSIONS$1.map((extension)=>`${candidate}${extension}`),...SOURCE_EXTENSIONS$1.map((extension)=>path$14.join(candidate,`index${extension}`))].find((filePath)=>{try{return fs$12.statSync(filePath).isFile()}catch{return false}})}function localDefaultReexport(source){const match=source.match(/export\s*{\s*(?:default(?:\s+as\s+default)?|[A-Za-z_$][\w$]*\s+as\s+default)\s*}\s*from\s*["']([^"']+)["']/);return match?.[1]?.startsWith(".")?match[1]:undefined}function isReactComponentSource(source,filePath="component.tsx"){if(!(/\bexport\s+default\b/.test(source)||/\bexport\s*{[^}]*\bdefault\b[^}]*}(?:\s*from\s*["'][^"']+["'])?/.test(source)))return false;const extension=path$14.extname(stripQueryAndHash(filePath)).toLowerCase();const canContainJsx=extension===".tsx"||extension===".jsx";const hasJsx=/<>|<\s*[A-Za-z][\w.:-]*(?:\s[^<>]*?)?\s*\/?>/.test(source);const importsReact=/\bfrom\s*["']react["']|\brequire\(\s*["']react["']\s*\)/.test(source);const usesReactApi=/\b(?:React\.)?(?:createElement|jsx|jsxs)\s*\(/.test(source);const isClientModule=/^\s*["']use client["']\s*;?/m.test(source);return canContainJsx&&hasJsx||importsReact&&(hasJsx||usesReactApi||isClientModule)}function isReactComponentFile(filePath,seen=new Set){const normalizedPath=path$14.resolve(filePath);if(seen.has(normalizedPath))return false;seen.add(normalizedPath);let source;try{source=fs$12.readFileSync(normalizedPath,"utf8")}catch{return false}if(isReactComponentSource(source,normalizedPath))return true;const reexport=localDefaultReexport(source);if(!reexport)return false;const reexportPath=resolveSourceFile(reexport,path$14.dirname(normalizedPath));return reexportPath?isReactComponentFile(reexportPath,seen):false}function getReactIslandExposes(options,root){if(options.experiments.ssrMode!=="ISLAND")return new Set;if(Object.hasOwn(options.shared,"react"))return new Set;const islandExposes=new Set;for(const[key,expose]of Object.entries(options.exposes)){const sourceFile=resolveSourceFile(expose.import,root);if(sourceFile&&isReactComponentFile(sourceFile))islandExposes.add(key)}return islandExposes}function generateReactIslandBrowserDefinition(enabled){if(!enabled)return"";return`
|
|
@@ -422,7 +423,7 @@ export default function ModuleFederationIslandClient({ html, islandProps }) {
|
|
|
422
423
|
suppressHydrationWarning: true,
|
|
423
424
|
dangerouslySetInnerHTML: { __html: html },
|
|
424
425
|
});
|
|
425
|
-
}`}function loadReactIslandConsumerModule(id){const serverRemoteId=remoteIdFromResolvedIslandId(id,RESOLVED_REACT_ISLAND_SERVER_ID_PREFIX);if(serverRemoteId!==undefined)return generateReactIslandConsumerServer(serverRemoteId);const clientRemoteId=remoteIdFromResolvedIslandId(id,RESOLVED_REACT_ISLAND_CLIENT_ID_PREFIX);if(clientRemoteId!==undefined)return generateReactIslandConsumerClient(clientRemoteId)}function getVirtualModuleScopeKey(options){return`${options.internalName}__${options.filename}`.replace(/[^a-zA-Z0-9_-]/g,"_")}function compareConfigValues(a,b){const serializedA=JSON.stringify(a);const serializedB=JSON.stringify(b);return serializedA<serializedB?-1:serializedA>serializedB?1:0}function stableConfigValue(value,ancestors=new WeakSet){if(typeof value==="function")return value.toString();if(!value||typeof value!=="object")return value;if(value instanceof Date)return{type:"Date",value:value.toISOString()};if(value instanceof RegExp)return{type:"RegExp",source:value.source,flags:value.flags};if(ancestors.has(value))return"__circular__";ancestors.add(value);let result;if(value instanceof Map){const entries=[...value.entries()].map(([key,item])=>[stableConfigValue(key,ancestors),stableConfigValue(item,ancestors)]);entries.sort(compareConfigValues);result={type:"Map",entries}}else if(value instanceof Set){const values=[...value].map((item)=>stableConfigValue(item,ancestors));values.sort(compareConfigValues);result={type:"Set",values}}else result=Array.isArray(value)?value.map((item)=>stableConfigValue(item,ancestors)):Object.fromEntries(Object.entries(value).filter(([key])=>key!=="implementation").sort(([a],[b])=>a<b?-1:a>b?1:0).map(([key,item])=>[key,stableConfigValue(item,ancestors)]));ancestors.delete(value);return result}function getFederationScopeKey(options){const identity=JSON.stringify(stableConfigValue(options));const ownerId=BigInt(`0x${
|
|
426
|
+
}`}function loadReactIslandConsumerModule(id){const serverRemoteId=remoteIdFromResolvedIslandId(id,RESOLVED_REACT_ISLAND_SERVER_ID_PREFIX);if(serverRemoteId!==undefined)return generateReactIslandConsumerServer(serverRemoteId);const clientRemoteId=remoteIdFromResolvedIslandId(id,RESOLVED_REACT_ISLAND_CLIENT_ID_PREFIX);if(clientRemoteId!==undefined)return generateReactIslandConsumerClient(clientRemoteId)}function getVirtualModuleScopeKey(options){return`${options.internalName}__${options.filename}`.replace(/[^a-zA-Z0-9_-]/g,"_")}function compareConfigValues(a,b){const serializedA=JSON.stringify(a);const serializedB=JSON.stringify(b);return serializedA<serializedB?-1:serializedA>serializedB?1:0}function stableConfigValue(value,ancestors=new WeakSet){if(typeof value==="function")return value.toString();if(!value||typeof value!=="object")return value;if(value instanceof Date)return{type:"Date",value:value.toISOString()};if(value instanceof RegExp)return{type:"RegExp",source:value.source,flags:value.flags};if(ancestors.has(value))return"__circular__";ancestors.add(value);let result;if(value instanceof Map){const entries=[...value.entries()].map(([key,item])=>[stableConfigValue(key,ancestors),stableConfigValue(item,ancestors)]);entries.sort(compareConfigValues);result={type:"Map",entries}}else if(value instanceof Set){const values=[...value].map((item)=>stableConfigValue(item,ancestors));values.sort(compareConfigValues);result={type:"Set",values}}else result=Array.isArray(value)?value.map((item)=>stableConfigValue(item,ancestors)):Object.fromEntries(Object.entries(value).filter(([key])=>key!=="implementation").sort(([a],[b])=>a<b?-1:a>b?1:0).map(([key,item])=>[key,stableConfigValue(item,ancestors)]));ancestors.delete(value);return result}function getFederationScopeKey(options){const identity=JSON.stringify(stableConfigValue(options));const ownerId=BigInt(`0x${createHash6("sha256").update(identity).digest("hex").slice(0,12)}`);return`${options.internalName}${MF_OWNER_INFIX}${ownerId}`}var EXPOSES_CSS_MAP_PLACEHOLDER="__MF_EXPOSES_CSS_MAP__";function getExposesCssMapPlaceholder(){return EXPOSES_CSS_MAP_PLACEHOLDER}function getVirtualExposesId(options){return`virtual:mf-exposes:${getVirtualModuleScopeKey(options)}`}function generateExposes(options,remoteDependencyMap={},command="build",reactIslandExposes=new Set){return`
|
|
426
427
|
const cssAssetMap = ${JSON.stringify(options.bundleAllCSS?EXPOSES_CSS_MAP_PLACEHOLDER:{})};
|
|
427
428
|
const injectedCssHrefs = new Set();
|
|
428
429
|
const exposeLoadPromises = new Map();
|
|
@@ -2925,7 +2926,7 @@ for (const __mfRemoteEntryPrefetchUrl of __mfRemoteEntryPrefetchUrls) {
|
|
|
2925
2926
|
${preloadBlock}${pendingSharesBlock}${sharedPreloadBlock}${pendingShareLoadsAwait}
|
|
2926
2927
|
})().then(() => ${entryImportExpression});
|
|
2927
2928
|
`;return[getRuntimeModuleCacheBootstrapCode(),importHelper,entryImportDeclaration,remoteEntryPrefetchBlock,importCode].join(`
|
|
2928
|
-
`)}function getSystemBootstrapSource(initSrc,entrySrc,pendingSharesSrc){return getBootstrapSource(initSrc,entrySrc,true,{pendingSharesSrc})}function injectHtml(){return inject==="html"&&(htmlFilePath||hasPackageDependency("@sveltejs/kit"))}function injectEntry(){if(inject==="html"&&hasPackageDependency("@sveltejs/kit"))return false;return inject==="entry"||!htmlFilePath}function normalizeDevHtmlProxyId(id){return decodeViteId(id).replace(/^\0/,"")}function normalizeModuleId(id){return normalizePathForImport(id.split("?")[0])}function isReactRouterClientEntry(id){const normalized=normalizeModuleId(decodeViteId(id).replace(/^\0+/,""));return/(?:^|\/)entry\.client\.(?:[cm]?[jt]sx?)$/.test(normalized)}function resolveProjectId(id){if(id.startsWith("\x00")||id.startsWith("virtual:"))return normalizeModuleId(id);return normalizeModuleId(path$14.isAbsolute(id)?id:path$14.resolve(viteConfig.root,id))}function isFederationInternalVirtualId(id){const normalized=decodeViteId(id).replace(/^\0+/,"");return normalized.includes("virtual:mf:")||normalized.startsWith("virtual:mf-")||/__(?:loadShare|prebuild|loadRemote)__/.test(normalized)}function isWorkspaceSourceId(id){const normalized=normalizeModuleId(decodeViteId(id));if(normalized.startsWith("\x00")||normalized.startsWith("virtual:"))return false;const filePath=stripQueryAndHash(normalized);if(filePath.startsWith("/@fs/"))return true;if(!path$14.isAbsolute(filePath))return false;const root=normalizePathForImport(path$14.resolve(viteConfig.root));const absolutePath=normalizePathForImport(path$14.resolve(filePath));const relativePath=normalizePathForImport(path$14.relative(root,absolutePath));return(relativePath===".."||relativePath.startsWith("../")||path$14.isAbsolute(relativePath))&&fs$2.existsSync(absolutePath)}function addEntryFile(file){const normalized=normalizeModuleId(file);if(!entryFiles.includes(normalized))entryFiles.push(normalized)}function addHtmlScriptEntries(htmlPath){if(!fs$2.existsSync(htmlPath))return;const htmlContent=fs$2.readFileSync(htmlPath,"utf-8");const scriptRegex=/<script\b(?=[^>]*\btype=["']module["'])(?=[^>]*\bsrc=["']([^"']+)["'])[^>]*>/gi;let match;while((match=scriptRegex.exec(htmlContent))!==null){if(/\svite-ignore(?:\s|=|\/?>)/i.test(match[0])){ignoredHtmlScriptSources.add(match[1]);continue}const scriptSrc=stripQueryAndHash(match[1]);if(/^(?:[a-z]+:)?\/\//i.test(scriptSrc))continue;addEntryFile(scriptSrc);addEntryFile(scriptSrc.startsWith("/")?path$14.resolve(viteConfig.root,scriptSrc.slice(1)):path$14.resolve(path$14.dirname(htmlPath),scriptSrc))}}function addEntryRemoteImports(entrySrc){if(!federationOptions||/^(?:[a-z]+:)?\/\//i.test(entrySrc))return;const file=path$14.resolve(viteConfig.root,stripQueryAndHash(entrySrc).replace(/^\//,""));if(!fs$2.existsSync(file))return;const code=fs$2.readFileSync(file,"utf-8");for(const source of findModuleImportSources(code)){const remote=Object.keys(federationOptions.remotes).find((name)=>source===name||source.startsWith(`${name}/`));if(remote)addUsedRemote(remote,source,federationOptions)}}return[{name:"add-entry",apply:"serve",config(_config,{command}){_command=command;const isRemoteEntry=entryName==="remoteEntry"&&federationOptions!==undefined&&isRemoteContainer(federationOptions);if(command==="serve"&&_config.experimental?.bundledDev&&isRemoteEntry){_config.experimental={..._config.experimental,bundledDev:false};_config.environments??={};_config.environments.client??={};if(_config.environments.client.isBundled!==false){_config.environments.client.isBundled=false;mfWarn("Vite bundledDev is disabled for the client environment of a Module Federation remote container so its remoteEntry keeps the standard init/get contract.")}}},configResolved(config){viteConfig=config;const resolvedEntryPath=getEntryPath();if(resolvedEntryPath.startsWith("virtual:mf"))devEntryPath=config.base+VITE_ID_PREFIX.slice(1)+resolvedEntryPath;else{const normalized=normalizePathForImport(resolvedEntryPath);const root=normalizePathForImport(config.root).replace(/\/$/,"");const relativePath=normalized.startsWith(root+"/")?normalized.slice(root.length):"/"+normalized.replace(/^[A-Za-z]:[\\/]/,"");devEntryPath=config.base+relativePath.replace(/^\//,"")}skipTransformIds=new Set(skipTransformFor.map(resolveProjectId))},configureServer(server){devServer=server;server.middlewares.use((req,res,next)=>{const rawUrl=req.url?.split("#")[0]??"";if(normalizeDevHtmlProxyId(rawUrl.split("?")[0])===DEV_HTML_PROXY_PREFIX.slice(0,-1)){const query=rawUrl.slice(rawUrl.indexOf("?")+1);const params=new URLSearchParams(query);const initSrc=params.get("init");const entrySrc=params.get("entry");if(initSrc&&entrySrc){const withBase=(src)=>viteConfig.base+src.replace(/^\//,"");const source=getBootstrapSource(withBase(initSrc),withBase(entrySrc));warmupDevEntryGraph(entrySrc).finally(()=>{res.statusCode=200;res.setHeader("Content-Type","application/javascript");res.end(source)});return}}if(!fileName){next();return}const devFileName=resolveHashPlaceholderFileName(fileName);if(devFileName!==fileName&&req.url?.startsWith((viteConfig.base+devFileName).replace(/^\/?/,"/")))req.url=req.url.replace(devFileName,fileName);if(req.url&&req.url.startsWith((viteConfig.base+fileName).replace(/^\/?/,"/"))){req.url=devEntryPath;req.headers["sec-fetch-dest"]="script"}next()})},transformIndexHtml:{order:"pre",handler(c){const shouldWrapEntryHtml=_command==="serve"&&inject==="entry"&&waitsForInit;if(!injectHtml()&&!shouldWrapEntryHtml)return;clientInjected=true;const base=viteConfig.base.replace(/\/$/,"");const stripBase=(p)=>base&&p.startsWith(base+"/")?p.slice(base.length):p;const html=rewriteEntryScripts(c,(originalSrc)=>{const entrySrc=stripBase(originalSrc);addEntryRemoteImports(entrySrc);const resolvedEntrySrc=entrySrc.startsWith("virtual:")?toViteEncodedId(entrySrc):entrySrc;const query=new URLSearchParams({init:sanitizeDevEntryPath(stripBase(devEntryPath)),entry:sanitizeDevEntryPath(resolvedEntrySrc)}).toString();return toViteEncodedId(`${DEV_HTML_PROXY_PREFIX}${query}`)});return html===c?injectEntryScript(c,stripBase(devEntryPath)):html}},resolveId(id){if(normalizeDevHtmlProxyId(id).startsWith(DEV_HTML_PROXY_PREFIX))return id},load(id){const normalizedId=normalizeDevHtmlProxyId(id);if(!normalizedId.startsWith(DEV_HTML_PROXY_PREFIX))return;const params=new URLSearchParams(normalizedId.slice(28));const initSrc=params.get("init");const entrySrc=params.get("entry");if(!initSrc||!entrySrc)return;const source=getBootstrapSource(initSrc,entrySrc);return warmupDevEntryGraph(entrySrc).then(()=>source)},transform(code,id){if(id.includes("node_modules")||inject!=="html"||htmlFilePath)return;if(id.includes(".svelte-kit")&&id.includes("internal.js"))return code.replace(/<head>/g,"<head><script type=\\\"module\\\" src=\\\""+sanitizeDevEntryPath(devEntryPath)+"\\\"></script>")}},{name:"add-entry",enforce:"post",applyToEnvironment(){return true},config(config){patchHashEntryFileNames(config,entryName,fileName)},configResolved(config){viteConfig=config;skipTransformIds=new Set(skipTransformFor.map(resolveProjectId));const clientEnvironmentInputs=[];for(const environment of Object.values(config.environments??{})){if(environment.consumer!=="client")continue;const input=getBuildInput(environment);if(!input){htmlFilePath??=path$14.resolve(config.root,"index.html");continue}if(typeof input==="string")clientEnvironmentInputs.push(input);else if(Array.isArray(input))clientEnvironmentInputs.push(...input);else clientEnvironmentInputs.push(...Object.values(input))}const inputOptions=clientEnvironmentInputs.length>0?clientEnvironmentInputs:getBuildInput(config);if(!inputOptions)htmlFilePath=path$14.resolve(config.root,"index.html");else if(typeof inputOptions==="string")entryFiles=[resolveProjectId(inputOptions)];else if(Array.isArray(inputOptions))entryFiles=inputOptions.filter((input)=>!isReactRouterClientRouteInput(String(input))).map(resolveProjectId);else if(typeof inputOptions==="object")entryFiles=Object.values(inputOptions).filter((input)=>!isReactRouterClientRouteInput(String(input))).map((input)=>resolveProjectId(String(input)));if(entryFiles.length>0)htmlFilePath=getFirstHtmlEntryFile(entryFiles)??htmlFilePath;if(config.command==="serve"&&!htmlFilePath){const rootIndexHtml=path$14.resolve(config.root,"index.html");if(fs$2.existsSync(rootIndexHtml))htmlFilePath=rootIndexHtml}if(htmlFilePath)addHtmlScriptEntries(htmlFilePath)},buildStart(){if(_command==="serve")return;if(skipSvelteKitSsrBuild())return;if(this.environment?.name==="ssr")return;const hasHash=fileName?.includes?.("[hash");const emitFileOptions={name:entryName,type:"chunk",id:getEntryPath(),preserveSignature:"strict"};if(!hasHash)emitFileOptions.fileName=fileName;emitFileId=this.emitFile(emitFileOptions);if(waitsForInit)pendingSharesEmitId=this.emitFile({name:"pendingShares",type:"chunk",id:getPendingSharesPath(federationOptions),preserveSignature:"strict"});if(htmlFilePath)addHtmlScriptEntries(htmlFilePath)},generateBundle(_options,bundle){if(skipSvelteKitSsrBuild())return;if(entryName==="remoteEntry"&&emitFileId&&fileName&&!viteConfig?.build?.ssr&&_options?.format==="es"&&viteConfig?.build?.modulePreload!==false){const remoteEntryFile=findRemoteEntryFile(fileName,bundle);if(remoteEntryFile)appendRemoteEntryWarmup(bundle,remoteEntryFile)}if(!injectHtml())return;if(!emitFileId)return;const htmlFileNames=Object.keys(bundle).filter((fileName)=>fileName.endsWith(".html"));if(htmlFileNames.length===0)return;const file=this.getFileName(emitFileId);emittedFileName=file;const pendingSharesFile=pendingSharesEmitId?this.getFileName(pendingSharesEmitId):undefined;const lastSlash=file.lastIndexOf("/");bootstrapDir=lastSlash!==-1?file.slice(0,lastSlash+1):"";const resolvePath=(builtFileName,htmlFileName)=>{if(!viteConfig.experimental?.renderBuiltUrl)return viteConfig.base+builtFileName;const result=viteConfig.experimental.renderBuiltUrl(builtFileName,{hostId:htmlFileName,hostType:"html",type:"asset",ssr:false});if(typeof result==="string")return result;if(result&&typeof result==="object"){if("runtime"in result){mfWarn('renderBuiltUrl returned runtime code for HTML injection. Runtime code cannot be used in <script src="">. Falling back to base path.');return viteConfig.base+builtFileName}if(result.relative)return builtFileName}return viteConfig.base+builtFileName};const basePrefix=viteConfig.base?.replace(/\/$/,"")??"";const stripBase=(p)=>basePrefix&&p.startsWith(basePrefix+"/")?p.slice(basePrefix.length):p;let bootstrapIndex=0;for(const fileName of htmlFileNames){let htmlAsset=bundle[fileName];if(htmlAsset.type==="chunk")return;let htmlContent=htmlAsset.source.toString()||"";const initPath=resolvePath(file,fileName);const scriptRegex=/<script\b(?=[^>]*\btype=["']module["'])(?=[^>]*\bsrc=["']([^"']+)["'])[^>]*>\s*<\/script>/gi;let rewritten=false;htmlContent=htmlContent.replace(scriptRegex,(scriptTag,entrySrc)=>{if(ignoredHtmlScriptSources.has(entrySrc))return scriptTag;rewritten=true;const strippedInit=stripBase(initPath);const strippedEntry=stripBase(entrySrc);const rebasedInitPath=bootstrapDir?rebaseImport(strippedInit,bootstrapDir):initPath;const rebasedEntrySrc=bootstrapDir?rebaseImport(strippedEntry,bootstrapDir):entrySrc;const pendingSharesPath=pendingSharesFile?resolvePath(pendingSharesFile,fileName):undefined;const bootstrapSource=getSystemBootstrapSource(rebasedInitPath,rebasedEntrySrc,pendingSharesPath&&bootstrapDir?rebaseImport(stripBase(pendingSharesPath),bootstrapDir):pendingSharesPath);const bootstrapHash=createHash5("sha256").update(bootstrapSource).digest("hex").slice(0,8);const bootstrapFileName=`${bootstrapDir}mf-entry-bootstrap-${bootstrapIndex++}-${bootstrapHash}.js`;const bootstrapRef=this.emitFile({type:"asset",fileName:bootstrapFileName,source:bootstrapSource});const bootstrapPath=viteConfig.base+this.getFileName(bootstrapRef);return scriptTag.replace(entrySrc,bootstrapPath)});if(!rewritten){const svelteKitHtml=rewriteSvelteKitInlineStart(htmlContent,initPath);if(svelteKitHtml!==htmlContent)htmlContent=svelteKitHtml;else{const scriptContent=`
|
|
2929
|
+
`)}function getSystemBootstrapSource(initSrc,entrySrc,pendingSharesSrc){return getBootstrapSource(initSrc,entrySrc,true,{pendingSharesSrc})}function injectHtml(){return inject==="html"&&(htmlFilePath||hasPackageDependency("@sveltejs/kit"))}function injectEntry(){if(inject==="html"&&hasPackageDependency("@sveltejs/kit"))return false;return inject==="entry"||!htmlFilePath}function normalizeDevHtmlProxyId(id){return decodeViteId(id).replace(/^\0/,"")}function normalizeModuleId(id){return normalizePathForImport(id.split("?")[0])}function isReactRouterClientEntry(id){const normalized=normalizeModuleId(decodeViteId(id).replace(/^\0+/,""));return/(?:^|\/)entry\.client\.(?:[cm]?[jt]sx?)$/.test(normalized)}function resolveProjectId(id){if(id.startsWith("\x00")||id.startsWith("virtual:"))return normalizeModuleId(id);return normalizeModuleId(path$14.isAbsolute(id)?id:path$14.resolve(viteConfig.root,id))}function isFederationInternalVirtualId(id){const normalized=decodeViteId(id).replace(/^\0+/,"");return normalized.includes("virtual:mf:")||normalized.startsWith("virtual:mf-")||/__(?:loadShare|prebuild|loadRemote)__/.test(normalized)}function isWorkspaceSourceId(id){const normalized=normalizeModuleId(decodeViteId(id));if(normalized.startsWith("\x00")||normalized.startsWith("virtual:"))return false;const filePath=stripQueryAndHash(normalized);if(filePath.startsWith("/@fs/"))return true;if(!path$14.isAbsolute(filePath))return false;const root=normalizePathForImport(path$14.resolve(viteConfig.root));const absolutePath=normalizePathForImport(path$14.resolve(filePath));const relativePath=normalizePathForImport(path$14.relative(root,absolutePath));return(relativePath===".."||relativePath.startsWith("../")||path$14.isAbsolute(relativePath))&&fs$2.existsSync(absolutePath)}function addEntryFile(file){const normalized=normalizeModuleId(file);if(!entryFiles.includes(normalized))entryFiles.push(normalized)}function addHtmlScriptEntries(htmlPath){if(!fs$2.existsSync(htmlPath))return;const htmlContent=fs$2.readFileSync(htmlPath,"utf-8");const scriptRegex=/<script\b(?=[^>]*\btype=["']module["'])(?=[^>]*\bsrc=["']([^"']+)["'])[^>]*>/gi;let match;while((match=scriptRegex.exec(htmlContent))!==null){if(/\svite-ignore(?:\s|=|\/?>)/i.test(match[0])){ignoredHtmlScriptSources.add(match[1]);continue}const scriptSrc=stripQueryAndHash(match[1]);if(/^(?:[a-z]+:)?\/\//i.test(scriptSrc))continue;addEntryFile(scriptSrc);addEntryFile(scriptSrc.startsWith("/")?path$14.resolve(viteConfig.root,scriptSrc.slice(1)):path$14.resolve(path$14.dirname(htmlPath),scriptSrc))}}function addEntryRemoteImports(entrySrc){if(!federationOptions||/^(?:[a-z]+:)?\/\//i.test(entrySrc))return;const file=path$14.resolve(viteConfig.root,stripQueryAndHash(entrySrc).replace(/^\//,""));if(!fs$2.existsSync(file))return;const code=fs$2.readFileSync(file,"utf-8");for(const source of findModuleImportSources(code)){const remote=Object.keys(federationOptions.remotes).find((name)=>source===name||source.startsWith(`${name}/`));if(remote)addUsedRemote(remote,source,federationOptions)}}return[{name:"add-entry",apply:"serve",config(_config,{command}){_command=command;const isRemoteEntry=entryName==="remoteEntry"&&federationOptions!==undefined&&isRemoteContainer(federationOptions);if(command==="serve"&&_config.experimental?.bundledDev&&isRemoteEntry){_config.experimental={..._config.experimental,bundledDev:false};_config.environments??={};_config.environments.client??={};if(_config.environments.client.isBundled!==false){_config.environments.client.isBundled=false;mfWarn("Vite bundledDev is disabled for the client environment of a Module Federation remote container so its remoteEntry keeps the standard init/get contract.")}}},configResolved(config){viteConfig=config;const resolvedEntryPath=getEntryPath();if(resolvedEntryPath.startsWith("virtual:mf"))devEntryPath=config.base+VITE_ID_PREFIX.slice(1)+resolvedEntryPath;else{const normalized=normalizePathForImport(resolvedEntryPath);const root=normalizePathForImport(config.root).replace(/\/$/,"");const relativePath=normalized.startsWith(root+"/")?normalized.slice(root.length):"/"+normalized.replace(/^[A-Za-z]:[\\/]/,"");devEntryPath=config.base+relativePath.replace(/^\//,"")}skipTransformIds=new Set(skipTransformFor.map(resolveProjectId))},configureServer(server){devServer=server;server.middlewares.use((req,res,next)=>{const rawUrl=req.url?.split("#")[0]??"";if(normalizeDevHtmlProxyId(rawUrl.split("?")[0])===DEV_HTML_PROXY_PREFIX.slice(0,-1)){const query=rawUrl.slice(rawUrl.indexOf("?")+1);const params=new URLSearchParams(query);const initSrc=params.get("init");const entrySrc=params.get("entry");if(initSrc&&entrySrc){const withBase=(src)=>viteConfig.base+src.replace(/^\//,"");const source=getBootstrapSource(withBase(initSrc),withBase(entrySrc));warmupDevEntryGraph(entrySrc).finally(()=>{res.statusCode=200;res.setHeader("Content-Type","application/javascript");res.end(source)});return}}if(!fileName){next();return}const devFileName=resolveHashPlaceholderFileName(fileName);if(devFileName!==fileName&&req.url?.startsWith((viteConfig.base+devFileName).replace(/^\/?/,"/")))req.url=req.url.replace(devFileName,fileName);if(req.url&&req.url.startsWith((viteConfig.base+fileName).replace(/^\/?/,"/"))){req.url=devEntryPath;req.headers["sec-fetch-dest"]="script"}next()})},transformIndexHtml:{order:"pre",handler(c){const shouldWrapEntryHtml=_command==="serve"&&inject==="entry"&&waitsForInit;if(!injectHtml()&&!shouldWrapEntryHtml)return;clientInjected=true;const base=viteConfig.base.replace(/\/$/,"");const stripBase=(p)=>base&&p.startsWith(base+"/")?p.slice(base.length):p;const html=rewriteEntryScripts(c,(originalSrc)=>{const entrySrc=stripBase(originalSrc);addEntryRemoteImports(entrySrc);const resolvedEntrySrc=entrySrc.startsWith("virtual:")?toViteEncodedId(entrySrc):entrySrc;const query=new URLSearchParams({init:sanitizeDevEntryPath(stripBase(devEntryPath)),entry:sanitizeDevEntryPath(resolvedEntrySrc)}).toString();return toViteEncodedId(`${DEV_HTML_PROXY_PREFIX}${query}`)});return html===c?injectEntryScript(c,stripBase(devEntryPath)):html}},resolveId(id){if(normalizeDevHtmlProxyId(id).startsWith(DEV_HTML_PROXY_PREFIX))return id},load(id){const normalizedId=normalizeDevHtmlProxyId(id);if(!normalizedId.startsWith(DEV_HTML_PROXY_PREFIX))return;const params=new URLSearchParams(normalizedId.slice(28));const initSrc=params.get("init");const entrySrc=params.get("entry");if(!initSrc||!entrySrc)return;const source=getBootstrapSource(initSrc,entrySrc);return warmupDevEntryGraph(entrySrc).then(()=>source)},transform(code,id){if(id.includes("node_modules")||inject!=="html"||htmlFilePath)return;if(id.includes(".svelte-kit")&&id.includes("internal.js"))return code.replace(/<head>/g,"<head><script type=\\\"module\\\" src=\\\""+sanitizeDevEntryPath(devEntryPath)+"\\\"></script>")}},{name:"add-entry",enforce:"post",applyToEnvironment(){return true},config(config){patchHashEntryFileNames(config,entryName,fileName)},configResolved(config){viteConfig=config;skipTransformIds=new Set(skipTransformFor.map(resolveProjectId));const clientEnvironmentInputs=[];for(const environment of Object.values(config.environments??{})){if(environment.consumer!=="client")continue;const input=getBuildInput(environment);if(!input){htmlFilePath??=path$14.resolve(config.root,"index.html");continue}if(typeof input==="string")clientEnvironmentInputs.push(input);else if(Array.isArray(input))clientEnvironmentInputs.push(...input);else clientEnvironmentInputs.push(...Object.values(input))}const inputOptions=clientEnvironmentInputs.length>0?clientEnvironmentInputs:getBuildInput(config);if(!inputOptions)htmlFilePath=path$14.resolve(config.root,"index.html");else if(typeof inputOptions==="string")entryFiles=[resolveProjectId(inputOptions)];else if(Array.isArray(inputOptions))entryFiles=inputOptions.filter((input)=>!isReactRouterClientRouteInput(String(input))).map(resolveProjectId);else if(typeof inputOptions==="object")entryFiles=Object.values(inputOptions).filter((input)=>!isReactRouterClientRouteInput(String(input))).map((input)=>resolveProjectId(String(input)));if(entryFiles.length>0)htmlFilePath=getFirstHtmlEntryFile(entryFiles)??htmlFilePath;if(config.command==="serve"&&!htmlFilePath){const rootIndexHtml=path$14.resolve(config.root,"index.html");if(fs$2.existsSync(rootIndexHtml))htmlFilePath=rootIndexHtml}if(htmlFilePath)addHtmlScriptEntries(htmlFilePath)},buildStart(){if(_command==="serve")return;if(skipSvelteKitSsrBuild())return;if(this.environment?.name==="ssr")return;const hasHash=fileName?.includes?.("[hash");const emitFileOptions={name:entryName,type:"chunk",id:getEntryPath(),preserveSignature:"strict"};if(!hasHash)emitFileOptions.fileName=fileName;emitFileId=this.emitFile(emitFileOptions);if(waitsForInit)pendingSharesEmitId=this.emitFile({name:"pendingShares",type:"chunk",id:getPendingSharesPath(federationOptions),preserveSignature:"strict"});if(htmlFilePath)addHtmlScriptEntries(htmlFilePath)},generateBundle(_options,bundle){if(skipSvelteKitSsrBuild())return;if(entryName==="remoteEntry"&&emitFileId&&fileName&&!viteConfig?.build?.ssr&&_options?.format==="es"&&viteConfig?.build?.modulePreload!==false){const remoteEntryFile=findRemoteEntryFile(fileName,bundle);if(remoteEntryFile)appendRemoteEntryWarmup(bundle,remoteEntryFile)}if(!injectHtml())return;if(!emitFileId)return;const htmlFileNames=Object.keys(bundle).filter((fileName)=>fileName.endsWith(".html"));if(htmlFileNames.length===0)return;const file=this.getFileName(emitFileId);emittedFileName=file;const pendingSharesFile=pendingSharesEmitId?this.getFileName(pendingSharesEmitId):undefined;const lastSlash=file.lastIndexOf("/");bootstrapDir=lastSlash!==-1?file.slice(0,lastSlash+1):"";const resolvePath=(builtFileName,htmlFileName)=>{if(!viteConfig.experimental?.renderBuiltUrl)return viteConfig.base+builtFileName;const result=viteConfig.experimental.renderBuiltUrl(builtFileName,{hostId:htmlFileName,hostType:"html",type:"asset",ssr:false});if(typeof result==="string")return result;if(result&&typeof result==="object"){if("runtime"in result){mfWarn('renderBuiltUrl returned runtime code for HTML injection. Runtime code cannot be used in <script src="">. Falling back to base path.');return viteConfig.base+builtFileName}if(result.relative)return builtFileName}return viteConfig.base+builtFileName};const basePrefix=viteConfig.base?.replace(/\/$/,"")??"";const stripBase=(p)=>basePrefix&&p.startsWith(basePrefix+"/")?p.slice(basePrefix.length):p;let bootstrapIndex=0;for(const fileName of htmlFileNames){let htmlAsset=bundle[fileName];if(htmlAsset.type==="chunk")return;let htmlContent=htmlAsset.source.toString()||"";const initPath=resolvePath(file,fileName);const scriptRegex=/<script\b(?=[^>]*\btype=["']module["'])(?=[^>]*\bsrc=["']([^"']+)["'])[^>]*>\s*<\/script>/gi;let rewritten=false;htmlContent=htmlContent.replace(scriptRegex,(scriptTag,entrySrc)=>{if(ignoredHtmlScriptSources.has(entrySrc))return scriptTag;rewritten=true;const strippedInit=stripBase(initPath);const strippedEntry=stripBase(entrySrc);const rebasedInitPath=bootstrapDir?rebaseImport(strippedInit,bootstrapDir):initPath;const rebasedEntrySrc=bootstrapDir?rebaseImport(strippedEntry,bootstrapDir):entrySrc;const pendingSharesPath=pendingSharesFile?resolvePath(pendingSharesFile,fileName):undefined;const bootstrapSource=getSystemBootstrapSource(rebasedInitPath,rebasedEntrySrc,pendingSharesPath&&bootstrapDir?rebaseImport(stripBase(pendingSharesPath),bootstrapDir):pendingSharesPath);const bootstrapHash=createHash6("sha256").update(bootstrapSource).digest("hex").slice(0,8);const bootstrapFileName=`${bootstrapDir}mf-entry-bootstrap-${bootstrapIndex++}-${bootstrapHash}.js`;const bootstrapRef=this.emitFile({type:"asset",fileName:bootstrapFileName,source:bootstrapSource});const bootstrapPath=viteConfig.base+this.getFileName(bootstrapRef);return scriptTag.replace(entrySrc,bootstrapPath)});if(!rewritten){const svelteKitHtml=rewriteSvelteKitInlineStart(htmlContent,initPath);if(svelteKitHtml!==htmlContent)htmlContent=svelteKitHtml;else{const scriptContent=`
|
|
2929
2930
|
<script type="module" src="${initPath}"></script>
|
|
2930
2931
|
`;htmlContent=htmlContent.replace("<head>",`<head>${scriptContent}`)}}if(waitsForInit&&viteConfig.build.modulePreload!==false)htmlContent=injectHostInitPreloads(htmlContent,bundle,(builtFileName)=>resolvePath(builtFileName,fileName),getRemoteEntryPreloadUrls());htmlAsset.source=htmlContent}},closeBundle(){if(_command==="serve"||!hasPackageDependency("@sveltejs/kit")||skipSvelteKitSsrBuild())return;let attempts=0;const retry=()=>{attempts+=1;if(!patchSvelteKitStaticHtml()&&attempts<20)setTimeout(retry,50)};setTimeout(retry,0)},transform(code,id){if(skipSvelteKitSsrBuild())return;if(viteConfig?.command==="build"&&!waitsForInit)return;if(isSvelteKitServerModule(id))return;if(hasEntryBootstrapParam(id))return;if(normalizeModuleId(id).endsWith(".html"))return;const projectId=resolveProjectId(id);if(skipTransformIds.has(projectId))return;if(!isClientEnvironment(this))return;const isVinext=hasPackageDependency("vinext");if(isVinext&&inject==="html"&&id.includes("virtual:vite-rsc/remove-duplicate-server-css")){const namespaceReactImport=`import * as React from 'react';`;if(code.includes(namespaceReactImport))return;const rewritten=code.replace(/import\s+React\s+from\s+['"]react['"];?/,namespaceReactImport);return rewritten===code?undefined:mapCodeToCodeWithSourcemap(rewritten)}if(isVinext&&inject==="html"&&(id.includes("virtual:vite-rsc/entry-browser")||id.includes("virtual:vinext-app-browser-entry"))){const injection=`import ${JSON.stringify(getEntryPath())};
|
|
2931
2932
|
`;if(code.includes(injection.trim())){clientInjected=true;return}clientInjected=true;return mapCodeToCodeWithSourcemap(injection+code)}if(_command==="serve"&&inject==="entry"&&waitsForInit&&!clientInjected&&/(?:^|\/)nuxt\/dist\/app\/entry\.js(?:\?|$)/.test(id)&&code.includes("vueApp.mount(vueAppRootContainer);")){clientInjected=true;const injection=`await import(${JSON.stringify(getEntryPath())}).then(({ initHost }) => initHost());
|
|
@@ -3192,12 +3193,12 @@ window.$RefreshReg$ = () => {};
|
|
|
3192
3193
|
window.$RefreshSig$ = () => (type) => type;`;var getPreambleCode=(base)=>preambleCode.replace("__BASE__",base);function virtualPreamblePlugin({name,isEnabled}){return{name:"vite:react-virtual-preamble",resolveId:{order:"pre",filter:{id:exactRegex(name)},handler(source){if(source===name)return"\x00"+source}},load:{filter:{id:exactRegex("\x00"+name)},handler(id){if(id==="\x00"+name){if(isEnabled())return preambleCode.replace("__BASE__","/");return""}}}}}var silenceUseClientWarning=(userConfig)=>({rollupOptions:{onwarn(warning,defaultHandler){if(warning.code==="MODULE_LEVEL_DIRECTIVE"&&(warning.message.includes("use client")||warning.message.includes("use server")))return;if(warning.code==="SOURCEMAP_ERROR"&&warning.message.includes("resolve original location")&&warning.pos===0)return;if(userConfig.build?.rollupOptions?.onwarn)userConfig.build.rollupOptions.onwarn(warning,defaultHandler);else defaultHandler(warning)}}});var defaultCodeFilter=/forwardRef|memo|\b(?:[A-Z]|use[A-Z0-9])/;var reactCompilerPreset=(options={})=>({preset:()=>({plugins:[[fileURLToPath11(import.meta.resolve("babel-plugin-react-compiler")),options]]}),rolldown:{filter:{code:options.compilationMode==="annotation"?/['"]use memo['"]/:defaultCodeFilter},applyToEnvironmentHook:(env)=>env.config.consumer==="client",optimizeDeps:{include:options.target==="17"||options.target==="18"?["react-compiler-runtime"]:["react/compiler-runtime"]}}});var refreshRuntimePath=join6(dirname5(fileURLToPath11(import.meta.url)),"refresh-runtime.js");var defaultIncludeRE=/\.[tj]sx?$/;var defaultExcludeRE=/\/node_modules\//;function viteReact(opts={}){const include=opts.include??defaultIncludeRE;const exclude=opts.exclude??defaultExcludeRE;const jsxImportSource=opts.jsxImportSource??"react";const jsxImportRuntime=`${jsxImportSource}/jsx-runtime`;const jsxImportDevRuntime=`${jsxImportSource}/jsx-dev-runtime`;let runningInVite=false;let skipFastRefresh=true;let base;let isBundledDev=false;function calculateSkipFastRefresh(isProduction,command,hmr){return isProduction||command==="build"||hmr===false}const viteBabel={name:"vite:react-babel",enforce:"pre",config(_userConfig,{command}){if(opts.jsxRuntime==="classic")return{oxc:{jsx:{runtime:"classic",refresh:command==="serve"},jsxRefreshInclude:makeIdFiltersToMatchWithQuery(include),jsxRefreshExclude:makeIdFiltersToMatchWithQuery(exclude)}};else return{oxc:{jsx:{runtime:"automatic",importSource:opts.jsxImportSource,refresh:command==="serve"},jsxRefreshInclude:makeIdFiltersToMatchWithQuery(include),jsxRefreshExclude:makeIdFiltersToMatchWithQuery(exclude)},optimizeDeps:{rolldownOptions:{transform:{jsx:{runtime:"automatic"}}}}}},configResolved(config){runningInVite=true;base=config.base;if(config.experimental.bundledDev)isBundledDev=true;if(skipFastRefresh!==calculateSkipFastRefresh(config.isProduction,config.command,config.server?.hmr))this.warn(`NODE_ENV (${JSON.stringify("development")}) or server.hmr was changed by plugins after the react plugin read the config. This may cause unexpected behavior.`)},options(options){if(!runningInVite){options.transform??={};options.transform.jsx={runtime:opts.jsxRuntime,importSource:opts.jsxImportSource};return options}}};const viteRefreshWrapper={name:"vite:react:refresh-wrapper",apply:"serve",async applyToEnvironment(env){if(env.config.consumer!=="client"||skipFastRefresh)return false;return reactRefreshWrapperPlugin({cwd:process.cwd(),include:makeIdFiltersToMatchWithQuery(include),exclude:makeIdFiltersToMatchWithQuery(exclude),jsxImportSource,reactRefreshHost:opts.reactRefreshHost??""})}};const viteConfigPost={name:"vite:react:config-post",enforce:"post",config(userConfig,{command}){skipFastRefresh=calculateSkipFastRefresh(false,command,userConfig.server?.hmr);if(skipFastRefresh)return{oxc:{jsx:{refresh:false}}}}};const viteReactRefreshBundledDevMode={name:"vite:react-refresh-fbm",enforce:"pre",transformIndexHtml:{handler(){if(!skipFastRefresh&&isBundledDev)return[{tag:"script",attrs:{type:"module"},children:getPreambleCode("/")}]},order:"pre"}};const dependencies=["react","react-dom",jsxImportDevRuntime,jsxImportRuntime];return[viteBabel,viteRefreshWrapper,viteConfigPost,viteReactRefreshBundledDevMode,{name:"vite:react-refresh",enforce:"pre",config:(userConfig)=>({build:silenceUseClientWarning(userConfig),optimizeDeps:{include:dependencies}}),resolveId:{filter:{id:exactRegex(runtimePublicPath)},handler(id){if(id==="/@react-refresh")return id}},load:{filter:{id:exactRegex(runtimePublicPath)},handler(id){if(id==="/@react-refresh")return readFileSync7(refreshRuntimePath,"utf-8").replace(/__README_URL__/g,"https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react")}},transformIndexHtml(){if(!skipFastRefresh&&!isBundledDev)return[{tag:"script",attrs:{type:"module"},children:getPreambleCode(base)}]}},virtualPreamblePlugin({name:"@vitejs/plugin-react/preamble",isEnabled:()=>!skipFastRefresh&&!isBundledDev})]}viteReact.preambleCode=preambleCode;function viteReactForCjs(options){return viteReact.call(this,options)}Object.assign(viteReactForCjs,{default:viteReactForCjs,reactCompilerPreset});import{tmpdir as tmpdir2}from"os";import{fileURLToPath as fileURLToPath12}from"url";import{createServer as createServer3}from"vite";var path10=runSync2(provide3(Path2,layer3));var runNested2=runPromiseWith2(empty());var makeTempDirectory2=flow((prefix)=>gen2(function*makeDirectory(){const fileSystem=yield*FileSystem;return yield*fileSystem.makeTempDirectory({directory:tmpdir2(),prefix})}).pipe(provide3(layer2)),runPromise2);var removeTempDirectory=flow((directory)=>gen2(function*removeTempDirectoryEffect(){const fileSystem=yield*FileSystem;yield*fileSystem.remove(directory,{force:true,recursive:true})}).pipe(provide3(layer2)),runPromise2);var declarationImport=(specifier)=>specifier.startsWith("file:")?fileURLToPath12(specifier):specifier;var moduleExport3=(exportName)=>{if(!/^[$A-Z_a-z][$\w]*$/u.test(exportName)){throw new TypeError(`Hosted Contribution export '${exportName}' is not a JavaScript identifier`)}return exportName};var virtualModuleSource=(input)=>`
|
|
3193
3194
|
import * as loaded from ${JSON.stringify(input.contributionImport)}
|
|
3194
3195
|
export const ${moduleExport3(input.exportName)} = loaded[${JSON.stringify(input.exportName)}]
|
|
3195
|
-
`;var contributionKey2=(input)=>JSON.stringify([input.packageFqn,input.contributionHost,input.contributionFqn]);var exposedModule=(key)=>`./${key}`;var randomUuid2=()=>{const bytes=new Uint8Array(16);crypto.getRandomValues(bytes);bytes[6]=bytes[6]%16+64;bytes[8]=bytes[8]%64+128;const hex=[...bytes].map((byte)=>byte.toString(16).padStart(2,"0"));return`${hex.slice(0,4).join("")}-${hex.slice(4,6).join("")}-${hex.slice(6,8).join("")}-${hex.slice(8,10).join("")}-${hex.slice(10).join("")}`};var authorizationPlugin=(input)=>({configureServer(server){server.middlewares.use((request,response,next)=>{const{origin}=request.headers;const{pathname}=new URL(request.url??"/","http://127.0.0.1");const authorized=origin===undefined?pathname.startsWith(input.capabilityBase):input.attachedOrigins.has(origin);if(!authorized){response.writeHead(403,{"content-type":"text/plain"});response.end("Host origin is not attached");return}if(origin!==undefined){response.setHeader("access-control-allow-origin",origin)}response.setHeader("cache-control","no-store");next()})},enforce:"pre",name:"ci-hosted-development-authorization"});var startViteDevelopmentAssetServer=flow((input)=>gen2(function*startAssetServer(){const capability=randomUuid2().replaceAll("-","");const capabilityPath=`__ci_capability__/${capability}/`;const capabilityBase=`/${capabilityPath}`;const attachedOrigins=new Set(input.hostOrigins);const frontendCacheDirectory=yield*promise2(()=>makeTempDirectory2("ci-hosted-vite-"));let frontendEntries=new Map;let frontendServer;let frontendServerPort;const warmFrontendServer=flow((server)=>gen2(function*warmServer(){yield*promise2(()=>server.warmupRequest(`${capabilityBase}remoteEntry.js`));yield*promise2(()=>server.waitForRequestsIdle())}),runNested2);const startFrontendServer=flow((entries,port)=>gen2(function*startFrontendServerEffect(){const exposes=Object.fromEntries([...entries.keys()].map((key)=>[exposedModule(key),`virtual:ci-hosted:${encodeURIComponent(key)}`]));const virtualPrefix="\x00virtual:ci-hosted:";const virtualEntries={load(id){return id.startsWith(virtualPrefix)?entries.get(decodeURIComponent(id.slice(virtualPrefix.length)))?.source??null:null},name:"ci-hosted-development-entries",resolveId(id){return id.startsWith("virtual:ci-hosted:")?`\x00${id}`:null}};const shared=Object.fromEntries(frontendHostProvidedModules.map((moduleName)=>[moduleName,{import:false,singleton:true,suppressMissingImportWarning:true}]));const declarationPath=declarationImport(input.declarationSpecifier);const root=path10.isAbsolute(declarationPath)?path10.dirname(declarationPath):process.cwd();const server=yield*promise2(()=>createServer3({base:capabilityBase,cacheDir:frontendCacheDirectory,configFile:false,logLevel:"silent",optimizeDeps:{entries:[...entries.values()].map((entry)=>entry.importPath),exclude:[...frontendHostProvidedModules]},plugins:[authorizationPlugin({attachedOrigins,capabilityBase}),viteReact(),virtualEntries,federation({dev:{remoteHmr:true},dts:false,exposes,filename:"remoteEntry.js",manifest:false,moduleParseIdleTimeout:1,name:`ci_hosted_${capability}`,shared})],resolve:workspaceSourceResolve(process.execArgv),root,server:{cors:false,headers:{"cache-control":"no-store"},host:"127.0.0.1",port,strictPort:port!==0},ssr:workspaceSourceSsrResolve(process.execArgv)}));yield*promise2(()=>server.listen());yield*promise2(()=>warmFrontendServer(server));return server}),runNested2);const synchronizeFrontendServer=flow((entries)=>gen2(function*synchronizeServer(){const previousKeys=[...frontendEntries.keys()].toSorted();const nextKeys=[...entries.keys()].toSorted();if(previousKeys.length===nextKeys.length&&previousKeys.every((key,index)=>key===nextKeys[index]&&frontendEntries.get(key)?.importPath===entries.get(key)?.importPath)){frontendEntries.clear();for(const[key,source]of entries){frontendEntries.set(key,source)}frontendServer?.moduleGraph.invalidateAll();const server=frontendServer;if(server!==undefined){yield*promise2(()=>warmFrontendServer(server))}return yield*void_3}const previousServer=frontendServer;const port=frontendServerPort??0;frontendServer=undefined;if(previousServer!==undefined){yield*promise2(()=>previousServer.close())}frontendEntries=entries;if(entries.size===0){frontendServerPort=undefined;return yield*void_3}const server=yield*promise2(()=>startFrontendServer(entries,port));frontendServer=server;const localUrl=server.resolvedUrls?.local.at(0);if(localUrl===undefined){yield*promise2(()=>server.close());frontendServer=undefined;throw new Error("Vite did not publish a loopback development URL")}frontendServerPort=Number(new URL(localUrl).port);return yield*void_3}),runNested2);const rebuild=flow((declarations)=>gen2(function*rebuildServer(){const nextFrontendEntries=new Map;for(const definition of declarations){for(const contribution of definition.hostedContributions){if(contribution.manifest.host==="backend"){continue}const key=contributionKey2({contributionFqn:contribution.manifest.fqn,contributionHost:contribution.manifest.host,packageFqn:definition.manifest.fqn});const importPath=resolveHostedContributionEntry(input.declarationSpecifier,{fqn:contribution.manifest.fqn,load:contribution.load});const source=virtualModuleSource({contributionImport:importPath,exportName:contribution.manifest.exportName});nextFrontendEntries.set(key,{importPath,source})}}yield*promise2(()=>synchronizeFrontendServer(nextFrontendEntries))}),runNested2);yield*promise2(()=>rebuild(input.declarations)).pipe(tapError2(()=>promise2(()=>frontendServer?.close().then(()=>null).catch(()=>null)??Promise.resolve(null)).pipe(andThen2(()=>promise2(()=>removeTempDirectory(frontendCacheDirectory))))));return{assetsFor:flow((definition)=>sync2(()=>definition.hostedContributions.flatMap(({manifest})=>{if(manifest.host==="backend"){return[]}const key=contributionKey2({contributionFqn:manifest.fqn,contributionHost:manifest.host,packageFqn:definition.manifest.fqn});const localUrl=frontendServer?.resolvedUrls?.local.at(0);if(localUrl===undefined){throw new Error(`Vite federation remote was not started for ${manifest.fqn}`)}const moduleUrl=new URL("remoteEntry.js",localUrl);moduleUrl.hash=encodeURIComponent(exposedModule(key));return{...manifest.compatibility===undefined?undefined:{compatibility:manifest.compatibility},contract:manifest.contract,exportName:manifest.exportName,fqn:manifest.fqn,host:manifest.host,moduleUrl:moduleUrl.href}})),runNested2),close:flow(()=>gen2(function*closeServer(){const server=frontendServer;if(server!==undefined){yield*promise2(()=>server.close())}yield*promise2(()=>removeTempDirectory(frontendCacheDirectory))}),runPromiseWith2(empty())),rebuild}}),runPromise2);class PackageDiagnosticsCommandError extends TaggedError3()("PackageDiagnosticsCommandError",{cause:optional2(Unknown2),message:String4}){}var requireOption3=(options,name)=>{const value=options.get(name);if(value===undefined||value===""){throw new PackageDiagnosticsCommandError({message:`Missing required option --${name}`})}return value};var parseOptions3=(args)=>{const options=new Map;for(let index=1;index<args.length;index+=2){const flag=args[index];const value=args[index+1];if(!flag?.startsWith("--")||!value||value.startsWith("--")){throw new PackageDiagnosticsCommandError({message:"Options must be supplied as --name value pairs"})}options.set(flag.slice(2),value)}return options};var packageDiagnosticsCommandEffect=(args,dependencies)=>{const[command]=args;if(command!=="trace"){return fail6(new PackageDiagnosticsCommandError({message:"Expected package diagnostics command: trace"}))}return try_2({catch:(cause)=>is2(PackageDiagnosticsCommandError)(cause)?cause:new PackageDiagnosticsCommandError({cause,message:"Could not configure package diagnostics command"}),try:()=>parseOptions3(args)}).pipe(flatMap3((options)=>tryPromise2({catch:(cause)=>new PackageDiagnosticsCommandError({cause,message:"Could not read hosted Extension diagnostic trace"}),try:async()=>{const response=await hostedExtensionDiagnosticsReadTrace({client:dependencies.client,headers:{"x-organization-id":requireOption3(options,"organization")},path:{diagnosticId:requireOption3(options,"diagnostic")},throwOnError:true});return response.data}})))};import{createHash as createHash6}from"crypto";var awaitValue7=(value)=>promise2(constant(Promise.resolve(value)));var path11=runSync2(provide3(Path2,layer5));var readBytesEffect=(readBytes,filePath)=>tryPromise2(flow(()=>suspend2(()=>awaitValue7(readBytes(filePath))),runPromise2));class PackageReleaseCommandError extends TaggedError3()("PackageReleaseCommandError",{cause:optional2(Unknown2),message:String4}){}var requireOption4=(options,name)=>{const value=options.get(name);if(value===undefined||value===""){throw new PackageReleaseCommandError({message:`Missing required option --${name}`})}return value};var supportedOptions=new Set(["archive","backend-url","bundle","idempotency-key","installation","manifest","organization","package","package-manifest","private-maps","release","scope","setup-file","version"]);var parseOptions4=(args)=>{const options=new Map;for(let index=1;index<args.length;index+=2){const flag=args[index];const value=args[index+1];if(!flag?.startsWith("--")||!value||value.startsWith("--")){throw new PackageReleaseCommandError({message:"Options must be supplied as --name value pairs"})}if(!supportedOptions.has(flag.slice(2))){throw new PackageReleaseCommandError({message:`Unknown option ${flag}`})}options.set(flag.slice(2),value)}return options};var idempotencyHeaders=(options)=>({"idempotency-key":requireOption4(options,"idempotency-key")});var administratorHeaders=(options)=>({...idempotencyHeaders(options),"x-organization-id":requireOption4(options,"organization")});var rejectRetiredPublishOptions=(options)=>{if(options.has("scope")){throw new PackageReleaseCommandError({message:"--scope is no longer supported; publisher credential scope is authoritative"})}if(options.has("organization")){throw new PackageReleaseCommandError({message:"--organization is no longer supported; publisher credential scope is authoritative"})}if(options.has("package")||options.has("version")){throw new PackageReleaseCommandError({message:"--package and --version are no longer supported; the authoritative release manifest supplies both"})}if(options.has("bundle")){throw new PackageReleaseCommandError({message:"--bundle is no longer supported for publication; use the verified --archive release artifact"})}};var digest3=(bytes)=>createHash6("sha256").update(bytes).digest("hex");var executePublish=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not publish package release"}),try:async()=>{rejectRetiredPublishOptions(options);const archiveBytes=await dependencies.readBytes(requireOption4(options,"archive"));const manifestPath=requireOption4(options,"manifest");const manifestBytes=await dependencies.readBytes(manifestPath);const packageManifestBytes=await dependencies.readBytes(requireOption4(options,"package-manifest"));const privateMapDirectory=options.has("private-maps")?requireOption4(options,"private-maps"):path11.join(path11.dirname(manifestPath),"private-source-maps");const privateMapFiles=await dependencies.listFiles(privateMapDirectory);const privateSourceMaps=await Promise.all(privateMapFiles.toSorted(compareCanonicalText).map(flow((fileName)=>gen2(function*readPrivateSourceMap(){if(!/^[\da-f]{64}\.map$/u.test(fileName)){return yield*new PackageReleaseCommandError({message:`Private source-map file '${fileName}' is not keyed by a runtime asset digest`})}const bytes=yield*readBytesEffect(dependencies.readBytes,path11.join(privateMapDirectory,fileName));return{bytes,digest:digest3(bytes),runtimeAssetDigest:fileName.slice(0,-4),size:bytes.byteLength}}),runPromise2)));const body=await preparePackagePublication({archiveBytes,manifestBytes,packageManifestBytes,privateSourceMaps});const accepted=await publishPackage({body,client:dependencies.client,idempotencyKey:requireOption4(options,"idempotency-key")});return accepted.operationId}});var executePromote=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not promote package release"}),try:async()=>{const body={protocolVersion:"v1",releaseId:requireOption4(options,"release")};const accepted=await promotePackage({body,client:dependencies.client,idempotencyKey:requireOption4(options,"idempotency-key")});return accepted.operationId}});var executeUpdate=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not update package installation"}),try:async()=>{const setupFile=options.get("setup-file");const setup=setupFile===undefined?undefined:await readConnectorSetup(setupFile,dependencies.readBytes);const body={...setup===undefined?undefined:{setup},installationId:requireOption4(options,"installation"),protocolVersion:"v1",releaseId:requireOption4(options,"release")};const accepted=await updatePackage({body,client:dependencies.client,idempotencyKey:requireOption4(options,"idempotency-key"),organizationId:requireOption4(options,"organization")});return accepted.operationId}});var executeInstall=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not install package"}),try:async()=>{const releaseId=options.get("release");const setupFile=options.get("setup-file");const setup=setupFile===undefined?undefined:await readConnectorSetup(setupFile,dependencies.readBytes);const accepted=await installPackage({...releaseId===undefined&&setup===undefined?undefined:{body:{...releaseId===undefined?undefined:{releaseId},...setup===undefined?undefined:{setup}}},client:dependencies.client,idempotencyKey:requireOption4(options,"idempotency-key"),organizationId:requireOption4(options,"organization"),packageFqn:requireOption4(options,"package")});return accepted.operationId}});var executeSync=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not sync package"}),try:async()=>{if(options.has("release")){throw new PackageReleaseCommandError({message:"package sync re-applies the current release and does not accept --release; use package update --release for an exact release"})}const accepted=await extensionPackagesSync({client:dependencies.client,headers:administratorHeaders(options),path:{fqn:requireOption4(options,"package")},throwOnError:true});return accepted.data.operationId}});var executeRollback=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not roll back package installation"}),try:async()=>{const accepted=await packageReleasesRollbackInstallation({body:{installationId:requireOption4(options,"installation"),protocolVersion:"v1",releaseId:requireOption4(options,"release")},client:dependencies.client,headers:administratorHeaders(options),throwOnError:true});return accepted.data.operationId}});var packageReleaseCommandEffect=(args,dependencies)=>{const[command]=args;const options=parseOptions4(args);if(options.has("setup-file")&&command!=="install"&&command!=="update"){return fail6(new PackageReleaseCommandError({message:"--setup-file is supported only for package install/update"}))}switch(command){case"install":{return executeInstall(options,dependencies)}case"publish":{return executePublish(options,dependencies)}case"promote":{return executePromote(options,dependencies)}case"rollback":{return executeRollback(options,dependencies)}case"sync":{return executeSync(options,dependencies)}case"update":{return executeUpdate(options,dependencies)}default:{return fail6(new PackageReleaseCommandError({message:"Expected one of: package publish, package promote, package install, package update, package sync, package rollback"}))}}};class PackageReleasesCommandError extends TaggedError3()("PackageReleasesCommandError",{cause:optional2(Unknown2),message:String4}){}var requireOption5=(options,name)=>{const value=options.get(name);if(value===undefined||value===""){throw new PackageReleasesCommandError({message:`Missing required option --${name}`})}return value};var parseOptions5=(args)=>{const options=new Map;for(let index=0;index<args.length;index+=2){const flag=args[index];const value=args[index+1];if(!flag?.startsWith("--")||!value||value.startsWith("--")){throw new PackageReleasesCommandError({message:"Options must be supplied as --name value pairs"})}options.set(flag.slice(2),value)}return options};var packageReleasesCommandEffect=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleasesCommandError)(cause)?cause:new PackageReleasesCommandError({cause,message:"Could not list package releases"}),try:async()=>{const parsed=parseOptions5(options);const response=await extensionPackagesListReleases({client:dependencies.client,headers:{"x-organization-id":requireOption5(parsed,"organization")},path:{fqn:requireOption5(parsed,"package")},throwOnError:true});return response.data}});import path12 from"path";class UpgradeCommandError extends TaggedError3()("UpgradeCommandError",{cause:optional2(Unknown2),message:String4}){}var registryUrl="https://registry.npmjs.org";var registryTimeout="30 seconds";var RegistryVersion=Struct({version:String4});var packageManagers=[{globalRoot:["npm","root","-g"],install:["npm","install","-g","--prefer-online"]},{globalRoot:["pnpm","root","-g"],install:["pnpm","add","-g"]}];var bunInstall=["bun","add","-g"];var bunGlobalRoot="/install/global/node_modules/";var latestVersion=(fetch2,name)=>tryPromise2({catch:(cause)=>new UpgradeCommandError({cause,message:`Could not reach ${registryUrl} to read the latest ci version`}),try:async(signal)=>{const response=await fetch2(`${registryUrl}/${name}/latest`,{headers:{accept:"application/json"},signal});return response.ok?await response.json():undefined}}).pipe(timeoutOrElse2({duration:registryTimeout,orElse:()=>fail6(new UpgradeCommandError({message:`${registryUrl} did not respond within ${registryTimeout}`}))}),flatMap3((body)=>is2(RegistryVersion)(body)?succeed6(body.version):fail6(new UpgradeCommandError({message:`${registryUrl} did not return the latest ci version`}))));var runPackageManager=(dependencies,command)=>tryPromise2({catch:(cause)=>new UpgradeCommandError({cause,message:`Could not run ${command.join(" ")}`}),try:async()=>await dependencies.runPackageManager(command)});var globalInstallCommand=fn2("Upgrade.globalInstallCommand")(function*globalInstallCommand(dependencies){const{directory,name}=dependencies.installation;if(directory.replaceAll("\\","/").includes(bunGlobalRoot)){return some2(bunInstall)}for(const manager of packageManagers){const root=yield*option2(runPackageManager(dependencies,manager.globalRoot));if(isSome2(root)&&root.value.exitCode===0&&dependencies.realPath(path12.join(root.value.stdout.trim(),name))===directory){return some2(manager.install)}}return none2()});var upgradeCommandEffect=(args,dependencies)=>gen2(function*upgradeCommand(){yield*parseCommandOptionsEffect(args,{});const{directory,name,version}=dependencies.installation;const latest=yield*latestVersion(dependencies.fetch,name);if(Bun.semver.order(version,latest)>=0){return yield*sync2(()=>{dependencies.writeOutput(`ci ${version} is the latest version
|
|
3196
|
+
`;var contributionKey2=(input)=>JSON.stringify([input.packageFqn,input.contributionHost,input.contributionFqn]);var exposedModule=(key)=>`./${key}`;var randomUuid2=()=>{const bytes=new Uint8Array(16);crypto.getRandomValues(bytes);bytes[6]=bytes[6]%16+64;bytes[8]=bytes[8]%64+128;const hex=[...bytes].map((byte)=>byte.toString(16).padStart(2,"0"));return`${hex.slice(0,4).join("")}-${hex.slice(4,6).join("")}-${hex.slice(6,8).join("")}-${hex.slice(8,10).join("")}-${hex.slice(10).join("")}`};var authorizationPlugin=(input)=>({configureServer(server){server.middlewares.use((request,response,next)=>{const{origin}=request.headers;const{pathname}=new URL(request.url??"/","http://127.0.0.1");const authorized=origin===undefined?pathname.startsWith(input.capabilityBase):input.attachedOrigins.has(origin);if(!authorized){response.writeHead(403,{"content-type":"text/plain"});response.end("Host origin is not attached");return}if(origin!==undefined){response.setHeader("access-control-allow-origin",origin)}response.setHeader("cache-control","no-store");next()})},enforce:"pre",name:"ci-hosted-development-authorization"});var startViteDevelopmentAssetServer=flow((input)=>gen2(function*startAssetServer(){const capability=randomUuid2().replaceAll("-","");const capabilityPath=`__ci_capability__/${capability}/`;const capabilityBase=`/${capabilityPath}`;const attachedOrigins=new Set(input.hostOrigins);const frontendCacheDirectory=yield*promise2(()=>makeTempDirectory2("ci-hosted-vite-"));let frontendEntries=new Map;let frontendServer;let frontendServerPort;const warmFrontendServer=flow((server)=>gen2(function*warmServer(){yield*promise2(()=>server.warmupRequest(`${capabilityBase}remoteEntry.js`));yield*promise2(()=>server.waitForRequestsIdle())}),runNested2);const startFrontendServer=flow((entries,port)=>gen2(function*startFrontendServerEffect(){const exposes=Object.fromEntries([...entries.keys()].map((key)=>[exposedModule(key),`virtual:ci-hosted:${encodeURIComponent(key)}`]));const virtualPrefix="\x00virtual:ci-hosted:";const virtualEntries={load(id){return id.startsWith(virtualPrefix)?entries.get(decodeURIComponent(id.slice(virtualPrefix.length)))?.source??null:null},name:"ci-hosted-development-entries",resolveId(id){return id.startsWith("virtual:ci-hosted:")?`\x00${id}`:null}};const shared=Object.fromEntries(frontendHostProvidedModules.map((moduleName)=>[moduleName,{import:false,singleton:true,suppressMissingImportWarning:true}]));const declarationPath=declarationImport(input.declarationSpecifier);const root=path10.isAbsolute(declarationPath)?path10.dirname(declarationPath):process.cwd();const server=yield*promise2(()=>createServer3({base:capabilityBase,cacheDir:frontendCacheDirectory,configFile:false,logLevel:"silent",optimizeDeps:{entries:[...entries.values()].map((entry)=>entry.importPath),exclude:[...frontendHostProvidedModules]},plugins:[authorizationPlugin({attachedOrigins,capabilityBase}),viteReact(),virtualEntries,federation({dev:{remoteHmr:true},dts:false,exposes,filename:"remoteEntry.js",manifest:false,moduleParseIdleTimeout:1,name:`ci_hosted_${capability}`,shared})],resolve:workspaceSourceResolve(process.execArgv),root,server:{cors:false,headers:{"cache-control":"no-store"},host:"127.0.0.1",port,strictPort:port!==0},ssr:workspaceSourceSsrResolve(process.execArgv)}));yield*promise2(()=>server.listen());yield*promise2(()=>warmFrontendServer(server));return server}),runNested2);const synchronizeFrontendServer=flow((entries)=>gen2(function*synchronizeServer(){const previousKeys=[...frontendEntries.keys()].toSorted();const nextKeys=[...entries.keys()].toSorted();if(previousKeys.length===nextKeys.length&&previousKeys.every((key,index)=>key===nextKeys[index]&&frontendEntries.get(key)?.importPath===entries.get(key)?.importPath)){frontendEntries.clear();for(const[key,source]of entries){frontendEntries.set(key,source)}frontendServer?.moduleGraph.invalidateAll();const server=frontendServer;if(server!==undefined){yield*promise2(()=>warmFrontendServer(server))}return yield*void_3}const previousServer=frontendServer;const port=frontendServerPort??0;frontendServer=undefined;if(previousServer!==undefined){yield*promise2(()=>previousServer.close())}frontendEntries=entries;if(entries.size===0){frontendServerPort=undefined;return yield*void_3}const server=yield*promise2(()=>startFrontendServer(entries,port));frontendServer=server;const localUrl=server.resolvedUrls?.local.at(0);if(localUrl===undefined){yield*promise2(()=>server.close());frontendServer=undefined;throw new Error("Vite did not publish a loopback development URL")}frontendServerPort=Number(new URL(localUrl).port);return yield*void_3}),runNested2);const rebuild=flow((declarations)=>gen2(function*rebuildServer(){const nextFrontendEntries=new Map;for(const definition of declarations){for(const contribution of definition.hostedContributions){if(contribution.manifest.host==="backend"){continue}const key=contributionKey2({contributionFqn:contribution.manifest.fqn,contributionHost:contribution.manifest.host,packageFqn:definition.manifest.fqn});const importPath=resolveHostedContributionEntry(input.declarationSpecifier,{fqn:contribution.manifest.fqn,load:contribution.load});const source=virtualModuleSource({contributionImport:importPath,exportName:contribution.manifest.exportName});nextFrontendEntries.set(key,{importPath,source})}}yield*promise2(()=>synchronizeFrontendServer(nextFrontendEntries))}),runNested2);yield*promise2(()=>rebuild(input.declarations)).pipe(tapError2(()=>promise2(()=>frontendServer?.close().then(()=>null).catch(()=>null)??Promise.resolve(null)).pipe(andThen2(()=>promise2(()=>removeTempDirectory(frontendCacheDirectory))))));return{assetsFor:flow((definition)=>sync2(()=>definition.hostedContributions.flatMap(({manifest})=>{if(manifest.host==="backend"){return[]}const key=contributionKey2({contributionFqn:manifest.fqn,contributionHost:manifest.host,packageFqn:definition.manifest.fqn});const localUrl=frontendServer?.resolvedUrls?.local.at(0);if(localUrl===undefined){throw new Error(`Vite federation remote was not started for ${manifest.fqn}`)}const moduleUrl=new URL("remoteEntry.js",localUrl);moduleUrl.hash=encodeURIComponent(exposedModule(key));return{...manifest.compatibility===undefined?undefined:{compatibility:manifest.compatibility},contract:manifest.contract,exportName:manifest.exportName,fqn:manifest.fqn,host:manifest.host,moduleUrl:moduleUrl.href}})),runNested2),close:flow(()=>gen2(function*closeServer(){const server=frontendServer;if(server!==undefined){yield*promise2(()=>server.close())}yield*promise2(()=>removeTempDirectory(frontendCacheDirectory))}),runPromiseWith2(empty())),rebuild}}),runPromise2);class PackageDiagnosticsCommandError extends TaggedError3()("PackageDiagnosticsCommandError",{cause:optional2(Unknown2),message:String4}){}var requireOption3=(options,name)=>{const value=options.get(name);if(value===undefined||value===""){throw new PackageDiagnosticsCommandError({message:`Missing required option --${name}`})}return value};var parseOptions3=(args)=>{const options=new Map;for(let index=1;index<args.length;index+=2){const flag=args[index];const value=args[index+1];if(!flag?.startsWith("--")||!value||value.startsWith("--")){throw new PackageDiagnosticsCommandError({message:"Options must be supplied as --name value pairs"})}options.set(flag.slice(2),value)}return options};var packageDiagnosticsCommandEffect=(args,dependencies)=>{const[command]=args;if(command!=="trace"){return fail6(new PackageDiagnosticsCommandError({message:"Expected package diagnostics command: trace"}))}return try_2({catch:(cause)=>is2(PackageDiagnosticsCommandError)(cause)?cause:new PackageDiagnosticsCommandError({cause,message:"Could not configure package diagnostics command"}),try:()=>parseOptions3(args)}).pipe(flatMap3((options)=>tryPromise2({catch:(cause)=>new PackageDiagnosticsCommandError({cause,message:"Could not read hosted Extension diagnostic trace"}),try:async()=>{const response=await hostedExtensionDiagnosticsReadTrace({client:dependencies.client,headers:{"x-organization-id":requireOption3(options,"organization")},path:{diagnosticId:requireOption3(options,"diagnostic")},throwOnError:true});return response.data}})))};import{createHash as createHash7}from"crypto";var awaitValue7=(value)=>promise2(constant(Promise.resolve(value)));var path11=runSync2(provide3(Path2,layer5));var readBytesEffect=(readBytes,filePath)=>tryPromise2(flow(()=>suspend2(()=>awaitValue7(readBytes(filePath))),runPromise2));class PackageReleaseCommandError extends TaggedError3()("PackageReleaseCommandError",{cause:optional2(Unknown2),message:String4}){}var requireOption4=(options,name)=>{const value=options.get(name);if(value===undefined||value===""){throw new PackageReleaseCommandError({message:`Missing required option --${name}`})}return value};var supportedOptions=new Set(["archive","backend-url","bundle","idempotency-key","inputs","installation","manifest","organization","package","package-manifest","private-maps","release","scope","version"]);var parseOptions4=(args)=>{const options=new Map;for(let index=1;index<args.length;index+=2){const flag=args[index];const value=args[index+1];if(!flag?.startsWith("--")||!value||value.startsWith("--")){throw new PackageReleaseCommandError({message:"Options must be supplied as --name value pairs"})}if(!supportedOptions.has(flag.slice(2))){throw new PackageReleaseCommandError({message:`Unknown option ${flag}`})}options.set(flag.slice(2),value)}return options};var idempotencyHeaders=(options)=>({"idempotency-key":requireOption4(options,"idempotency-key")});var administratorHeaders=(options)=>({...idempotencyHeaders(options),"x-organization-id":requireOption4(options,"organization")});var rejectRetiredPublishOptions=(options)=>{if(options.has("scope")){throw new PackageReleaseCommandError({message:"--scope is no longer supported; publisher credential scope is authoritative"})}if(options.has("organization")){throw new PackageReleaseCommandError({message:"--organization is no longer supported; publisher credential scope is authoritative"})}if(options.has("package")||options.has("version")){throw new PackageReleaseCommandError({message:"--package and --version are no longer supported; the authoritative release manifest supplies both"})}if(options.has("bundle")){throw new PackageReleaseCommandError({message:"--bundle is no longer supported for publication; use the verified --archive release artifact"})}};var digest3=(bytes)=>createHash7("sha256").update(bytes).digest("hex");var rejectInputs=(message)=>{throw new PackageReleaseCommandError({message})};var readInputs=async(options,readBytes)=>{const filePath=options.get("inputs");return filePath===undefined?{}:inputsFromFile(await readInputsFile(filePath,rejectInputs,readBytes))};var executePublish=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not publish package release"}),try:async()=>{rejectRetiredPublishOptions(options);const archiveBytes=await dependencies.readBytes(requireOption4(options,"archive"));const manifestPath=requireOption4(options,"manifest");const manifestBytes=await dependencies.readBytes(manifestPath);const packageManifestBytes=await dependencies.readBytes(requireOption4(options,"package-manifest"));const privateMapDirectory=options.has("private-maps")?requireOption4(options,"private-maps"):path11.join(path11.dirname(manifestPath),"private-source-maps");const privateMapFiles=await dependencies.listFiles(privateMapDirectory);const privateSourceMaps=await Promise.all(privateMapFiles.toSorted(compareCanonicalText).map(flow((fileName)=>gen2(function*readPrivateSourceMap(){if(!/^[\da-f]{64}\.map$/u.test(fileName)){return yield*new PackageReleaseCommandError({message:`Private source-map file '${fileName}' is not keyed by a runtime asset digest`})}const bytes=yield*readBytesEffect(dependencies.readBytes,path11.join(privateMapDirectory,fileName));return{bytes,digest:digest3(bytes),runtimeAssetDigest:fileName.slice(0,-4),size:bytes.byteLength}}),runPromise2)));const body=await preparePackagePublication({archiveBytes,manifestBytes,packageManifestBytes,privateSourceMaps});const accepted=await publishPackage({body,client:dependencies.client,idempotencyKey:requireOption4(options,"idempotency-key")});return accepted.operationId}});var executePromote=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not promote package release"}),try:async()=>{const body={protocolVersion:"v1",releaseId:requireOption4(options,"release")};const accepted=await promotePackage({body,client:dependencies.client,idempotencyKey:requireOption4(options,"idempotency-key")});return accepted.operationId}});var executeUpdate=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not update package installation"}),try:async()=>{const body={...await readInputs(options,dependencies.readBytes),installationId:requireOption4(options,"installation"),protocolVersion:"v1",releaseId:requireOption4(options,"release")};const accepted=await updatePackage({body,client:dependencies.client,idempotencyKey:requireOption4(options,"idempotency-key"),organizationId:requireOption4(options,"organization")});return accepted.operationId}});var executeInstall=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not install package"}),try:async()=>{const releaseId=options.get("release");const body={...releaseId===undefined?undefined:{releaseId},...await readInputs(options,dependencies.readBytes)};const accepted=await installPackage({...Object.keys(body).length===0?undefined:{body},client:dependencies.client,idempotencyKey:requireOption4(options,"idempotency-key"),organizationId:requireOption4(options,"organization"),packageFqn:requireOption4(options,"package")});return accepted.operationId}});var executeSync=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not sync package"}),try:async()=>{if(options.has("release")){throw new PackageReleaseCommandError({message:"package sync re-applies the current release and does not accept --release; use package update --release for an exact release"})}const accepted=await extensionPackagesSync({client:dependencies.client,headers:administratorHeaders(options),path:{fqn:requireOption4(options,"package")},throwOnError:true});return accepted.data.operationId}});var executeRollback=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not roll back package installation"}),try:async()=>{const accepted=await packageReleasesRollbackInstallation({body:{installationId:requireOption4(options,"installation"),protocolVersion:"v1",releaseId:requireOption4(options,"release")},client:dependencies.client,headers:administratorHeaders(options),throwOnError:true});return accepted.data.operationId}});var packageReleaseCommandEffect=(args,dependencies)=>{const[command]=args;const options=parseOptions4(args);if(options.has("inputs")&&command!=="install"&&command!=="update"){return fail6(new PackageReleaseCommandError({message:"--inputs is supported only for package install/update"}))}switch(command){case"install":{return executeInstall(options,dependencies)}case"publish":{return executePublish(options,dependencies)}case"promote":{return executePromote(options,dependencies)}case"rollback":{return executeRollback(options,dependencies)}case"sync":{return executeSync(options,dependencies)}case"update":{return executeUpdate(options,dependencies)}default:{return fail6(new PackageReleaseCommandError({message:"Expected one of: package publish, package promote, package install, package update, package sync, package rollback"}))}}};class PackageReleasesCommandError extends TaggedError3()("PackageReleasesCommandError",{cause:optional2(Unknown2),message:String4}){}var requireOption5=(options,name)=>{const value=options.get(name);if(value===undefined||value===""){throw new PackageReleasesCommandError({message:`Missing required option --${name}`})}return value};var parseOptions5=(args)=>{const options=new Map;for(let index=0;index<args.length;index+=2){const flag=args[index];const value=args[index+1];if(!flag?.startsWith("--")||!value||value.startsWith("--")){throw new PackageReleasesCommandError({message:"Options must be supplied as --name value pairs"})}options.set(flag.slice(2),value)}return options};var packageReleasesCommandEffect=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleasesCommandError)(cause)?cause:new PackageReleasesCommandError({cause,message:"Could not list package releases"}),try:async()=>{const parsed=parseOptions5(options);const response=await extensionPackagesListReleases({client:dependencies.client,headers:{"x-organization-id":requireOption5(parsed,"organization")},path:{fqn:requireOption5(parsed,"package")},throwOnError:true});return response.data}});import path12 from"path";class UpgradeCommandError extends TaggedError3()("UpgradeCommandError",{cause:optional2(Unknown2),message:String4}){}var registryUrl="https://registry.npmjs.org";var registryTimeout="30 seconds";var RegistryVersion=Struct({version:String4});var packageManagers=[{globalRoot:["npm","root","-g"],install:["npm","install","-g","--prefer-online"]},{globalRoot:["pnpm","root","-g"],install:["pnpm","add","-g"]}];var bunInstall=["bun","add","-g"];var bunGlobalRoot="/install/global/node_modules/";var latestVersion=(fetch2,name)=>tryPromise2({catch:(cause)=>new UpgradeCommandError({cause,message:`Could not reach ${registryUrl} to read the latest ci version`}),try:async(signal)=>{const response=await fetch2(`${registryUrl}/${name}/latest`,{headers:{accept:"application/json"},signal});return response.ok?await response.json():undefined}}).pipe(timeoutOrElse2({duration:registryTimeout,orElse:()=>fail6(new UpgradeCommandError({message:`${registryUrl} did not respond within ${registryTimeout}`}))}),flatMap3((body)=>is2(RegistryVersion)(body)?succeed6(body.version):fail6(new UpgradeCommandError({message:`${registryUrl} did not return the latest ci version`}))));var runPackageManager=(dependencies,command)=>tryPromise2({catch:(cause)=>new UpgradeCommandError({cause,message:`Could not run ${command.join(" ")}`}),try:async()=>await dependencies.runPackageManager(command)});var globalInstallCommand=fn2("Upgrade.globalInstallCommand")(function*globalInstallCommand(dependencies){const{directory,name}=dependencies.installation;if(directory.replaceAll("\\","/").includes(bunGlobalRoot)){return some2(bunInstall)}for(const manager of packageManagers){const root=yield*option2(runPackageManager(dependencies,manager.globalRoot));if(isSome2(root)&&root.value.exitCode===0&&dependencies.realPath(path12.join(root.value.stdout.trim(),name))===directory){return some2(manager.install)}}return none2()});var upgradeCommandEffect=(args,dependencies)=>gen2(function*upgradeCommand(){yield*parseCommandOptionsEffect(args,{});const{directory,name,version}=dependencies.installation;const latest=yield*latestVersion(dependencies.fetch,name);if(Bun.semver.order(version,latest)>=0){return yield*sync2(()=>{dependencies.writeOutput(`ci ${version} is the latest version
|
|
3196
3197
|
`)})}const install=yield*globalInstallCommand(dependencies);if(isNone2(install)){return yield*new UpgradeCommandError({message:`ci at ${directory} is not a global npm, pnpm or Bun install; install ${name}@${latest} with the package manager that installed it`})}const command=[...install.value,`${name}@${latest}`];dependencies.writeDiagnostic(`Upgrading ci from ${version} to ${latest}: ${command.join(" ")}
|
|
3197
3198
|
`);const{exitCode,stdout}=yield*runPackageManager(dependencies,command);if(exitCode!==0){return yield*new UpgradeCommandError({message:`${stdout}${command.join(" ")} failed (exit code ${exitCode}); ci ${version} is still installed`})}return yield*sync2(()=>{dependencies.writeOutput(`Upgraded ci from ${version} to ${latest}
|
|
3198
3199
|
`)})}).pipe(mapError2((cause)=>is2(UpgradeCommandError)(cause)?cause:new UpgradeCommandError({cause,message:cause.message})));class WhoamiCommandError extends TaggedError3()("WhoamiCommandError",{cause:optional2(Unknown2),message:String4}){}var whoamiCommandEffect=(args,dependencies)=>gen2(function*whoamiCommand(){yield*parseCommandOptionsEffect(args,{values:targetOptions});const target=yield*tryConfiguration(()=>resolveBackendManagementTarget({args,environment:dependencies.environment,organizationLookup:true}));const identity=yield*managementData("Identity read",authMe,{client:makeBackendManagementClient({backendUrl:target.apiOrigin,fetch:dependencies.fetch,token:target.token})});const source=target.credentialSource==="management-token"?"CI_MANAGEMENT_TOKEN":`CLI Session (Profile ${target.profile??"unknown"})`;const keyOrganization=identity.organizationId===undefined?undefined:`${identity.organizationName??identity.organizationId} (${identity.organizationId})`;const lines=identity.credentialKind==="api_key"?[`Credential: ${source}`,`API key: ${identity.apiKeyName??identity.id}`,`API key Organization: ${keyOrganization??"unknown"}`,`Tenant: ${target.apiOrigin}`,`Current Organization: ${target.organizationId??identity.organizationId??"none"}`]:[`Credential: ${source}`,`User: ${identity.name??identity.email??identity.id}${identity.email===null?"":` <${identity.email}>`}`,`Tenant: ${target.apiOrigin}`,`Current Organization: ${target.organizationId??"none (run ci orgs use <organization-id>)"}`,`Session expires: ${identity.sessionExpiresAt??"unknown"}`];dependencies.writeOutput(`${lines.join(`
|
|
3199
3200
|
`)}
|
|
3200
|
-
`)}).pipe(mapError2((cause)=>new WhoamiCommandError({cause,message:cause.message})));import{fileURLToPath as fileURLToPath13}from"url";var{existsSync:existsSync9,watch:watch3}=await import("fs");var path13=runSync2(provide3(Path2,layer5));var declarationPackageRoot=(declarationPath)=>{const declarationDirectory=path13.dirname(declarationPath);let candidate=declarationDirectory;while(true){if(existsSync9(path13.join(candidate,"package.json"))){return candidate}const parent=path13.dirname(candidate);if(parent===candidate){return declarationDirectory}candidate=parent}};var watchPackageDeclaration=(specifier,refresh,reportFailure)=>{if(!specifier.startsWith("file:")){return{close:flow(()=>promise2(constant(Promise.resolve())),runPromise2)}}let closed=false;let refreshGeneration=0;let refreshQueue=Promise.resolve();const scheduleRefresh=()=>{refreshGeneration+=1;const generation=refreshGeneration;runPromise2(sleep2("25 millis").pipe(flatMap3(()=>{if(closed||generation!==refreshGeneration){return void_3}const previousRefresh=refreshQueue;refreshQueue=runPromise2(gen2(function*refreshDeclaration(){yield*promise2(constant(previousRefresh));yield*tryPromise2(refresh).pipe(catch_2((error)=>sync2(()=>{reportFailure(error instanceof Error?error:new Error(String(error)))})))}));return void_3})))};const watcher=watch3(declarationPackageRoot(fileURLToPath13(specifier)),{recursive:true},scheduleRefresh);watcher.on("error",(error)=>{reportFailure(error)});return{close:flow(()=>gen2(function*closeWatcher(){closed=true;refreshGeneration+=1;watcher.close();yield*promise2(constant(refreshQueue))}),runPromise2)}};var awaitValue8=(value)=>promise2(constant(Promise.resolve(value)));var writeStandardError=(value)=>{process.stderr.write(value)};var openerCommand=(url)=>{if(process.platform==="darwin"){return["open",url]}if(process.platform==="win32"){return["rundll32","url.dll,FileProtocolHandler",url]}return["xdg-open",url]};var openWithOperatingSystem=(url)=>{const command=openerCommand(url);try{Bun.spawn(command,{stderr:"ignore",stdout:"ignore"})}catch{}};var readEnvFile=(filePath)=>existsSync10(filePath)?readFileSync8(filePath,"utf-8"):undefined;var writeEnvFile=(filePath,content)=>{const temporary=`${filePath}.${process.pid}.tmp`;writeFileSync6(temporary,content,{mode:384});if(existsSync10(filePath)){chmodSync2(temporary,statSync3(filePath).mode)}renameSync2(temporary,filePath)};var realPath2=(target)=>existsSync10(target)?realpathSync5(target):undefined;var runPackageManager2=async(command)=>{const child=Bun.spawn([...command],{stderr:"inherit",stdout:"pipe"});const stdout=await new Response(child.stdout).text();return{exitCode:await child.exited,stdout}};var defaultCliAdapters={fetch:globalThis.fetch,writeDiagnostic:writeStandardError,writeOutput:(value)=>{process.stdout.write(value)}};var fileSystem=runSync2(provide3(FileSystem,layer2));var
|
|
3201
|
+
`)}).pipe(mapError2((cause)=>new WhoamiCommandError({cause,message:cause.message})));import{fileURLToPath as fileURLToPath13}from"url";var{existsSync:existsSync9,watch:watch3}=await import("fs");var path13=runSync2(provide3(Path2,layer5));var declarationPackageRoot=(declarationPath)=>{const declarationDirectory=path13.dirname(declarationPath);let candidate=declarationDirectory;while(true){if(existsSync9(path13.join(candidate,"package.json"))){return candidate}const parent=path13.dirname(candidate);if(parent===candidate){return declarationDirectory}candidate=parent}};var watchPackageDeclaration=(specifier,refresh,reportFailure)=>{if(!specifier.startsWith("file:")){return{close:flow(()=>promise2(constant(Promise.resolve())),runPromise2)}}let closed=false;let refreshGeneration=0;let refreshQueue=Promise.resolve();const scheduleRefresh=()=>{refreshGeneration+=1;const generation=refreshGeneration;runPromise2(sleep2("25 millis").pipe(flatMap3(()=>{if(closed||generation!==refreshGeneration){return void_3}const previousRefresh=refreshQueue;refreshQueue=runPromise2(gen2(function*refreshDeclaration(){yield*promise2(constant(previousRefresh));yield*tryPromise2(refresh).pipe(catch_2((error)=>sync2(()=>{reportFailure(error instanceof Error?error:new Error(String(error)))})))}));return void_3})))};const watcher=watch3(declarationPackageRoot(fileURLToPath13(specifier)),{recursive:true},scheduleRefresh);watcher.on("error",(error)=>{reportFailure(error)});return{close:flow(()=>gen2(function*closeWatcher(){closed=true;refreshGeneration+=1;watcher.close();yield*promise2(constant(refreshQueue))}),runPromise2)}};var awaitValue8=(value)=>promise2(constant(Promise.resolve(value)));var writeStandardError=(value)=>{process.stderr.write(value)};var promptStandardInput=async(question)=>{const terminal=createInterface({input:process.stdin,output:process.stderr});try{return await terminal.question(question)}finally{terminal.close()}};var openerCommand=(url)=>{if(process.platform==="darwin"){return["open",url]}if(process.platform==="win32"){return["rundll32","url.dll,FileProtocolHandler",url]}return["xdg-open",url]};var openWithOperatingSystem=(url)=>{const command=openerCommand(url);try{Bun.spawn(command,{stderr:"ignore",stdout:"ignore"})}catch{}};var readEnvFile=(filePath)=>existsSync10(filePath)?readFileSync8(filePath,"utf-8"):undefined;var writeEnvFile=(filePath,content)=>{const temporary=`${filePath}.${process.pid}.tmp`;writeFileSync6(temporary,content,{mode:384});if(existsSync10(filePath)){chmodSync2(temporary,statSync3(filePath).mode)}renameSync2(temporary,filePath)};var realPath2=(target)=>existsSync10(target)?realpathSync5(target):undefined;var runPackageManager2=async(command)=>{const child=Bun.spawn([...command],{stderr:"inherit",stdout:"pipe"});const stdout=await new Response(child.stdout).text();return{exitCode:await child.exited,stdout}};var defaultCliAdapters={fetch:globalThis.fetch,prompt:promptStandardInput,writeDiagnostic:writeStandardError,writeOutput:(value)=>{process.stdout.write(value)}};var fileSystem=runSync2(provide3(FileSystem,layer2));var nodePath5=runSync2(provide3(Path2,layer5));var runNative=runPromiseWith2(empty());var runFileEffect=runNative;var encodeJson4=encodeSync(fromJsonString2(Unknown2));var packagePreflightErrorTag="PackagePreflightError";var packagePreflightDiagnostic=Struct({_tag:Literal2(packagePreflightErrorTag),diagnostic:Struct({message:String4})});var usage6=`Usage:
|
|
3201
3202
|
ci login <API URL> [--organization <organization-id>] [--no-browser] [--profile <name>]
|
|
3202
3203
|
ci whoami
|
|
3203
3204
|
ci logout
|
|
@@ -3220,15 +3221,16 @@ export const ${moduleExport3(input.exportName)} = loaded[${JSON.stringify(input.
|
|
|
3220
3221
|
ci doctor [--fqn <fqn>] [--redirect-uri <uri>]...
|
|
3221
3222
|
(whoami, logout, orgs, apps and doctor also accept [--backend-url <url>] [--organization <organization-id>] [--profile <name>])
|
|
3222
3223
|
ci upgrade (installs the latest version over a global npm, pnpm or Bun install)
|
|
3223
|
-
ci deploy --backend-url <url> --organization <organization-id> --declaration <module> [--gateway-url <GatewayFQN>=<HTTPS-origin>]... [--accept-breaking-changes] [--timeout-ms <milliseconds>] [--non-interactive] [--json]
|
|
3224
|
+
ci deploy --backend-url <url> --organization <organization-id> --declaration <module> [--inputs <file>] [--var <name>=<value>|<name>=@<ORG_VARIABLE_KEY>]... [--gateway-url <GatewayFQN>=<HTTPS-origin>]... [--accept-breaking-changes] [--timeout-ms <milliseconds>] [--non-interactive] [--json]
|
|
3225
|
+
ci deploy --declaration <module> --inputs-template (prints the Inputs File template: declared variables and connection slots; no Backend access)
|
|
3224
3226
|
ci package dev --backend-url <url> --declaration <module> --host-origin <origin> [...]
|
|
3225
3227
|
ci package build --declaration <module> --out <directory>
|
|
3226
3228
|
ci package validate --archive <release.tar> --manifest <manifest.json> --package-manifest <package-manifest.json> [--private-maps <directory>]
|
|
3227
3229
|
ci package publish --backend-url <url> --archive <release.tar> --manifest <manifest.json> --package-manifest <package-manifest.json> [--private-maps <directory>] --idempotency-key <key>
|
|
3228
3230
|
ci package promote --backend-url <url> --release <release-id> --idempotency-key <key>
|
|
3229
3231
|
ci package releases --backend-url <url> --organization <organization-id> --package <package-fqn> (promoted releases visible to the Organization)
|
|
3230
|
-
ci package install --backend-url <url> --organization <organization-id> --package <package-fqn> [--release <release-id>] --idempotency-key <key>
|
|
3231
|
-
ci package update --backend-url <url> --organization <organization-id> --installation <installation-id> --release <release-id> --idempotency-key <key>
|
|
3232
|
+
ci package install --backend-url <url> --organization <organization-id> --package <package-fqn> [--release <release-id>] [--inputs <file>] --idempotency-key <key>
|
|
3233
|
+
ci package update --backend-url <url> --organization <organization-id> --installation <installation-id> --release <release-id> [--inputs <file>] --idempotency-key <key>
|
|
3232
3234
|
ci package sync --backend-url <url> --organization <organization-id> --package <package-fqn> --idempotency-key <key> (maintenance: re-applies the current release; use update --release to select a release)
|
|
3233
3235
|
ci package rollback --backend-url <url> --organization <organization-id> --installation <installation-id> --release <release-id> --idempotency-key <key>
|
|
3234
3236
|
ci package operation snapshot --backend-url <url> --organization <organization-id> --operation <operation-id>
|
|
@@ -3241,12 +3243,12 @@ Configuration (flag > environment > CLI Profile):
|
|
|
3241
3243
|
CI_MANAGEMENT_TOKEN Management credential with the command's required permission; else the Profile CLI Session
|
|
3242
3244
|
CI_BACKEND_URL Backend URL when --backend-url is absent; else the Profile API origin
|
|
3243
3245
|
CI_PROFILE CLI Profile to use (or --profile <name>); default is the current Profile in $XDG_CONFIG_HOME/ci or ~/.config/ci
|
|
3244
|
-
--organization Organization for organization-scoped commands; else the Profile Current Organization`;var optionValue4=(args,name)=>{const index=args.lastIndexOf(`--${name}`);return index===-1?undefined:args[index+1]};var withoutOption=(args,name)=>{const retained=[];for(let index=0;index<args.length;index+=1){if(args[index]===`--${name}`){index+=1}else{retained.push(args[index]??"")}}return retained};var resolvedDeclarationSpecifier=(declaration)=>{if(declaration.startsWith("file:")){return declaration}if(declaration.startsWith(".")||declaration.startsWith("/")){return pathToFileURL5(
|
|
3246
|
+
--organization Organization for organization-scoped commands; else the Profile Current Organization`;var optionValue4=(args,name)=>{const index=args.lastIndexOf(`--${name}`);return index===-1?undefined:args[index+1]};var withoutOption=(args,name)=>{const retained=[];for(let index=0;index<args.length;index+=1){if(args[index]===`--${name}`){index+=1}else{retained.push(args[index]??"")}}return retained};var resolvedDeclarationSpecifier=(declaration)=>{if(declaration.startsWith("file:")){return declaration}if(declaration.startsWith(".")||declaration.startsWith("/")){return pathToFileURL5(nodePath5.resolve(process.cwd(),declaration)).href}return import.meta.resolve(declaration)};var developmentCommandEffect=(options,environment,adapters)=>try_2({catch:(cause)=>is2(PackageDevelopmentCommandError)(cause)?cause:new PackageDevelopmentCommandError({cause,message:cause instanceof Error?cause.message:"Could not configure package development"}),try:()=>{const client=backendManagementClientFromCli({args:options,environment,fetch:adapters.fetch});let failWatch;const watchFailure=callback2((resume)=>{failWatch=(error)=>{resume(fail6(error))}});return packageDevelopmentCommandEffect(["dev",...withoutOption(withoutOption(options,"backend-url"),"profile")],{awaitTermination:flow(()=>raceFirst2(callback2((resume)=>{const stop=()=>{resume(succeed6(null))};process.once("SIGINT",stop);process.once("SIGTERM",stop);return sync2(()=>{process.off("SIGINT",stop);process.off("SIGTERM",stop)})}),watchFailure).pipe(asVoid2),runNative),createDevelopmentSession:flow((request)=>map4(suspend2(()=>awaitValue8(createDevelopmentSession(client,request))),(session)=>({localManifestRevision:session.localManifestRevision,sessionId:session.sessionId})),runNative),heartbeatDevelopmentSession:flow((sessionId)=>suspend2(()=>awaitValue8(heartbeatDevelopmentSession(client,sessionId))).pipe(asVoid2),runNative),loadDeclarations:loadFreshPackageDeclarations,reportWarning:(message)=>{const writeDiagnostic=adapters.writeDiagnostic??writeStandardError;writeDiagnostic(`${message}
|
|
3245
3247
|
`)},resolveDeclarationSpecifier:resolvedDeclarationSpecifier,startAssets:startViteDevelopmentAssetServer,terminateDevelopmentSession:flow((sessionId)=>suspend2(()=>awaitValue8(terminateDevelopmentSession(client,sessionId))).pipe(asVoid2),runNative),updateLocalManifest:flow((request)=>map4(suspend2(()=>awaitValue8(updateDevelopmentSessionLocalManifest(client,request))),(session)=>({localManifestRevision:session.localManifestRevision,sessionId:session.sessionId})),runNative),watchDeclaration:(specifier,refresh)=>watchPackageDeclaration(specifier,refresh,(error)=>{failWatch?.(error)}),writeResult:(result)=>{adapters.writeOutput(`${result}
|
|
3246
3248
|
`)}})}}).pipe(flatten3);class CliCommandError extends TaggedError3()("CliCommandError",{message:String4}){}var artifactCommandEffect=(command,options,adapters)=>tryPromise2({catch:(cause)=>new CliCommandError({message:cause instanceof Error?cause.message:`Could not ${command} package release`}),try:flow(()=>gen2(function*artifactCommand(){const output=command==="build"?yield*suspend2(()=>awaitValue8(runPackageBuildCommand(options,{makeDirectory:flow((directoryPath)=>suspend2(()=>awaitValue8(runFileEffect(fileSystem.makeDirectory(directoryPath,{recursive:true})))).pipe(asVoid2),runNative),resolveDeclarationSpecifier:resolvedDeclarationSpecifier,writeBytes:flow((filePath,bytes)=>suspend2(()=>awaitValue8(runFileEffect(fileSystem.writeFile(filePath,bytes)))).pipe(asVoid2),runNative)}))):yield*suspend2(()=>awaitValue8(runPackageValidationCommand(options,{listFiles:flow((directoryPath)=>suspend2(()=>awaitValue8(runFileEffect(fileSystem.readDirectory(directoryPath)))),runNative),readBytes:flow((filePath)=>suspend2(()=>awaitValue8(runFileEffect(fileSystem.readFile(filePath)))),runNative)})));adapters.writeOutput(`${output}
|
|
3247
3249
|
`)}),runNative)});var renderPackageOperationResult=(result,adapters)=>{if(result.kind==="operation_accepted"){adapters.writeOutput(`Operation ID: ${result.operationId}
|
|
3248
3250
|
`);return}adapters.writeOutput(`${JSON.stringify(result.snapshot)}
|
|
3249
|
-
`);const writeDiagnostic=adapters.writeDiagnostic??writeStandardError;writeDiagnostic(renderPackageOperationSummary(result.snapshot))};var organizationScopedReleaseCommands=new Set(["install","rollback","sync","update"]);var managementInvocation=(options,environment,adapters,scope)=>{const commandOptions=withoutOption(options,"profile");const organizationTarget=scope==="organization"?resolveOrganizationTarget({args:options,environment}):undefined;const target=organizationTarget??resolveBackendManagementTarget({args:options,environment});return{client:makeBackendManagementClient({backendUrl:target.apiOrigin,fetch:adapters.fetch,token:target.token}),options:organizationTarget===undefined||optionValue4(commandOptions,"organization")!==undefined?commandOptions:[...commandOptions,"--organization",organizationTarget.organizationId]}};var accessDependencies=(environment,adapters)=>({environment,fetch:adapters.fetch,writeDiagnostic:adapters.writeDiagnostic??writeStandardError,writeOutput:adapters.writeOutput});var accessCommands=new Map([["apps",(args,environment,adapters)=>{const dependencies=accessDependencies(environment,adapters);if(args[0]==="enroll"||args[0]==="env"){const command=args[0]==="enroll"?appsEnrollCommandEffect:appsEnvCommandEffect;return command(args.slice(1),{...dependencies,readEnvFile,writeEnvFile})}return args[0]==="redirect-uris"||args[0]==="origins"?appsUrlsCommandEffect(args,dependencies):appsCommandEffect(args,dependencies)}],["doctor",(args,environment,adapters)=>doctorCommandEffect(args,accessDependencies(environment,adapters))],["login",(args,environment,adapters)=>loginCommandEffect(args,{...accessDependencies(environment,adapters),delay:adapters.delay??Bun.sleep,deviceName:hostname(),openBrowser:adapters.openBrowser??openWithOperatingSystem})],["logout",(args,environment,adapters)=>logoutCommandEffect(args,accessDependencies(environment,adapters))],["orgs",(args,environment,adapters)=>orgsCommandEffect(args,accessDependencies(environment,adapters))],["whoami",(args,environment,adapters)=>whoamiCommandEffect(args,accessDependencies(environment,adapters))]]);var cliEffect=(args,environment=Bun.env,adapters=defaultCliAdapters)=>{const[group,command,...options]=args;const accessCommand=accessCommands.get(group??"");if(accessCommand!==undefined){return accessCommand(args.slice(1),environment,adapters)}if(group==="upgrade"){return upgradeCommandEffect(args.slice(1),{fetch:adapters.fetch,installation:{directory:realpathSync5(
|
|
3251
|
+
`);const writeDiagnostic=adapters.writeDiagnostic??writeStandardError;writeDiagnostic(renderPackageOperationSummary(result.snapshot))};var organizationScopedReleaseCommands=new Set(["install","rollback","sync","update"]);var managementInvocation=(options,environment,adapters,scope)=>{const commandOptions=withoutOption(options,"profile");const organizationTarget=scope==="organization"?resolveOrganizationTarget({args:options,environment}):undefined;const target=organizationTarget??resolveBackendManagementTarget({args:options,environment});return{client:makeBackendManagementClient({backendUrl:target.apiOrigin,fetch:adapters.fetch,token:target.token}),options:organizationTarget===undefined||optionValue4(commandOptions,"organization")!==undefined?commandOptions:[...commandOptions,"--organization",organizationTarget.organizationId]}};var accessDependencies=(environment,adapters)=>({environment,fetch:adapters.fetch,writeDiagnostic:adapters.writeDiagnostic??writeStandardError,writeOutput:adapters.writeOutput});var accessCommands=new Map([["apps",(args,environment,adapters)=>{const dependencies=accessDependencies(environment,adapters);if(args[0]==="enroll"||args[0]==="env"){const command=args[0]==="enroll"?appsEnrollCommandEffect:appsEnvCommandEffect;return command(args.slice(1),{...dependencies,readEnvFile,writeEnvFile})}return args[0]==="redirect-uris"||args[0]==="origins"?appsUrlsCommandEffect(args,dependencies):appsCommandEffect(args,dependencies)}],["doctor",(args,environment,adapters)=>doctorCommandEffect(args,accessDependencies(environment,adapters))],["login",(args,environment,adapters)=>loginCommandEffect(args,{...accessDependencies(environment,adapters),delay:adapters.delay??Bun.sleep,deviceName:hostname(),openBrowser:adapters.openBrowser??openWithOperatingSystem})],["logout",(args,environment,adapters)=>logoutCommandEffect(args,accessDependencies(environment,adapters))],["orgs",(args,environment,adapters)=>orgsCommandEffect(args,accessDependencies(environment,adapters))],["whoami",(args,environment,adapters)=>whoamiCommandEffect(args,accessDependencies(environment,adapters))]]);var cliEffect=(args,environment=Bun.env,adapters=defaultCliAdapters)=>{const[group,command,...options]=args;const accessCommand=accessCommands.get(group??"");if(accessCommand!==undefined){return accessCommand(args.slice(1),environment,adapters)}if(group==="upgrade"){return upgradeCommandEffect(args.slice(1),{fetch:adapters.fetch,installation:{directory:realpathSync5(nodePath5.join(import.meta.dir,"..")),name,version},realPath:realPath2,runPackageManager:runPackageManager2,writeDiagnostic:adapters.writeDiagnostic??writeStandardError,writeOutput:adapters.writeOutput})}if(group==="deploy"){const deployArgs=args.slice(1);const json=deployArgs.includes("--json");const output={resolveDeclarationSpecifier:resolvedDeclarationSpecifier,writeOutput:adapters.writeOutput};return try_2({catch:(cause)=>is2(DeployCommandError)(cause)?cause:new DeployCommandError({cause,json,message:"Invalid deployment options"}),try:()=>parseDeployOptions(deployArgs)}).pipe(flatMap3((parsed)=>parsed.inputsTemplate?inputsTemplateEffect(parsed,output):resolveOrganizationContext({args:deployArgs,environment,fetch:adapters.fetch}).pipe(mapError2((cause)=>new DeployCommandError({cause,json,message:cause.message})),flatMap3((context)=>deploymentManagementClients({environment,fetch:adapters.fetch,target:context.target}).pipe(mapError2((cause)=>new DeployCommandError({cause,json,message:"ci deploy requires the CI_PUBLISHER_TOKEN credential"})),flatMap3((clients)=>deployCommandEffect({...parsed,organizationId:context.organizationId},{...clients,...output,prompt:adapters.prompt??promptStandardInput,writeDiagnostic:adapters.writeDiagnostic??writeStandardError})))))),asVoid2)}if(group!=="package"||command===undefined){return fail6(new CliCommandError({message:usage6}))}if(command==="dev"){return developmentCommandEffect(options,environment,adapters)}if(command==="build"||command==="validate"){return artifactCommandEffect(command,options,adapters)}if(command==="operation"){return try_2({catch:(cause)=>is2(PackageOperationCommandError)(cause)?cause:new PackageOperationCommandError({cause,message:is2(BackendManagementConfigurationError)(cause)?cause.message:"Could not configure package operation command"}),try:()=>{const invocation=managementInvocation(options,environment,adapters,"organization");return packageOperationCommandEffect(invocation.options,{client:invocation.client,writeEvent:(event)=>{adapters.writeOutput(`${event}
|
|
3250
3252
|
`)}})}}).pipe(flatten3,tap2((result)=>sync2(()=>{renderPackageOperationResult(result,adapters)})),asVoid2)}if(command==="releases"){return try_2({catch:(cause)=>is2(PackageReleasesCommandError)(cause)?cause:new PackageReleasesCommandError({cause,message:is2(BackendManagementConfigurationError)(cause)?cause.message:"Could not configure package releases command"}),try:()=>{const invocation=managementInvocation(options,environment,adapters,"organization");return packageReleasesCommandEffect(invocation.options,{client:invocation.client})}}).pipe(flatten3,tap2((releases)=>sync2(()=>{adapters.writeOutput(`${encodeJson4(releases)}
|
|
3251
3253
|
`)})),asVoid2)}if(command==="diagnostics"){return try_2({catch:(cause)=>is2(PackageDiagnosticsCommandError)(cause)?cause:new PackageDiagnosticsCommandError({cause,message:is2(BackendManagementConfigurationError)(cause)?cause.message:"Could not configure package diagnostics command"}),try:()=>{const invocation=managementInvocation(options,environment,adapters,"organization");return packageDiagnosticsCommandEffect(invocation.options,{client:invocation.client})}}).pipe(flatten3,tap2((diagnostic)=>sync2(()=>{adapters.writeOutput(`${encodeJson4(diagnostic)}
|
|
3252
3254
|
`)})),asVoid2)}return try_2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:is2(BackendManagementConfigurationError)(cause)?cause.message:"Could not configure package release command"}),try:()=>{const invocation=managementInvocation(options,environment,adapters,organizationScopedReleaseCommands.has(command)?"organization":"credential");return packageReleaseCommandEffect([command,...invocation.options],{client:invocation.client,listFiles:flow((directoryPath)=>fileSystem.readDirectory(directoryPath),runNative),readBytes:flow((filePath)=>map4(suspend2(()=>awaitValue8(Bun.file(filePath).arrayBuffer())),(bytes)=>new Uint8Array(bytes)),runNative)})}}).pipe(flatten3,tap2((operationId)=>sync2(()=>{adapters.writeOutput(`Operation ID: ${operationId}
|