@collective-intelligence/cli 0.1.28 → 0.1.30

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.
Files changed (3) hide show
  1. package/README.md +113 -2
  2. package/dist/cli.js +43 -33
  3. package/package.json +8 -8
package/dist/cli.js CHANGED
@@ -195,10 +195,10 @@ ${filtered.slice(0,5).join(`
195
195
  ${err.message}
196
196
  ${err.stack}`,"Broker","error")});this._webSocketServer.on("listening",()=>{fileLog(`WebSocket server is listening on port ${Broker.DEFAULT_WEB_SOCKET_PORT}`,"Broker","info")});this._webSocketServer.on("connection",wsHandler);this._webSocketServer.on("close",(code)=>{fileLog(`WebSocket Server Close with Code ${code}`,"Broker","warn");this._webSocketServer&&this._webSocketServer.close();this._webSocketServer=undefined});server.on("upgrade",(req,socket,head)=>{if(req.url){const{pathname}=parse4(req.url);if(pathname==="/")this._webSocketServer?.handleUpgrade(req,socket,head,(ws)=>{this._webSocketServer?.emit("connection",ws,req)})}});server.listen(Broker.DEFAULT_WEB_SOCKET_PORT)}async _takeAction(action,client){const{kind,payload}=action;if(kind===ActionKind.ADD_PUBLISHER)await this._addPublisher(payload,client);if(kind===ActionKind.UPDATE_PUBLISHER)await this._updatePublisher(payload,client);if(kind===ActionKind.ADD_SUBSCRIBER)await this._addSubscriber(payload,client);if(kind===ActionKind.EXIT_SUBSCRIBER)await this._removeSubscriber(payload,client);if(kind===ActionKind.EXIT_PUBLISHER)await this._removePublisher(payload,client);if(kind===ActionKind.ADD_WEB_CLIENT)await this._addWebClient(payload,client);if(kind===ActionKind.NOTIFY_WEB_CLIENT)await this._notifyWebClient(payload,client);if(kind===ActionKind.FETCH_TYPES)await this._fetchTypes(payload,client);if(kind===ActionKind.ADD_DYNAMIC_REMOTE)this._addDynamicRemote(payload)}async _addPublisher(context,client){const{name,ip,remoteTypeTarPath}=context??{};const identifier=getIdentifier({name,ip});if(this._publisherMap.has(identifier)){fileLog(`[${ActionKind.ADD_PUBLISHER}] ${identifier} has been added, this action will be ignored`,"Broker","warn");return}try{const publisher=new Publisher({name,ip,remoteTypeTarPath,ws:client});this._publisherMap.set(identifier,publisher);fileLog(`[${ActionKind.ADD_PUBLISHER}] ${identifier} Adding Publisher Succeed`,"Broker","info");const tmpSubScribers=this._getTmpSubScribers(identifier);if(tmpSubScribers){fileLog(`[${ActionKind.ADD_PUBLISHER}] consumeTmpSubscriber set ${publisher.name}\u2019s subscribers `,"Broker","info");this._consumeTmpSubScribers(publisher,tmpSubScribers);this._clearTmpSubScriberRelation(identifier)}}catch(err){const msg=error3(err,ActionKind.ADD_PUBLISHER,"Broker");client.send(msg);client.close()}}async _updatePublisher(context,client){const{name,updateMode,updateKind,updateSourcePaths,remoteTypeTarPath,ip}=context??{};const identifier=getIdentifier({name,ip});if(!this._publisherMap.has(identifier)){fileLog(`[${ActionKind.UPDATE_PUBLISHER}] ${identifier} has not been started, this action will be ignored
197
197
  this._publisherMap: ${JSON.stringify(this._publisherMap.entries())}
198
- `,"Broker","warn");return}try{const publisher=this._publisherMap.get(identifier);fileLog(`[${ActionKind.UPDATE_PUBLISHER}] ${identifier} update, and notify subscribers to update`,"Broker","info");if(publisher){publisher.notifySubscribers({remoteTypeTarPath,name,updateMode,updateKind,updateSourcePaths:updateSourcePaths||[]});this._publisherMap.forEach((p)=>{if(p.name===publisher.name)return;const dynamicRemoteInfo=p.dynamicRemoteMap.get(identifier);if(dynamicRemoteInfo){fileLog(`dynamicRemoteInfo: ${JSON.stringify(dynamicRemoteInfo)}, identifier:${identifier} publish: ${p.name}`,"Broker","info");p.fetchRemoteTypes({remoteInfo:dynamicRemoteInfo,once:false})}})}}catch(err){const msg=error3(err,ActionKind.UPDATE_PUBLISHER,"Broker");client.send(msg);client.close()}}async _fetchTypes(context,_client){const{name,ip,remoteInfo}=context??{};const identifier=getIdentifier({name,ip});try{const publisher=this._publisherMap.get(identifier);fileLog(`[${ActionKind.FETCH_TYPES}] ${identifier} fetch types`,"Broker","info");if(publisher)publisher.fetchRemoteTypes({remoteInfo,once:true})}catch(err){fileLog(`[${ActionKind.FETCH_TYPES}] ${identifier} fetch types fail , error info: ${err}`,"Broker","error")}}_addDynamicRemote(context){const{name,ip,remoteInfo,remoteIp}=context??{};const identifier=getIdentifier({name,ip});const publisher=this._publisherMap.get(identifier);const remoteId=getIdentifier({name:remoteInfo.name,ip:remoteIp});fileLog(`[${ActionKind.ADD_DYNAMIC_REMOTE}] identifier:${identifier},publisher: ${publisher.name}, remoteId:${remoteId}`,"Broker","error");if(!publisher||publisher.dynamicRemoteMap.has(remoteId))return;publisher.dynamicRemoteMap.set(remoteId,remoteInfo)}async _addSubscriber(context,client){const{publishers,name:subscriberName}=context??{};publishers.forEach((publisher)=>{const{name,ip}=publisher;const identifier=getIdentifier({name,ip});if(!this._publisherMap.has(identifier)){fileLog(`[${ActionKind.ADD_SUBSCRIBER}]: ${identifier} has not been started, ${subscriberName} will add the relation to tmp shelter`,"Broker","warn");this._addTmpSubScriberRelation({name:getIdentifier({name:context.name,ip:context.ip}),client},publisher);return}try{const registeredPublisher=this._publisherMap.get(identifier);if(registeredPublisher){registeredPublisher.addSubscriber(getIdentifier({name:subscriberName,ip:context.ip}),client);fileLog(`[${ActionKind.ADD_SUBSCRIBER}]: ${identifier} has been started, Adding Subscriber ${subscriberName} Succeed, this.__publisherMap are: ${JSON.stringify(Array.from(this._publisherMap.entries()))}`,"Broker","info");registeredPublisher.notifySubscriber(getIdentifier({name:subscriberName,ip:context.ip}),{updateKind:UpdateKind.UPDATE_TYPE,updateMode:UpdateMode.PASSIVE,updateSourcePaths:[registeredPublisher.name],remoteTypeTarPath:registeredPublisher.remoteTypeTarPath,name:registeredPublisher.name});fileLog(`[${ActionKind.ADD_SUBSCRIBER}]: notifySubscriber Subscriber ${subscriberName}, updateMode: "PASSIVE", updateSourcePaths: ${registeredPublisher.name}`,"Broker","info")}}catch(err){const msg=error3(err,ActionKind.ADD_SUBSCRIBER,"Broker");client.send(msg);client.close()}})}async _removeSubscriber(context,client){const{publishers}=context??{};const subscriberIdentifier=getIdentifier({name:context?.name,ip:context?.ip});publishers.forEach((publisher)=>{const{name,ip}=publisher;const identifier=getIdentifier({name,ip});const registeredPublisher=this._publisherMap.get(identifier);if(!registeredPublisher){fileLog(`[${ActionKind.EXIT_SUBSCRIBER}], ${identifier} does not exit `,"Broker","warn");return}try{fileLog(`[${ActionKind.EXIT_SUBSCRIBER}], ${identifier} will exit `,"Broker","INFO");registeredPublisher.removeSubscriber(subscriberIdentifier);this._clearTmpSubScriberRelation(identifier);if(!registeredPublisher.hasSubscribes)this._publisherMap.delete(identifier);if(!this.hasPublishers)this.exit()}catch(err){const msg=error3(err,ActionKind.EXIT_SUBSCRIBER,"Broker");client.send(msg);client.close()}})}async _removePublisher(context,client){const{name,ip}=context??{};const identifier=getIdentifier({name,ip});const publisher=this._publisherMap.get(identifier);if(!publisher){fileLog(`[${ActionKind.EXIT_PUBLISHER}]: ${identifier}} has not been added, this action will be ingored`,"Broker","warn");return}try{const{subscribers}=publisher;subscribers.forEach((subscriber,subscriberIdentifier)=>{this._addTmpSubScriberRelation({name:subscriberIdentifier,client:subscriber},{name:publisher.name,ip:publisher.ip});fileLog(`[${ActionKind.EXIT_PUBLISHER}]: ${identifier} is removing , subscriber: ${subscriberIdentifier} will be add tmpSubScriberRelation`,"Broker","info")});this._publisherMap.delete(identifier);fileLog(`[${ActionKind.EXIT_PUBLISHER}]: ${identifier} is removed `,"Broker","info");if(!this.hasPublishers){fileLog(`[${ActionKind.EXIT_PUBLISHER}]: _publisherMap is empty, all server will exit `,"Broker","warn");this.exit()}}catch(err){const msg=error3(err,ActionKind.EXIT_PUBLISHER,"Broker");client.send(msg);client.close()}}async _addWebClient(context,client){const{name}=context??{};const identifier=getIdentifier({name});if(this._webClientMap.has(identifier))fileLog(`${identifier}} has been added, this action will override prev WebClient`,"Broker","warn");try{this._webClientMap.set(identifier,client);fileLog(`${identifier} adding WebClient Succeed`,"Broker","info")}catch(err){const msg=error3(err,ActionKind.ADD_WEB_CLIENT,"Broker");client.send(msg);client.close()}}async _notifyWebClient(context,client){const{name,updateMode}=context??{};const identifier=getIdentifier({name});const webClient=this._webClientMap.get(identifier);if(!webClient){fileLog(`[${ActionKind.NOTIFY_WEB_CLIENT}] ${identifier} has not been added, this action will be ignored`,"Broker","warn");return}try{const api=new ReloadWebClientAPI({name,updateMode});webClient.send(JSON.stringify(api));fileLog(`[${ActionKind.NOTIFY_WEB_CLIENT}] Notify ${name} WebClient Succeed`,"Broker","info")}catch(err){const msg=error3(err,ActionKind.NOTIFY_WEB_CLIENT,"Broker");client.send(msg);client.close()}}_addTmpSubScriberRelation(subscriber,publisher){const publisherIdentifier=getIdentifier({name:publisher.name,ip:publisher.ip});const subscriberIdentifier=subscriber.name;const shelter=this._tmpSubscriberShelter.get(publisherIdentifier);if(!shelter){const map=new Map;map.set(subscriberIdentifier,subscriber);this._tmpSubscriberShelter.set(publisherIdentifier,{subscribers:map,timestamp:Date.now()});fileLog(`[AddTmpSubscriberRelation] ${publisherIdentifier}'s subscriber has ${subscriberIdentifier} `,"Broker","info");return}if(shelter.subscribers.get(subscriberIdentifier)){fileLog(`[AddTmpSubscriberRelation] ${publisherIdentifier} and ${subscriberIdentifier} relation has been added`,"Broker","warn");shelter.subscribers.set(subscriberIdentifier,subscriber);shelter.timestamp=Date.now()}else{fileLog(`AddTmpSubscriberLog ${publisherIdentifier}'s shelter has been added, update shelter.subscribers ${subscriberIdentifier}`,"Broker","warn");shelter.subscribers.set(subscriberIdentifier,subscriber)}}_getTmpSubScribers(publisherIdentifier){return this._tmpSubscriberShelter.get(publisherIdentifier)?.subscribers}_consumeTmpSubScribers(publisher,tmpSubScribers){tmpSubScribers.forEach((tmpSubScriber,identifier)=>{fileLog(`notifyTmpSubScribers ${publisher.name} will be add a subscriber: ${identifier} `,"Broker","warn");publisher.addSubscriber(identifier,tmpSubScriber.client);publisher.notifySubscriber(identifier,{updateKind:UpdateKind.UPDATE_TYPE,updateMode:UpdateMode.PASSIVE,updateSourcePaths:[publisher.name],remoteTypeTarPath:publisher.remoteTypeTarPath,name:publisher.name})})}_clearTmpSubScriberRelation(identifier){this._tmpSubscriberShelter.delete(identifier)}_clearTmpSubScriberRelations(){this._tmpSubscriberShelter.clear()}_disconnect(){this._publisherMap.forEach((publisher)=>{publisher.close()})}_setSchedule(){const serverTest=Number(process.env["FEDERATION_SERVER_TEST"]);this._scheduleJob=scheduleCleanup(()=>{this._tmpSubscriberShelter.forEach((tmpSubscriber,identifier)=>{fileLog(` _clearTmpSubScriberRelation ${identifier}, ${Date.now()-tmpSubscriber.timestamp>=(process.env["GARFISH_MODULE_SERVER_TEST"]?serverTest:Broker.DEFAULT_WAITING_TIME)}`,"Broker","info");if(Date.now()-tmpSubscriber.timestamp>=(process.env["FEDERATION_SERVER_TEST"]?serverTest:Broker.DEFAULT_WAITING_TIME))this._clearTmpSubScriberRelation(identifier)})},serverTest)}_clearSchedule(){if(!this._scheduleJob)return;this._scheduleJob.cancel();this._scheduleJob=null}_stopWhenSIGTERMOrSIGINT(){process.on("SIGTERM",()=>{this.exit()});process.on("SIGINT",()=>{this.exit()})}_handleUnexpectedExit(){process.on("unhandledRejection",(error)=>{console.error("Unhandled Rejection Error: ",error);fileLog(`Unhandled Rejection Error: ${error}`,"Broker","fatal");process.exit(1)});process.on("uncaughtException",(error)=>{console.error("Unhandled Exception Error: ",error);fileLog(`Unhandled Rejection Error: ${error}`,"Broker","fatal");process.exit(1)})}async start(){}exit(){const brokerExitLog=new BrokerExitLog;this.broadcast(JSON.stringify(brokerExitLog));this._disconnect();this._clearSchedule();this._clearTmpSubScriberRelations();this._webSocketServer&&this._webSocketServer.close();this._secureWebSocketServer&&this._secureWebSocketServer.close();process.exit(0)}broadcast(message){fileLog(`[broadcast] exit info : ${JSON.stringify(message)}`,"Broker","warn");this._webSocketServer?.clients.forEach((client)=>{client.send(JSON.stringify(message))});this._secureWebSocketServer?.clients.forEach((client)=>{client.send(JSON.stringify(message))})}}});function processFn(options,normalizeSimple,normalizeOptions,fn){const object=(obj)=>{for(const[key,value]of Object.entries(obj)){if(typeof value==="string"){fn(key,normalizeSimple(value,key))}else{fn(key,normalizeOptions(value,key))}}};const array=(items)=>{for(const item of items){if(typeof item==="string"){fn(item,normalizeSimple(item,item))}else if(item&&typeof item==="object"){object(item)}else{throw new Error("Unexpected options format")}}};if(!options){return}else if(Array.isArray(options)){array(options)}else if(typeof options==="object"){object(options)}else{throw new Error("Unexpected options format")}}function parseOptions2(options,normalizeSimple,normalizeOptions){const items=[];processFn(options,normalizeSimple,normalizeOptions,(key,value)=>{items.push([key,value])});return items}var init_utils2=()=>{};var init_dist2=__esm(()=>{init_utils2()});import{copyFile as copyFile3,lstat,mkdir as mkdir2,readdir}from"fs/promises";import{existsSync as existsSync4,readFileSync as readFileSync4}from"fs";import path22 from"path";import path6 from"path";import fs from"fs";function getTypedName(name){return`@types/${name.replace(/^@/,"").replace("/","__")}`}function getPackageRootDir(packageName,context=process.cwd()){if(!packageName){throw new Error("No package name provided.")}const entryFile=__require2.resolve(packageName,{paths:[context]});const entryDir=path6.dirname(entryFile);let fallbackPackageJsonPath=path6.join(entryDir,"package.json");if(!fs.existsSync(fallbackPackageJsonPath)){fallbackPackageJsonPath=null}const match=packageName.match(/^@[^/]+\/(.+)$/);const localName=match?match[1]:packageName;let currentDir=entryDir;while(path6.basename(currentDir)!==localName&&path6.dirname(currentDir)!==currentDir){try{currentDir=path6.dirname(currentDir)}catch(err){if(err.code==="EACCES"){continue}else{throw err}}}if(path6.basename(currentDir)===localName){const candidate=path6.join(currentDir,"package.json");if(fs.existsSync(candidate)){const pkgContent=JSON.parse(fs.readFileSync(candidate,"utf8"));if(pkgContent.name===packageName){return currentDir}}}if(fallbackPackageJsonPath){return entryDir}throw new Error(`Could not find a matching package.json for "${packageName}" and no fallback was found.`)}function resolvePackageJson(packageName,context){try{return __require2.resolve(`${packageName}/package.json`,{paths:[context]})}catch(e){let currentPath=path6.resolve(context);while(true){const candidate=path6.join(currentPath,"node_modules",packageName,"package.json");if(fs.existsSync(candidate)){return candidate}const parentPath=path6.dirname(currentPath);if(parentPath===currentPath){throw new Error(`Could not resolve package.json for "${packageName}".`)}currentPath=parentPath}}}var __require2,ignoredPkgs,isNodeUtils=(pkgJsonPath,importPath)=>{return pkgJsonPath===importPath},ThirdPartyExtractor=class{constructor({destDir,context=process.cwd(),exclude=[]}){this.destDir=destDir;this.context=context;this.pkgs={};this.pattern=/(from|import\()\s*['"]([^'"]+)['"]/g;this.exclude=exclude}addPkgs(pkgName,dirName){if(ignoredPkgs.includes(pkgName)){return}if(this.exclude.some((pattern)=>{if(typeof pattern==="string"){return new RegExp(pattern).test(pkgName)}else{return pattern.test(pkgName)}})){return}this.pkgs[pkgName]=dirName}inferPkgDir(importPath){if(this.pkgs[importPath]){return}if(path22.isAbsolute(importPath)){return}if(importPath.startsWith(".")){return}try{const importEntry=__require2.resolve(importPath,{paths:[this.context]});if(isNodeUtils(importEntry,importPath)){return}const packageDir=getPackageRootDir(importPath,this.context);const pkgJsonPath=path22.join(packageDir,"package.json");const dir=path22.dirname(pkgJsonPath);const pkg=JSON.parse(readFileSync4(pkgJsonPath,"utf-8"));const types=pkg.types||pkg.typings;if(dir===this.context){return}if(types){const typesDir=path22.dirname(path22.resolve(dir,types));this.addPkgs(pkg.name,typesDir);return typesDir}else if(existsSync4(path22.resolve(dir,"index.d.ts"))){this.addPkgs(pkg.name,dir);return dir}else{const typedPkgName=getTypedName(pkg.name);const typedPkgJsonPath=resolvePackageJson(typedPkgName,this.context);const typedDir=path22.dirname(typedPkgJsonPath);readFileSync4(typedPkgJsonPath,"utf-8");this.addPkgs(typedPkgName,typedDir);return typedDir}}catch(_err){return}}collectTypeImports(str){const{pattern}=this;let match;const imports=new Set;while((match=pattern.exec(str))!==null){imports.add(match[2])}return[...imports]}collectPkgs(str){const imports=this.collectTypeImports(str);imports.forEach((importPath)=>{this.inferPkgDir(importPath)})}async copyDts(){if(!Object.keys(this.pkgs).length){return}const ensureDir=async(dir)=>mkdir2(dir,{recursive:true});const copyFiles=async(srcDir,destDir)=>{if(srcDir.startsWith(".")){return}const files=await readdir(srcDir);await Promise.all(files.map(async(file)=>{const fullPath=path22.join(srcDir,file);if(["node_modules","bin"].includes(file)){return}const stats=await lstat(fullPath);if(stats.isDirectory()){const destFullPath=path22.join(destDir,file);await ensureDir(destFullPath);await copyFiles(fullPath,destFullPath)}else{if(fullPath.endsWith(".d.ts")||fullPath.endsWith("package.json")){await copyFile3(fullPath,path22.join(destDir,file))}}}))};await ensureDir(this.destDir);await Promise.all(Object.keys(this.pkgs).map(async(pkgName)=>{const pkgDir=this.pkgs[pkgName];const destDir=path22.resolve(this.destDir,pkgName);await ensureDir(destDir);await copyFiles(pkgDir,destDir)}))}};var init_dist3=__esm(()=>{__require2=((x)=>__require)(function(x){if(true)return __require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});ignoredPkgs=["typescript"]});var require_constants=__commonJS(function(exports,module){module.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var require_errors=__commonJS(function(exports){var errors={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",MAX_OUTPUT_EXCEEDED:"Decompressed data exceeds the declared uncompressed size",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DUPLICATE_ENTRY:"Duplicate entry name {0}",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",ZIP64_VALUE_TOO_LARGE:"Zip64 value exceeds the maximum safe integer",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function E(message){return function(...args){if(args.length){message=message.replace(/\{(\d)\}/g,(_,n)=>args[n]||"")}return new Error("ADM-ZIP: "+message)}}for(const msg of Object.keys(errors)){exports[msg]=E(errors[msg])}});var require_utils=__commonJS(function(exports,module){var fsystem=__require("fs");var pth=__require("path");var Constants=require_constants();var Errors=require_errors();var isWin=typeof process==="object"&&process.platform==="win32";var is_Obj=(obj)=>typeof obj==="object"&&obj!==null;var crcTable=new Uint32Array(256).map((t,c)=>{for(let k=0;k<8;k++){if((c&1)!==0){c=3988292384^c>>>1}else{c>>>=1}}return c>>>0});function Utils(opts){this.sep=pth.sep;this.fs=fsystem;if(is_Obj(opts)){if(is_Obj(opts.fs)&&typeof opts.fs.statSync==="function"){this.fs=opts.fs}}}module.exports=Utils;Utils.prototype.makeDir=function(folder){const self=this;function mkdirSync(fpath){let resolvedPath=fpath.split(self.sep)[0];fpath.split(self.sep).forEach(function(name){if(!name||name.substr(-1,1)===":")return;resolvedPath+=self.sep+name;var stat;try{stat=self.fs.statSync(resolvedPath)}catch(e){if(e.message&&e.message.startsWith("ENOENT")){self.fs.mkdirSync(resolvedPath)}else{throw e}}if(stat&&stat.isFile())throw Errors.FILE_IN_THE_WAY(`"${resolvedPath}"`)})}mkdirSync(folder)};Utils.prototype.writeFileTo=function(path,content,overwrite,attr){const self=this;if(self.fs.existsSync(path)){if(!overwrite)return false;var stat=self.fs.statSync(path);if(stat.isDirectory()){return false}}var folder=pth.dirname(path);if(!self.fs.existsSync(folder)){self.makeDir(folder)}var fd;try{fd=self.fs.openSync(path,"w",438)}catch(e){self.fs.chmodSync(path,438);fd=self.fs.openSync(path,"w",438)}if(fd){try{self.fs.writeSync(fd,content,0,content.length,0)}finally{self.fs.closeSync(fd)}}self.fs.chmodSync(path,attr||438);return true};Utils.prototype.writeFileToAsync=function(path,content,overwrite,attr,callback){if(typeof attr==="function"){callback=attr;attr=undefined}const self=this;self.fs.exists(path,function(exist){if(exist&&!overwrite)return callback(false);self.fs.stat(path,function(err,stat){if(exist&&stat&&stat.isDirectory()){return callback(false)}var folder=pth.dirname(path);self.fs.exists(folder,function(exists){if(!exists){try{self.makeDir(folder)}catch(e){return callback(false)}}const writeToFd=function(fd){self.fs.write(fd,content,0,content.length,0,function(writeErr){self.fs.close(fd,function(){if(writeErr)return callback(false);self.fs.chmod(path,attr||438,function(){callback(true)})})})};self.fs.open(path,"w",438,function(err,fd){if(err){self.fs.chmod(path,438,function(){self.fs.open(path,"w",438,function(retryErr,fd){if(retryErr||!fd)return callback(false);writeToFd(fd)})})}else if(fd){writeToFd(fd)}else{callback(false)}})})})})};Utils.prototype.assertPathSafe=function(root,target){const self=this;if(typeof self.fs.lstatSync!=="function")return;const resolvedRoot=pth.resolve(root);const resolvedTarget=pth.resolve(target);if(resolvedTarget===resolvedRoot)return;const rel=pth.relative(resolvedRoot,resolvedTarget);if(!rel||rel===".."||rel.startsWith(".."+pth.sep)||pth.isAbsolute(rel))return;let cur=resolvedRoot;for(const part of rel.split(pth.sep)){if(!part||part===".")continue;cur=pth.join(cur,part);let stat;try{stat=self.fs.lstatSync(cur)}catch(e){break}if(stat.isSymbolicLink())throw Errors.FILE_IN_THE_WAY(`"${cur}"`)}};Utils.prototype.findFiles=function(path){const self=this;const canLstat=typeof self.fs.lstatSync==="function";const rootReal=self.fs.realpathSync(path);function escapesRoot(p){if(!canLstat)return false;if(!self.fs.lstatSync(p).isSymbolicLink())return false;let real;try{real=self.fs.realpathSync(p)}catch(e){return true}return!(real===rootReal||real.startsWith(rootReal+pth.sep))}function findSync(dir,pattern,recursive,visited){if(typeof pattern==="boolean"){recursive=pattern;pattern=undefined}let files=[];self.fs.readdirSync(dir).forEach(function(file){const path=pth.join(dir,file);if(escapesRoot(path))return;const stat=self.fs.statSync(path);if(!pattern||pattern.test(path)){files.push(pth.normalize(path)+(stat.isDirectory()?self.sep:""))}if(stat.isDirectory()&&recursive){const realDir=self.fs.realpathSync(path);if(!visited.has(realDir)){visited.add(realDir);files=files.concat(findSync(path,pattern,recursive,visited))}}});return files}return findSync(path,undefined,true,new Set([rootReal]))};Utils.prototype.findFilesAsync=function(dir,cb){const self=this;const results=[];let finished=false;const finish=function(err){if(finished)return;finished=true;cb(err,err?undefined:results)};const canLstat=typeof self.fs.lstat==="function";let rootReal=null;const escapesRoot=function(file,cb){if(!canLstat)return cb(null,false);self.fs.lstat(file,function(err,lst){if(err)return cb(err);if(!lst||!lst.isSymbolicLink())return cb(null,false);self.fs.realpath(file,function(err,real){if(err)return cb(null,true);cb(null,!(real===rootReal||real.startsWith(rootReal+pth.sep)))})})};const walk=function(dir,visited,done){self.fs.readdir(dir,function(err,list){if(err)return done(err);let pending=list.length;if(!pending)return done();list.forEach(function(name){const file=pth.join(dir,name);escapesRoot(file,function(err,escapes){if(err)return done(err);if(escapes){if(!--pending)done();return}self.fs.stat(file,function(err,stat){if(err)return done(err);if(!stat){if(!--pending)done();return}results.push(pth.normalize(file)+(stat.isDirectory()?self.sep:""));if(!stat.isDirectory()){if(!--pending)done();return}self.fs.realpath(file,function(err,realDir){if(err)return done(err);if(visited.has(realDir)){if(!--pending)done();return}visited.add(realDir);walk(file,visited,function(err){if(err)return done(err);if(!--pending)done()})})})})})})};self.fs.realpath(dir,function(err,realDir){if(err)return finish(err);rootReal=realDir;walk(dir,new Set([realDir]),finish)})};Utils.prototype.getAttributes=function(){};Utils.prototype.setAttributes=function(){};Utils.crc32update=function(crc,byte){return crcTable[(crc^byte)&255]^crc>>>8};Utils.crc32=function(buf){if(typeof buf==="string"){buf=Buffer.from(buf,"utf8")}let len=buf.length;let crc=~0;for(let off=0;off<len;)crc=Utils.crc32update(crc,buf[off++]);return~crc>>>0};Utils.methodToString=function(method){switch(method){case Constants.STORED:return"STORED ("+method+")";case Constants.DEFLATED:return"DEFLATED ("+method+")";default:return"UNSUPPORTED ("+method+")"}};Utils.canonical=function(path){if(!path)return"";const safeSuffix=pth.posix.normalize("/"+path.split("\\").join("/"));return pth.join(".",safeSuffix)};Utils.zipnamefix=function(path){if(!path)return"";const safeSuffix=pth.posix.normalize("/"+path.split("\\").join("/"));return pth.posix.join(".",safeSuffix)};Utils.findLast=function(arr,callback){if(!Array.isArray(arr))throw new TypeError("arr is not array");const len=arr.length>>>0;for(let i=len-1;i>=0;i--){if(callback(arr[i],i,arr)){return arr[i]}}return};Utils.sanitize=function(prefix,name){prefix=pth.resolve(pth.normalize(prefix));var parts=name.split("/");for(var i=0,l=parts.length;i<l;i++){var path=pth.normalize(pth.join(prefix,parts.slice(i,l).join(pth.sep)));if(path===prefix||path.startsWith(prefix+pth.sep)){return path}}return pth.normalize(pth.join(prefix,pth.basename(name)))};Utils.toBuffer=function toBuffer(input,encoder){if(Buffer.isBuffer(input)){return input}else if(input instanceof Uint8Array){return Buffer.from(input)}else{return typeof input==="string"?encoder(input):Buffer.alloc(0)}};Utils.readBigUInt64LE=function(buffer,index){const lo=buffer.readUInt32LE(index);const hi=buffer.readUInt32LE(index+4);const value=hi*4294967296+lo;if(value>Number.MAX_SAFE_INTEGER){throw Errors.ZIP64_VALUE_TOO_LARGE()}return value};Utils.writeBigUInt64LE=function(buffer,value,index){const lo=value>>>0;const hi=Math.floor(value/4294967296)>>>0;buffer.writeUInt32LE(lo,index);buffer.writeUInt32LE(hi,index+4)};Utils.fromDOS2Date=function(val){return new Date((val>>25&127)+1980,Math.max((val>>21&15)-1,0),Math.max(val>>16&31,1),val>>11&31,val>>5&63,(val&31)<<1)};Utils.fromDate2DOS=function(val){let date=0;let time=0;if(val.getFullYear()>1979){date=(val.getFullYear()-1980&127)<<9|val.getMonth()+1<<5|val.getDate();time=val.getHours()<<11|val.getMinutes()<<5|val.getSeconds()>>1}return date<<16|time};Utils.isWin=isWin;Utils.crcTable=crcTable});var require_fattr=__commonJS(function(exports,module){var pth=__require("path");module.exports=function(path,{fs}){var _path=path||"",_obj=newAttr(),_stat=null;function newAttr(){return{directory:false,readonly:false,hidden:false,executable:false,mtime:0,atime:0}}if(_path&&fs.existsSync(_path)){_stat=fs.statSync(_path);_obj.directory=_stat.isDirectory();_obj.mtime=_stat.mtime;_obj.atime=_stat.atime;_obj.executable=(73&_stat.mode)!==0;_obj.readonly=(128&_stat.mode)===0;_obj.hidden=pth.basename(_path)[0]==="."}else{console.warn("Invalid path: "+_path)}return{get directory(){return _obj.directory},get readOnly(){return _obj.readonly},get hidden(){return _obj.hidden},get mtime(){return _obj.mtime},get atime(){return _obj.atime},get executable(){return _obj.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:_path,isDirectory:_obj.directory,isReadOnly:_obj.readonly,isHidden:_obj.hidden,isExecutable:_obj.executable,mTime:_obj.mtime,aTime:_obj.atime}},toString:function(){return JSON.stringify(this.toJSON(),null,"\t")}}}});var require_decoder=__commonJS(function(exports,module){module.exports={efs:true,encode:(data)=>Buffer.from(data,"utf8"),decode:(data)=>data.toString("utf8")}});var require_util=__commonJS(function(exports,module){module.exports=require_utils();module.exports.Constants=require_constants();module.exports.Errors=require_errors();module.exports.FileAttr=require_fattr();module.exports.decoder=require_decoder()});var require_entryHeader=__commonJS(function(exports,module){var Utils=require_util();var Constants=Utils.Constants;module.exports=function(){var _verMade=20,_version=10,_flags=0,_method=0,_time=0,_crc=0,_compressedSize=0,_size=0,_fnameLen=0,_extraLen=0,_comLen=0,_diskStart=0,_inattr=0,_attr=0,_offset=0;_verMade|=Utils.isWin?2560:768;_flags|=Constants.FLG_EFS;const _localHeader={extraLen:0};const uint32=(val)=>Math.max(0,val)>>>0;const uint16=(val)=>Math.max(0,val)&65535;const uint8=(val)=>Math.max(0,val)&255;_time=Utils.fromDate2DOS(new Date);return{get made(){return _verMade},set made(val){_verMade=val},get version(){return _version},set version(val){_version=val},get flags(){return _flags},set flags(val){_flags=val},get flags_efs(){return(_flags&Constants.FLG_EFS)>0},set flags_efs(val){if(val){_flags|=Constants.FLG_EFS}else{_flags&=~Constants.FLG_EFS}},get flags_desc(){return(_flags&Constants.FLG_DESC)>0},set flags_desc(val){if(val){_flags|=Constants.FLG_DESC}else{_flags&=~Constants.FLG_DESC}},get method(){return _method},set method(val){switch(val){case Constants.STORED:this.version=10;break;case Constants.DEFLATED:default:this.version=20}_method=val},get time(){return Utils.fromDOS2Date(this.timeval)},set time(val){val=new Date(val);this.timeval=Utils.fromDate2DOS(val)},get timeval(){return _time},set timeval(val){_time=uint32(val)},get timeHighByte(){return uint8(_time>>>8)},get crc(){return _crc},set crc(val){_crc=uint32(val)},get compressedSize(){return _compressedSize},set compressedSize(val){_compressedSize=uint32(val)},get size(){return _size},set size(val){_size=uint32(val)},get fileNameLength(){return _fnameLen},set fileNameLength(val){_fnameLen=val},get extraLength(){return _extraLen},set extraLength(val){_extraLen=val},get extraLocalLength(){return _localHeader.extraLen},set extraLocalLength(val){_localHeader.extraLen=val},get commentLength(){return _comLen},set commentLength(val){_comLen=val},get diskNumStart(){return _diskStart},set diskNumStart(val){_diskStart=uint32(val)},get inAttr(){return _inattr},set inAttr(val){_inattr=uint32(val)},get attr(){return _attr},set attr(val){_attr=uint32(val)},get fileAttr(){return(_attr||0)>>16&511},get offset(){return _offset},set offset(val){_offset=uint32(val)},get encrypted(){return(_flags&Constants.FLG_ENC)===Constants.FLG_ENC},get centralHeaderSize(){return Constants.CENHDR+_fnameLen+_extraLen+_comLen},get realDataOffset(){return _offset+Constants.LOCHDR+_localHeader.fnameLen+_localHeader.extraLen},get localHeader(){return _localHeader},loadLocalHeaderFromBinary:function(input){if(_offset<0||_offset+Constants.LOCHDR>input.length){throw Utils.Errors.INVALID_LOC()}var data=input.slice(_offset,_offset+Constants.LOCHDR);if(data.readUInt32LE(0)!==Constants.LOCSIG){throw Utils.Errors.INVALID_LOC()}_localHeader.version=data.readUInt16LE(Constants.LOCVER);_localHeader.flags=data.readUInt16LE(Constants.LOCFLG);_localHeader.flags_desc=(_localHeader.flags&Constants.FLG_DESC)>0;_localHeader.method=data.readUInt16LE(Constants.LOCHOW);_localHeader.time=data.readUInt32LE(Constants.LOCTIM);_localHeader.crc=data.readUInt32LE(Constants.LOCCRC);_localHeader.compressedSize=data.readUInt32LE(Constants.LOCSIZ);_localHeader.size=data.readUInt32LE(Constants.LOCLEN);_localHeader.fnameLen=data.readUInt16LE(Constants.LOCNAM);_localHeader.extraLen=data.readUInt16LE(Constants.LOCEXT);const extraStart=_offset+Constants.LOCHDR+_localHeader.fnameLen;const extraEnd=extraStart+_localHeader.extraLen;return input.slice(extraStart,extraEnd)},loadFromBinary:function(data){if(data.length!==Constants.CENHDR||data.readUInt32LE(0)!==Constants.CENSIG){throw Utils.Errors.INVALID_CEN()}_verMade=data.readUInt16LE(Constants.CENVEM);_version=data.readUInt16LE(Constants.CENVER);_flags=data.readUInt16LE(Constants.CENFLG);_method=data.readUInt16LE(Constants.CENHOW);_time=data.readUInt32LE(Constants.CENTIM);_crc=data.readUInt32LE(Constants.CENCRC);_compressedSize=data.readUInt32LE(Constants.CENSIZ);_size=data.readUInt32LE(Constants.CENLEN);_fnameLen=data.readUInt16LE(Constants.CENNAM);_extraLen=data.readUInt16LE(Constants.CENEXT);_comLen=data.readUInt16LE(Constants.CENCOM);_diskStart=data.readUInt16LE(Constants.CENDSK);_inattr=data.readUInt16LE(Constants.CENATT);_attr=data.readUInt32LE(Constants.CENATX);_offset=data.readUInt32LE(Constants.CENOFF)},localHeaderToBinary:function(){var data=Buffer.alloc(Constants.LOCHDR);data.writeUInt32LE(Constants.LOCSIG,0);data.writeUInt16LE(_version,Constants.LOCVER);data.writeUInt16LE(_flags&~Constants.FLG_DESC,Constants.LOCFLG);data.writeUInt16LE(_method,Constants.LOCHOW);data.writeUInt32LE(_time,Constants.LOCTIM);data.writeUInt32LE(_crc,Constants.LOCCRC);data.writeUInt32LE(_compressedSize,Constants.LOCSIZ);data.writeUInt32LE(_size,Constants.LOCLEN);data.writeUInt16LE(_fnameLen,Constants.LOCNAM);data.writeUInt16LE(_localHeader.extraLen,Constants.LOCEXT);return data},centralHeaderToBinary:function(){var data=Buffer.alloc(Constants.CENHDR+_fnameLen+_extraLen+_comLen);data.writeUInt32LE(Constants.CENSIG,0);data.writeUInt16LE(_verMade,Constants.CENVEM);data.writeUInt16LE(_version,Constants.CENVER);data.writeUInt16LE(_flags&~Constants.FLG_DESC,Constants.CENFLG);data.writeUInt16LE(_method,Constants.CENHOW);data.writeUInt32LE(_time,Constants.CENTIM);data.writeUInt32LE(_crc,Constants.CENCRC);data.writeUInt32LE(_compressedSize,Constants.CENSIZ);data.writeUInt32LE(_size,Constants.CENLEN);data.writeUInt16LE(_fnameLen,Constants.CENNAM);data.writeUInt16LE(_extraLen,Constants.CENEXT);data.writeUInt16LE(_comLen,Constants.CENCOM);data.writeUInt16LE(_diskStart,Constants.CENDSK);data.writeUInt16LE(_inattr,Constants.CENATT);data.writeUInt32LE(_attr,Constants.CENATX);data.writeUInt32LE(_offset,Constants.CENOFF);return data},toJSON:function(){const bytes=function(nr){return nr+" bytes"};return{made:_verMade,version:_version,flags:_flags,method:Utils.methodToString(_method),time:this.time,crc:"0x"+_crc.toString(16).toUpperCase(),compressedSize:bytes(_compressedSize),size:bytes(_size),fileNameLength:bytes(_fnameLen),extraLength:bytes(_extraLen),commentLength:bytes(_comLen),diskNumStart:_diskStart,inAttr:_inattr,attr:_attr,offset:_offset,centralHeaderSize:bytes(Constants.CENHDR+_fnameLen+_extraLen+_comLen)}},toString:function(){return JSON.stringify(this.toJSON(),null,"\t")}}}});var require_mainHeader=__commonJS(function(exports,module){var Utils=require_util();var Constants=Utils.Constants;module.exports=function(){var _volumeEntries=0,_totalEntries=0,_size=0,_offset=0,_commentLength=0;const needsZip64=()=>_volumeEntries>Constants.EF_ZIP64_OR_16||_totalEntries>Constants.EF_ZIP64_OR_16||_size>Constants.EF_ZIP64_OR_32||_offset>Constants.EF_ZIP64_OR_32;return{get diskEntries(){return _volumeEntries},set diskEntries(val){_volumeEntries=_totalEntries=val},get totalEntries(){return _totalEntries},set totalEntries(val){_totalEntries=_volumeEntries=val},get size(){return _size},set size(val){_size=val},get offset(){return _offset},set offset(val){_offset=val},get commentLength(){return _commentLength},set commentLength(val){_commentLength=val},get mainHeaderSize(){return(needsZip64()?Constants.ZIP64HDR+Constants.END64HDR:0)+Constants.ENDHDR+_commentLength},loadFromBinary:function(data){if((data.length!==Constants.ENDHDR||data.readUInt32LE(0)!==Constants.ENDSIG)&&(data.length<Constants.ZIP64HDR||data.readUInt32LE(0)!==Constants.ZIP64SIG)){throw Utils.Errors.INVALID_END()}if(data.readUInt32LE(0)===Constants.ENDSIG){_volumeEntries=data.readUInt16LE(Constants.ENDSUB);_totalEntries=data.readUInt16LE(Constants.ENDTOT);_size=data.readUInt32LE(Constants.ENDSIZ);_offset=data.readUInt32LE(Constants.ENDOFF);_commentLength=data.readUInt16LE(Constants.ENDCOM)}else{_volumeEntries=Utils.readBigUInt64LE(data,Constants.ZIP64SUB);_totalEntries=Utils.readBigUInt64LE(data,Constants.ZIP64TOT);_size=Utils.readBigUInt64LE(data,Constants.ZIP64SIZB);_offset=Utils.readBigUInt64LE(data,Constants.ZIP64OFF);_commentLength=0}},toBinary:function(){if(!needsZip64()){var b=Buffer.alloc(Constants.ENDHDR+_commentLength);b.writeUInt32LE(Constants.ENDSIG,0);b.writeUInt32LE(0,4);b.writeUInt16LE(_volumeEntries,Constants.ENDSUB);b.writeUInt16LE(_totalEntries,Constants.ENDTOT);b.writeUInt32LE(_size,Constants.ENDSIZ);b.writeUInt32LE(_offset,Constants.ENDOFF);b.writeUInt16LE(_commentLength,Constants.ENDCOM);b.fill(" ",Constants.ENDHDR);return b}var b=Buffer.alloc(this.mainHeaderSize);let offset=0;b.writeUInt32LE(Constants.ZIP64SIG,offset);Utils.writeBigUInt64LE(b,Constants.ZIP64HDR-Constants.ZIP64LEAD,offset+Constants.ZIP64SIZE);b.writeUInt16LE(45,offset+Constants.ZIP64VEM);b.writeUInt16LE(45,offset+Constants.ZIP64VER);b.writeUInt32LE(0,offset+Constants.ZIP64DSK);b.writeUInt32LE(0,offset+Constants.ZIP64DSKDIR);Utils.writeBigUInt64LE(b,_volumeEntries,offset+Constants.ZIP64SUB);Utils.writeBigUInt64LE(b,_totalEntries,offset+Constants.ZIP64TOT);Utils.writeBigUInt64LE(b,_size,offset+Constants.ZIP64SIZB);Utils.writeBigUInt64LE(b,_offset,offset+Constants.ZIP64OFF);const zip64EndOffset=_offset+_size;offset+=Constants.ZIP64HDR;b.writeUInt32LE(Constants.END64SIG,offset);b.writeUInt32LE(0,offset+Constants.END64START);Utils.writeBigUInt64LE(b,zip64EndOffset,offset+Constants.END64OFF);b.writeUInt32LE(1,offset+Constants.END64NUMDISKS);offset+=Constants.END64HDR;b.writeUInt32LE(Constants.ENDSIG,offset);b.writeUInt32LE(0,offset+4);b.writeUInt16LE(Math.min(_volumeEntries,Constants.EF_ZIP64_OR_16),offset+Constants.ENDSUB);b.writeUInt16LE(Math.min(_totalEntries,Constants.EF_ZIP64_OR_16),offset+Constants.ENDTOT);b.writeUInt32LE(Math.min(_size,Constants.EF_ZIP64_OR_32),offset+Constants.ENDSIZ);b.writeUInt32LE(Math.min(_offset,Constants.EF_ZIP64_OR_32),offset+Constants.ENDOFF);b.writeUInt16LE(_commentLength,offset+Constants.ENDCOM);b.fill(" ",offset+Constants.ENDHDR);return b},toJSON:function(){const offset=function(nr,len){let offs=nr.toString(16).toUpperCase();while(offs.length<len)offs="0"+offs;return"0x"+offs};return{diskEntries:_volumeEntries,totalEntries:_totalEntries,size:_size+" bytes",offset:offset(_offset,4),commentLength:_commentLength}},toString:function(){return JSON.stringify(this.toJSON(),null,"\t")}}}});var require_headers=__commonJS(function(exports){exports.EntryHeader=require_entryHeader();exports.MainHeader=require_mainHeader()});var require_deflater=__commonJS(function(exports,module){module.exports=function(inbuf){var zlib=__require("zlib");var opts={chunkSize:(parseInt(inbuf.length/1024)+1)*1024};return{deflate:function(){return zlib.deflateRawSync(inbuf,opts)},deflateAsync:function(callback){var tmp=zlib.createDeflateRaw(opts),parts=[],total=0;tmp.on("data",function(data){parts.push(data);total+=data.length});tmp.on("end",function(){var buf=Buffer.alloc(total),written=0;buf.fill(0);for(var i=0;i<parts.length;i++){var part=parts[i];part.copy(buf,written);written+=part.length}callback&&callback(buf)});tmp.end(inbuf)}}}});var require_inflater=__commonJS(function(exports,module){var version=+(process?.versions?.node??"").split(".")[0]||0;var Errors=require_errors();module.exports=function(inbuf,expectedLength){var zlib=__require("zlib");const maxOutputLength=expectedLength>0?expectedLength:1;const option=version>=15?{maxOutputLength}:{};return{inflate:function(){return zlib.inflateRawSync(inbuf,option)},inflateAsync:function(callback){var tmp=zlib.createInflateRaw(option),parts=[],total=0,done=false;const fail=function(err){if(done)return;done=true;tmp.destroy();callback&&callback(Buffer.alloc(0),err)};tmp.on("error",function(err){fail(err)});tmp.on("data",function(data){if(done)return;total+=data.length;if(total>maxOutputLength){return fail(Errors.MAX_OUTPUT_EXCEEDED())}parts.push(data)});tmp.on("end",function(){if(done)return;done=true;var buf=Buffer.alloc(total),written=0;buf.fill(0);for(var i=0;i<parts.length;i++){var part=parts[i];part.copy(buf,written);written+=part.length}callback&&callback(buf)});tmp.end(inbuf)}}}});var require_zipcrypto=__commonJS(function(exports,module){var{randomFillSync}=__require("crypto");var Errors=require_errors();var crctable=new Uint32Array(256).map((t,crc)=>{for(let j=0;j<8;j++){if((crc&1)!==0){crc=crc>>>1^3988292384}else{crc>>>=1}}return crc>>>0});var uMul=(a,b)=>Math.imul(a,b)>>>0;var crc32update=(pCrc32,bval)=>{return crctable[(pCrc32^bval)&255]^pCrc32>>>8};var genSalt=()=>{if(typeof randomFillSync==="function"){return randomFillSync(Buffer.alloc(12))}else{return genSalt.node()}};genSalt.node=()=>{const salt=Buffer.alloc(12);const len=salt.length;for(let i=0;i<len;i++)salt[i]=Math.random()*256&255;return salt};var config={genSalt};function Initkeys(pw){const pass=Buffer.isBuffer(pw)?pw:Buffer.from(pw);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let i=0;i<pass.length;i++){this.updateKeys(pass[i])}}Initkeys.prototype.updateKeys=function(byteValue){const keys=this.keys;keys[0]=crc32update(keys[0],byteValue);keys[1]+=keys[0]&255;keys[1]=uMul(keys[1],134775813)+1;keys[2]=crc32update(keys[2],keys[1]>>>24);return byteValue};Initkeys.prototype.next=function(){const k=(this.keys[2]|2)>>>0;return uMul(k,k^1)>>8&255};function make_decrypter(pwd){const keys=new Initkeys(pwd);return function(data){const result=Buffer.alloc(data.length);let pos=0;for(let c of data){result[pos++]=keys.updateKeys(c^keys.next())}return result}}function make_encrypter(pwd){const keys=new Initkeys(pwd);return function(data,result,pos=0){if(!result)result=Buffer.alloc(data.length);for(let c of data){const k=keys.next();result[pos++]=c^k;keys.updateKeys(c)}return result}}function decrypt(data,header,pwd){if(!data||!Buffer.isBuffer(data)||data.length<12){return Buffer.alloc(0)}const decrypter=make_decrypter(pwd);const salt=decrypter(data.slice(0,12));const verifyByte=(header.flags&8)===8?header.timeHighByte:header.crc>>>24;if(salt[11]!==verifyByte){throw Errors.WRONG_PASSWORD()}return decrypter(data.slice(12))}function _salter(data){if(Buffer.isBuffer(data)&&data.length>=12){config.genSalt=function(){return data.slice(0,12)}}else if(data==="node"){config.genSalt=genSalt.node}else{config.genSalt=genSalt}}function encrypt(data,header,pwd,oldlike=false){if(data==null)data=Buffer.alloc(0);if(!Buffer.isBuffer(data))data=Buffer.from(data.toString());const encrypter=make_encrypter(pwd);const salt=config.genSalt();salt[11]=header.crc>>>24&255;if(oldlike)salt[10]=header.crc>>>16&255;const result=Buffer.alloc(data.length+12);encrypter(salt,result);return encrypter(data,result,12)}module.exports={decrypt,encrypt,_salter}});var require_methods=__commonJS(function(exports){exports.Deflater=require_deflater();exports.Inflater=require_inflater();exports.ZipCrypto=require_zipcrypto()});var require_zipEntry=__commonJS(function(exports,module){var Utils=require_util();var Headers2=require_headers();var Constants=Utils.Constants;var Methods=require_methods();module.exports=function(options,input){var _centralHeader=new Headers2.EntryHeader,_entryName=Buffer.alloc(0),_comment=Buffer.alloc(0),_isDirectory=false,uncompressedData=null,_extra=Buffer.alloc(0),_extralocal=Buffer.alloc(0),_efs=true;const opts=options;const decoder=typeof opts.decoder==="object"?opts.decoder:Utils.decoder;_efs=decoder.hasOwnProperty("efs")?decoder.efs:false;function getCompressedDataFromZip(){if(!input||!(input instanceof Uint8Array)){return Buffer.alloc(0)}_extralocal=_centralHeader.loadLocalHeaderFromBinary(input);const dataOffset=_centralHeader.realDataOffset;const dataEnd=dataOffset+_centralHeader.compressedSize;if(dataOffset<0||dataEnd<dataOffset||dataEnd>input.length){throw Utils.Errors.INVALID_LOC()}return input.slice(dataOffset,dataEnd)}function crc32OK(data){const expectedCrc=_centralHeader.flags_desc||_centralHeader.localHeader.flags_desc?_centralHeader.crc:_centralHeader.localHeader.crc;return Utils.crc32(data)===expectedCrc}function decompress(async,callback,pass){if(typeof callback==="undefined"&&typeof async==="string"){pass=async;async=undefined}if(_isDirectory){if(async&&callback){callback(Buffer.alloc(0),Utils.Errors.DIRECTORY_CONTENT_ERROR())}return Buffer.alloc(0)}var compressedData;try{compressedData=getCompressedDataFromZip();if(compressedData.length===0){if(async&&callback)callback(compressedData);return compressedData}if(_centralHeader.encrypted){if(typeof pass!=="string"&&!Buffer.isBuffer(pass)){throw Utils.Errors.INVALID_PASS_PARAM()}compressedData=Methods.ZipCrypto.decrypt(compressedData,_centralHeader,pass)}}catch(err){if(async&&callback){callback(Buffer.alloc(0),err);return Buffer.alloc(0)}throw err}var data;switch(_centralHeader.method){case Utils.Constants.STORED:data=Buffer.alloc(compressedData.length);compressedData.copy(data);if(!crc32OK(data)){if(async&&callback)callback(data,Utils.Errors.BAD_CRC());throw Utils.Errors.BAD_CRC()}else{if(async&&callback)callback(data);return data}case Utils.Constants.DEFLATED:var inflater=new Methods.Inflater(compressedData,_centralHeader.size);if(!async){data=inflater.inflate();if(!crc32OK(data)){throw Utils.Errors.BAD_CRC(`"${decoder.decode(_entryName)}"`)}return data}else{inflater.inflateAsync(function(result,err){if(!callback)return;if(err){callback(Buffer.alloc(0),err)}else if(!crc32OK(result)){callback(result,Utils.Errors.BAD_CRC())}else{callback(result)}})}break;default:if(async&&callback)callback(Buffer.alloc(0),Utils.Errors.UNKNOWN_METHOD());throw Utils.Errors.UNKNOWN_METHOD()}}function compress(async,callback){if((!uncompressedData||!uncompressedData.length)&&Buffer.isBuffer(input)){if(async&&callback)callback(getCompressedDataFromZip());return getCompressedDataFromZip()}if(uncompressedData.length&&!_isDirectory){var compressedData;switch(_centralHeader.method){case Utils.Constants.STORED:_centralHeader.compressedSize=_centralHeader.size;compressedData=Buffer.alloc(uncompressedData.length);uncompressedData.copy(compressedData);if(async&&callback)callback(compressedData);return compressedData;default:case Utils.Constants.DEFLATED:var deflater=new Methods.Deflater(uncompressedData);if(!async){var deflated=deflater.deflate();_centralHeader.compressedSize=deflated.length;return deflated}else{deflater.deflateAsync(function(data){compressedData=Buffer.alloc(data.length);_centralHeader.compressedSize=data.length;data.copy(compressedData);callback&&callback(compressedData)})}deflater=null;break}}else if(async&&callback){callback(Buffer.alloc(0))}else{return Buffer.alloc(0)}}function readUInt64LE(buffer,offset){return Utils.readBigUInt64LE(buffer,offset)}function parseExtra(data){try{var offset=0;var signature,size,part;while(offset+4<data.length){signature=data.readUInt16LE(offset);offset+=2;size=data.readUInt16LE(offset);offset+=2;part=data.slice(offset,offset+size);offset+=size;if(Constants.ID_ZIP64===signature){parseZip64ExtendedInformation(part)}}}catch(error){throw Utils.Errors.EXTRA_FIELD_PARSE_ERROR()}}function parseZip64ExtendedInformation(data){var size,compressedSize,offset,diskNumStart;if(data.length>=Constants.EF_ZIP64_SCOMP){size=readUInt64LE(data,Constants.EF_ZIP64_SUNCOMP);if(_centralHeader.size===Constants.EF_ZIP64_OR_32){_centralHeader.size=size}}if(data.length>=Constants.EF_ZIP64_RHO){compressedSize=readUInt64LE(data,Constants.EF_ZIP64_SCOMP);if(_centralHeader.compressedSize===Constants.EF_ZIP64_OR_32){_centralHeader.compressedSize=compressedSize}}if(data.length>=Constants.EF_ZIP64_DSN){offset=readUInt64LE(data,Constants.EF_ZIP64_RHO);if(_centralHeader.offset===Constants.EF_ZIP64_OR_32){_centralHeader.offset=offset}}if(data.length>=Constants.EF_ZIP64_DSN+4){diskNumStart=data.readUInt32LE(Constants.EF_ZIP64_DSN);if(_centralHeader.diskNumStart===Constants.EF_ZIP64_OR_16){_centralHeader.diskNumStart=diskNumStart}}}return{get entryName(){return decoder.decode(_entryName)},get rawEntryName(){return _entryName},set entryName(val){_entryName=Utils.toBuffer(val,decoder.encode);var lastChar=_entryName[_entryName.length-1];_isDirectory=lastChar===47||lastChar===92;_centralHeader.fileNameLength=_entryName.length},get efs(){if(typeof _efs==="function"){return _efs(this.entryName)}else{return _efs}},get extra(){return _extra},set extra(val){_extra=val;_centralHeader.extraLength=val.length;parseExtra(val)},get comment(){return decoder.decode(_comment)},set comment(val){_comment=Utils.toBuffer(val,decoder.encode);_centralHeader.commentLength=_comment.length;if(_comment.length>65535)throw Utils.Errors.COMMENT_TOO_LONG()},get name(){const n=decoder.decode(_entryName);return _isDirectory?n.replace(/[/\\]$/,"").split("/").pop():n.split("/").pop()},get isDirectory(){return _isDirectory},getCompressedData:function(){return compress(false,null)},getCompressedDataAsync:function(callback){compress(true,callback)},setData:function(value){uncompressedData=Utils.toBuffer(value,Utils.decoder.encode);if(!_isDirectory&&uncompressedData.length){_centralHeader.size=uncompressedData.length;_centralHeader.method=Utils.Constants.DEFLATED;_centralHeader.crc=Utils.crc32(value);_centralHeader.changed=true}else{_centralHeader.method=Utils.Constants.STORED}},getData:function(pass){if(_centralHeader.changed){return uncompressedData}else{return decompress(false,null,pass)}},getDataAsync:function(callback,pass){if(_centralHeader.changed){callback(uncompressedData)}else{decompress(true,callback,pass)}},set attr(attr){_centralHeader.attr=attr},get attr(){return _centralHeader.attr},set header(data){_centralHeader.loadFromBinary(data)},get header(){return _centralHeader},packCentralHeader:function(){_centralHeader.flags_efs=this.efs;_centralHeader.extraLength=_extra.length;var header=_centralHeader.centralHeaderToBinary();var addpos=Utils.Constants.CENHDR;_entryName.copy(header,addpos);addpos+=_entryName.length;_extra.copy(header,addpos);addpos+=_centralHeader.extraLength;_comment.copy(header,addpos);return header},packLocalHeader:function(){let addpos=0;_centralHeader.flags_efs=this.efs;_centralHeader.extraLocalLength=_extralocal.length;const localHeaderBuf=_centralHeader.localHeaderToBinary();const localHeader=Buffer.alloc(localHeaderBuf.length+_entryName.length+_centralHeader.extraLocalLength);localHeaderBuf.copy(localHeader,addpos);addpos+=localHeaderBuf.length;_entryName.copy(localHeader,addpos);addpos+=_entryName.length;_extralocal.copy(localHeader,addpos);addpos+=_extralocal.length;return localHeader},toJSON:function(){const bytes=function(nr){return"<"+(nr&&nr.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:_centralHeader.toJSON(),compressedData:bytes(input),data:bytes(uncompressedData)}},toString:function(){return JSON.stringify(this.toJSON(),null,"\t")}}}});var require_zipFile=__commonJS(function(exports,module){var ZipEntry=require_zipEntry();var Headers2=require_headers();var Utils=require_util();module.exports=function(inBuffer,options){var entryList=[],entryTable=Object.create(null),_comment=Buffer.alloc(0),mainHeader=new Headers2.MainHeader,loadedEntries=false;var password=null;const temporary=new Set;const opts=options;const{noSort,decoder}=opts;if(inBuffer){readMainHeader(opts.readEntries)}else{loadedEntries=true}function makeTemporaryFolders(){const foldersList=new Set;for(const elem of Object.keys(entryTable)){const elements=elem.split("/");elements.pop();if(!elements.length)continue;for(let i=0;i<elements.length;i++){const sub=elements.slice(0,i+1).join("/")+"/";foldersList.add(sub)}}for(const elem of foldersList){if(!(elem in entryTable)){const tempfolder=new ZipEntry(opts);tempfolder.entryName=elem;tempfolder.attr=16;tempfolder.temporary=true;entryList.push(tempfolder);entryTable[tempfolder.entryName]=tempfolder;temporary.add(tempfolder)}}}function readEntries(){loadedEntries=true;entryTable=Object.create(null);if(mainHeader.diskEntries>(inBuffer.length-mainHeader.offset)/Utils.Constants.CENHDR){throw Utils.Errors.DISK_ENTRY_TOO_LARGE()}entryList=new Array(mainHeader.diskEntries);var index=mainHeader.offset;for(var i=0;i<entryList.length;i++){var tmp=index,entry=new ZipEntry(opts,inBuffer);entry.header=inBuffer.slice(tmp,tmp+=Utils.Constants.CENHDR);entry.entryName=inBuffer.slice(tmp,tmp+=entry.header.fileNameLength);if(entry.header.extraLength){entry.extra=inBuffer.slice(tmp,tmp+=entry.header.extraLength)}if(entry.header.commentLength)entry.comment=inBuffer.slice(tmp,tmp+entry.header.commentLength);index+=entry.header.centralHeaderSize;if(entry.entryName in entryTable){throw Utils.Errors.DUPLICATE_ENTRY(`"${entry.entryName}"`)}entryList[i]=entry;entryTable[entry.entryName]=entry}temporary.clear();makeTemporaryFolders()}function readMainHeader(readNow){var i=inBuffer.length-Utils.Constants.ENDHDR,max=Math.max(0,i-65535),n=max,endStart=inBuffer.length,endOffset=-1,commentEnd=0;const trailingSpace=typeof opts.trailingSpace==="boolean"?opts.trailingSpace:false;if(trailingSpace)max=0;for(i;i>=n;i--){if(inBuffer[i]!==80)continue;if(inBuffer.readUInt32LE(i)===Utils.Constants.ENDSIG){endOffset=i;commentEnd=i;endStart=i+Utils.Constants.ENDHDR;n=i-Utils.Constants.END64HDR;continue}if(inBuffer.readUInt32LE(i)===Utils.Constants.END64SIG){n=max;continue}if(inBuffer.readUInt32LE(i)===Utils.Constants.ZIP64SIG){endOffset=i;endStart=i+Utils.readBigUInt64LE(inBuffer,i+Utils.Constants.ZIP64SIZE)+Utils.Constants.ZIP64LEAD;break}}if(endOffset==-1)throw Utils.Errors.INVALID_FORMAT();mainHeader.loadFromBinary(inBuffer.slice(endOffset,endStart));if(mainHeader.commentLength){_comment=inBuffer.slice(commentEnd+Utils.Constants.ENDHDR)}if(readNow)readEntries()}function sortEntries(){if(entryList.length>1&&!noSort){entryList=entryList.map((entry)=>({entry,key:entry.entryName.toLowerCase()})).sort((a,b)=>a.key.localeCompare(b.key)).map((pair)=>pair.entry)}}return{get entries(){if(!loadedEntries){readEntries()}return entryList.filter((e)=>!temporary.has(e))},get comment(){return decoder.decode(_comment)},set comment(val){_comment=Utils.toBuffer(val,decoder.encode);mainHeader.commentLength=_comment.length},getEntryCount:function(){if(!loadedEntries){return mainHeader.diskEntries}return entryList.length},forEach:function(callback){this.entries.forEach(callback)},getEntry:function(entryName){if(!loadedEntries){readEntries()}return entryTable[entryName]||null},setEntry:function(entry){if(!loadedEntries){readEntries()}entryList.push(entry);entryTable[entry.entryName]=entry;mainHeader.totalEntries=entryList.length},deleteFile:function(entryName,withsubfolders=true){if(!loadedEntries){readEntries()}const entry=entryTable[entryName];const list=this.getEntryChildren(entry,withsubfolders).map((child)=>child.entryName);list.forEach(this.deleteEntry)},deleteEntry:function(entryName){if(!loadedEntries){readEntries()}const entry=entryTable[entryName];const index=entryList.indexOf(entry);if(index>=0){entryList.splice(index,1);delete entryTable[entryName];mainHeader.totalEntries=entryList.length}},getEntryChildren:function(entry,subfolders=true){if(!loadedEntries){readEntries()}if(typeof entry==="object"){if(entry.isDirectory&&subfolders){const list=[];const name=entry.entryName;for(const zipEntry of entryList){if(zipEntry.entryName.startsWith(name)){list.push(zipEntry)}}return list}else{return[entry]}}return[]},getChildCount:function(entry){if(entry&&entry.isDirectory){const list=this.getEntryChildren(entry);return list.includes(entry)?list.length-1:list.length}return 0},compressToBuffer:function(){if(!loadedEntries){readEntries()}sortEntries();const dataBlock=[];const headerBlocks=[];let totalSize=0;let dindex=0;mainHeader.size=0;mainHeader.offset=0;let totalEntries=0;for(const entry of this.entries){const compressedData=entry.getCompressedData();entry.header.offset=dindex;const localHeader=entry.packLocalHeader();const dataLength=localHeader.length+compressedData.length;dindex+=dataLength;dataBlock.push(localHeader);dataBlock.push(compressedData);const centralHeader=entry.packCentralHeader();headerBlocks.push(centralHeader);mainHeader.size+=centralHeader.length;totalSize+=dataLength+centralHeader.length;totalEntries++}totalSize+=mainHeader.mainHeaderSize;mainHeader.offset=dindex;mainHeader.totalEntries=totalEntries;dindex=0;const outBuffer=Buffer.alloc(totalSize);for(const content of dataBlock){content.copy(outBuffer,dindex);dindex+=content.length}for(const content of headerBlocks){content.copy(outBuffer,dindex);dindex+=content.length}const mh=mainHeader.toBinary();if(_comment){_comment.copy(mh,mh.length-_comment.length)}mh.copy(outBuffer,dindex);inBuffer=outBuffer;loadedEntries=false;return outBuffer},toAsyncBuffer:function(onSuccess,onFail,onItemStart,onItemEnd){try{if(!loadedEntries){readEntries()}sortEntries();const dataBlock=[];const centralHeaders=[];let totalSize=0;let dindex=0;let totalEntries=0;mainHeader.size=0;mainHeader.offset=0;const compress2Buffer=function(entryLists){if(entryLists.length>0){const entry=entryLists.shift();const name=entry.entryName+entry.extra.toString();if(onItemStart)onItemStart(name);entry.getCompressedDataAsync(function(compressedData){if(onItemEnd)onItemEnd(name);entry.header.offset=dindex;const localHeader=entry.packLocalHeader();const dataLength=localHeader.length+compressedData.length;dindex+=dataLength;dataBlock.push(localHeader);dataBlock.push(compressedData);const centalHeader=entry.packCentralHeader();centralHeaders.push(centalHeader);mainHeader.size+=centalHeader.length;totalSize+=dataLength+centalHeader.length;totalEntries++;compress2Buffer(entryLists)})}else{totalSize+=mainHeader.mainHeaderSize;mainHeader.offset=dindex;mainHeader.totalEntries=totalEntries;dindex=0;const outBuffer=Buffer.alloc(totalSize);dataBlock.forEach(function(content){content.copy(outBuffer,dindex);dindex+=content.length});centralHeaders.forEach(function(content){content.copy(outBuffer,dindex);dindex+=content.length});const mh=mainHeader.toBinary();if(_comment){_comment.copy(mh,mh.length-_comment.length)}mh.copy(outBuffer,dindex);inBuffer=outBuffer;loadedEntries=false;onSuccess(outBuffer)}};compress2Buffer(Array.from(this.entries))}catch(e){onFail(e)}}}}});var require_adm_zip=__commonJS(function(exports,module){var Utils=require_util();var pth=__require("path");var ZipEntry=require_zipEntry();var ZipFile=require_zipFile();var get_Bool=(...val)=>Utils.findLast(val,(c)=>typeof c==="boolean");var get_Str=(...val)=>Utils.findLast(val,(c)=>typeof c==="string");var get_Fun=(...val)=>Utils.findLast(val,(c)=>typeof c==="function");var defaultOptions={noSort:false,readEntries:false,method:Utils.Constants.NONE,fs:null};module.exports=function(input,options){let inBuffer=null;const opts=Object.assign(Object.create(null),defaultOptions);if(input&&typeof input==="object"){if(!(input instanceof Uint8Array)){Object.assign(opts,input);input=opts.input?opts.input:undefined;if(opts.input)delete opts.input}if(Buffer.isBuffer(input)){inBuffer=input;opts.method=Utils.Constants.BUFFER;input=undefined}}Object.assign(opts,options);const filetools=new Utils(opts);const applyDirAttributes=(dirEntries)=>{dirEntries.filter((d)=>d.attr).sort((a,b)=>b.path.length-a.path.length).forEach((d)=>filetools.fs.chmodSync(d.path,d.attr))};if(typeof opts.decoder!=="object"||typeof opts.decoder.encode!=="function"||typeof opts.decoder.decode!=="function"){opts.decoder=Utils.decoder}if(input&&typeof input==="string"){if(filetools.fs.existsSync(input)){opts.method=Utils.Constants.FILE;opts.filename=input;inBuffer=filetools.fs.readFileSync(input)}else{throw Utils.Errors.INVALID_FILENAME()}}const _zip=new ZipFile(inBuffer,opts);const{canonical,sanitize,zipnamefix}=Utils;function getEntry(entry){if(entry&&_zip){var item;if(typeof entry==="string")item=_zip.getEntry(pth.posix.normalize(entry));if(typeof entry==="object"&&typeof entry.entryName!=="undefined"&&typeof entry.header!=="undefined")item=_zip.getEntry(entry.entryName);if(item){return item}}return null}function fixPath(zipPath){const{join,normalize,sep}=pth.posix;return join(pth.isAbsolute(zipPath)?"/":".",normalize(sep+zipPath.split("\\").join(sep)+sep))}function filenameFilter(filterfn){if(filterfn instanceof RegExp){return function(rx){return function(filename){return rx.test(filename)}}(filterfn)}else if(typeof filterfn!=="function"){return()=>true}return filterfn}const relativePath=(local,entry)=>{let lastChar=entry.slice(-1);lastChar=lastChar===filetools.sep?filetools.sep:"";return pth.relative(local,entry)+lastChar};return{readFile:function(entry,pass){var item=getEntry(entry);return item&&item.getData(pass)||null},childCount:function(entry){const item=getEntry(entry);if(item){return _zip.getChildCount(item)}},readFileAsync:function(entry,callback){var item=getEntry(entry);if(item){item.getDataAsync(callback)}else{callback(null,"getEntry failed for:"+entry)}},readAsText:function(entry,encoding){var item=getEntry(entry);if(item){var data=item.getData();if(data&&data.length){return data.toString(encoding||"utf8")}}return""},readAsTextAsync:function(entry,callback,encoding){var item=getEntry(entry);if(item){item.getDataAsync(function(data,err){if(err){callback(data,err);return}if(data&&data.length){callback(data.toString(encoding||"utf8"))}else{callback("")}})}else{callback("")}},deleteFile:function(entry,withsubfolders=true){var item=getEntry(entry);if(item){_zip.deleteFile(item.entryName,withsubfolders)}},deleteEntry:function(entry){var item=getEntry(entry);if(item){_zip.deleteEntry(item.entryName)}},addZipComment:function(comment){_zip.comment=comment},getZipComment:function(){return _zip.comment||""},addZipEntryComment:function(entry,comment){var item=getEntry(entry);if(item){item.comment=comment}},getZipEntryComment:function(entry){var item=getEntry(entry);if(item){return item.comment||""}return""},updateFile:function(entry,content){var item=getEntry(entry);if(item){item.setData(content)}},addLocalFile:function(localPath,zipPath,zipName,comment){if(filetools.fs.existsSync(localPath)){zipPath=zipPath?fixPath(zipPath):"";const p=pth.win32.basename(pth.win32.normalize(localPath));zipPath+=zipName?zipName:p;const _attr=filetools.fs.statSync(localPath);const data=_attr.isFile()?filetools.fs.readFileSync(localPath):Buffer.alloc(0);if(_attr.isDirectory())zipPath+=filetools.sep;this.addFile(zipPath,data,comment,_attr)}else{throw Utils.Errors.FILE_NOT_FOUND(localPath)}},addLocalFileAsync:function(options,callback){options=typeof options==="object"?options:{localPath:options};const localPath=pth.resolve(options.localPath);const{comment}=options;let{zipPath,zipName}=options;const self=this;filetools.fs.stat(localPath,function(err,stats){if(err)return callback(err,false);zipPath=zipPath?fixPath(zipPath):"";const p=pth.win32.basename(pth.win32.normalize(localPath));zipPath+=zipName?zipName:p;if(stats.isFile()){filetools.fs.readFile(localPath,function(err,data){if(err)return callback(err,false);self.addFile(zipPath,data,comment,stats);return setImmediate(callback,undefined,true)})}else if(stats.isDirectory()){zipPath+=filetools.sep;self.addFile(zipPath,Buffer.alloc(0),comment,stats);return setImmediate(callback,undefined,true)}})},addLocalFolder:function(localPath,zipPath,filter){filter=filenameFilter(filter);zipPath=zipPath?fixPath(zipPath):"";localPath=pth.normalize(localPath);if(filetools.fs.existsSync(localPath)){const items=filetools.findFiles(localPath);const self=this;if(items.length){for(const filepath of items){const p=pth.join(zipPath,relativePath(localPath,filepath));if(filter(p)){self.addLocalFile(filepath,pth.dirname(p))}}}}else{throw Utils.Errors.FILE_NOT_FOUND(localPath)}},addLocalFolderAsync:function(localPath,callback,zipPath,filter){filter=filenameFilter(filter);zipPath=zipPath?fixPath(zipPath):"";localPath=pth.normalize(localPath);var self=this;filetools.fs.open(localPath,"r",function(err){if(err&&err.code==="ENOENT"){callback(undefined,Utils.Errors.FILE_NOT_FOUND(localPath))}else if(err){callback(undefined,err)}else{var items=filetools.findFiles(localPath);var i=-1;var next=function(){i+=1;if(i<items.length){var filepath=items[i];var p=relativePath(localPath,filepath).split("\\").join("/");p=p.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"");if(filter(p)){filetools.fs.stat(filepath,function(er0,stats){if(er0)callback(undefined,er0);if(stats.isFile()){filetools.fs.readFile(filepath,function(er1,data){if(er1){callback(undefined,er1)}else{self.addFile(zipPath+p,data,"",stats);next()}})}else{self.addFile(zipPath+p+"/",Buffer.alloc(0),"",stats);next()}})}else{process.nextTick(()=>{next()})}}else{callback(true,undefined)}};next()}})},addLocalFolderAsync2:function(options,callback){const self=this;options=typeof options==="object"?options:{localPath:options};const localPath=pth.resolve(options.localPath);let{zipPath,filter,namefix}=options;if(filter instanceof RegExp){filter=function(rx){return function(filename){return rx.test(filename)}}(filter)}else if(typeof filter!=="function"){filter=function(){return true}}zipPath=zipPath?fixPath(zipPath):"";if(namefix==="latin1"){namefix=(str)=>str.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")}if(typeof namefix!=="function")namefix=(str)=>str;const relPathFix=(entry)=>pth.join(zipPath,namefix(relativePath(localPath,entry)));const fileNameFix=(entry)=>pth.win32.basename(pth.win32.normalize(namefix(entry)));filetools.fs.open(localPath,"r",function(err){if(err&&err.code==="ENOENT"){callback(Utils.Errors.FILE_NOT_FOUND(localPath),false)}else if(err){callback(err,false)}else{filetools.findFilesAsync(localPath,function(err,fileEntries){if(err)return callback(err,false);fileEntries=fileEntries.filter((dir)=>filter(relPathFix(dir)));if(!fileEntries.length)return callback(undefined,true);setImmediate(fileEntries.reverse().reduce(function(next,entry){return function(err,done){if(err||done===false)return setImmediate(next,err,false);self.addLocalFileAsync({localPath:entry,zipPath:pth.dirname(relPathFix(entry)),zipName:fileNameFix(entry)},next)}},callback))})}})},addLocalFolderPromise:function(localPath,props){return new Promise((resolve,reject)=>{this.addLocalFolderAsync2(Object.assign({localPath},props),(err,done)=>{if(err)return reject(err);if(done)resolve(this)})})},addFile:function(entryName,content,comment,attr){entryName=zipnamefix(entryName);let entry=getEntry(entryName);const update=entry!=null;if(!update){entry=new ZipEntry(opts);entry.entryName=entryName}entry.comment=comment||"";const isStat=typeof attr==="object"&&attr instanceof filetools.fs.Stats;if(isStat){entry.header.time=attr.mtime}var fileattr=entry.isDirectory?16:0;let unix=entry.isDirectory?16384:32768;if(isStat){unix|=4095&attr.mode}else if(typeof attr==="number"){unix|=4095&attr}else{unix|=entry.isDirectory?493:420}fileattr=(fileattr|unix<<16)>>>0;entry.attr=fileattr;entry.setData(content);if(!update)_zip.setEntry(entry);return entry},getEntries:function(password){_zip.password=password;return _zip?_zip.entries:[]},getEntry:function(name){return getEntry(name)},getEntryCount:function(){return _zip.getEntryCount()},forEach:function(callback){return _zip.forEach(callback)},extractEntryTo:function(entry,targetPath,maintainEntryPath,overwrite,keepOriginalPermission,outFileName){overwrite=get_Bool(false,overwrite);keepOriginalPermission=get_Bool(false,keepOriginalPermission);maintainEntryPath=get_Bool(true,maintainEntryPath);outFileName=get_Str(keepOriginalPermission,outFileName);var item=getEntry(entry);if(!item){throw Utils.Errors.NO_ENTRY()}var entryName=canonical(item.entryName);var target=sanitize(targetPath,outFileName&&!item.isDirectory?canonical(outFileName):maintainEntryPath?entryName:pth.basename(entryName));if(item.isDirectory){var children=_zip.getEntryChildren(item);children.forEach(function(child){if(child.isDirectory)return;var content=child.getData();if(!content){throw Utils.Errors.CANT_EXTRACT_FILE()}var name=canonical(maintainEntryPath?child.entryName:child.entryName.substring(item.entryName.length));var childName=sanitize(targetPath,name);filetools.assertPathSafe(targetPath,childName);const fileAttr=keepOriginalPermission?child.header.fileAttr:undefined;filetools.writeFileTo(childName,content,overwrite,fileAttr)});return true}var content=item.getData(_zip.password);if(!content)throw Utils.Errors.CANT_EXTRACT_FILE();filetools.assertPathSafe(targetPath,target);if(filetools.fs.existsSync(target)&&!overwrite){throw Utils.Errors.CANT_OVERRIDE()}const fileAttr=keepOriginalPermission?entry.header.fileAttr:undefined;filetools.writeFileTo(target,content,overwrite,fileAttr);return true},test:function(pass){if(!_zip){return false}for(var entry of _zip.entries){try{if(entry.isDirectory){continue}var content=entry.getData(pass);if(!content){return false}}catch(err){return false}}return true},extractAllTo:function(targetPath,overwrite,keepOriginalPermission,pass){keepOriginalPermission=get_Bool(false,keepOriginalPermission);pass=get_Str(keepOriginalPermission,pass);overwrite=get_Bool(false,overwrite);if(!_zip)throw Utils.Errors.NO_ZIP();const dirEntries=[];_zip.entries.forEach(function(entry){var entryName=sanitize(targetPath,canonical(entry.entryName));filetools.assertPathSafe(targetPath,entryName);if(entry.isDirectory){filetools.makeDir(entryName);if(keepOriginalPermission)dirEntries.push({path:entryName,attr:entry.header.fileAttr});return}var content=entry.getData(pass);if(!content){throw Utils.Errors.CANT_EXTRACT_FILE()}const fileAttr=keepOriginalPermission?entry.header.fileAttr:undefined;filetools.writeFileTo(entryName,content,overwrite,fileAttr);try{filetools.fs.utimesSync(entryName,entry.header.time,entry.header.time)}catch(err){}});applyDirAttributes(dirEntries)},extractAllToAsync:function(targetPath,overwrite,keepOriginalPermission,callback){callback=get_Fun(overwrite,keepOriginalPermission,callback);keepOriginalPermission=get_Bool(false,keepOriginalPermission);overwrite=get_Bool(false,overwrite);if(!callback){return new Promise((resolve,reject)=>{this.extractAllToAsync(targetPath,overwrite,keepOriginalPermission,function(err){if(err){reject(err)}else{resolve(this)}})})}if(!_zip){callback(Utils.Errors.NO_ZIP());return}targetPath=pth.resolve(targetPath);const getPath=(entry)=>sanitize(targetPath,pth.normalize(canonical(entry.entryName)));const getError=(msg,file)=>new Error(msg+': "'+file+'"');const dirEntries=[];const fileEntries=[];_zip.entries.forEach((e)=>{if(e.isDirectory){dirEntries.push(e)}else{fileEntries.push(e)}});const deferredDirAttr=[];for(const entry of dirEntries){const dirPath=getPath(entry);const dirAttr=keepOriginalPermission?entry.header.fileAttr:undefined;try{filetools.assertPathSafe(targetPath,dirPath);filetools.makeDir(dirPath)}catch(er){callback(getError("Unable to create folder",dirPath));continue}if(dirAttr)deferredDirAttr.push({path:dirPath,attr:dirAttr});try{filetools.fs.utimesSync(dirPath,entry.header.time,entry.header.time)}catch(er){}}const done=(err)=>{if(!err){try{applyDirAttributes(deferredDirAttr)}catch(er){return callback(getError("Unable to set folder permissions",er.path||""))}}callback(err)};fileEntries.reverse().reduce(function(next,entry){return function(err){if(err){next(err)}else{const entryName=pth.normalize(canonical(entry.entryName));const filePath=sanitize(targetPath,entryName);try{filetools.assertPathSafe(targetPath,filePath)}catch(er){return next(er)}entry.getDataAsync(function(content,err_1){if(err_1){next(err_1)}else if(!content){next(Utils.Errors.CANT_EXTRACT_FILE())}else{const fileAttr=keepOriginalPermission?entry.header.fileAttr:undefined;filetools.writeFileToAsync(filePath,content,overwrite,fileAttr,function(succ){if(!succ){return next(getError("Unable to write file",filePath))}filetools.fs.utimes(filePath,entry.header.time,entry.header.time,function(){next()})})}})}}},done)()},writeZip:function(targetFileName,callback){if(arguments.length===1){if(typeof targetFileName==="function"){callback=targetFileName;targetFileName=""}}if(!targetFileName&&opts.filename){targetFileName=opts.filename}if(!targetFileName)return;var zipData=_zip.compressToBuffer();if(zipData){var ok=filetools.writeFileTo(targetFileName,zipData,true);if(typeof callback==="function")callback(!ok?new Error("failed"):null,"")}},writeZipPromise:function(targetFileName,props){const{overwrite,perm}=Object.assign({overwrite:true},props);return new Promise((resolve,reject)=>{if(!targetFileName&&opts.filename)targetFileName=opts.filename;if(!targetFileName)reject("ADM-ZIP: ZIP File Name Missing");this.toBufferPromise().then((zipData)=>{const ret=(done)=>done?resolve(done):reject("ADM-ZIP: Wasn't able to write zip file");filetools.writeFileToAsync(targetFileName,zipData,overwrite,perm,ret)},reject)})},toBufferPromise:function(){return new Promise((resolve,reject)=>{_zip.toAsyncBuffer(resolve,reject)})},toBuffer:function(onSuccess,onFail,onItemStart,onItemEnd){if(typeof onSuccess==="function"){_zip.toAsyncBuffer(onSuccess,onFail,onItemStart,onItemEnd);return null}return _zip.compressToBuffer()}}}});var RUNTIME_001="RUNTIME-001",RUNTIME_002="RUNTIME-002",RUNTIME_003="RUNTIME-003",RUNTIME_004="RUNTIME-004",RUNTIME_005="RUNTIME-005",RUNTIME_006="RUNTIME-006",RUNTIME_007="RUNTIME-007",RUNTIME_008="RUNTIME-008",RUNTIME_009="RUNTIME-009",RUNTIME_010="RUNTIME-010",RUNTIME_011="RUNTIME-011",RUNTIME_012="RUNTIME-012",RUNTIME_013="RUNTIME-013",RUNTIME_014="RUNTIME-014",RUNTIME_015="RUNTIME-015",TYPE_001="TYPE-001",BUILD_001="BUILD-001",BUILD_002="BUILD-002";var init_error_codes=()=>{};var runtimeDescMap,typeDescMap,buildDescMap,errorDescMap;var init_desc=__esm(()=>{init_error_codes();runtimeDescMap={[RUNTIME_001]:"Failed to get remoteEntry exports.",[RUNTIME_002]:'The remote entry interface does not contain "init"',[RUNTIME_003]:"Failed to get manifest.",[RUNTIME_004]:"Failed to locate remote.",[RUNTIME_005]:"Invalid loadShareSync function call from bundler runtime",[RUNTIME_006]:"Invalid loadShareSync function call from runtime",[RUNTIME_007]:"Failed to get remote snapshot.",[RUNTIME_008]:"Failed to load script resources.",[RUNTIME_009]:"Please call createInstance first.",[RUNTIME_010]:'The name option cannot be changed after initialization. If you want to create a new instance with a different name, please use "createInstance" api.',[RUNTIME_011]:"The remoteEntry URL is missing from the remote snapshot.",[RUNTIME_012]:'The getter for the shared module is not a function. This may be caused by setting "shared.import: false" without the host providing the corresponding lib.',[RUNTIME_013]:"The manifest is not a valid Module Federation manifest.",[RUNTIME_014]:"The remote does not expose the requested module.",[RUNTIME_015]:"Remote container initialization failed."};typeDescMap={[TYPE_001]:"Failed to generate type declaration. Execute the below cmd to reproduce and fix the error."};buildDescMap={[BUILD_001]:"Failed to find expose module.",[BUILD_002]:"PublicPath is required in prod mode."};errorDescMap={...runtimeDescMap,...typeDescMap,...buildDescMap}});var init_dist4=__esm(()=>{init_error_codes();init_desc()});var getDocsUrl=(errorCode)=>{return`View the docs to see how to solve: https://module-federation.io/guide/troubleshooting/${errorCode.split("-")[0].toLowerCase()}#${errorCode.toLowerCase()}`},getShortErrorMsg2=(errorCode,errorDescMap,args,originalErrorMsg)=>{const msg=[`${[errorDescMap[errorCode]]} #${errorCode}`];args&&msg.push(`args: ${JSON.stringify(args)}`);msg.push(getDocsUrl(errorCode));originalErrorMsg&&msg.push(`Original Error Message:
198
+ `,"Broker","warn");return}try{const publisher=this._publisherMap.get(identifier);fileLog(`[${ActionKind.UPDATE_PUBLISHER}] ${identifier} update, and notify subscribers to update`,"Broker","info");if(publisher){publisher.notifySubscribers({remoteTypeTarPath,name,updateMode,updateKind,updateSourcePaths:updateSourcePaths||[]});this._publisherMap.forEach((p)=>{if(p.name===publisher.name)return;const dynamicRemoteInfo=p.dynamicRemoteMap.get(identifier);if(dynamicRemoteInfo){fileLog(`dynamicRemoteInfo: ${JSON.stringify(dynamicRemoteInfo)}, identifier:${identifier} publish: ${p.name}`,"Broker","info");p.fetchRemoteTypes({remoteInfo:dynamicRemoteInfo,once:false})}})}}catch(err){const msg=error3(err,ActionKind.UPDATE_PUBLISHER,"Broker");client.send(msg);client.close()}}async _fetchTypes(context,_client){const{name,ip,remoteInfo}=context??{};const identifier=getIdentifier({name,ip});try{const publisher=this._publisherMap.get(identifier);fileLog(`[${ActionKind.FETCH_TYPES}] ${identifier} fetch types`,"Broker","info");if(publisher)publisher.fetchRemoteTypes({remoteInfo,once:true})}catch(err){fileLog(`[${ActionKind.FETCH_TYPES}] ${identifier} fetch types fail , error info: ${err}`,"Broker","error")}}_addDynamicRemote(context){const{name,ip,remoteInfo,remoteIp}=context??{};const identifier=getIdentifier({name,ip});const publisher=this._publisherMap.get(identifier);const remoteId=getIdentifier({name:remoteInfo.name,ip:remoteIp});fileLog(`[${ActionKind.ADD_DYNAMIC_REMOTE}] identifier:${identifier},publisher: ${publisher.name}, remoteId:${remoteId}`,"Broker","error");if(!publisher||publisher.dynamicRemoteMap.has(remoteId))return;publisher.dynamicRemoteMap.set(remoteId,remoteInfo)}async _addSubscriber(context,client){const{publishers,name:subscriberName}=context??{};publishers.forEach((publisher)=>{const{name,ip}=publisher;const identifier=getIdentifier({name,ip});if(!this._publisherMap.has(identifier)){fileLog(`[${ActionKind.ADD_SUBSCRIBER}]: ${identifier} has not been started, ${subscriberName} will add the relation to tmp shelter`,"Broker","warn");this._addTmpSubScriberRelation({name:getIdentifier({name:context.name,ip:context.ip}),client},publisher);return}try{const registeredPublisher=this._publisherMap.get(identifier);if(registeredPublisher){registeredPublisher.addSubscriber(getIdentifier({name:subscriberName,ip:context.ip}),client);fileLog(`[${ActionKind.ADD_SUBSCRIBER}]: ${identifier} has been started, Adding Subscriber ${subscriberName} Succeed, this.__publisherMap are: ${JSON.stringify(Array.from(this._publisherMap.entries()))}`,"Broker","info");registeredPublisher.notifySubscriber(getIdentifier({name:subscriberName,ip:context.ip}),{updateKind:UpdateKind.UPDATE_TYPE,updateMode:UpdateMode.PASSIVE,updateSourcePaths:[registeredPublisher.name],remoteTypeTarPath:registeredPublisher.remoteTypeTarPath,name:registeredPublisher.name});fileLog(`[${ActionKind.ADD_SUBSCRIBER}]: notifySubscriber Subscriber ${subscriberName}, updateMode: "PASSIVE", updateSourcePaths: ${registeredPublisher.name}`,"Broker","info")}}catch(err){const msg=error3(err,ActionKind.ADD_SUBSCRIBER,"Broker");client.send(msg);client.close()}})}async _removeSubscriber(context,client){const{publishers}=context??{};const subscriberIdentifier=getIdentifier({name:context?.name,ip:context?.ip});publishers.forEach((publisher)=>{const{name,ip}=publisher;const identifier=getIdentifier({name,ip});const registeredPublisher=this._publisherMap.get(identifier);if(!registeredPublisher){fileLog(`[${ActionKind.EXIT_SUBSCRIBER}], ${identifier} does not exit `,"Broker","warn");return}try{fileLog(`[${ActionKind.EXIT_SUBSCRIBER}], ${identifier} will exit `,"Broker","INFO");registeredPublisher.removeSubscriber(subscriberIdentifier);this._clearTmpSubScriberRelation(identifier);if(!registeredPublisher.hasSubscribes)this._publisherMap.delete(identifier);if(!this.hasPublishers)this.exit()}catch(err){const msg=error3(err,ActionKind.EXIT_SUBSCRIBER,"Broker");client.send(msg);client.close()}})}async _removePublisher(context,client){const{name,ip}=context??{};const identifier=getIdentifier({name,ip});const publisher=this._publisherMap.get(identifier);if(!publisher){fileLog(`[${ActionKind.EXIT_PUBLISHER}]: ${identifier}} has not been added, this action will be ingored`,"Broker","warn");return}try{const{subscribers}=publisher;subscribers.forEach((subscriber,subscriberIdentifier)=>{this._addTmpSubScriberRelation({name:subscriberIdentifier,client:subscriber},{name:publisher.name,ip:publisher.ip});fileLog(`[${ActionKind.EXIT_PUBLISHER}]: ${identifier} is removing , subscriber: ${subscriberIdentifier} will be add tmpSubScriberRelation`,"Broker","info")});this._publisherMap.delete(identifier);fileLog(`[${ActionKind.EXIT_PUBLISHER}]: ${identifier} is removed `,"Broker","info");if(!this.hasPublishers){fileLog(`[${ActionKind.EXIT_PUBLISHER}]: _publisherMap is empty, all server will exit `,"Broker","warn");this.exit()}}catch(err){const msg=error3(err,ActionKind.EXIT_PUBLISHER,"Broker");client.send(msg);client.close()}}async _addWebClient(context,client){const{name}=context??{};const identifier=getIdentifier({name});if(this._webClientMap.has(identifier))fileLog(`${identifier}} has been added, this action will override prev WebClient`,"Broker","warn");try{this._webClientMap.set(identifier,client);fileLog(`${identifier} adding WebClient Succeed`,"Broker","info")}catch(err){const msg=error3(err,ActionKind.ADD_WEB_CLIENT,"Broker");client.send(msg);client.close()}}async _notifyWebClient(context,client){const{name,updateMode}=context??{};const identifier=getIdentifier({name});const webClient=this._webClientMap.get(identifier);if(!webClient){fileLog(`[${ActionKind.NOTIFY_WEB_CLIENT}] ${identifier} has not been added, this action will be ignored`,"Broker","warn");return}try{const api=new ReloadWebClientAPI({name,updateMode});webClient.send(JSON.stringify(api));fileLog(`[${ActionKind.NOTIFY_WEB_CLIENT}] Notify ${name} WebClient Succeed`,"Broker","info")}catch(err){const msg=error3(err,ActionKind.NOTIFY_WEB_CLIENT,"Broker");client.send(msg);client.close()}}_addTmpSubScriberRelation(subscriber,publisher){const publisherIdentifier=getIdentifier({name:publisher.name,ip:publisher.ip});const subscriberIdentifier=subscriber.name;const shelter=this._tmpSubscriberShelter.get(publisherIdentifier);if(!shelter){const map=new Map;map.set(subscriberIdentifier,subscriber);this._tmpSubscriberShelter.set(publisherIdentifier,{subscribers:map,timestamp:Date.now()});fileLog(`[AddTmpSubscriberRelation] ${publisherIdentifier}'s subscriber has ${subscriberIdentifier} `,"Broker","info");return}if(shelter.subscribers.get(subscriberIdentifier)){fileLog(`[AddTmpSubscriberRelation] ${publisherIdentifier} and ${subscriberIdentifier} relation has been added`,"Broker","warn");shelter.subscribers.set(subscriberIdentifier,subscriber);shelter.timestamp=Date.now()}else{fileLog(`AddTmpSubscriberLog ${publisherIdentifier}'s shelter has been added, update shelter.subscribers ${subscriberIdentifier}`,"Broker","warn");shelter.subscribers.set(subscriberIdentifier,subscriber)}}_getTmpSubScribers(publisherIdentifier){return this._tmpSubscriberShelter.get(publisherIdentifier)?.subscribers}_consumeTmpSubScribers(publisher,tmpSubScribers){tmpSubScribers.forEach((tmpSubScriber,identifier)=>{fileLog(`notifyTmpSubScribers ${publisher.name} will be add a subscriber: ${identifier} `,"Broker","warn");publisher.addSubscriber(identifier,tmpSubScriber.client);publisher.notifySubscriber(identifier,{updateKind:UpdateKind.UPDATE_TYPE,updateMode:UpdateMode.PASSIVE,updateSourcePaths:[publisher.name],remoteTypeTarPath:publisher.remoteTypeTarPath,name:publisher.name})})}_clearTmpSubScriberRelation(identifier){this._tmpSubscriberShelter.delete(identifier)}_clearTmpSubScriberRelations(){this._tmpSubscriberShelter.clear()}_disconnect(){this._publisherMap.forEach((publisher)=>{publisher.close()})}_setSchedule(){const serverTest=Number(process.env["FEDERATION_SERVER_TEST"]);this._scheduleJob=scheduleCleanup(()=>{this._tmpSubscriberShelter.forEach((tmpSubscriber,identifier)=>{fileLog(` _clearTmpSubScriberRelation ${identifier}, ${Date.now()-tmpSubscriber.timestamp>=(process.env["GARFISH_MODULE_SERVER_TEST"]?serverTest:Broker.DEFAULT_WAITING_TIME)}`,"Broker","info");if(Date.now()-tmpSubscriber.timestamp>=(process.env["FEDERATION_SERVER_TEST"]?serverTest:Broker.DEFAULT_WAITING_TIME))this._clearTmpSubScriberRelation(identifier)})},serverTest)}_clearSchedule(){if(!this._scheduleJob)return;this._scheduleJob.cancel();this._scheduleJob=null}_stopWhenSIGTERMOrSIGINT(){process.on("SIGTERM",()=>{this.exit()});process.on("SIGINT",()=>{this.exit()})}_handleUnexpectedExit(){process.on("unhandledRejection",(error)=>{console.error("Unhandled Rejection Error: ",error);fileLog(`Unhandled Rejection Error: ${error}`,"Broker","fatal");process.exit(1)});process.on("uncaughtException",(error)=>{console.error("Unhandled Exception Error: ",error);fileLog(`Unhandled Rejection Error: ${error}`,"Broker","fatal");process.exit(1)})}async start(){}exit(){const brokerExitLog=new BrokerExitLog;this.broadcast(JSON.stringify(brokerExitLog));this._disconnect();this._clearSchedule();this._clearTmpSubScriberRelations();this._webSocketServer&&this._webSocketServer.close();this._secureWebSocketServer&&this._secureWebSocketServer.close();process.exit(0)}broadcast(message){fileLog(`[broadcast] exit info : ${JSON.stringify(message)}`,"Broker","warn");this._webSocketServer?.clients.forEach((client)=>{client.send(JSON.stringify(message))});this._secureWebSocketServer?.clients.forEach((client)=>{client.send(JSON.stringify(message))})}}});function processFn(options,normalizeSimple,normalizeOptions,fn){const object=(obj)=>{for(const[key,value]of Object.entries(obj)){if(typeof value==="string"){fn(key,normalizeSimple(value,key))}else{fn(key,normalizeOptions(value,key))}}};const array=(items)=>{for(const item of items){if(typeof item==="string"){fn(item,normalizeSimple(item,item))}else if(item&&typeof item==="object"){object(item)}else{throw new Error("Unexpected options format")}}};if(!options){return}else if(Array.isArray(options)){array(options)}else if(typeof options==="object"){object(options)}else{throw new Error("Unexpected options format")}}function parseOptions2(options,normalizeSimple,normalizeOptions){const items=[];processFn(options,normalizeSimple,normalizeOptions,(key,value)=>{items.push([key,value])});return items}var init_utils2=()=>{};var init_dist2=__esm(()=>{init_utils2()});import{copyFile as copyFile3,lstat as lstat3,mkdir as mkdir2,readdir}from"fs/promises";import{existsSync as existsSync4,readFileSync as readFileSync4}from"fs";import path22 from"path";import path6 from"path";import fs from"fs";function getTypedName(name){return`@types/${name.replace(/^@/,"").replace("/","__")}`}function getPackageRootDir(packageName,context=process.cwd()){if(!packageName){throw new Error("No package name provided.")}const entryFile=__require2.resolve(packageName,{paths:[context]});const entryDir=path6.dirname(entryFile);let fallbackPackageJsonPath=path6.join(entryDir,"package.json");if(!fs.existsSync(fallbackPackageJsonPath)){fallbackPackageJsonPath=null}const match=packageName.match(/^@[^/]+\/(.+)$/);const localName=match?match[1]:packageName;let currentDir=entryDir;while(path6.basename(currentDir)!==localName&&path6.dirname(currentDir)!==currentDir){try{currentDir=path6.dirname(currentDir)}catch(err){if(err.code==="EACCES"){continue}else{throw err}}}if(path6.basename(currentDir)===localName){const candidate=path6.join(currentDir,"package.json");if(fs.existsSync(candidate)){const pkgContent=JSON.parse(fs.readFileSync(candidate,"utf8"));if(pkgContent.name===packageName){return currentDir}}}if(fallbackPackageJsonPath){return entryDir}throw new Error(`Could not find a matching package.json for "${packageName}" and no fallback was found.`)}function resolvePackageJson(packageName,context){try{return __require2.resolve(`${packageName}/package.json`,{paths:[context]})}catch(e){let currentPath=path6.resolve(context);while(true){const candidate=path6.join(currentPath,"node_modules",packageName,"package.json");if(fs.existsSync(candidate)){return candidate}const parentPath=path6.dirname(currentPath);if(parentPath===currentPath){throw new Error(`Could not resolve package.json for "${packageName}".`)}currentPath=parentPath}}}var __require2,ignoredPkgs,isNodeUtils=(pkgJsonPath,importPath)=>{return pkgJsonPath===importPath},ThirdPartyExtractor=class{constructor({destDir,context=process.cwd(),exclude=[]}){this.destDir=destDir;this.context=context;this.pkgs={};this.pattern=/(from|import\()\s*['"]([^'"]+)['"]/g;this.exclude=exclude}addPkgs(pkgName,dirName){if(ignoredPkgs.includes(pkgName)){return}if(this.exclude.some((pattern)=>{if(typeof pattern==="string"){return new RegExp(pattern).test(pkgName)}else{return pattern.test(pkgName)}})){return}this.pkgs[pkgName]=dirName}inferPkgDir(importPath){if(this.pkgs[importPath]){return}if(path22.isAbsolute(importPath)){return}if(importPath.startsWith(".")){return}try{const importEntry=__require2.resolve(importPath,{paths:[this.context]});if(isNodeUtils(importEntry,importPath)){return}const packageDir=getPackageRootDir(importPath,this.context);const pkgJsonPath=path22.join(packageDir,"package.json");const dir=path22.dirname(pkgJsonPath);const pkg=JSON.parse(readFileSync4(pkgJsonPath,"utf-8"));const types=pkg.types||pkg.typings;if(dir===this.context){return}if(types){const typesDir=path22.dirname(path22.resolve(dir,types));this.addPkgs(pkg.name,typesDir);return typesDir}else if(existsSync4(path22.resolve(dir,"index.d.ts"))){this.addPkgs(pkg.name,dir);return dir}else{const typedPkgName=getTypedName(pkg.name);const typedPkgJsonPath=resolvePackageJson(typedPkgName,this.context);const typedDir=path22.dirname(typedPkgJsonPath);readFileSync4(typedPkgJsonPath,"utf-8");this.addPkgs(typedPkgName,typedDir);return typedDir}}catch(_err){return}}collectTypeImports(str){const{pattern}=this;let match;const imports=new Set;while((match=pattern.exec(str))!==null){imports.add(match[2])}return[...imports]}collectPkgs(str){const imports=this.collectTypeImports(str);imports.forEach((importPath)=>{this.inferPkgDir(importPath)})}async copyDts(){if(!Object.keys(this.pkgs).length){return}const ensureDir=async(dir)=>mkdir2(dir,{recursive:true});const copyFiles=async(srcDir,destDir)=>{if(srcDir.startsWith(".")){return}const files=await readdir(srcDir);await Promise.all(files.map(async(file)=>{const fullPath=path22.join(srcDir,file);if(["node_modules","bin"].includes(file)){return}const stats=await lstat3(fullPath);if(stats.isDirectory()){const destFullPath=path22.join(destDir,file);await ensureDir(destFullPath);await copyFiles(fullPath,destFullPath)}else{if(fullPath.endsWith(".d.ts")||fullPath.endsWith("package.json")){await copyFile3(fullPath,path22.join(destDir,file))}}}))};await ensureDir(this.destDir);await Promise.all(Object.keys(this.pkgs).map(async(pkgName)=>{const pkgDir=this.pkgs[pkgName];const destDir=path22.resolve(this.destDir,pkgName);await ensureDir(destDir);await copyFiles(pkgDir,destDir)}))}};var init_dist3=__esm(()=>{__require2=((x)=>__require)(function(x){if(true)return __require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});ignoredPkgs=["typescript"]});var require_constants=__commonJS(function(exports,module){module.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var require_errors=__commonJS(function(exports){var errors={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",MAX_OUTPUT_EXCEEDED:"Decompressed data exceeds the declared uncompressed size",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DUPLICATE_ENTRY:"Duplicate entry name {0}",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",ZIP64_VALUE_TOO_LARGE:"Zip64 value exceeds the maximum safe integer",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function E(message){return function(...args){if(args.length){message=message.replace(/\{(\d)\}/g,(_,n)=>args[n]||"")}return new Error("ADM-ZIP: "+message)}}for(const msg of Object.keys(errors)){exports[msg]=E(errors[msg])}});var require_utils=__commonJS(function(exports,module){var fsystem=__require("fs");var pth=__require("path");var Constants=require_constants();var Errors=require_errors();var isWin=typeof process==="object"&&process.platform==="win32";var is_Obj=(obj)=>typeof obj==="object"&&obj!==null;var crcTable=new Uint32Array(256).map((t,c)=>{for(let k=0;k<8;k++){if((c&1)!==0){c=3988292384^c>>>1}else{c>>>=1}}return c>>>0});function Utils(opts){this.sep=pth.sep;this.fs=fsystem;if(is_Obj(opts)){if(is_Obj(opts.fs)&&typeof opts.fs.statSync==="function"){this.fs=opts.fs}}}module.exports=Utils;Utils.prototype.makeDir=function(folder){const self=this;function mkdirSync(fpath){let resolvedPath=fpath.split(self.sep)[0];fpath.split(self.sep).forEach(function(name){if(!name||name.substr(-1,1)===":")return;resolvedPath+=self.sep+name;var stat;try{stat=self.fs.statSync(resolvedPath)}catch(e){if(e.message&&e.message.startsWith("ENOENT")){self.fs.mkdirSync(resolvedPath)}else{throw e}}if(stat&&stat.isFile())throw Errors.FILE_IN_THE_WAY(`"${resolvedPath}"`)})}mkdirSync(folder)};Utils.prototype.writeFileTo=function(path,content,overwrite,attr){const self=this;if(self.fs.existsSync(path)){if(!overwrite)return false;var stat=self.fs.statSync(path);if(stat.isDirectory()){return false}}var folder=pth.dirname(path);if(!self.fs.existsSync(folder)){self.makeDir(folder)}var fd;try{fd=self.fs.openSync(path,"w",438)}catch(e){self.fs.chmodSync(path,438);fd=self.fs.openSync(path,"w",438)}if(fd){try{self.fs.writeSync(fd,content,0,content.length,0)}finally{self.fs.closeSync(fd)}}self.fs.chmodSync(path,attr||438);return true};Utils.prototype.writeFileToAsync=function(path,content,overwrite,attr,callback){if(typeof attr==="function"){callback=attr;attr=undefined}const self=this;self.fs.exists(path,function(exist){if(exist&&!overwrite)return callback(false);self.fs.stat(path,function(err,stat){if(exist&&stat&&stat.isDirectory()){return callback(false)}var folder=pth.dirname(path);self.fs.exists(folder,function(exists){if(!exists){try{self.makeDir(folder)}catch(e){return callback(false)}}const writeToFd=function(fd){self.fs.write(fd,content,0,content.length,0,function(writeErr){self.fs.close(fd,function(){if(writeErr)return callback(false);self.fs.chmod(path,attr||438,function(){callback(true)})})})};self.fs.open(path,"w",438,function(err,fd){if(err){self.fs.chmod(path,438,function(){self.fs.open(path,"w",438,function(retryErr,fd){if(retryErr||!fd)return callback(false);writeToFd(fd)})})}else if(fd){writeToFd(fd)}else{callback(false)}})})})})};Utils.prototype.assertPathSafe=function(root,target){const self=this;if(typeof self.fs.lstatSync!=="function")return;const resolvedRoot=pth.resolve(root);const resolvedTarget=pth.resolve(target);if(resolvedTarget===resolvedRoot)return;const rel=pth.relative(resolvedRoot,resolvedTarget);if(!rel||rel===".."||rel.startsWith(".."+pth.sep)||pth.isAbsolute(rel))return;let cur=resolvedRoot;for(const part of rel.split(pth.sep)){if(!part||part===".")continue;cur=pth.join(cur,part);let stat;try{stat=self.fs.lstatSync(cur)}catch(e){break}if(stat.isSymbolicLink())throw Errors.FILE_IN_THE_WAY(`"${cur}"`)}};Utils.prototype.findFiles=function(path){const self=this;const canLstat=typeof self.fs.lstatSync==="function";const rootReal=self.fs.realpathSync(path);function escapesRoot(p){if(!canLstat)return false;if(!self.fs.lstatSync(p).isSymbolicLink())return false;let real;try{real=self.fs.realpathSync(p)}catch(e){return true}return!(real===rootReal||real.startsWith(rootReal+pth.sep))}function findSync(dir,pattern,recursive,visited){if(typeof pattern==="boolean"){recursive=pattern;pattern=undefined}let files=[];self.fs.readdirSync(dir).forEach(function(file){const path=pth.join(dir,file);if(escapesRoot(path))return;const stat=self.fs.statSync(path);if(!pattern||pattern.test(path)){files.push(pth.normalize(path)+(stat.isDirectory()?self.sep:""))}if(stat.isDirectory()&&recursive){const realDir=self.fs.realpathSync(path);if(!visited.has(realDir)){visited.add(realDir);files=files.concat(findSync(path,pattern,recursive,visited))}}});return files}return findSync(path,undefined,true,new Set([rootReal]))};Utils.prototype.findFilesAsync=function(dir,cb){const self=this;const results=[];let finished=false;const finish=function(err){if(finished)return;finished=true;cb(err,err?undefined:results)};const canLstat=typeof self.fs.lstat==="function";let rootReal=null;const escapesRoot=function(file,cb){if(!canLstat)return cb(null,false);self.fs.lstat(file,function(err,lst){if(err)return cb(err);if(!lst||!lst.isSymbolicLink())return cb(null,false);self.fs.realpath(file,function(err,real){if(err)return cb(null,true);cb(null,!(real===rootReal||real.startsWith(rootReal+pth.sep)))})})};const walk=function(dir,visited,done){self.fs.readdir(dir,function(err,list){if(err)return done(err);let pending=list.length;if(!pending)return done();list.forEach(function(name){const file=pth.join(dir,name);escapesRoot(file,function(err,escapes){if(err)return done(err);if(escapes){if(!--pending)done();return}self.fs.stat(file,function(err,stat){if(err)return done(err);if(!stat){if(!--pending)done();return}results.push(pth.normalize(file)+(stat.isDirectory()?self.sep:""));if(!stat.isDirectory()){if(!--pending)done();return}self.fs.realpath(file,function(err,realDir){if(err)return done(err);if(visited.has(realDir)){if(!--pending)done();return}visited.add(realDir);walk(file,visited,function(err){if(err)return done(err);if(!--pending)done()})})})})})})};self.fs.realpath(dir,function(err,realDir){if(err)return finish(err);rootReal=realDir;walk(dir,new Set([realDir]),finish)})};Utils.prototype.getAttributes=function(){};Utils.prototype.setAttributes=function(){};Utils.crc32update=function(crc,byte){return crcTable[(crc^byte)&255]^crc>>>8};Utils.crc32=function(buf){if(typeof buf==="string"){buf=Buffer.from(buf,"utf8")}let len=buf.length;let crc=~0;for(let off=0;off<len;)crc=Utils.crc32update(crc,buf[off++]);return~crc>>>0};Utils.methodToString=function(method){switch(method){case Constants.STORED:return"STORED ("+method+")";case Constants.DEFLATED:return"DEFLATED ("+method+")";default:return"UNSUPPORTED ("+method+")"}};Utils.canonical=function(path){if(!path)return"";const safeSuffix=pth.posix.normalize("/"+path.split("\\").join("/"));return pth.join(".",safeSuffix)};Utils.zipnamefix=function(path){if(!path)return"";const safeSuffix=pth.posix.normalize("/"+path.split("\\").join("/"));return pth.posix.join(".",safeSuffix)};Utils.findLast=function(arr,callback){if(!Array.isArray(arr))throw new TypeError("arr is not array");const len=arr.length>>>0;for(let i=len-1;i>=0;i--){if(callback(arr[i],i,arr)){return arr[i]}}return};Utils.sanitize=function(prefix,name){prefix=pth.resolve(pth.normalize(prefix));var parts=name.split("/");for(var i=0,l=parts.length;i<l;i++){var path=pth.normalize(pth.join(prefix,parts.slice(i,l).join(pth.sep)));if(path===prefix||path.startsWith(prefix+pth.sep)){return path}}return pth.normalize(pth.join(prefix,pth.basename(name)))};Utils.toBuffer=function toBuffer(input,encoder){if(Buffer.isBuffer(input)){return input}else if(input instanceof Uint8Array){return Buffer.from(input)}else{return typeof input==="string"?encoder(input):Buffer.alloc(0)}};Utils.readBigUInt64LE=function(buffer,index){const lo=buffer.readUInt32LE(index);const hi=buffer.readUInt32LE(index+4);const value=hi*4294967296+lo;if(value>Number.MAX_SAFE_INTEGER){throw Errors.ZIP64_VALUE_TOO_LARGE()}return value};Utils.writeBigUInt64LE=function(buffer,value,index){const lo=value>>>0;const hi=Math.floor(value/4294967296)>>>0;buffer.writeUInt32LE(lo,index);buffer.writeUInt32LE(hi,index+4)};Utils.fromDOS2Date=function(val){return new Date((val>>25&127)+1980,Math.max((val>>21&15)-1,0),Math.max(val>>16&31,1),val>>11&31,val>>5&63,(val&31)<<1)};Utils.fromDate2DOS=function(val){let date=0;let time=0;if(val.getFullYear()>1979){date=(val.getFullYear()-1980&127)<<9|val.getMonth()+1<<5|val.getDate();time=val.getHours()<<11|val.getMinutes()<<5|val.getSeconds()>>1}return date<<16|time};Utils.isWin=isWin;Utils.crcTable=crcTable});var require_fattr=__commonJS(function(exports,module){var pth=__require("path");module.exports=function(path,{fs}){var _path=path||"",_obj=newAttr(),_stat=null;function newAttr(){return{directory:false,readonly:false,hidden:false,executable:false,mtime:0,atime:0}}if(_path&&fs.existsSync(_path)){_stat=fs.statSync(_path);_obj.directory=_stat.isDirectory();_obj.mtime=_stat.mtime;_obj.atime=_stat.atime;_obj.executable=(73&_stat.mode)!==0;_obj.readonly=(128&_stat.mode)===0;_obj.hidden=pth.basename(_path)[0]==="."}else{console.warn("Invalid path: "+_path)}return{get directory(){return _obj.directory},get readOnly(){return _obj.readonly},get hidden(){return _obj.hidden},get mtime(){return _obj.mtime},get atime(){return _obj.atime},get executable(){return _obj.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:_path,isDirectory:_obj.directory,isReadOnly:_obj.readonly,isHidden:_obj.hidden,isExecutable:_obj.executable,mTime:_obj.mtime,aTime:_obj.atime}},toString:function(){return JSON.stringify(this.toJSON(),null,"\t")}}}});var require_decoder=__commonJS(function(exports,module){module.exports={efs:true,encode:(data)=>Buffer.from(data,"utf8"),decode:(data)=>data.toString("utf8")}});var require_util=__commonJS(function(exports,module){module.exports=require_utils();module.exports.Constants=require_constants();module.exports.Errors=require_errors();module.exports.FileAttr=require_fattr();module.exports.decoder=require_decoder()});var require_entryHeader=__commonJS(function(exports,module){var Utils=require_util();var Constants=Utils.Constants;module.exports=function(){var _verMade=20,_version=10,_flags=0,_method=0,_time=0,_crc=0,_compressedSize=0,_size=0,_fnameLen=0,_extraLen=0,_comLen=0,_diskStart=0,_inattr=0,_attr=0,_offset=0;_verMade|=Utils.isWin?2560:768;_flags|=Constants.FLG_EFS;const _localHeader={extraLen:0};const uint32=(val)=>Math.max(0,val)>>>0;const uint16=(val)=>Math.max(0,val)&65535;const uint8=(val)=>Math.max(0,val)&255;_time=Utils.fromDate2DOS(new Date);return{get made(){return _verMade},set made(val){_verMade=val},get version(){return _version},set version(val){_version=val},get flags(){return _flags},set flags(val){_flags=val},get flags_efs(){return(_flags&Constants.FLG_EFS)>0},set flags_efs(val){if(val){_flags|=Constants.FLG_EFS}else{_flags&=~Constants.FLG_EFS}},get flags_desc(){return(_flags&Constants.FLG_DESC)>0},set flags_desc(val){if(val){_flags|=Constants.FLG_DESC}else{_flags&=~Constants.FLG_DESC}},get method(){return _method},set method(val){switch(val){case Constants.STORED:this.version=10;break;case Constants.DEFLATED:default:this.version=20}_method=val},get time(){return Utils.fromDOS2Date(this.timeval)},set time(val){val=new Date(val);this.timeval=Utils.fromDate2DOS(val)},get timeval(){return _time},set timeval(val){_time=uint32(val)},get timeHighByte(){return uint8(_time>>>8)},get crc(){return _crc},set crc(val){_crc=uint32(val)},get compressedSize(){return _compressedSize},set compressedSize(val){_compressedSize=uint32(val)},get size(){return _size},set size(val){_size=uint32(val)},get fileNameLength(){return _fnameLen},set fileNameLength(val){_fnameLen=val},get extraLength(){return _extraLen},set extraLength(val){_extraLen=val},get extraLocalLength(){return _localHeader.extraLen},set extraLocalLength(val){_localHeader.extraLen=val},get commentLength(){return _comLen},set commentLength(val){_comLen=val},get diskNumStart(){return _diskStart},set diskNumStart(val){_diskStart=uint32(val)},get inAttr(){return _inattr},set inAttr(val){_inattr=uint32(val)},get attr(){return _attr},set attr(val){_attr=uint32(val)},get fileAttr(){return(_attr||0)>>16&511},get offset(){return _offset},set offset(val){_offset=uint32(val)},get encrypted(){return(_flags&Constants.FLG_ENC)===Constants.FLG_ENC},get centralHeaderSize(){return Constants.CENHDR+_fnameLen+_extraLen+_comLen},get realDataOffset(){return _offset+Constants.LOCHDR+_localHeader.fnameLen+_localHeader.extraLen},get localHeader(){return _localHeader},loadLocalHeaderFromBinary:function(input){if(_offset<0||_offset+Constants.LOCHDR>input.length){throw Utils.Errors.INVALID_LOC()}var data=input.slice(_offset,_offset+Constants.LOCHDR);if(data.readUInt32LE(0)!==Constants.LOCSIG){throw Utils.Errors.INVALID_LOC()}_localHeader.version=data.readUInt16LE(Constants.LOCVER);_localHeader.flags=data.readUInt16LE(Constants.LOCFLG);_localHeader.flags_desc=(_localHeader.flags&Constants.FLG_DESC)>0;_localHeader.method=data.readUInt16LE(Constants.LOCHOW);_localHeader.time=data.readUInt32LE(Constants.LOCTIM);_localHeader.crc=data.readUInt32LE(Constants.LOCCRC);_localHeader.compressedSize=data.readUInt32LE(Constants.LOCSIZ);_localHeader.size=data.readUInt32LE(Constants.LOCLEN);_localHeader.fnameLen=data.readUInt16LE(Constants.LOCNAM);_localHeader.extraLen=data.readUInt16LE(Constants.LOCEXT);const extraStart=_offset+Constants.LOCHDR+_localHeader.fnameLen;const extraEnd=extraStart+_localHeader.extraLen;return input.slice(extraStart,extraEnd)},loadFromBinary:function(data){if(data.length!==Constants.CENHDR||data.readUInt32LE(0)!==Constants.CENSIG){throw Utils.Errors.INVALID_CEN()}_verMade=data.readUInt16LE(Constants.CENVEM);_version=data.readUInt16LE(Constants.CENVER);_flags=data.readUInt16LE(Constants.CENFLG);_method=data.readUInt16LE(Constants.CENHOW);_time=data.readUInt32LE(Constants.CENTIM);_crc=data.readUInt32LE(Constants.CENCRC);_compressedSize=data.readUInt32LE(Constants.CENSIZ);_size=data.readUInt32LE(Constants.CENLEN);_fnameLen=data.readUInt16LE(Constants.CENNAM);_extraLen=data.readUInt16LE(Constants.CENEXT);_comLen=data.readUInt16LE(Constants.CENCOM);_diskStart=data.readUInt16LE(Constants.CENDSK);_inattr=data.readUInt16LE(Constants.CENATT);_attr=data.readUInt32LE(Constants.CENATX);_offset=data.readUInt32LE(Constants.CENOFF)},localHeaderToBinary:function(){var data=Buffer.alloc(Constants.LOCHDR);data.writeUInt32LE(Constants.LOCSIG,0);data.writeUInt16LE(_version,Constants.LOCVER);data.writeUInt16LE(_flags&~Constants.FLG_DESC,Constants.LOCFLG);data.writeUInt16LE(_method,Constants.LOCHOW);data.writeUInt32LE(_time,Constants.LOCTIM);data.writeUInt32LE(_crc,Constants.LOCCRC);data.writeUInt32LE(_compressedSize,Constants.LOCSIZ);data.writeUInt32LE(_size,Constants.LOCLEN);data.writeUInt16LE(_fnameLen,Constants.LOCNAM);data.writeUInt16LE(_localHeader.extraLen,Constants.LOCEXT);return data},centralHeaderToBinary:function(){var data=Buffer.alloc(Constants.CENHDR+_fnameLen+_extraLen+_comLen);data.writeUInt32LE(Constants.CENSIG,0);data.writeUInt16LE(_verMade,Constants.CENVEM);data.writeUInt16LE(_version,Constants.CENVER);data.writeUInt16LE(_flags&~Constants.FLG_DESC,Constants.CENFLG);data.writeUInt16LE(_method,Constants.CENHOW);data.writeUInt32LE(_time,Constants.CENTIM);data.writeUInt32LE(_crc,Constants.CENCRC);data.writeUInt32LE(_compressedSize,Constants.CENSIZ);data.writeUInt32LE(_size,Constants.CENLEN);data.writeUInt16LE(_fnameLen,Constants.CENNAM);data.writeUInt16LE(_extraLen,Constants.CENEXT);data.writeUInt16LE(_comLen,Constants.CENCOM);data.writeUInt16LE(_diskStart,Constants.CENDSK);data.writeUInt16LE(_inattr,Constants.CENATT);data.writeUInt32LE(_attr,Constants.CENATX);data.writeUInt32LE(_offset,Constants.CENOFF);return data},toJSON:function(){const bytes=function(nr){return nr+" bytes"};return{made:_verMade,version:_version,flags:_flags,method:Utils.methodToString(_method),time:this.time,crc:"0x"+_crc.toString(16).toUpperCase(),compressedSize:bytes(_compressedSize),size:bytes(_size),fileNameLength:bytes(_fnameLen),extraLength:bytes(_extraLen),commentLength:bytes(_comLen),diskNumStart:_diskStart,inAttr:_inattr,attr:_attr,offset:_offset,centralHeaderSize:bytes(Constants.CENHDR+_fnameLen+_extraLen+_comLen)}},toString:function(){return JSON.stringify(this.toJSON(),null,"\t")}}}});var require_mainHeader=__commonJS(function(exports,module){var Utils=require_util();var Constants=Utils.Constants;module.exports=function(){var _volumeEntries=0,_totalEntries=0,_size=0,_offset=0,_commentLength=0;const needsZip64=()=>_volumeEntries>Constants.EF_ZIP64_OR_16||_totalEntries>Constants.EF_ZIP64_OR_16||_size>Constants.EF_ZIP64_OR_32||_offset>Constants.EF_ZIP64_OR_32;return{get diskEntries(){return _volumeEntries},set diskEntries(val){_volumeEntries=_totalEntries=val},get totalEntries(){return _totalEntries},set totalEntries(val){_totalEntries=_volumeEntries=val},get size(){return _size},set size(val){_size=val},get offset(){return _offset},set offset(val){_offset=val},get commentLength(){return _commentLength},set commentLength(val){_commentLength=val},get mainHeaderSize(){return(needsZip64()?Constants.ZIP64HDR+Constants.END64HDR:0)+Constants.ENDHDR+_commentLength},loadFromBinary:function(data){if((data.length!==Constants.ENDHDR||data.readUInt32LE(0)!==Constants.ENDSIG)&&(data.length<Constants.ZIP64HDR||data.readUInt32LE(0)!==Constants.ZIP64SIG)){throw Utils.Errors.INVALID_END()}if(data.readUInt32LE(0)===Constants.ENDSIG){_volumeEntries=data.readUInt16LE(Constants.ENDSUB);_totalEntries=data.readUInt16LE(Constants.ENDTOT);_size=data.readUInt32LE(Constants.ENDSIZ);_offset=data.readUInt32LE(Constants.ENDOFF);_commentLength=data.readUInt16LE(Constants.ENDCOM)}else{_volumeEntries=Utils.readBigUInt64LE(data,Constants.ZIP64SUB);_totalEntries=Utils.readBigUInt64LE(data,Constants.ZIP64TOT);_size=Utils.readBigUInt64LE(data,Constants.ZIP64SIZB);_offset=Utils.readBigUInt64LE(data,Constants.ZIP64OFF);_commentLength=0}},toBinary:function(){if(!needsZip64()){var b=Buffer.alloc(Constants.ENDHDR+_commentLength);b.writeUInt32LE(Constants.ENDSIG,0);b.writeUInt32LE(0,4);b.writeUInt16LE(_volumeEntries,Constants.ENDSUB);b.writeUInt16LE(_totalEntries,Constants.ENDTOT);b.writeUInt32LE(_size,Constants.ENDSIZ);b.writeUInt32LE(_offset,Constants.ENDOFF);b.writeUInt16LE(_commentLength,Constants.ENDCOM);b.fill(" ",Constants.ENDHDR);return b}var b=Buffer.alloc(this.mainHeaderSize);let offset=0;b.writeUInt32LE(Constants.ZIP64SIG,offset);Utils.writeBigUInt64LE(b,Constants.ZIP64HDR-Constants.ZIP64LEAD,offset+Constants.ZIP64SIZE);b.writeUInt16LE(45,offset+Constants.ZIP64VEM);b.writeUInt16LE(45,offset+Constants.ZIP64VER);b.writeUInt32LE(0,offset+Constants.ZIP64DSK);b.writeUInt32LE(0,offset+Constants.ZIP64DSKDIR);Utils.writeBigUInt64LE(b,_volumeEntries,offset+Constants.ZIP64SUB);Utils.writeBigUInt64LE(b,_totalEntries,offset+Constants.ZIP64TOT);Utils.writeBigUInt64LE(b,_size,offset+Constants.ZIP64SIZB);Utils.writeBigUInt64LE(b,_offset,offset+Constants.ZIP64OFF);const zip64EndOffset=_offset+_size;offset+=Constants.ZIP64HDR;b.writeUInt32LE(Constants.END64SIG,offset);b.writeUInt32LE(0,offset+Constants.END64START);Utils.writeBigUInt64LE(b,zip64EndOffset,offset+Constants.END64OFF);b.writeUInt32LE(1,offset+Constants.END64NUMDISKS);offset+=Constants.END64HDR;b.writeUInt32LE(Constants.ENDSIG,offset);b.writeUInt32LE(0,offset+4);b.writeUInt16LE(Math.min(_volumeEntries,Constants.EF_ZIP64_OR_16),offset+Constants.ENDSUB);b.writeUInt16LE(Math.min(_totalEntries,Constants.EF_ZIP64_OR_16),offset+Constants.ENDTOT);b.writeUInt32LE(Math.min(_size,Constants.EF_ZIP64_OR_32),offset+Constants.ENDSIZ);b.writeUInt32LE(Math.min(_offset,Constants.EF_ZIP64_OR_32),offset+Constants.ENDOFF);b.writeUInt16LE(_commentLength,offset+Constants.ENDCOM);b.fill(" ",offset+Constants.ENDHDR);return b},toJSON:function(){const offset=function(nr,len){let offs=nr.toString(16).toUpperCase();while(offs.length<len)offs="0"+offs;return"0x"+offs};return{diskEntries:_volumeEntries,totalEntries:_totalEntries,size:_size+" bytes",offset:offset(_offset,4),commentLength:_commentLength}},toString:function(){return JSON.stringify(this.toJSON(),null,"\t")}}}});var require_headers=__commonJS(function(exports){exports.EntryHeader=require_entryHeader();exports.MainHeader=require_mainHeader()});var require_deflater=__commonJS(function(exports,module){module.exports=function(inbuf){var zlib=__require("zlib");var opts={chunkSize:(parseInt(inbuf.length/1024)+1)*1024};return{deflate:function(){return zlib.deflateRawSync(inbuf,opts)},deflateAsync:function(callback){var tmp=zlib.createDeflateRaw(opts),parts=[],total=0;tmp.on("data",function(data){parts.push(data);total+=data.length});tmp.on("end",function(){var buf=Buffer.alloc(total),written=0;buf.fill(0);for(var i=0;i<parts.length;i++){var part=parts[i];part.copy(buf,written);written+=part.length}callback&&callback(buf)});tmp.end(inbuf)}}}});var require_inflater=__commonJS(function(exports,module){var version=+(process?.versions?.node??"").split(".")[0]||0;var Errors=require_errors();module.exports=function(inbuf,expectedLength){var zlib=__require("zlib");const maxOutputLength=expectedLength>0?expectedLength:1;const option=version>=15?{maxOutputLength}:{};return{inflate:function(){return zlib.inflateRawSync(inbuf,option)},inflateAsync:function(callback){var tmp=zlib.createInflateRaw(option),parts=[],total=0,done=false;const fail=function(err){if(done)return;done=true;tmp.destroy();callback&&callback(Buffer.alloc(0),err)};tmp.on("error",function(err){fail(err)});tmp.on("data",function(data){if(done)return;total+=data.length;if(total>maxOutputLength){return fail(Errors.MAX_OUTPUT_EXCEEDED())}parts.push(data)});tmp.on("end",function(){if(done)return;done=true;var buf=Buffer.alloc(total),written=0;buf.fill(0);for(var i=0;i<parts.length;i++){var part=parts[i];part.copy(buf,written);written+=part.length}callback&&callback(buf)});tmp.end(inbuf)}}}});var require_zipcrypto=__commonJS(function(exports,module){var{randomFillSync}=__require("crypto");var Errors=require_errors();var crctable=new Uint32Array(256).map((t,crc)=>{for(let j=0;j<8;j++){if((crc&1)!==0){crc=crc>>>1^3988292384}else{crc>>>=1}}return crc>>>0});var uMul=(a,b)=>Math.imul(a,b)>>>0;var crc32update=(pCrc32,bval)=>{return crctable[(pCrc32^bval)&255]^pCrc32>>>8};var genSalt=()=>{if(typeof randomFillSync==="function"){return randomFillSync(Buffer.alloc(12))}else{return genSalt.node()}};genSalt.node=()=>{const salt=Buffer.alloc(12);const len=salt.length;for(let i=0;i<len;i++)salt[i]=Math.random()*256&255;return salt};var config={genSalt};function Initkeys(pw){const pass=Buffer.isBuffer(pw)?pw:Buffer.from(pw);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let i=0;i<pass.length;i++){this.updateKeys(pass[i])}}Initkeys.prototype.updateKeys=function(byteValue){const keys=this.keys;keys[0]=crc32update(keys[0],byteValue);keys[1]+=keys[0]&255;keys[1]=uMul(keys[1],134775813)+1;keys[2]=crc32update(keys[2],keys[1]>>>24);return byteValue};Initkeys.prototype.next=function(){const k=(this.keys[2]|2)>>>0;return uMul(k,k^1)>>8&255};function make_decrypter(pwd){const keys=new Initkeys(pwd);return function(data){const result=Buffer.alloc(data.length);let pos=0;for(let c of data){result[pos++]=keys.updateKeys(c^keys.next())}return result}}function make_encrypter(pwd){const keys=new Initkeys(pwd);return function(data,result,pos=0){if(!result)result=Buffer.alloc(data.length);for(let c of data){const k=keys.next();result[pos++]=c^k;keys.updateKeys(c)}return result}}function decrypt(data,header,pwd){if(!data||!Buffer.isBuffer(data)||data.length<12){return Buffer.alloc(0)}const decrypter=make_decrypter(pwd);const salt=decrypter(data.slice(0,12));const verifyByte=(header.flags&8)===8?header.timeHighByte:header.crc>>>24;if(salt[11]!==verifyByte){throw Errors.WRONG_PASSWORD()}return decrypter(data.slice(12))}function _salter(data){if(Buffer.isBuffer(data)&&data.length>=12){config.genSalt=function(){return data.slice(0,12)}}else if(data==="node"){config.genSalt=genSalt.node}else{config.genSalt=genSalt}}function encrypt(data,header,pwd,oldlike=false){if(data==null)data=Buffer.alloc(0);if(!Buffer.isBuffer(data))data=Buffer.from(data.toString());const encrypter=make_encrypter(pwd);const salt=config.genSalt();salt[11]=header.crc>>>24&255;if(oldlike)salt[10]=header.crc>>>16&255;const result=Buffer.alloc(data.length+12);encrypter(salt,result);return encrypter(data,result,12)}module.exports={decrypt,encrypt,_salter}});var require_methods=__commonJS(function(exports){exports.Deflater=require_deflater();exports.Inflater=require_inflater();exports.ZipCrypto=require_zipcrypto()});var require_zipEntry=__commonJS(function(exports,module){var Utils=require_util();var Headers2=require_headers();var Constants=Utils.Constants;var Methods=require_methods();module.exports=function(options,input){var _centralHeader=new Headers2.EntryHeader,_entryName=Buffer.alloc(0),_comment=Buffer.alloc(0),_isDirectory=false,uncompressedData=null,_extra=Buffer.alloc(0),_extralocal=Buffer.alloc(0),_efs=true;const opts=options;const decoder=typeof opts.decoder==="object"?opts.decoder:Utils.decoder;_efs=decoder.hasOwnProperty("efs")?decoder.efs:false;function getCompressedDataFromZip(){if(!input||!(input instanceof Uint8Array)){return Buffer.alloc(0)}_extralocal=_centralHeader.loadLocalHeaderFromBinary(input);const dataOffset=_centralHeader.realDataOffset;const dataEnd=dataOffset+_centralHeader.compressedSize;if(dataOffset<0||dataEnd<dataOffset||dataEnd>input.length){throw Utils.Errors.INVALID_LOC()}return input.slice(dataOffset,dataEnd)}function crc32OK(data){const expectedCrc=_centralHeader.flags_desc||_centralHeader.localHeader.flags_desc?_centralHeader.crc:_centralHeader.localHeader.crc;return Utils.crc32(data)===expectedCrc}function decompress(async,callback,pass){if(typeof callback==="undefined"&&typeof async==="string"){pass=async;async=undefined}if(_isDirectory){if(async&&callback){callback(Buffer.alloc(0),Utils.Errors.DIRECTORY_CONTENT_ERROR())}return Buffer.alloc(0)}var compressedData;try{compressedData=getCompressedDataFromZip();if(compressedData.length===0){if(async&&callback)callback(compressedData);return compressedData}if(_centralHeader.encrypted){if(typeof pass!=="string"&&!Buffer.isBuffer(pass)){throw Utils.Errors.INVALID_PASS_PARAM()}compressedData=Methods.ZipCrypto.decrypt(compressedData,_centralHeader,pass)}}catch(err){if(async&&callback){callback(Buffer.alloc(0),err);return Buffer.alloc(0)}throw err}var data;switch(_centralHeader.method){case Utils.Constants.STORED:data=Buffer.alloc(compressedData.length);compressedData.copy(data);if(!crc32OK(data)){if(async&&callback)callback(data,Utils.Errors.BAD_CRC());throw Utils.Errors.BAD_CRC()}else{if(async&&callback)callback(data);return data}case Utils.Constants.DEFLATED:var inflater=new Methods.Inflater(compressedData,_centralHeader.size);if(!async){data=inflater.inflate();if(!crc32OK(data)){throw Utils.Errors.BAD_CRC(`"${decoder.decode(_entryName)}"`)}return data}else{inflater.inflateAsync(function(result,err){if(!callback)return;if(err){callback(Buffer.alloc(0),err)}else if(!crc32OK(result)){callback(result,Utils.Errors.BAD_CRC())}else{callback(result)}})}break;default:if(async&&callback)callback(Buffer.alloc(0),Utils.Errors.UNKNOWN_METHOD());throw Utils.Errors.UNKNOWN_METHOD()}}function compress(async,callback){if((!uncompressedData||!uncompressedData.length)&&Buffer.isBuffer(input)){if(async&&callback)callback(getCompressedDataFromZip());return getCompressedDataFromZip()}if(uncompressedData.length&&!_isDirectory){var compressedData;switch(_centralHeader.method){case Utils.Constants.STORED:_centralHeader.compressedSize=_centralHeader.size;compressedData=Buffer.alloc(uncompressedData.length);uncompressedData.copy(compressedData);if(async&&callback)callback(compressedData);return compressedData;default:case Utils.Constants.DEFLATED:var deflater=new Methods.Deflater(uncompressedData);if(!async){var deflated=deflater.deflate();_centralHeader.compressedSize=deflated.length;return deflated}else{deflater.deflateAsync(function(data){compressedData=Buffer.alloc(data.length);_centralHeader.compressedSize=data.length;data.copy(compressedData);callback&&callback(compressedData)})}deflater=null;break}}else if(async&&callback){callback(Buffer.alloc(0))}else{return Buffer.alloc(0)}}function readUInt64LE(buffer,offset){return Utils.readBigUInt64LE(buffer,offset)}function parseExtra(data){try{var offset=0;var signature,size,part;while(offset+4<data.length){signature=data.readUInt16LE(offset);offset+=2;size=data.readUInt16LE(offset);offset+=2;part=data.slice(offset,offset+size);offset+=size;if(Constants.ID_ZIP64===signature){parseZip64ExtendedInformation(part)}}}catch(error){throw Utils.Errors.EXTRA_FIELD_PARSE_ERROR()}}function parseZip64ExtendedInformation(data){var size,compressedSize,offset,diskNumStart;if(data.length>=Constants.EF_ZIP64_SCOMP){size=readUInt64LE(data,Constants.EF_ZIP64_SUNCOMP);if(_centralHeader.size===Constants.EF_ZIP64_OR_32){_centralHeader.size=size}}if(data.length>=Constants.EF_ZIP64_RHO){compressedSize=readUInt64LE(data,Constants.EF_ZIP64_SCOMP);if(_centralHeader.compressedSize===Constants.EF_ZIP64_OR_32){_centralHeader.compressedSize=compressedSize}}if(data.length>=Constants.EF_ZIP64_DSN){offset=readUInt64LE(data,Constants.EF_ZIP64_RHO);if(_centralHeader.offset===Constants.EF_ZIP64_OR_32){_centralHeader.offset=offset}}if(data.length>=Constants.EF_ZIP64_DSN+4){diskNumStart=data.readUInt32LE(Constants.EF_ZIP64_DSN);if(_centralHeader.diskNumStart===Constants.EF_ZIP64_OR_16){_centralHeader.diskNumStart=diskNumStart}}}return{get entryName(){return decoder.decode(_entryName)},get rawEntryName(){return _entryName},set entryName(val){_entryName=Utils.toBuffer(val,decoder.encode);var lastChar=_entryName[_entryName.length-1];_isDirectory=lastChar===47||lastChar===92;_centralHeader.fileNameLength=_entryName.length},get efs(){if(typeof _efs==="function"){return _efs(this.entryName)}else{return _efs}},get extra(){return _extra},set extra(val){_extra=val;_centralHeader.extraLength=val.length;parseExtra(val)},get comment(){return decoder.decode(_comment)},set comment(val){_comment=Utils.toBuffer(val,decoder.encode);_centralHeader.commentLength=_comment.length;if(_comment.length>65535)throw Utils.Errors.COMMENT_TOO_LONG()},get name(){const n=decoder.decode(_entryName);return _isDirectory?n.replace(/[/\\]$/,"").split("/").pop():n.split("/").pop()},get isDirectory(){return _isDirectory},getCompressedData:function(){return compress(false,null)},getCompressedDataAsync:function(callback){compress(true,callback)},setData:function(value){uncompressedData=Utils.toBuffer(value,Utils.decoder.encode);if(!_isDirectory&&uncompressedData.length){_centralHeader.size=uncompressedData.length;_centralHeader.method=Utils.Constants.DEFLATED;_centralHeader.crc=Utils.crc32(value);_centralHeader.changed=true}else{_centralHeader.method=Utils.Constants.STORED}},getData:function(pass){if(_centralHeader.changed){return uncompressedData}else{return decompress(false,null,pass)}},getDataAsync:function(callback,pass){if(_centralHeader.changed){callback(uncompressedData)}else{decompress(true,callback,pass)}},set attr(attr){_centralHeader.attr=attr},get attr(){return _centralHeader.attr},set header(data){_centralHeader.loadFromBinary(data)},get header(){return _centralHeader},packCentralHeader:function(){_centralHeader.flags_efs=this.efs;_centralHeader.extraLength=_extra.length;var header=_centralHeader.centralHeaderToBinary();var addpos=Utils.Constants.CENHDR;_entryName.copy(header,addpos);addpos+=_entryName.length;_extra.copy(header,addpos);addpos+=_centralHeader.extraLength;_comment.copy(header,addpos);return header},packLocalHeader:function(){let addpos=0;_centralHeader.flags_efs=this.efs;_centralHeader.extraLocalLength=_extralocal.length;const localHeaderBuf=_centralHeader.localHeaderToBinary();const localHeader=Buffer.alloc(localHeaderBuf.length+_entryName.length+_centralHeader.extraLocalLength);localHeaderBuf.copy(localHeader,addpos);addpos+=localHeaderBuf.length;_entryName.copy(localHeader,addpos);addpos+=_entryName.length;_extralocal.copy(localHeader,addpos);addpos+=_extralocal.length;return localHeader},toJSON:function(){const bytes=function(nr){return"<"+(nr&&nr.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:_centralHeader.toJSON(),compressedData:bytes(input),data:bytes(uncompressedData)}},toString:function(){return JSON.stringify(this.toJSON(),null,"\t")}}}});var require_zipFile=__commonJS(function(exports,module){var ZipEntry=require_zipEntry();var Headers2=require_headers();var Utils=require_util();module.exports=function(inBuffer,options){var entryList=[],entryTable=Object.create(null),_comment=Buffer.alloc(0),mainHeader=new Headers2.MainHeader,loadedEntries=false;var password=null;const temporary=new Set;const opts=options;const{noSort,decoder}=opts;if(inBuffer){readMainHeader(opts.readEntries)}else{loadedEntries=true}function makeTemporaryFolders(){const foldersList=new Set;for(const elem of Object.keys(entryTable)){const elements=elem.split("/");elements.pop();if(!elements.length)continue;for(let i=0;i<elements.length;i++){const sub=elements.slice(0,i+1).join("/")+"/";foldersList.add(sub)}}for(const elem of foldersList){if(!(elem in entryTable)){const tempfolder=new ZipEntry(opts);tempfolder.entryName=elem;tempfolder.attr=16;tempfolder.temporary=true;entryList.push(tempfolder);entryTable[tempfolder.entryName]=tempfolder;temporary.add(tempfolder)}}}function readEntries(){loadedEntries=true;entryTable=Object.create(null);if(mainHeader.diskEntries>(inBuffer.length-mainHeader.offset)/Utils.Constants.CENHDR){throw Utils.Errors.DISK_ENTRY_TOO_LARGE()}entryList=new Array(mainHeader.diskEntries);var index=mainHeader.offset;for(var i=0;i<entryList.length;i++){var tmp=index,entry=new ZipEntry(opts,inBuffer);entry.header=inBuffer.slice(tmp,tmp+=Utils.Constants.CENHDR);entry.entryName=inBuffer.slice(tmp,tmp+=entry.header.fileNameLength);if(entry.header.extraLength){entry.extra=inBuffer.slice(tmp,tmp+=entry.header.extraLength)}if(entry.header.commentLength)entry.comment=inBuffer.slice(tmp,tmp+entry.header.commentLength);index+=entry.header.centralHeaderSize;if(entry.entryName in entryTable){throw Utils.Errors.DUPLICATE_ENTRY(`"${entry.entryName}"`)}entryList[i]=entry;entryTable[entry.entryName]=entry}temporary.clear();makeTemporaryFolders()}function readMainHeader(readNow){var i=inBuffer.length-Utils.Constants.ENDHDR,max=Math.max(0,i-65535),n=max,endStart=inBuffer.length,endOffset=-1,commentEnd=0;const trailingSpace=typeof opts.trailingSpace==="boolean"?opts.trailingSpace:false;if(trailingSpace)max=0;for(i;i>=n;i--){if(inBuffer[i]!==80)continue;if(inBuffer.readUInt32LE(i)===Utils.Constants.ENDSIG){endOffset=i;commentEnd=i;endStart=i+Utils.Constants.ENDHDR;n=i-Utils.Constants.END64HDR;continue}if(inBuffer.readUInt32LE(i)===Utils.Constants.END64SIG){n=max;continue}if(inBuffer.readUInt32LE(i)===Utils.Constants.ZIP64SIG){endOffset=i;endStart=i+Utils.readBigUInt64LE(inBuffer,i+Utils.Constants.ZIP64SIZE)+Utils.Constants.ZIP64LEAD;break}}if(endOffset==-1)throw Utils.Errors.INVALID_FORMAT();mainHeader.loadFromBinary(inBuffer.slice(endOffset,endStart));if(mainHeader.commentLength){_comment=inBuffer.slice(commentEnd+Utils.Constants.ENDHDR)}if(readNow)readEntries()}function sortEntries(){if(entryList.length>1&&!noSort){entryList=entryList.map((entry)=>({entry,key:entry.entryName.toLowerCase()})).sort((a,b)=>a.key.localeCompare(b.key)).map((pair)=>pair.entry)}}return{get entries(){if(!loadedEntries){readEntries()}return entryList.filter((e)=>!temporary.has(e))},get comment(){return decoder.decode(_comment)},set comment(val){_comment=Utils.toBuffer(val,decoder.encode);mainHeader.commentLength=_comment.length},getEntryCount:function(){if(!loadedEntries){return mainHeader.diskEntries}return entryList.length},forEach:function(callback){this.entries.forEach(callback)},getEntry:function(entryName){if(!loadedEntries){readEntries()}return entryTable[entryName]||null},setEntry:function(entry){if(!loadedEntries){readEntries()}entryList.push(entry);entryTable[entry.entryName]=entry;mainHeader.totalEntries=entryList.length},deleteFile:function(entryName,withsubfolders=true){if(!loadedEntries){readEntries()}const entry=entryTable[entryName];const list=this.getEntryChildren(entry,withsubfolders).map((child)=>child.entryName);list.forEach(this.deleteEntry)},deleteEntry:function(entryName){if(!loadedEntries){readEntries()}const entry=entryTable[entryName];const index=entryList.indexOf(entry);if(index>=0){entryList.splice(index,1);delete entryTable[entryName];mainHeader.totalEntries=entryList.length}},getEntryChildren:function(entry,subfolders=true){if(!loadedEntries){readEntries()}if(typeof entry==="object"){if(entry.isDirectory&&subfolders){const list=[];const name=entry.entryName;for(const zipEntry of entryList){if(zipEntry.entryName.startsWith(name)){list.push(zipEntry)}}return list}else{return[entry]}}return[]},getChildCount:function(entry){if(entry&&entry.isDirectory){const list=this.getEntryChildren(entry);return list.includes(entry)?list.length-1:list.length}return 0},compressToBuffer:function(){if(!loadedEntries){readEntries()}sortEntries();const dataBlock=[];const headerBlocks=[];let totalSize=0;let dindex=0;mainHeader.size=0;mainHeader.offset=0;let totalEntries=0;for(const entry of this.entries){const compressedData=entry.getCompressedData();entry.header.offset=dindex;const localHeader=entry.packLocalHeader();const dataLength=localHeader.length+compressedData.length;dindex+=dataLength;dataBlock.push(localHeader);dataBlock.push(compressedData);const centralHeader=entry.packCentralHeader();headerBlocks.push(centralHeader);mainHeader.size+=centralHeader.length;totalSize+=dataLength+centralHeader.length;totalEntries++}totalSize+=mainHeader.mainHeaderSize;mainHeader.offset=dindex;mainHeader.totalEntries=totalEntries;dindex=0;const outBuffer=Buffer.alloc(totalSize);for(const content of dataBlock){content.copy(outBuffer,dindex);dindex+=content.length}for(const content of headerBlocks){content.copy(outBuffer,dindex);dindex+=content.length}const mh=mainHeader.toBinary();if(_comment){_comment.copy(mh,mh.length-_comment.length)}mh.copy(outBuffer,dindex);inBuffer=outBuffer;loadedEntries=false;return outBuffer},toAsyncBuffer:function(onSuccess,onFail,onItemStart,onItemEnd){try{if(!loadedEntries){readEntries()}sortEntries();const dataBlock=[];const centralHeaders=[];let totalSize=0;let dindex=0;let totalEntries=0;mainHeader.size=0;mainHeader.offset=0;const compress2Buffer=function(entryLists){if(entryLists.length>0){const entry=entryLists.shift();const name=entry.entryName+entry.extra.toString();if(onItemStart)onItemStart(name);entry.getCompressedDataAsync(function(compressedData){if(onItemEnd)onItemEnd(name);entry.header.offset=dindex;const localHeader=entry.packLocalHeader();const dataLength=localHeader.length+compressedData.length;dindex+=dataLength;dataBlock.push(localHeader);dataBlock.push(compressedData);const centalHeader=entry.packCentralHeader();centralHeaders.push(centalHeader);mainHeader.size+=centalHeader.length;totalSize+=dataLength+centalHeader.length;totalEntries++;compress2Buffer(entryLists)})}else{totalSize+=mainHeader.mainHeaderSize;mainHeader.offset=dindex;mainHeader.totalEntries=totalEntries;dindex=0;const outBuffer=Buffer.alloc(totalSize);dataBlock.forEach(function(content){content.copy(outBuffer,dindex);dindex+=content.length});centralHeaders.forEach(function(content){content.copy(outBuffer,dindex);dindex+=content.length});const mh=mainHeader.toBinary();if(_comment){_comment.copy(mh,mh.length-_comment.length)}mh.copy(outBuffer,dindex);inBuffer=outBuffer;loadedEntries=false;onSuccess(outBuffer)}};compress2Buffer(Array.from(this.entries))}catch(e){onFail(e)}}}}});var require_adm_zip=__commonJS(function(exports,module){var Utils=require_util();var pth=__require("path");var ZipEntry=require_zipEntry();var ZipFile=require_zipFile();var get_Bool=(...val)=>Utils.findLast(val,(c)=>typeof c==="boolean");var get_Str=(...val)=>Utils.findLast(val,(c)=>typeof c==="string");var get_Fun=(...val)=>Utils.findLast(val,(c)=>typeof c==="function");var defaultOptions={noSort:false,readEntries:false,method:Utils.Constants.NONE,fs:null};module.exports=function(input,options){let inBuffer=null;const opts=Object.assign(Object.create(null),defaultOptions);if(input&&typeof input==="object"){if(!(input instanceof Uint8Array)){Object.assign(opts,input);input=opts.input?opts.input:undefined;if(opts.input)delete opts.input}if(Buffer.isBuffer(input)){inBuffer=input;opts.method=Utils.Constants.BUFFER;input=undefined}}Object.assign(opts,options);const filetools=new Utils(opts);const applyDirAttributes=(dirEntries)=>{dirEntries.filter((d)=>d.attr).sort((a,b)=>b.path.length-a.path.length).forEach((d)=>filetools.fs.chmodSync(d.path,d.attr))};if(typeof opts.decoder!=="object"||typeof opts.decoder.encode!=="function"||typeof opts.decoder.decode!=="function"){opts.decoder=Utils.decoder}if(input&&typeof input==="string"){if(filetools.fs.existsSync(input)){opts.method=Utils.Constants.FILE;opts.filename=input;inBuffer=filetools.fs.readFileSync(input)}else{throw Utils.Errors.INVALID_FILENAME()}}const _zip=new ZipFile(inBuffer,opts);const{canonical,sanitize,zipnamefix}=Utils;function getEntry(entry){if(entry&&_zip){var item;if(typeof entry==="string")item=_zip.getEntry(pth.posix.normalize(entry));if(typeof entry==="object"&&typeof entry.entryName!=="undefined"&&typeof entry.header!=="undefined")item=_zip.getEntry(entry.entryName);if(item){return item}}return null}function fixPath(zipPath){const{join,normalize,sep}=pth.posix;return join(pth.isAbsolute(zipPath)?"/":".",normalize(sep+zipPath.split("\\").join(sep)+sep))}function filenameFilter(filterfn){if(filterfn instanceof RegExp){return function(rx){return function(filename){return rx.test(filename)}}(filterfn)}else if(typeof filterfn!=="function"){return()=>true}return filterfn}const relativePath=(local,entry)=>{let lastChar=entry.slice(-1);lastChar=lastChar===filetools.sep?filetools.sep:"";return pth.relative(local,entry)+lastChar};return{readFile:function(entry,pass){var item=getEntry(entry);return item&&item.getData(pass)||null},childCount:function(entry){const item=getEntry(entry);if(item){return _zip.getChildCount(item)}},readFileAsync:function(entry,callback){var item=getEntry(entry);if(item){item.getDataAsync(callback)}else{callback(null,"getEntry failed for:"+entry)}},readAsText:function(entry,encoding){var item=getEntry(entry);if(item){var data=item.getData();if(data&&data.length){return data.toString(encoding||"utf8")}}return""},readAsTextAsync:function(entry,callback,encoding){var item=getEntry(entry);if(item){item.getDataAsync(function(data,err){if(err){callback(data,err);return}if(data&&data.length){callback(data.toString(encoding||"utf8"))}else{callback("")}})}else{callback("")}},deleteFile:function(entry,withsubfolders=true){var item=getEntry(entry);if(item){_zip.deleteFile(item.entryName,withsubfolders)}},deleteEntry:function(entry){var item=getEntry(entry);if(item){_zip.deleteEntry(item.entryName)}},addZipComment:function(comment){_zip.comment=comment},getZipComment:function(){return _zip.comment||""},addZipEntryComment:function(entry,comment){var item=getEntry(entry);if(item){item.comment=comment}},getZipEntryComment:function(entry){var item=getEntry(entry);if(item){return item.comment||""}return""},updateFile:function(entry,content){var item=getEntry(entry);if(item){item.setData(content)}},addLocalFile:function(localPath,zipPath,zipName,comment){if(filetools.fs.existsSync(localPath)){zipPath=zipPath?fixPath(zipPath):"";const p=pth.win32.basename(pth.win32.normalize(localPath));zipPath+=zipName?zipName:p;const _attr=filetools.fs.statSync(localPath);const data=_attr.isFile()?filetools.fs.readFileSync(localPath):Buffer.alloc(0);if(_attr.isDirectory())zipPath+=filetools.sep;this.addFile(zipPath,data,comment,_attr)}else{throw Utils.Errors.FILE_NOT_FOUND(localPath)}},addLocalFileAsync:function(options,callback){options=typeof options==="object"?options:{localPath:options};const localPath=pth.resolve(options.localPath);const{comment}=options;let{zipPath,zipName}=options;const self=this;filetools.fs.stat(localPath,function(err,stats){if(err)return callback(err,false);zipPath=zipPath?fixPath(zipPath):"";const p=pth.win32.basename(pth.win32.normalize(localPath));zipPath+=zipName?zipName:p;if(stats.isFile()){filetools.fs.readFile(localPath,function(err,data){if(err)return callback(err,false);self.addFile(zipPath,data,comment,stats);return setImmediate(callback,undefined,true)})}else if(stats.isDirectory()){zipPath+=filetools.sep;self.addFile(zipPath,Buffer.alloc(0),comment,stats);return setImmediate(callback,undefined,true)}})},addLocalFolder:function(localPath,zipPath,filter){filter=filenameFilter(filter);zipPath=zipPath?fixPath(zipPath):"";localPath=pth.normalize(localPath);if(filetools.fs.existsSync(localPath)){const items=filetools.findFiles(localPath);const self=this;if(items.length){for(const filepath of items){const p=pth.join(zipPath,relativePath(localPath,filepath));if(filter(p)){self.addLocalFile(filepath,pth.dirname(p))}}}}else{throw Utils.Errors.FILE_NOT_FOUND(localPath)}},addLocalFolderAsync:function(localPath,callback,zipPath,filter){filter=filenameFilter(filter);zipPath=zipPath?fixPath(zipPath):"";localPath=pth.normalize(localPath);var self=this;filetools.fs.open(localPath,"r",function(err){if(err&&err.code==="ENOENT"){callback(undefined,Utils.Errors.FILE_NOT_FOUND(localPath))}else if(err){callback(undefined,err)}else{var items=filetools.findFiles(localPath);var i=-1;var next=function(){i+=1;if(i<items.length){var filepath=items[i];var p=relativePath(localPath,filepath).split("\\").join("/");p=p.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"");if(filter(p)){filetools.fs.stat(filepath,function(er0,stats){if(er0)callback(undefined,er0);if(stats.isFile()){filetools.fs.readFile(filepath,function(er1,data){if(er1){callback(undefined,er1)}else{self.addFile(zipPath+p,data,"",stats);next()}})}else{self.addFile(zipPath+p+"/",Buffer.alloc(0),"",stats);next()}})}else{process.nextTick(()=>{next()})}}else{callback(true,undefined)}};next()}})},addLocalFolderAsync2:function(options,callback){const self=this;options=typeof options==="object"?options:{localPath:options};const localPath=pth.resolve(options.localPath);let{zipPath,filter,namefix}=options;if(filter instanceof RegExp){filter=function(rx){return function(filename){return rx.test(filename)}}(filter)}else if(typeof filter!=="function"){filter=function(){return true}}zipPath=zipPath?fixPath(zipPath):"";if(namefix==="latin1"){namefix=(str)=>str.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")}if(typeof namefix!=="function")namefix=(str)=>str;const relPathFix=(entry)=>pth.join(zipPath,namefix(relativePath(localPath,entry)));const fileNameFix=(entry)=>pth.win32.basename(pth.win32.normalize(namefix(entry)));filetools.fs.open(localPath,"r",function(err){if(err&&err.code==="ENOENT"){callback(Utils.Errors.FILE_NOT_FOUND(localPath),false)}else if(err){callback(err,false)}else{filetools.findFilesAsync(localPath,function(err,fileEntries){if(err)return callback(err,false);fileEntries=fileEntries.filter((dir)=>filter(relPathFix(dir)));if(!fileEntries.length)return callback(undefined,true);setImmediate(fileEntries.reverse().reduce(function(next,entry){return function(err,done){if(err||done===false)return setImmediate(next,err,false);self.addLocalFileAsync({localPath:entry,zipPath:pth.dirname(relPathFix(entry)),zipName:fileNameFix(entry)},next)}},callback))})}})},addLocalFolderPromise:function(localPath,props){return new Promise((resolve,reject)=>{this.addLocalFolderAsync2(Object.assign({localPath},props),(err,done)=>{if(err)return reject(err);if(done)resolve(this)})})},addFile:function(entryName,content,comment,attr){entryName=zipnamefix(entryName);let entry=getEntry(entryName);const update=entry!=null;if(!update){entry=new ZipEntry(opts);entry.entryName=entryName}entry.comment=comment||"";const isStat=typeof attr==="object"&&attr instanceof filetools.fs.Stats;if(isStat){entry.header.time=attr.mtime}var fileattr=entry.isDirectory?16:0;let unix=entry.isDirectory?16384:32768;if(isStat){unix|=4095&attr.mode}else if(typeof attr==="number"){unix|=4095&attr}else{unix|=entry.isDirectory?493:420}fileattr=(fileattr|unix<<16)>>>0;entry.attr=fileattr;entry.setData(content);if(!update)_zip.setEntry(entry);return entry},getEntries:function(password){_zip.password=password;return _zip?_zip.entries:[]},getEntry:function(name){return getEntry(name)},getEntryCount:function(){return _zip.getEntryCount()},forEach:function(callback){return _zip.forEach(callback)},extractEntryTo:function(entry,targetPath,maintainEntryPath,overwrite,keepOriginalPermission,outFileName){overwrite=get_Bool(false,overwrite);keepOriginalPermission=get_Bool(false,keepOriginalPermission);maintainEntryPath=get_Bool(true,maintainEntryPath);outFileName=get_Str(keepOriginalPermission,outFileName);var item=getEntry(entry);if(!item){throw Utils.Errors.NO_ENTRY()}var entryName=canonical(item.entryName);var target=sanitize(targetPath,outFileName&&!item.isDirectory?canonical(outFileName):maintainEntryPath?entryName:pth.basename(entryName));if(item.isDirectory){var children=_zip.getEntryChildren(item);children.forEach(function(child){if(child.isDirectory)return;var content=child.getData();if(!content){throw Utils.Errors.CANT_EXTRACT_FILE()}var name=canonical(maintainEntryPath?child.entryName:child.entryName.substring(item.entryName.length));var childName=sanitize(targetPath,name);filetools.assertPathSafe(targetPath,childName);const fileAttr=keepOriginalPermission?child.header.fileAttr:undefined;filetools.writeFileTo(childName,content,overwrite,fileAttr)});return true}var content=item.getData(_zip.password);if(!content)throw Utils.Errors.CANT_EXTRACT_FILE();filetools.assertPathSafe(targetPath,target);if(filetools.fs.existsSync(target)&&!overwrite){throw Utils.Errors.CANT_OVERRIDE()}const fileAttr=keepOriginalPermission?entry.header.fileAttr:undefined;filetools.writeFileTo(target,content,overwrite,fileAttr);return true},test:function(pass){if(!_zip){return false}for(var entry of _zip.entries){try{if(entry.isDirectory){continue}var content=entry.getData(pass);if(!content){return false}}catch(err){return false}}return true},extractAllTo:function(targetPath,overwrite,keepOriginalPermission,pass){keepOriginalPermission=get_Bool(false,keepOriginalPermission);pass=get_Str(keepOriginalPermission,pass);overwrite=get_Bool(false,overwrite);if(!_zip)throw Utils.Errors.NO_ZIP();const dirEntries=[];_zip.entries.forEach(function(entry){var entryName=sanitize(targetPath,canonical(entry.entryName));filetools.assertPathSafe(targetPath,entryName);if(entry.isDirectory){filetools.makeDir(entryName);if(keepOriginalPermission)dirEntries.push({path:entryName,attr:entry.header.fileAttr});return}var content=entry.getData(pass);if(!content){throw Utils.Errors.CANT_EXTRACT_FILE()}const fileAttr=keepOriginalPermission?entry.header.fileAttr:undefined;filetools.writeFileTo(entryName,content,overwrite,fileAttr);try{filetools.fs.utimesSync(entryName,entry.header.time,entry.header.time)}catch(err){}});applyDirAttributes(dirEntries)},extractAllToAsync:function(targetPath,overwrite,keepOriginalPermission,callback){callback=get_Fun(overwrite,keepOriginalPermission,callback);keepOriginalPermission=get_Bool(false,keepOriginalPermission);overwrite=get_Bool(false,overwrite);if(!callback){return new Promise((resolve,reject)=>{this.extractAllToAsync(targetPath,overwrite,keepOriginalPermission,function(err){if(err){reject(err)}else{resolve(this)}})})}if(!_zip){callback(Utils.Errors.NO_ZIP());return}targetPath=pth.resolve(targetPath);const getPath=(entry)=>sanitize(targetPath,pth.normalize(canonical(entry.entryName)));const getError=(msg,file)=>new Error(msg+': "'+file+'"');const dirEntries=[];const fileEntries=[];_zip.entries.forEach((e)=>{if(e.isDirectory){dirEntries.push(e)}else{fileEntries.push(e)}});const deferredDirAttr=[];for(const entry of dirEntries){const dirPath=getPath(entry);const dirAttr=keepOriginalPermission?entry.header.fileAttr:undefined;try{filetools.assertPathSafe(targetPath,dirPath);filetools.makeDir(dirPath)}catch(er){callback(getError("Unable to create folder",dirPath));continue}if(dirAttr)deferredDirAttr.push({path:dirPath,attr:dirAttr});try{filetools.fs.utimesSync(dirPath,entry.header.time,entry.header.time)}catch(er){}}const done=(err)=>{if(!err){try{applyDirAttributes(deferredDirAttr)}catch(er){return callback(getError("Unable to set folder permissions",er.path||""))}}callback(err)};fileEntries.reverse().reduce(function(next,entry){return function(err){if(err){next(err)}else{const entryName=pth.normalize(canonical(entry.entryName));const filePath=sanitize(targetPath,entryName);try{filetools.assertPathSafe(targetPath,filePath)}catch(er){return next(er)}entry.getDataAsync(function(content,err_1){if(err_1){next(err_1)}else if(!content){next(Utils.Errors.CANT_EXTRACT_FILE())}else{const fileAttr=keepOriginalPermission?entry.header.fileAttr:undefined;filetools.writeFileToAsync(filePath,content,overwrite,fileAttr,function(succ){if(!succ){return next(getError("Unable to write file",filePath))}filetools.fs.utimes(filePath,entry.header.time,entry.header.time,function(){next()})})}})}}},done)()},writeZip:function(targetFileName,callback){if(arguments.length===1){if(typeof targetFileName==="function"){callback=targetFileName;targetFileName=""}}if(!targetFileName&&opts.filename){targetFileName=opts.filename}if(!targetFileName)return;var zipData=_zip.compressToBuffer();if(zipData){var ok=filetools.writeFileTo(targetFileName,zipData,true);if(typeof callback==="function")callback(!ok?new Error("failed"):null,"")}},writeZipPromise:function(targetFileName,props){const{overwrite,perm}=Object.assign({overwrite:true},props);return new Promise((resolve,reject)=>{if(!targetFileName&&opts.filename)targetFileName=opts.filename;if(!targetFileName)reject("ADM-ZIP: ZIP File Name Missing");this.toBufferPromise().then((zipData)=>{const ret=(done)=>done?resolve(done):reject("ADM-ZIP: Wasn't able to write zip file");filetools.writeFileToAsync(targetFileName,zipData,overwrite,perm,ret)},reject)})},toBufferPromise:function(){return new Promise((resolve,reject)=>{_zip.toAsyncBuffer(resolve,reject)})},toBuffer:function(onSuccess,onFail,onItemStart,onItemEnd){if(typeof onSuccess==="function"){_zip.toAsyncBuffer(onSuccess,onFail,onItemStart,onItemEnd);return null}return _zip.compressToBuffer()}}}});var RUNTIME_001="RUNTIME-001",RUNTIME_002="RUNTIME-002",RUNTIME_003="RUNTIME-003",RUNTIME_004="RUNTIME-004",RUNTIME_005="RUNTIME-005",RUNTIME_006="RUNTIME-006",RUNTIME_007="RUNTIME-007",RUNTIME_008="RUNTIME-008",RUNTIME_009="RUNTIME-009",RUNTIME_010="RUNTIME-010",RUNTIME_011="RUNTIME-011",RUNTIME_012="RUNTIME-012",RUNTIME_013="RUNTIME-013",RUNTIME_014="RUNTIME-014",RUNTIME_015="RUNTIME-015",TYPE_001="TYPE-001",BUILD_001="BUILD-001",BUILD_002="BUILD-002";var init_error_codes=()=>{};var runtimeDescMap,typeDescMap,buildDescMap,errorDescMap;var init_desc=__esm(()=>{init_error_codes();runtimeDescMap={[RUNTIME_001]:"Failed to get remoteEntry exports.",[RUNTIME_002]:'The remote entry interface does not contain "init"',[RUNTIME_003]:"Failed to get manifest.",[RUNTIME_004]:"Failed to locate remote.",[RUNTIME_005]:"Invalid loadShareSync function call from bundler runtime",[RUNTIME_006]:"Invalid loadShareSync function call from runtime",[RUNTIME_007]:"Failed to get remote snapshot.",[RUNTIME_008]:"Failed to load script resources.",[RUNTIME_009]:"Please call createInstance first.",[RUNTIME_010]:'The name option cannot be changed after initialization. If you want to create a new instance with a different name, please use "createInstance" api.',[RUNTIME_011]:"The remoteEntry URL is missing from the remote snapshot.",[RUNTIME_012]:'The getter for the shared module is not a function. This may be caused by setting "shared.import: false" without the host providing the corresponding lib.',[RUNTIME_013]:"The manifest is not a valid Module Federation manifest.",[RUNTIME_014]:"The remote does not expose the requested module.",[RUNTIME_015]:"Remote container initialization failed."};typeDescMap={[TYPE_001]:"Failed to generate type declaration. Execute the below cmd to reproduce and fix the error."};buildDescMap={[BUILD_001]:"Failed to find expose module.",[BUILD_002]:"PublicPath is required in prod mode."};errorDescMap={...runtimeDescMap,...typeDescMap,...buildDescMap}});var init_dist4=__esm(()=>{init_error_codes();init_desc()});var getDocsUrl=(errorCode)=>{return`View the docs to see how to solve: https://module-federation.io/guide/troubleshooting/${errorCode.split("-")[0].toLowerCase()}#${errorCode.toLowerCase()}`},getShortErrorMsg2=(errorCode,errorDescMap,args,originalErrorMsg)=>{const msg=[`${[errorDescMap[errorCode]]} #${errorCode}`];args&&msg.push(`args: ${JSON.stringify(args)}`);msg.push(getDocsUrl(errorCode));originalErrorMsg&&msg.push(`Original Error Message:
199
199
  ${originalErrorMsg}`);return msg.join(`
200
- `)};var init_getShortErrorMsg=()=>{};import fs2 from"fs";import path7 from"path";function reportDiagnostic(code,message,args,context){try{const dir=path7.resolve(process.cwd(),".mf","diagnostics");fs2.mkdirSync(dir,{recursive:true});const output={...context,latestErrorEvent:{code,message,args,timestamp:Date.now()}};fs2.writeFileSync(path7.join(dir,"latest.json"),JSON.stringify(output,null,2))}catch{}}function logAndReport(code,descMap,args,logger,originalErrorMsg,context){const msg=getShortErrorMsg2(code,descMap,args,originalErrorMsg);reportDiagnostic(code,msg,args,context);return logger(msg)}var init_node=__esm(()=>{init_getShortErrorMsg()});import{createRequire as createRequire2}from"module";import fs3,{existsSync as existsSync5,mkdirSync as mkdirSync4,realpathSync as realpathSync2,rmSync,writeFileSync as writeFileSync3}from"fs";import{fileURLToPath as fileURLToPath7}from"url";import path8,{dirname as dirname3,extname,isAbsolute as isAbsolute2,join as join4,normalize as normalize2,relative,resolve as resolve5,sep}from"path";import{cp as cp2,mkdir as mkdir3,readFile as readFile4,readdir as readdir2,rm as rm2,stat as stat3,writeFile as writeFile3}from"fs/promises";import crypto2 from"crypto";import{execFile,execFileSync,fork}from"child_process";import{styleText}from"util";import{Agent}from"undici";import util2 from"util";import WebSocket3 from"ws"with{type:"jsx"};import{createRequire as createRequire$1}from"module";import process$1 from"process";function writeTempTsConfig(tsConfig,context,name,cwd){const createHash=(contents)=>{return crypto2.createHash("md5").update(contents).digest("hex")};const hash=createHash(`${JSON.stringify(tsConfig)}${name}${Date.now()}`);const tempTsConfigJsonPath=resolve5(cwd??context,"node_modules",TEMP_DIR,`tsconfig.${hash}.json`);mkdirSync4(dirname3(tempTsConfigJsonPath),{recursive:true});writeFileSync3(tempTsConfigJsonPath,JSON.stringify(tsConfig,null,2));return tempTsConfigJsonPath}function getExposeKey(options){const{filePath,rootDir,outDir,mapExposeToEntry}=options;return mapExposeToEntry[relative(outDir,filePath.replace(new RegExp(`\\.d.ts$`),""))]}function getDTSManagerConstructor(implementation){if(implementation){const NewConstructor=__require3(implementation);return NewConstructor.default?NewConstructor.default:NewConstructor}return DTSManager}function retrieveTypesAssetsInfo(options){let apiTypesPath="";let zipTypesPath="";try{const{tsConfig,remoteOptions,mapComponentsToExpose}=retrieveRemoteConfig(options);if(!Object.keys(mapComponentsToExpose).length||!tsConfig.files.length)return{apiTypesPath,zipTypesPath,zipName:"",apiFileName:""};zipTypesPath=retrieveTypesZipPath(retrieveMfTypesPath(tsConfig,remoteOptions),remoteOptions);if(remoteOptions.generateAPITypes)apiTypesPath=retrieveMfAPITypesPath(tsConfig,remoteOptions);return{apiTypesPath,zipTypesPath,zipName:path8.basename(zipTypesPath),apiFileName:path8.basename(apiTypesPath)}}catch(err){console.error(styleText("red",`Unable to compile federated types, ${err}`));return{apiTypesPath:"",zipTypesPath:"",zipName:"",apiFileName:""}}}function isDebugMode2(){return Boolean(process.env["FEDERATION_DEBUG"])||process.env["NODE_ENV"]==="test"}function cloneDeepOptions(options){const excludeKeys=new Set(["manifest","async"]);const cache=new WeakMap;function sanitize(val,key){if(key!==undefined&&excludeKeys.has(key)||typeof val==="function")return false;if(key==="extractThirdParty"&&Array.isArray(val))return val.map(String);if(Array.isArray(val)){if(cache.has(val))return cache.get(val);const out=[];cache.set(val,out);val.forEach((v,i)=>out.push(sanitize(v,String(i))));return out}if(val!==null&&typeof val==="object"&&Object.getPrototypeOf(val)===Object.prototype){const obj=val;if(cache.has(obj))return cache.get(obj);const out={};cache.set(obj,out);for(const[k,v]of Object.entries(obj))out[k]=sanitize(v,k);return out}return val}return structuredClone(sanitize(options))}async function nativeFetch(url,config){const controller=new AbortController;const timeoutMs=config?.timeout??60000;const timeoutId=setTimeout(()=>controller.abort(),timeoutMs);const headers={...getEnvHeaders(),...config?.headers??{}};const dispatcher=config?.dispatcher??createDispatcherFromFamily(config?.family);try{const resp=await fetch(url,{headers,signal:controller.signal,...dispatcher?{dispatcher}:{},...config?.agent?{agent:config.agent}:{}});const headerRecord=toHeaderRecord(resp.headers);if(!resp.ok)throw new Error(`Request failed with status ${resp.status}`);if(config?.responseType==="arraybuffer")return{data:await resp.arrayBuffer(),headers:headerRecord,status:resp.status};return{data:(resp.headers.get("content-type")||"").includes("application/json")||url.endsWith(".json")?await resp.json():await resp.text(),headers:headerRecord,status:resp.status}}finally{clearTimeout(timeoutId)}}function getEffectiveRootDir(parsedCommandLine){const compilerOptions=parsedCommandLine.options;if(compilerOptions.rootDir)return compilerOptions.rootDir;const files=parsedCommandLine.fileNames;if(files.length>0)return files.map((file)=>dirname3(file)).reduce((commonPath,fileDir)=>{while(!fileDir.startsWith(commonPath))commonPath=dirname3(commonPath);return commonPath},files[0]);if(parsedCommandLine.projectReferences.length){const relativeReferences=parsedCommandLine.projectReferences.filter((reference)=>!isAbsolute2(reference.originalPath??reference.path));const referencesForRoot=relativeReferences.length?relativeReferences:parsedCommandLine.projectReferences;return referencesForRoot.map((reference)=>dirname3(reference.path)).reduce((commonPath,filePath)=>{while(!filePath.startsWith(commonPath))commonPath=dirname3(commonPath);return commonPath},dirname3(referencesForRoot[0].path))}throw new Error("Can not get effective rootDir, please set compilerOptions.rootDir !")}async function generateTypes(options){return new(getDTSManagerConstructor(options.remote?.implementation))(options).generateTypes()}function exposeRpc(fn){const sendMessage=(message)=>new Promise((resolve,reject)=>{if(!process$1.send)reject(new Error(`Process ${process$1.pid} doesn't have IPC channels`));else if(!process$1.connected)reject(new Error(`Process ${process$1.pid} doesn't have open IPC channels`));else process$1.send(message,undefined,undefined,(error)=>{if(error)reject(error);else resolve(undefined)})});const handleMessage=async(message)=>{if(message.type===RpcGMCallTypes.CALL){if(!process$1.send)return;let value,error;try{value=await fn(...message.args)}catch(fnError){error=fnError}try{if(error)await sendMessage({type:RpcGMCallTypes.REJECT,id:message.id,error});else await sendMessage({type:RpcGMCallTypes.RESOLVE,id:message.id,value})}catch(sendError){if(error){if(error instanceof Error)console.error(error)}console.error(sendError)}}};process$1.on("message",handleMessage)}var import_adm_zip,__defProp2,__exportAll=(all,no_symbols)=>{let target={};for(var name in all){__defProp2(target,name,{get:all[name],enumerable:true})}if(!no_symbols){__defProp2(target,Symbol.toStringTag,{value:"Module"})}return target},__require3,__filename2,__dirname2,parseMajorVersion=(version)=>{const major=Number.parseInt(version.split(".")[0],10);return Number.isNaN(major)?0:major},isMissingTypeScriptPackage=(error)=>typeof error==="object"&&error!==null&&("code"in error)&&error.code==="MODULE_NOT_FOUND"&&("message"in error)&&typeof error.message==="string"&&error.message.includes("typescript/package.json"),resolveTypeScriptPackage=(context=process.cwd())=>{const candidateContexts=[...new Set([context,process.cwd()])];let missingTypeScriptError;for(const candidateContext of candidateContexts){const requireFromContext=createRequire$1(resolve5(candidateContext,"package.json"));try{return{packageJsonPath:requireFromContext.resolve("typescript/package.json"),packageJson:requireFromContext("typescript/package.json"),requireFromContext}}catch(error){if(!isMissingTypeScriptPackage(error))throw error;missingTypeScriptError=error}}throw missingTypeScriptError},getTypeScriptPackageInfo=(context=process.cwd())=>{const{packageJsonPath,packageJson}=resolveTypeScriptPackage(context);const version=packageJson.version||"0.0.0";const packageRoot=dirname3(packageJsonPath);const bin=typeof packageJson.bin==="string"?packageJson.bin:packageJson.bin?.["tsc"]??"./bin/tsc";return{packageJsonPath,packageRoot,version,majorVersion:parseMajorVersion(version),tscBinPath:resolve5(packageRoot,bin)}},requireTypeScript=(context=process.cwd())=>{const{requireFromContext}=resolveTypeScriptPackage(context);return requireFromContext("typescript")},STARTS_WITH_SLASH,DEFINITION_FILE_EXTENSION=".d.ts",retrieveMfTypesPath=(tsConfig,remoteOptions)=>normalize2(tsConfig.compilerOptions.outDir.replace(remoteOptions.compiledTypesFolder,"")),retrieveOriginalOutDir=(tsConfig,remoteOptions)=>normalize2(tsConfig.compilerOptions.outDir.replace(remoteOptions.compiledTypesFolder,"").replace(remoteOptions.typesFolder,"")),retrieveMfAPITypesPath=(tsConfig,remoteOptions)=>join4(retrieveOriginalOutDir(tsConfig,remoteOptions),`${remoteOptions.typesFolder}.d.ts`),removeExt=(f)=>{const vueExt=".vue";const ext=extname(f);if(ext===vueExt)return f;const regexPattern=new RegExp(`\\${ext}$`);return f.replace(regexPattern,"")},processTypesFile=async(options)=>{const{outDir,filePath,rootDir,cb,mapExposeToEntry,mfTypePath}=options;if(!existsSync5(filePath))return;if((await stat3(filePath)).isDirectory()){const files=await readdir2(filePath);await Promise.all(files.map((file)=>processTypesFile({...options,filePath:join4(filePath,file)})))}else if(filePath.endsWith(".d.ts")){const exposeKey=getExposeKey({filePath,rootDir,outDir,mapExposeToEntry});if(exposeKey){const mfeTypeEntry=join4(mfTypePath,`${exposeKey==="."?"index":exposeKey}${DEFINITION_FILE_EXTENSION}`);const mfeTypeEntryDirectory=dirname3(mfeTypeEntry);const relativePathToOutput=relative(mfeTypeEntryDirectory,filePath).replace(DEFINITION_FILE_EXTENSION,"").replace(STARTS_WITH_SLASH,"").split(sep).join("/");mkdirSync4(mfeTypeEntryDirectory,{recursive:true});await writeFile3(mfeTypeEntry,`export * from './${relativePathToOutput}';
201
- export { default } from './${relativePathToOutput}';`)}cb(await readFile4(filePath,"utf8"))}},getPMFromUserAgent=()=>{const userAgent=process.env["npm_config_user_agent"];if(userAgent==null)return"null";return userAgent.split("/")[0]},resolvePackageManagerExecutable=()=>{switch(getPMFromUserAgent()){case"yarn":return"yarn";default:return"npx"}},splitCommandArgs=(value)=>{const args=[];let current="";let quote=null;let escaped=false;for(const char of value){if(escaped){current+=char;escaped=false;continue}if(char==="\\"){escaped=true;continue}if(quote){if(char===quote)quote=null;else current+=char;continue}if(char==='"'||char==="'"){quote=char;continue}if(char.trim()===""){if(current){args.push(current);current=""}continue}current+=char}if(current)args.push(current);return args},formatCommandForDisplay=(executable,args)=>{const formatArg=(arg)=>{if(/[\s'"]/.test(arg))return JSON.stringify(arg);return arg};return[executable,...args].map(formatArg).join(" ")},getTypeScriptContext$1=(remoteOptions)=>{const dtsOptions=remoteOptions.moduleFederationConfig.dts;return typeof dtsOptions!=="boolean"&&dtsOptions?.cwd?dtsOptions.cwd:remoteOptions.context},resolveCompilerCommand=(remoteOptions,tempTsConfigJsonPath)=>{const compilerArgs=splitCommandArgs(remoteOptions.compilerInstance);const resolvedCompilerArgs=compilerArgs.length>0?compilerArgs:[remoteOptions.compilerInstance];if(resolvedCompilerArgs[0]==="tsc"){const args=[getTypeScriptPackageInfo(getTypeScriptContext$1(remoteOptions)).tscBinPath,...resolvedCompilerArgs.slice(1),"--project",tempTsConfigJsonPath];return{executable:process.execPath,args,displayCommand:formatCommandForDisplay(process.execPath,args),shell:false}}const executable=resolvePackageManagerExecutable();const args=[...resolvedCompilerArgs,"--project",tempTsConfigJsonPath];return{executable,args,displayCommand:formatCommandForDisplay(executable,args),shell:process.platform==="win32"}},compileTs=async(mapComponentsToExpose,tsConfig,remoteOptions)=>{if(!Object.keys(mapComponentsToExpose).length)return;const{compilerOptions}=tsConfig;const tempTsConfigJsonPath=writeTempTsConfig(tsConfig,remoteOptions.context,remoteOptions.moduleFederationConfig.name||"mf",typeof remoteOptions.moduleFederationConfig.dts!=="boolean"?remoteOptions.moduleFederationConfig.dts?.cwd??undefined:undefined);logger$1.debug(`tempTsConfigJsonPath: ${tempTsConfigJsonPath}`);try{const mfTypePath=retrieveMfTypesPath(tsConfig,remoteOptions);const thirdPartyExtractor=new ThirdPartyExtractor({destDir:resolve5(mfTypePath,"node_modules"),context:remoteOptions.context,exclude:typeof remoteOptions.extractThirdParty==="object"?remoteOptions.extractThirdParty.exclude:undefined});const execPromise=util2.promisify(execFile);const compilerCommand=resolveCompilerCommand(remoteOptions,tempTsConfigJsonPath);try{await execPromise(compilerCommand.executable,compilerCommand.args,{cwd:getTypeScriptContext$1(remoteOptions),shell:compilerCommand.shell})}catch(err){if(compilerOptions.tsBuildInfoFile)try{await rm2(compilerOptions.tsBuildInfoFile)}catch(e){}logAndReport(TYPE_001,typeDescMap,{cmd:compilerCommand.displayCommand},(msg)=>{throw new Error(msg)},undefined)}const mapExposeToEntry=Object.fromEntries(Object.entries(mapComponentsToExpose).map(([exposed,filename])=>{const normalizedFileName=normalize2(filename);let relativeFileName="";if(isAbsolute2(normalizedFileName))relativeFileName=relative(tsConfig.compilerOptions.rootDir,normalizedFileName);else relativeFileName=relative(tsConfig.compilerOptions.rootDir,resolve5(remoteOptions.context,normalizedFileName));return[removeExt(relativeFileName),exposed]}));const cb=remoteOptions.extractThirdParty?thirdPartyExtractor.collectPkgs.bind(thirdPartyExtractor):()=>{return};await processTypesFile({outDir:compilerOptions.outDir,filePath:compilerOptions.outDir,rootDir:compilerOptions.rootDir,mfTypePath,cb,mapExposeToEntry});if(remoteOptions.extractThirdParty)await thirdPartyExtractor.copyDts();if(remoteOptions.deleteTsConfig)await rm2(tempTsConfigJsonPath)}catch(err){throw err}},retrieveTypesZipPath=(mfTypesPath,remoteOptions)=>join4(mfTypesPath.replace(remoteOptions.typesFolder,""),`${remoteOptions.typesFolder}.zip`),createTypesArchive=async(tsConfig,remoteOptions)=>{const mfTypesPath=retrieveMfTypesPath(tsConfig,remoteOptions);const zip=new import_adm_zip.default;zip.addLocalFolder(mfTypesPath);return zip.writeZipPromise(retrieveTypesZipPath(mfTypesPath,remoteOptions))},downloadErrorLogger=(destinationFolder,fileToDownload)=>(reason)=>{throw{...reason,message:`Network error: Unable to download federated mocks for '${destinationFolder}' from '${fileToDownload}' because '${reason.message}'`}},retrieveTypesArchiveDestinationPath=(hostOptions,destinationFolder)=>{return resolve5(hostOptions.context,hostOptions.typesFolder,destinationFolder)},downloadTypesArchive=(hostOptions)=>{let retries=0;return async([destinationFolder,fileToDownload])=>{const destinationPath=retrieveTypesArchiveDestinationPath(hostOptions,destinationFolder);while(retries++<hostOptions.maxRetries)try{const url=new URL(fileToDownload).href;const response=await nativeFetch(url,{responseType:"arraybuffer",timeout:hostOptions.timeout,family:hostOptions.family}).catch(downloadErrorLogger(destinationFolder,url));if(typeof response.headers?.["content-type"]==="string"&&response.headers["content-type"].includes("text/html"))throw new Error(`${url} receives invalid content-type: ${response.headers["content-type"]}`);try{if(hostOptions.deleteTypesFolder)await rm2(destinationPath,{recursive:true,force:true})}catch(error){fileLog(`Unable to remove types folder, ${error}`,"downloadTypesArchive","error")}new import_adm_zip.default(Buffer.from(response.data)).extractAllTo(destinationPath,true);fileLog(`zip.extractAllTo success destinationPath: ${destinationPath}; url: ${url}`,"downloadTypesArchive","info");return[destinationFolder,destinationPath]}catch(error){fileLog(`Error during types archive download: ${error?.message||"unknown error"}`,"downloadTypesArchive","error");if(retries>=hostOptions.maxRetries){logger$1.error(`Failed to download types archive from "${fileToDownload}". Set FEDERATION_DEBUG=true for details.`);if(hostOptions.abortOnError!==false)throw error;return}}}},defaultOptions$1,buildZipUrl=(hostOptions,url)=>{const remoteUrl=new URL(url,"file:");remoteUrl.pathname=`${remoteUrl.pathname.split("/").slice(0,-1).join("/")}/${hostOptions.remoteTypesFolder}.zip`;return remoteUrl.protocol==="file:"?remoteUrl.pathname:remoteUrl.href},buildApiTypeUrl=(zipUrl)=>{if(!zipUrl)return;return zipUrl.replace(".zip",".d.ts")},retrieveRemoteInfo=(options)=>{const{hostOptions,remoteAlias,remote}=options;const{remoteTypeUrls}=hostOptions;let decodedRemote=remote;if(decodedRemote.startsWith(ENCODE_NAME_PREFIX))decodedRemote=decodeName(decodedRemote,ENCODE_NAME_PREFIX);const parsedInfo=parseEntry(decodedRemote,undefined,"@");const url="entry"in parsedInfo?parsedInfo.entry:parsedInfo.name===decodedRemote?decodedRemote:"";let zipUrl="";let apiTypeUrl="";const name=parsedInfo.name||remoteAlias;const remoteTypeUrl=typeof remoteTypeUrls==="object"&&remoteTypeUrls[name];if(remoteTypeUrl){zipUrl=remoteTypeUrl.zip;apiTypeUrl=remoteTypeUrl.api}const shouldResolveTypeUrlsByConvention=Boolean(url&&!url.includes(MANIFEST_EXT));if(!zipUrl&&shouldResolveTypeUrlsByConvention)zipUrl=buildZipUrl(hostOptions,url);if(!apiTypeUrl&&zipUrl&&(remoteTypeUrl||shouldResolveTypeUrlsByConvention))apiTypeUrl=buildApiTypeUrl(zipUrl);return{name,url,zipUrl,apiTypeUrl,alias:remoteAlias}},resolveRemotes=(hostOptions)=>{const parsedOptions=parseOptions2(hostOptions.moduleFederationConfig.remotes||{},(item,key)=>({remote:Array.isArray(item)?item[0]:item,key}),(item,key)=>({remote:Array.isArray(item.external)?item.external[0]:item.external,key}));const remoteTypeUrls=hostOptions.remoteTypeUrls??{};if(typeof remoteTypeUrls!=="object")throw new Error("remoteTypeUrls must be consumed before resolveRemotes");const remoteInfos=Object.keys(remoteTypeUrls).reduce((sum,remoteName)=>{const{zip,api,alias}=remoteTypeUrls[remoteName];sum[alias]={name:remoteName,url:"",zipUrl:zip,apiTypeUrl:api,alias:alias||remoteName};return sum},{});return parsedOptions.reduce((accumulator,item)=>{const{key,remote}=item[1];const res=retrieveRemoteInfo({hostOptions,remoteAlias:key,remote});if(accumulator[key]){accumulator[key]={...accumulator[key],url:res.url,apiTypeUrl:accumulator[key].apiTypeUrl||res.apiTypeUrl};return accumulator}accumulator[key]=res;return accumulator},remoteInfos)},retrieveHostConfig=(options)=>{validateOptions(options);const hostOptions={...defaultOptions$1,...options};return{hostOptions,mapRemotesToDownload:resolveRemotes(hostOptions)}},REMOTE_ALIAS_IDENTIFIER="REMOTE_ALIAS_IDENTIFIER",REMOTE_API_TYPES_FILE_NAME="apis.d.ts",HOST_API_TYPES_FILE_NAME="index.d.ts",DTSManager=class{constructor(options){this.options=cloneDeepOptions(options);this.runtimePkgs=["@module-federation/runtime","@module-federation/enhanced/runtime","@module-federation/runtime-tools"];this.loadedRemoteAPIAlias=new Set;this.remoteAliasMap={};this.extraOptions=options?.extraOptions||{};this.updatedRemoteInfos={}}generateAPITypes(mapComponentsToExpose){const exposePaths=new Set;const packageType=Object.keys(mapComponentsToExpose).reduce((sum,exposeKey)=>{const exposePath=path8.join(REMOTE_ALIAS_IDENTIFIER,exposeKey).split(path8.sep).join("/");exposePaths.add(`'${exposePath}'`);sum=`T extends '${exposePath}' ? typeof import('${exposePath}') :`+sum;return sum},"any;");return`
200
+ `)};var init_getShortErrorMsg=()=>{};import fs2 from"fs";import path7 from"path";function reportDiagnostic(code,message,args,context){try{const dir=path7.resolve(process.cwd(),".mf","diagnostics");fs2.mkdirSync(dir,{recursive:true});const output={...context,latestErrorEvent:{code,message,args,timestamp:Date.now()}};fs2.writeFileSync(path7.join(dir,"latest.json"),JSON.stringify(output,null,2))}catch{}}function logAndReport(code,descMap,args,logger,originalErrorMsg,context){const msg=getShortErrorMsg2(code,descMap,args,originalErrorMsg);reportDiagnostic(code,msg,args,context);return logger(msg)}var init_node=__esm(()=>{init_getShortErrorMsg()});import{createRequire as createRequire2}from"module";import fs3,{existsSync as existsSync5,mkdirSync as mkdirSync4,realpathSync as realpathSync2,rmSync,writeFileSync as writeFileSync3}from"fs";import{fileURLToPath as fileURLToPath7}from"url";import path8,{dirname as dirname3,extname,isAbsolute as isAbsolute3,join as join5,normalize as normalize3,relative,resolve as resolve5,sep}from"path";import{cp as cp2,mkdir as mkdir3,readFile as readFile4,readdir as readdir2,rm as rm2,stat as stat3,writeFile as writeFile3}from"fs/promises";import crypto2 from"crypto";import{execFile,execFileSync,fork}from"child_process";import{styleText}from"util";import{Agent}from"undici";import util2 from"util";import WebSocket3 from"ws"with{type:"jsx"};import{createRequire as createRequire$1}from"module";import process$1 from"process";function writeTempTsConfig(tsConfig,context,name,cwd){const createHash=(contents)=>{return crypto2.createHash("md5").update(contents).digest("hex")};const hash=createHash(`${JSON.stringify(tsConfig)}${name}${Date.now()}`);const tempTsConfigJsonPath=resolve5(cwd??context,"node_modules",TEMP_DIR,`tsconfig.${hash}.json`);mkdirSync4(dirname3(tempTsConfigJsonPath),{recursive:true});writeFileSync3(tempTsConfigJsonPath,JSON.stringify(tsConfig,null,2));return tempTsConfigJsonPath}function getExposeKey(options){const{filePath,rootDir,outDir,mapExposeToEntry}=options;return mapExposeToEntry[relative(outDir,filePath.replace(new RegExp(`\\.d.ts$`),""))]}function getDTSManagerConstructor(implementation){if(implementation){const NewConstructor=__require3(implementation);return NewConstructor.default?NewConstructor.default:NewConstructor}return DTSManager}function retrieveTypesAssetsInfo(options){let apiTypesPath="";let zipTypesPath="";try{const{tsConfig,remoteOptions,mapComponentsToExpose}=retrieveRemoteConfig(options);if(!Object.keys(mapComponentsToExpose).length||!tsConfig.files.length)return{apiTypesPath,zipTypesPath,zipName:"",apiFileName:""};zipTypesPath=retrieveTypesZipPath(retrieveMfTypesPath(tsConfig,remoteOptions),remoteOptions);if(remoteOptions.generateAPITypes)apiTypesPath=retrieveMfAPITypesPath(tsConfig,remoteOptions);return{apiTypesPath,zipTypesPath,zipName:path8.basename(zipTypesPath),apiFileName:path8.basename(apiTypesPath)}}catch(err){console.error(styleText("red",`Unable to compile federated types, ${err}`));return{apiTypesPath:"",zipTypesPath:"",zipName:"",apiFileName:""}}}function isDebugMode2(){return Boolean(process.env["FEDERATION_DEBUG"])||process.env["NODE_ENV"]==="test"}function cloneDeepOptions(options){const excludeKeys=new Set(["manifest","async"]);const cache=new WeakMap;function sanitize(val,key){if(key!==undefined&&excludeKeys.has(key)||typeof val==="function")return false;if(key==="extractThirdParty"&&Array.isArray(val))return val.map(String);if(Array.isArray(val)){if(cache.has(val))return cache.get(val);const out=[];cache.set(val,out);val.forEach((v,i)=>out.push(sanitize(v,String(i))));return out}if(val!==null&&typeof val==="object"&&Object.getPrototypeOf(val)===Object.prototype){const obj=val;if(cache.has(obj))return cache.get(obj);const out={};cache.set(obj,out);for(const[k,v]of Object.entries(obj))out[k]=sanitize(v,k);return out}return val}return structuredClone(sanitize(options))}async function nativeFetch(url,config){const controller=new AbortController;const timeoutMs=config?.timeout??60000;const timeoutId=setTimeout(()=>controller.abort(),timeoutMs);const headers={...getEnvHeaders(),...config?.headers??{}};const dispatcher=config?.dispatcher??createDispatcherFromFamily(config?.family);try{const resp=await fetch(url,{headers,signal:controller.signal,...dispatcher?{dispatcher}:{},...config?.agent?{agent:config.agent}:{}});const headerRecord=toHeaderRecord(resp.headers);if(!resp.ok)throw new Error(`Request failed with status ${resp.status}`);if(config?.responseType==="arraybuffer")return{data:await resp.arrayBuffer(),headers:headerRecord,status:resp.status};return{data:(resp.headers.get("content-type")||"").includes("application/json")||url.endsWith(".json")?await resp.json():await resp.text(),headers:headerRecord,status:resp.status}}finally{clearTimeout(timeoutId)}}function getEffectiveRootDir(parsedCommandLine){const compilerOptions=parsedCommandLine.options;if(compilerOptions.rootDir)return compilerOptions.rootDir;const files=parsedCommandLine.fileNames;if(files.length>0)return files.map((file)=>dirname3(file)).reduce((commonPath,fileDir)=>{while(!fileDir.startsWith(commonPath))commonPath=dirname3(commonPath);return commonPath},files[0]);if(parsedCommandLine.projectReferences.length){const relativeReferences=parsedCommandLine.projectReferences.filter((reference)=>!isAbsolute3(reference.originalPath??reference.path));const referencesForRoot=relativeReferences.length?relativeReferences:parsedCommandLine.projectReferences;return referencesForRoot.map((reference)=>dirname3(reference.path)).reduce((commonPath,filePath)=>{while(!filePath.startsWith(commonPath))commonPath=dirname3(commonPath);return commonPath},dirname3(referencesForRoot[0].path))}throw new Error("Can not get effective rootDir, please set compilerOptions.rootDir !")}async function generateTypes(options){return new(getDTSManagerConstructor(options.remote?.implementation))(options).generateTypes()}function exposeRpc(fn){const sendMessage=(message)=>new Promise((resolve,reject)=>{if(!process$1.send)reject(new Error(`Process ${process$1.pid} doesn't have IPC channels`));else if(!process$1.connected)reject(new Error(`Process ${process$1.pid} doesn't have open IPC channels`));else process$1.send(message,undefined,undefined,(error)=>{if(error)reject(error);else resolve(undefined)})});const handleMessage=async(message)=>{if(message.type===RpcGMCallTypes.CALL){if(!process$1.send)return;let value,error;try{value=await fn(...message.args)}catch(fnError){error=fnError}try{if(error)await sendMessage({type:RpcGMCallTypes.REJECT,id:message.id,error});else await sendMessage({type:RpcGMCallTypes.RESOLVE,id:message.id,value})}catch(sendError){if(error){if(error instanceof Error)console.error(error)}console.error(sendError)}}};process$1.on("message",handleMessage)}var import_adm_zip,__defProp2,__exportAll=(all,no_symbols)=>{let target={};for(var name in all){__defProp2(target,name,{get:all[name],enumerable:true})}if(!no_symbols){__defProp2(target,Symbol.toStringTag,{value:"Module"})}return target},__require3,__filename2,__dirname2,parseMajorVersion=(version)=>{const major=Number.parseInt(version.split(".")[0],10);return Number.isNaN(major)?0:major},isMissingTypeScriptPackage=(error)=>typeof error==="object"&&error!==null&&("code"in error)&&error.code==="MODULE_NOT_FOUND"&&("message"in error)&&typeof error.message==="string"&&error.message.includes("typescript/package.json"),resolveTypeScriptPackage=(context=process.cwd())=>{const candidateContexts=[...new Set([context,process.cwd()])];let missingTypeScriptError;for(const candidateContext of candidateContexts){const requireFromContext=createRequire$1(resolve5(candidateContext,"package.json"));try{return{packageJsonPath:requireFromContext.resolve("typescript/package.json"),packageJson:requireFromContext("typescript/package.json"),requireFromContext}}catch(error){if(!isMissingTypeScriptPackage(error))throw error;missingTypeScriptError=error}}throw missingTypeScriptError},getTypeScriptPackageInfo=(context=process.cwd())=>{const{packageJsonPath,packageJson}=resolveTypeScriptPackage(context);const version=packageJson.version||"0.0.0";const packageRoot=dirname3(packageJsonPath);const bin=typeof packageJson.bin==="string"?packageJson.bin:packageJson.bin?.["tsc"]??"./bin/tsc";return{packageJsonPath,packageRoot,version,majorVersion:parseMajorVersion(version),tscBinPath:resolve5(packageRoot,bin)}},requireTypeScript=(context=process.cwd())=>{const{requireFromContext}=resolveTypeScriptPackage(context);return requireFromContext("typescript")},STARTS_WITH_SLASH,DEFINITION_FILE_EXTENSION=".d.ts",retrieveMfTypesPath=(tsConfig,remoteOptions)=>normalize3(tsConfig.compilerOptions.outDir.replace(remoteOptions.compiledTypesFolder,"")),retrieveOriginalOutDir=(tsConfig,remoteOptions)=>normalize3(tsConfig.compilerOptions.outDir.replace(remoteOptions.compiledTypesFolder,"").replace(remoteOptions.typesFolder,"")),retrieveMfAPITypesPath=(tsConfig,remoteOptions)=>join5(retrieveOriginalOutDir(tsConfig,remoteOptions),`${remoteOptions.typesFolder}.d.ts`),removeExt=(f)=>{const vueExt=".vue";const ext=extname(f);if(ext===vueExt)return f;const regexPattern=new RegExp(`\\${ext}$`);return f.replace(regexPattern,"")},processTypesFile=async(options)=>{const{outDir,filePath,rootDir,cb,mapExposeToEntry,mfTypePath}=options;if(!existsSync5(filePath))return;if((await stat3(filePath)).isDirectory()){const files=await readdir2(filePath);await Promise.all(files.map((file)=>processTypesFile({...options,filePath:join5(filePath,file)})))}else if(filePath.endsWith(".d.ts")){const exposeKey=getExposeKey({filePath,rootDir,outDir,mapExposeToEntry});if(exposeKey){const mfeTypeEntry=join5(mfTypePath,`${exposeKey==="."?"index":exposeKey}${DEFINITION_FILE_EXTENSION}`);const mfeTypeEntryDirectory=dirname3(mfeTypeEntry);const relativePathToOutput=relative(mfeTypeEntryDirectory,filePath).replace(DEFINITION_FILE_EXTENSION,"").replace(STARTS_WITH_SLASH,"").split(sep).join("/");mkdirSync4(mfeTypeEntryDirectory,{recursive:true});await writeFile3(mfeTypeEntry,`export * from './${relativePathToOutput}';
201
+ export { default } from './${relativePathToOutput}';`)}cb(await readFile4(filePath,"utf8"))}},getPMFromUserAgent=()=>{const userAgent=process.env["npm_config_user_agent"];if(userAgent==null)return"null";return userAgent.split("/")[0]},resolvePackageManagerExecutable=()=>{switch(getPMFromUserAgent()){case"yarn":return"yarn";default:return"npx"}},splitCommandArgs=(value)=>{const args=[];let current="";let quote=null;let escaped=false;for(const char of value){if(escaped){current+=char;escaped=false;continue}if(char==="\\"){escaped=true;continue}if(quote){if(char===quote)quote=null;else current+=char;continue}if(char==='"'||char==="'"){quote=char;continue}if(char.trim()===""){if(current){args.push(current);current=""}continue}current+=char}if(current)args.push(current);return args},formatCommandForDisplay=(executable,args)=>{const formatArg=(arg)=>{if(/[\s'"]/.test(arg))return JSON.stringify(arg);return arg};return[executable,...args].map(formatArg).join(" ")},getTypeScriptContext$1=(remoteOptions)=>{const dtsOptions=remoteOptions.moduleFederationConfig.dts;return typeof dtsOptions!=="boolean"&&dtsOptions?.cwd?dtsOptions.cwd:remoteOptions.context},resolveCompilerCommand=(remoteOptions,tempTsConfigJsonPath)=>{const compilerArgs=splitCommandArgs(remoteOptions.compilerInstance);const resolvedCompilerArgs=compilerArgs.length>0?compilerArgs:[remoteOptions.compilerInstance];if(resolvedCompilerArgs[0]==="tsc"){const args=[getTypeScriptPackageInfo(getTypeScriptContext$1(remoteOptions)).tscBinPath,...resolvedCompilerArgs.slice(1),"--project",tempTsConfigJsonPath];return{executable:process.execPath,args,displayCommand:formatCommandForDisplay(process.execPath,args),shell:false}}const executable=resolvePackageManagerExecutable();const args=[...resolvedCompilerArgs,"--project",tempTsConfigJsonPath];return{executable,args,displayCommand:formatCommandForDisplay(executable,args),shell:process.platform==="win32"}},compileTs=async(mapComponentsToExpose,tsConfig,remoteOptions)=>{if(!Object.keys(mapComponentsToExpose).length)return;const{compilerOptions}=tsConfig;const tempTsConfigJsonPath=writeTempTsConfig(tsConfig,remoteOptions.context,remoteOptions.moduleFederationConfig.name||"mf",typeof remoteOptions.moduleFederationConfig.dts!=="boolean"?remoteOptions.moduleFederationConfig.dts?.cwd??undefined:undefined);logger$1.debug(`tempTsConfigJsonPath: ${tempTsConfigJsonPath}`);try{const mfTypePath=retrieveMfTypesPath(tsConfig,remoteOptions);const thirdPartyExtractor=new ThirdPartyExtractor({destDir:resolve5(mfTypePath,"node_modules"),context:remoteOptions.context,exclude:typeof remoteOptions.extractThirdParty==="object"?remoteOptions.extractThirdParty.exclude:undefined});const execPromise=util2.promisify(execFile);const compilerCommand=resolveCompilerCommand(remoteOptions,tempTsConfigJsonPath);try{await execPromise(compilerCommand.executable,compilerCommand.args,{cwd:getTypeScriptContext$1(remoteOptions),shell:compilerCommand.shell})}catch(err){if(compilerOptions.tsBuildInfoFile)try{await rm2(compilerOptions.tsBuildInfoFile)}catch(e){}logAndReport(TYPE_001,typeDescMap,{cmd:compilerCommand.displayCommand},(msg)=>{throw new Error(msg)},undefined)}const mapExposeToEntry=Object.fromEntries(Object.entries(mapComponentsToExpose).map(([exposed,filename])=>{const normalizedFileName=normalize3(filename);let relativeFileName="";if(isAbsolute3(normalizedFileName))relativeFileName=relative(tsConfig.compilerOptions.rootDir,normalizedFileName);else relativeFileName=relative(tsConfig.compilerOptions.rootDir,resolve5(remoteOptions.context,normalizedFileName));return[removeExt(relativeFileName),exposed]}));const cb=remoteOptions.extractThirdParty?thirdPartyExtractor.collectPkgs.bind(thirdPartyExtractor):()=>{return};await processTypesFile({outDir:compilerOptions.outDir,filePath:compilerOptions.outDir,rootDir:compilerOptions.rootDir,mfTypePath,cb,mapExposeToEntry});if(remoteOptions.extractThirdParty)await thirdPartyExtractor.copyDts();if(remoteOptions.deleteTsConfig)await rm2(tempTsConfigJsonPath)}catch(err){throw err}},retrieveTypesZipPath=(mfTypesPath,remoteOptions)=>join5(mfTypesPath.replace(remoteOptions.typesFolder,""),`${remoteOptions.typesFolder}.zip`),createTypesArchive=async(tsConfig,remoteOptions)=>{const mfTypesPath=retrieveMfTypesPath(tsConfig,remoteOptions);const zip=new import_adm_zip.default;zip.addLocalFolder(mfTypesPath);return zip.writeZipPromise(retrieveTypesZipPath(mfTypesPath,remoteOptions))},downloadErrorLogger=(destinationFolder,fileToDownload)=>(reason)=>{throw{...reason,message:`Network error: Unable to download federated mocks for '${destinationFolder}' from '${fileToDownload}' because '${reason.message}'`}},retrieveTypesArchiveDestinationPath=(hostOptions,destinationFolder)=>{return resolve5(hostOptions.context,hostOptions.typesFolder,destinationFolder)},downloadTypesArchive=(hostOptions)=>{let retries=0;return async([destinationFolder,fileToDownload])=>{const destinationPath=retrieveTypesArchiveDestinationPath(hostOptions,destinationFolder);while(retries++<hostOptions.maxRetries)try{const url=new URL(fileToDownload).href;const response=await nativeFetch(url,{responseType:"arraybuffer",timeout:hostOptions.timeout,family:hostOptions.family}).catch(downloadErrorLogger(destinationFolder,url));if(typeof response.headers?.["content-type"]==="string"&&response.headers["content-type"].includes("text/html"))throw new Error(`${url} receives invalid content-type: ${response.headers["content-type"]}`);try{if(hostOptions.deleteTypesFolder)await rm2(destinationPath,{recursive:true,force:true})}catch(error){fileLog(`Unable to remove types folder, ${error}`,"downloadTypesArchive","error")}new import_adm_zip.default(Buffer.from(response.data)).extractAllTo(destinationPath,true);fileLog(`zip.extractAllTo success destinationPath: ${destinationPath}; url: ${url}`,"downloadTypesArchive","info");return[destinationFolder,destinationPath]}catch(error){fileLog(`Error during types archive download: ${error?.message||"unknown error"}`,"downloadTypesArchive","error");if(retries>=hostOptions.maxRetries){logger$1.error(`Failed to download types archive from "${fileToDownload}". Set FEDERATION_DEBUG=true for details.`);if(hostOptions.abortOnError!==false)throw error;return}}}},defaultOptions$1,buildZipUrl=(hostOptions,url)=>{const remoteUrl=new URL(url,"file:");remoteUrl.pathname=`${remoteUrl.pathname.split("/").slice(0,-1).join("/")}/${hostOptions.remoteTypesFolder}.zip`;return remoteUrl.protocol==="file:"?remoteUrl.pathname:remoteUrl.href},buildApiTypeUrl=(zipUrl)=>{if(!zipUrl)return;return zipUrl.replace(".zip",".d.ts")},retrieveRemoteInfo=(options)=>{const{hostOptions,remoteAlias,remote}=options;const{remoteTypeUrls}=hostOptions;let decodedRemote=remote;if(decodedRemote.startsWith(ENCODE_NAME_PREFIX))decodedRemote=decodeName(decodedRemote,ENCODE_NAME_PREFIX);const parsedInfo=parseEntry(decodedRemote,undefined,"@");const url="entry"in parsedInfo?parsedInfo.entry:parsedInfo.name===decodedRemote?decodedRemote:"";let zipUrl="";let apiTypeUrl="";const name=parsedInfo.name||remoteAlias;const remoteTypeUrl=typeof remoteTypeUrls==="object"&&remoteTypeUrls[name];if(remoteTypeUrl){zipUrl=remoteTypeUrl.zip;apiTypeUrl=remoteTypeUrl.api}const shouldResolveTypeUrlsByConvention=Boolean(url&&!url.includes(MANIFEST_EXT));if(!zipUrl&&shouldResolveTypeUrlsByConvention)zipUrl=buildZipUrl(hostOptions,url);if(!apiTypeUrl&&zipUrl&&(remoteTypeUrl||shouldResolveTypeUrlsByConvention))apiTypeUrl=buildApiTypeUrl(zipUrl);return{name,url,zipUrl,apiTypeUrl,alias:remoteAlias}},resolveRemotes=(hostOptions)=>{const parsedOptions=parseOptions2(hostOptions.moduleFederationConfig.remotes||{},(item,key)=>({remote:Array.isArray(item)?item[0]:item,key}),(item,key)=>({remote:Array.isArray(item.external)?item.external[0]:item.external,key}));const remoteTypeUrls=hostOptions.remoteTypeUrls??{};if(typeof remoteTypeUrls!=="object")throw new Error("remoteTypeUrls must be consumed before resolveRemotes");const remoteInfos=Object.keys(remoteTypeUrls).reduce((sum,remoteName)=>{const{zip,api,alias}=remoteTypeUrls[remoteName];sum[alias]={name:remoteName,url:"",zipUrl:zip,apiTypeUrl:api,alias:alias||remoteName};return sum},{});return parsedOptions.reduce((accumulator,item)=>{const{key,remote}=item[1];const res=retrieveRemoteInfo({hostOptions,remoteAlias:key,remote});if(accumulator[key]){accumulator[key]={...accumulator[key],url:res.url,apiTypeUrl:accumulator[key].apiTypeUrl||res.apiTypeUrl};return accumulator}accumulator[key]=res;return accumulator},remoteInfos)},retrieveHostConfig=(options)=>{validateOptions(options);const hostOptions={...defaultOptions$1,...options};return{hostOptions,mapRemotesToDownload:resolveRemotes(hostOptions)}},REMOTE_ALIAS_IDENTIFIER="REMOTE_ALIAS_IDENTIFIER",REMOTE_API_TYPES_FILE_NAME="apis.d.ts",HOST_API_TYPES_FILE_NAME="index.d.ts",DTSManager=class{constructor(options){this.options=cloneDeepOptions(options);this.runtimePkgs=["@module-federation/runtime","@module-federation/enhanced/runtime","@module-federation/runtime-tools"];this.loadedRemoteAPIAlias=new Set;this.remoteAliasMap={};this.extraOptions=options?.extraOptions||{};this.updatedRemoteInfos={}}generateAPITypes(mapComponentsToExpose){const exposePaths=new Set;const packageType=Object.keys(mapComponentsToExpose).reduce((sum,exposeKey)=>{const exposePath=path8.join(REMOTE_ALIAS_IDENTIFIER,exposeKey).split(path8.sep).join("/");exposePaths.add(`'${exposePath}'`);sum=`T extends '${exposePath}' ? typeof import('${exposePath}') :`+sum;return sum},"any;");return`
202
202
  export type RemoteKeys = ${[...exposePaths].join(" | ")};
203
203
  type PackageType<T> = ${packageType}`}async extractRemoteTypes(options){const{remoteOptions,tsConfig}=options;if(!remoteOptions.extractRemoteTypes)return;let hasRemotes=false;const remotes=remoteOptions.moduleFederationConfig.remotes;if(remotes){if(Array.isArray(remotes))hasRemotes=Boolean(remotes.length);else if(typeof remotes==="object")hasRemotes=Boolean(Object.keys(remotes).length)}const mfTypesPath=retrieveMfTypesPath(tsConfig,remoteOptions);if(hasRemotes&&this.options.host)try{const{hostOptions}=retrieveHostConfig(this.options.host);const remoteTypesFolder=path8.resolve(hostOptions.context,hostOptions.typesFolder);const targetDir=path8.join(mfTypesPath,"node_modules");if(fs3.existsSync(remoteTypesFolder)){const targetFolder=path8.resolve(remoteOptions.context,targetDir);await mkdir3(targetFolder,{recursive:true});await cp2(remoteTypesFolder,targetFolder,{recursive:true,force:true})}}catch(err){if(this.options.host?.abortOnError===false)fileLog(`Unable to copy remote types, ${err}`,"extractRemoteTypes","error");else throw err}}async generateTypes(){try{const{options}=this;if(!options.remote)throw new Error("options.remote is required if you want to generateTypes");const{remoteOptions,tsConfig,mapComponentsToExpose}=retrieveRemoteConfig(options.remote);if(!Object.keys(mapComponentsToExpose).length)return;if(!tsConfig.files?.length){logger$1.info("No type files to compile, skip");return}if(tsConfig.compilerOptions.tsBuildInfoFile)try{const tsBuildInfoFile=path8.resolve(remoteOptions.context,tsConfig.compilerOptions.tsBuildInfoFile);const mfTypesPath=retrieveMfTypesPath(tsConfig,remoteOptions);if(!fs3.existsSync(mfTypesPath))fs3.rmSync(tsBuildInfoFile,{force:true})}catch(e){}await this.extractRemoteTypes({remoteOptions,tsConfig,mapComponentsToExpose});await compileTs(mapComponentsToExpose,tsConfig,remoteOptions);await createTypesArchive(tsConfig,remoteOptions);let apiTypesPath="";if(remoteOptions.generateAPITypes){const apiTypes=this.generateAPITypes(mapComponentsToExpose);apiTypesPath=retrieveMfAPITypesPath(tsConfig,remoteOptions);fs3.writeFileSync(apiTypesPath,apiTypes)}try{if(remoteOptions.deleteTypesFolder)await rm2(retrieveMfTypesPath(tsConfig,remoteOptions),{recursive:true,force:true})}catch(err){if(isDebugMode2())console.error(err)}logger$1.success("Federated types created correctly")}catch(error){if(this.options.remote?.abortOnError===false){if(this.options.displayErrorInTerminal)logger$1.error(error)}else throw error}}async requestRemoteManifest(remoteInfo,hostOptions){try{if(!remoteInfo.url.includes(MANIFEST_EXT))return remoteInfo;if(remoteInfo.zipUrl)return remoteInfo;const url=remoteInfo.url;const manifestJson=(await nativeFetch(url,{timeout:hostOptions.timeout,family:hostOptions.family})).data;if(!manifestJson.metaData.types.zip)throw new Error(`Can not get ${remoteInfo.name}'s types archive url!`);const addProtocol=(u)=>{if(u.startsWith("//"))return`https:${u}`;return u};let publicPath;if("publicPath"in manifestJson.metaData)publicPath=manifestJson.metaData.publicPath;else{const getPublicPath=new Function(manifestJson.metaData.getPublicPath);if(manifestJson.metaData.getPublicPath.startsWith("function"))publicPath=getPublicPath()();else publicPath=getPublicPath()}if(publicPath==="auto")publicPath=inferAutoPublicPath(remoteInfo.url);const normalizedPublicPath=addProtocol(publicPath).endsWith("/")?addProtocol(publicPath):`${addProtocol(publicPath)}/`;remoteInfo.zipUrl=new URL(manifestJson.metaData.types.zip,normalizedPublicPath).href;if(!manifestJson.metaData.types.api){console.warn(`Can not get ${remoteInfo.name}'s api types url!`);remoteInfo.apiTypeUrl="";return remoteInfo}remoteInfo.apiTypeUrl=new URL(manifestJson.metaData.types.api,normalizedPublicPath).href;return remoteInfo}catch(_err){fileLog(`fetch manifest failed, ${_err}, ${remoteInfo.name} will be ignored`,"requestRemoteManifest","error");return remoteInfo}}async consumeTargetRemotes(hostOptions,remoteInfo){if(!remoteInfo.zipUrl)throw new Error(`Can not get ${remoteInfo.name}'s types archive url!`);return downloadTypesArchive(hostOptions)([remoteInfo.alias,remoteInfo.zipUrl])}async downloadAPITypes(remoteInfo,destinationPath,hostOptions){const{apiTypeUrl}=remoteInfo;if(!apiTypeUrl)return;try{let apiTypeFile=(await nativeFetch(apiTypeUrl,{timeout:hostOptions.timeout,family:hostOptions.family})).data;apiTypeFile=apiTypeFile.replaceAll(REMOTE_ALIAS_IDENTIFIER,remoteInfo.alias);const filePath=path8.join(destinationPath,REMOTE_API_TYPES_FILE_NAME);fs3.writeFileSync(filePath,apiTypeFile);const existed=this.loadedRemoteAPIAlias.has(remoteInfo.alias);this.loadedRemoteAPIAlias.add(remoteInfo.alias);fileLog(`success`,"downloadAPITypes","info");return existed}catch(err){fileLog(`Unable to download "${remoteInfo.name}" api types, ${err}`,"downloadAPITypes","error")}}consumeAPITypes(hostOptions){const apiTypeFileName=path8.join(hostOptions.context,hostOptions.typesFolder,HOST_API_TYPES_FILE_NAME);try{const existedFile=fs3.readFileSync(apiTypeFileName,"utf-8");new ThirdPartyExtractor({destDir:""}).collectTypeImports(existedFile).forEach((existedImport)=>{const alias=existedImport.split("./").slice(1).join("./").replace("/apis.d.ts","");this.loadedRemoteAPIAlias.add(alias)})}catch(err){}if(!this.loadedRemoteAPIAlias.size)return;const packageTypes=[];const remoteKeys=[];const importTypeStr=[...this.loadedRemoteAPIAlias].sort().map((alias,index)=>{const remoteKey=`RemoteKeys_${index}`;const packageType=`PackageType_${index}`;packageTypes.push(`T extends ${remoteKey} ? ${packageType}<T>`);remoteKeys.push(remoteKey);return`import type { PackageType as ${packageType},RemoteKeys as ${remoteKey} } from './${alias}/apis.d.ts';`}).join(`
204
204
  `);const remoteKeysStr=`type RemoteKeys = ${remoteKeys.join(" | ")};`;const packageTypesStr=`type PackageType<T, Y=any> = ${[...packageTypes,"Y"].join(` :
@@ -211,16 +211,16 @@ export { default } from './${relativePathToOutput}';`)}cb(await readFile4(filePa
211
211
  }`}).join(`
212
212
  `)}
213
213
  `;fs3.writeFileSync(path8.join(hostOptions.context,hostOptions.typesFolder,HOST_API_TYPES_FILE_NAME),fileStr)}async consumeArchiveTypes(options){const{hostOptions,mapRemotesToDownload}=retrieveHostConfig(options);const downloadPromises=Object.entries(mapRemotesToDownload).map(async(item)=>{const remoteInfo=item[1];if(!this.remoteAliasMap[remoteInfo.alias]){const requiredRemoteInfo=await this.requestRemoteManifest(remoteInfo,hostOptions);this.remoteAliasMap[remoteInfo.alias]=requiredRemoteInfo}return this.consumeTargetRemotes(hostOptions,this.remoteAliasMap[remoteInfo.alias])});return{hostOptions,downloadPromisesResult:await Promise.allSettled(downloadPromises)}}async consumeTypes(){try{const{options}=this;if(!options.host)throw new Error("options.host is required if you want to consumeTypes");const{mapRemotesToDownload}=retrieveHostConfig(options.host);if(!Object.keys(mapRemotesToDownload).length)return;const{downloadPromisesResult,hostOptions}=await this.consumeArchiveTypes(options.host);if(hostOptions.consumeAPITypes){await Promise.all(downloadPromisesResult.map(async(item)=>{if(item.status==="rejected"||!item.value)return;const[alias,destinationPath]=item.value;const remoteInfo=this.remoteAliasMap[alias];if(!remoteInfo)return;await this.downloadAPITypes(remoteInfo,destinationPath,hostOptions)}));this.consumeAPITypes(hostOptions)}logger$1.success("Federated types extraction completed")}catch(err){if(this.options.host?.abortOnError===false)fileLog(`Unable to consume federated types, ${err}`,"consumeTypes","error");else throw err}}async updateTypes(options){try{const{remoteName,updateMode,remoteTarPath,remoteInfo:updatedRemoteInfo,once}=options;const hostName=this.options?.host?.moduleFederationConfig?.name;fileLog(`options: ${JSON.stringify(options,null,2)};
214
- hostName: ${hostName}`,"updateTypes","info");if(updateMode===UpdateMode.POSITIVE&&remoteName===hostName){if(!this.options.remote)return;await this.generateTypes()}else{const{remoteAliasMap}=this;if(!this.options.host)return;const{hostOptions,mapRemotesToDownload}=retrieveHostConfig(this.options.host);const loadedRemoteInfo=Object.values(remoteAliasMap).find((i)=>i.name===remoteName);const consumeTypes=async(requiredRemoteInfo)=>{fileLog(`consumeTypes start`,"updateTypes","info");if(!requiredRemoteInfo.zipUrl)throw new Error(`Can not get ${requiredRemoteInfo.name}'s types archive url!`);const[_alias,destinationPath]=await this.consumeTargetRemotes(hostOptions,{...requiredRemoteInfo,zipUrl:remoteTarPath||requiredRemoteInfo.zipUrl});if(await this.downloadAPITypes(requiredRemoteInfo,destinationPath,hostOptions))this.consumeAPITypes(hostOptions);fileLog(`consumeTypes end`,"updateTypes","info")};fileLog(`loadedRemoteInfo: ${JSON.stringify(loadedRemoteInfo,null,2)}`,"updateTypes","info");if(!loadedRemoteInfo){const remoteInfo=Object.values(mapRemotesToDownload).find((item)=>{return item.name===remoteName});fileLog(`remoteInfo: ${JSON.stringify(remoteInfo,null,2)}`,"updateTypes","info");if(remoteInfo){if(!this.remoteAliasMap[remoteInfo.alias]){const requiredRemoteInfo=await this.requestRemoteManifest(remoteInfo,hostOptions);this.remoteAliasMap[remoteInfo.alias]=requiredRemoteInfo}await consumeTypes(this.remoteAliasMap[remoteInfo.alias])}else if(updatedRemoteInfo){const consumeDynamicRemoteTypes=async()=>{await consumeTypes(this.updatedRemoteInfos[updatedRemoteInfo.name])};if(!this.updatedRemoteInfos[updatedRemoteInfo.name]){const parsedRemoteInfo=retrieveRemoteInfo({hostOptions,remoteAlias:updatedRemoteInfo.alias||updatedRemoteInfo.name,remote:updatedRemoteInfo.url});fileLog(`start request manifest`,"consumeTypes","info");this.updatedRemoteInfos[updatedRemoteInfo.name]=await this.requestRemoteManifest(parsedRemoteInfo,hostOptions);fileLog(`end request manifest, this.updatedRemoteInfos[updatedRemoteInfo.name]: ${JSON.stringify(this.updatedRemoteInfos[updatedRemoteInfo.name],null,2)}`,"updateTypes","info");await consumeDynamicRemoteTypes()}if(!once&&this.updatedRemoteInfos[updatedRemoteInfo.name])await consumeDynamicRemoteTypes()}}else await consumeTypes(loadedRemoteInfo)}}catch(err){fileLog(`updateTypes fail, ${err}`,"updateTypes","error")}}},dispatcherCache,validateOptions=(options)=>{if(!options.moduleFederationConfig)throw new Error("moduleFederationConfig is required")},isTSProject=(dtsOptions,context=process.cwd())=>{if(dtsOptions===false)return false;try{let filepath="";if(typeof dtsOptions==="object"&&dtsOptions.tsConfigPath)filepath=dtsOptions.tsConfigPath;else filepath=path8.resolve(context,"./tsconfig.json");if(!path8.isAbsolute(filepath))filepath=path8.resolve(context,filepath);return fs3.existsSync(filepath)}catch(err){return false}},getEnvHeaders=()=>{const headersStr=getProcessEnv()["MF_ENV_HEADERS"];if(!headersStr||headersStr==="undefined")return{};try{return{...JSON.parse(headersStr)}}catch{return{}}},createDispatcherFromFamily=(family)=>{if(!family)return;if(dispatcherCache.has(family))return dispatcherCache.get(family);try{const dispatcher=new Agent({connect:{family}});dispatcherCache.set(family,dispatcher);return dispatcher}catch{}},toHeaderRecord=(headers)=>{const out={};headers.forEach((value,key)=>{out[key.toLowerCase()]=value});return out},defaultOptions2,getDependentFiles=(rootFiles,configContent,rootDir,typescript)=>{const dependentFiles=typescript.createProgram(rootFiles,configContent.options).getSourceFiles().map((file)=>file.fileName).filter((file)=>!file.endsWith(".d.ts")&&isFileWithinRootDir(file,rootDir)).map((file)=>normalizeFileToRootDir(file,rootDir));return dependentFiles.length?dependentFiles:rootFiles},normalizeForComparison=(value)=>{try{return normalize2(realpathSync2.native(value))}catch{return normalize2(value)}},isFileWithinRootDir=(file,rootDir)=>{const normalizedFile=normalizeForComparison(file);const normalizedRootDir=normalizeForComparison(rootDir);return normalizedFile===normalizedRootDir||normalizedFile.startsWith(normalizedRootDir.endsWith(sep)?normalizedRootDir:`${normalizedRootDir}${sep}`)},normalizeFileToRootDir=(file,rootDir)=>{const normalizedFile=normalizeForComparison(file);const normalizedRootDir=normalizeForComparison(rootDir);if(normalizedFile===normalizedRootDir||normalizedFile.startsWith(normalizedRootDir.endsWith(sep)?normalizedRootDir:`${normalizedRootDir}${sep}`))return normalize2(join4(rootDir,relative(normalizedRootDir,normalizedFile)));return normalize2(file)},getTypeScriptContext=({context,moduleFederationConfig})=>{const dtsOptions=moduleFederationConfig.dts;return typeof dtsOptions!=="boolean"&&dtsOptions?.cwd?dtsOptions.cwd:context},resolveFromConfigDir=(value,configDir)=>{if(typeof value!=="string")return value;return isAbsolute2(value)?normalize2(value):resolve5(configDir,value)},normalizeCompilerOptions=(compilerOptions={},configDir)=>{const normalizedOptions={...compilerOptions};for(const pathOption of["rootDir","outDir","declarationDir","tsBuildInfoFile"])if(typeof normalizedOptions[pathOption]==="string")normalizedOptions[pathOption]=resolveFromConfigDir(normalizedOptions[pathOption],configDir);if(normalizedOptions["moduleResolution"]==="node"||normalizedOptions["moduleResolution"]==="node10")normalizedOptions["moduleResolution"]="bundler";return normalizedOptions},parseShowConfigOutput=(stdout,resolvedTsConfigPath)=>{const configDir=dirname3(resolvedTsConfigPath);const shownConfig=JSON.parse(stdout);const compilerOptions=normalizeCompilerOptions(shownConfig.compilerOptions,configDir);const fileNames=(shownConfig.files||[]).map((file)=>resolveFromConfigDir(file,configDir));const projectReferences=(shownConfig.references||[]).map((reference)=>({...reference,path:resolveFromConfigDir(reference.path,configDir),originalPath:reference.path}));return{rawTsConfigJson:{...shownConfig,compilerOptions},configContent:{options:compilerOptions,fileNames,projectReferences}}},readTsConfigWithTsc=(resolvedTsConfigPath,typeScriptContext)=>{const typeScriptPackageInfo=getTypeScriptPackageInfo(typeScriptContext);return parseShowConfigOutput(execFileSync(process.execPath,[typeScriptPackageInfo.tscBinPath,"--showConfig","--project",resolvedTsConfigPath],{cwd:typeScriptContext,encoding:"utf8",stdio:["ignore","pipe","pipe"]}),resolvedTsConfigPath)},writeListFilesTsConfig=(rootFiles,resolvedTsConfigPath,context,compilerOptions)=>{const tempTsConfigJsonPath=resolve5(context,"node_modules",TEMP_DIR,`tsconfig.list-files.${crypto2.createHash("md5").update(`${JSON.stringify(rootFiles)}${resolvedTsConfigPath}${Date.now()}`).digest("hex")}.json`);mkdirSync4(dirname3(tempTsConfigJsonPath),{recursive:true});const listFilesConfig=compilerOptions?{compilerOptions,files:rootFiles.map((file)=>isAbsolute2(file)?file:resolve5(context,file))}:{extends:resolvedTsConfigPath,files:rootFiles.map((file)=>isAbsolute2(file)?file:resolve5(context,file))};writeFileSync3(tempTsConfigJsonPath,JSON.stringify(listFilesConfig,null,2));return tempTsConfigJsonPath},formatCompilerError=(error)=>{const readOutput=(value)=>{if(Buffer.isBuffer(value))return value.toString("utf8");return typeof value==="string"?value:""};if(typeof error==="object"&&error!==null){const processError=error;const stderr=readOutput(processError.stderr).trim();if(stderr)return stderr.split(/\r?\n/)[0];const stdout=readOutput(processError.stdout).trim();if(stdout)return stdout.split(/\r?\n/)[0];if(typeof processError.message==="string")return processError.message}return String(error)},getDependentFilesWithTsc=(rootFiles,rootDir,resolvedTsConfigPath,compilerOptions,context,typeScriptContext)=>{if(!rootFiles.length)return[];const typeScriptPackageInfo=getTypeScriptPackageInfo(typeScriptContext);const listFilesTsConfigPath=writeListFilesTsConfig(rootFiles,resolvedTsConfigPath,context,compilerOptions);try{const dependentFiles=execFileSync(process.execPath,[typeScriptPackageInfo.tscBinPath,"--listFilesOnly","--project",listFilesTsConfigPath],{cwd:typeScriptContext,encoding:"utf8",stdio:["ignore","pipe","pipe"]}).split(/\r?\n/).map((file)=>file.trim()).filter(Boolean).map((file)=>isAbsolute2(file)?file:resolve5(context,file)).filter((file)=>!file.endsWith(".d.ts")&&isFileWithinRootDir(file,rootDir)).map((file)=>normalizeFileToRootDir(file,rootDir));return dependentFiles.length?dependentFiles:rootFiles}catch(error){logger$1.warn(`Failed to collect TypeScript dependency files with "tsc --listFilesOnly"; falling back to exposed files only. ${formatCompilerError(error)}`);return rootFiles}finally{rmSync(listFilesTsConfigPath,{force:true})}},readTsConfig=(remoteOptions,mapComponentsToExpose)=>{const{tsConfigPath,typesFolder,compiledTypesFolder,context,additionalFilesToCompile,outputDir}=remoteOptions;const resolvedTsConfigPath=resolve5(context,tsConfigPath);const typeScriptContext=getTypeScriptContext(remoteOptions);const typeScriptPackageInfo=getTypeScriptPackageInfo(typeScriptContext);let rawTsConfigJson;let configContent;let typescript;if(typeScriptPackageInfo.majorVersion===7)({rawTsConfigJson,configContent}=readTsConfigWithTsc(resolvedTsConfigPath,typeScriptContext));else{typescript=requireTypeScript(typeScriptContext);const readResult=typescript.readConfigFile(resolvedTsConfigPath,typescript.sys.readFile);if(readResult.error)throw new Error(readResult.error.messageText.toString());rawTsConfigJson=readResult.config||{};configContent=typescript.parseJsonConfigFileContent(rawTsConfigJson,typescript.sys,dirname3(resolvedTsConfigPath));configContent.projectReferences=configContent.projectReferences||[]}const rootDir=getEffectiveRootDir(configContent);const outDir=resolve5(context,outputDir||configContent.options.outDir||"dist",typesFolder,compiledTypesFolder);const defaultCompilerOptions={rootDir,emitDeclarationOnly:true,noEmit:false,declaration:true,outDir};rawTsConfigJson.compilerOptions=rawTsConfigJson.compilerOptions||{};rawTsConfigJson.compilerOptions={incremental:true,tsBuildInfoFile:resolve5(context,"node_modules/.cache/mf-types/.tsbuildinfo"),...rawTsConfigJson.compilerOptions,...defaultCompilerOptions};const{paths,baseUrl,...restCompilerOptions}=rawTsConfigJson.compilerOptions||{};rawTsConfigJson.compilerOptions=restCompilerOptions;const outDirWithoutTypesFolder=resolve5(context,outputDir||configContent.options.outDir||"dist");const excludeExtensions=[".mdx",".md"];const rootFiles=[...Object.values(mapComponentsToExpose),...additionalFilesToCompile].filter((filename)=>!excludeExtensions.some((ext)=>filename.endsWith(ext)));const filesToCompile=[...typescript?getDependentFiles(rootFiles,configContent,rootDir,typescript):getDependentFilesWithTsc(rootFiles,rootDir,resolvedTsConfigPath,configContent.options,context,typeScriptContext),...configContent.fileNames.filter((filename)=>filename.endsWith(".d.ts")&&!filename.startsWith(outDirWithoutTypesFolder))];rawTsConfigJson.include=[];rawTsConfigJson.files=[...new Set(filesToCompile)];rawTsConfigJson.exclude=[];"references"in rawTsConfigJson&&delete rawTsConfigJson.references;rawTsConfigJson.extends=resolvedTsConfigPath;rawTsConfigJson.compilerOptions.declarationDir=outDir;return rawTsConfigJson},TS_EXTENSIONS,resolveWithExtension=(exposedPath,context)=>{const explicitExtension=extname(exposedPath);if(TS_EXTENSIONS.includes(explicitExtension))return resolve5(context,exposedPath);for(const extension of TS_EXTENSIONS){const exposedPathWithExtension=resolve5(context,`${exposedPath}${extension}`);if(existsSync5(exposedPathWithExtension))return exposedPathWithExtension}},resolveExposes=(remoteOptions)=>{return parseOptions2(remoteOptions.moduleFederationConfig.exposes||{},(item,key)=>({exposePath:Array.isArray(item)?item[0]:item,key}),(item,key)=>({exposePath:Array.isArray(item.import)?item.import[0]:item.import[0],key})).reduce((accumulator,item)=>{const{exposePath,key}=item[1];accumulator[key]=resolveWithExtension(exposePath,remoteOptions.context)||resolveWithExtension(join4(exposePath,"index"),remoteOptions.context)||exposePath;return accumulator},{})},retrieveRemoteConfig=(options)=>{validateOptions(options);const remoteOptions={...defaultOptions2,...options};const mapComponentsToExpose=resolveExposes(remoteOptions);const tsConfig=readTsConfig(remoteOptions,mapComponentsToExpose);if(tsConfig.compilerOptions.incremental&&tsConfig.compilerOptions.tsBuildInfoFile&&options.deleteTypesFolder!==true)remoteOptions.deleteTypesFolder=false;return{tsConfig,mapComponentsToExpose,remoteOptions}},RpcGMCallTypes;var init_expose_rpc_B0rqtOKP=__esm(()=>{init_Action_DNNg2YDh();init_Broker_BfFUcTHm();init_dist2();init_dist();init_dist3();init_dist4();init_node();import_adm_zip=__toESM(require_adm_zip(),1);__defProp2=Object.defineProperty;__require3=createRequire2(import.meta.url);__filename2=fileURLToPath7(import.meta.url);__dirname2=path8.dirname(__filename2);STARTS_WITH_SLASH=/^\//;defaultOptions$1={typesFolder:"@mf-types",remoteTypesFolder:"@mf-types",deleteTypesFolder:true,maxRetries:3,implementation:"",context:process.cwd(),abortOnError:true,consumeAPITypes:false,runtimePkgs:[],remoteTypeUrls:{},timeout:60000,typesOnBuild:false,family:0};dispatcherCache=new Map;defaultOptions2={tsConfigPath:"./tsconfig.json",typesFolder:"@mf-types",compiledTypesFolder:"compiled-types",hostRemoteTypesFolder:"@mf-types",deleteTypesFolder:true,additionalFilesToCompile:[],compilerInstance:"tsc",compileInChildProcess:false,implementation:"",generateAPITypes:false,context:process.cwd(),abortOnError:true,extractRemoteTypes:false,extractThirdParty:false,outputDir:"",deleteTsConfig:true};TS_EXTENSIONS=[".ts",".tsx",".vue",".svelte",".js",".jsx"];RpcGMCallTypes=function(RpcGMCallTypes){RpcGMCallTypes["CALL"]="mf_call";RpcGMCallTypes["RESOLVE"]="mf_resolve";RpcGMCallTypes["REJECT"]="mf_reject";RpcGMCallTypes["EXIT"]="mf_exit";return RpcGMCallTypes}({})});import{fileURLToPath as fileURLToPath8}from"url";import path9 from"path";import{randomUUID as randomUUID2}from"crypto";import*as child_process from"child_process";import*as process$2 from"process";function createControlledPromise(){let resolve=()=>{return};let reject=()=>{return};return{promise:new Promise((aResolve,aReject)=>{resolve=aResolve;reject=aReject}),resolve,reject}}function wrapRpc(childProcess,options){return async(...args)=>{if(!childProcess.send)throw new Error(`Process ${childProcess.pid} doesn't have IPC channels`);else if(!childProcess.connected)throw new Error(`Process ${childProcess.pid} doesn't have open IPC channels`);const{id,once}=options;const{promise:resultPromise,resolve:resolveResult,reject:rejectResult}=createControlledPromise();const{promise:sendPromise,resolve:resolveSend,reject:rejectSend}=createControlledPromise();const handleMessage=(message)=>{if(message?.id===id){if(message.type===RpcGMCallTypes.RESOLVE)resolveResult(message.value);else if(message.type===RpcGMCallTypes.REJECT)rejectResult(message.error)}if(once&&childProcess?.kill)childProcess.kill("SIGTERM")};const handleClose=(code,signal)=>{rejectResult(new RpcExitError(code?`Process ${childProcess.pid} exited with code ${code}${signal?` [${signal}]`:""}`:`Process ${childProcess.pid} exited${signal?` [${signal}]`:""}`,code,signal));removeHandlers()};const removeHandlers=()=>{childProcess.off("message",handleMessage);childProcess.off("close",handleClose)};if(once)childProcess.once("message",handleMessage);else childProcess.on("message",handleMessage);childProcess.on("close",handleClose);childProcess.send({type:RpcGMCallTypes.CALL,id,args},(error)=>{if(error){rejectSend(error);removeHandlers()}else resolveSend(undefined)});return sendPromise.then(()=>resultPromise)}}function createRpcWorker(modulePath,data,memoryLimit,once){const options={env:{...process$2.env,[FEDERATION_WORKER_DATA_ENV_KEY]:JSON.stringify(data||{})},stdio:["inherit","inherit","inherit","ipc"],serialization:"advanced"};if(memoryLimit)options.execArgv=[`--max-old-space-size=${memoryLimit}`];let childProcess,remoteMethod;const id=randomUUID2();return{connect(...args){if(childProcess&&!childProcess.connected){childProcess.send({type:RpcGMCallTypes.EXIT,id});childProcess=undefined;remoteMethod=undefined}if(!childProcess?.connected){childProcess=child_process.fork(modulePath,options);remoteMethod=wrapRpc(childProcess,{id,once})}if(!remoteMethod)return Promise.reject(new Error("Worker is not connected - cannot perform RPC."));return remoteMethod(...args)},terminate(){try{if(childProcess.connected)childProcess.send({type:RpcGMCallTypes.EXIT,id},(err)=>{if(err)console.error("Error sending message:",err)})}catch(error){if(error.code==="EPIPE")console.error("Pipe closed before message could be sent:",error);else console.error("Unexpected error:",error)}childProcess=undefined;remoteMethod=undefined},get connected(){return Boolean(childProcess?.connected)},get process(){return childProcess},get id(){return id}}}function getRpcWorkerData(){return JSON.parse(process$2.env[FEDERATION_WORKER_DATA_ENV_KEY]||"{}")}async function generateTypesInChildProcess(options){return new DtsWorker(options).controlledPromise}async function consumeTypes(options){await new(getDTSManagerConstructor(options.host?.implementation))(options).consumeTypes()}var RpcExitError,FEDERATION_WORKER_DATA_ENV_KEY="VMOK_WORKER_DATA_ENV",rpc_exports,__filename3,__dirname3,__extname,DtsWorker=class{constructor(options){this._options=cloneDeepOptions(options);this.removeUnSerializationOptions();this.rpcWorker=createRpcWorker(path9.resolve(__dirname3,`./fork-generate-dts${__extname}`),{},undefined,true);this._res=this.rpcWorker.connect(this._options)}removeUnSerializationOptions(){if(this._options.remote?.moduleFederationConfig?.manifest)delete this._options.remote?.moduleFederationConfig?.manifest;if(this._options.host?.moduleFederationConfig?.manifest)delete this._options.host?.moduleFederationConfig?.manifest}get controlledPromise(){const ensureChildProcessExit=()=>{try{const pid=this.rpcWorker.process?.pid;const rootPid=process.pid;if(pid&&rootPid!==pid)process.kill(pid,0)}catch(error){if(isDebugMode2())console.error(error)}};return Promise.resolve(this._res).then(()=>{this.exit();ensureChildProcessExit()}).catch((err)=>{if(isDebugMode2())console.error(err);ensureChildProcessExit()})}exit(){try{this.rpcWorker?.terminate()}catch(err){if(isDebugMode2())console.error(err)}}};var init_consumeTypes_WKYNaS9i=__esm(()=>{init_expose_rpc_B0rqtOKP();RpcExitError=class extends Error{constructor(message,code,signal){super(message);this.code=code;this.signal=signal;this.name="RpcExitError"}};rpc_exports=__exportAll({RpcExitError:()=>RpcExitError,RpcGMCallTypes:()=>RpcGMCallTypes,createRpcWorker:()=>createRpcWorker,exposeRpc:()=>exposeRpc,getRpcWorkerData:()=>getRpcWorkerData,wrapRpc:()=>wrapRpc});__filename3=fileURLToPath8(import.meta.url);__dirname3=path9.dirname(__filename3);__extname=path9.extname(__filename3)});var init_core=__esm(()=>{init_expose_rpc_B0rqtOKP();init_Broker_BfFUcTHm();init_consumeTypes_WKYNaS9i()});import{fileURLToPath as fileURLToPath9}from"url";import path10 from"path";var __filename$1,__dirname$1,__filename4,__dirname4,DEFAULT_CONSUME_TYPES,normalizeConsumeTypesOptions=({context,dtsOptions,pluginOptions})=>{const normalizedConsumeTypes=normalizeOptions(true,DEFAULT_CONSUME_TYPES,"mfOptions.dts.consumeTypes")(dtsOptions.consumeTypes);if(!normalizedConsumeTypes)return;const dtsManagerOptions={host:{implementation:dtsOptions.implementation,context,moduleFederationConfig:pluginOptions,...normalizedConsumeTypes},extraOptions:dtsOptions.extraOptions||{},displayErrorInTerminal:dtsOptions.displayErrorInTerminal};validateOptions(dtsManagerOptions.host);return dtsManagerOptions},consumeTypesAPI=async(dtsManagerOptions,cb)=>{return(typeof dtsManagerOptions.host.remoteTypeUrls==="function"?dtsManagerOptions.host.remoteTypeUrls():Promise.resolve(dtsManagerOptions.host.remoteTypeUrls)).then((remoteTypeUrls)=>{consumeTypes({...dtsManagerOptions,host:{...dtsManagerOptions.host,remoteTypeUrls}}).then(()=>{typeof cb==="function"&&cb(remoteTypeUrls)}).catch(()=>{typeof cb==="function"&&cb(remoteTypeUrls)})})},DEFAULT_GENERATE_TYPES,normalizeGenerateTypesOptions=({context,outputDir,dtsOptions,pluginOptions})=>{const normalizedGenerateTypes=normalizeOptions(true,DEFAULT_GENERATE_TYPES,"mfOptions.dts.generateTypes")(dtsOptions.generateTypes);if(!normalizedGenerateTypes)return;const normalizedConsumeTypes=normalizeOptions(true,{},"mfOptions.dts.consumeTypes")(dtsOptions.consumeTypes);const finalOptions={remote:{implementation:dtsOptions.implementation,context,outputDir,moduleFederationConfig:pluginOptions,...normalizedGenerateTypes},host:normalizedConsumeTypes===false?undefined:{context,moduleFederationConfig:pluginOptions,...normalizedConsumeTypes,remoteTypeUrls:typeof normalizedConsumeTypes?.remoteTypeUrls==="object"?normalizedConsumeTypes?.remoteTypeUrls:undefined},extraOptions:dtsOptions.extraOptions||{},displayErrorInTerminal:dtsOptions.displayErrorInTerminal};if(dtsOptions.tsConfigPath&&!finalOptions.remote.tsConfigPath)finalOptions.remote.tsConfigPath=dtsOptions.tsConfigPath;validateOptions(finalOptions.remote);return finalOptions},getGenerateTypesFn=(dtsManagerOptions)=>{let fn=generateTypes;if(dtsManagerOptions.remote.compileInChildProcess)fn=generateTypesInChildProcess;return fn},generateTypesAPI=({dtsManagerOptions})=>{return getGenerateTypesFn(dtsManagerOptions)(dtsManagerOptions).then(async()=>{await callAfterGenerateHook({dtsManagerOptions,generatedTypes:retrieveTypesAssetsInfo(dtsManagerOptions.remote)})})},callAfterGenerateHook=async({dtsManagerOptions,generatedTypes})=>{const afterGenerate=dtsManagerOptions.remote.afterGenerate;if(!afterGenerate)return;try{await afterGenerate(generatedTypes)}catch(error){if(dtsManagerOptions.remote.abortOnError===false){if(dtsManagerOptions.displayErrorInTerminal)logger.error(error);return}throw error}},normalizeDtsOptions=(options,context,defaultOptions)=>{return normalizeOptions(isTSProject(options.dts,context),{generateTypes:defaultOptions?.defaultGenerateOptions||DEFAULT_GENERATE_TYPES,consumeTypes:defaultOptions?.defaultConsumeOptions||DEFAULT_CONSUME_TYPES,extraOptions:{},displayErrorInTerminal:true},"mfOptions.dts")(options.dts)};var init_esm=__esm(()=>{init_expose_rpc_B0rqtOKP();init_Action_DNNg2YDh();init_Broker_BfFUcTHm();init_consumeTypes_WKYNaS9i();init_core();init_dist();__filename$1=fileURLToPath9(import.meta.url);__dirname$1=path10.dirname(__filename$1);__filename4=fileURLToPath9(import.meta.url);__dirname4=path10.dirname(__filename4);DEFAULT_CONSUME_TYPES={abortOnError:false,consumeAPITypes:true,typesOnBuild:false};DEFAULT_GENERATE_TYPES={generateAPITypes:true,compileInChildProcess:true,abortOnError:false,extractThirdParty:false,extractRemoteTypes:false}});import fs4 from"fs";import*as path$13 from"path";import os from"os";function pluginDts(options){if(options.dts===false)return[];const baseDtsModuleFederationConfig=buildDtsModuleFederationConfig(options);const getDtsModuleFederationConfig=(context)=>({...baseDtsModuleFederationConfig,dts:resolveDtsPluginOptions(options.dts,options,context)});let resolvedConfig;let devWorker;let normalizedDevOptions;let hasGeneratedBundle=false;return[{name:"module-federation-dts-dev",apply:"serve",config(config){normalizedDevOptions=normalizeDevOptions(options.dev);if(!normalizedDevOptions)return;if(normalizedDevOptions.disableDynamicRemoteTypeHints)return;ensureRuntimePlugin(options,DYNAMIC_HINTS_PLUGIN);const define=config.define?{...config.define}:{};if(!("FEDERATION_IPV4"in define))define.FEDERATION_IPV4=JSON.stringify(getIPv4());config.define=define},configResolved(config){resolvedConfig=config},configureServer(server){if(!normalizedDevOptions||!resolvedConfig)return;const devOptions=normalizedDevOptions;if(devOptions.disableDynamicRemoteTypeHints&&devOptions.disableHotTypesReload&&devOptions.disableLiveReload)return;if(!options.name)throw createModuleFederationError("name is required if you want to enable dev server!");const outputDir=resolveOutputDir(resolvedConfig);const dtsModuleFederationConfig=getDtsModuleFederationConfig(resolvedConfig.root);const normalizedDtsOptions=normalizeDevDtsOptions(dtsModuleFederationConfig.dts,resolvedConfig.root);if(typeof normalizedDtsOptions!=="object")return;const normalizedGenerateTypes=normalizeOptions(Boolean(normalizedDtsOptions),{compileInChildProcess:true},"mfOptions.dts.generateTypes")(normalizedDtsOptions.generateTypes);const remote=normalizedGenerateTypes===false?undefined:{implementation:normalizedDtsOptions.implementation,context:resolvedConfig.root,outputDir,moduleFederationConfig:{...dtsModuleFederationConfig},hostRemoteTypesFolder:normalizedGenerateTypes.typesFolder||"@mf-types",...normalizedGenerateTypes,typesFolder:DEV_TYPES_FOLDER};if(remote)server.middlewares.use(createDevDtsAssetMiddleware(getDevDtsAssetPaths({outputDir,publicTypesFolder:remote.hostRemoteTypesFolder||"@mf-types",root:resolvedConfig.root,base:resolvedConfig.base})));if(remote&&!remote.tsConfigPath&&normalizedDtsOptions.tsConfigPath)remote.tsConfigPath=normalizedDtsOptions.tsConfigPath;const normalizedConsumeTypes=normalizeOptions(Boolean(normalizedDtsOptions),{consumeAPITypes:true},"mfOptions.dts.consumeTypes")(normalizedDtsOptions.consumeTypes);const host=normalizedConsumeTypes===false?undefined:{implementation:normalizedDtsOptions.implementation,context:resolvedConfig.root,moduleFederationConfig:dtsModuleFederationConfig,typesFolder:normalizedConsumeTypes.typesFolder||"@mf-types",abortOnError:false,...normalizedConsumeTypes};const extraOptions=normalizedDtsOptions.extraOptions||{};if(!remote&&!host&&devOptions.disableLiveReload)return;const startDevWorker=async()=>{let remoteTypeUrls;if(host)remoteTypeUrls=await new Promise((resolve)=>{consumeTypesAPI({host,extraOptions,displayErrorInTerminal:normalizedDtsOptions.displayErrorInTerminal},resolve)});devWorker=new DevWorker({name:options.name,remote,host:host?{...host,remoteTypeUrls}:undefined,extraOptions,disableLiveReload:devOptions.disableLiveReload,disableHotTypesReload:devOptions.disableHotTypesReload});let updateTimer;const update=()=>{clearTimeout(updateTimer);updateTimer=setTimeout(()=>devWorker?.update(),UPDATE_DEBOUNCE_MS)};server.watcher.on("change",update);server.watcher.on("add",update);server.watcher.on("unlink",update);server.httpServer?.once("close",()=>{clearTimeout(updateTimer);devWorker?.exit();server.watcher.off("change",update);server.watcher.off("add",update);server.watcher.off("unlink",update)})};startDevWorker().catch((error)=>{logDtsError(error,normalizedDtsOptions)})}},{name:"module-federation-dts-build",apply:"build",configResolved(config){resolvedConfig=config},async generateBundle(){if(hasGeneratedBundle)return;hasGeneratedBundle=true;if(!resolvedConfig)return;let normalizedDtsOptions;try{normalizedDtsOptions=normalizeDtsOptions(getDtsModuleFederationConfig(resolvedConfig.root),resolvedConfig.root)}catch(error){logDtsError(error,options.dts);return}if(typeof normalizedDtsOptions!=="object")return;const context=resolvedConfig.root;const outputDir=resolveOutputDir(resolvedConfig);let consumeOptions;try{consumeOptions=normalizeConsumeTypesOptions({context,dtsOptions:normalizedDtsOptions,pluginOptions:getDtsModuleFederationConfig(resolvedConfig.root)})}catch(error){logDtsError(error,normalizedDtsOptions);return}if(consumeOptions?.host?.typesOnBuild)try{await consumeTypesAPI(consumeOptions)}catch(error){logDtsError(error,normalizedDtsOptions)}let generateOptions;try{generateOptions=normalizeGenerateTypesOptions({context,outputDir,dtsOptions:normalizedDtsOptions,pluginOptions:getDtsModuleFederationConfig(resolvedConfig.root)})}catch(error){logDtsError(error,normalizedDtsOptions);return}if(!generateOptions)return;try{await generateTypesAPI({dtsManagerOptions:generateOptions})}catch(error){logDtsError(error,normalizedDtsOptions)}}}]}var DEFAULT_DEV_OPTIONS,DYNAMIC_HINTS_PLUGIN="@module-federation/dts-plugin/dynamic-remote-type-hints-plugin",localIpv4="127.0.0.1",getIpv4Interfaces=()=>{try{const interfaces=os.networkInterfaces();const ipv4Interfaces=[];Object.values(interfaces).forEach((detail)=>{detail?.forEach((detail)=>{const familyV4Value=typeof detail.family==="string"?"IPv4":4;if(detail.family===familyV4Value&&detail.address!==localIpv4)ipv4Interfaces.push(detail)})});return ipv4Interfaces}catch(_err){return[]}},getIPv4=()=>{if(process.env["FEDERATION_IPV4"])return process.env["FEDERATION_IPV4"];return(getIpv4Interfaces()[0]||{address:localIpv4}).address},DEV_TYPES_FOLDER=".dev-server",UPDATE_DEBOUNCE_MS=300,forkDevWorkerPath,DevWorker=class{worker=rpc_exports.createRpcWorker(forkDevWorkerPath,{},undefined,false);constructor(options){this.worker.connect(options)}update(){this.worker.process?.send?.({type:rpc_exports.RpcGMCallTypes.CALL,id:this.worker.id,args:[undefined,"update"]})}exit(){this.worker.terminate()}},normalizeDevOptions=(dev)=>{if(dev===false)return false;if(dev===true||typeof dev==="undefined")return{...DEFAULT_DEV_OPTIONS};return{...DEFAULT_DEV_OPTIONS,...dev}},buildDtsModuleFederationConfig=(options)=>{const exposes={};Object.entries(options.exposes).forEach(([key,value])=>{if(value.import)exposes[key]=value.import});const remotes={};Object.entries(options.remotes).forEach(([key,remote])=>{if(!remote.entry)return;const entryGlobalName=remote.entryGlobalName?.startsWith("http")||remote.entryGlobalName?.includes(".json")?remote.name||key:remote.entryGlobalName||remote.name||key;remotes[key]=`${entryGlobalName}@${remote.entry}`});return{...options,exposes,remotes}},resolveOutputDir=(config)=>{const{outDir}=config.build;if(path$13.isAbsolute(outDir))return normalizePathForImport(path$13.relative(config.root,outDir));return outDir},ensureRuntimePlugin=(options,pluginId)=>{if(!options.runtimePlugins.some((plugin)=>{if(typeof plugin==="string")return plugin===pluginId;return plugin[0]===pluginId}))options.runtimePlugins.push(pluginId)},getExposeImportPaths=(options)=>{return Object.values(options.exposes).map((value)=>{return value.import}).filter((value)=>Boolean(value))},usesVueSfcExposes=(options)=>{return getExposeImportPaths(options).some((value)=>value.endsWith(".vue"))},resolveDtsPluginOptions=(dts,options,context)=>{if(dts===false)return false;const inferredGenerateTypesDefaults={generateAPITypes:true};if(usesVueSfcExposes(options)&&hasPackageDependency("vue-tsc",context))inferredGenerateTypesDefaults.compilerInstance="vue-tsc";if(dts===true||typeof dts==="undefined")return{generateTypes:inferredGenerateTypesDefaults};const generateTypes=dts.generateTypes;return{...dts,generateTypes:generateTypes===false?false:{...inferredGenerateTypesDefaults,...generateTypes===true||typeof generateTypes==="undefined"?{}:generateTypes}}},getBasePath2=(base)=>{if(base.startsWith("http://")||base.startsWith("https://"))return new URL(base).pathname.replace(/\/$/,"")||"/";return base.replace(/\/$/,"")||"/"},joinBaseAndAsset=(base,assetFileName)=>{const basePath=getBasePath2(base);return`${basePath==="/"?"":basePath}/${assetFileName}`.replace(/\/{2,}/g,"/")},getDevDtsAssetPaths=(options)=>{const{outputDir,publicTypesFolder,root,base}=options;return{apiFilePath:path$13.resolve(root,outputDir,`${DEV_TYPES_FOLDER}.d.ts`),apiRequestPath:joinBaseAndAsset(base,`${publicTypesFolder}.d.ts`),zipFilePath:path$13.resolve(root,outputDir,`${DEV_TYPES_FOLDER}.zip`),zipRequestPath:joinBaseAndAsset(base,`${publicTypesFolder}.zip`)}},createDevDtsAssetMiddleware=(assetPaths)=>{return(req,res,next)=>{const requestPath=req.url?.split("?")[0];const isZipRequest=requestPath===assetPaths.zipRequestPath;const isApiRequest=requestPath===assetPaths.apiRequestPath;if(!isZipRequest&&!isApiRequest){next();return}const filePath=isZipRequest?assetPaths.zipFilePath:assetPaths.apiFilePath;if(!fs4.existsSync(filePath)){res.statusCode=404;res.end();return}res.statusCode=200;res.setHeader("Content-Type",isZipRequest?"application/x-gzip":"application/typescript");if(req.method==="HEAD"){res.end();return}const stream=fs4.createReadStream(filePath);stream.on("error",()=>{if(!res.headersSent)res.statusCode=500;res.end()});res.on("close",()=>{stream.destroy()});stream.pipe(res)}},normalizeDevDtsOptions=(dts,context)=>{return normalizeOptions(isTSProject(dts,context),{generateTypes:{compileInChildProcess:true},consumeTypes:{consumeAPITypes:true},extraOptions:{},displayErrorInTerminal:typeof dts==="object"&&dts?dts.displayErrorInTerminal:undefined},"mfOptions.dts")(dts)},logDtsError=(error,dtsOptions)=>{if(dtsOptions===false)return;if(typeof dtsOptions==="object"&&dtsOptions&&dtsOptions.displayErrorInTerminal===false)return;mfError(error)};var init_pluginDts_DnEX3cp_=__esm(()=>{init_logger_DOwfTlw5();init_dtsConstants_r5OfegUr();init_dist();init_esm();init_core();DEFAULT_DEV_OPTIONS={disableLiveReload:true,disableHotTypesReload:false,disableDynamicRemoteTypeHints:false};forkDevWorkerPath=(()=>{return resolveImportPath("@module-federation/dts-plugin/dist/fork-dev-worker.js")})()});var pipeArguments=(self,args)=>{switch(args.length){case 0:return self;case 1:return args[0](self);case 2:return args[1](args[0](self));case 3:return args[2](args[1](args[0](self)));case 4:return args[3](args[2](args[1](args[0](self))));case 5:return args[4](args[3](args[2](args[1](args[0](self)))));case 6:return args[5](args[4](args[3](args[2](args[1](args[0](self))))));case 7:return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))));case 8:return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))));case 9:return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))));default:{let ret=self;for(let i=0,len=args.length;i<len;i++){ret=args[i](ret)}return ret}}};var Prototype={pipe(){return pipeArguments(this,arguments)}};var Class=function(){function PipeableBase(){}PipeableBase.prototype=Prototype;return PipeableBase}();var dual=function(arity,body){if(typeof arity==="function"){return function(){return arity(arguments)?body.apply(this,arguments):(self)=>body(self,...arguments)}}switch(arity){case 0:case 1:throw new RangeError(`Invalid arity ${arity}`);case 2:return function(a,b){if(arguments.length>=2){return body(a,b)}return function(self){return body(self,a)}};case 3:return function(a,b,c){if(arguments.length>=3){return body(a,b,c)}return function(self){return body(self,a,b)}};default:return function(){if(arguments.length>=arity){return body.apply(this,arguments)}const args=arguments;return function(self){return body(self,...args)}}}};var identity=(a)=>a;var constant=(value)=>()=>value;var constTrue=constant(true);var constFalse=constant(false);var constUndefined=constant(undefined);var constVoid=constUndefined;function pipe(a,...args){return pipeArguments(a,args)}function flow(ab,bc,cd,de,ef,fg,gh,hi,ij){switch(arguments.length){case 1:return ab;case 2:return function(){return bc(ab.apply(this,arguments))};case 3:return function(){return cd(bc(ab.apply(this,arguments)))};case 4:return function(){return de(cd(bc(ab.apply(this,arguments))))};case 5:return function(){return ef(de(cd(bc(ab.apply(this,arguments)))))};case 6:return function(){return fg(ef(de(cd(bc(ab.apply(this,arguments))))))};case 7:return function(){return gh(fg(ef(de(cd(bc(ab.apply(this,arguments)))))))};case 8:return function(){return hi(gh(fg(ef(de(cd(bc(ab.apply(this,arguments))))))))};case 9:return function(){return ij(hi(gh(fg(ef(de(cd(bc(ab.apply(this,arguments)))))))))}}return}function memoize(f){const cache=new WeakMap;return(a)=>{const cached=cache.get(a);if(cached!==undefined)return cached;const result=f(a);cache.set(a,result);return result}}function memoizeIdempotent(f){const cache=new WeakMap;return(a)=>{const cached=cache.get(a);if(cached!==undefined)return cached;const result=f(a);cache.set(a,result);if(result!==a){cache.set(result,result)}return result}}var make=(isEquivalent)=>(self,that)=>self===that||isEquivalent(self,that);var getAllObjectKeys=(obj)=>{const keys=new Set(Reflect.ownKeys(obj));if(obj.constructor===Object)return keys;if(obj instanceof Error){keys.delete("stack")}const proto=Object.getPrototypeOf(obj);let current=proto;while(current!==null&&current!==Object.prototype){const ownKeys=Reflect.ownKeys(current);for(let i=0;i<ownKeys.length;i++){keys.add(ownKeys[i])}current=Object.getPrototypeOf(current)}if(keys.has("constructor")&&typeof obj.constructor==="function"&&proto===obj.constructor.prototype){keys.delete("constructor")}return keys};var byReferenceInstances=new WeakSet;var viewBytes=(view)=>new Uint8Array(view.buffer,view.byteOffset,view.byteLength);var backEdges=0;var addBackEdge=()=>{backEdges++};function isString(input){return typeof input==="string"}function isNumber(input){return typeof input==="number"}function isBoolean(input){return typeof input==="boolean"}function isSymbol(input){return typeof input==="symbol"}function isPropertyKey(u){return isString(u)||isNumber(u)||isSymbol(u)}function isFunction(input){return typeof input==="function"}function isNotNullish(input){return input!=null}function isUnknown(_){return true}function isObject(input){return typeof input==="object"&&input!==null&&!Array.isArray(input)}function isObjectKeyword(input){return typeof input==="object"&&input!==null||isFunction(input)}var hasProperty=dual(2,(self,property)=>isObjectKeyword(self)&&(property in self));var isTagged=dual(2,(self,tag)=>hasProperty(self,"_tag")&&self["_tag"]===tag);function isIterable(input){return hasProperty(input,Symbol.iterator)||isString(input)}var symbol="~effect/Hash";var hash=(self)=>{switch(typeof self){case"number":return number(self);case"bigint":return string(self.toString(10));case"string":return string(self);case"function":case"object":{if(self===null){break}else if(self instanceof Date){if(Number.isNaN(self.getTime())){return string("Invalid Date")}return string(self.toISOString())}else if(self instanceof RegExp){return string(self.toString())}else{if(byReferenceInstances.has(self)){return random(self)}const cached=hashCache.get(self);if(cached!==undefined){return cached}if(visitedObjects.has(self)){addBackEdge();return string("[Circular]")}visitedObjects.add(self);const seen=backEdges;let h;try{if(symbol in self){h=self[symbol]()}else if(typeof self==="function"){h=random(self)}else if(self instanceof DataView){h=array(viewBytes(self))}else if(Array.isArray(self)||ArrayBuffer.isView(self)){h=array(self)}else if(self instanceof Map){h=hashMap(self)}else if(self instanceof Set){h=hashSet(self)}else{h=structure(self)}}finally{visitedObjects.delete(self)}if(seen===backEdges){hashCache.set(self,h)}return h}}}return optimize(mix(string(String(self))))};var random=(self)=>{if(!randomHashCache.has(self)){randomHashCache.set(self,optimize(Math.random()*4294967296|0))}return randomHashCache.get(self)};var mix=(h)=>{h^=h>>>16;h=Math.imul(h,2246822507);h^=h>>>13;h=Math.imul(h,3266489909);return h^h>>>16};var combine=dual(2,(self,b)=>mix(Math.imul(self,2654435761)+Math.imul(b,2246822507)));var optimize=(n)=>n&3221225471|n>>>1&1073741824;var float64=new DataView(new ArrayBuffer(8));var number=(n)=>{const h=n|0;if(h===n){return optimize(h)}float64.setFloat64(0,n!==n?NaN:n);return optimize(combine(float64.getInt32(0),float64.getInt32(4)))};var string=(str)=>{let h=5381,i=str.length;while(i){h=h*33^str.charCodeAt(--i)}return optimize(h)};var structureKeys=(o,keys)=>{let h=12289;for(const key of keys){h^=combine(hash(key),hash(o[key]))}return optimize(h)};var structure=(o)=>structureKeys(o,getAllObjectKeys(o));var unordered=(seed,f)=>(iter)=>{let h=seed;for(const element of iter){h^=f(element)}return optimize(h)};var array=(arr)=>{let h=6151;for(const element of arr){h=combine(h,hash(element))}return optimize(h)};var hashMap=unordered(string("Map"),([k,v])=>combine(hash(k),hash(v)));var setSeed=string("Set");var hashSet=unordered(setSeed,(element)=>combine(setSeed,hash(element)));var randomHashCache=new WeakMap;var hashCache=new WeakMap;var visitedObjects=new WeakSet;var symbol2="~effect/Equal";function equals(){if(arguments.length===1){return(self)=>compareBoth(self,arguments[0])}return compareBoth(arguments[0],arguments[1])}function compareBoth(self,that){if(self===that)return true;if(self==null||that==null)return false;const selfType=typeof self;if(selfType!==typeof that){return false}if(selfType==="number"&&self!==self&&that!==that){return true}if(selfType!=="object"&&selfType!=="function"){return false}if(byReferenceInstances.has(self)||byReferenceInstances.has(that)){return false}return compareObjects(self,that)}function compareObjects(self,that){const depth=pathLeft.length;for(let i=depth;i-- >0;){if(pathLeft[i]===self&&pathRight[i]===that)return true}if(depth)return compareOnPath(self,that);let known=results.get(self);if(!known)results.set(self,known=new WeakMap);let result=known.get(that);if(result===undefined)known.set(that,result=compareOnPath(self,that));return result}function compareOnPath(self,that){pathLeft.push(self);pathRight.push(that);try{return compareStructure(self,that)}finally{pathLeft.pop();pathRight.pop()}}var pathLeft=[];var pathRight=[];var results=new WeakMap;function compareStructure(self,that){if(hash(self)!==hash(that)){return false}else if(self instanceof Date){if(!(that instanceof Date))return false;const selfTime=self.getTime();const thatTime=that.getTime();return selfTime===thatTime||Number.isNaN(selfTime)&&Number.isNaN(thatTime)}else if(self instanceof RegExp){return that instanceof RegExp&&self.toString()===that.toString()}const bothEquals=isEqual(self);if(bothEquals!==isEqual(that)||typeof self==="function"&&!bothEquals){return false}else if(bothEquals){return self[symbol2](that)}else if(Array.isArray(self)){if(!Array.isArray(that)||self.length!==that.length){return false}return compareArrays(self,that)}else if(ArrayBuffer.isView(self)){const selfIsDataView=self instanceof DataView;if(!ArrayBuffer.isView(that)||self.byteLength!==that.byteLength||selfIsDataView!==that instanceof DataView){return false}if(selfIsDataView){return compareTypedArrays(viewBytes(self),viewBytes(that))}return compareTypedArrays(self,that)}else if(self instanceof Map){if(!(that instanceof Map)||self.size!==that.size){return false}return compareHashed(self,that,entryHash,equalEntries)}else if(self instanceof Set){if(!(that instanceof Set)||self.size!==that.size){return false}return compareHashed(self,that,hash,compareBoth)}return compareRecords(self,that)}function compareArrays(self,that){for(let i=0;i<self.length;i++){if(!compareBoth(self[i],that[i])){return false}}return true}function compareTypedArrays(self,that){if(self.length!==that.length){return false}for(let i=0;i<self.length;i++){if(self[i]!==that[i]){return false}}return true}function compareRecords(self,that){const selfKeys=getAllObjectKeys(self);const thatKeys=getAllObjectKeys(that);if(selfKeys.size!==thatKeys.size){return false}for(const key of selfKeys){if(!thatKeys.has(key)||!compareBoth(self[key],that[key])){return false}}return true}function compareHashed(self,that,hashOf,equivalent){const groups=new Map;for(const item of that){const h=hashOf(item);const group=groups.get(h);if(group)group.push(item);else groups.set(h,[item])}outer:for(const item of self){const group=groups.get(hashOf(item));if(group){for(let i=0;i<group.length;i++){if(equivalent(item,group[i])){group[i]=group[group.length-1];group.pop();continue outer}}}return false}return true}var entryHash=(entry)=>hash(entry[0]);var equalEntries=(self,that)=>compareBoth(self[0],that[0])&&compareBoth(self[1],that[1]);var isEqual=(u)=>hasProperty(u,symbol2);var symbolRedactable=Symbol.for("~effect/Redactable");var isRedactable=(u)=>hasProperty(u,symbolRedactable);function redact(u){if(isRedactable(u))return getRedacted(u);return u}function getRedacted(redactable){return redactable[symbolRedactable](globalThis[currentFiberTypeId]?.context??emptyContext)}var currentFiberTypeId="~effect/Fiber/currentFiber";var emptyMap=new Map;var emptyContext={"~effect/Context":{},base:emptyMap,depth:0,mapUnsafe:emptyMap,pipe(){return pipeArguments(this,arguments)}};function format(input,options){const space=options?.space??0;const ancestors=new WeakSet;const gap=!space?"":typeof space==="number"?" ".repeat(space):space;const ind=(d)=>gap.repeat(d);const wrap=(v,body)=>{const ctor=v?.constructor;return ctor&&ctor!==Object.prototype.constructor&&ctor.name?`${ctor.name}(${body})`:body};const ownKeys=(o)=>{try{return Reflect.ownKeys(o)}catch{return["[ownKeys threw]"]}};function recur(v,d=0){try{return recurUnsafe(v,d)}catch{if(typeof v==="object"&&v!==null||typeof v==="function")ancestors.delete(v);return"[inspection threw]"}}function recurUnsafe(v,d=0){if(typeof v==="string")return JSON.stringify(v);if(typeof v==="number"||v==null||typeof v==="boolean"||typeof v==="symbol")return String(v);if(typeof v==="bigint")return String(v)+"n";if(typeof v==="object"||typeof v==="function"){if(ancestors.has(v))return CIRCULAR;ancestors.add(v);let output;if(symbolRedactable in v){output=recur(getRedacted(v),d)}else if(Array.isArray(v)){output=!gap||v.length<=1?`[${v.map((x)=>recur(x,d)).join(",")}]`:`[
214
+ hostName: ${hostName}`,"updateTypes","info");if(updateMode===UpdateMode.POSITIVE&&remoteName===hostName){if(!this.options.remote)return;await this.generateTypes()}else{const{remoteAliasMap}=this;if(!this.options.host)return;const{hostOptions,mapRemotesToDownload}=retrieveHostConfig(this.options.host);const loadedRemoteInfo=Object.values(remoteAliasMap).find((i)=>i.name===remoteName);const consumeTypes=async(requiredRemoteInfo)=>{fileLog(`consumeTypes start`,"updateTypes","info");if(!requiredRemoteInfo.zipUrl)throw new Error(`Can not get ${requiredRemoteInfo.name}'s types archive url!`);const[_alias,destinationPath]=await this.consumeTargetRemotes(hostOptions,{...requiredRemoteInfo,zipUrl:remoteTarPath||requiredRemoteInfo.zipUrl});if(await this.downloadAPITypes(requiredRemoteInfo,destinationPath,hostOptions))this.consumeAPITypes(hostOptions);fileLog(`consumeTypes end`,"updateTypes","info")};fileLog(`loadedRemoteInfo: ${JSON.stringify(loadedRemoteInfo,null,2)}`,"updateTypes","info");if(!loadedRemoteInfo){const remoteInfo=Object.values(mapRemotesToDownload).find((item)=>{return item.name===remoteName});fileLog(`remoteInfo: ${JSON.stringify(remoteInfo,null,2)}`,"updateTypes","info");if(remoteInfo){if(!this.remoteAliasMap[remoteInfo.alias]){const requiredRemoteInfo=await this.requestRemoteManifest(remoteInfo,hostOptions);this.remoteAliasMap[remoteInfo.alias]=requiredRemoteInfo}await consumeTypes(this.remoteAliasMap[remoteInfo.alias])}else if(updatedRemoteInfo){const consumeDynamicRemoteTypes=async()=>{await consumeTypes(this.updatedRemoteInfos[updatedRemoteInfo.name])};if(!this.updatedRemoteInfos[updatedRemoteInfo.name]){const parsedRemoteInfo=retrieveRemoteInfo({hostOptions,remoteAlias:updatedRemoteInfo.alias||updatedRemoteInfo.name,remote:updatedRemoteInfo.url});fileLog(`start request manifest`,"consumeTypes","info");this.updatedRemoteInfos[updatedRemoteInfo.name]=await this.requestRemoteManifest(parsedRemoteInfo,hostOptions);fileLog(`end request manifest, this.updatedRemoteInfos[updatedRemoteInfo.name]: ${JSON.stringify(this.updatedRemoteInfos[updatedRemoteInfo.name],null,2)}`,"updateTypes","info");await consumeDynamicRemoteTypes()}if(!once&&this.updatedRemoteInfos[updatedRemoteInfo.name])await consumeDynamicRemoteTypes()}}else await consumeTypes(loadedRemoteInfo)}}catch(err){fileLog(`updateTypes fail, ${err}`,"updateTypes","error")}}},dispatcherCache,validateOptions=(options)=>{if(!options.moduleFederationConfig)throw new Error("moduleFederationConfig is required")},isTSProject=(dtsOptions,context=process.cwd())=>{if(dtsOptions===false)return false;try{let filepath="";if(typeof dtsOptions==="object"&&dtsOptions.tsConfigPath)filepath=dtsOptions.tsConfigPath;else filepath=path8.resolve(context,"./tsconfig.json");if(!path8.isAbsolute(filepath))filepath=path8.resolve(context,filepath);return fs3.existsSync(filepath)}catch(err){return false}},getEnvHeaders=()=>{const headersStr=getProcessEnv()["MF_ENV_HEADERS"];if(!headersStr||headersStr==="undefined")return{};try{return{...JSON.parse(headersStr)}}catch{return{}}},createDispatcherFromFamily=(family)=>{if(!family)return;if(dispatcherCache.has(family))return dispatcherCache.get(family);try{const dispatcher=new Agent({connect:{family}});dispatcherCache.set(family,dispatcher);return dispatcher}catch{}},toHeaderRecord=(headers)=>{const out={};headers.forEach((value,key)=>{out[key.toLowerCase()]=value});return out},defaultOptions2,getDependentFiles=(rootFiles,configContent,rootDir,typescript)=>{const dependentFiles=typescript.createProgram(rootFiles,configContent.options).getSourceFiles().map((file)=>file.fileName).filter((file)=>!file.endsWith(".d.ts")&&isFileWithinRootDir(file,rootDir)).map((file)=>normalizeFileToRootDir(file,rootDir));return dependentFiles.length?dependentFiles:rootFiles},normalizeForComparison=(value)=>{try{return normalize3(realpathSync2.native(value))}catch{return normalize3(value)}},isFileWithinRootDir=(file,rootDir)=>{const normalizedFile=normalizeForComparison(file);const normalizedRootDir=normalizeForComparison(rootDir);return normalizedFile===normalizedRootDir||normalizedFile.startsWith(normalizedRootDir.endsWith(sep)?normalizedRootDir:`${normalizedRootDir}${sep}`)},normalizeFileToRootDir=(file,rootDir)=>{const normalizedFile=normalizeForComparison(file);const normalizedRootDir=normalizeForComparison(rootDir);if(normalizedFile===normalizedRootDir||normalizedFile.startsWith(normalizedRootDir.endsWith(sep)?normalizedRootDir:`${normalizedRootDir}${sep}`))return normalize3(join5(rootDir,relative(normalizedRootDir,normalizedFile)));return normalize3(file)},getTypeScriptContext=({context,moduleFederationConfig})=>{const dtsOptions=moduleFederationConfig.dts;return typeof dtsOptions!=="boolean"&&dtsOptions?.cwd?dtsOptions.cwd:context},resolveFromConfigDir=(value,configDir)=>{if(typeof value!=="string")return value;return isAbsolute3(value)?normalize3(value):resolve5(configDir,value)},normalizeCompilerOptions=(compilerOptions={},configDir)=>{const normalizedOptions={...compilerOptions};for(const pathOption of["rootDir","outDir","declarationDir","tsBuildInfoFile"])if(typeof normalizedOptions[pathOption]==="string")normalizedOptions[pathOption]=resolveFromConfigDir(normalizedOptions[pathOption],configDir);if(normalizedOptions["moduleResolution"]==="node"||normalizedOptions["moduleResolution"]==="node10")normalizedOptions["moduleResolution"]="bundler";return normalizedOptions},parseShowConfigOutput=(stdout,resolvedTsConfigPath)=>{const configDir=dirname3(resolvedTsConfigPath);const shownConfig=JSON.parse(stdout);const compilerOptions=normalizeCompilerOptions(shownConfig.compilerOptions,configDir);const fileNames=(shownConfig.files||[]).map((file)=>resolveFromConfigDir(file,configDir));const projectReferences=(shownConfig.references||[]).map((reference)=>({...reference,path:resolveFromConfigDir(reference.path,configDir),originalPath:reference.path}));return{rawTsConfigJson:{...shownConfig,compilerOptions},configContent:{options:compilerOptions,fileNames,projectReferences}}},readTsConfigWithTsc=(resolvedTsConfigPath,typeScriptContext)=>{const typeScriptPackageInfo=getTypeScriptPackageInfo(typeScriptContext);return parseShowConfigOutput(execFileSync(process.execPath,[typeScriptPackageInfo.tscBinPath,"--showConfig","--project",resolvedTsConfigPath],{cwd:typeScriptContext,encoding:"utf8",stdio:["ignore","pipe","pipe"]}),resolvedTsConfigPath)},writeListFilesTsConfig=(rootFiles,resolvedTsConfigPath,context,compilerOptions)=>{const tempTsConfigJsonPath=resolve5(context,"node_modules",TEMP_DIR,`tsconfig.list-files.${crypto2.createHash("md5").update(`${JSON.stringify(rootFiles)}${resolvedTsConfigPath}${Date.now()}`).digest("hex")}.json`);mkdirSync4(dirname3(tempTsConfigJsonPath),{recursive:true});const listFilesConfig=compilerOptions?{compilerOptions,files:rootFiles.map((file)=>isAbsolute3(file)?file:resolve5(context,file))}:{extends:resolvedTsConfigPath,files:rootFiles.map((file)=>isAbsolute3(file)?file:resolve5(context,file))};writeFileSync3(tempTsConfigJsonPath,JSON.stringify(listFilesConfig,null,2));return tempTsConfigJsonPath},formatCompilerError=(error)=>{const readOutput=(value)=>{if(Buffer.isBuffer(value))return value.toString("utf8");return typeof value==="string"?value:""};if(typeof error==="object"&&error!==null){const processError=error;const stderr=readOutput(processError.stderr).trim();if(stderr)return stderr.split(/\r?\n/)[0];const stdout=readOutput(processError.stdout).trim();if(stdout)return stdout.split(/\r?\n/)[0];if(typeof processError.message==="string")return processError.message}return String(error)},getDependentFilesWithTsc=(rootFiles,rootDir,resolvedTsConfigPath,compilerOptions,context,typeScriptContext)=>{if(!rootFiles.length)return[];const typeScriptPackageInfo=getTypeScriptPackageInfo(typeScriptContext);const listFilesTsConfigPath=writeListFilesTsConfig(rootFiles,resolvedTsConfigPath,context,compilerOptions);try{const dependentFiles=execFileSync(process.execPath,[typeScriptPackageInfo.tscBinPath,"--listFilesOnly","--project",listFilesTsConfigPath],{cwd:typeScriptContext,encoding:"utf8",stdio:["ignore","pipe","pipe"]}).split(/\r?\n/).map((file)=>file.trim()).filter(Boolean).map((file)=>isAbsolute3(file)?file:resolve5(context,file)).filter((file)=>!file.endsWith(".d.ts")&&isFileWithinRootDir(file,rootDir)).map((file)=>normalizeFileToRootDir(file,rootDir));return dependentFiles.length?dependentFiles:rootFiles}catch(error){logger$1.warn(`Failed to collect TypeScript dependency files with "tsc --listFilesOnly"; falling back to exposed files only. ${formatCompilerError(error)}`);return rootFiles}finally{rmSync(listFilesTsConfigPath,{force:true})}},readTsConfig=(remoteOptions,mapComponentsToExpose)=>{const{tsConfigPath,typesFolder,compiledTypesFolder,context,additionalFilesToCompile,outputDir}=remoteOptions;const resolvedTsConfigPath=resolve5(context,tsConfigPath);const typeScriptContext=getTypeScriptContext(remoteOptions);const typeScriptPackageInfo=getTypeScriptPackageInfo(typeScriptContext);let rawTsConfigJson;let configContent;let typescript;if(typeScriptPackageInfo.majorVersion===7)({rawTsConfigJson,configContent}=readTsConfigWithTsc(resolvedTsConfigPath,typeScriptContext));else{typescript=requireTypeScript(typeScriptContext);const readResult=typescript.readConfigFile(resolvedTsConfigPath,typescript.sys.readFile);if(readResult.error)throw new Error(readResult.error.messageText.toString());rawTsConfigJson=readResult.config||{};configContent=typescript.parseJsonConfigFileContent(rawTsConfigJson,typescript.sys,dirname3(resolvedTsConfigPath));configContent.projectReferences=configContent.projectReferences||[]}const rootDir=getEffectiveRootDir(configContent);const outDir=resolve5(context,outputDir||configContent.options.outDir||"dist",typesFolder,compiledTypesFolder);const defaultCompilerOptions={rootDir,emitDeclarationOnly:true,noEmit:false,declaration:true,outDir};rawTsConfigJson.compilerOptions=rawTsConfigJson.compilerOptions||{};rawTsConfigJson.compilerOptions={incremental:true,tsBuildInfoFile:resolve5(context,"node_modules/.cache/mf-types/.tsbuildinfo"),...rawTsConfigJson.compilerOptions,...defaultCompilerOptions};const{paths,baseUrl,...restCompilerOptions}=rawTsConfigJson.compilerOptions||{};rawTsConfigJson.compilerOptions=restCompilerOptions;const outDirWithoutTypesFolder=resolve5(context,outputDir||configContent.options.outDir||"dist");const excludeExtensions=[".mdx",".md"];const rootFiles=[...Object.values(mapComponentsToExpose),...additionalFilesToCompile].filter((filename)=>!excludeExtensions.some((ext)=>filename.endsWith(ext)));const filesToCompile=[...typescript?getDependentFiles(rootFiles,configContent,rootDir,typescript):getDependentFilesWithTsc(rootFiles,rootDir,resolvedTsConfigPath,configContent.options,context,typeScriptContext),...configContent.fileNames.filter((filename)=>filename.endsWith(".d.ts")&&!filename.startsWith(outDirWithoutTypesFolder))];rawTsConfigJson.include=[];rawTsConfigJson.files=[...new Set(filesToCompile)];rawTsConfigJson.exclude=[];"references"in rawTsConfigJson&&delete rawTsConfigJson.references;rawTsConfigJson.extends=resolvedTsConfigPath;rawTsConfigJson.compilerOptions.declarationDir=outDir;return rawTsConfigJson},TS_EXTENSIONS,resolveWithExtension=(exposedPath,context)=>{const explicitExtension=extname(exposedPath);if(TS_EXTENSIONS.includes(explicitExtension))return resolve5(context,exposedPath);for(const extension of TS_EXTENSIONS){const exposedPathWithExtension=resolve5(context,`${exposedPath}${extension}`);if(existsSync5(exposedPathWithExtension))return exposedPathWithExtension}},resolveExposes=(remoteOptions)=>{return parseOptions2(remoteOptions.moduleFederationConfig.exposes||{},(item,key)=>({exposePath:Array.isArray(item)?item[0]:item,key}),(item,key)=>({exposePath:Array.isArray(item.import)?item.import[0]:item.import[0],key})).reduce((accumulator,item)=>{const{exposePath,key}=item[1];accumulator[key]=resolveWithExtension(exposePath,remoteOptions.context)||resolveWithExtension(join5(exposePath,"index"),remoteOptions.context)||exposePath;return accumulator},{})},retrieveRemoteConfig=(options)=>{validateOptions(options);const remoteOptions={...defaultOptions2,...options};const mapComponentsToExpose=resolveExposes(remoteOptions);const tsConfig=readTsConfig(remoteOptions,mapComponentsToExpose);if(tsConfig.compilerOptions.incremental&&tsConfig.compilerOptions.tsBuildInfoFile&&options.deleteTypesFolder!==true)remoteOptions.deleteTypesFolder=false;return{tsConfig,mapComponentsToExpose,remoteOptions}},RpcGMCallTypes;var init_expose_rpc_B0rqtOKP=__esm(()=>{init_Action_DNNg2YDh();init_Broker_BfFUcTHm();init_dist2();init_dist();init_dist3();init_dist4();init_node();import_adm_zip=__toESM(require_adm_zip(),1);__defProp2=Object.defineProperty;__require3=createRequire2(import.meta.url);__filename2=fileURLToPath7(import.meta.url);__dirname2=path8.dirname(__filename2);STARTS_WITH_SLASH=/^\//;defaultOptions$1={typesFolder:"@mf-types",remoteTypesFolder:"@mf-types",deleteTypesFolder:true,maxRetries:3,implementation:"",context:process.cwd(),abortOnError:true,consumeAPITypes:false,runtimePkgs:[],remoteTypeUrls:{},timeout:60000,typesOnBuild:false,family:0};dispatcherCache=new Map;defaultOptions2={tsConfigPath:"./tsconfig.json",typesFolder:"@mf-types",compiledTypesFolder:"compiled-types",hostRemoteTypesFolder:"@mf-types",deleteTypesFolder:true,additionalFilesToCompile:[],compilerInstance:"tsc",compileInChildProcess:false,implementation:"",generateAPITypes:false,context:process.cwd(),abortOnError:true,extractRemoteTypes:false,extractThirdParty:false,outputDir:"",deleteTsConfig:true};TS_EXTENSIONS=[".ts",".tsx",".vue",".svelte",".js",".jsx"];RpcGMCallTypes=function(RpcGMCallTypes){RpcGMCallTypes["CALL"]="mf_call";RpcGMCallTypes["RESOLVE"]="mf_resolve";RpcGMCallTypes["REJECT"]="mf_reject";RpcGMCallTypes["EXIT"]="mf_exit";return RpcGMCallTypes}({})});import{fileURLToPath as fileURLToPath8}from"url";import path9 from"path";import{randomUUID as randomUUID2}from"crypto";import*as child_process from"child_process";import*as process$2 from"process";function createControlledPromise(){let resolve=()=>{return};let reject=()=>{return};return{promise:new Promise((aResolve,aReject)=>{resolve=aResolve;reject=aReject}),resolve,reject}}function wrapRpc(childProcess,options){return async(...args)=>{if(!childProcess.send)throw new Error(`Process ${childProcess.pid} doesn't have IPC channels`);else if(!childProcess.connected)throw new Error(`Process ${childProcess.pid} doesn't have open IPC channels`);const{id,once}=options;const{promise:resultPromise,resolve:resolveResult,reject:rejectResult}=createControlledPromise();const{promise:sendPromise,resolve:resolveSend,reject:rejectSend}=createControlledPromise();const handleMessage=(message)=>{if(message?.id===id){if(message.type===RpcGMCallTypes.RESOLVE)resolveResult(message.value);else if(message.type===RpcGMCallTypes.REJECT)rejectResult(message.error)}if(once&&childProcess?.kill)childProcess.kill("SIGTERM")};const handleClose=(code,signal)=>{rejectResult(new RpcExitError(code?`Process ${childProcess.pid} exited with code ${code}${signal?` [${signal}]`:""}`:`Process ${childProcess.pid} exited${signal?` [${signal}]`:""}`,code,signal));removeHandlers()};const removeHandlers=()=>{childProcess.off("message",handleMessage);childProcess.off("close",handleClose)};if(once)childProcess.once("message",handleMessage);else childProcess.on("message",handleMessage);childProcess.on("close",handleClose);childProcess.send({type:RpcGMCallTypes.CALL,id,args},(error)=>{if(error){rejectSend(error);removeHandlers()}else resolveSend(undefined)});return sendPromise.then(()=>resultPromise)}}function createRpcWorker(modulePath,data,memoryLimit,once){const options={env:{...process$2.env,[FEDERATION_WORKER_DATA_ENV_KEY]:JSON.stringify(data||{})},stdio:["inherit","inherit","inherit","ipc"],serialization:"advanced"};if(memoryLimit)options.execArgv=[`--max-old-space-size=${memoryLimit}`];let childProcess,remoteMethod;const id=randomUUID2();return{connect(...args){if(childProcess&&!childProcess.connected){childProcess.send({type:RpcGMCallTypes.EXIT,id});childProcess=undefined;remoteMethod=undefined}if(!childProcess?.connected){childProcess=child_process.fork(modulePath,options);remoteMethod=wrapRpc(childProcess,{id,once})}if(!remoteMethod)return Promise.reject(new Error("Worker is not connected - cannot perform RPC."));return remoteMethod(...args)},terminate(){try{if(childProcess.connected)childProcess.send({type:RpcGMCallTypes.EXIT,id},(err)=>{if(err)console.error("Error sending message:",err)})}catch(error){if(error.code==="EPIPE")console.error("Pipe closed before message could be sent:",error);else console.error("Unexpected error:",error)}childProcess=undefined;remoteMethod=undefined},get connected(){return Boolean(childProcess?.connected)},get process(){return childProcess},get id(){return id}}}function getRpcWorkerData(){return JSON.parse(process$2.env[FEDERATION_WORKER_DATA_ENV_KEY]||"{}")}async function generateTypesInChildProcess(options){return new DtsWorker(options).controlledPromise}async function consumeTypes(options){await new(getDTSManagerConstructor(options.host?.implementation))(options).consumeTypes()}var RpcExitError,FEDERATION_WORKER_DATA_ENV_KEY="VMOK_WORKER_DATA_ENV",rpc_exports,__filename3,__dirname3,__extname,DtsWorker=class{constructor(options){this._options=cloneDeepOptions(options);this.removeUnSerializationOptions();this.rpcWorker=createRpcWorker(path9.resolve(__dirname3,`./fork-generate-dts${__extname}`),{},undefined,true);this._res=this.rpcWorker.connect(this._options)}removeUnSerializationOptions(){if(this._options.remote?.moduleFederationConfig?.manifest)delete this._options.remote?.moduleFederationConfig?.manifest;if(this._options.host?.moduleFederationConfig?.manifest)delete this._options.host?.moduleFederationConfig?.manifest}get controlledPromise(){const ensureChildProcessExit=()=>{try{const pid=this.rpcWorker.process?.pid;const rootPid=process.pid;if(pid&&rootPid!==pid)process.kill(pid,0)}catch(error){if(isDebugMode2())console.error(error)}};return Promise.resolve(this._res).then(()=>{this.exit();ensureChildProcessExit()}).catch((err)=>{if(isDebugMode2())console.error(err);ensureChildProcessExit()})}exit(){try{this.rpcWorker?.terminate()}catch(err){if(isDebugMode2())console.error(err)}}};var init_consumeTypes_WKYNaS9i=__esm(()=>{init_expose_rpc_B0rqtOKP();RpcExitError=class extends Error{constructor(message,code,signal){super(message);this.code=code;this.signal=signal;this.name="RpcExitError"}};rpc_exports=__exportAll({RpcExitError:()=>RpcExitError,RpcGMCallTypes:()=>RpcGMCallTypes,createRpcWorker:()=>createRpcWorker,exposeRpc:()=>exposeRpc,getRpcWorkerData:()=>getRpcWorkerData,wrapRpc:()=>wrapRpc});__filename3=fileURLToPath8(import.meta.url);__dirname3=path9.dirname(__filename3);__extname=path9.extname(__filename3)});var init_core=__esm(()=>{init_expose_rpc_B0rqtOKP();init_Broker_BfFUcTHm();init_consumeTypes_WKYNaS9i()});import{fileURLToPath as fileURLToPath9}from"url";import path10 from"path";var __filename$1,__dirname$1,__filename4,__dirname4,DEFAULT_CONSUME_TYPES,normalizeConsumeTypesOptions=({context,dtsOptions,pluginOptions})=>{const normalizedConsumeTypes=normalizeOptions(true,DEFAULT_CONSUME_TYPES,"mfOptions.dts.consumeTypes")(dtsOptions.consumeTypes);if(!normalizedConsumeTypes)return;const dtsManagerOptions={host:{implementation:dtsOptions.implementation,context,moduleFederationConfig:pluginOptions,...normalizedConsumeTypes},extraOptions:dtsOptions.extraOptions||{},displayErrorInTerminal:dtsOptions.displayErrorInTerminal};validateOptions(dtsManagerOptions.host);return dtsManagerOptions},consumeTypesAPI=async(dtsManagerOptions,cb)=>{return(typeof dtsManagerOptions.host.remoteTypeUrls==="function"?dtsManagerOptions.host.remoteTypeUrls():Promise.resolve(dtsManagerOptions.host.remoteTypeUrls)).then((remoteTypeUrls)=>{consumeTypes({...dtsManagerOptions,host:{...dtsManagerOptions.host,remoteTypeUrls}}).then(()=>{typeof cb==="function"&&cb(remoteTypeUrls)}).catch(()=>{typeof cb==="function"&&cb(remoteTypeUrls)})})},DEFAULT_GENERATE_TYPES,normalizeGenerateTypesOptions=({context,outputDir,dtsOptions,pluginOptions})=>{const normalizedGenerateTypes=normalizeOptions(true,DEFAULT_GENERATE_TYPES,"mfOptions.dts.generateTypes")(dtsOptions.generateTypes);if(!normalizedGenerateTypes)return;const normalizedConsumeTypes=normalizeOptions(true,{},"mfOptions.dts.consumeTypes")(dtsOptions.consumeTypes);const finalOptions={remote:{implementation:dtsOptions.implementation,context,outputDir,moduleFederationConfig:pluginOptions,...normalizedGenerateTypes},host:normalizedConsumeTypes===false?undefined:{context,moduleFederationConfig:pluginOptions,...normalizedConsumeTypes,remoteTypeUrls:typeof normalizedConsumeTypes?.remoteTypeUrls==="object"?normalizedConsumeTypes?.remoteTypeUrls:undefined},extraOptions:dtsOptions.extraOptions||{},displayErrorInTerminal:dtsOptions.displayErrorInTerminal};if(dtsOptions.tsConfigPath&&!finalOptions.remote.tsConfigPath)finalOptions.remote.tsConfigPath=dtsOptions.tsConfigPath;validateOptions(finalOptions.remote);return finalOptions},getGenerateTypesFn=(dtsManagerOptions)=>{let fn=generateTypes;if(dtsManagerOptions.remote.compileInChildProcess)fn=generateTypesInChildProcess;return fn},generateTypesAPI=({dtsManagerOptions})=>{return getGenerateTypesFn(dtsManagerOptions)(dtsManagerOptions).then(async()=>{await callAfterGenerateHook({dtsManagerOptions,generatedTypes:retrieveTypesAssetsInfo(dtsManagerOptions.remote)})})},callAfterGenerateHook=async({dtsManagerOptions,generatedTypes})=>{const afterGenerate=dtsManagerOptions.remote.afterGenerate;if(!afterGenerate)return;try{await afterGenerate(generatedTypes)}catch(error){if(dtsManagerOptions.remote.abortOnError===false){if(dtsManagerOptions.displayErrorInTerminal)logger.error(error);return}throw error}},normalizeDtsOptions=(options,context,defaultOptions)=>{return normalizeOptions(isTSProject(options.dts,context),{generateTypes:defaultOptions?.defaultGenerateOptions||DEFAULT_GENERATE_TYPES,consumeTypes:defaultOptions?.defaultConsumeOptions||DEFAULT_CONSUME_TYPES,extraOptions:{},displayErrorInTerminal:true},"mfOptions.dts")(options.dts)};var init_esm=__esm(()=>{init_expose_rpc_B0rqtOKP();init_Action_DNNg2YDh();init_Broker_BfFUcTHm();init_consumeTypes_WKYNaS9i();init_core();init_dist();__filename$1=fileURLToPath9(import.meta.url);__dirname$1=path10.dirname(__filename$1);__filename4=fileURLToPath9(import.meta.url);__dirname4=path10.dirname(__filename4);DEFAULT_CONSUME_TYPES={abortOnError:false,consumeAPITypes:true,typesOnBuild:false};DEFAULT_GENERATE_TYPES={generateAPITypes:true,compileInChildProcess:true,abortOnError:false,extractThirdParty:false,extractRemoteTypes:false}});import fs4 from"fs";import*as path$13 from"path";import os from"os";function pluginDts(options){if(options.dts===false)return[];const baseDtsModuleFederationConfig=buildDtsModuleFederationConfig(options);const getDtsModuleFederationConfig=(context)=>({...baseDtsModuleFederationConfig,dts:resolveDtsPluginOptions(options.dts,options,context)});let resolvedConfig;let devWorker;let normalizedDevOptions;let hasGeneratedBundle=false;return[{name:"module-federation-dts-dev",apply:"serve",config(config){normalizedDevOptions=normalizeDevOptions(options.dev);if(!normalizedDevOptions)return;if(normalizedDevOptions.disableDynamicRemoteTypeHints)return;ensureRuntimePlugin(options,DYNAMIC_HINTS_PLUGIN);const define=config.define?{...config.define}:{};if(!("FEDERATION_IPV4"in define))define.FEDERATION_IPV4=JSON.stringify(getIPv4());config.define=define},configResolved(config){resolvedConfig=config},configureServer(server){if(!normalizedDevOptions||!resolvedConfig)return;const devOptions=normalizedDevOptions;if(devOptions.disableDynamicRemoteTypeHints&&devOptions.disableHotTypesReload&&devOptions.disableLiveReload)return;if(!options.name)throw createModuleFederationError("name is required if you want to enable dev server!");const outputDir=resolveOutputDir(resolvedConfig);const dtsModuleFederationConfig=getDtsModuleFederationConfig(resolvedConfig.root);const normalizedDtsOptions=normalizeDevDtsOptions(dtsModuleFederationConfig.dts,resolvedConfig.root);if(typeof normalizedDtsOptions!=="object")return;const normalizedGenerateTypes=normalizeOptions(Boolean(normalizedDtsOptions),{compileInChildProcess:true},"mfOptions.dts.generateTypes")(normalizedDtsOptions.generateTypes);const remote=normalizedGenerateTypes===false?undefined:{implementation:normalizedDtsOptions.implementation,context:resolvedConfig.root,outputDir,moduleFederationConfig:{...dtsModuleFederationConfig},hostRemoteTypesFolder:normalizedGenerateTypes.typesFolder||"@mf-types",...normalizedGenerateTypes,typesFolder:DEV_TYPES_FOLDER};if(remote)server.middlewares.use(createDevDtsAssetMiddleware(getDevDtsAssetPaths({outputDir,publicTypesFolder:remote.hostRemoteTypesFolder||"@mf-types",root:resolvedConfig.root,base:resolvedConfig.base})));if(remote&&!remote.tsConfigPath&&normalizedDtsOptions.tsConfigPath)remote.tsConfigPath=normalizedDtsOptions.tsConfigPath;const normalizedConsumeTypes=normalizeOptions(Boolean(normalizedDtsOptions),{consumeAPITypes:true},"mfOptions.dts.consumeTypes")(normalizedDtsOptions.consumeTypes);const host=normalizedConsumeTypes===false?undefined:{implementation:normalizedDtsOptions.implementation,context:resolvedConfig.root,moduleFederationConfig:dtsModuleFederationConfig,typesFolder:normalizedConsumeTypes.typesFolder||"@mf-types",abortOnError:false,...normalizedConsumeTypes};const extraOptions=normalizedDtsOptions.extraOptions||{};if(!remote&&!host&&devOptions.disableLiveReload)return;const startDevWorker=async()=>{let remoteTypeUrls;if(host)remoteTypeUrls=await new Promise((resolve)=>{consumeTypesAPI({host,extraOptions,displayErrorInTerminal:normalizedDtsOptions.displayErrorInTerminal},resolve)});devWorker=new DevWorker({name:options.name,remote,host:host?{...host,remoteTypeUrls}:undefined,extraOptions,disableLiveReload:devOptions.disableLiveReload,disableHotTypesReload:devOptions.disableHotTypesReload});let updateTimer;const update=()=>{clearTimeout(updateTimer);updateTimer=setTimeout(()=>devWorker?.update(),UPDATE_DEBOUNCE_MS)};server.watcher.on("change",update);server.watcher.on("add",update);server.watcher.on("unlink",update);server.httpServer?.once("close",()=>{clearTimeout(updateTimer);devWorker?.exit();server.watcher.off("change",update);server.watcher.off("add",update);server.watcher.off("unlink",update)})};startDevWorker().catch((error)=>{logDtsError(error,normalizedDtsOptions)})}},{name:"module-federation-dts-build",apply:"build",configResolved(config){resolvedConfig=config},async generateBundle(){if(hasGeneratedBundle)return;hasGeneratedBundle=true;if(!resolvedConfig)return;let normalizedDtsOptions;try{normalizedDtsOptions=normalizeDtsOptions(getDtsModuleFederationConfig(resolvedConfig.root),resolvedConfig.root)}catch(error){logDtsError(error,options.dts);return}if(typeof normalizedDtsOptions!=="object")return;const context=resolvedConfig.root;const outputDir=resolveOutputDir(resolvedConfig);let consumeOptions;try{consumeOptions=normalizeConsumeTypesOptions({context,dtsOptions:normalizedDtsOptions,pluginOptions:getDtsModuleFederationConfig(resolvedConfig.root)})}catch(error){logDtsError(error,normalizedDtsOptions);return}if(consumeOptions?.host?.typesOnBuild)try{await consumeTypesAPI(consumeOptions)}catch(error){logDtsError(error,normalizedDtsOptions)}let generateOptions;try{generateOptions=normalizeGenerateTypesOptions({context,outputDir,dtsOptions:normalizedDtsOptions,pluginOptions:getDtsModuleFederationConfig(resolvedConfig.root)})}catch(error){logDtsError(error,normalizedDtsOptions);return}if(!generateOptions)return;try{await generateTypesAPI({dtsManagerOptions:generateOptions})}catch(error){logDtsError(error,normalizedDtsOptions)}}}]}var DEFAULT_DEV_OPTIONS,DYNAMIC_HINTS_PLUGIN="@module-federation/dts-plugin/dynamic-remote-type-hints-plugin",localIpv4="127.0.0.1",getIpv4Interfaces=()=>{try{const interfaces=os.networkInterfaces();const ipv4Interfaces=[];Object.values(interfaces).forEach((detail)=>{detail?.forEach((detail)=>{const familyV4Value=typeof detail.family==="string"?"IPv4":4;if(detail.family===familyV4Value&&detail.address!==localIpv4)ipv4Interfaces.push(detail)})});return ipv4Interfaces}catch(_err){return[]}},getIPv4=()=>{if(process.env["FEDERATION_IPV4"])return process.env["FEDERATION_IPV4"];return(getIpv4Interfaces()[0]||{address:localIpv4}).address},DEV_TYPES_FOLDER=".dev-server",UPDATE_DEBOUNCE_MS=300,forkDevWorkerPath,DevWorker=class{worker=rpc_exports.createRpcWorker(forkDevWorkerPath,{},undefined,false);constructor(options){this.worker.connect(options)}update(){this.worker.process?.send?.({type:rpc_exports.RpcGMCallTypes.CALL,id:this.worker.id,args:[undefined,"update"]})}exit(){this.worker.terminate()}},normalizeDevOptions=(dev)=>{if(dev===false)return false;if(dev===true||typeof dev==="undefined")return{...DEFAULT_DEV_OPTIONS};return{...DEFAULT_DEV_OPTIONS,...dev}},buildDtsModuleFederationConfig=(options)=>{const exposes={};Object.entries(options.exposes).forEach(([key,value])=>{if(value.import)exposes[key]=value.import});const remotes={};Object.entries(options.remotes).forEach(([key,remote])=>{if(!remote.entry)return;const entryGlobalName=remote.entryGlobalName?.startsWith("http")||remote.entryGlobalName?.includes(".json")?remote.name||key:remote.entryGlobalName||remote.name||key;remotes[key]=`${entryGlobalName}@${remote.entry}`});return{...options,exposes,remotes}},resolveOutputDir=(config)=>{const{outDir}=config.build;if(path$13.isAbsolute(outDir))return normalizePathForImport(path$13.relative(config.root,outDir));return outDir},ensureRuntimePlugin=(options,pluginId)=>{if(!options.runtimePlugins.some((plugin)=>{if(typeof plugin==="string")return plugin===pluginId;return plugin[0]===pluginId}))options.runtimePlugins.push(pluginId)},getExposeImportPaths=(options)=>{return Object.values(options.exposes).map((value)=>{return value.import}).filter((value)=>Boolean(value))},usesVueSfcExposes=(options)=>{return getExposeImportPaths(options).some((value)=>value.endsWith(".vue"))},resolveDtsPluginOptions=(dts,options,context)=>{if(dts===false)return false;const inferredGenerateTypesDefaults={generateAPITypes:true};if(usesVueSfcExposes(options)&&hasPackageDependency("vue-tsc",context))inferredGenerateTypesDefaults.compilerInstance="vue-tsc";if(dts===true||typeof dts==="undefined")return{generateTypes:inferredGenerateTypesDefaults};const generateTypes=dts.generateTypes;return{...dts,generateTypes:generateTypes===false?false:{...inferredGenerateTypesDefaults,...generateTypes===true||typeof generateTypes==="undefined"?{}:generateTypes}}},getBasePath2=(base)=>{if(base.startsWith("http://")||base.startsWith("https://"))return new URL(base).pathname.replace(/\/$/,"")||"/";return base.replace(/\/$/,"")||"/"},joinBaseAndAsset=(base,assetFileName)=>{const basePath=getBasePath2(base);return`${basePath==="/"?"":basePath}/${assetFileName}`.replace(/\/{2,}/g,"/")},getDevDtsAssetPaths=(options)=>{const{outputDir,publicTypesFolder,root,base}=options;return{apiFilePath:path$13.resolve(root,outputDir,`${DEV_TYPES_FOLDER}.d.ts`),apiRequestPath:joinBaseAndAsset(base,`${publicTypesFolder}.d.ts`),zipFilePath:path$13.resolve(root,outputDir,`${DEV_TYPES_FOLDER}.zip`),zipRequestPath:joinBaseAndAsset(base,`${publicTypesFolder}.zip`)}},createDevDtsAssetMiddleware=(assetPaths)=>{return(req,res,next)=>{const requestPath=req.url?.split("?")[0];const isZipRequest=requestPath===assetPaths.zipRequestPath;const isApiRequest=requestPath===assetPaths.apiRequestPath;if(!isZipRequest&&!isApiRequest){next();return}const filePath=isZipRequest?assetPaths.zipFilePath:assetPaths.apiFilePath;if(!fs4.existsSync(filePath)){res.statusCode=404;res.end();return}res.statusCode=200;res.setHeader("Content-Type",isZipRequest?"application/x-gzip":"application/typescript");if(req.method==="HEAD"){res.end();return}const stream=fs4.createReadStream(filePath);stream.on("error",()=>{if(!res.headersSent)res.statusCode=500;res.end()});res.on("close",()=>{stream.destroy()});stream.pipe(res)}},normalizeDevDtsOptions=(dts,context)=>{return normalizeOptions(isTSProject(dts,context),{generateTypes:{compileInChildProcess:true},consumeTypes:{consumeAPITypes:true},extraOptions:{},displayErrorInTerminal:typeof dts==="object"&&dts?dts.displayErrorInTerminal:undefined},"mfOptions.dts")(dts)},logDtsError=(error,dtsOptions)=>{if(dtsOptions===false)return;if(typeof dtsOptions==="object"&&dtsOptions&&dtsOptions.displayErrorInTerminal===false)return;mfError(error)};var init_pluginDts_DnEX3cp_=__esm(()=>{init_logger_DOwfTlw5();init_dtsConstants_r5OfegUr();init_dist();init_esm();init_core();DEFAULT_DEV_OPTIONS={disableLiveReload:true,disableHotTypesReload:false,disableDynamicRemoteTypeHints:false};forkDevWorkerPath=(()=>{return resolveImportPath("@module-federation/dts-plugin/dist/fork-dev-worker.js")})()});var pipeArguments=(self,args)=>{switch(args.length){case 0:return self;case 1:return args[0](self);case 2:return args[1](args[0](self));case 3:return args[2](args[1](args[0](self)));case 4:return args[3](args[2](args[1](args[0](self))));case 5:return args[4](args[3](args[2](args[1](args[0](self)))));case 6:return args[5](args[4](args[3](args[2](args[1](args[0](self))))));case 7:return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))));case 8:return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))));case 9:return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))));default:{let ret=self;for(let i=0,len=args.length;i<len;i++){ret=args[i](ret)}return ret}}};var Prototype={pipe(){return pipeArguments(this,arguments)}};var Class=function(){function PipeableBase(){}PipeableBase.prototype=Prototype;return PipeableBase}();var dual=function(arity,body){if(typeof arity==="function"){return function(){return arity(arguments)?body.apply(this,arguments):(self)=>body(self,...arguments)}}switch(arity){case 0:case 1:throw new RangeError(`Invalid arity ${arity}`);case 2:return function(a,b){if(arguments.length>=2){return body(a,b)}return function(self){return body(self,a)}};case 3:return function(a,b,c){if(arguments.length>=3){return body(a,b,c)}return function(self){return body(self,a,b)}};default:return function(){if(arguments.length>=arity){return body.apply(this,arguments)}const args=arguments;return function(self){return body(self,...args)}}}};var identity=(a)=>a;var constant=(value)=>()=>value;var constTrue=constant(true);var constFalse=constant(false);var constUndefined=constant(undefined);var constVoid=constUndefined;function pipe(a,...args){return pipeArguments(a,args)}function flow(ab,bc,cd,de,ef,fg,gh,hi,ij){switch(arguments.length){case 1:return ab;case 2:return function(){return bc(ab.apply(this,arguments))};case 3:return function(){return cd(bc(ab.apply(this,arguments)))};case 4:return function(){return de(cd(bc(ab.apply(this,arguments))))};case 5:return function(){return ef(de(cd(bc(ab.apply(this,arguments)))))};case 6:return function(){return fg(ef(de(cd(bc(ab.apply(this,arguments))))))};case 7:return function(){return gh(fg(ef(de(cd(bc(ab.apply(this,arguments)))))))};case 8:return function(){return hi(gh(fg(ef(de(cd(bc(ab.apply(this,arguments))))))))};case 9:return function(){return ij(hi(gh(fg(ef(de(cd(bc(ab.apply(this,arguments)))))))))}}return}function memoize(f){const cache=new WeakMap;return(a)=>{const cached=cache.get(a);if(cached!==undefined)return cached;const result=f(a);cache.set(a,result);return result}}function memoizeIdempotent(f){const cache=new WeakMap;return(a)=>{const cached=cache.get(a);if(cached!==undefined)return cached;const result=f(a);cache.set(a,result);if(result!==a){cache.set(result,result)}return result}}var make=(isEquivalent)=>(self,that)=>self===that||isEquivalent(self,that);var getAllObjectKeys=(obj)=>{const keys=new Set(Reflect.ownKeys(obj));if(obj.constructor===Object)return keys;if(obj instanceof Error){keys.delete("stack")}const proto=Object.getPrototypeOf(obj);let current=proto;while(current!==null&&current!==Object.prototype){const ownKeys=Reflect.ownKeys(current);for(let i=0;i<ownKeys.length;i++){keys.add(ownKeys[i])}current=Object.getPrototypeOf(current)}if(keys.has("constructor")&&typeof obj.constructor==="function"&&proto===obj.constructor.prototype){keys.delete("constructor")}return keys};var byReferenceInstances=new WeakSet;var viewBytes=(view)=>new Uint8Array(view.buffer,view.byteOffset,view.byteLength);var isArrayBufferLike=(u)=>u instanceof ArrayBuffer||typeof SharedArrayBuffer!=="undefined"&&u instanceof SharedArrayBuffer;var bufferBytes=(buffer)=>{try{return new Uint8Array(buffer)}catch{return}};var backEdges=0;var addBackEdge=()=>{backEdges++};function isString(input){return typeof input==="string"}function isNumber(input){return typeof input==="number"}function isBoolean(input){return typeof input==="boolean"}function isSymbol(input){return typeof input==="symbol"}function isPropertyKey(u){return isString(u)||isNumber(u)||isSymbol(u)}function isFunction(input){return typeof input==="function"}function isNotUndefined(input){return input!==undefined}function isNotNullish(input){return input!=null}function isUnknown(_){return true}function isObject(input){return typeof input==="object"&&input!==null&&!Array.isArray(input)}function isObjectKeyword(input){return typeof input==="object"&&input!==null||isFunction(input)}var hasProperty=dual(2,(self,property)=>isObjectKeyword(self)&&(property in self));var isTagged=dual(2,(self,tag)=>hasProperty(self,"_tag")&&self["_tag"]===tag);function isIterable(input){return hasProperty(input,Symbol.iterator)||isString(input)}var symbol="~effect/Hash";var hash=(self)=>{switch(typeof self){case"number":return number(self);case"bigint":return string(self.toString(10));case"string":return string(self);case"function":case"object":{if(self===null){break}else if(self instanceof Date){if(Number.isNaN(self.getTime())){return string("Invalid Date")}return string(self.toISOString())}else if(self instanceof RegExp){return string(self.toString())}else{if(byReferenceInstances.has(self)){return random(self)}const cached=hashCache.get(self);if(cached!==undefined){return cached}if(visitedObjects.has(self)){addBackEdge();return string("[Circular]")}visitedObjects.add(self);const seen=backEdges;let h;try{if(symbol in self){h=self[symbol]()}else if(typeof self==="function"){h=random(self)}else if(isArrayBufferLike(self)){const bytes=bufferBytes(self);h=bytes===undefined?random(self):array(bytes)}else if(self instanceof DataView){h=array(viewBytes(self))}else if(Array.isArray(self)||ArrayBuffer.isView(self)){h=array(self)}else if(self instanceof Map){h=hashMap(self)}else if(self instanceof Set){h=hashSet(self)}else{h=structure(self)}}finally{visitedObjects.delete(self)}if(seen===backEdges){hashCache.set(self,h)}return h}}}return optimize(mix(string(String(self))))};var random=(self)=>{if(!randomHashCache.has(self)){randomHashCache.set(self,optimize(Math.random()*4294967296|0))}return randomHashCache.get(self)};var mix=(h)=>{h^=h>>>16;h=Math.imul(h,2246822507);h^=h>>>13;h=Math.imul(h,3266489909);return h^h>>>16};var combine=dual(2,(self,b)=>mix(Math.imul(self,2654435761)+Math.imul(b,2246822507)));var optimize=(n)=>n&3221225471|n>>>1&1073741824;var float64=new DataView(new ArrayBuffer(8));var number=(n)=>{const h=n|0;if(h===n){return optimize(h)}float64.setFloat64(0,n!==n?NaN:n);return optimize(combine(float64.getInt32(0),float64.getInt32(4)))};var string=(str)=>{let h=5381,i=str.length;while(i){h=h*33^str.charCodeAt(--i)}return optimize(h)};var structureKeys=(o,keys)=>{let h=12289;for(const key of keys){h^=combine(hash(key),hash(o[key]))}return optimize(h)};var structure=(o)=>structureKeys(o,getAllObjectKeys(o));var unordered=(seed,f)=>(iter)=>{let h=seed;for(const element of iter){h^=f(element)}return optimize(h)};var array=(arr)=>{let h=6151;for(const element of arr){h=combine(h,hash(element))}return optimize(h)};var hashMap=unordered(string("Map"),([k,v])=>combine(hash(k),hash(v)));var setSeed=string("Set");var hashSet=unordered(setSeed,(element)=>combine(setSeed,hash(element)));var randomHashCache=new WeakMap;var hashCache=new WeakMap;var visitedObjects=new WeakSet;var symbol2="~effect/Equal";function equals(){if(arguments.length===1){return(self)=>compareBoth(self,arguments[0])}return compareBoth(arguments[0],arguments[1])}function compareBoth(self,that){if(self===that)return true;if(self==null||that==null)return false;const selfType=typeof self;if(selfType!==typeof that){return false}if(selfType==="number"&&self!==self&&that!==that){return true}if(selfType!=="object"&&selfType!=="function"){return false}if(byReferenceInstances.has(self)||byReferenceInstances.has(that)){return false}return compareObjects(self,that)}function compareObjects(self,that){const depth=pathLeft.length;for(let i=depth;i-- >0;){if(pathLeft[i]===self&&pathRight[i]===that)return true}if(depth)return compareOnPath(self,that);let known=results.get(self);if(!known)results.set(self,known=new WeakMap);let result=known.get(that);if(result===undefined)known.set(that,result=compareOnPath(self,that));return result}function compareOnPath(self,that){pathLeft.push(self);pathRight.push(that);try{return compareStructure(self,that)}finally{pathLeft.pop();pathRight.pop()}}var pathLeft=[];var pathRight=[];var results=new WeakMap;function compareStructure(self,that){if(hash(self)!==hash(that)){return false}else if(self instanceof Date){if(!(that instanceof Date))return false;const selfTime=self.getTime();const thatTime=that.getTime();return selfTime===thatTime||Number.isNaN(selfTime)&&Number.isNaN(thatTime)}else if(self instanceof RegExp){return that instanceof RegExp&&self.toString()===that.toString()}const bothEquals=isEqual(self);if(bothEquals!==isEqual(that)||typeof self==="function"&&!bothEquals){return false}else if(bothEquals){return self[symbol2](that)}else if(Array.isArray(self)){if(!Array.isArray(that)||self.length!==that.length){return false}return compareArrays(self,that)}else if(isArrayBufferLike(self)){if(!isArrayBufferLike(that)||self instanceof ArrayBuffer!==that instanceof ArrayBuffer){return false}const selfBytes=bufferBytes(self);const thatBytes=bufferBytes(that);return selfBytes!==undefined&&thatBytes!==undefined&&compareTypedArrays(selfBytes,thatBytes)}else if(ArrayBuffer.isView(self)){const selfIsDataView=self instanceof DataView;if(!ArrayBuffer.isView(that)||self.byteLength!==that.byteLength||selfIsDataView!==that instanceof DataView){return false}if(selfIsDataView){return compareTypedArrays(viewBytes(self),viewBytes(that))}return compareTypedArrays(self,that)}else if(self instanceof Map){if(!(that instanceof Map)||self.size!==that.size){return false}return compareHashed(self,that,entryHash,equalEntries)}else if(self instanceof Set){if(!(that instanceof Set)||self.size!==that.size){return false}return compareHashed(self,that,hash,compareBoth)}return compareRecords(self,that)}function compareArrays(self,that){for(let i=0;i<self.length;i++){if(!compareBoth(self[i],that[i])){return false}}return true}function compareTypedArrays(self,that){if(self.length!==that.length){return false}for(let i=0;i<self.length;i++){if(self[i]!==that[i]){return false}}return true}function compareRecords(self,that){const selfKeys=getAllObjectKeys(self);const thatKeys=getAllObjectKeys(that);if(selfKeys.size!==thatKeys.size){return false}for(const key of selfKeys){if(!thatKeys.has(key)||!compareBoth(self[key],that[key])){return false}}return true}function compareHashed(self,that,hashOf,equivalent){const groups=new Map;let remaining=0;for(const item of that){const h=hashOf(item);const group=groups.get(h);if(group)group.push(item);else groups.set(h,[item]);remaining++}outer:for(const item of self){const group=groups.get(hashOf(item));if(group){for(let i=0;i<group.length;i++){if(equivalent(item,group[i])){group[i]=group[group.length-1];group.pop();remaining--;continue outer}}}return false}return remaining===0}var entryHash=(entry)=>hash(entry[0]);var equalEntries=(self,that)=>compareBoth(self[0],that[0])&&compareBoth(self[1],that[1]);var isEqual=(u)=>hasProperty(u,symbol2);var symbolRedactable=Symbol.for("~effect/Redactable");var isRedactable=(u)=>hasProperty(u,symbolRedactable);function redact(u){if(isRedactable(u))return getRedacted(u);return u}function getRedacted(redactable){return redactable[symbolRedactable](globalThis[currentFiberTypeId]?.context??emptyContext)}var currentFiberTypeId="~effect/Fiber/currentFiber";var emptyMap=new Map;var emptyContext={"~effect/Context":{},base:emptyMap,depth:0,mapUnsafe:emptyMap,pipe(){return pipeArguments(this,arguments)}};function format(input,options){const space=options?.space??0;const ancestors=new WeakSet;const gap=!space?"":typeof space==="number"?" ".repeat(space):space;const ind=(d)=>gap.repeat(d);const wrap=(v,body)=>{const ctor=v?.constructor;return ctor&&ctor!==Object.prototype.constructor&&ctor.name?`${ctor.name}(${body})`:body};const ownKeys=(o)=>{try{return Reflect.ownKeys(o)}catch{return["[ownKeys threw]"]}};function recur(v,d=0){try{return recurUnsafe(v,d)}catch{if(typeof v==="object"&&v!==null||typeof v==="function")ancestors.delete(v);return"[inspection threw]"}}function recurUnsafe(v,d=0){if(typeof v==="string")return JSON.stringify(v);if(typeof v==="number"||v==null||typeof v==="boolean"||typeof v==="symbol")return String(v);if(typeof v==="bigint")return String(v)+"n";if(typeof v==="object"||typeof v==="function"){if(ancestors.has(v))return CIRCULAR;ancestors.add(v);let output;if(symbolRedactable in v){output=recur(getRedacted(v),d)}else if(Array.isArray(v)){output=!gap||v.length<=1?`[${v.map((x)=>recur(x,d)).join(",")}]`:`[
215
215
  ${ind(d+1)}${v.map((x)=>recur(x,d+1)).join(`,
216
216
  `+ind(d+1))}
217
217
  ${ind(d)}]`}else if(v instanceof Date){output=formatDate(v)}else if(!options?.ignoreToString&&hasProperty(v,"toString")&&typeof v["toString"]==="function"&&v["toString"]!==Object.prototype.toString&&v["toString"]!==Array.prototype.toString){const s=safeToString(v);output=v instanceof Error&&v.cause!==undefined?`${s} (cause: ${recur(v.cause,d)})`:s}else if(Symbol.iterator in v){output=`${v.constructor.name}(${recur(Array.from(v),d)})`}else{const keys=ownKeys(v);if(!gap||keys.length<=1){const body=`{${keys.map((k)=>`${formatPropertyKey(k)}:${recur(safeGet(v,k),d)}`).join(",")}}`;output=wrap(v,body)}else{const body=`{
218
218
  ${keys.map((k)=>`${ind(d+1)}${formatPropertyKey(k)}: ${recur(safeGet(v,k),d+1)}`).join(`,
219
219
  `)}
220
- ${ind(d)}}`;output=wrap(v,body)}}ancestors.delete(v);return output}return String(v)}return recur(input,0)}var CIRCULAR="[Circular]";function formatPropertyKey(name){return typeof name==="string"?JSON.stringify(name):String(name)}function formatPath(path){return path.map((key)=>`[${formatPropertyKey(key)}]`).join("")}function formatDate(date){try{return date.toISOString()}catch{return"Invalid Date"}}function safeToString(input){try{const s=input.toString();return typeof s==="string"?s:String(s)}catch{return"[toString threw]"}}function safeGet(input,key){try{return input[key]}catch{return"[property access threw]"}}function formatJson(input,options){const ancestors=[];return JSON.stringify(input,function(key,value){const original=Object.getOwnPropertyDescriptor(this,key)?.value;const redacted=hasProperty(original,symbolRedactable)?redact(original):redact(value);if(typeof redacted==="bigint"){return format(redacted)}if(typeof redacted!=="object"||redacted===null){return redacted}const current=redacted instanceof Error&&!hasProperty(redacted,"toJSON")?{...redacted,name:redacted.name,message:redacted.message}:redacted;while(ancestors.length>0&&ancestors[ancestors.length-1]!==this){ancestors.pop()}if(ancestors.includes(redacted)){return}ancestors.push(redacted);if(current!==redacted){ancestors.push(current)}return current},options?.space)??"null"}var NodeInspectSymbol=Symbol.for("nodejs.util.inspect.custom");var toJson=(input)=>{try{input=redact(input);if(hasProperty(input,"toJSON")&&isFunction(input["toJSON"])&&input["toJSON"].length===0){return input.toJSON()}else if(Array.isArray(input)){return input.map(toJson)}return input}catch{return"[toJSON threw]"}};var toStringUnknown=(u,whitespace=2)=>{if(typeof u==="string"){return u}try{return typeof u==="object"?formatJson(u,{space:whitespace}):format(u,{space:whitespace})}catch{return String(u)}};var BaseProto={toJSON(){return toJson(this)},[NodeInspectSymbol](){return this.toJSON()},toString(){return format(this.toJSON())}};var isStackTraceLimitWritable=()=>{const desc=Object.getOwnPropertyDescriptor(Error,"stackTraceLimit");if(desc===undefined){return Object.isExtensible(Error)}return Object.hasOwn(desc,"writable")?desc.writable===true:desc.set!==undefined};var canWriteStackTraceLimit=isStackTraceLimitWritable();var getStackTraceLimit=()=>Error.stackTraceLimit;var setStackTraceLimit=(value)=>{if(canWriteStackTraceLimit){Error.stackTraceLimit=value}};class SingleShotGen{constructor(self){this.value=self;this.done=false}next(a){if(this.done){this.value=a;return this}this.done=true;return{value:this.value,done:false}}}var pickInternalCall=()=>{const InternalTypeId="~effect/Utils/internal";const standard={[InternalTypeId]:(body)=>{return body()}};const forced={[InternalTypeId]:(body)=>{try{return body()}finally{}}};const isNotOptimizedAway=getStackTraceLimit()!==0&&standard[InternalTypeId](()=>new Error().stack)?.includes(InternalTypeId)===true;return isNotOptimizedAway?standard[InternalTypeId]:forced[InternalTypeId]};var internalCall=pickInternalCall();function assignProperty(self,key,value){if(key==="__proto__"){Object.defineProperty(self,key,{value,writable:true,enumerable:true,configurable:true})}else{self[key]=value}}function assignProperties(self,source){for(const key of Reflect.ownKeys(source)){if(Object.prototype.propertyIsEnumerable.call(source,key)){assignProperty(self,key,source[key])}}}var EffectTypeId=`~effect/Effect`;var ExitTypeId=`~effect/Exit`;var effectVariance={_A:identity,_E:identity,_R:identity};var identifier=`${EffectTypeId}/identifier`;var args=`${EffectTypeId}/args`;var evaluate=`${EffectTypeId}/evaluate`;var contA=`${EffectTypeId}/successCont`;var contE=`${EffectTypeId}/failureCont`;var contAll=`${EffectTypeId}/ensureCont`;var Yield=Symbol.for("effect/Effect/Yield");var PipeInspectableProto={pipe(){return pipeArguments(this,arguments)},toJSON(){return{...this}},toString(){return format(this.toJSON(),{ignoreToString:true,space:2})},[NodeInspectSymbol](){return this.toJSON()}};var StructuralProto={[symbol](){return structureKeys(this,Object.keys(this))},[symbol2](that){const selfKeys=Object.keys(this);const thatKeys=Object.keys(that);if(selfKeys.length!==thatKeys.length)return false;for(let i=0;i<selfKeys.length;i++){if(selfKeys[i]!==thatKeys[i]||!equals(this[selfKeys[i]],that[selfKeys[i]])){return false}}return true}};var EffectProto={[EffectTypeId]:effectVariance,...PipeInspectableProto,[Symbol.iterator](){return new SingleShotGen(this)},toJSON(){return{_id:"Effect",op:this[identifier],...args in this?{args:this[args]}:undefined}}};var isEffect=(u)=>hasProperty(u,EffectTypeId);var isExit=(u)=>hasProperty(u,ExitTypeId);var CauseTypeId="~effect/Cause";var CauseReasonTypeId="~effect/Cause/Reason";var isCause=(self)=>hasProperty(self,CauseTypeId);class CauseImpl{constructor(failures){this[CauseTypeId]=CauseTypeId;this.reasons=failures}pipe(){return pipeArguments(this,arguments)}toJSON(){return{_id:"Cause",failures:this.reasons.map((f)=>f.toJSON())}}toString(){return`Cause(${format(this.reasons)})`}[NodeInspectSymbol](){return this.toJSON()}[symbol2](that){return isCause(that)&&this.reasons.length===that.reasons.length&&this.reasons.every((e,i)=>equals(e,that.reasons[i]))}[symbol](){return array(this.reasons)}}var annotationsMap=new WeakMap;class ReasonBase{[CauseReasonTypeId];annotations;_tag;constructor(_tag,annotations,originalError){this[CauseReasonTypeId]=CauseReasonTypeId;this._tag=_tag;if(annotations!==constEmptyAnnotations&&typeof originalError==="object"&&originalError!==null&&annotations.size>0){const prevAnnotations=annotationsMap.get(originalError);if(prevAnnotations){annotations=new Map([...prevAnnotations,...annotations])}annotationsMap.set(originalError,annotations)}this.annotations=annotations}annotate(annotations,options){if(annotations.mapUnsafe.size===0)return this;const newAnnotations=new Map(this.annotations);annotations.mapUnsafe.forEach((value,key)=>{if(options?.overwrite!==true&&newAnnotations.has(key))return;newAnnotations.set(key,value)});const self=Object.assign(Object.create(Object.getPrototypeOf(this)),this);self.annotations=newAnnotations;return self}pipe(){return pipeArguments(this,arguments)}toString(){return format(this)}[NodeInspectSymbol](){return this.toString()}}var constEmptyAnnotations=new Map;class Fail extends ReasonBase{constructor(error,annotations=constEmptyAnnotations){super("Fail",annotations,error);this.error=error}toString(){return`Fail(${format(this.error)})`}toJSON(){return{_tag:"Fail",error:this.error}}[symbol2](that){return isFailReason(that)&&equals(this.error,that.error)&&equals(this.annotations,that.annotations)}[symbol](){return combine(string(this._tag))(combine(hash(this.error))(hash(this.annotations)))}}var causeFromReasons=(reasons)=>new CauseImpl(reasons);var dedupeReasons=(self,that)=>{const buckets=new Map;const out=[];for(const reason of self.concat(that)){const hash2=hash(reason);const bucket=buckets.get(hash2);if(bucket===undefined){buckets.set(hash2,[reason])}else if(bucket.some((previous)=>equals(previous,reason))){continue}else{bucket.push(reason)}out.push(reason)}return out};var causeCombine=dual(2,(self,that)=>{if(self.reasons.length===0){return that}else if(that.reasons.length===0){return self}const newCause=new CauseImpl(dedupeReasons(self.reasons,that.reasons));return equals(self,newCause)?self:newCause});var causeEmpty=new CauseImpl([]);var causeFail=(error)=>new CauseImpl([new Fail(error)]);class Die extends ReasonBase{constructor(defect,annotations=constEmptyAnnotations){super("Die",annotations,defect);this.defect=defect}toString(){return`Die(${format(this.defect)})`}toJSON(){return{_tag:"Die",defect:this.defect}}[symbol2](that){return isDieReason(that)&&equals(this.defect,that.defect)&&equals(this.annotations,that.annotations)}[symbol](){return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations)))}}var causeDie=(defect)=>new CauseImpl([new Die(defect)]);var causeAnnotate=dual((args)=>isCause(args[0]),(self,annotations,options)=>{if(annotations.mapUnsafe.size===0)return self;return new CauseImpl(self.reasons.map((f)=>f.annotate(annotations,options)))});var isFailReason=(self)=>self._tag==="Fail";var isDieReason=(self)=>self._tag==="Die";var isInterruptReason=(self)=>self._tag==="Interrupt";function defaultEvaluate(_fiber){return exitDie(`Effect.evaluate: Not implemented`)}var makePrimitiveProto=(options)=>({...EffectProto,[identifier]:options.op,[evaluate]:options[evaluate]??defaultEvaluate,[contA]:options[contA],[contE]:options[contE],[contAll]:options[contAll]});var makePrimitive=(options)=>{const Proto=makePrimitiveProto(options);const PrimitiveImpl=function(value){this[args]=value};PrimitiveImpl.prototype=Proto;return function(value){return new PrimitiveImpl(value)}};var makeExit=(options)=>{const Proto={[ExitTypeId]:ExitTypeId,_tag:options.op,get[options.prop](){return this[args]},...makePrimitiveProto(options),toString(){return`${options.op}(${format(this[args])})`},toJSON(){return{_id:"Exit",_tag:options.op,[options.prop]:this[args]}},[symbol2](that){return isExit(that)&&that._tag===this._tag&&equals(this[args],that[args])},[symbol](){return combine(string(options.op),hash(this[args]))}};const ExitPrimitive=function(value){this[args]=value};ExitPrimitive.prototype=Proto;return function(value){return new ExitPrimitive(value)}};var exitSucceed=makeExit({op:"Success",prop:"value",[evaluate](fiber){const cont=fiber.getCont(contA);return cont?cont[contA](this[args],fiber,this):fiber.yieldWith(this)}});var StackTraceKey={key:"effect/Cause/StackTrace"};var InterruptorStackTrace={key:"effect/Cause/InterruptorStackTrace"};var exitFailCause=makeExit({op:"Failure",prop:"cause",[evaluate](fiber){let cause=this[args];let annotated=false;if(fiber.cache.stackFrame){cause=causeAnnotate(cause,{mapUnsafe:new Map([[StackTraceKey.key,fiber.cache.stackFrame]])});annotated=true}let cont=fiber.getCont(contE);const interruptedCause=fiber._interruptedCause;if(interruptedCause&&fiber.interruptible){let skippedHandler=false;while(cont&&fiber.interruptible){skippedHandler||=identifier in cont;cont=fiber.getCont(contE)}if(skippedHandler){cause=causeFromReasons(cause.reasons.filter((reason)=>reason._tag!=="Fail"))}cause=causeCombine(cause,interruptedCause);annotated=true}return cont?cont[contE](cause,fiber,annotated?undefined:this):fiber.yieldWith(annotated?exitFailCause(cause):this)}});var exitFail=(e)=>exitFailCause(causeFail(e));var exitDie=(defect)=>exitFailCause(causeDie(defect));var withFiber=makePrimitive({op:"WithFiber",[evaluate](fiber){return this[args](fiber)}});var withFiberSucceed=makePrimitive({op:"WithFiberSucceed",[evaluate](fiber){const value=this[args](fiber);const cont=fiber.getCont(contA);return cont?cont[contA](value,fiber):fiber.yieldWith(exitSucceed(value))}});var YieldableError=function(){class YieldableError extends globalThis.Error{}const proto=makePrimitiveProto({op:"YieldableError",[evaluate](){return exitFail(this)}});delete proto.toString;Object.assign(YieldableError.prototype,proto);return YieldableError}();var Error2=function(){const plainArgsSymbol=Symbol.for("effect/Data/Error/plainArgs");return class Base extends YieldableError{constructor(args){super(args?.message,args?.cause?{cause:args.cause}:undefined);if(args){assignProperties(this,args);Object.defineProperty(this,plainArgsSymbol,{value:args,enumerable:false})}}toJSON(){return{...this[plainArgsSymbol],...this}}}}();var TaggedError=(tag)=>{class Base extends Error2{_tag=tag}Base.prototype.name=tag;return Base};var DoneTypeId="~effect/Cause/Done";var isDone=(u)=>hasProperty(u,DoneTypeId);var DoneVoid={[DoneTypeId]:DoneTypeId,_tag:"Done",value:undefined};var Done=(value)=>{if(value===undefined)return DoneVoid;return{[DoneTypeId]:DoneTypeId,_tag:"Done",value}};var doneVoid=exitFail(DoneVoid);var done=(value)=>{if(value===undefined)return doneVoid;return exitFail(Done(value))};var TypeId="~effect/Option";var CommonProto={[TypeId]:{_A:(_)=>_},...PipeInspectableProto,[Symbol.iterator](){return new SingleShotGen(this)}};var SomeProto=Object.defineProperty(Object.assign(Object.create(CommonProto),{_tag:"Some",_op:"Some",[symbol2](that){return isOption(that)&&isSome(that)&&equals(this.value,that.value)},[symbol](){return combine(hash(this._tag))(hash(this.value))},toString(){return`some(${format(this.value)})`},toJSON(){return{_id:"Option",_tag:this._tag,value:toJson(this.value)}}}),"valueOrUndefined",{get(){return this.value}});var NoneHash=hash("None");var NoneProto=Object.assign(Object.create(CommonProto),{_tag:"None",_op:"None",valueOrUndefined:undefined,[symbol2](that){return isOption(that)&&isNone(that)},[symbol](){return NoneHash},toString(){return`none()`},toJSON(){return{_id:"Option",_tag:this._tag}}});var isOption=(input)=>hasProperty(input,TypeId);var isNone=(fa)=>fa._tag==="None";var isSome=(fa)=>fa._tag==="Some";var none=Object.create(NoneProto);var SomeImpl=function(value){this.value=value};SomeImpl.prototype=SomeProto;var some=(value)=>new SomeImpl(value);var TypeId2="~effect/Result";var CommonProto2={[TypeId2]:{_A:(_)=>_,_E:(_)=>_},...PipeInspectableProto,[Symbol.iterator](){return new SingleShotGen(this)}};var SuccessProto=Object.assign(Object.create(CommonProto2),{_tag:"Success",_op:"Success",[symbol2](that){return isResult(that)&&isSuccess(that)&&equals(this.success,that.success)},[symbol](){return combine(hash(this._tag))(hash(this.success))},toString(){return`success(${format(this.success)})`},toJSON(){return{_id:"Result",_tag:this._tag,value:toJson(this.success)}}});var FailureProto=Object.assign(Object.create(CommonProto2),{_tag:"Failure",_op:"Failure",[symbol2](that){return isResult(that)&&isFailure(that)&&equals(this.failure,that.failure)},[symbol](){return combine(hash(this._tag))(hash(this.failure))},toString(){return`failure(${format(this.failure)})`},toJSON(){return{_id:"Result",_tag:this._tag,failure:toJson(this.failure)}}});var isResult=(input)=>hasProperty(input,TypeId2);var isFailure=(result)=>result._tag==="Failure";var isSuccess=(result)=>result._tag==="Success";var FailureImpl=function(failure){this.failure=failure};FailureImpl.prototype=FailureProto;var fail=(failure)=>new FailureImpl(failure);var SuccessImpl=function(success){this.success=success};SuccessImpl.prototype=SuccessProto;var succeed=(success)=>new SuccessImpl(success);function make2(compare){return(self,that)=>self===that?0:compare(self,that)}var String2=make2((self,that)=>self<that?-1:1);var Number2=make2((self,that)=>{if(globalThis.Number.isNaN(self)&&globalThis.Number.isNaN(that))return 0;if(globalThis.Number.isNaN(self))return-1;if(globalThis.Number.isNaN(that))return 1;return self<that?-1:1});var mapInput=dual(2,(self,f)=>make2((b1,b2)=>self(f(b1),f(b2))));var isGreaterThan=(O)=>dual(2,(self,that)=>O(self,that)===1);var none2=()=>none;var some2=some;var isNone2=isNone;var isSome2=isSome;var match=dual(2,(self,{onNone,onSome})=>isNone2(self)?onNone():onSome(self.value));var getOrElse=dual(2,(self,onNone)=>isNone2(self)?onNone():self.value);var fromNullishOr=(a)=>a==null?none2():some2(a);var getOrUndefined=getOrElse(constUndefined);var flatMap=dual(2,(self,f)=>isNone2(self)?none2():f(self.value));var BigInt2=globalThis.BigInt;var toNumber=(b)=>{if(b>BigInt2(Number.MAX_SAFE_INTEGER)||b<BigInt2(Number.MIN_SAFE_INTEGER)){return none2()}return some2(Number(b))};var bigint0=BigInt(0);var bigint1=BigInt(1);var decimalBase=BigInt(1000);var binaryBase=BigInt(1024);var decimalUnits=[{symbol:"B",factor:bigint1,names:["B","byte","bytes"]},{symbol:"kB",factor:decimalBase,names:["kB","kilobyte","kilobytes"]},{symbol:"MB",factor:decimalBase**BigInt(2),names:["MB","megabyte","megabytes"]},{symbol:"GB",factor:decimalBase**BigInt(3),names:["GB","gigabyte","gigabytes"]},{symbol:"TB",factor:decimalBase**BigInt(4),names:["TB","terabyte","terabytes"]},{symbol:"PB",factor:decimalBase**BigInt(5),names:["PB","petabyte","petabytes"]},{symbol:"EB",factor:decimalBase**BigInt(6),names:["EB","exabyte","exabytes"]},{symbol:"ZB",factor:decimalBase**BigInt(7),names:["ZB","zettabyte","zettabytes"]},{symbol:"YB",factor:decimalBase**BigInt(8),names:["YB","yottabyte","yottabytes"]},{symbol:"RB",factor:decimalBase**BigInt(9),names:["RB","ronnabyte","ronnabytes"]},{symbol:"QB",factor:decimalBase**BigInt(10),names:["QB","quettabyte","quettabytes"]}];var binaryUnits=[decimalUnits[0],{symbol:"KiB",factor:binaryBase,names:["KiB","kibibyte","kibibytes"]},{symbol:"MiB",factor:binaryBase**BigInt(2),names:["MiB","mebibyte","mebibytes"]},{symbol:"GiB",factor:binaryBase**BigInt(3),names:["GiB","gibibyte","gibibytes"]},{symbol:"TiB",factor:binaryBase**BigInt(4),names:["TiB","tebibyte","tebibytes"]},{symbol:"PiB",factor:binaryBase**BigInt(5),names:["PiB","pebibyte","pebibytes"]},{symbol:"EiB",factor:binaryBase**BigInt(6),names:["EiB","exbibyte","exbibytes"]},{symbol:"ZiB",factor:binaryBase**BigInt(7),names:["ZiB","zebibyte","zebibytes"]},{symbol:"YiB",factor:binaryBase**BigInt(8),names:["YiB","yobibyte","yobibytes"]}];var allUnits=[...decimalUnits,...binaryUnits.slice(1)];var unitsByName=new Map(allUnits.flatMap((unit)=>unit.names.map((name)=>[name,unit])));var make3=(value)=>value;var invalid=(message)=>{throw new Error(`Invalid ByteSize: ${message}`)};var fromNumber=(input)=>{if(!Number.isSafeInteger(input)||input<0){return invalid(`expected a non-negative safe integer, received ${input}`)}return make3(BigInt(input))};var fromStringUnsafe=(input)=>{const match=/^\s*(\d+)(?:\.(\d+))?\s*([A-Za-z]+)\s*$/.exec(input);if(match===null)return invalid(`unsupported syntax ${JSON.stringify(input)}`);const unit=unitsByName.get(match[3]);if(unit===undefined)return invalid(`unsupported unit ${JSON.stringify(match[3])}`);const fraction=match[2]??"";const scale=BigInt(10)**BigInt(fraction.length);const numerator=BigInt(match[1]+fraction)*unit.factor;if(numerator%scale!==bigint0){return invalid(`${JSON.stringify(input)} does not represent an integral number of bytes`)}return make3(numerator/scale)};var fromInputUnsafe=(input)=>{switch(typeof input){case"bigint":if(input<bigint0)return invalid(`expected a non-negative bigint, received ${input}`);return make3(input);case"number":return fromNumber(input);case"string":return fromStringUnsafe(input)}return invalid(`unsupported input ${input}`)};var bytes=(value)=>typeof value==="bigint"?fromInputUnsafe(value):fromNumber(value);var Prototype2=(options)=>makePrimitiveProto({op:options.label,[evaluate]:options.evaluate});var ServiceTypeId="~effect/Context/Service";var Service=function(){function KeyClass(){}const self=KeyClass;Object.setPrototypeOf(self,ServiceProto);const init=(key,options)=>{self.key=key;if(options?.defaultValue){self[ReferenceTypeId]=ReferenceTypeId;self.defaultValue=options.defaultValue}if(options?.make){self.make=options.make}if(options?.fiberCached){cacheKeys.add(key)}return self};return arguments.length>0?init(arguments[0],arguments[1]):init};var ServiceProto={[ServiceTypeId]:ServiceTypeId,...Prototype2({label:"Service",evaluate(fiber){return exitSucceed(get(fiber.context,this))}}),toJSON(){return{_id:"Service",key:this.key}},of(self){return self},context(self){return make4(this,self)},use(f){return withFiber((fiber)=>f(get(fiber.context,this)))},useSync(f){return withFiber((fiber)=>exitSucceed(f(get(fiber.context,this))))}};var cacheKeys=new Set;var ReferenceTypeId="~effect/Context/Reference";var TypeId3="~effect/Context";var MaxDepth=8;var FlattenAfterBaseHits=8;var makeImpl=(cacheRoot,base,overlay,depth)=>{const self=Object.create(Proto);self.cacheRoot=cacheRoot??self;self.base=base;self.overlay=overlay;self.depth=depth;self._flat=undefined;self.baseHits=0;return self};var applyOverlays=(map,overlay)=>{if(!overlay)return;applyOverlays(map,overlay.parent);map.set(overlay.key,overlay.value)};var flatten=(self)=>{if(self._flat)return self._flat;if(!self.overlay)return self._flat=self.base;const map=new Map(self.base);applyOverlays(map,self.overlay);return self._flat=map};var withFlat=(self,f)=>{const map=new Map(self.mapUnsafe);f(map);return makeUnsafe(map)};var notFound=Symbol();var lookup=(self,key)=>{const impl=self;for(let overlay=impl.overlay;overlay;overlay=overlay.parent){if(overlay.key===key)return overlay.value}const value=impl.base.get(key);if(value===undefined&&!impl.base.has(key))return notFound;if(impl.overlay&&++impl.baseHits>=impl.base.size&&impl.baseHits>=FlattenAfterBaseHits){impl.base=flatten(impl);impl.overlay=undefined;impl.depth=0}return value};var makeUnsafe=(mapUnsafe)=>makeImpl(undefined,mapUnsafe,undefined,0);var Proto={get mapUnsafe(){return flatten(this)},...PipeInspectableProto,[TypeId3]:{_Services:(_)=>_},toJSON(){return{_id:"Context",services:Array.from(this.mapUnsafe).map(([key,value])=>({key,value}))}},[symbol2](that){if(!isContext(that))return false;const self=this.mapUnsafe;const other=that.mapUnsafe;if(self.size!==other.size)return false;for(const[key,value]of self){if(!other.has(key)||!equals(value,other.get(key)))return false}return true},[symbol](){return number(this.mapUnsafe.size)}};var hasSameCache=(self,that)=>self.cacheRoot===that.cacheRoot;var isContext=(u)=>hasProperty(u,TypeId3);var isReference=(u)=>!!u[ReferenceTypeId];var empty=()=>emptyContext2;var emptyContext2=makeUnsafe(new Map);var make4=(key,service)=>makeUnsafe(new Map([[key.key,service]]));var add=dual(3,(self,key,service)=>addUnsafe(self,key.key,service));var addUnsafe=(self,key,service)=>{const impl=self;const cacheRoot=cacheKeys.has(key)?undefined:impl.cacheRoot;if(impl.depth>=MaxDepth){const map=new Map(impl.mapUnsafe);map.set(key,service);return makeImpl(cacheRoot,map,undefined,0)}return makeImpl(cacheRoot,impl.base,{key,value:service,parent:impl.overlay},impl.depth+1)};var getOrUndefined2=dual(2,(self,key)=>getOrUndefinedUnsafe(self,key.key));var getOrUndefinedUnsafe=(self,key)=>{const value=lookup(self,key);return value===notFound?undefined:value};var getUnsafe=dual(2,(self,service)=>{const value=lookup(self,service.key);if(value===notFound){if(isReference(service))return getDefaultValue(service);throw serviceNotFoundError(service)}return value});var get=getUnsafe;var defaultValueCacheKey="~effect/Context/defaultValue";var getDefaultValue=(ref)=>{if(defaultValueCacheKey in ref){return ref[defaultValueCacheKey]}return ref[defaultValueCacheKey]=ref.defaultValue()};var serviceNotFoundError=(service)=>{const error=new Error(`Service not found${service.key?`: ${String(service.key)}`:""}`);if(error.stack){const lines=error.stack.split(`
220
+ ${ind(d)}}`;output=wrap(v,body)}}ancestors.delete(v);return output}return String(v)}return recur(input,0)}var CIRCULAR="[Circular]";function formatPropertyKey(name){return typeof name==="string"?JSON.stringify(name):String(name)}function formatPath(path){return path.map((key)=>`[${formatPropertyKey(key)}]`).join("")}function formatDate(date){try{return date.toISOString()}catch{return"Invalid Date"}}function safeToString(input){try{const s=input.toString();return typeof s==="string"?s:String(s)}catch{return"[toString threw]"}}function safeGet(input,key){try{return input[key]}catch{return"[property access threw]"}}function formatJson(input,options){const ancestors=[];const sources=new WeakMap;return JSON.stringify(input,function(key,value){const original=Object.getOwnPropertyDescriptor(sources.get(this)??this,key)?.value;const redacted=hasProperty(original,symbolRedactable)?redact(original):redact(value);if(typeof redacted==="bigint"){return format(redacted)}if(typeof redacted!=="object"||redacted===null){return redacted}const current=redacted instanceof Error&&!hasProperty(redacted,"toJSON")?{...redacted,name:redacted.name,message:redacted.message}:redacted;while(ancestors.length>0&&ancestors[ancestors.length-1]!==this){ancestors.pop()}if(ancestors.includes(redacted)){return}ancestors.push(redacted);if(current!==redacted){ancestors.push(current)}if(!hasGetter(current)||isJsonPrimitiveWrapper(current)){return current}const view=redactingView(current);sources.set(view,current);ancestors.push(view);return view},options?.space)??"null"}function hasGetter(object){for(const key of Object.getOwnPropertyNames(object)){if(Object.getOwnPropertyDescriptor(object,key)?.get!==undefined){return true}}return false}function redactingView(object){const view=Array.isArray(object)?[]:{};const keys=Array.isArray(object)?Array.from({length:object.length},(_,i)=>String(i)):Object.keys(object);for(const key of keys){Object.defineProperty(view,key,{enumerable:true,get:()=>{const value=Reflect.get(object,key);return Object.getOwnPropertyDescriptor(object,key)?.get!==undefined?redact(value):value}})}return view}function isJsonPrimitiveWrapper(object){for(const valueOf of[Number.prototype.valueOf,Boolean.prototype.valueOf,String.prototype.valueOf]){try{Reflect.apply(valueOf,object,[]);return true}catch{}}return false}var NodeInspectSymbol=Symbol.for("nodejs.util.inspect.custom");var toJson=(input)=>{try{input=redact(input);if(hasProperty(input,"toJSON")&&isFunction(input["toJSON"])&&input["toJSON"].length===0){return input.toJSON()}else if(Array.isArray(input)){return input.map(toJson)}return input}catch{return"[toJSON threw]"}};var toStringUnknown=(u,whitespace=2)=>{if(typeof u==="string"){return u}try{return typeof u==="object"?formatJson(u,{space:whitespace}):format(u,{space:whitespace})}catch{return String(u)}};var BaseProto={toJSON(){return toJson(this)},[NodeInspectSymbol](){return this.toJSON()},toString(){return format(this.toJSON())}};var isStackTraceLimitWritable=()=>{const desc=Object.getOwnPropertyDescriptor(Error,"stackTraceLimit");if(desc===undefined){return Object.isExtensible(Error)}return Object.hasOwn(desc,"writable")?desc.writable===true:desc.set!==undefined};var canWriteStackTraceLimit=isStackTraceLimitWritable();var getStackTraceLimit=()=>Error.stackTraceLimit;var setStackTraceLimit=(value)=>{if(canWriteStackTraceLimit){Error.stackTraceLimit=value}};class SingleShotGen{constructor(self){this.value=self;this.done=false}next(a){if(this.done){this.value=a;return this}this.done=true;return{value:this.value,done:false}}}var pickInternalCall=()=>{const InternalTypeId="~effect/Utils/internal";const standard={[InternalTypeId]:(body)=>{return body()}};const forced={[InternalTypeId]:(body)=>{try{return body()}finally{}}};const limit=getStackTraceLimit();if(limit===0)return forced[InternalTypeId];setStackTraceLimit(2);const error=standard[InternalTypeId](()=>new Error);setStackTraceLimit(limit);return error.stack?.includes(InternalTypeId)===true?standard[InternalTypeId]:forced[InternalTypeId]};var internalCall=pickInternalCall();function assignProperty(self,key,value){if(key==="__proto__"){Object.defineProperty(self,key,{value,writable:true,enumerable:true,configurable:true})}else{self[key]=value}}function assignProperties(self,source){if(!Object.hasOwn(source,"__proto__")){Object.assign(self,source);return}for(const key of Reflect.ownKeys(source)){if(Object.prototype.propertyIsEnumerable.call(source,key)){assignProperty(self,key,source[key])}}}var EffectTypeId=`~effect/Effect`;var ExitTypeId=`~effect/Exit`;var effectVariance={_A:identity,_E:identity,_R:identity};var identifier=`${EffectTypeId}/identifier`;var args=`${EffectTypeId}/args`;var evaluate=`${EffectTypeId}/evaluate`;var contA=`${EffectTypeId}/successCont`;var contE=`${EffectTypeId}/failureCont`;var contAll=`${EffectTypeId}/ensureCont`;var Yield=Symbol.for("effect/Effect/Yield");var PipeInspectableProto={pipe(){return pipeArguments(this,arguments)},toJSON(){return{...this}},toString(){return format(this.toJSON(),{ignoreToString:true,space:2})},[NodeInspectSymbol](){return this.toJSON()}};var StructuralProto={[symbol](){return structureKeys(this,Object.keys(this))},[symbol2](that){const selfKeys=Object.keys(this);const thatKeys=Object.keys(that);if(selfKeys.length!==thatKeys.length)return false;for(let i=0;i<selfKeys.length;i++){if(selfKeys[i]!==thatKeys[i]||!equals(this[selfKeys[i]],that[selfKeys[i]])){return false}}return true}};var EffectProto={[EffectTypeId]:effectVariance,...PipeInspectableProto,[Symbol.iterator](){return new SingleShotGen(this)},toJSON(){return{_id:"Effect",op:this[identifier],...args in this?{args:this[args]}:undefined}}};var isEffect=(u)=>hasProperty(u,EffectTypeId);var isExit=(u)=>hasProperty(u,ExitTypeId);var CauseTypeId="~effect/Cause";var CauseReasonTypeId="~effect/Cause/Reason";var isCause=(self)=>hasProperty(self,CauseTypeId);class CauseImpl{constructor(failures){this[CauseTypeId]=CauseTypeId;this.reasons=failures}pipe(){return pipeArguments(this,arguments)}toJSON(){return{_id:"Cause",reasons:this.reasons.map((f)=>f.toJSON())}}toString(){return`Cause(${format(this.reasons)})`}[NodeInspectSymbol](){return this.toJSON()}[symbol2](that){return isCause(that)&&this.reasons.length===that.reasons.length&&this.reasons.every((e,i)=>equals(e,that.reasons[i]))}[symbol](){return array(this.reasons)}}var annotationsMap=new WeakMap;class ReasonBase{[CauseReasonTypeId];annotations;_tag;constructor(_tag,annotations,originalError){this[CauseReasonTypeId]=CauseReasonTypeId;this._tag=_tag;if(annotations!==constEmptyAnnotations&&typeof originalError==="object"&&originalError!==null&&annotations.size>0){const prevAnnotations=annotationsMap.get(originalError);if(prevAnnotations){annotations=new Map([...prevAnnotations,...annotations])}annotationsMap.set(originalError,annotations)}this.annotations=annotations}annotate(annotations,options){if(annotations.mapUnsafe.size===0)return this;const newAnnotations=new Map(this.annotations);annotations.mapUnsafe.forEach((value,key)=>{if(options?.overwrite!==true&&newAnnotations.has(key))return;newAnnotations.set(key,value)});if(options?.overwrite!==true&&newAnnotations.size===this.annotations.size)return this;const self=Object.assign(Object.create(Object.getPrototypeOf(this)),this);self.annotations=newAnnotations;return self}pipe(){return pipeArguments(this,arguments)}toString(){return format(this)}[NodeInspectSymbol](){return this.toString()}}var constEmptyAnnotations=new Map;class Fail extends ReasonBase{constructor(error,annotations=constEmptyAnnotations){super("Fail",annotations,error);this.error=error}toString(){return`Fail(${format(this.error)})`}toJSON(){return{_tag:"Fail",error:this.error}}[symbol2](that){return isFailReason(that)&&equals(this.error,that.error)&&equals(this.annotations,that.annotations)}[symbol](){return combine(string(this._tag))(combine(hash(this.error))(hash(this.annotations)))}}var causeFromReasons=(reasons)=>new CauseImpl(reasons);var dedupeReasons=(self,that)=>{const buckets=new Map;const out=[];for(const reason of self.concat(that)){const hash2=hash(reason);const bucket=buckets.get(hash2);if(bucket===undefined){buckets.set(hash2,[reason])}else if(bucket.some((previous)=>equals(previous,reason))){continue}else{bucket.push(reason)}out.push(reason)}return out};var causeCombine=dual(2,(self,that)=>{if(self.reasons.length===0){return that}else if(that.reasons.length===0){return self}const newCause=new CauseImpl(dedupeReasons(self.reasons,that.reasons));return equals(self,newCause)?self:newCause});var causeAddInterrupts=(self,interrupts)=>{const reasons=self.reasons.slice();for(const reason of interrupts.reasons){if(isInterruptReason(reason)&&!reasons.some((r)=>isInterruptReason(r)&&r.fiberId===reason.fiberId&&r.annotations===reason.annotations)){reasons.push(reason)}}return reasons.length===self.reasons.length?self:new CauseImpl(reasons)};var causeEmpty=new CauseImpl([]);var causeFail=(error)=>new CauseImpl([new Fail(error)]);class Die extends ReasonBase{constructor(defect,annotations=constEmptyAnnotations){super("Die",annotations,defect);this.defect=defect}toString(){return`Die(${format(this.defect)})`}toJSON(){return{_tag:"Die",defect:this.defect}}[symbol2](that){return isDieReason(that)&&equals(this.defect,that.defect)&&equals(this.annotations,that.annotations)}[symbol](){return combine(string(this._tag))(combine(hash(this.defect))(hash(this.annotations)))}}var causeDie=(defect)=>new CauseImpl([new Die(defect)]);var causeAnnotate=dual((args)=>isCause(args[0]),(self,annotations,options)=>{if(annotations.mapUnsafe.size===0)return self;return new CauseImpl(self.reasons.map((f)=>f.annotate(annotations,options)))});var isFailReason=(self)=>self._tag==="Fail";var isDieReason=(self)=>self._tag==="Die";var isInterruptReason=(self)=>self._tag==="Interrupt";function defaultEvaluate(_fiber){return exitDie(`Effect.evaluate: Not implemented`)}var makePrimitiveProto=(options)=>({...EffectProto,[identifier]:options.op,[evaluate]:options[evaluate]??defaultEvaluate,[contA]:options[contA],[contE]:options[contE],[contAll]:options[contAll]});var makePrimitive=(options)=>{const Proto=makePrimitiveProto(options);const PrimitiveImpl=function(value){this[args]=value};PrimitiveImpl.prototype=Proto;return function(value){return new PrimitiveImpl(value)}};var makeExit=(options)=>{const Proto={[ExitTypeId]:ExitTypeId,_tag:options.op,get[options.prop](){return this[args]},...makePrimitiveProto(options),toString(){return`${options.op}(${format(this[args])})`},toJSON(){return{_id:"Exit",_tag:options.op,[options.prop]:this[args]}},[symbol2](that){return isExit(that)&&that._tag===this._tag&&equals(this[args],that[args])},[symbol](){return combine(string(options.op),hash(this[args]))}};const ExitPrimitive=function(value){this[args]=value};ExitPrimitive.prototype=Proto;return function(value){return new ExitPrimitive(value)}};var exitSucceed=makeExit({op:"Success",prop:"value",[evaluate](fiber){const cont=fiber.getCont(contA);return cont?cont[contA](this[args],fiber,this):fiber.yieldWith(this)}});var StackTraceKey={key:"effect/Cause/StackTrace"};var InterruptorStackTrace={key:"effect/Cause/InterruptorStackTrace"};var exitFailCause=makeExit({op:"Failure",prop:"cause",[evaluate](fiber){let cause=this[args];let annotated=false;if(fiber.cache.stackFrame){cause=causeAnnotate(cause,{mapUnsafe:new Map([[StackTraceKey.key,fiber.cache.stackFrame]])});annotated=true}let cont=fiber.getCont(contE);const interruptedCause=fiber._interruptedCause;if(interruptedCause&&fiber.interruptible){let skippedHandler=false;while(cont&&fiber.interruptible){skippedHandler||=identifier in cont;cont=fiber.getCont(contE)}if(skippedHandler){cause=causeFromReasons(cause.reasons.filter((reason)=>reason._tag!=="Fail"))}cause=causeAddInterrupts(cause,interruptedCause);annotated=true}return cont?cont[contE](cause,fiber,annotated?undefined:this):fiber.yieldWith(annotated?exitFailCause(cause):this)}});var exitFail=(e)=>exitFailCause(causeFail(e));var exitDie=(defect)=>exitFailCause(causeDie(defect));var withFiber=makePrimitive({op:"WithFiber",[evaluate](fiber){return this[args](fiber)}});var withFiberSucceed=makePrimitive({op:"WithFiberSucceed",[evaluate](fiber){const value=this[args](fiber);const cont=fiber.getCont(contA);return cont?cont[contA](value,fiber):fiber.yieldWith(exitSucceed(value))}});var YieldableError=function(){class YieldableError extends globalThis.Error{}const proto=makePrimitiveProto({op:"YieldableError",[evaluate](){return exitFail(this)}});delete proto.toString;Object.assign(YieldableError.prototype,proto);return YieldableError}();var Error2=function(){const plainArgsSymbol=Symbol.for("effect/Data/Error/plainArgs");return class Base extends YieldableError{constructor(args){super(args?.message,args?.cause?{cause:args.cause}:undefined);if(args){assignProperties(this,args);Object.defineProperty(this,plainArgsSymbol,{value:args,enumerable:false})}}toJSON(){return{...this[plainArgsSymbol],...this}}}}();var TaggedError=(tag)=>{class Base extends Error2{_tag=tag}Base.prototype.name=tag;return Base};var DoneTypeId="~effect/Cause/Done";var isDone=(u)=>hasProperty(u,DoneTypeId);var DoneVoid={[DoneTypeId]:DoneTypeId,_tag:"Done",value:undefined};var Done=(value)=>{if(value===undefined)return DoneVoid;return{[DoneTypeId]:DoneTypeId,_tag:"Done",value}};var doneVoid=exitFail(DoneVoid);var done=(value)=>{if(value===undefined)return doneVoid;return exitFail(Done(value))};var TypeId="~effect/Option";var CommonProto={[TypeId]:{_A:(_)=>_},...PipeInspectableProto,[Symbol.iterator](){return new SingleShotGen(this)}};var SomeProto=Object.defineProperty(Object.assign(Object.create(CommonProto),{_tag:"Some",_op:"Some",[symbol2](that){return isOption(that)&&isSome(that)&&equals(this.value,that.value)},[symbol](){return combine(hash(this._tag))(hash(this.value))},toString(){return`some(${format(this.value)})`},toJSON(){return{_id:"Option",_tag:this._tag,value:toJson(this.value)}}}),"valueOrUndefined",{get(){return this.value}});var NoneHash=hash("None");var NoneProto=Object.assign(Object.create(CommonProto),{_tag:"None",_op:"None",valueOrUndefined:undefined,[symbol2](that){return isOption(that)&&isNone(that)},[symbol](){return NoneHash},toString(){return`none()`},toJSON(){return{_id:"Option",_tag:this._tag}}});var isOption=(input)=>hasProperty(input,TypeId);var isNone=(fa)=>fa._tag==="None";var isSome=(fa)=>fa._tag==="Some";var none=Object.create(NoneProto);var SomeImpl=function(value){this.value=value};SomeImpl.prototype=SomeProto;var some=(value)=>new SomeImpl(value);var TypeId2="~effect/Result";var CommonProto2={[TypeId2]:{_A:(_)=>_,_E:(_)=>_},...PipeInspectableProto,[Symbol.iterator](){return new SingleShotGen(this)}};var SuccessProto=Object.assign(Object.create(CommonProto2),{_tag:"Success",_op:"Success",[symbol2](that){return isResult(that)&&isSuccess(that)&&equals(this.success,that.success)},[symbol](){return combine(hash(this._tag))(hash(this.success))},toString(){return`success(${format(this.success)})`},toJSON(){return{_id:"Result",_tag:this._tag,value:toJson(this.success)}}});var FailureProto=Object.assign(Object.create(CommonProto2),{_tag:"Failure",_op:"Failure",[symbol2](that){return isResult(that)&&isFailure(that)&&equals(this.failure,that.failure)},[symbol](){return combine(hash(this._tag))(hash(this.failure))},toString(){return`failure(${format(this.failure)})`},toJSON(){return{_id:"Result",_tag:this._tag,failure:toJson(this.failure)}}});var isResult=(input)=>hasProperty(input,TypeId2);var isFailure=(result)=>result._tag==="Failure";var isSuccess=(result)=>result._tag==="Success";var FailureImpl=function(failure){this.failure=failure};FailureImpl.prototype=FailureProto;var fail=(failure)=>new FailureImpl(failure);var SuccessImpl=function(success){this.success=success};SuccessImpl.prototype=SuccessProto;var succeed=(success)=>new SuccessImpl(success);function make2(compare){return(self,that)=>self===that?0:compare(self,that)}var String2=make2((self,that)=>self<that?-1:1);var Number2=make2((self,that)=>{if(globalThis.Number.isNaN(self)&&globalThis.Number.isNaN(that))return 0;if(globalThis.Number.isNaN(self))return-1;if(globalThis.Number.isNaN(that))return 1;return self<that?-1:1});var mapInput=dual(2,(self,f)=>make2((b1,b2)=>self(f(b1),f(b2))));var isGreaterThan=(O)=>dual(2,(self,that)=>O(self,that)===1);var none2=()=>none;var some2=some;var isNone2=isNone;var isSome2=isSome;var match=dual(2,(self,{onNone,onSome})=>isNone2(self)?onNone():onSome(self.value));var getOrElse=dual(2,(self,onNone)=>isNone2(self)?onNone():self.value);var orElse=dual(2,(self,that)=>isNone2(self)?that():self);var fromNullishOr=(a)=>a==null?none2():some2(a);var getOrUndefined=getOrElse(constUndefined);var map=dual(2,(self,f)=>isNone2(self)?none2():some2(f(self.value)));var flatMap=dual(2,(self,f)=>isNone2(self)?none2():f(self.value));var BigInt2=globalThis.BigInt;var toNumber=(b)=>{if(b>BigInt2(Number.MAX_SAFE_INTEGER)||b<BigInt2(Number.MIN_SAFE_INTEGER)){return none2()}return some2(Number(b))};var bigint0=BigInt(0);var bigint1=BigInt(1);var decimalBase=BigInt(1000);var binaryBase=BigInt(1024);var decimalUnits=[{symbol:"B",factor:bigint1,names:["B","byte","bytes"]},{symbol:"kB",factor:decimalBase,names:["kB","kilobyte","kilobytes"]},{symbol:"MB",factor:decimalBase**BigInt(2),names:["MB","megabyte","megabytes"]},{symbol:"GB",factor:decimalBase**BigInt(3),names:["GB","gigabyte","gigabytes"]},{symbol:"TB",factor:decimalBase**BigInt(4),names:["TB","terabyte","terabytes"]},{symbol:"PB",factor:decimalBase**BigInt(5),names:["PB","petabyte","petabytes"]},{symbol:"EB",factor:decimalBase**BigInt(6),names:["EB","exabyte","exabytes"]},{symbol:"ZB",factor:decimalBase**BigInt(7),names:["ZB","zettabyte","zettabytes"]},{symbol:"YB",factor:decimalBase**BigInt(8),names:["YB","yottabyte","yottabytes"]},{symbol:"RB",factor:decimalBase**BigInt(9),names:["RB","ronnabyte","ronnabytes"]},{symbol:"QB",factor:decimalBase**BigInt(10),names:["QB","quettabyte","quettabytes"]}];var binaryUnits=[decimalUnits[0],{symbol:"KiB",factor:binaryBase,names:["KiB","kibibyte","kibibytes"]},{symbol:"MiB",factor:binaryBase**BigInt(2),names:["MiB","mebibyte","mebibytes"]},{symbol:"GiB",factor:binaryBase**BigInt(3),names:["GiB","gibibyte","gibibytes"]},{symbol:"TiB",factor:binaryBase**BigInt(4),names:["TiB","tebibyte","tebibytes"]},{symbol:"PiB",factor:binaryBase**BigInt(5),names:["PiB","pebibyte","pebibytes"]},{symbol:"EiB",factor:binaryBase**BigInt(6),names:["EiB","exbibyte","exbibytes"]},{symbol:"ZiB",factor:binaryBase**BigInt(7),names:["ZiB","zebibyte","zebibytes"]},{symbol:"YiB",factor:binaryBase**BigInt(8),names:["YiB","yobibyte","yobibytes"]}];var allUnits=[...decimalUnits,...binaryUnits.slice(1)];var unitsByName=new Map(allUnits.flatMap((unit)=>unit.names.map((name)=>[name,unit])));var make3=(value)=>value;var invalid=(message)=>{throw new Error(`Invalid ByteSize: ${message}`)};var fromNumber=(input)=>{if(!Number.isSafeInteger(input)||input<0){return invalid(`expected a non-negative safe integer, received ${input}`)}return make3(BigInt(input))};var fromStringUnsafe=(input)=>{const match=/^\s*(\d+)(?:\.(\d+))?\s*([A-Za-z]+)\s*$/.exec(input);if(match===null)return invalid(`unsupported syntax ${JSON.stringify(input)}`);const unit=unitsByName.get(match[3]);if(unit===undefined)return invalid(`unsupported unit ${JSON.stringify(match[3])}`);const fraction=match[2]??"";const scale=BigInt(10)**BigInt(fraction.length);const numerator=BigInt(match[1]+fraction)*unit.factor;if(numerator%scale!==bigint0){return invalid(`${JSON.stringify(input)} does not represent an integral number of bytes`)}return make3(numerator/scale)};var fromInputUnsafe=(input)=>{switch(typeof input){case"bigint":if(input<bigint0)return invalid(`expected a non-negative bigint, received ${input}`);return make3(input);case"number":return fromNumber(input);case"string":return fromStringUnsafe(input)}return invalid(`unsupported input ${input}`)};var bytes=(value)=>typeof value==="bigint"?fromInputUnsafe(value):fromNumber(value);var Prototype2=(options)=>makePrimitiveProto({op:options.label,[evaluate]:options.evaluate});var ServiceTypeId="~effect/Context/Service";var Service=function(){function KeyClass(){}const self=KeyClass;Object.setPrototypeOf(self,ServiceProto);const init=(key,options)=>{self.key=key;if(options?.defaultValue){self[ReferenceTypeId]=ReferenceTypeId;self.defaultValue=options.defaultValue}if(options?.make){self.make=options.make}if(options?.fiberCached){cacheKeys.add(key)}return self};return arguments.length>0?init(arguments[0],arguments[1]):init};var ServiceProto={[ServiceTypeId]:ServiceTypeId,...Prototype2({label:"Service",evaluate(fiber){return exitSucceed(get(fiber.context,this))}}),toJSON(){return{_id:"Service",key:this.key}},of(self){return self},context(self){return make4(this,self)},use(f){return withFiber((fiber)=>f(get(fiber.context,this)))},useSync(f){return withFiber((fiber)=>exitSucceed(f(get(fiber.context,this))))}};var cacheKeys=new Set;var ReferenceTypeId="~effect/Context/Reference";var TypeId3="~effect/Context";var FlattenAfterBaseHits=8;var makeImpl=(cacheRoot,base,overlay,depth,maxDepth)=>{const self=Object.create(Proto);self.cacheRoot=cacheRoot??self;self.base=base;self.overlay=overlay;self.depth=depth;self._flat=undefined;self.baseHits=0;self.maxDepth=maxDepth;return self};var applyOverlays=(map,overlay)=>{if(!overlay)return;applyOverlays(map,overlay.parent);map.set(overlay.key,overlay.value)};var flatten=(self)=>{if(self._flat)return self._flat;if(!self.overlay)return self._flat=self.base;const map=new Map(self.base);applyOverlays(map,self.overlay);return self._flat=map};var withFlat=(self,f)=>{const map=new Map(self.mapUnsafe);f(map);return makeImpl(undefined,map,undefined,0,self.maxDepth)};var notFound=Symbol();var lookup=(self,key)=>{const impl=self;for(let overlay=impl.overlay;overlay;overlay=overlay.parent){if(overlay.key===key)return overlay.value}const value=impl.base.get(key);if(value===undefined&&!impl.base.has(key))return notFound;if(impl.overlay&&++impl.baseHits>=impl.base.size&&impl.baseHits>=FlattenAfterBaseHits){impl.base=flatten(impl);impl.overlay=undefined;impl.depth=0}return value};var makeUnsafe=(mapUnsafe,options)=>{const maxDepth=options?.maxDepth;return makeImpl(undefined,mapUnsafe,undefined,0,Number.isInteger(maxDepth)&&maxDepth>=0?maxDepth:8)};var Proto={get mapUnsafe(){return flatten(this)},...PipeInspectableProto,[TypeId3]:{_Services:(_)=>_},toJSON(){return{_id:"Context",services:Array.from(this.mapUnsafe).map(([key,value])=>({key,value}))}},[symbol2](that){if(!isContext(that))return false;const self=this.mapUnsafe;const other=that.mapUnsafe;if(self.size!==other.size)return false;for(const[key,value]of self){if(!other.has(key)||!equals(value,other.get(key)))return false}return true},[symbol](){return number(this.mapUnsafe.size)}};var hasSameCache=(self,that)=>self.cacheRoot===that.cacheRoot;var isContext=(u)=>hasProperty(u,TypeId3);var isReference=(u)=>!!u[ReferenceTypeId];var empty=()=>emptyContext2;var emptyContext2=makeUnsafe(new Map);var make4=(key,service)=>makeUnsafe(new Map([[key.key,service]]));var add=dual(3,(self,key,service)=>addUnsafe(self,key.key,service));var addUnsafe=(self,key,service)=>{const impl=self;const cacheRoot=cacheKeys.has(key)?undefined:impl.cacheRoot;if(impl.depth>=impl.maxDepth){const map=new Map(impl._flat??impl.base);if(!impl._flat)applyOverlays(map,impl.overlay);map.set(key,service);return makeImpl(cacheRoot,map,undefined,0,impl.maxDepth)}return makeImpl(cacheRoot,impl.base,{key,value:service,parent:impl.overlay},impl.depth+1,impl.maxDepth)};var getOrUndefined2=dual(2,(self,key)=>getOrUndefinedUnsafe(self,key.key));var getOrUndefinedUnsafe=(self,key)=>{const value=lookup(self,key);return value===notFound?undefined:value};var getUnsafe=dual(2,(self,service)=>{const value=lookup(self,service.key);if(value===notFound){if(isReference(service))return getDefaultValue(service);throw serviceNotFoundError(service)}return value});var get=getUnsafe;var defaultValueCacheKey="~effect/Context/defaultValue";var getDefaultValue=(ref)=>{if(defaultValueCacheKey in ref){return ref[defaultValueCacheKey]}return ref[defaultValueCacheKey]=ref.defaultValue()};var serviceNotFoundError=(service)=>{const error=new Error(`Service not found${service.key?`: ${String(service.key)}`:""}`);if(error.stack){const lines=error.stack.split(`
221
221
  `);lines.splice(1,3);error.stack=lines.join(`
222
- `)}return error};var getOption=dual(2,(self,service)=>{const value=lookup(self,service.key);if(value!==notFound)return some2(value);return isReference(service)?some2(getDefaultValue(service)):none2()});var merge=dual(2,(self,that)=>{if(self.mapUnsafe.size===0)return that;if(that.mapUnsafe.size===0)return self;return withFlat(self,(map)=>that.mapUnsafe.forEach((value,key)=>map.set(key,value)))});var mergeAll=(...ctxs)=>{const map=new Map;for(let i=0;i<ctxs.length;i++){ctxs[i].mapUnsafe.forEach((value,key)=>{map.set(key,value)})}return makeUnsafe(map)};var Reference=Service;var isArrayNonEmpty=(self)=>self.length>0;var normalize=(n)=>n>0?Math.floor(n):0;var succeed2=succeed;var fail2=fail;var isFailure2=isFailure;var isSuccess2=isSuccess;var match2=dual(2,(self,{onFailure,onSuccess})=>isFailure2(self)?onFailure(self.failure):onSuccess(self.success));var make5=(...elements)=>elements;var Array2=globalThis.Array;var fromIterable=(collection)=>Array2.isArray(collection)?collection:Array2.from(collection);var ensure=(self)=>Array2.isArray(self)?self:[self];var append=dual(2,(self,last)=>[...self,last]);var isArray=Array2.isArray;var isArrayEmpty=(self)=>self.length===0;var isReadonlyArrayEmpty=isArrayEmpty;var isArrayNonEmpty2=isArrayNonEmpty;var isReadonlyArrayNonEmpty=isArrayNonEmpty;function isCanonicalArrayIndex(key){const index=Number(key);return String(index)===key&&Number.isInteger(index)&&index>=0&&index<2**32-1}function isOutOfBounds(i,as){return!Number.isFinite(i)||i<0||i>=as.length}var getUnsafe2=dual(2,(self,index)=>{const i=Math.floor(index);if(isOutOfBounds(i,self)){throw new Error(`Index out of bounds: ${i}`)}return self[i]});var headNonEmpty=getUnsafe2(0);var sort=dual(2,(self,O)=>{const out=Array2.from(self);out.sort(O);return out});var zip=dual(2,(self,that)=>zipWith(self,that,make5));var zipWith=dual(3,(self,that,f)=>{const as=fromIterable(self);const bs=fromIterable(that);if(isReadonlyArrayNonEmpty(as)&&isReadonlyArrayNonEmpty(bs)){const out=[f(headNonEmpty(as),headNonEmpty(bs))];const len=Math.min(as.length,bs.length);for(let i=1;i<len;i++){out[i]=f(as[i],bs[i])}return out}return[]});var empty2=()=>[];var of=(a)=>[a];var map=dual(2,(self,f)=>self.map(f));var flatMap2=dual(2,(self,f)=>{if(isReadonlyArrayEmpty(self)){return[]}const out=[];for(let i=0;i<self.length;i++){const inner=f(self[i],i);for(let j=0;j<inner.length;j++){out.push(inner[j])}}return out});var flatten2=flatMap2(identity);var TypeId4="~effect/Duration";var bigint02=BigInt(0);var bigint12=BigInt(1);var bigint2=BigInt(2);var bigint10=BigInt(10);var bigint24=BigInt(24);var bigint60=BigInt(60);var bigint1e3=BigInt(1000);var bigint1e6=BigInt(1e6);var roundTiesAwayFromZero=(input)=>BigInt(input<0?Math.ceil(input-0.5):Math.floor(input+0.5));var roundMillisToNanos=(millis)=>roundTiesAwayFromZero(millis*1e6);var parseNanos=(input,scale)=>{const decimalIndex=input.indexOf(".");if(decimalIndex===-1)return BigInt(input)*scale;const isNegative=input[0]==="-";const fractional=input.slice(decimalIndex+1);const fractionalScale=bigint10**BigInt(fractional.length);const scaled=(BigInt(input.slice(isNegative?1:0,decimalIndex))*fractionalScale+BigInt(fractional))*scale;const rounded=scaled/fractionalScale+(scaled%fractionalScale*bigint2>=fractionalScale?bigint12:bigint02);return isNegative?-rounded:rounded};var DURATION_REGEXP=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/;var fromInputUnsafe2=(input)=>{switch(typeof input){case"number":return millis(input);case"bigint":return nanos(input);case"string":{if(input==="Infinity"){return infinity}if(input==="-Infinity"){return negativeInfinity}const match=DURATION_REGEXP.exec(input);if(!match)break;const[_,valueStr,unit]=match;if(unit==="nano"||unit==="nanos"){return nanos(parseNanos(valueStr,bigint12))}if(unit==="micro"||unit==="micros"){return nanos(parseNanos(valueStr,bigint1e3))}const value=Number(valueStr);switch(unit){case"milli":case"millis":return millis(value);case"second":case"seconds":return seconds(value);case"minute":case"minutes":return minutes(value);case"hour":case"hours":return hours(value);case"day":case"days":return days(value);case"week":case"weeks":return weeks(value)}break}case"object":{if(input===null)break;if(TypeId4 in input)return input;if(Array.isArray(input)){if(input.length!==2||!input.every(isNumber)){return invalid2(input)}if(Number.isNaN(input[0])||Number.isNaN(input[1])){return zero}if(input[0]===-Infinity||input[1]===-Infinity){return negativeInfinity}if(input[0]===Infinity||input[1]===Infinity){return infinity}return make6(roundTiesAwayFromZero(input[0]*1e9+input[1]))}const obj=input;let millis=0;if(obj.weeks)millis+=obj.weeks*604800000;if(obj.days)millis+=obj.days*86400000;if(obj.hours)millis+=obj.hours*3600000;if(obj.minutes)millis+=obj.minutes*60000;if(obj.seconds)millis+=obj.seconds*1000;if(obj.milliseconds)millis+=obj.milliseconds;if(!obj.microseconds&&!obj.nanoseconds)return make6(millis);return make6(roundTiesAwayFromZero(millis*1e6+(obj.microseconds??0)*1000+(obj.nanoseconds??0)))}}return invalid2(input)};var invalid2=(input)=>{throw new Error(`Invalid Input: ${input}`)};var zeroDurationValue={_tag:"Millis",millis:0};var infinityDurationValue={_tag:"Infinity"};var negativeInfinityDurationValue={_tag:"NegativeInfinity"};var DurationProto={[TypeId4]:TypeId4,[symbol](){switch(this.value._tag){case"Millis":{const nanos=this.value.millis*1e6;return Number.isFinite(nanos)?hash(roundTiesAwayFromZero(nanos)):number(this.value.millis)}case"Nanos":return hash(this.value.nanos);default:return structure(this.value)}},[symbol2](that){return isDuration(that)&&equals2(this,that)},toString(){switch(this.value._tag){case"Infinity":return"Infinity";case"NegativeInfinity":return"-Infinity";case"Nanos":return`${this.value.nanos} nanos`;case"Millis":return`${this.value.millis} millis`}},toJSON(){switch(this.value._tag){case"Millis":return{_id:"Duration",_tag:"Millis",millis:this.value.millis};case"Nanos":return{_id:"Duration",_tag:"Nanos",nanos:String(this.value.nanos)};case"Infinity":return{_id:"Duration",_tag:"Infinity"};case"NegativeInfinity":return{_id:"Duration",_tag:"NegativeInfinity"}}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}};var make6=(input)=>{const duration=Object.create(DurationProto);if(typeof input==="number"){if(isNaN(input)||input===0||Object.is(input,-0)){duration.value=zeroDurationValue}else if(!Number.isFinite(input)){duration.value=input>0?infinityDurationValue:negativeInfinityDurationValue}else if(!Number.isInteger(input)){duration.value={_tag:"Nanos",nanos:roundMillisToNanos(input)}}else{duration.value={_tag:"Millis",millis:input}}}else if(input===bigint02){duration.value=zeroDurationValue}else{duration.value={_tag:"Nanos",nanos:input}}return duration};var isDuration=(u)=>hasProperty(u,TypeId4);var isZero=(self)=>{switch(self.value._tag){case"Millis":return self.value.millis===0;case"Nanos":return self.value.nanos===bigint02;case"Infinity":case"NegativeInfinity":return false}};var isNegative=(self)=>{switch(self.value._tag){case"Millis":return self.value.millis<0;case"Nanos":return self.value.nanos<bigint02;case"NegativeInfinity":return true;case"Infinity":return false}};var abs=(self)=>{switch(self.value._tag){case"Infinity":case"NegativeInfinity":return infinity;case"Millis":return self.value.millis<0?make6(-self.value.millis):self;case"Nanos":return self.value.nanos<bigint02?make6(-self.value.nanos):self}};var zero=make6(0);var infinity=make6(Infinity);var negativeInfinity=make6(-Infinity);var nanos=(nanos)=>make6(nanos);var millis=(millis)=>make6(millis);var seconds=(seconds)=>make6(seconds*1000);var minutes=(minutes)=>make6(minutes*60000);var hours=(hours)=>make6(hours*3600000);var days=(days)=>make6(days*86400000);var weeks=(weeks)=>make6(weeks*604800000);var toMillis=(self)=>match3(fromInputUnsafe2(self),{onMillis:identity,onNanos:(nanos)=>Number(nanos)/1e6,onInfinity:()=>Infinity,onNegativeInfinity:()=>-Infinity});var toNanosUnsafe=(input)=>{const self=fromInputUnsafe2(input);switch(self.value._tag){case"Infinity":case"NegativeInfinity":throw new Error("Cannot convert infinite duration to nanos");case"Nanos":return self.value.nanos;case"Millis":return roundMillisToNanos(self.value.millis)}};var match3=dual(2,(self,options)=>{switch(self.value._tag){case"Millis":return options.onMillis(self.value.millis);case"Nanos":return options.onNanos(self.value.nanos);case"Infinity":return options.onInfinity();case"NegativeInfinity":return(options.onNegativeInfinity??options.onInfinity)()}});var matchPair=dual(3,(self,that,options)=>{if(self.value._tag==="Infinity"||self.value._tag==="NegativeInfinity"||that.value._tag==="Infinity"||that.value._tag==="NegativeInfinity")return options.onInfinity(self,that);if(self.value._tag==="Millis"){return that.value._tag==="Millis"?options.onMillis(self.value.millis,that.value.millis):options.onNanos(toNanosUnsafe(self),that.value.nanos)}else{return options.onNanos(self.value.nanos,toNanosUnsafe(that))}});var Equivalence=(self,that)=>matchPair(self,that,{onMillis:(self,that)=>self===that,onNanos:(self,that)=>self===that,onInfinity:(self,that)=>self.value._tag===that.value._tag});var equals2=dual(2,(self,that)=>Equivalence(self,that));var parts=(self)=>{if(self.value._tag==="Infinity"){return{days:Infinity,hours:Infinity,minutes:Infinity,seconds:Infinity,millis:Infinity,nanos:Infinity}}if(self.value._tag==="NegativeInfinity"){return{days:-Infinity,hours:-Infinity,minutes:-Infinity,seconds:-Infinity,millis:-Infinity,nanos:-Infinity}}const n=toNanosUnsafe(self);const neg=n<bigint02;const a=neg?-n:n;const ms=a/bigint1e6;const sec=ms/bigint1e3;const min=sec/bigint60;const hr=min/bigint60;const d=hr/bigint24;const sign=neg?-1:1;return{days:sign*Number(d),hours:sign*Number(hr%bigint24),minutes:sign*Number(min%bigint60),seconds:sign*Number(sec%bigint60),millis:sign*Number(ms%bigint1e3),nanos:sign*Number(a%bigint1e6)}};var format2=(self)=>{if(self.value._tag==="Infinity"){return"Infinity"}if(self.value._tag==="NegativeInfinity"){return"-Infinity"}if(isZero(self)){return"0"}if(isNegative(self)){return"-"+format2(abs(self))}const fragments=parts(self);const pieces=[];if(fragments.days!==0){pieces.push(`${fragments.days}d`)}if(fragments.hours!==0){pieces.push(`${fragments.hours}h`)}if(fragments.minutes!==0){pieces.push(`${fragments.minutes}m`)}if(fragments.seconds!==0){pieces.push(`${fragments.seconds}s`)}if(fragments.millis!==0){pieces.push(`${fragments.millis}ms`)}if(fragments.nanos!==0){pieces.push(`${fragments.nanos}ns`)}return pieces.join(" ")};var Scheduler=Reference("effect/Scheduler",{fiberCached:true,defaultValue:()=>new MixedScheduler});var setMicrotask=(f)=>{let cancelled=false;Promise.resolve().then(()=>{if(!cancelled)f()});return()=>{cancelled=true}};var setTimer="setImmediate"in globalThis?(f)=>{const timer=globalThis.setImmediate(f);return()=>globalThis.clearImmediate(timer)}:(f)=>{const timer=setTimeout(f,0);return()=>clearTimeout(timer)};var setImmediate2=(f)=>{try{return setTimer(f)}catch{return setMicrotask(f)}};class PriorityBuckets{buckets=[];scheduleTask(task,priority){const buckets=this.buckets;const len=buckets.length;let bucket;let index=0;for(;index<len;index++){if(buckets[index][0]>priority)break;bucket=buckets[index]}if(bucket&&bucket[0]===priority){bucket[1].push(task)}else if(index===len){buckets.push([priority,[task]])}else{buckets.splice(index,0,[priority,[task]])}}drain(){const buckets=this.buckets;this.buckets=[];return buckets}}class MixedScheduler{executionMode;setImmediate;constructor(executionMode="async",setImmediateFn){this.executionMode=executionMode;this.setImmediate=setImmediateFn??(executionMode==="sync"?setMicrotask:setImmediate2)}shouldYield(fiber){return fiber.currentOpCount>=fiber.cache.maxOpsBeforeYield}makeDispatcher(){return new MixedSchedulerDispatcher(this.setImmediate)}}class MixedSchedulerDispatcher{tasks=new PriorityBuckets;running=undefined;setImmediate;constructor(setImmediateFn=setImmediate2){this.setImmediate=setImmediateFn}scheduleTask(task,priority){this.tasks.scheduleTask(task,priority);if(this.running===undefined){this.running=this.setImmediate(this.afterScheduled)}}afterScheduled=()=>{this.running=undefined;this.runTasks()};runTasks(){const buckets=this.tasks.drain();for(let i=0;i<buckets.length;i++){const toRun=buckets[i][1];for(let j=0;j<toRun.length;j++){toRun[j]()}}}flush(){while(this.tasks.buckets.length>0){if(this.running!==undefined){this.running();this.running=undefined}this.runTasks()}}}var MaxOpsBeforeYield=Reference("effect/Scheduler/MaxOpsBeforeYield",{fiberCached:true,defaultValue:()=>2048});var PreventSchedulerYield=Reference("effect/Scheduler/PreventSchedulerYield",{fiberCached:true,defaultValue:()=>false});var Error3=Error2;var TaggedError2=TaggedError;var EncodingErrorTypeId="~effect/encoding/EncodingError";class EncodingError extends TaggedError2("EncodingError"){[EncodingErrorTypeId]=EncodingErrorTypeId}var random2=(length)=>{switch(length){case 16:return random16();case 32:return random32();default:{let result="";for(let i=length>>>3;i>0;i--){result+=random8()}return result}}};var hexCharCodes=Uint8Array.from("0123456789abcdef",(c)=>c.charCodeAt(0));var randomWord=()=>Math.random()*4294967296>>>0;var random8=()=>{const a=randomWord();return String.fromCharCode(hexCharCodes[a>>>28],hexCharCodes[a>>>24&15],hexCharCodes[a>>>20&15],hexCharCodes[a>>>16&15],hexCharCodes[a>>>12&15],hexCharCodes[a>>>8&15],hexCharCodes[a>>>4&15],hexCharCodes[a&15])};var random16=()=>{const a=randomWord();const b=randomWord();return String.fromCharCode(hexCharCodes[a>>>28],hexCharCodes[a>>>24&15],hexCharCodes[a>>>20&15],hexCharCodes[a>>>16&15],hexCharCodes[a>>>12&15],hexCharCodes[a>>>8&15],hexCharCodes[a>>>4&15],hexCharCodes[a&15],hexCharCodes[b>>>28],hexCharCodes[b>>>24&15],hexCharCodes[b>>>20&15],hexCharCodes[b>>>16&15],hexCharCodes[b>>>12&15],hexCharCodes[b>>>8&15],hexCharCodes[b>>>4&15],hexCharCodes[b&15])};var random32=()=>{const a=randomWord();const b=randomWord();const c=randomWord();const d=randomWord();return String.fromCharCode(hexCharCodes[a>>>28],hexCharCodes[a>>>24&15],hexCharCodes[a>>>20&15],hexCharCodes[a>>>16&15],hexCharCodes[a>>>12&15],hexCharCodes[a>>>8&15],hexCharCodes[a>>>4&15],hexCharCodes[a&15],hexCharCodes[b>>>28],hexCharCodes[b>>>24&15],hexCharCodes[b>>>20&15],hexCharCodes[b>>>16&15],hexCharCodes[b>>>12&15],hexCharCodes[b>>>8&15],hexCharCodes[b>>>4&15],hexCharCodes[b&15],hexCharCodes[c>>>28],hexCharCodes[c>>>24&15],hexCharCodes[c>>>20&15],hexCharCodes[c>>>16&15],hexCharCodes[c>>>12&15],hexCharCodes[c>>>8&15],hexCharCodes[c>>>4&15],hexCharCodes[c&15],hexCharCodes[d>>>28],hexCharCodes[d>>>24&15],hexCharCodes[d>>>20&15],hexCharCodes[d>>>16&15],hexCharCodes[d>>>12&15],hexCharCodes[d>>>8&15],hexCharCodes[d>>>4&15],hexCharCodes[d&15])};var ParentSpanKey="effect/Tracer/ParentSpan";class ParentSpan extends Service()(ParentSpanKey,{fiberCached:true}){}var make7=(options)=>options;var DisablePropagation=Reference("effect/Tracer/DisablePropagation",{defaultValue:constFalse});var CurrentTraceLevel=Reference("effect/Tracer/CurrentTraceLevel",{defaultValue:()=>"Info"});var MinimumTraceLevel=Reference("effect/Tracer/MinimumTraceLevel",{defaultValue:()=>"All"});var TracerKey="effect/Tracer";var nativeTracer=make7({span:(options)=>new NativeSpan(options)});class NativeSpan{_tag="Span";sampled;name;parent;annotations;links;startTime;kind;status;_traceId=undefined;_spanId=undefined;_attributes=undefined;_events=undefined;constructor(options){this.name=options.name;this.parent=options.parent;this.annotations=options.annotations;this.links=options.links;this.startTime=options.startTime;this.kind=options.kind;this.sampled=options.sampled;this.status={_tag:"Started",startTime:options.startTime}}get traceId(){return this._traceId??=getOrUndefined(this.parent)?.traceId??random2(32)}get spanId(){return this._spanId??=random2(16)}get attributes(){return this._attributes??=new Map}get events(){return this._events??=[]}end(endTime,exit){this.status={_tag:"Ended",endTime,exit,startTime:this.status.startTime}}attribute(key,value){this.attributes.set(key,value)}event(name,startTime,attributes){this.events.push([name,startTime,attributes??{}])}addLinks(links){this.links.push(...links)}}var FiberRuntimeMetricsKey="effect/Metric/FiberRuntimeMetrics";var CurrentStackFrame=Reference("effect/References/CurrentStackFrame",{fiberCached:true,defaultValue:constUndefined});var TracerEnabled=Reference("effect/References/TracerEnabled",{fiberCached:true,defaultValue:constTrue});var TracerTimingEnabled=Reference("effect/References/TracerTimingEnabled",{defaultValue:constTrue});var TracerSpanAnnotations=Reference("effect/References/TracerSpanAnnotations",{defaultValue:()=>({})});var TracerSpanLinks=Reference("effect/References/TracerSpanLinks",{defaultValue:()=>[]});var CurrentLogAnnotations=Reference("effect/References/CurrentLogAnnotations",{defaultValue:()=>({})});var CurrentLogLevel=Reference("effect/References/CurrentLogLevel",{fiberCached:true,defaultValue:()=>"Info"});var MinimumLogLevel=Reference("effect/References/MinimumLogLevel",{fiberCached:true,defaultValue:()=>"Info"});var CurrentLogSpans=Reference("effect/References/CurrentLogSpans",{defaultValue:()=>[]});var makeStackCleaner=(line)=>(stack)=>{let cache;return()=>{if(cache!==undefined)return cache;const trace=stack();if(!trace)return;const lines=trace.split(`
223
- `);if(lines[line]!==undefined){cache=lines[line].trim();return cache}}};class Interrupt extends ReasonBase{constructor(fiberId,annotations=constEmptyAnnotations){super("Interrupt",annotations,"Interrupted");this.fiberId=fiberId}toString(){return`Interrupt(${this.fiberId})`}toJSON(){return{_tag:"Interrupt",fiberId:this.fiberId}}[symbol2](that){return isInterruptReason(that)&&this.fiberId===that.fiberId&&this.annotations===that.annotations}[symbol](){return combine(string(`${this._tag}:${this.fiberId}`))(random(this.annotations))}}var causeInterrupt=(fiberId)=>new CauseImpl([new Interrupt(fiberId)]);var findFail=(self)=>{const reason=self.reasons.find(isFailReason);return reason?succeed2(reason):fail2(self)};var findError=(self)=>{for(let i=0;i<self.reasons.length;i++){const reason=self.reasons[i];if(reason._tag==="Fail"){return succeed2(reason.error)}}return fail2(self)};var findDefect=(self)=>{const reason=self.reasons.find(isDieReason);return reason?succeed2(reason.defect):fail2(self)};var hasInterrupts=(self)=>self.reasons.some(isInterruptReason);var causeMap=dual(2,(self,f)=>{let hasFail=false;const failures=self.reasons.map((failure)=>{if(isFailReason(failure)){hasFail=true;return new Fail(f(failure.error),failure.annotations)}return failure});return hasFail?causeFromReasons(failures):self});var causeSquash=(self)=>{let die;for(const reason of self.reasons){if(reason._tag==="Fail")return reason.error;if(reason._tag==="Die")die??=reason}if(die!==undefined)return die.defect;if(self.reasons.length>0)return new globalThis.Error("All fibers interrupted without error");return new globalThis.Error("Empty cause")};var causePrettyErrors=(self,options)=>{const errors=[];const interrupts=[];if(self.reasons.length===0)return errors;const prevStackLimit=getStackTraceLimit();if(prevStackLimit!==0)setStackTraceLimit(1);try{for(const failure of self.reasons){if(failure._tag==="Interrupt"){interrupts.push(failure);continue}errors.push(causePrettyError(failure._tag==="Die"?failure.defect:failure.error,failure.annotations,options))}if(errors.length===0){const cause=new Error("The fiber was interrupted by:");cause.name="InterruptCause";cause.stack=interruptCauseStack(cause,interrupts);const error=new globalThis.Error("All fibers interrupted without error",{cause});error.name="InterruptError";error.stack=`${error.name}: ${error.message}`;errors.push(causePrettyError(error,interrupts[0].annotations,options))}}finally{if(prevStackLimit!==0)setStackTraceLimit(prevStackLimit)}return errors};var causePrettyError=(original,annotations,options)=>{const kind=typeof original;let error;if(original&&kind==="object"){error=new globalThis.Error(causePrettyMessage(original),{cause:original.cause?causePrettyError(original.cause):undefined});if(typeof original.name==="string"){error.name=original.name}if(typeof original.stack==="string"){error.stack=cleanErrorStack(original.stack,error,annotations)}else{const stack=`${error.name}: ${error.message}`;error.stack=annotations?addStackAnnotations(stack,annotations):stack}if(options?.includeCauseInStack){error.stack=renderPrettyError(error)}for(const key of Object.keys(original)){if(!(key in error)){error[key]=original[key]}}}else{error=new globalThis.Error(!original?`Unknown error: ${original}`:kind==="string"?original:formatJson(original))}return error};var causePrettyMessage=(u)=>{if(typeof u.message==="string"){return u.message}else if(typeof u.toString==="function"&&u.toString!==Object.prototype.toString&&u.toString!==Array.prototype.toString){try{return u.toString()}catch{}}return formatJson(u)};var locationRegExp=/\((.*)\)/g;var cleanErrorStack=(stack,error,annotations)=>{const message=`${error.name}: ${error.message}`;const lines=(stack.startsWith(message)?stack.slice(message.length):stack).split(`
222
+ `)}return error};var getOption=dual(2,(self,service)=>{const value=lookup(self,service.key);if(value!==notFound)return some2(value);return isReference(service)?some2(getDefaultValue(service)):none2()});var merge=dual(2,(self,that)=>{if(self.mapUnsafe.size===0)return that;if(that.mapUnsafe.size===0)return self;return withFlat(self,(map)=>that.mapUnsafe.forEach((value,key)=>map.set(key,value)))});var mergeAll=(...ctxs)=>{const map=new Map;for(let i=0;i<ctxs.length;i++){ctxs[i].mapUnsafe.forEach((value,key)=>{map.set(key,value)})}return makeUnsafe(map)};var Reference=Service;var isArrayNonEmpty=(self)=>self.length>0;var normalize=(n)=>n>0?Math.floor(n):0;var succeed2=succeed;var fail2=fail;var isFailure2=isFailure;var isSuccess2=isSuccess;var match2=dual(2,(self,{onFailure,onSuccess})=>isFailure2(self)?onFailure(self.failure):onSuccess(self.success));var make5=(...elements)=>elements;var Array2=globalThis.Array;var fromIterable=(collection)=>Array2.isArray(collection)?collection:Array2.from(collection);var ensure=(self)=>Array2.isArray(self)?self:[self];var append=dual(2,(self,last)=>[...self,last]);var isArray=Array2.isArray;var isArrayEmpty=(self)=>self.length===0;var isReadonlyArrayEmpty=isArrayEmpty;var isArrayNonEmpty2=isArrayNonEmpty;var isReadonlyArrayNonEmpty=isArrayNonEmpty;function isCanonicalArrayIndex(key){const index=Number(key);return String(index)===key&&Number.isInteger(index)&&index>=0&&index<2**32-1}function isOutOfBounds(i,as){return!Number.isFinite(i)||i<0||i>=as.length}var getUnsafe2=dual(2,(self,index)=>{const i=Math.floor(index);if(isOutOfBounds(i,self)){throw new Error(`Index out of bounds: ${i}`)}return self[i]});var headNonEmpty=getUnsafe2(0);var sort=dual(2,(self,O)=>{const out=Array2.from(self);out.sort(O);return out});var zip=dual(2,(self,that)=>zipWith(self,that,make5));var zipWith=dual(3,(self,that,f)=>{const as=fromIterable(self);const bs=fromIterable(that);if(isReadonlyArrayNonEmpty(as)&&isReadonlyArrayNonEmpty(bs)){const out=[f(headNonEmpty(as),headNonEmpty(bs))];const len=Math.min(as.length,bs.length);for(let i=1;i<len;i++){out[i]=f(as[i],bs[i])}return out}return[]});var empty2=()=>[];var of=(a)=>[a];var map2=dual(2,(self,f)=>self.map(f));var flatMap2=dual(2,(self,f)=>{if(isReadonlyArrayEmpty(self)){return[]}const out=[];for(let i=0;i<self.length;i++){const inner=f(self[i],i);for(let j=0;j<inner.length;j++){out.push(inner[j])}}return out});var flatten2=flatMap2(identity);var TypeId4="~effect/Duration";var bigint02=BigInt(0);var bigint12=BigInt(1);var bigint2=BigInt(2);var bigint10=BigInt(10);var bigint24=BigInt(24);var bigint60=BigInt(60);var bigint1e3=BigInt(1000);var bigint1e6=BigInt(1e6);var bigint1e9=BigInt(1e9);var bigintNanosPerMinute=BigInt(60000000000);var bigintNanosPerHour=BigInt(3600000000000);var bigintNanosPerDay=BigInt(86400000000000);var bigintNanosPerWeek=BigInt(604800000000000);var roundTiesAwayFromZero=(input)=>BigInt(Math.sign(input)*Math.round(Math.abs(input)));var roundMillisToNanos=(millis)=>Number.isInteger(millis)?BigInt(millis)*bigint1e6:roundTiesAwayFromZero(millis*1e6);var fromNanosNumber=(nanos)=>make6(Number.isFinite(nanos)?roundTiesAwayFromZero(nanos):nanos);var nanosToUnit=(nanos,divisor)=>{const value=Number(nanos);if(Number.isFinite(value))return value/divisor;const scale=BigInt(divisor);return Number(nanos/scale)+Number(nanos%scale)/divisor};var parseNanos=(input,scale)=>{const decimalIndex=input.indexOf(".");if(decimalIndex===-1)return BigInt(input)*scale;const isNegative=input[0]==="-";const fractional=input.slice(decimalIndex+1);const fractionalScale=bigint10**BigInt(fractional.length);const scaled=(BigInt(input.slice(isNegative?1:0,decimalIndex))*fractionalScale+BigInt(fractional))*scale;return divideTiesAwayFromZero(isNegative?-scaled:scaled,fractionalScale)};var divideTiesAwayFromZero=(numerator,denominator)=>{const absolute=numerator<bigint02?-numerator:numerator;const rounded=absolute/denominator+(absolute%denominator*bigint2>=denominator?bigint12:bigint02);return numerator<bigint02?-rounded:rounded};var fromMillisString=(input,scale)=>{const millis=Number(input)*scale;if(!Number.isFinite(millis))return make6(millis);const nanos=parseNanos(input,BigInt(scale)*bigint1e6);return make6(Number.isInteger(millis)&&BigInt(millis)*bigint1e6===nanos?millis:nanos)};var DURATION_REGEXP=/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/;var fromInputUnsafe2=(input)=>{switch(typeof input){case"number":return millis(input);case"bigint":return nanos(input);case"string":{if(input==="Infinity"){return infinity}if(input==="-Infinity"){return negativeInfinity}const match=DURATION_REGEXP.exec(input);if(!match)break;const[_,valueStr,unit]=match;if(unit==="nano"||unit==="nanos"){return nanos(parseNanos(valueStr,bigint12))}if(unit==="micro"||unit==="micros"){return nanos(parseNanos(valueStr,bigint1e3))}switch(unit){case"milli":case"millis":return fromMillisString(valueStr,1);case"second":case"seconds":return fromMillisString(valueStr,1000);case"minute":case"minutes":return fromMillisString(valueStr,60000);case"hour":case"hours":return fromMillisString(valueStr,3600000);case"day":case"days":return fromMillisString(valueStr,86400000);case"week":case"weeks":return fromMillisString(valueStr,604800000)}break}case"object":{if(input===null)break;if(TypeId4 in input)return input;if(Array.isArray(input)){if(input.length!==2||!input.every(isNumber)){return invalid2(input)}if(Number.isNaN(input[0])||Number.isNaN(input[1])){return zero}if(input[0]===-Infinity||input[1]===-Infinity){return negativeInfinity}if(input[0]===Infinity||input[1]===Infinity){return infinity}const nanos=input[0]*1e9+input[1];return Number.isFinite(nanos)&&Number.isInteger(input[0])&&Number.isInteger(input[1])?make6(BigInt(input[0])*bigint1e9+BigInt(input[1])):fromNanosNumber(nanos)}const obj=input;let millis=0;if(obj.weeks)millis+=obj.weeks*604800000;if(obj.days)millis+=obj.days*86400000;if(obj.hours)millis+=obj.hours*3600000;if(obj.minutes)millis+=obj.minutes*60000;if(obj.seconds)millis+=obj.seconds*1000;if(obj.milliseconds)millis+=obj.milliseconds;if(!obj.microseconds&&!obj.nanoseconds){if(!Number.isFinite(millis))return make6(millis);const exact=sumObjectNanos(obj);return exact===undefined||BigInt(millis)*bigint1e6===exact?make6(millis):make6(exact)}const nanos=millis*1e6+(obj.microseconds??0)*1000+(obj.nanoseconds??0);const exact=Number.isFinite(nanos)?sumObjectNanos(obj):undefined;return exact===undefined?fromNanosNumber(nanos):make6(exact)}}return invalid2(input)};var isIntegerOrUnset=(n)=>!n||Number.isInteger(n);var sumObjectNanos=(obj)=>{if(!isIntegerOrUnset(obj.weeks)||!isIntegerOrUnset(obj.days)||!isIntegerOrUnset(obj.hours)||!isIntegerOrUnset(obj.minutes)||!isIntegerOrUnset(obj.seconds)||!isIntegerOrUnset(obj.milliseconds)||!isIntegerOrUnset(obj.microseconds)||!isIntegerOrUnset(obj.nanoseconds))return;let nanos=bigint02;if(obj.weeks)nanos+=BigInt(obj.weeks)*bigintNanosPerWeek;if(obj.days)nanos+=BigInt(obj.days)*bigintNanosPerDay;if(obj.hours)nanos+=BigInt(obj.hours)*bigintNanosPerHour;if(obj.minutes)nanos+=BigInt(obj.minutes)*bigintNanosPerMinute;if(obj.seconds)nanos+=BigInt(obj.seconds)*bigint1e9;if(obj.milliseconds)nanos+=BigInt(obj.milliseconds)*bigint1e6;if(obj.microseconds)nanos+=BigInt(obj.microseconds)*bigint1e3;if(obj.nanoseconds)nanos+=BigInt(obj.nanoseconds);return nanos};var invalid2=(input)=>{throw new Error(`Invalid Input: ${input}`)};var zeroDurationValue={_tag:"Millis",millis:0};var infinityDurationValue={_tag:"Infinity"};var negativeInfinityDurationValue={_tag:"NegativeInfinity"};var DurationProto={[TypeId4]:TypeId4,[symbol](){switch(this.value._tag){case"Millis":return hash(roundMillisToNanos(this.value.millis));case"Nanos":return hash(this.value.nanos);default:return structure(this.value)}},[symbol2](that){return isDuration(that)&&equals2(this,that)},toString(){switch(this.value._tag){case"Infinity":return"Infinity";case"NegativeInfinity":return"-Infinity";case"Nanos":return`${this.value.nanos} nanos`;case"Millis":return`${this.value.millis} millis`}},toJSON(){switch(this.value._tag){case"Millis":return{_id:"Duration",_tag:"Millis",millis:this.value.millis};case"Nanos":return{_id:"Duration",_tag:"Nanos",nanos:String(this.value.nanos)};case"Infinity":return{_id:"Duration",_tag:"Infinity"};case"NegativeInfinity":return{_id:"Duration",_tag:"NegativeInfinity"}}},[NodeInspectSymbol](){return this.toJSON()},pipe(){return pipeArguments(this,arguments)}};var make6=(input)=>{const duration=Object.create(DurationProto);if(typeof input==="number"){if(isNaN(input)||input===0||Object.is(input,-0)){duration.value=zeroDurationValue}else if(!Number.isFinite(input)){duration.value=input>0?infinityDurationValue:negativeInfinityDurationValue}else if(!Number.isInteger(input)){duration.value={_tag:"Nanos",nanos:roundMillisToNanos(input)}}else{duration.value={_tag:"Millis",millis:input}}}else if(input===bigint02){duration.value=zeroDurationValue}else{duration.value={_tag:"Nanos",nanos:input}}return duration};var isDuration=(u)=>hasProperty(u,TypeId4);var isZero=(self)=>{switch(self.value._tag){case"Millis":return self.value.millis===0;case"Nanos":return self.value.nanos===bigint02;case"Infinity":case"NegativeInfinity":return false}};var isNegative=(self)=>{switch(self.value._tag){case"Millis":return self.value.millis<0;case"Nanos":return self.value.nanos<bigint02;case"NegativeInfinity":return true;case"Infinity":return false}};var abs=(self)=>{switch(self.value._tag){case"Infinity":case"NegativeInfinity":return infinity;case"Millis":return self.value.millis<0?make6(-self.value.millis):self;case"Nanos":return self.value.nanos<bigint02?make6(-self.value.nanos):self}};var zero=make6(0);var infinity=make6(Infinity);var negativeInfinity=make6(-Infinity);var nanos=(nanos)=>make6(nanos);var millis=(millis)=>make6(millis);var toMillis=(self)=>match3(fromInputUnsafe2(self),{onMillis:identity,onNanos:(nanos)=>nanosToUnit(nanos,1e6),onInfinity:()=>Infinity,onNegativeInfinity:()=>-Infinity});var toNanosUnsafe=(input)=>{const self=fromInputUnsafe2(input);switch(self.value._tag){case"Infinity":case"NegativeInfinity":throw new Error("Cannot convert infinite duration to nanos");case"Nanos":return self.value.nanos;case"Millis":return roundMillisToNanos(self.value.millis)}};var match3=dual(2,(self,options)=>{switch(self.value._tag){case"Millis":return options.onMillis(self.value.millis);case"Nanos":return options.onNanos(self.value.nanos);case"Infinity":return options.onInfinity();case"NegativeInfinity":return(options.onNegativeInfinity??options.onInfinity)()}});var matchPair=dual(3,(self,that,options)=>{if(self.value._tag==="Infinity"||self.value._tag==="NegativeInfinity"||that.value._tag==="Infinity"||that.value._tag==="NegativeInfinity")return options.onInfinity(self,that);if(self.value._tag==="Millis"){return that.value._tag==="Millis"?options.onMillis(self.value.millis,that.value.millis):options.onNanos(toNanosUnsafe(self),that.value.nanos)}else{return options.onNanos(self.value.nanos,toNanosUnsafe(that))}});var Equivalence=(self,that)=>matchPair(self,that,{onMillis:(self,that)=>self===that,onNanos:(self,that)=>self===that,onInfinity:(self,that)=>self.value._tag===that.value._tag});var equals2=dual(2,(self,that)=>Equivalence(self,that));var parts=(self)=>{if(self.value._tag==="Infinity"){return{days:Infinity,hours:Infinity,minutes:Infinity,seconds:Infinity,millis:Infinity,nanos:Infinity}}if(self.value._tag==="NegativeInfinity"){return{days:-Infinity,hours:-Infinity,minutes:-Infinity,seconds:-Infinity,millis:-Infinity,nanos:-Infinity}}const n=toNanosUnsafe(self);const neg=n<bigint02;const a=neg?-n:n;const ms=a/bigint1e6;const sec=ms/bigint1e3;const min=sec/bigint60;const hr=min/bigint60;const d=hr/bigint24;const sign=neg?-1:1;return{days:sign*Number(d),hours:sign*Number(hr%bigint24),minutes:sign*Number(min%bigint60),seconds:sign*Number(sec%bigint60),millis:sign*Number(ms%bigint1e3),nanos:sign*Number(a%bigint1e6)}};var format2=(self)=>{if(self.value._tag==="Infinity"){return"Infinity"}if(self.value._tag==="NegativeInfinity"){return"-Infinity"}if(isZero(self)){return"0"}if(isNegative(self)){return"-"+format2(abs(self))}const fragments=parts(self);const pieces=[];if(fragments.days!==0){pieces.push(`${fragments.days}d`)}if(fragments.hours!==0){pieces.push(`${fragments.hours}h`)}if(fragments.minutes!==0){pieces.push(`${fragments.minutes}m`)}if(fragments.seconds!==0){pieces.push(`${fragments.seconds}s`)}if(fragments.millis!==0){pieces.push(`${fragments.millis}ms`)}if(fragments.nanos!==0){pieces.push(`${fragments.nanos}ns`)}return pieces.join(" ")};var Scheduler=Reference("effect/Scheduler",{fiberCached:true,defaultValue:()=>new MixedScheduler});var setMicrotask=(f)=>{let cancelled=false;Promise.resolve().then(()=>{if(!cancelled)f()});return()=>{cancelled=true}};var setTimer="setImmediate"in globalThis?(f)=>{const timer=globalThis.setImmediate(f);return()=>globalThis.clearImmediate(timer)}:(f)=>{const timer=setTimeout(f,0);return()=>clearTimeout(timer)};var setImmediate2=(f)=>{try{return setTimer(f)}catch{return setMicrotask(f)}};class PriorityBuckets{buckets=[];scheduleTask(task,priority){const buckets=this.buckets;const len=buckets.length;let bucket;let index=0;for(;index<len;index++){if(buckets[index][0]>priority)break;bucket=buckets[index]}if(bucket&&bucket[0]===priority){bucket[1].push(task)}else if(index===len){buckets.push([priority,[task]])}else{buckets.splice(index,0,[priority,[task]])}}drain(){const buckets=this.buckets;this.buckets=[];return buckets}}class MixedScheduler{executionMode;setImmediate;constructor(executionMode="async",setImmediateFn){this.executionMode=executionMode;this.setImmediate=setImmediateFn??(executionMode==="sync"?setMicrotask:setImmediate2)}shouldYield(fiber){return fiber.currentOpCount>=fiber.cache.maxOpsBeforeYield}makeDispatcher(){return new MixedSchedulerDispatcher(this.setImmediate)}}class MixedSchedulerDispatcher{tasks=new PriorityBuckets;running=undefined;setImmediate;constructor(setImmediateFn=setImmediate2){this.setImmediate=setImmediateFn}scheduleTask(task,priority){this.tasks.scheduleTask(task,priority);if(this.running===undefined){this.running=this.setImmediate(this.afterScheduled)}}afterScheduled=()=>{this.running=undefined;this.runTasks()};runTasks(){const buckets=this.tasks.drain();for(let i=0;i<buckets.length;i++){const toRun=buckets[i][1];for(let j=0;j<toRun.length;j++){toRun[j]()}}}flush(){while(this.tasks.buckets.length>0){if(this.running!==undefined){this.running();this.running=undefined}this.runTasks()}}}var MaxOpsBeforeYield=Reference("effect/Scheduler/MaxOpsBeforeYield",{fiberCached:true,defaultValue:()=>2048});var PreventSchedulerYield=Reference("effect/Scheduler/PreventSchedulerYield",{fiberCached:true,defaultValue:()=>false});var Error3=Error2;var TaggedError2=TaggedError;var EncodingErrorTypeId="~effect/encoding/EncodingError";class EncodingError extends TaggedError2("EncodingError"){[EncodingErrorTypeId]=EncodingErrorTypeId}var random2=(length)=>{switch(length){case 16:return random16();case 32:return random32();default:{let result="";for(let i=length>>>3;i>0;i--){result+=random8()}return result}}};var hexCharCodes=Uint8Array.from("0123456789abcdef",(c)=>c.charCodeAt(0));var randomWord=()=>Math.random()*4294967296>>>0;var random8=()=>{const a=randomWord();return String.fromCharCode(hexCharCodes[a>>>28],hexCharCodes[a>>>24&15],hexCharCodes[a>>>20&15],hexCharCodes[a>>>16&15],hexCharCodes[a>>>12&15],hexCharCodes[a>>>8&15],hexCharCodes[a>>>4&15],hexCharCodes[a&15])};var random16=()=>{const a=randomWord();const b=randomWord();return String.fromCharCode(hexCharCodes[a>>>28],hexCharCodes[a>>>24&15],hexCharCodes[a>>>20&15],hexCharCodes[a>>>16&15],hexCharCodes[a>>>12&15],hexCharCodes[a>>>8&15],hexCharCodes[a>>>4&15],hexCharCodes[a&15],hexCharCodes[b>>>28],hexCharCodes[b>>>24&15],hexCharCodes[b>>>20&15],hexCharCodes[b>>>16&15],hexCharCodes[b>>>12&15],hexCharCodes[b>>>8&15],hexCharCodes[b>>>4&15],hexCharCodes[b&15])};var random32=()=>{const a=randomWord();const b=randomWord();const c=randomWord();const d=randomWord();return String.fromCharCode(hexCharCodes[a>>>28],hexCharCodes[a>>>24&15],hexCharCodes[a>>>20&15],hexCharCodes[a>>>16&15],hexCharCodes[a>>>12&15],hexCharCodes[a>>>8&15],hexCharCodes[a>>>4&15],hexCharCodes[a&15],hexCharCodes[b>>>28],hexCharCodes[b>>>24&15],hexCharCodes[b>>>20&15],hexCharCodes[b>>>16&15],hexCharCodes[b>>>12&15],hexCharCodes[b>>>8&15],hexCharCodes[b>>>4&15],hexCharCodes[b&15],hexCharCodes[c>>>28],hexCharCodes[c>>>24&15],hexCharCodes[c>>>20&15],hexCharCodes[c>>>16&15],hexCharCodes[c>>>12&15],hexCharCodes[c>>>8&15],hexCharCodes[c>>>4&15],hexCharCodes[c&15],hexCharCodes[d>>>28],hexCharCodes[d>>>24&15],hexCharCodes[d>>>20&15],hexCharCodes[d>>>16&15],hexCharCodes[d>>>12&15],hexCharCodes[d>>>8&15],hexCharCodes[d>>>4&15],hexCharCodes[d&15])};var ParentSpanKey="effect/Tracer/ParentSpan";class ParentSpan extends Service()(ParentSpanKey,{fiberCached:true}){}var make7=(options)=>options;var DisablePropagation=Reference("effect/Tracer/DisablePropagation",{defaultValue:constFalse});var CurrentTraceLevel=Reference("effect/Tracer/CurrentTraceLevel",{defaultValue:()=>"Info"});var MinimumTraceLevel=Reference("effect/Tracer/MinimumTraceLevel",{defaultValue:()=>"All"});var TracerKey="effect/Tracer";var nativeTracer=make7({span:(options)=>new NativeSpan(options)});class NativeSpan{_tag="Span";sampled;name;parent;annotations;links;startTime;kind;status;_traceId=undefined;_spanId=undefined;_attributes=undefined;_events=undefined;constructor(options){this.name=options.name;this.parent=options.parent;this.annotations=options.annotations;this.links=options.links;this.startTime=options.startTime;this.kind=options.kind;this.sampled=options.sampled;this.status={_tag:"Started",startTime:options.startTime}}get traceId(){return this._traceId??=getOrUndefined(this.parent)?.traceId??random2(32)}get spanId(){return this._spanId??=random2(16)}get attributes(){return this._attributes??=new Map}get events(){return this._events??=[]}end(endTime,exit){if(this.status._tag==="Ended")return;this.status={_tag:"Ended",endTime,exit,startTime:this.status.startTime}}attribute(key,value){if(this.status._tag==="Ended")return;this.attributes.set(key,value)}event(name,startTime,attributes){if(this.status._tag==="Ended")return;this.events.push([name,startTime,attributes??{}])}addLinks(links){if(this.status._tag==="Ended")return;this.links.push(...links)}}var FiberRuntimeMetricsKey="effect/Metric/FiberRuntimeMetrics";var CurrentStackFrame=Reference("effect/References/CurrentStackFrame",{fiberCached:true,defaultValue:constUndefined});var TracerEnabled=Reference("effect/References/TracerEnabled",{fiberCached:true,defaultValue:constTrue});var TracerTimingEnabled=Reference("effect/References/TracerTimingEnabled",{defaultValue:constTrue});var TracerSpanAnnotations=Reference("effect/References/TracerSpanAnnotations",{defaultValue:()=>({})});var TracerSpanLinks=Reference("effect/References/TracerSpanLinks",{defaultValue:()=>[]});var CurrentLogAnnotations=Reference("effect/References/CurrentLogAnnotations",{defaultValue:()=>({})});var CurrentLogLevel=Reference("effect/References/CurrentLogLevel",{fiberCached:true,defaultValue:()=>"Info"});var MinimumLogLevel=Reference("effect/References/MinimumLogLevel",{fiberCached:true,defaultValue:()=>"Info"});var UnhandledLogLevel=Reference("effect/References/UnhandledLogLevel",{defaultValue:()=>"Error"});var CurrentLogSpans=Reference("effect/References/CurrentLogSpans",{defaultValue:()=>[]});var makeStackCleaner=(line)=>(stack)=>{let cache;return()=>{if(cache!==undefined)return cache;const trace=stack();if(!trace)return;const lines=trace.split(`
223
+ `);if(lines[line]!==undefined){cache=lines[line].trim();return cache}}};class Interrupt extends ReasonBase{constructor(fiberId,annotations=constEmptyAnnotations){super("Interrupt",annotations,"Interrupted");this.fiberId=fiberId}toString(){return`Interrupt(${this.fiberId})`}toJSON(){return{_tag:"Interrupt",fiberId:this.fiberId}}[symbol2](that){return isInterruptReason(that)&&this.fiberId===that.fiberId&&this.annotations===that.annotations}[symbol](){return string(`${this._tag}:${this.fiberId}`)}}var causeInterrupt=(fiberId)=>new CauseImpl([new Interrupt(fiberId)]);var hasFails=(self)=>self.reasons.some(isFailReason);var findError=(self)=>{for(let i=0;i<self.reasons.length;i++){const reason=self.reasons[i];if(reason._tag==="Fail"){return succeed2(reason.error)}}return fail2(self)};var hasDies=(self)=>self.reasons.some(isDieReason);var causeElectDefects=(self)=>hasDies(self)&&hasFails(self)?causeFromReasons(self.reasons.map((reason)=>reason._tag==="Fail"&&!isDone(reason.error)?new Die(reason.error,reason.annotations):reason)):self;var findRecoverableError=(self)=>hasDies(self)?fail2(causeElectDefects(self)):findError(self);var findDefect=(self)=>{const reason=self.reasons.find(isDieReason);return reason?succeed2(reason.defect):fail2(self)};var hasInterrupts=(self)=>self.reasons.some(isInterruptReason);var reasonAnnotations=(self)=>makeUnsafe(self.annotations);var causeMap=dual(2,(self,f)=>{let hasFail=false;const failures=self.reasons.map((failure)=>{if(isFailReason(failure)){hasFail=true;return new Fail(f(failure.error),failure.annotations)}return failure});return hasFail?causeFromReasons(failures):self});var causeSquash=(self)=>{let die;for(const reason of self.reasons){if(reason._tag==="Fail")return reason.error;if(reason._tag==="Die")die??=reason}if(die!==undefined)return die.defect;if(self.reasons.length>0)return new globalThis.Error("All fibers interrupted without error");return new globalThis.Error("Empty cause")};var causePrettyErrors=(self,options)=>{const errors=[];const interrupts=[];if(self.reasons.length===0)return errors;const prevStackLimit=getStackTraceLimit();if(prevStackLimit!==0)setStackTraceLimit(1);try{for(const failure of self.reasons){if(failure._tag==="Interrupt"){interrupts.push(failure);continue}errors.push(causePrettyError(failure._tag==="Die"?failure.defect:failure.error,failure.annotations,options))}if(errors.length===0){const cause=new Error("The fiber was interrupted by:");cause.name="InterruptCause";cause.stack=interruptCauseStack(cause,interrupts);const error=new globalThis.Error("All fibers interrupted without error",{cause});error.name="InterruptError";error.stack=`${error.name}: ${error.message}`;errors.push(causePrettyError(error,interrupts[0].annotations,options))}}finally{if(prevStackLimit!==0)setStackTraceLimit(prevStackLimit)}return errors};var causePrettyError=(original,annotations,options,seen=new Set)=>{const kind=typeof original;let error;if(original&&kind==="object"){seen.add(original);const cause=original.cause;error=new globalThis.Error(causePrettyMessage(original),{cause:cause!==undefined&&!seen.has(cause)?causePrettyError(cause,undefined,undefined,seen):undefined});if(typeof original.name==="string"){error.name=original.name}if(typeof original.stack==="string"){error.stack=cleanErrorStack(original.stack,error,annotations)}else{const stack=`${error.name}: ${error.message}`;error.stack=annotations?addStackAnnotations(stack,annotations):stack}if(options?.includeCauseInStack){error.stack=renderPrettyError(error)}for(const key of Object.keys(original)){if(!(key in error)){error[key]=original[key]}}}else{error=new globalThis.Error(!original?`Unknown error: ${original}`:kind==="string"?original:formatJson(original));const stack=`${error.name}: ${error.message}`;error.stack=annotations?addStackAnnotations(stack,annotations):stack}return error};var causePrettyMessage=(u)=>{if(typeof u.message==="string"){return u.message}else if(typeof u.toString==="function"&&u.toString!==Object.prototype.toString&&u.toString!==Array.prototype.toString){try{return u.toString()}catch{}}return formatJson(u)};var locationRegExp=/\((.*)\)/g;var cleanErrorStack=(stack,error,annotations)=>{const message=`${error.name}: ${error.message}`;const lines=(stack.startsWith(message)?stack.slice(message.length):stack).split(`
224
224
  `);const out=[message];for(let i=1;i<lines.length;i++){if(/Generator\.next|~effect\/(?:Effect|Utils)/.test(lines[i])){break}out.push(lines[i])}return annotations?addStackAnnotations(out.join(`
225
225
  `),annotations):out.join(`
226
226
  `)};var addStackAnnotations=(stack,annotations)=>{const frame=annotations?.get(StackTraceKey.key);if(frame){stack=`${stack}
@@ -233,17 +233,17 @@ ${renderErrorCause(e.cause," ")}
233
233
  `);let stack=`${prefix}[cause]: ${lines[0]}`;for(let i=1,len=lines.length;i<len;i++){stack+=`
234
234
  ${prefix}${lines[i]}`}if(cause.cause){stack+=` {
235
235
  ${renderErrorCause(cause.cause,`${prefix} `)}
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(flatMap3(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=flatMap3(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)?flatMap3(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 flatMap3(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 flatMap3=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 flatMap3(self,f)});var flatten3=(self)=>flatMap3(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:flatMap3(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)=>flatMap3(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)=>flatMap3(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?flatMap3(eff,(_)=>exit):exit},[contE](cause,_,exit){exit??=exitFailCause(cause);let eff;try{eff=this.onExit(exit)}catch(defect){eff=exitDie(defect)}return eff?flatMap3(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)=>flatMap3(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)=>flatMap3(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?flatMap3(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 flatMap3(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)=>flatMap3(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 flatMap4=flatMap3;var flatten4=flatten3;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 make8=()=>({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 make9=(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=make8();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)=>make9({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),flatMap4((channel)=>toTransform(channel)(upstream,scope)),flatMap4((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(flatMap4(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(flatMap4(self.transform(upstream,scope),done2)));var forEach3=(f)=>forEachArray(forEach2((_)=>f(_),{discard:true}));var forEachArray=(f)=>fromTransform2((upstream)=>upstream.pipe(flatMap4(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 make10=(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)=>flatMap4(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(flatMap4(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)=>flatMap4(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 flatMap4(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 flatMap4(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 flatMap4(this.append?succeed6(undefined):positionToNumber(position,"writeAll"),(nodePosition)=>flatMap4(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)=>flatMap4(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)=>make10({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
- `)){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 make11=(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
- `)}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 String3(){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(),String3());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 String4=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 String4;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 flatMap4(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)&&parameter.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 flatMap4(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):flatMap4(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):flatMap4(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 flatMap4(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=flatMap4(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=flatMap4(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 make12(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=make12(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 make13(ast,this[RebuildOptions])}};function make13(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 make13(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)=>make13(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"),String3()));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 make14(new Declaration(typeParameters.map(getAST),(typeParameters)=>run(typeParameters.map((ast)=>make14(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))}}var decodeEffect2=decodeUnknownEffect2;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 make14=make13;function isSchema(u){return hasProperty(u,TypeId19)&&u[TypeId19]===TypeId19}var optionalKey2=lambda((schema)=>make14(optionalKey(schema.ast),{schema}));var optional2=lambda((self)=>{const schema=UndefinedOr(self);return make14(optional(self.ast),{schema})});function Literal2(literal){const out=make14(new Literal(literal),{literal,transform(to){return out.pipe(decodeTo2(Literal2(to),{decode:transform(()=>to),encode:transform(()=>literal)}))}});return out}var Unknown2=make14(unknown);var Null2=make14(null_);var Undefined2=make14(undefined_2);var String5=make14(string2);var Number5=make14(number2);var Boolean3=make14(boolean);function makeStruct(ast,fields){return make14(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 make14(record(key.ast,value.ast),{key,value})}function makeTuple(ast,elements){return make14(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)=>make14(new Arrays(false,[],[schema.ast]),{value:schema}));function makeUnion(ast,members){return make14(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 make14(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 NullOr=lambda((self)=>Union2([self,Null2]));var UndefinedOr=lambda((self)=>Union2([self,Undefined2]));function brand(identifier){return(schema)=>make14(schema.ast,{schema,identifier})}function decodeTo2(to,transformation){return(from)=>{return make14(decodeTo(from.ast,to.ast,transformation?makeTransformation(transformation):passthrough2()),{from,to})}}function withConstructorDefault2(defaultValue){return(schema)=>make14(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=make14(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 isNonEmpty(annotations){return makeIsMinLength(1,1,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 NonEmptyString=String5.check(isNonEmpty());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:String5,flags:String5}),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=String5.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=String5.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:String5.check(isBase64()),type:String5,name:String5,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([String5,Union2([Struct({_tag:tag("String"),value:String5}),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()(String5.annotate({expected:"a query string that will be decoded as URLSearchParams"}),transform2({decode:(e)=>new globalThis.URLSearchParams(e),encode:(params)=>params.toString()}))});var Base64String=String5.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)=>make11(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)=>make11(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 make14(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 make12(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=make14(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=make14(annotate(Json,{toCode:()=>({runtime:"Schema.Json",Type:"Schema.Json"})}));var JsonObject=Record(String5,Json2);import{chmodSync as chmodSync2,existsSync as existsSync10,readFileSync as readFileSync9,realpathSync as realpathSync5,renameSync as renameSync2,statSync as statSync3,writeFileSync as writeFileSync7}from"fs";import{rename as rename3}from"fs/promises";import{homedir,hostname}from"os";import{createInterface}from"readline/promises";import{pathToFileURL as pathToFileURL5}from"url";var name="@collective-intelligence/cli";var version="0.1.28";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,`
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?causeAddInterrupts(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;try{return asyncContext.runInAsyncScope(this.evaluate,this,effect)}finally{asyncContext.emitDestroy()}}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(flatMap3(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){try{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=flatMap3(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)}`)}current=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 thunk=this[args];const value=thunk();const cont=fiber.getCont(contA);return cont?cont[contA](value,fiber):fiber.yieldWith(exitSucceed(value))}});var suspend=makePrimitive({op:"Suspend",[evaluate](_fiber){const thunk=this[args];return thunk()}});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 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 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.yieldWith(()=>{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)?flatMap3(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 fnBody=(bodyOrOptions,pipeables)=>typeof bodyOrOptions==="function"?bodyOrOptions:pipeables.shift().bind(bodyOrOptions.self);var fnUntraced=(bodyOrOptions,...pipeables)=>{const body=fnBody(bodyOrOptions,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=fnBody(bodyOrOptions,pipeables);const definitionName=`${name} (definition)`;const definitionStack=defError?fnStackCleaner(()=>defError.stack):constUndefined;const makeCallFrame=(callError)=>(prev)=>({name,stack:callError?fnStackCleaner(()=>callError.stack):constUndefined,parent:{name:definitionName,stack:definitionStack,parent:prev}});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,makeCallFrame(callError))})};var fnUntracedEager=(bodyOrOptions,...pipeables)=>{const body=fnBody(bodyOrOptions,pipeables);return 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 flatMap3(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 limit=getStackTraceLimit();if(limit===0)return false;const marker="~effect/Effect/stackProbe";const probe={[marker]:function stackProbe(){return new Error}};setStackTraceLimit(1);const error=probe[marker]();setStackTraceLimit(limit);return error.stack?.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)=>map3(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 flatMap3=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 flatMap3(self,f)});var flatten3=(self)=>flatMap3(self,identity);var map3=dual(2,(self,f)=>new ContImpl(self,mapCont,f));var mapEager=dual(2,(self,f)=>effectIsExit(self)?exitMap(self,f):map3(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=findRecoverableError(self.cause);if(isFailure2(error))return exitFailCause(error.failure);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;return exitFailCause(causeMap(self.cause,f))});var exitMapBoth=dual(2,(self,options)=>{if(self._tag==="Success")return exitSucceed(options.onSuccess(self.value));return exitFailCause(causeMap(self.cause,options.onFailure))});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 zipWith2=dual((args)=>isEffect(args[1]),(self,that,f,options)=>options?.concurrent?map3(all([self,that],{concurrency:2}),([a,a2])=>f(a,a2)):flatMap3(self,(a)=>map3(that,(a2)=>f(a,a2))));var forever=dual((args)=>isEffect(args[0]),(self,options)=>whileLoop({while:constTrue,body:constant(options?.disableYield?self:flatMap3(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,findRecoverableError,(e)=>f(e)));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=findRecoverableError(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 catchReason=dual((args)=>isEffect(args[0]),(self,errorTag,reasonTag,f,orElse)=>catchIf(self,(e)=>isTagged(e,errorTag)&&hasProperty(e,"reason")&&(orElse!==undefined||isTagged(e.reason,reasonTag)),(e)=>{const reason=e.reason;if(isTagged(reason,reasonTag))return f(reason,e);return orElse?orElse(reason,e):fail3(e)}));var mapError=dual(2,(self,f)=>catchCause(self,(cause)=>failCause(causeMap(cause,f))));var mapBoth=dual(2,(self,options)=>matchCauseEffect(self,{onFailure:(cause)=>failCause(causeMap(cause,options.onFailure)),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 ignoreCauseLogger=(log)=>log==="Unhandled"?(...message)=>withFiber((fiber)=>{const level=fiber.getRef(UnhandledLogLevel);return level===undefined?void_:logWithLevel(level)(...message)}):logWithLevel(log===true?undefined:log);var ignore=dual((args)=>isEffect(args[0]),(self,options)=>{if(!options?.log){return matchEffect(self,{onFailure:(_)=>void_,onSuccess:(_)=>void_})}const logEffect=ignoreCauseLogger(options.log);return matchCauseEffect(self,{onFailure(cause){const error=findRecoverableError(cause);return isFailure2(error)?failCause(error.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 error=findRecoverableError(cause);if(isFailure2(error))return failCause(error.failure);const handlers=this.payload;return fiber.succeedWith(continuationMarksStack?handlers.onFailure(error.success):internalCall(()=>handlers.onFailure(error.success)))});var matchEffect=dual(2,(self,options)=>matchCauseEffect(self,{onFailure:(cause)=>{const error=findRecoverableError(cause);return isFailure2(error)?failCause(error.failure):options.onFailure(error.success)},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=findRecoverableError(self.cause);if(isFailure2(error))return exitFailCause(error.failure);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)=>flatMap3(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)=>{fiberEnterUninterruptibleUnsafe(fiber);return scopeCloseUnsafe(self,exit_)??void_});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(causeElectDefects(causeCombine(exit_.cause,cause))));var scopeCloseFinalizers=fnUntraced(function*(self,finalizers,exit_){let exits=[];const fibers=[];const arr=Array.from(finalizers);const parent=getCurrentFiber();for(let i=arr.length-1;i>=0;i--){const[key,finalizer]=arr[i];if(self.strategy==="sequential"){exits.push(yield*exit(runFinalizer(finalizer,exit_)))}else if(key!==parent){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)=>flatMap3(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?flatMap3(eff,(_)=>exit):exit},[contE](cause,_,exit){exit??=exitFailCause(cause);let eff;try{eff=this.onExit(exit)}catch(defect){eff=exitDie(defect)}return eff?flatMap3(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)=>flatMap3(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(()=>map3(forEach(Object.entries(arg),([key,effect])=>map3(options?.mode==="result"?result(effect):effect,(value)=>[key,value]),{concurrency:options?.concurrency}),Object.fromEntries))};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)=>flatMap3(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?flatMap3(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 flatMap3(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"?causeElectDefects(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(!daemon){parentRuntime.children().add(child);child._parent=parentRuntime}if(immediate){child.evaluate(effect)}else{child._asyncContext=captureAsyncContext();parentRuntime.currentDispatcher.scheduleTask(()=>child.evaluate(effect),0)}return child};var fiberScopeFinalizer=(fiber)=>()=>withFiber((current)=>current===fiber?void_:fiberInterrupt(fiber));var forkIn=dual((args)=>isEffect(args[0]),(self,scope,options)=>withFiber((parent)=>{const fiber=scope.state._tag==="Closed"?new FiberImpl(parent.context):forkUnsafe(parent,self,options?.startImmediately,true,options?.uninterruptible);if(!fiber._exit){if(scope.state._tag!=="Closed"){scopeAddFinalizerUnsafe(scope,fiber,fiberScopeFinalizer(fiber));fiber.addObserver(()=>scopeRemoveFinalizerUnsafe(scope,fiber))}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??false,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"||span.status._tag==="Ended")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 makeFailReason=(error)=>new Fail(error);var makeDieReason=(defect)=>new Die(defect);var map4=causeMap;var squash=causeSquash;var isDone2=isDone;var done2=done;var reasonAnnotations2=reasonAnnotations;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(map3(suspend(()=>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(map3(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(map3((context)=>mergeAll(...context)))};var mergeAll2=(...layers)=>fromBuildMemo((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)=>flatMap3(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 flatMap4=flatMap3;var flatten4=flatten3;var andThen2=andThen;var tap2=tap;var result2=result;var option2=option;var exit2=exit;var map5=map3;var as2=as;var asVoid2=asVoid;var zipWith3=zipWith2;var catch_2=catch_;var catchTag2=catchTag;var catchReason2=catchReason;var catchCause2=catchCause;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)=>{let synchronous=true;let pending;try{fn(...args,(err,result)=>{const effect=err?onError?suspend2(()=>fail6(onError(err,args))):fail6(err):succeed6(result);if(synchronous){pending??=effect}else{resume(effect)}})}catch(err){pending=onSyncError?fail6(onSyncError(err,args)):die3(err)}synchronous=false;if(pending){resume(pending)}});var mapEager2=mapEager;var mapErrorEager2=mapErrorEager;var mapBothEager2=mapBothEager;var flatMapEager2=flatMapEager;var catchEager2=catchEager;var fnUntracedEager2=fnUntracedEager;var maxExpansions=1e4;var maxExpandedLength=2**22;var maxBraceDepth=64;var compile=(patterns,dot)=>{const nodes=[];const starts=new Set;for(const pattern of patterns){for(const expanded of expandBraces(pattern)){const start=nodes.length;if(compilePattern(expanded,nodes)){starts.add(start)}}}return{nodes,initial:closure(nodes,starts),dot}};var isUnc=(path)=>path.startsWith("//")&&path[2]!==undefined&&path[2]!=="/";var compilePattern=(pattern,nodes)=>{if(pattern===""||isUnc(pattern)){return false}const raw=splitSegments(pattern);const globstar=raw.indexOf("**");if(globstar!==-1&&raw.some((segment,i)=>i>globstar&&(segment==="."||segment===".."))){return false}const{directory,segments}=normalize2(raw);if(segments.length===0){return false}for(const segment of segments){if(segment!=="**"){nodes.push(compileSegment(Array.from(segment)))}else if(nodes[nodes.length-1]!==globstarNode){nodes.push(globstarNode)}}nodes.push({_tag:"End",directoryOnly:directory});return true};var globstarNode={_tag:"Globstar"};var splitSegments=(pattern)=>{const segments=[];let start=0;for(let i=0;i<pattern.length;i++){if(pattern[i]==="\\"){i++}else if(pattern[i]==="/"){segments.push(pattern.slice(start,i));start=i+1}}segments.push(pattern.slice(start));return segments};var drive=/^[A-Za-z]:/;var isDrive=(segment)=>segment.length===2&&drive.test(segment);var isRoot=(name)=>name===""||name.length===3&&name[2]==="/"&&drive.test(name);var isAbsolute=(path)=>path.startsWith("/")||path[2]==="/"&&drive.test(path);var normalize2=(raw)=>{const segments=[];let i=0;if(raw.length>1&&(raw[0]===""||isDrive(raw[0]))){segments.push(raw[0]===""?"":`${raw[0]}/`);i=1}let directory=false;for(;i<raw.length;i++){const segment=raw[i];if(segment===""||segment==="."){directory=i===raw.length-1&&segments.length>0}else{segments.push(segment);directory=false}}if(segments.length===0&&raw.includes(".")){segments.push(".")}return{segments,directory}};var compileSegment=(chars)=>{const tokens=[];let literal="";let magic=false;let classes=true;for(let i=0;i<chars.length;i++){const char=chars[i];if(char==="\\"&&i+1<chars.length){literal+=chars[++i];tokens.push({_tag:"Char",value:chars[i]})}else if(char==="*"){magic=true;if(tokens[tokens.length-1]?._tag!=="Star"){tokens.push({_tag:"Star"})}}else if(char==="?"){magic=true;tokens.push({_tag:"Any"})}else if(char==="["&&classes){const parsed=parseClass(chars,i);if(parsed===undefined){classes=false;literal+=char;tokens.push({_tag:"Char",value:char})}else{magic=true;tokens.push(parsed.token);i=parsed.end}}else{literal+=char;tokens.push({_tag:"Char",value:char})}}if(!magic){return{_tag:"Literal",value:literal}}const first=tokens[0];return{_tag:"Wildcard",tokens,leadingDot:first._tag==="Char"&&first.value==="."}};var range=(from,to)=>[from.codePointAt(0),to.codePointAt(0)];var posixClasses={alnum:[...range("0","9"),...range("A","Z"),...range("a","z")],alpha:[...range("A","Z"),...range("a","z")],blank:[9,9,32,32],cntrl:[0,31,127,127],digit:range("0","9"),graph:[33,126],lower:range("a","z"),print:[32,126],punct:[33,47,58,64,91,96,123,126],space:[9,13,32,32],upper:range("A","Z"),word:[...range("0","9"),...range("A","Z"),95,95,...range("a","z")],xdigit:[...range("0","9"),...range("A","F"),...range("a","f")]};var parsePosixClass=(chars,open)=>{for(let i=open+2;i<chars.length&&i<=open+8;i++){if(chars[i]===":"&&chars[i+1]==="]"){const ranges=posixClasses[chars.slice(open+2,i).join("")];return ranges===undefined?undefined:{ranges,end:i+1}}}return};var parseClass=(chars,open)=>{let i=open+1;const negated=chars[i]==="!"||chars[i]==="^";if(negated){i++}const ranges=[];for(let first=true;i<chars.length;i++,first=false){let char=chars[i];if(char==="/"){return}if(char==="]"&&!first){return{token:{_tag:"Class",ranges,negated},end:i}}if(char==="["&&chars[i+1]===":"){const posix=parsePosixClass(chars,i);if(posix!==undefined){ranges.push(...posix.ranges);i=posix.end;continue}}if(char==="\\"&&i+1<chars.length){char=chars[++i]}if(chars[i+1]==="-"&&i+2<chars.length&&chars[i+2]!=="]"){let next=i+2;if(chars[next]==="/"){return}if(chars[next]==="\\"&&next+1<chars.length){next++}ranges.push(...range(char,chars[next]));i=next;continue}ranges.push(...range(char,char))}return};var expandBraces=(pattern)=>{const chars=Array.from(pattern);const groups=matchBraceGroups(chars);if(groups.size===0){return[pattern]}const sequence=parseBraceSequence(chars,0,chars.length,groups,0);if(sequence===undefined){return[pattern]}const count=countExpansions(sequence);return count>maxExpansions||count*pattern.length>maxExpandedLength?[pattern]:expandSequence(sequence)};var matchBraceGroups=(chars)=>{const groups=new Map;const stack=[];let classes=true;for(let i=0;i<chars.length;i++){const char=chars[i];if(char==="\\"){i++}else if(char==="/"){classes=true}else if(char==="["&&classes){const parsed=parseClass(chars,i);if(parsed===undefined){classes=false}else{i=parsed.end}}else if(char==="{"){stack.push({open:i,commas:[]})}else if(char===","){stack[stack.length-1]?.commas.push(i)}else if(char==="}"){const group=stack.pop();if(group!==undefined&&group.commas.length>0){groups.set(group.open,{commas:group.commas,close:i})}}}return groups};var parseBraceSequence=(chars,start,end,groups,depth)=>{if(depth>maxBraceDepth){return}const parts=[];let text="";for(let i=start;i<end;i++){const group=groups.get(i);if(group===undefined){if(chars[i]==="\\"&&i+1<end){text+=chars[i++]}text+=chars[i];continue}const alternatives=[];let from=i+1;for(const to of[...group.commas,group.close]){const alternative=parseBraceSequence(chars,from,to,groups,depth+1);if(alternative===undefined){return}alternatives.push(alternative);from=to+1}if(text!==""){parts.push(text);text=""}parts.push(alternatives);i=group.close}if(text!==""){parts.push(text)}return parts};var countExpansions=(sequence)=>{let count=1;for(const part of sequence){if(typeof part!=="string"){let sum=0;for(const alternative of part){sum+=countExpansions(alternative)}count*=sum;if(count>maxExpansions){return Infinity}}}return count};var expandSequence=(sequence)=>{let out=[""];for(const part of sequence){if(typeof part==="string"){out=out.map((prefix)=>prefix+part)}else{const alternatives=part.flatMap(expandSequence);out=out.flatMap((prefix)=>alternatives.map((alternative)=>prefix+alternative))}}return out};var matchToken=(token,char)=>{switch(token._tag){case"Char":return token.value===char;case"Any":return true;case"Star":return false;case"Class":{const code=char.codePointAt(0);let found=false;for(let i=0;i<token.ranges.length&&!found;i+=2){found=code>=token.ranges[i]&&code<=token.ranges[i+1]}return found!==token.negated}}};var matchWildcard=(node,name,chars,dot)=>{if(name==="."||name===".."||name.startsWith(".")&&!dot&&!node.leadingDot){return false}const{tokens}=node;let t=0;let c=0;let star=-1;let resume=0;while(c<chars.length){if(tokens[t]?._tag==="Star"){star=t++;resume=c}else if(t<tokens.length&&matchToken(tokens[t],chars[c])){t++;c++}else if(star!==-1){t=star+1;c=++resume}else{return false}}while(tokens[t]?._tag==="Star"){t++}return t===tokens.length};var closure=(nodes,states)=>{for(const state of states){if(nodes[state]._tag==="Globstar"){states.add(state+1)}}return states};var step=(compiled,states,name)=>{const explicit=new Set;const viaGlobstar=new Set;const root=isRoot(name);let chars;for(const state of states){const node=compiled.nodes[state];switch(node._tag){case"Globstar":{if(!root&&name!=="."&&name!==".."&&(compiled.dot||!name.startsWith("."))){viaGlobstar.add(state)}break}case"Literal":{if(node.value===name){explicit.add(state+1)}break}case"Wildcard":{if(!root&&matchWildcard(node,name,chars??=Array.from(name),compiled.dot)){explicit.add(state+1)}break}}}return{explicit:closure(compiled.nodes,explicit),globstar:closure(compiled.nodes,viaGlobstar)}};var union=(step)=>{if(step.globstar.size===0){return step.explicit}const states=new Set(step.explicit);for(const state of step.globstar){states.add(state)}return states};var accepts=(compiled,states,isDirectory)=>{for(const state of states){const node=compiled.nodes[state];if(node._tag==="End"&&(isDirectory||!node.directoryOnly)){return true}}return false};var canDescend=(compiled,states)=>{for(const state of states){if(compiled.nodes[state]._tag!=="End"){return true}}return false};var needsDirectory=(compiled,states)=>{for(const state of states){const node=compiled.nodes[state];if(node._tag==="End"&&node.directoryOnly){return true}}return false};var join=(parent,name)=>{if(parent===""){return name===""?"/":name}return parent.endsWith("/")?parent+name:`${parent}/${name}`};var isMissing=(error)=>error.reason._tag==="NotFound"||error.reason._tag==="BadResource";var isIgnorable=(error)=>isMissing(error)||error.reason._tag==="PermissionDenied";var isNotLink=(error)=>isIgnorable(error)||error.reason._tag==="Unknown";var byName=mapInput(String2,(entry)=>entry.name);var make8=(fs)=>(pattern,options)=>walk(fs,compile([pattern],options?.dot??false),options);var walk=fnUntraced2(function*(fs,compiled,options){if(compiled.initial.size===0){return[]}const root=options?.root??"";const excludes=compile(options?.exclude??[],true);const excludeNeedsDirectory=excludes.nodes.some((node)=>node._tag==="End"&&node.directoryOnly);const toFsPath=(relative)=>isAbsolute(relative)?relative:relative===""?root===""?".":root:join(root,relative);const isUnlisted=(value)=>value==="."||value===".."||isRoot(value);const probe=(parent,name,named)=>{const path=toFsPath(join(parent,name));return fs.stat(path).pipe(map5((info)=>info.type),catchReason2("PlatformError","NotFound",()=>fs.readLink(path).pipe(as2("SymbolicLink"),catchIf2(isNotLink,()=>succeed6(undefined)))),catchIf2(named?isMissing:isIgnorable,()=>succeed6(undefined)),map5((type)=>type===undefined?undefined:{name,type}))};const entries=(relative,states,named)=>{const literals=new Set;let listed=!named;for(const state of states){const node=compiled.nodes[state];if(node._tag==="Literal"){literals.add(node.value)}else if(node._tag!=="End"){listed=true}}const probed=listed?[...literals].filter(isUnlisted):[...literals];return zipWith3(listed?catchIf2(fs.readDirectoryEntries(toFsPath(relative)),named?isMissing:isIgnorable,()=>succeed6([])):succeed6([]),forEach2(probed,(name)=>probe(relative,name,named),{concurrency:16}),(listing,found)=>({entries:sort([...listing,...found.filter(isNotUndefined)],byName),named:named&&!listed}))};const visit=fnUntraced2(function*({name,type},parent,states,excluded){const result=step(compiled,states,name);const next=union(result);if(next.size===0){return}const relative=join(parent,name);const nextExcluded=union(step(excludes,excluded,name));const descend=canDescend(compiled,next);const isDirectory=!descend&&!needsDirectory(compiled,next)&&!excludeNeedsDirectory?false:type!=="Unknown"&&type!=="SymbolicLink"?type==="Directory":yield*fs.stat(toFsPath(relative)).pipe(map5((info)=>info.type==="Directory"),catchIf2(isIgnorable,()=>succeed6(false)));const accepted=accepts(compiled,next,isDirectory);if(!accepted&&(!isDirectory||!descend)||accepts(excludes,nextExcluded,isDirectory)){return}const child=(next)=>({relative,accepted,excluded:nextExcluded,next});if(!isDirectory||!descend){return child(undefined)}if(result.globstar.size===0){return child(next)}const followed=canDescend(compiled,result.explicit)?result.explicit:undefined;if(type!=="Unknown"){return child(type==="SymbolicLink"?followed:next)}return yield*fs.readLink(toFsPath(relative)).pipe(as2(child(followed)),catchIf2(isNotLink,()=>succeed6(child(next))))});const directory=fnUntraced2(function*(relative,states,excluded,named,out){const listing=yield*entries(relative,states,named);const children=yield*forEach2(listing.entries,(entry)=>visit(entry,relative,states,excluded),{concurrency:16});for(const child of children){if(child===undefined){continue}if(child.accepted){out.push(child.relative)}if(child.next!==undefined){yield*directory(child.relative,child.next,child.excluded,listing.named,out)}}});const out=[];yield*directory("",compiled.initial,excludes.initial,true,out);return out});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 make9=()=>({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 make10=(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=make9();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 failCause4=dual(2,(self,cause)=>sync(()=>failCauseUnsafe(self,cause)));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 suspendTake(()=>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 suspendTake=makePrimitive({op:"QueueTake",[evaluate](fiber){const effect=this[args]();return isExit(effect)?effect[evaluate](fiber):effect}});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([]))}const state=self.state;if(state._tag==="Done"){return isDoneCause(state.exit.cause)}}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)=>make10({capacity:options?.bufferSize,strategy:options?.strategy}).pipe(tap2((queue)=>addFinalizer(scope,shutdown(queue))),tap2((queue)=>provide(f(queue),scope).pipe(catchCause2((cause)=>failCause4(queue,cause)),forkIn2(scope,{startImmediately:true}))));var callbackArray=(f,options)=>fromTransform((_,scope)=>map5(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),flatMap4((channel)=>toTransform(channel)(upstream,scope)),flatMap4((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(flatMap4(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(flatMap4(self.transform(upstream,scope),done2)));var forEach3=(f)=>forEachArray(forEach2((_)=>f(_),{discard:true}));var forEachArray=(f)=>fromTransform2((upstream)=>upstream.pipe(flatMap4(f),forever2({disableYield:true}),catchDone(()=>endVoid)));var unwrap2=(effect)=>fromChannel2(unwrap(map5(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(map5(effect,toChannel2)));var TypeId12="~effect/FileSystem";var FileSystem=Service("effect/FileSystem");var make11=(impl)=>FileSystem.of({...impl,[TypeId12]:TypeId12,glob:make8(impl),exists:(path)=>pipe(impl.access(path),as2(true),catchTag2("PlatformError",(e)=>e.reason._tag==="NotFound"?succeed6(false):fail6(e))),readFileString:(path,encoding)=>flatMap4(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(flatMap4(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"}),map5((file)=>forEach3((_)=>file.writeAll(_))),unwrap2),writeFileString:(path,data,options)=>flatMap4(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":case"EPERM":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 toUint64=(value)=>BigInt.asUintN(64,value);var toUint64Option=(value)=>map(fromNullishOr(value),toUint64);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 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,force:true})))})();var openFlagBits=(flag)=>{const{O_APPEND,O_CREAT,O_EXCL,O_RDONLY,O_RDWR,O_TRUNC,O_WRONLY}=NFS.constants;switch(flag){case"r":return O_RDONLY;case"r+":return O_RDWR;case"w":return O_TRUNC|O_CREAT|O_WRONLY;case"wx":return O_TRUNC|O_CREAT|O_WRONLY|O_EXCL;case"w+":return O_TRUNC|O_CREAT|O_RDWR;case"wx+":return O_TRUNC|O_CREAT|O_RDWR|O_EXCL;case"a":return O_APPEND|O_CREAT|O_WRONLY;case"ax":return O_APPEND|O_CREAT|O_WRONLY|O_EXCL;case"a+":return O_APPEND|O_CREAT|O_RDWR;case"ax+":return O_APPEND|O_CREAT|O_RDWR|O_EXCL}};var noFollowFlags=(method,flag)=>suspend2(()=>{const{O_NOFOLLOW}=NFS.constants;if(process.platform==="win32"||typeof O_NOFOLLOW!=="number"||O_NOFOLLOW===0){return fail6(badArgument({module:"FileSystem",method,description:"noFollow is not supported on this platform"}))}return succeed6(openFlagBits(flag)|O_NOFOLLOW)});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(options?.noFollow===true?flatMap4(noFollowFlags(method,options.flag??"r"),(flags)=>nodeOpen(path,flags,options.mode)):nodeOpen(path,options?.flag??"r",options?.mode),(fd)=>orDie2(nodeClose(fd))),map5((fd)=>makeFile(fd,options?.flag?.startsWith("a")??false)))};var open2=openFactory("open");var negativePosition=(method)=>badArgument({module:"FileSystem",method,description:"Cannot read before the start of the file"});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 flatMap4(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,options){return suspend2(()=>{const explicit=options?.position;if(explicit!==undefined){return explicit<BigInt(0)?fail6(negativePosition("read")):nodeRead(this.fd,{buffer,position:explicit})}const position=this.position;return map5(nodeRead(this.fd,{buffer,position}),(bytesRead)=>{this.position=position+BigInt(bytesRead);return bytesRead})})}readAlloc(size,options){return suspend2(()=>{try{if(!Number.isInteger(size)||size<0){throw new RangeError("size must be a non-negative integer")}const explicit=options?.position;if(explicit!==undefined&&explicit<BigInt(0)){return fail6(negativePosition("readAlloc"))}const buffer=Buffer.allocUnsafeSlow(size);const position=explicit??this.position;return map5(nodeReadAlloc(this.fd,{buffer,position}),(bytesRead)=>{if(bytesRead===0){return none2()}if(explicit===undefined){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 map5(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 flatMap4(this.append?succeed6(undefined):positionToNumber(position,"write"),(nodePosition)=>map5(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 flatMap4(this.append?succeed6(undefined):positionToNumber(position,"writeAll"),(nodePosition)=>flatMap4(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,force:true})))})();var readDirectory=(path,options)=>tryPromise2({try:()=>NFS.promises.readdir(path,options),catch:(err)=>handleErrnoException("FileSystem","readDirectory")(err,[path])});var readDirectoryEntries=(path)=>tryPromise2({try:()=>NFS.promises.readdir(path,{withFileTypes:true}),catch:(err)=>handleErrnoException("FileSystem","readDirectoryEntries")(err,[path])}).pipe(map5((entries)=>entries.map((entry)=>({name:entry.name,type:fileType(entry)}))));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(process.platform==="win32"?NFS.realpath.native: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 fileType=(stat)=>stat.isFile()?"File":stat.isDirectory()?"Directory":stat.isSymbolicLink()?"SymbolicLink":stat.isBlockDevice()?"BlockDevice":stat.isCharacterDevice()?"CharacterDevice":stat.isFIFO()?"FIFO":stat.isSocket()?"Socket":"Unknown";var makeFileInfo=(stat,method="stat")=>try_2({try:()=>({type:fileType(stat),mtime:fromNullishOr(stat.mtime),atime:fromNullishOr(stat.atime),birthtime:fromNullishOr(stat.birthtime),dev:toUint64(stat.dev),rdev:toUint64Option(stat.rdev),ino:toUint64Option(stat.ino),mode:bigintToNumber(stat.mode,"mode"),nlink:toUint64Option(stat.nlink),uid:bigintToNumberOption(stat.uid),gid:bigintToNumberOption(stat.gid),size:bytes(stat.size),blksize:stat.blksize!==undefined?some2(bytes(stat.blksize)):none2(),blocks:fromNullishOr(stat.blocks)}),catch:handleBadArgument(method)});var statFactory=(method,nodeStatFn)=>{const nodeStat=effectify(nodeStatFn,handleErrnoException("FileSystem",method),handleBadArgument(method));return(path)=>flatMap4(nodeStat(path,{bigint:true}),(stat)=>makeFileInfo(stat,method))};var stat2=statFactory("stat",NFS.stat);var lstat2=statFactory("lstat",NFS.lstat);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())).pipe(tap2(()=>sync2(()=>options?.onReady?.()))));var watch2=(backend,path,options)=>all2([stat2(path),serviceOption2(WatchBackend)]).pipe(map5(([stat,callerBackend])=>orElse(callerBackend,()=>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=map5(serviceOption2(WatchBackend),(backend)=>make11({access:access2,chmod:chmod2,chown:chown2,copy,copyFile:copyFile2,link:link2,lstat:lstat2,makeDirectory,makeTempDirectory,makeTempDirectoryScoped,makeTempFile,makeTempFileScoped,open:open2,readDirectory,readDirectoryEntries,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");var make12=(impl)=>Path2.of({...impl,[TypeId13]:TypeId13,resolveWithin(root,input){if(impl.parse(input).root!=="")return none2();const base=impl.resolve(root);const candidate=impl.resolve(base,input);const relative=impl.relative(base,candidate);return relative===".."||relative.startsWith(`..${impl.sep}`)||impl.isAbsolute(relative)?none2():some2(candidate)}});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 try_2({try:()=>decodeURIComponent(pathname),catch:(cause)=>new BadArgument({module:"Path",method:"fromFileUrl",cause})})}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
+ `)){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=make12({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)(make12({...NodePath.posix,...fileUrlOps(false)}));var layerWin32=succeed5(Path2)(make12({...NodePath.win32,...fileUrlOps(true)}));var layer4=succeed5(Path2)(make12({...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;const toBase64=Uint8Array.prototype.toBase64;if(length>=32&&typeof toBase64==="function")return toBase64.call(bytes);return length<128?encodeShort(bytes):encodeLong(bytes)};var encodeShort=(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 encodeLong=(bytes)=>{const length=bytes.length;const result=new Uint8Array(Math.ceil(length/3)*4);let i;let j=0;for(i=2;i<length;i+=3,j+=4){result[j]=alphabetCodes[bytes[i-2]>>2];result[j+1]=alphabetCodes[(bytes[i-2]&3)<<4|bytes[i-1]>>4];result[j+2]=alphabetCodes[(bytes[i-1]&15)<<2|bytes[i]>>6];result[j+3]=alphabetCodes[bytes[i]&63]}if(i===length+1){result[j]=alphabetCodes[bytes[i-2]>>2];result[j+1]=alphabetCodes[(bytes[i-2]&3)<<4];result[j+2]=paddingCode;result[j+3]=paddingCode}if(i===length){result[j]=alphabetCodes[bytes[i-2]>>2];result[j+1]=alphabetCodes[(bytes[i-2]&3)<<4|bytes[i-1]>>4];result[j+2]=alphabetCodes[(bytes[i-1]&15)<<2];result[j+3]=paddingCode}return decoder.decode(result)};var encoder=new TextEncoder;var decoder=new TextDecoder;var stripCrlf=(str)=>str.replace(/[\n\r]/g,"");var alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var alphabetCodes=encoder.encode(alphabet);var paddingCode=61;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 make13=(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,map2(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)??findMessage(issue.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 getFilterMessage(issue,checkHook){const message=checkHook(issue);if(message!==undefined||issue.issue._tag!=="InvalidValue")return message;const expected=findExpected(issue.issue);return expected===undefined?getExpectedMessage(formatCheck(issue.filter),issue):getExpectedMessage(expected,issue.issue)}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,messageOverride){let message;switch(issue._tag){case"Filter":return formatIssue(issue.issue,path,messageOverride??getFilterMessage(issue,defaultCheckHook));case"Encoding":return formatIssue(issue.issue,path,messageOverride);case"Pointer":return formatIssue(issue.issue,path+formatPath(issue.path),messageOverride);case"Composite":case"AnyOf":{if(issue._tag==="Composite"||issue.issues.length>0){return issue.issues.map((issue)=>formatIssue(issue,path,messageOverride)).join(`
238
+ `)}message=messageOverride??findMessage(issue)??getExpectedMessage(getExpected(issue.ast),issue);break}default:message=messageOverride??defaultLeafHook(issue);break}return path?`${message}
239
+ at ${path}`:message}function findMessage(issue){if(issue._tag==="Pointer"||issue._tag==="Composite")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 String3(){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 ContentTypeId=Symbol.for("~effect/Schema/content");function setContent(operation,content){Object.defineProperty(operation,ContentTypeId,{value:content});return operation}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(),String3());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??{}),setContent(stringifyJson(options),{mediaType:"application/json",preserveSchema:options?.reviver===undefined&&options?.replacer===undefined}))}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;run??=this.run(this.typeParameters);try{return run(input,this,options)}catch(error){return die3(error)}}}_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 String4=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 String4;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:[],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 flatMap4(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(map4(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+)?|\\.\\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)&&parameter.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)||type.encoding!==undefined&&isOptional(toEncoded(type))){throw new Error("Cannot use `Schema.optionalKey` or `Schema.optional` with index signatures. Index signatures already allow keys to be absent; use `Schema.UndefinedOr` to allow `undefined` values.")}}};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 flatMap4(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):flatMap4(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):flatMap4(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=(snapshot,index,pending)=>{const property=properties[index];return flatMap4(exit2(pending),(exit)=>{const state={...snapshot,out:{...snapshot.out}};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 union2(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))}if(effectIsExit(eff))return resumeUnion(eff,state);let first=true;return suspend2(()=>{if(!first)return parseUnionCandidates(ast,parser,candidates,input,options);first=false;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 addLiteral(literal){if(!literals.includes(literal)){literals.push(literal)}}function go(ast){switch(ast._tag){case"Literal":if(isPropertyKey(ast.literal)){addLiteral(ast.literal)}return;case"UniqueSymbol":addLiteral(ast.symbol);return;case"Enum":for(const[,value]of ast.enums){addLiteral(value)}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 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){const apply=compileTransformationUnsafe(transformation);return(result,current,options)=>{try{return apply(result,current,options)}catch(error){return die3(error)}}}function compileTransformationUnsafe(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(()=>map4(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 compile2(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);try{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=flatMap4(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=flatMap4(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}catch(error){return die3(error)}};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??=compile2(this.ast,decodeChild)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=compile2(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 compiledMakeEffect(){return this.save("compiledMakeEffect",this.operation("makeEffect"))}get decodeEffect(){return this.save("decodeEffect",this.operation("decodeEffect")??compile2(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.compiledMakeEffect;if(makeEffect!==undefined)return this.save("makeEffect",makeEffect);const child=(ast)=>lazyParser(this.resolve,ast,"makeEffect");return this.save("makeEffect",compile2(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 make14(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})}var constructorDefectMessage="Constructor adapter can only throw schema issues";function throwConstructorDefect(error){throw new Error(constructorDefectMessage,{cause:die2(error)})}function makeConstructorSync(ast){let entry;return(input,options)=>constructSync(entry??=resolve4(ast),input,options)}function constructSync(entry,input,options){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){throwConstructorDefect(error)}if(output!==invalid3&&output!==missing)return output}return runSync3(parserResult(entry.makeEffect(input,parseOptions),input),constructorDefectMessage)}function makeClassSync(ast,input,options,construct){const entry=resolve4(ast);const descriptor=getConstructorDescriptor(ast);if(descriptor===undefined||entry.make!==undefined||entry.compiledMakeEffect!==undefined){return constructSync(entry,input,options)}if(descriptor.isConstructed(input))return input;const fields=constructSync((entry.resolve??resolve4)(descriptor.link.to),input,options);try{return construct(fields)}catch(error){throwConstructorDefect(error)}}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=make14(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 make15(ast,this[RebuildOptions])}};function make15(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 makeCodecDerivation(step,options){const deriveBody=memoize((owner)=>{const body=replaceContext(owner,undefined);const out=step(body,recur);return out===body?null:out});const recur=applyToSelfOrLastLinkEncodingIdempotent((ast)=>{const derived=deriveBody(getContextOwner(ast));if(derived===null)return ast;const out=replaceContext(derived,ast.context);return ast.context===undefined?out:replaceContextLastLink(out,withoutConstructorDefault(ast.context))},options);return recur}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 make15(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)=>make15(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"),String3()));var arrayFromSingleTransformation=new Transformation(transform((input)=>typeof input==="string"?[input]:input),passthrough());var isCodecArrayFromSingleLink=(link)=>link.transformation===arrayFromSingleTransformation;var toCodecStringTreeAST=makeCodecDerivation((ast,recur)=>toCodecStringTreeASTStep(ast,recur,(ast)=>{throw new globalThis.Error("Missing structural codec for StringTree",{cause:ast})}),{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 make16(new Declaration(typeParameters.map(getAST),(typeParameters)=>run(typeParameters.map((ast)=>make16(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)}toJSON(){return{_tag:this._tag,message:this.message}}[NodeInspectSymbol](){return this.toJSON()}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(()=>map4(cause,(issue)=>new SchemaError(issue))))}function fromIssueExit(exit){return isSuccess3(exit)?exit:failCause2(map4(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))}}var decodeEffect2=decodeUnknownEffect2;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 make16=make15;function isSchema(u){return hasProperty(u,TypeId19)&&u[TypeId19]===TypeId19}var optionalKey2=lambda((schema)=>make16(optionalKey(schema.ast),{schema}));var optional2=lambda((self)=>{const schema=UndefinedOr(self);return make16(optional(self.ast),{schema})});function Literal2(literal){const out=make16(new Literal(literal),{literal,transform(to){return out.pipe(decodeTo2(Literal2(to),{decode:transform(()=>to),encode:transform(()=>literal)}))}});return out}var Unknown2=make16(unknown);var Null2=make16(null_);var Undefined2=make16(undefined_2);var String5=make16(string2);var Number5=make16(number2);var Boolean3=make16(boolean);function makeStruct(ast,fields){return make16(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 make16(record(key.ast,value.ast),{key,value})}var ArraySchema=lambda((schema)=>make16(new Arrays(false,[],[schema.ast]),{value:schema}));function makeUnion(ast,members){return make16(ast,{members,mapMembers(f,options){const members=f(this.members);return makeUnion(union2(members,this.ast.options,options?.unsafePreserveChecks?this.ast.checks:undefined),members)}})}function Union2(members,options){return makeUnion(union2(members,options,undefined),members)}function Literals(literals){const members=literals.map(Literal2);return make16(union2(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 NullOr=lambda((self)=>Union2([self,Null2]));var UndefinedOr=lambda((self)=>Union2([self,Undefined2]));function brand(identifier){return(schema)=>make16(schema.ast,{schema,identifier})}function decodeTo2(to,transformation){return(from)=>{return make16(decodeTo(from.ast,to.ast,transformation?makeTransformation(transformation):passthrough2()),{from,to})}}function withConstructorDefault2(defaultValue){return(schema)=>make16(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 globalThis.RegExp(${format(source)})`:`new globalThis.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 pattern="^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$";const regExp=/^[0-9a-zA-Z+/]*={0,2}$/;return makeFilter2((s)=>s.length%4===0&&regExp.test(s),{expected:"a base64 encoded string",representation:{id:"effect/schema/isBase64",payload:null},toJsonSchema:()=>({pattern}),arbitraryConstraint:{patterns:[{source:pattern,flags:""}]},toCode:()=>({runtime:"Schema.isBase64()"}),...annotations})}var Finite=make16(finite);function isInt(annotations){return makeFilter2((n)=>globalThis.Number.isSafeInteger(n),{expected:"an integer",representation:{id:"effect/schema/isInt",payload:null},toJsonSchema:()=>({type:"integer",minimum:globalThis.Number.MIN_SAFE_INTEGER,maximum:globalThis.Number.MAX_SAFE_INTEGER}),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 isNonEmpty(annotations){return makeIsMinLength(1,1,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 NonEmptyString=String5.check(isNonEmpty());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:String5,flags:String5}),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=String5.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=String5.annotate({expected:"a string that will be decoded as 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:String5.check(isBase64()),type:String5,name:String5,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 URLSearchParams2=instanceOf(globalThis.URLSearchParams,{representation:{id:"effect/schema/URLSearchParams",payload:null},toCode:()=>({runtime:`Schema.URLSearchParams`,Type:`globalThis.URLSearchParams`}),expected:"URLSearchParams",toCodecJson:()=>link3()(String5.annotate({expected:"a query string that will be decoded as URLSearchParams"}),transform2({decode:(e)=>new globalThis.URLSearchParams(e),encode:(params)=>params.toString()}))});var Base64String=String5.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)=>make13(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)=>make13(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 make16(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 makeClassSync(toType(getClassSchema(this).ast),input??{},options,(fields)=>makeClassTrusted(this,fields))}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 makeClassTrusted(self,fields){return new self(fields,{"~payload":{token:payloadToken,value:fields}})}function getClassTransformation(self){return new Transformation(transform((input)=>makeClassTrusted(self,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=make16(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=make16(annotate(Json,{toCode:()=>({runtime:"Schema.Json",Type:"Schema.Json"})}));var JsonObject=Record(String5,Json2);import{chmodSync as chmodSync2,existsSync as existsSync10,readFileSync as readFileSync9,realpathSync as realpathSync5,renameSync as renameSync2,statSync as statSync3,writeFileSync as writeFileSync7}from"fs";import{rename as rename4}from"fs/promises";import{homedir,hostname}from"os";import{createInterface}from"readline/promises";import{pathToFileURL as pathToFileURL5}from"url";var name="@collective-intelligence/cli";var version="0.1.30";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(`
243
243
  `);const dataLines=[];let eventName;for(const line of lines){if(line.startsWith("data:")){dataLines.push(line.replace(/^data:\s*/,""))}else if(line.startsWith("event:")){eventName=line.replace(/^event:\s*/,"")}else if(line.startsWith("id:")){lastEventId=line.replace(/^id:\s*/,"")}else if(line.startsWith("retry:")){const parsed=Number.parseInt(line.replace(/^retry:\s*/,""),10);if(!Number.isNaN(parsed)){retryDelay=parsed}}}let data;let parsedJson=false;if(dataLines.length){const rawData=dataLines.join(`
244
- `);try{data=JSON.parse(rawData);parsedJson=true}catch{data=rawData}}if(parsedJson){if(responseValidator){await responseValidator(data)}if(responseTransformer){data=await responseTransformer(data)}}onSseEvent?.({data,event:eventName,id:lastEventId,retry:retryDelay});if(dataLines.length){yield data}}}}finally{signal.removeEventListener("abort",abortHandler);reader.releaseLock()}break}catch(error){onSseError?.(error);if(sseMaxRetryAttempts!==undefined&&attempt>=sseMaxRetryAttempts){break}const backoff=Math.min(retryDelay*2**(attempt-1),sseMaxRetryDelay??30000);await sleep(backoff)}}};const stream=createStream();return{stream}}var separatorArrayExplode=(style)=>{switch(style){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}};var separatorArrayNoExplode=(style)=>{switch(style){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}};var separatorObjectExplode=(style)=>{switch(style){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}};var serializeArrayParam=({allowReserved,explode,name,style,value})=>{if(!explode){const joinedValues=(allowReserved?value:value.map((v)=>encodeURIComponent(v))).join(separatorArrayNoExplode(style));switch(style){case"label":return`.${joinedValues}`;case"matrix":return`;${name}=${joinedValues}`;case"simple":return joinedValues;default:return`${name}=${joinedValues}`}}const separator=separatorArrayExplode(style);const joinedValues=value.map((v)=>{if(style==="label"||style==="simple"){return allowReserved?v:encodeURIComponent(v)}return serializePrimitiveParam({allowReserved,name,value:v})}).join(separator);return style==="label"||style==="matrix"?separator+joinedValues:joinedValues};var serializePrimitiveParam=({allowReserved,name,value})=>{if(value===undefined||value===null){return""}if(typeof value==="object"){throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.")}return`${name}=${allowReserved?value:encodeURIComponent(value)}`};var serializeObjectParam=({allowReserved,explode,name,style,value,valueOnly})=>{if(value instanceof Date){return valueOnly?value.toISOString():`${name}=${value.toISOString()}`}if(style!=="deepObject"&&!explode){let values=[];Object.entries(value).forEach(([key,v])=>{values=[...values,key,allowReserved?v:encodeURIComponent(v)]});const joinedValues=values.join(",");switch(style){case"form":return`${name}=${joinedValues}`;case"label":return`.${joinedValues}`;case"matrix":return`;${name}=${joinedValues}`;default:return joinedValues}}const separator=separatorObjectExplode(style);const joinedValues=Object.entries(value).map(([key,v])=>serializePrimitiveParam({allowReserved,name:style==="deepObject"?`${name}[${key}]`:key,value:v})).join(separator);return style==="label"||style==="matrix"?separator+joinedValues:joinedValues};var PATH_PARAM_RE=/\{[^{}]+\}/g;var defaultPathSerializer=({path,url:_url})=>{let url=_url;const matches=_url.match(PATH_PARAM_RE);if(matches){for(const match of matches){let explode=false;let name=match.substring(1,match.length-1);let style="simple";if(name.endsWith("*")){explode=true;name=name.substring(0,name.length-1)}if(name.startsWith(".")){name=name.substring(1);style="label"}else if(name.startsWith(";")){name=name.substring(1);style="matrix"}const value=path[name];if(value===undefined||value===null){continue}if(Array.isArray(value)){url=url.replace(match,serializeArrayParam({explode,name,style,value}));continue}if(typeof value==="object"){url=url.replace(match,serializeObjectParam({explode,name,style,value,valueOnly:true}));continue}if(style==="matrix"){url=url.replace(match,`;${serializePrimitiveParam({name,value})}`);continue}const replaceValue=encodeURIComponent(style==="label"?`.${value}`:value);url=url.replace(match,replaceValue)}}return url};var getUrl=({baseUrl,path,query,querySerializer,url:_url})=>{const pathUrl=_url.startsWith("/")?_url:`/${_url}`;let url=(baseUrl??"")+pathUrl;if(path){url=defaultPathSerializer({path,url})}let search=query?querySerializer(query):"";if(search.startsWith("?")){search=search.substring(1)}if(search){url+=`?${search}`}return url};function getValidRequestBody(options){const hasBody=options.body!==undefined;const isSerializedBody=hasBody&&options.bodySerializer;if(isSerializedBody){if("serializedBody"in options){const hasSerializedBody=options.serializedBody!==undefined&&options.serializedBody!=="";return hasSerializedBody?options.serializedBody:null}return options.body!==""?options.body:null}if(hasBody){return options.body}return}var getAuthToken=async(auth,callback)=>{const token=typeof callback==="function"?await callback(auth):callback;if(!token){return}if(auth.scheme==="bearer"){return`Bearer ${token}`}if(auth.scheme==="basic"){return`Basic ${btoa(token)}`}return token};var createQuerySerializer=({parameters={},...args}={})=>{const querySerializer=(queryParams)=>{const search=[];if(queryParams&&typeof queryParams==="object"){for(const name in queryParams){const value=queryParams[name];if(value===undefined||value===null){continue}const options=parameters[name]||args;if(Array.isArray(value)){const serializedArray=serializeArrayParam({allowReserved:options.allowReserved,explode:true,name,style:"form",value,...options.array});if(serializedArray)search.push(serializedArray)}else if(typeof value==="object"){const serializedObject=serializeObjectParam({allowReserved:options.allowReserved,explode:true,name,style:"deepObject",value,...options.object});if(serializedObject)search.push(serializedObject)}else{const serializedPrimitive=serializePrimitiveParam({allowReserved:options.allowReserved,name,value});if(serializedPrimitive)search.push(serializedPrimitive)}}}return search.join("&")};return querySerializer};var getParseAs=(contentType)=>{if(!contentType){return"stream"}const cleanContent=contentType.split(";")[0]?.trim();if(!cleanContent){return}if(cleanContent.startsWith("application/json")||cleanContent.endsWith("+json")){return"json"}if(cleanContent==="multipart/form-data"){return"formData"}if(["application/","audio/","image/","video/"].some((type)=>cleanContent.startsWith(type))){return"blob"}if(cleanContent.startsWith("text/")){return"text"}return};var checkForExistence=(options,name)=>{if(!name){return false}if(options.headers.has(name)||options.query?.[name]||options.headers.get("Cookie")?.includes(`${name}=`)){return true}return false};var setAuthParams=async({security,...options})=>{for(const auth of security){if(checkForExistence(options,auth.name)){continue}const token=await getAuthToken(auth,options.auth);if(!token){continue}const name=auth.name??"Authorization";switch(auth.in){case"query":if(!options.query){options.query={}}options.query[name]=token;break;case"cookie":options.headers.append("Cookie",`${name}=${token}`);break;case"header":default:options.headers.set(name,token);break}}};var buildUrl=(options)=>getUrl({baseUrl:options.baseUrl,path:options.path,query:options.query,querySerializer:typeof options.querySerializer==="function"?options.querySerializer:createQuerySerializer(options.querySerializer),url:options.url});var mergeConfigs=(a,b)=>{const config={...a,...b};if(config.baseUrl?.endsWith("/")){config.baseUrl=config.baseUrl.substring(0,config.baseUrl.length-1)}config.headers=mergeHeaders(a.headers,b.headers);return config};var headersEntries=(headers)=>{const entries=[];headers.forEach((value,key)=>{entries.push([key,value])});return entries};var mergeHeaders=(...headers)=>{const mergedHeaders=new Headers;for(const header of headers){if(!header){continue}const iterator=header instanceof Headers?headersEntries(header):Object.entries(header);for(const[key,value]of iterator){if(value===null){mergedHeaders.delete(key)}else if(Array.isArray(value)){for(const v of value){mergedHeaders.append(key,v)}}else if(value!==undefined){mergedHeaders.set(key,typeof value==="object"?JSON.stringify(value):value)}}}return mergedHeaders};class Interceptors{fns=[];clear(){this.fns=[]}eject(id){const index=this.getInterceptorIndex(id);if(this.fns[index]){this.fns[index]=null}}exists(id){const index=this.getInterceptorIndex(id);return Boolean(this.fns[index])}getInterceptorIndex(id){if(typeof id==="number"){return this.fns[id]?id:-1}return this.fns.indexOf(id)}update(id,fn){const index=this.getInterceptorIndex(id);if(this.fns[index]){this.fns[index]=fn;return id}return false}use(fn){this.fns.push(fn);return this.fns.length-1}}var createInterceptors=()=>({error:new Interceptors,request:new Interceptors,response:new Interceptors});var defaultQuerySerializer=createQuerySerializer({allowReserved:false,array:{explode:true,style:"form"},object:{explode:true,style:"deepObject"}});var defaultHeaders={"Content-Type":"application/json"};var createConfig=(override={})=>({...jsonBodySerializer,headers:defaultHeaders,parseAs:"auto",querySerializer:defaultQuerySerializer,...override});var createClient=(config={})=>{let _config=mergeConfigs(createConfig(),config);const getConfig=()=>({..._config});const setConfig=(config)=>{_config=mergeConfigs(_config,config);return getConfig()};const interceptors=createInterceptors();const beforeRequest=async(options)=>{const opts={..._config,...options,fetch:options.fetch??_config.fetch??globalThis.fetch,headers:mergeHeaders(_config.headers,options.headers),serializedBody:undefined};if(opts.security){await setAuthParams({...opts,security:opts.security})}if(opts.requestValidator){await opts.requestValidator(opts)}if(opts.body!==undefined&&opts.bodySerializer){opts.serializedBody=opts.bodySerializer(opts.body)}if(opts.body===undefined||opts.serializedBody===""){opts.headers.delete("Content-Type")}const resolvedOpts=opts;const url=buildUrl(resolvedOpts);return{opts:resolvedOpts,url}};const request=async(options)=>{const{opts,url}=await beforeRequest(options);const requestInit={redirect:"follow",...opts,body:getValidRequestBody(opts)};let request=new Request(url,requestInit);for(const fn of interceptors.request.fns){if(fn){request=await fn(request,opts)}}const _fetch=opts.fetch;let response;try{response=await _fetch(request)}catch(error){let finalError=error;for(const fn of interceptors.error.fns){if(fn){finalError=await fn(error,undefined,request,opts)}}finalError=finalError||{};if(opts.throwOnError){throw finalError}return opts.responseStyle==="data"?undefined:{error:finalError,request,response:undefined}}for(const fn of interceptors.response.fns){if(fn){response=await fn(response,request,opts)}}const result={request,response};if(response.ok){const parseAs=(opts.parseAs==="auto"?getParseAs(response.headers.get("Content-Type")):opts.parseAs)??"json";if(response.status===204||response.headers.get("Content-Length")==="0"){let emptyData;switch(parseAs){case"arrayBuffer":case"blob":case"text":emptyData=await response[parseAs]();break;case"formData":emptyData=new FormData;break;case"stream":emptyData=response.body;break;case"json":default:emptyData={};break}return opts.responseStyle==="data"?emptyData:{data:emptyData,...result}}let data;switch(parseAs){case"arrayBuffer":case"blob":case"formData":case"text":data=await response[parseAs]();break;case"json":{const text=await response.text();data=text?JSON.parse(text):{};break}case"stream":return opts.responseStyle==="data"?response.body:{data:response.body,...result}}if(parseAs==="json"){if(opts.responseValidator){await opts.responseValidator(data)}if(opts.responseTransformer){data=await opts.responseTransformer(data)}}return opts.responseStyle==="data"?data:{data,...result}}const textError=await response.text();let jsonError;try{jsonError=JSON.parse(textError)}catch{}const error=jsonError??textError;let finalError=error;for(const fn of interceptors.error.fns){if(fn){finalError=await fn(error,response,request,opts)}}finalError=finalError||{};if(opts.throwOnError){throw finalError}return opts.responseStyle==="data"?undefined:{error:finalError,...result}};const makeMethodFn=(method)=>(options)=>request({...options,method});const makeSseFn=(method)=>async(options)=>{const{opts,url}=await beforeRequest(options);return createSseClient({...opts,body:opts.body,headers:opts.headers,method,onRequest:async(url,init)=>{let request=new Request(url,init);for(const fn of interceptors.request.fns){if(fn){request=await fn(request,opts)}}return request},serializedBody:getValidRequestBody(opts),url})};const _buildUrl=(options)=>buildUrl({..._config,...options});return{buildUrl:_buildUrl,connect:makeMethodFn("CONNECT"),delete:makeMethodFn("DELETE"),get:makeMethodFn("GET"),getConfig,head:makeMethodFn("HEAD"),interceptors,options:makeMethodFn("OPTIONS"),patch:makeMethodFn("PATCH"),post:makeMethodFn("POST"),put:makeMethodFn("PUT"),request,setConfig,sse:{connect:makeSseFn("CONNECT"),delete:makeSseFn("DELETE"),get:makeSseFn("GET"),head:makeSseFn("HEAD"),options:makeSseFn("OPTIONS"),patch:makeSseFn("PATCH"),post:makeSseFn("POST"),put:makeSseFn("PUT"),trace:makeSseFn("TRACE")},trace:makeMethodFn("TRACE")}};var client=createClient(createConfig());var authLogout=(options)=>(options?.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/auth/logout",...options});var authMe=(options)=>(options?.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/auth/me",...options});var authMeOrganizations=(options)=>(options?.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/auth/me/organizations",...options});var authStartCliDevice=(options)=>(options.client??client).post({url:"/auth/cli/device",...options,headers:{"Content-Type":"application/json",...options.headers}});var authExchangeCliToken=(options)=>(options.client??client).post({url:"/auth/cli/token",...options,headers:{"Content-Type":"application/json",...options.headers}});var aiModelPresetsList=(options)=>(options?.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/ai/model-presets",...options});var aiModelPresetsDefault=(options)=>(options?.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/ai/model-presets/default",...options});var developmentSessionsCreate=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/development-sessions",...options,headers:{"Content-Type":"application/json",...options.headers}});var developmentSessionsTerminate=(options)=>(options.client??client).delete({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/development-sessions/{sessionId}",...options});var developmentSessionsHeartbeat=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/development-sessions/{sessionId}/heartbeat",...options});var developmentSessionsUpdateLocalManifest=(options)=>(options.client??client).put({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/development-sessions/{sessionId}/local-manifest",...options,headers:{"Content-Type":"application/json",...options.headers}});var hostedExtensionDiagnosticsReadTrace=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/hosted-extension-diagnostics/{diagnosticId}/trace",...options});var packageOperationsSnapshot=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-operations/{operationId}",...options});var packageOperationsEvents=(options)=>(options.client??client).sse.get({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-operations/{operationId}/events",...options});var packageOperationsContinueOperation=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-operations/{operationId}/continuations",...options});var packageReleasesUpdateInstallation=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-installations/update",...options,headers:{"Content-Type":"application/json",...options.headers}});var packageReleasesRollbackInstallation=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-installations/rollback",...options,headers:{"Content-Type":"application/json",...options.headers}});var packageReleasesPromote=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-releases/promote",...options,headers:{"Content-Type":"application/json",...options.headers}});var packageReleasesPublish=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-releases/publish",...options,headers:{"Content-Type":"application/json",...options.headers}});var packageReleasesLookupPublished=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-releases/lookup",...options,headers:{"Content-Type":"application/json",...options.headers}});var extensionPackagesListInstalled=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/packages/installed",...options});var extensionPackagesListReleases=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/packages/{fqn}/releases",...options});var extensionPackagesInstall=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/packages/{fqn}/install",...options,headers:{"Content-Type":"application/json",...options.headers}});var extensionPackagesSync=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/packages/{fqn}/sync",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationsSearch=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organizations/search",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationSetupCatalog=(options)=>(options?.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/setup/catalog",...options});var organizationSetupSetup=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/setup",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationCredentialsUpsert=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/credentials/upsert",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationCredentialsList=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/credentials/list",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationCredentialsGet=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/credentials/get",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationCredentialsRotate=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/credentials/rotate",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationCredentialsRevoke=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/credentials/revoke",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationServicePrincipalsList=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/service-principals",...options});var organizationExternalAppsList=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/external-apps",...options});var organizationExternalAppsEnroll=(options)=>(options.client??client).put({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/external-apps/by-fqn/{fqn}",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationExternalAppsGet=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/external-apps/{id}",...options});var organizationExternalAppsUpdate=(options)=>(options.client??client).put({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/external-apps/{id}",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationExternalAppsDisable=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/external-apps/{id}/disable",...options});var organizationExternalAppsRotateCredential=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/external-apps/{id}/credential/rotate",...options});var normalizedBackendUrl=(value)=>value.replace(/\/$/u,"");var makeBackendManagementClient=(config)=>createClient({baseUrl:normalizedBackendUrl(config.backendUrl),fetch:config.fetch,headers:config.token===undefined?{}:{authorization:`Bearer ${config.token}`}});function makeValue(value){return{_tag:"Value",value}}function makeRecord(keys,value){return{_tag:"Record",keys,value}}function makeArray(length,value){return{_tag:"Array",length,value}}var ConfigProvider=Reference("effect/ConfigProvider",{defaultValue:()=>fromEnv()});var Proto3={...PipeInspectableProto,toJSON(){return{_id:"ConfigProvider"}}};var identityPath=(path)=>path;function makeProvider(load,mapInput){const self=Object.create(Proto3);self.load=load;self.mapInput=mapInput;return self}function makeSource(get,transform){return makeProvider((path)=>get(transform(path)),(f)=>makeSource(get,(path)=>f(transform(path))))}function make15(get){return makeSource(get,identityPath)}var layer6=(self)=>isEffect2(self)?effect(ConfigProvider)(self):succeed5(ConfigProvider)(self);function fromUnknown(root,options){const preserveEmptyStrings=options?.preserveEmptyStrings===true;return make15((path)=>succeed6(nodeAtJson(root,path,preserveEmptyStrings)))}function nodeAtJson(root,path,preserveEmptyStrings){let cur=root;for(const seg of path){if(cur===null||cur===undefined)return;if(Array.isArray(cur)){if(typeof seg!=="number"||!Number.isInteger(seg)||seg<0||seg>=cur.length)return;cur=cur[seg];continue}if(isObject(cur)){if(typeof seg!=="string")return;if(!Object.hasOwn(cur,seg))return;cur=cur[seg];continue}return}return describeUnknown(cur,preserveEmptyStrings)}function describeUnknown(u,preserveEmptyStrings){if(u===undefined||u===null)return;if(typeof u==="string")return stringNode(u,preserveEmptyStrings);if(typeof u==="number"||typeof u==="boolean"||typeof u==="bigint"){return makeValue(String(u))}if(Array.isArray(u))return makeArray(u.length);if(isObject(u)){return makeRecord(new Set(Object.keys(u)))}return makeValue(format(u))}function stringNode(value,preserveEmptyStrings){const normalized=emptyStringAsMissing(value,preserveEmptyStrings);return normalized===undefined?undefined:makeValue(normalized)}function emptyStringAsMissing(value,preserveEmptyStrings){return value===""&&!preserveEmptyStrings?undefined:value}function fromEnvRecord(env,options){const preserveEmptyStrings=options?.preserveEmptyStrings===true;const trie=buildEnvTrie(env);return make15((path)=>succeed6(nodeAtEnv(trie,env,path,preserveEmptyStrings)))}function fromEnv(options){const env=options?.env??{...globalThis.process?.env,...import.meta?.env};return fromEnvRecord(env,{preserveEmptyStrings:options?.preserveEmptyStrings})}function buildEnvTrie(env){const trie={};for(const[name,value]of Object.entries(env)){if(value===undefined)continue;const segments=name.split("_");let node=trie;for(const seg of segments){const children=node.children??=Object.create(null);node=children[seg]??={}}}return trie}function nodeAtEnv(trie,env,path,preserveEmptyStrings){const key=path.map(String).join("_");const leafValue=emptyStringAsMissing(Object.hasOwn(env,key)?env[key]:undefined,preserveEmptyStrings);const trieNode=trieNodeAt(trie,path);const children=trieNode?.children?Object.keys(trieNode.children):[];if(children.length===0){return leafValue===undefined?undefined:makeValue(leafValue)}const allNumeric=children.every(isCanonicalArrayIndex);if(allNumeric){const length=Math.max(...children.map((k)=>parseInt(k,10)))+1;return makeArray(length,leafValue)}return makeRecord(new Set(children),leafValue)}function trieNodeAt(root,path){if(path.length===0)return root;let node=root;for(const seg of path){node=node?.children?.[String(seg)];if(!node)return}return node}var TypeId20="~effect/Config";class ConfigError{_tag="ConfigError";name="ConfigError";cause;constructor(cause){this.cause=cause}get message(){return this.cause.toString()}toString(){return`ConfigError(${this.message})`}}var Proto4={...Prototype2({label:"Config",evaluate(fiber){return this.parse(fiber.getRef(ConfigProvider))}}),[TypeId20]:TypeId20,toJSON(){return{_id:"Config"}}};function make16(evaluator){const self=Object.create(Proto4);self.evaluator=evaluator;self.parse=(provider)=>flatMapEager2(evaluator(provider,[]),fromResult2);return self}var isSourceError=(u)=>isTagged(u,"SourceError");var cursorToString=()=>"<configuration>";var loadCursor=(provider,path)=>provider.load(path).pipe(orDie2,mapEager2((node)=>({provider,path,node,toString:cursorToString})));var loadChildCursor=(cursor,segment)=>loadCursor(cursor.provider,[...cursor.path,segment]);var decodeFromCursor=(ast,decode)=>decodeTo(unknown,ast,new Transformation(transformEffect((input)=>decode(input)),passthrough()));var isScalarInput=(ast)=>{switch(ast._tag){case"Union":return ast.types.every(isScalarInput);case"Objects":case"Arrays":case"Suspend":return false;default:return true}};var hasProviderInput=(ast,node)=>{switch(ast._tag){case"Objects":return node?._tag==="Record";case"Arrays":return node?._tag==="Array";case"Union":return ast.types.some((ast)=>hasProviderInput(ast,node));case"Suspend":return hasProviderInput(ast.thunk(),node);default:return node?.value!==undefined}};var toConfigCursorAST=memoize((root)=>{const seen=new WeakSet;const recur=applyToSelfOrLastLinkEncoding((ast)=>{seen.add(ast);switch(ast._tag){case"Objects":{const matchesIndex=ast.indexSignatures.map((is)=>_is(is.parameter));const materialize=fnUntraced2(function*(cursor){if(cursor.node?._tag!=="Record"){return}const node=cursor.node;const keys=new Set;for(const property of ast.propertySignatures){if(typeof property.name==="string")keys.add(property.name)}if(matchesIndex.length>0){for(const key of node.keys){if(matchesIndex.some((matches)=>matches(key)))keys.add(key)}}const out={};for(const key of keys){const child=yield*loadChildCursor(cursor,key);if(child.node!==undefined)assignProperty(out,key,child)}return out});return decodeFromCursor(ast.recur(recur,(ast)=>ast),materialize)}case"Arrays":{const materialize=fnUntraced2(function*(cursor){if(cursor.node?._tag!=="Array"){return}const out=[];for(let i=0;i<cursor.node.length;i++){out.push(yield*loadChildCursor(cursor,i))}return out});return decodeFromCursor(ast.recur(recur),materialize)}case"Union":for(const member of ast.types){recur(member)}if(!isScalarInput(ast))return ast.recur(recur);break;case"Suspend":{const target=ast.thunk();if(!seen.has(target))recur(target);return ast.recur(recur)}case"Declaration":case"Any":throw new globalThis.Error("Config.schema does not support opaque StringTree encodings",{cause:ast})}return decodeFromCursor(ast,(cursor)=>succeed6(cursor.node?.value))});return recur(root)});function schema(codec,path){const codecStringTree=toCodecStringTree2(codec);const encodedAst=toEncoded(codecStringTree.ast);const decodeCursor=decodeUnknownEffect(make14(toConfigCursorAST(codecStringTree.ast)));const localPath=typeof path==="string"?[path]:path??[];return make16((provider,pathPrefix)=>{const fullPath=[...pathPrefix,...localPath];return loadCursor(provider,fullPath).pipe(flatMapEager2((cursor)=>decodeCursor(cursor).pipe(mapEager2(succeed2),catchEager2((issue)=>{const error=new ConfigError(new SchemaError(fullPath.length>0?new Pointer(fullPath,issue):issue));return hasProviderInput(encodedAst,cursor.node)?fail6(error):succeed6(fail2(error))}))),catchDefect2((defect)=>isSourceError(defect)?fail6(new ConfigError(defect)):die3(defect)))})}class BackendManagementConfigurationError extends TaggedError3()("BackendManagementConfigurationError",{message:String5}){}var tryConfiguration=(evaluate)=>try_2({catch:(cause)=>is2(BackendManagementConfigurationError)(cause)?cause:new BackendManagementConfigurationError({message:cause instanceof Error?cause.message:"CLI configuration step failed"}),try:evaluate});import{chmodSync,existsSync,mkdirSync,readFileSync,renameSync,writeFileSync}from"fs";import path from"path";var ProfileSchema=Struct({apiOrigin:String5,currentOrganizationId:optionalKey2(String5),session:optionalKey2(Struct({expiresAt:optionalKey2(String5),token:String5}))});var ProfileStoreSchema=Struct({current:optionalKey2(String5),profiles:Record(String5,ProfileSchema)});var profileStoreJson=fromJsonString2(ProfileStoreSchema);var decodeProfileStore=decodeUnknownSync(profileStoreJson);var encodeProfileStore=encodeSync(profileStoreJson);var nonEmpty=(value)=>value===""?undefined:value;var profileDirectory=(environment)=>{const configHome=nonEmpty(environment.XDG_CONFIG_HOME);if(configHome!==undefined){return path.join(configHome,"ci")}const home=nonEmpty(environment.HOME);return home===undefined?undefined:path.join(home,".config","ci")};var profileName=(apiOrigin)=>new URL(apiOrigin).host;var readProfileStore=(environment)=>{const directory=profileDirectory(environment);if(directory===undefined){return{profiles:{}}}const file=path.join(directory,"profiles.json");if(!existsSync(file)){return{profiles:{}}}try{return decodeProfileStore(readFileSync(file,"utf-8"))}catch{throw new BackendManagementConfigurationError({message:`CLI Profile file ${file} is invalid; fix or remove it, then run ci login`})}};var writeProfileStore=(environment,store)=>{const directory=profileDirectory(environment);if(directory===undefined){throw new BackendManagementConfigurationError({message:"Cannot locate the CLI configuration directory; set XDG_CONFIG_HOME or HOME"})}mkdirSync(directory,{mode:448,recursive:true});chmodSync(directory,448);const file=path.join(directory,"profiles.json");const temporary=`${file}.${process.pid}.tmp`;writeFileSync(temporary,`${encodeProfileStore(store)}
245
- `,{mode:384});chmodSync(temporary,384);renameSync(temporary,file)};var updateProfile=(environment,name,update)=>{const store=readProfileStore(environment);const latest=store.profiles[name];const next=latest===undefined?undefined:update(latest);if(next!==undefined){writeProfileStore(environment,{...store,profiles:{...store.profiles,[name]:next}})}return next};var configurationError=(message)=>new BackendManagementConfigurationError({message});var nonEmpty2=(value)=>value===undefined||value.trim()===""?undefined:value;var optionValue=(args,name)=>{const index=args.indexOf(`--${name}`);const value=index===-1?undefined:args[index+1];return value===undefined||value.startsWith("--")?undefined:value};var sameOrigin=(left,right)=>{try{return new URL(left).origin===new URL(right).origin}catch{return false}};var storedProfile=(store,name)=>name!==undefined&&Object.hasOwn(store.profiles,name)?store.profiles[name]:undefined;var tenantProfileName=(apiOrigin)=>{try{return profileName(apiOrigin)}catch{return}};var selectProfile=(store,requestedName,explicitOrigin)=>{if(requestedName!==undefined){const profile=storedProfile(store,requestedName);if(profile===undefined){throw configurationError(`CLI Profile ${requestedName} does not exist; run ci login or select another --profile`)}if(explicitOrigin!==undefined&&!sameOrigin(profile.apiOrigin,explicitOrigin)){throw configurationError(`CLI Profile ${requestedName} belongs to ${profile.apiOrigin}, not ${explicitOrigin}`)}return{name:requestedName,profile}}const name=explicitOrigin===undefined?store.current:tenantProfileName(explicitOrigin);const profile=storedProfile(store,name);if(name===undefined||profile===undefined||explicitOrigin!==undefined&&!sameOrigin(profile.apiOrigin,explicitOrigin)){return}return{name,profile}};var sessionToken=(selected)=>{const session=selected?.profile.session;if(selected===undefined||session===undefined){return}if(session.expiresAt!==undefined&&Date.parse(session.expiresAt)<=Date.now()){throw configurationError(`The CLI Session of Profile ${selected.name} expired; run ci login or set CI_MANAGEMENT_TOKEN`)}return session.token};var isOrganizationApiKey=(token)=>token.startsWith("dpk_");var resolveTarget=(input,organizationRequired)=>{const{args,environment}=input;const explicitOrigin=nonEmpty2(optionValue(args,"backend-url"))??nonEmpty2(environment.CI_BACKEND_URL);const environmentToken=nonEmpty2(environment.CI_MANAGEMENT_TOKEN);const explicitOrganization=nonEmpty2(optionValue(args,"organization"));const apiKey=environmentToken!==undefined&&isOrganizationApiKey(environmentToken);const profileNeeded=explicitOrigin===undefined||environmentToken===undefined||organizationRequired&&explicitOrganization===undefined&&!apiKey;const selected=profileNeeded?selectProfile(readProfileStore(environment),nonEmpty2(optionValue(args,"profile"))??nonEmpty2(environment.CI_PROFILE),explicitOrigin):undefined;const apiOrigin=explicitOrigin??selected?.profile.apiOrigin;if(apiOrigin===undefined){throw configurationError("Missing backend URL: pass --backend-url, set CI_BACKEND_URL, or run ci login")}const token=environmentToken??sessionToken(selected);if(token===undefined){throw configurationError("Missing credential: run ci login or set CI_MANAGEMENT_TOKEN")}return{apiOrigin,credentialSource:environmentToken===undefined?"cli-session":"management-token",organizationId:explicitOrganization??(apiKey?undefined:selected?.profile.currentOrganizationId),profile:selected?.name,token}};var resolveBackendManagementTarget=(input)=>resolveTarget(input,input.organizationLookup===true);var missingOrganizationMessage="Missing Organization: pass --organization or run ci orgs use <organization-id>";var selectedProfile=(input)=>{const store=readProfileStore(input.environment);const selected=selectProfile(store,nonEmpty2(optionValue(input.args,"profile"))??nonEmpty2(input.environment.CI_PROFILE),nonEmpty2(optionValue(input.args,"backend-url"))??nonEmpty2(input.environment.CI_BACKEND_URL));return selected===undefined?undefined:{...selected,store}};var resolveOrganizationTarget=(input)=>{const target=resolveTarget(input,true);if(target.organizationId===undefined){throw configurationError(isOrganizationApiKey(target.token)?"Missing Organization: pass --organization with the Organization of the CI_MANAGEMENT_TOKEN API key":missingOrganizationMessage)}return{...target,organizationId:target.organizationId}};var apiKeyOrganizationMismatch=(input)=>isOrganizationApiKey(input.token)&&input.apiKey!==undefined&&input.apiKey.organizationId!==input.organizationId?configurationError(`Organization API key ${input.apiKey.name} belongs to Organization ${input.apiKey.organizationId} and cannot act for Organization ${input.organizationId}; pass --organization ${input.apiKey.organizationId} or use a credential for ${input.organizationId}`):undefined;var backendManagementClientFromCli=(input)=>{const target=resolveBackendManagementTarget(input);return makeBackendManagementClient({backendUrl:target.apiOrigin,fetch:input.fetch??globalThis.fetch,token:target.token})};var deploymentManagementClients=fn2("BackendManagement.deploymentClients")(function*deploymentManagementClients(input){const publisher=yield*schema(Redacted(String5.check(isMinLength(1))),"CI_PUBLISHER_TOKEN").pipe(provide3(layer6(fromUnknown(input.environment))));return{organization:makeBackendManagementClient({backendUrl:input.target.apiOrigin,fetch:input.fetch,token:input.target.token}),publisher:makeBackendManagementClient({backendUrl:input.target.apiOrigin,fetch:input.fetch,token:value2(publisher)})}});class DevelopmentSessionRejectedError extends TaggedError3()("DevelopmentSessionRejectedError",{reason:Literals(["session_not_found","session_owned"])}){}var hasWireTag=(cause,tag)=>is2(TaggedStruct(tag,{}))(cause);var createDevelopmentSession=async(client,input)=>{try{const result=await developmentSessionsCreate({body:{hostOrigins:[...input.hostOrigins],packageManifest:{fqn:input.packageFqn},protocolVersion:"v1"},client,throwOnError:true});return result.data}catch(error){throw hasWireTag(error,"Conflict")?new DevelopmentSessionRejectedError({reason:"session_owned"}):error}};var updateDevelopmentSessionLocalManifest=flow((client,input)=>tryPromise2(()=>developmentSessionsUpdateLocalManifest({body:{hostedContributions:[...input.hostedContributions]},client,path:{sessionId:input.sessionId},throwOnError:true})).pipe(map4((result)=>result.data),mapError2((cause)=>hasWireTag(cause.cause,"NotFound")?new DevelopmentSessionRejectedError({reason:"session_not_found"}):cause)),runPromise2);var heartbeatDevelopmentSession=flow((client,sessionId)=>tryPromise2(()=>developmentSessionsHeartbeat({client,path:{sessionId},throwOnError:true})).pipe(asVoid2,mapError2((cause)=>hasWireTag(cause.cause,"NotFound")?new DevelopmentSessionRejectedError({reason:"session_not_found"}):cause)),runPromise2);var terminateDevelopmentSession=flow((client,sessionId)=>tryPromise2(()=>developmentSessionsTerminate({client,path:{sessionId},throwOnError:true})).pipe(asVoid2),runPromise2);class ManagementRequestError extends TaggedError3()("ManagementRequestError",{body:optional2(Unknown2),cause:optional2(Unknown2),message:String5,status:Finite}){}var BackendReason=Union2([Struct({message:String5}),Struct({detail:String5}),Struct({error_description:String5}),Struct({error:String5})]);var backendReason=(body)=>{if(!is2(BackendReason)(body)){return}if("message"in body){return body.message}if("detail"in body){return body.detail}return"error_description"in body?body.error_description:body.error};var requestFailure=(label,response,body)=>{if(response.status===401){return new ManagementRequestError({body,message:`${label} failed: the backend rejected the credential; run ci login or check CI_MANAGEMENT_TOKEN`,status:401})}const reason=backendReason(body);return new ManagementRequestError({body,message:`${label} failed (HTTP ${response.status})${reason===undefined?"":`: ${reason}`}`,status:response.status})};var requestTimeout="30 seconds";var withRequestTimeout=(label,subject)=>(effect)=>effect.pipe(timeoutOrElse2({duration:requestTimeout,orElse:()=>fail6(new ManagementRequestError({message:`${label} failed: ${subject} did not respond within ${requestTimeout}`,status:0}))}));var unreachable=(label,cause)=>new ManagementRequestError({cause,message:`${label} failed: could not reach the backend`,status:0});var sendRequest=(label,operation,options)=>tryPromise2({catch:(cause)=>unreachable(label,cause),try:async(signal)=>await operation({...options,signal})}).pipe(withRequestTimeout(label,"the backend"),flatMap4((result)=>{const{response}=result;return response===undefined?fail6(unreachable(label,result.error)):succeed6({response,result})}));var managementData=(label,operation,options)=>flatMap4(sendRequest(label,operation,options),({response,result})=>response.ok&&result.data!==undefined?succeed6(result.data):fail6(requestFailure(label,response,result.error)));var managementOk=(label,operation,options)=>flatMap4(sendRequest(label,operation,options),({response,result})=>response.ok?void_3:fail6(requestFailure(label,response,result.error)));var TenantDiscoverySchema=Struct({api_base_url:String5,dashboard_url:String5,issuer:String5,jwks_uri:String5});var JwksSchema=Struct({keys:ArraySchema(Unknown2)});var SigningKeyUnavailable=Struct({error:Literal2("signing_key_unavailable")});var send=(fetch2,label,url)=>tryPromise2({catch:(cause)=>new ManagementRequestError({cause,message:`${label} failed: could not reach ${url}`,status:0}),try:async(signal)=>{const response=await fetch2(url,{headers:{accept:"application/json"},signal});return{response,text:await response.text()}}}).pipe(withRequestTimeout(label,url));var notJson=(label,url,response,cause)=>new ManagementRequestError({cause,message:`${label} failed: ${url} did not return JSON (HTTP ${response.status})`,status:response.status});var parseJson2=(text,onFailure)=>try_2({catch:onFailure,try:()=>JSON.parse(text)});var readTenantDiscovery=fn2("BackendManagement.readTenantDiscovery")(function*readTenantDiscovery(fetch2,apiUrl){const origin=yield*try_2({catch:()=>new ManagementRequestError({message:`Invalid API URL ${apiUrl}`,status:0}),try:()=>new URL(apiUrl).origin});const label=`Tenant discovery at ${new URL(origin).host}`;const notApiUrl=(status,cause)=>new ManagementRequestError({cause,message:`${label} failed: ${apiUrl} is not a CI API URL; copy the login command from the dashboard: Organization settings \u2192 CLI`,status});const{response,text}=yield*send(fetch2,label,`${origin}/.well-known/ci-configuration`);if(response.status===404){return yield*notApiUrl(404)}const body=yield*parseJson2(text,(cause)=>response.ok?notApiUrl(response.status,cause):notJson(label,apiUrl,response,cause));if(!response.ok){return yield*requestFailure(label,response,body)}const document=yield*decodeUnknownEffect2(TenantDiscoverySchema)(body).pipe(mapError2((cause)=>notApiUrl(response.status,cause)));return{apiBaseUrl:document.api_base_url,dashboardUrl:document.dashboard_url,issuer:document.issuer,jwksUri:document.jwks_uri}});var readSigningKeyCount=fn2("BackendManagement.readSigningKeyCount")(function*readSigningKeyCount(fetch2,jwksUri){const label="JWKS read";const{response,text}=yield*send(fetch2,label,jwksUri);const body=yield*parseJson2(text,(cause)=>notJson(label,jwksUri,response,cause));if(response.status===503&&is2(SigningKeyUnavailable)(body)){return yield*new ManagementRequestError({body,message:"JWKS is unavailable: the backend has no External App signing key (set APP_EXTERNAL_APP_JWT_PRIVATE_JWK)",status:503})}if(!response.ok||!is2(JwksSchema)(body)){return yield*requestFailure(label,response,body)}return body.keys.length});var readIdentity=(client)=>managementData("Identity read",authMe,{client});var resolveManagementContext=fn2("BackendManagement.resolveContext")(function*resolveManagementContext(input){const target=yield*try_2({catch:(cause)=>is2(BackendManagementConfigurationError)(cause)?cause:new BackendManagementConfigurationError({message:"Could not resolve the backend credential"}),try:()=>resolveBackendManagementTarget({args:input.args,environment:input.environment,organizationLookup:true})});const client=makeBackendManagementClient({backendUrl:target.apiOrigin,fetch:input.fetch,token:target.token});const organizationId=target.organizationId===undefined&&isOrganizationApiKey(target.token)?(yield*readIdentity(client)).organizationId:target.organizationId;return{client,organizationId,target}});var resolveOrganizationContext=(input)=>flatMap4(resolveManagementContext(input),(context)=>{const{organizationId}=context;return organizationId===undefined?fail6(new BackendManagementConfigurationError({message:missingOrganizationMessage})):succeed6({...context,organizationId})});var explainOrganizationForbidden=(context,organizationId)=>(error)=>error.status===403&&isOrganizationApiKey(context.target.token)?readIdentity(context.client).pipe(map4((identity)=>apiKeyOrganizationMismatch({apiKey:identity.apiKeyName===undefined||identity.organizationId===undefined?undefined:{name:identity.apiKeyName,organizationId:identity.organizationId},organizationId,token:context.target.token})??error),orElseSucceed2(()=>error),flatMap4(fail6)):fail6(error);class CommandOptionsError extends TaggedError3()("CommandOptionsError",{message:String5}){}var targetOptions=["backend-url","organization","profile"];var parseCommandOptions=(args,spec)=>{const repeatable=new Set(spec.repeatable);const valueNames=new Set([...spec.values??[],...repeatable]);const switchNames=new Set(spec.switches);const values=new Map;const switches=new Set;const positionals=[];for(let index=0;index<args.length;index+=1){const argument=args[index]??"";if(!argument.startsWith("--")){positionals.push(argument);continue}const name=argument.slice(2);if(switchNames.has(name)){switches.add(name);continue}if(!valueNames.has(name)){throw new CommandOptionsError({message:`Unknown option ${argument}`})}const value=args[index+1];if(value===undefined||value.startsWith("--")||value.trim()===""){throw new CommandOptionsError({message:`Missing value for ${argument}`})}index+=1;const existing=values.get(name);if(existing!==undefined&&!repeatable.has(name)){throw new CommandOptionsError({message:`Duplicate option ${argument}`})}values.set(name,[...existing??[],value])}if(positionals.length>(spec.positionals??0)){throw new CommandOptionsError({message:`Unexpected argument ${positionals[spec.positionals??0]??""}`})}return{positionals,switches,values}};var optionValue2=(options,name)=>options.values.get(name)?.[0];var optionValues=(options,name)=>options.values.get(name)??[];var parseCommandOptionsEffect=(args,spec)=>try_2({catch:(cause)=>is2(CommandOptionsError)(cause)?cause:new CommandOptionsError({message:"Invalid options"}),try:()=>parseCommandOptions(args,spec)});class AppsCommandError extends TaggedError3()("AppsCommandError",{cause:optional2(Unknown2),message:String5}){}var usage="Usage: ci apps list | ci apps get <application-id> | ci apps rotate-secret <application-id> | ci apps disable <application-id> | ci apps enroll ... | ci apps env ... | ci apps redirect-uris ... | ci apps origins ...";var encodeJson=encodeSync(fromJsonString2(Unknown2));var applicationSummary=(application)=>({allowedOrigins:application.allowedOrigins,applicationId:application.id,applicationType:application.applicationType,audience:application.audience,clientId:application.clientId,enabled:application.enabled,fqn:application.fqn,name:application.name,postLogoutRedirectUris:application.postLogoutRedirectUris,primaryRedirectUri:application.primaryRedirectUri,redirectUris:application.redirectUris,scopes:application.scopes});var appsCommandEffect=(args,dependencies)=>gen2(function*appsCommand(){const[command,...rest]=args;const options=yield*parseCommandOptionsEffect(rest,{positionals:command==="list"?0:1,values:targetOptions});const[applicationId]=options.positionals;const applicationCommands=new Set(["disable","get","rotate-secret"]);if(command!=="list"&&(applicationId===undefined||!applicationCommands.has(command??""))){return yield*new AppsCommandError({message:usage})}const context=yield*resolveOrganizationContext({args:rest,environment:dependencies.environment,fetch:dependencies.fetch});const request={client:context.client,headers:{"x-organization-id":context.organizationId}};const operation=(id)=>gen2(function*appsOperation(){if(command==="get"){return applicationSummary(yield*managementData("External App read",organizationExternalAppsGet,{...request,path:{id}}))}if(command==="disable"){return applicationSummary(yield*managementData("External App disable",organizationExternalAppsDisable,{...request,path:{id}}))}const rotated=yield*managementData("Client secret rotation",organizationExternalAppsRotateCredential,{...request,path:{id}});return{applicationId:rotated.application.id,clientId:rotated.application.clientId,clientSecret:rotated.clientSecret}});const explainForbidden=(effect)=>effect.pipe(catchTag2("ManagementRequestError",explainOrganizationForbidden(context,context.organizationId)));const result=applicationId===undefined?yield*explainForbidden(managementData("External App list",organizationExternalAppsList,request).pipe(map4((response)=>response.data.map(applicationSummary)))):yield*explainForbidden(operation(applicationId));return yield*sync2(()=>{dependencies.writeOutput(`${encodeJson(result)}
246
- `)})}).pipe(mapError2((cause)=>is2(AppsCommandError)(cause)?cause:new AppsCommandError({cause,message:cause.message})));var check=(name,passed,detail)=>({detail,name,passed});var redirectCheck=(applications,fqn,redirectUris)=>{if(fqn===undefined){const missing=redirectUris.filter((uri)=>!applications.some((application)=>application.enabled&&application.redirectUris.includes(uri)));return missing.length===0?check("redirect-uri",true,`registered: ${redirectUris.join(", ")}`):check("redirect-uri",false,`no enabled External App registers ${missing.join(", ")}`)}const application=applications.find((candidate)=>candidate.fqn===fqn);if(application===undefined){return check("redirect-uri",false,`no External App ${fqn} exists`)}if(!application.enabled){return check("redirect-uri",false,`External App ${fqn} is disabled`)}const expected=redirectUris.length===0?application.redirectUris:redirectUris;const missing=expected.filter((uri)=>!application.redirectUris.includes(uri));return missing.length===0&&expected.length>0?check("redirect-uri",true,`${fqn} registers ${expected.join(", ")}`):check("redirect-uri",false,`${fqn} does not register ${missing.length===0?"any redirect URI":missing.join(", ")}`)};var listApplications=(context)=>managementData("External App list",organizationExternalAppsList,{client:context.client,headers:{"x-organization-id":context.organizationId}}).pipe(map4((response)=>response.data),catchTag2("ManagementRequestError",explainOrganizationForbidden(context,context.organizationId)));var runTenantPreflight=fn2("Preflight.tenant")(function*runTenantPreflight(input){const{context}=input;const{apiOrigin}=context.target;const discovery=yield*result2(readTenantDiscovery(input.fetch,apiOrigin));const keys=yield*result2(readSigningKeyCount(input.fetch,isSuccess2(discovery)?discovery.success.jwksUri:`${apiOrigin.replace(/\/$/u,"")}/oauth/jwks`));const applications=yield*result2(listApplications(context));return{applications:isSuccess2(applications)?applications.success:undefined,checks:[isSuccess2(discovery)?check("discovery",true,`issuer ${discovery.success.issuer}`):check("discovery",false,discovery.failure.message),isFailure2(keys)?check("jwks",false,keys.failure.message):check("jwks",keys.success>0,keys.success>0?`${keys.success} signing key(s) published`:"JWKS publishes no signing key"),isSuccess2(applications)?check("organization",true,`Organization ${context.organizationId} is accessible with this credential`):check("organization",false,applications.failure.message)],discovery:isSuccess2(discovery)?discovery.success:undefined}});var runRedirectPreflight=fn2("Preflight.redirect")(function*runRedirectPreflight(input){const applications=yield*result2(listApplications(input.context));return isSuccess2(applications)?redirectCheck(applications.success,input.fqn,input.redirectUris):check("redirect-uri",false,applications.failure.message)});var runPreflight=fn2("Preflight.run")(function*runPreflight(input){const tenant=yield*runTenantPreflight(input);const checks=[...tenant.checks];if(input.fqn!==undefined||input.redirectUris.length>0){checks.push(tenant.applications===undefined?check("redirect-uri",false,"not checked: the Organization check failed"):redirectCheck(tenant.applications,input.fqn,input.redirectUris))}return{checks,discovery:tenant.discovery}});var renderPreflight=(checks)=>`${checks.map((entry)=>`${entry.passed?"PASS":"FAIL"} ${entry.name}: ${entry.detail}`).join(`
244
+ `);try{data=JSON.parse(rawData);parsedJson=true}catch{data=rawData}}if(parsedJson){if(responseValidator){await responseValidator(data)}if(responseTransformer){data=await responseTransformer(data)}}onSseEvent?.({data,event:eventName,id:lastEventId,retry:retryDelay});if(dataLines.length){yield data}}}}finally{signal.removeEventListener("abort",abortHandler);reader.releaseLock()}break}catch(error){onSseError?.(error);if(sseMaxRetryAttempts!==undefined&&attempt>=sseMaxRetryAttempts){break}const backoff=Math.min(retryDelay*2**(attempt-1),sseMaxRetryDelay??30000);await sleep(backoff)}}};const stream=createStream();return{stream}}var separatorArrayExplode=(style)=>{switch(style){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}};var separatorArrayNoExplode=(style)=>{switch(style){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}};var separatorObjectExplode=(style)=>{switch(style){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}};var serializeArrayParam=({allowReserved,explode,name,style,value})=>{if(!explode){const joinedValues=(allowReserved?value:value.map((v)=>encodeURIComponent(v))).join(separatorArrayNoExplode(style));switch(style){case"label":return`.${joinedValues}`;case"matrix":return`;${name}=${joinedValues}`;case"simple":return joinedValues;default:return`${name}=${joinedValues}`}}const separator=separatorArrayExplode(style);const joinedValues=value.map((v)=>{if(style==="label"||style==="simple"){return allowReserved?v:encodeURIComponent(v)}return serializePrimitiveParam({allowReserved,name,value:v})}).join(separator);return style==="label"||style==="matrix"?separator+joinedValues:joinedValues};var serializePrimitiveParam=({allowReserved,name,value})=>{if(value===undefined||value===null){return""}if(typeof value==="object"){throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.")}return`${name}=${allowReserved?value:encodeURIComponent(value)}`};var serializeObjectParam=({allowReserved,explode,name,style,value,valueOnly})=>{if(value instanceof Date){return valueOnly?value.toISOString():`${name}=${value.toISOString()}`}if(style!=="deepObject"&&!explode){let values=[];Object.entries(value).forEach(([key,v])=>{values=[...values,key,allowReserved?v:encodeURIComponent(v)]});const joinedValues=values.join(",");switch(style){case"form":return`${name}=${joinedValues}`;case"label":return`.${joinedValues}`;case"matrix":return`;${name}=${joinedValues}`;default:return joinedValues}}const separator=separatorObjectExplode(style);const joinedValues=Object.entries(value).map(([key,v])=>serializePrimitiveParam({allowReserved,name:style==="deepObject"?`${name}[${key}]`:key,value:v})).join(separator);return style==="label"||style==="matrix"?separator+joinedValues:joinedValues};var PATH_PARAM_RE=/\{[^{}]+\}/g;var defaultPathSerializer=({path,url:_url})=>{let url=_url;const matches=_url.match(PATH_PARAM_RE);if(matches){for(const match of matches){let explode=false;let name=match.substring(1,match.length-1);let style="simple";if(name.endsWith("*")){explode=true;name=name.substring(0,name.length-1)}if(name.startsWith(".")){name=name.substring(1);style="label"}else if(name.startsWith(";")){name=name.substring(1);style="matrix"}const value=path[name];if(value===undefined||value===null){continue}if(Array.isArray(value)){url=url.replace(match,serializeArrayParam({explode,name,style,value}));continue}if(typeof value==="object"){url=url.replace(match,serializeObjectParam({explode,name,style,value,valueOnly:true}));continue}if(style==="matrix"){url=url.replace(match,`;${serializePrimitiveParam({name,value})}`);continue}const replaceValue=encodeURIComponent(style==="label"?`.${value}`:value);url=url.replace(match,replaceValue)}}return url};var getUrl=({baseUrl,path,query,querySerializer,url:_url})=>{const pathUrl=_url.startsWith("/")?_url:`/${_url}`;let url=(baseUrl??"")+pathUrl;if(path){url=defaultPathSerializer({path,url})}let search=query?querySerializer(query):"";if(search.startsWith("?")){search=search.substring(1)}if(search){url+=`?${search}`}return url};function getValidRequestBody(options){const hasBody=options.body!==undefined;const isSerializedBody=hasBody&&options.bodySerializer;if(isSerializedBody){if("serializedBody"in options){const hasSerializedBody=options.serializedBody!==undefined&&options.serializedBody!=="";return hasSerializedBody?options.serializedBody:null}return options.body!==""?options.body:null}if(hasBody){return options.body}return}var getAuthToken=async(auth,callback)=>{const token=typeof callback==="function"?await callback(auth):callback;if(!token){return}if(auth.scheme==="bearer"){return`Bearer ${token}`}if(auth.scheme==="basic"){return`Basic ${btoa(token)}`}return token};var createQuerySerializer=({parameters={},...args}={})=>{const querySerializer=(queryParams)=>{const search=[];if(queryParams&&typeof queryParams==="object"){for(const name in queryParams){const value=queryParams[name];if(value===undefined||value===null){continue}const options=parameters[name]||args;if(Array.isArray(value)){const serializedArray=serializeArrayParam({allowReserved:options.allowReserved,explode:true,name,style:"form",value,...options.array});if(serializedArray)search.push(serializedArray)}else if(typeof value==="object"){const serializedObject=serializeObjectParam({allowReserved:options.allowReserved,explode:true,name,style:"deepObject",value,...options.object});if(serializedObject)search.push(serializedObject)}else{const serializedPrimitive=serializePrimitiveParam({allowReserved:options.allowReserved,name,value});if(serializedPrimitive)search.push(serializedPrimitive)}}}return search.join("&")};return querySerializer};var getParseAs=(contentType)=>{if(!contentType){return"stream"}const cleanContent=contentType.split(";")[0]?.trim();if(!cleanContent){return}if(cleanContent.startsWith("application/json")||cleanContent.endsWith("+json")){return"json"}if(cleanContent==="multipart/form-data"){return"formData"}if(["application/","audio/","image/","video/"].some((type)=>cleanContent.startsWith(type))){return"blob"}if(cleanContent.startsWith("text/")){return"text"}return};var checkForExistence=(options,name)=>{if(!name){return false}if(options.headers.has(name)||options.query?.[name]||options.headers.get("Cookie")?.includes(`${name}=`)){return true}return false};var setAuthParams=async({security,...options})=>{for(const auth of security){if(checkForExistence(options,auth.name)){continue}const token=await getAuthToken(auth,options.auth);if(!token){continue}const name=auth.name??"Authorization";switch(auth.in){case"query":if(!options.query){options.query={}}options.query[name]=token;break;case"cookie":options.headers.append("Cookie",`${name}=${token}`);break;case"header":default:options.headers.set(name,token);break}}};var buildUrl=(options)=>getUrl({baseUrl:options.baseUrl,path:options.path,query:options.query,querySerializer:typeof options.querySerializer==="function"?options.querySerializer:createQuerySerializer(options.querySerializer),url:options.url});var mergeConfigs=(a,b)=>{const config={...a,...b};if(config.baseUrl?.endsWith("/")){config.baseUrl=config.baseUrl.substring(0,config.baseUrl.length-1)}config.headers=mergeHeaders(a.headers,b.headers);return config};var headersEntries=(headers)=>{const entries=[];headers.forEach((value,key)=>{entries.push([key,value])});return entries};var mergeHeaders=(...headers)=>{const mergedHeaders=new Headers;for(const header of headers){if(!header){continue}const iterator=header instanceof Headers?headersEntries(header):Object.entries(header);for(const[key,value]of iterator){if(value===null){mergedHeaders.delete(key)}else if(Array.isArray(value)){for(const v of value){mergedHeaders.append(key,v)}}else if(value!==undefined){mergedHeaders.set(key,typeof value==="object"?JSON.stringify(value):value)}}}return mergedHeaders};class Interceptors{fns=[];clear(){this.fns=[]}eject(id){const index=this.getInterceptorIndex(id);if(this.fns[index]){this.fns[index]=null}}exists(id){const index=this.getInterceptorIndex(id);return Boolean(this.fns[index])}getInterceptorIndex(id){if(typeof id==="number"){return this.fns[id]?id:-1}return this.fns.indexOf(id)}update(id,fn){const index=this.getInterceptorIndex(id);if(this.fns[index]){this.fns[index]=fn;return id}return false}use(fn){this.fns.push(fn);return this.fns.length-1}}var createInterceptors=()=>({error:new Interceptors,request:new Interceptors,response:new Interceptors});var defaultQuerySerializer=createQuerySerializer({allowReserved:false,array:{explode:true,style:"form"},object:{explode:true,style:"deepObject"}});var defaultHeaders={"Content-Type":"application/json"};var createConfig=(override={})=>({...jsonBodySerializer,headers:defaultHeaders,parseAs:"auto",querySerializer:defaultQuerySerializer,...override});var createClient=(config={})=>{let _config=mergeConfigs(createConfig(),config);const getConfig=()=>({..._config});const setConfig=(config)=>{_config=mergeConfigs(_config,config);return getConfig()};const interceptors=createInterceptors();const beforeRequest=async(options)=>{const opts={..._config,...options,fetch:options.fetch??_config.fetch??globalThis.fetch,headers:mergeHeaders(_config.headers,options.headers),serializedBody:undefined};if(opts.security){await setAuthParams({...opts,security:opts.security})}if(opts.requestValidator){await opts.requestValidator(opts)}if(opts.body!==undefined&&opts.bodySerializer){opts.serializedBody=opts.bodySerializer(opts.body)}if(opts.body===undefined||opts.serializedBody===""){opts.headers.delete("Content-Type")}const resolvedOpts=opts;const url=buildUrl(resolvedOpts);return{opts:resolvedOpts,url}};const request=async(options)=>{const{opts,url}=await beforeRequest(options);const requestInit={redirect:"follow",...opts,body:getValidRequestBody(opts)};let request=new Request(url,requestInit);for(const fn of interceptors.request.fns){if(fn){request=await fn(request,opts)}}const _fetch=opts.fetch;let response;try{response=await _fetch(request)}catch(error){let finalError=error;for(const fn of interceptors.error.fns){if(fn){finalError=await fn(error,undefined,request,opts)}}finalError=finalError||{};if(opts.throwOnError){throw finalError}return opts.responseStyle==="data"?undefined:{error:finalError,request,response:undefined}}for(const fn of interceptors.response.fns){if(fn){response=await fn(response,request,opts)}}const result={request,response};if(response.ok){const parseAs=(opts.parseAs==="auto"?getParseAs(response.headers.get("Content-Type")):opts.parseAs)??"json";if(response.status===204||response.headers.get("Content-Length")==="0"){let emptyData;switch(parseAs){case"arrayBuffer":case"blob":case"text":emptyData=await response[parseAs]();break;case"formData":emptyData=new FormData;break;case"stream":emptyData=response.body;break;case"json":default:emptyData={};break}return opts.responseStyle==="data"?emptyData:{data:emptyData,...result}}let data;switch(parseAs){case"arrayBuffer":case"blob":case"formData":case"text":data=await response[parseAs]();break;case"json":{const text=await response.text();data=text?JSON.parse(text):{};break}case"stream":return opts.responseStyle==="data"?response.body:{data:response.body,...result}}if(parseAs==="json"){if(opts.responseValidator){await opts.responseValidator(data)}if(opts.responseTransformer){data=await opts.responseTransformer(data)}}return opts.responseStyle==="data"?data:{data,...result}}const textError=await response.text();let jsonError;try{jsonError=JSON.parse(textError)}catch{}const error=jsonError??textError;let finalError=error;for(const fn of interceptors.error.fns){if(fn){finalError=await fn(error,response,request,opts)}}finalError=finalError||{};if(opts.throwOnError){throw finalError}return opts.responseStyle==="data"?undefined:{error:finalError,...result}};const makeMethodFn=(method)=>(options)=>request({...options,method});const makeSseFn=(method)=>async(options)=>{const{opts,url}=await beforeRequest(options);return createSseClient({...opts,body:opts.body,headers:opts.headers,method,onRequest:async(url,init)=>{let request=new Request(url,init);for(const fn of interceptors.request.fns){if(fn){request=await fn(request,opts)}}return request},serializedBody:getValidRequestBody(opts),url})};const _buildUrl=(options)=>buildUrl({..._config,...options});return{buildUrl:_buildUrl,connect:makeMethodFn("CONNECT"),delete:makeMethodFn("DELETE"),get:makeMethodFn("GET"),getConfig,head:makeMethodFn("HEAD"),interceptors,options:makeMethodFn("OPTIONS"),patch:makeMethodFn("PATCH"),post:makeMethodFn("POST"),put:makeMethodFn("PUT"),request,setConfig,sse:{connect:makeSseFn("CONNECT"),delete:makeSseFn("DELETE"),get:makeSseFn("GET"),head:makeSseFn("HEAD"),options:makeSseFn("OPTIONS"),patch:makeSseFn("PATCH"),post:makeSseFn("POST"),put:makeSseFn("PUT"),trace:makeSseFn("TRACE")},trace:makeMethodFn("TRACE")}};var client=createClient(createConfig());var authLogout=(options)=>(options?.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/auth/logout",...options});var authMe=(options)=>(options?.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/auth/me",...options});var authMeOrganizations=(options)=>(options?.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/auth/me/organizations",...options});var authStartCliDevice=(options)=>(options.client??client).post({url:"/auth/cli/device",...options,headers:{"Content-Type":"application/json",...options.headers}});var authExchangeCliToken=(options)=>(options.client??client).post({url:"/auth/cli/token",...options,headers:{"Content-Type":"application/json",...options.headers}});var aiModelPresetsList=(options)=>(options?.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/ai/model-presets",...options});var aiModelPresetsDefault=(options)=>(options?.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/ai/model-presets/default",...options});var developmentSessionsCreate=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/development-sessions",...options,headers:{"Content-Type":"application/json",...options.headers}});var developmentSessionsTerminate=(options)=>(options.client??client).delete({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/development-sessions/{sessionId}",...options});var developmentSessionsHeartbeat=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/development-sessions/{sessionId}/heartbeat",...options});var developmentSessionsUpdateLocalManifest=(options)=>(options.client??client).put({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/development-sessions/{sessionId}/local-manifest",...options,headers:{"Content-Type":"application/json",...options.headers}});var hostedExtensionDiagnosticsReadTrace=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/hosted-extension-diagnostics/{diagnosticId}/trace",...options});var packageOperationsSnapshot=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-operations/{operationId}",...options});var packageOperationsEvents=(options)=>(options.client??client).sse.get({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-operations/{operationId}/events",...options});var packageOperationsContinueOperation=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-operations/{operationId}/continuations",...options});var packageReleasesUpdateInstallation=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-installations/update",...options,headers:{"Content-Type":"application/json",...options.headers}});var packageReleasesRollbackInstallation=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-installations/rollback",...options,headers:{"Content-Type":"application/json",...options.headers}});var packageReleasesPromote=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-releases/promote",...options,headers:{"Content-Type":"application/json",...options.headers}});var packageReleasesPublish=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-releases/publish",...options,headers:{"Content-Type":"application/json",...options.headers}});var packageReleasesLookupPublished=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/package-releases/lookup",...options,headers:{"Content-Type":"application/json",...options.headers}});var extensionPackagesListInstalled=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/packages/installed",...options});var extensionPackagesListReleases=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/packages/{fqn}/releases",...options});var extensionPackagesInstall=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/packages/{fqn}/install",...options,headers:{"Content-Type":"application/json",...options.headers}});var extensionPackagesSync=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/extensions/packages/{fqn}/sync",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationsSearch=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organizations/search",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationSetupCatalog=(options)=>(options?.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/setup/catalog",...options});var organizationSetupSetup=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/setup",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationTransferPreview=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/preview",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationTransferExports=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/exports",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationTransferImports=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/imports",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationTransferRollbacks=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/rollbacks",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationTransferRuns=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/runs",...options});var organizationTransferRun=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/runs/{runId}",...options});var organizationTransferCancel=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/runs/{runId}/cancel",...options});var organizationTransferResume=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/runs/{runId}/resume",...options});var organizationTransferPurge=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/runs/{runId}/purge",...options});var organizationTransferEvents=(options)=>(options.client??client).sse.get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/runs/{runId}/events",...options});var organizationTransferReport=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/runs/{runId}/report",...options});var organizationTransferUploadUrls=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/archives/{archiveId}/upload-urls",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationTransferDownloadUrls=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/transfer/archives/{archiveId}/download-urls",...options});var organizationCredentialsUpsert=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/credentials/upsert",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationCredentialsList=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/credentials/list",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationCredentialsGet=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/credentials/get",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationCredentialsRotate=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/credentials/rotate",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationCredentialsRevoke=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/credentials/revoke",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationServicePrincipalsList=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/service-principals",...options});var organizationExternalAppsList=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/external-apps",...options});var organizationExternalAppsEnroll=(options)=>(options.client??client).put({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/external-apps/by-fqn/{fqn}",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationExternalAppsGet=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/external-apps/{id}",...options});var organizationExternalAppsUpdate=(options)=>(options.client??client).put({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/external-apps/{id}",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationExternalAppsDisable=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/external-apps/{id}/disable",...options});var organizationExternalAppsRotateCredential=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/external-apps/{id}/credential/rotate",...options});var normalizedBackendUrl=(value)=>value.replace(/\/$/u,"");var makeBackendManagementClient=(config)=>createClient({baseUrl:normalizedBackendUrl(config.backendUrl),fetch:config.fetch,headers:config.token===undefined?{}:{authorization:`Bearer ${config.token}`}});function makeValue(value){return{_tag:"Value",value}}function makeRecord(keys,value){return{_tag:"Record",keys,value}}function makeArray(length,value){return{_tag:"Array",length,value}}var ConfigProvider=Reference("effect/ConfigProvider",{defaultValue:()=>fromEnv()});var Proto3={...PipeInspectableProto,toJSON(){return{_id:"ConfigProvider"}}};var identityPath=(path)=>path;function makeProvider(load,mapInput){const self=Object.create(Proto3);self.load=load;self.mapInput=mapInput;return self}function makeSource(get,transform){return makeProvider((path)=>get(transform(path)),(f)=>makeSource(get,(path)=>f(transform(path))))}function make17(get){return makeSource(get,identityPath)}var layer6=(self)=>isEffect2(self)?effect(ConfigProvider)(self):succeed5(ConfigProvider)(self);function fromUnknown(root,options){const preserveEmptyStrings=options?.preserveEmptyStrings===true;return make17((path)=>succeed6(nodeAtJson(root,path,preserveEmptyStrings)))}function nodeAtJson(root,path,preserveEmptyStrings){let cur=root;for(const seg of path){if(cur===null||cur===undefined)return;if(Array.isArray(cur)){if(typeof seg!=="number"||!Number.isInteger(seg)||seg<0||seg>=cur.length)return;cur=cur[seg];continue}if(isObject(cur)){if(typeof seg!=="string")return;if(!Object.hasOwn(cur,seg))return;cur=cur[seg];continue}return}return describeUnknown(cur,preserveEmptyStrings)}function describeUnknown(u,preserveEmptyStrings){if(u===undefined||u===null)return;if(typeof u==="string")return stringNode(u,preserveEmptyStrings);if(typeof u==="number"||typeof u==="boolean"||typeof u==="bigint"){return makeValue(String(u))}if(Array.isArray(u))return makeArray(u.length);if(isObject(u)){return makeRecord(new Set(Object.keys(u)))}return makeValue(format(u))}function stringNode(value,preserveEmptyStrings){const normalized=emptyStringAsMissing(value,preserveEmptyStrings);return normalized===undefined?undefined:makeValue(normalized)}function emptyStringAsMissing(value,preserveEmptyStrings){return value===""&&!preserveEmptyStrings?undefined:value}function fromEnvRecord(env,options){const preserveEmptyStrings=options?.preserveEmptyStrings===true;const trie=buildEnvTrie(env);return make17((path)=>succeed6(nodeAtEnv(trie,env,path,preserveEmptyStrings)))}function fromEnv(options){const env=options?.env??{...globalThis.process?.env,...import.meta?.env};return fromEnvRecord(env,{preserveEmptyStrings:options?.preserveEmptyStrings})}function buildEnvTrie(env){const trie={};for(const[name,value]of Object.entries(env)){if(value===undefined)continue;const segments=name.split("_");let node=trie;for(const seg of segments){const children=node.children??=Object.create(null);node=children[seg]??={}}}return trie}function nodeAtEnv(trie,env,path,preserveEmptyStrings){const key=path.map(String).join("_");const leafValue=emptyStringAsMissing(Object.hasOwn(env,key)?env[key]:undefined,preserveEmptyStrings);const trieNode=trieNodeAt(trie,path);const children=trieNode?.children?Object.keys(trieNode.children):[];if(children.length===0){return leafValue===undefined?undefined:makeValue(leafValue)}const allNumeric=children.every(isCanonicalArrayIndex);if(allNumeric){const length=Math.max(...children.map((k)=>parseInt(k,10)))+1;return makeArray(length,leafValue)}return makeRecord(new Set(children),leafValue)}function trieNodeAt(root,path){if(path.length===0)return root;let node=root;for(const seg of path){node=node?.children?.[String(seg)];if(!node)return}return node}var TypeId20="~effect/Config";class ConfigError{_tag="ConfigError";name="ConfigError";cause;constructor(cause){this.cause=cause}get message(){return this.cause.toString()}toString(){return`ConfigError(${this.message})`}}var Proto4={...Prototype2({label:"Config",evaluate(fiber){return this.parse(fiber.getRef(ConfigProvider))}}),[TypeId20]:TypeId20,toJSON(){return{_id:"Config"}}};function make18(evaluator){const self=Object.create(Proto4);self.evaluator=evaluator;self.parse=(provider)=>flatMapEager2(evaluator(provider,[]),fromResult2);return self}var isSourceError=(u)=>isTagged(u,"SourceError");var cursorToString=()=>"<configuration>";var mapReasons=(f)=>(self)=>catchCause2(self,(cause)=>failCause3(fromReasons(cause.reasons.map(f))));var loadCursor=(provider,path)=>provider.load(path).pipe(mapReasons((reason)=>isFailReason2(reason)?makeDieReason(reason.error).annotate(reasonAnnotations2(reason)):reason),mapEager2((node)=>({provider,path,node,toString:cursorToString})));var loadChildCursor=(cursor,segment)=>loadCursor(cursor.provider,[...cursor.path,segment]);var decodeFromCursor=(ast,decode)=>decodeTo(unknown,ast,new Transformation(transformEffect((input)=>decode(input)),passthrough()));var isScalarInput=(ast)=>{switch(ast._tag){case"Union":return ast.types.every(isScalarInput);case"Objects":case"Arrays":case"Suspend":return false;default:return true}};var hasProviderInput=(ast,node)=>{switch(ast._tag){case"Objects":return node?._tag==="Record";case"Arrays":return node?._tag==="Array";case"Union":return ast.types.some((ast)=>hasProviderInput(ast,node));case"Suspend":return hasProviderInput(ast.thunk(),node);default:return node?.value!==undefined}};var toConfigCursorAST=memoize((root)=>{const seen=new WeakSet;const recur=applyToSelfOrLastLinkEncoding((ast)=>{seen.add(ast);switch(ast._tag){case"Objects":{const materialize=fnUntraced2(function*(cursor){if(cursor.node?._tag!=="Record"){return}const node=cursor.node;const keys=new Set;for(const property of ast.propertySignatures){if(typeof property.name==="string")keys.add(property.name)}if(ast.indexSignatures.length>0){const input={};for(const key of node.keys){assignProperty(input,key,undefined)}for(const is of ast.indexSignatures){for(const key of getIndexSignatureKeys(input,is.parameter)){if(typeof key==="string")keys.add(key)}}}const out={};for(const key of keys){const child=yield*loadChildCursor(cursor,key);if(child.node!==undefined)assignProperty(out,key,child)}return out});return decodeFromCursor(ast.recur(recur,(ast)=>ast),materialize)}case"Arrays":{const materialize=fnUntraced2(function*(cursor){if(cursor.node?._tag!=="Array"){return}const out=[];for(let i=0;i<cursor.node.length;i++){out.push(yield*loadChildCursor(cursor,i))}return out});return decodeFromCursor(ast.recur(recur),materialize)}case"Union":for(const member of ast.types){recur(member)}if(!isScalarInput(ast))return ast.recur(recur);break;case"Suspend":{const target=ast.thunk();if(!seen.has(target))recur(target);return ast.recur(recur)}case"Declaration":case"Any":throw new globalThis.Error("Config.schema does not support opaque StringTree encodings",{cause:ast})}return decodeFromCursor(ast,(cursor)=>succeed6(cursor.node?.value))});return recur(root)});function schema(codec,path){const codecStringTree=toCodecStringTree2(codec);const encodedAst=toEncoded(codecStringTree.ast);const decodeCursor=decodeUnknownEffect(make16(toConfigCursorAST(codecStringTree.ast)));const localPath=typeof path==="string"?[path]:path??[];return make18((provider,pathPrefix)=>{const fullPath=[...pathPrefix,...localPath];return loadCursor(provider,fullPath).pipe(flatMapEager2((cursor)=>decodeCursor(cursor).pipe(mapEager2(succeed2),catchEager2((issue)=>{const error=new ConfigError(new SchemaError(fullPath.length>0?new Pointer(fullPath,issue):issue));return hasProviderInput(encodedAst,cursor.node)?fail6(error):succeed6(fail2(error))}))),mapReasons((reason)=>isDieReason2(reason)&&isSourceError(reason.defect)?makeFailReason(new ConfigError(reason.defect)).annotate(reasonAnnotations2(reason)):reason))})}class BackendManagementConfigurationError extends TaggedError3()("BackendManagementConfigurationError",{message:String5}){}var tryConfiguration=(evaluate)=>try_2({catch:(cause)=>is2(BackendManagementConfigurationError)(cause)?cause:new BackendManagementConfigurationError({message:cause instanceof Error?cause.message:"CLI configuration step failed"}),try:evaluate});import{chmodSync,existsSync,mkdirSync,readFileSync,renameSync,writeFileSync}from"fs";import path from"path";var ProfileSchema=Struct({apiOrigin:String5,currentOrganizationId:optionalKey2(String5),session:optionalKey2(Struct({expiresAt:optionalKey2(String5),token:String5}))});var ProfileStoreSchema=Struct({current:optionalKey2(String5),profiles:Record(String5,ProfileSchema)});var profileStoreJson=fromJsonString2(ProfileStoreSchema);var decodeProfileStore=decodeUnknownSync(profileStoreJson);var encodeProfileStore=encodeSync(profileStoreJson);var nonEmpty=(value)=>value===""?undefined:value;var profileDirectory=(environment)=>{const configHome=nonEmpty(environment.XDG_CONFIG_HOME);if(configHome!==undefined){return path.join(configHome,"ci")}const home=nonEmpty(environment.HOME);return home===undefined?undefined:path.join(home,".config","ci")};var profileName=(apiOrigin)=>new URL(apiOrigin).host;var readProfileStore=(environment)=>{const directory=profileDirectory(environment);if(directory===undefined){return{profiles:{}}}const file=path.join(directory,"profiles.json");if(!existsSync(file)){return{profiles:{}}}try{return decodeProfileStore(readFileSync(file,"utf-8"))}catch{throw new BackendManagementConfigurationError({message:`CLI Profile file ${file} is invalid; fix or remove it, then run ci login`})}};var writeProfileStore=(environment,store)=>{const directory=profileDirectory(environment);if(directory===undefined){throw new BackendManagementConfigurationError({message:"Cannot locate the CLI configuration directory; set XDG_CONFIG_HOME or HOME"})}mkdirSync(directory,{mode:448,recursive:true});chmodSync(directory,448);const file=path.join(directory,"profiles.json");const temporary=`${file}.${process.pid}.tmp`;writeFileSync(temporary,`${encodeProfileStore(store)}
245
+ `,{mode:384});chmodSync(temporary,384);renameSync(temporary,file)};var updateProfile=(environment,name,update)=>{const store=readProfileStore(environment);const latest=store.profiles[name];const next=latest===undefined?undefined:update(latest);if(next!==undefined){writeProfileStore(environment,{...store,profiles:{...store.profiles,[name]:next}})}return next};var configurationError=(message)=>new BackendManagementConfigurationError({message});var nonEmpty2=(value)=>value===undefined||value.trim()===""?undefined:value;var optionValue=(args,name)=>{const index=args.indexOf(`--${name}`);const value=index===-1?undefined:args[index+1];return value===undefined||value.startsWith("--")?undefined:value};var sameOrigin=(left,right)=>{try{return new URL(left).origin===new URL(right).origin}catch{return false}};var storedProfile=(store,name)=>name!==undefined&&Object.hasOwn(store.profiles,name)?store.profiles[name]:undefined;var tenantProfileName=(apiOrigin)=>{try{return profileName(apiOrigin)}catch{return}};var selectProfile=(store,requestedName,explicitOrigin)=>{if(requestedName!==undefined){const profile=storedProfile(store,requestedName);if(profile===undefined){throw configurationError(`CLI Profile ${requestedName} does not exist; run ci login or select another --profile`)}if(explicitOrigin!==undefined&&!sameOrigin(profile.apiOrigin,explicitOrigin)){throw configurationError(`CLI Profile ${requestedName} belongs to ${profile.apiOrigin}, not ${explicitOrigin}`)}return{name:requestedName,profile}}const name=explicitOrigin===undefined?store.current:tenantProfileName(explicitOrigin);const profile=storedProfile(store,name);if(name===undefined||profile===undefined||explicitOrigin!==undefined&&!sameOrigin(profile.apiOrigin,explicitOrigin)){return}return{name,profile}};var sessionToken=(selected)=>{const session=selected?.profile.session;if(selected===undefined||session===undefined){return}if(session.expiresAt!==undefined&&Date.parse(session.expiresAt)<=Date.now()){throw configurationError(`The CLI Session of Profile ${selected.name} expired; run ci login or set CI_MANAGEMENT_TOKEN`)}return session.token};var isOrganizationApiKey=(token)=>token.startsWith("dpk_");var resolveTarget=(input,organizationRequired)=>{const{args,environment}=input;const explicitOrigin=nonEmpty2(optionValue(args,"backend-url"))??nonEmpty2(environment.CI_BACKEND_URL);const environmentToken=nonEmpty2(environment.CI_MANAGEMENT_TOKEN);const explicitOrganization=nonEmpty2(optionValue(args,"organization"));const apiKey=environmentToken!==undefined&&isOrganizationApiKey(environmentToken);const profileNeeded=explicitOrigin===undefined||environmentToken===undefined||organizationRequired&&explicitOrganization===undefined&&!apiKey;const selected=profileNeeded?selectProfile(readProfileStore(environment),nonEmpty2(optionValue(args,"profile"))??nonEmpty2(environment.CI_PROFILE),explicitOrigin):undefined;const apiOrigin=explicitOrigin??selected?.profile.apiOrigin;if(apiOrigin===undefined){throw configurationError("Missing backend URL: pass --backend-url, set CI_BACKEND_URL, or run ci login")}const token=environmentToken??sessionToken(selected);if(token===undefined){throw configurationError("Missing credential: run ci login or set CI_MANAGEMENT_TOKEN")}return{apiOrigin,credentialSource:environmentToken===undefined?"cli-session":"management-token",organizationId:explicitOrganization??(apiKey?undefined:selected?.profile.currentOrganizationId),profile:selected?.name,token}};var resolveBackendManagementTarget=(input)=>resolveTarget(input,input.organizationLookup===true);var missingOrganizationMessage="Missing Organization: pass --organization or run ci orgs use <organization-id>";var selectedProfile=(input)=>{const store=readProfileStore(input.environment);const selected=selectProfile(store,nonEmpty2(optionValue(input.args,"profile"))??nonEmpty2(input.environment.CI_PROFILE),nonEmpty2(optionValue(input.args,"backend-url"))??nonEmpty2(input.environment.CI_BACKEND_URL));return selected===undefined?undefined:{...selected,store}};var resolveOrganizationTarget=(input)=>{const target=resolveTarget(input,true);if(target.organizationId===undefined){throw configurationError(isOrganizationApiKey(target.token)?"Missing Organization: pass --organization with the Organization of the CI_MANAGEMENT_TOKEN API key":missingOrganizationMessage)}return{...target,organizationId:target.organizationId}};var apiKeyOrganizationMismatch=(input)=>isOrganizationApiKey(input.token)&&input.apiKey!==undefined&&input.apiKey.organizationId!==input.organizationId?configurationError(`Organization API key ${input.apiKey.name} belongs to Organization ${input.apiKey.organizationId} and cannot act for Organization ${input.organizationId}; pass --organization ${input.apiKey.organizationId} or use a credential for ${input.organizationId}`):undefined;var backendManagementClientFromCli=(input)=>{const target=resolveBackendManagementTarget(input);return makeBackendManagementClient({backendUrl:target.apiOrigin,fetch:input.fetch??globalThis.fetch,token:target.token})};var deploymentManagementClients=fn2("BackendManagement.deploymentClients")(function*deploymentManagementClients(input){const publisher=yield*schema(Redacted(String5.check(isMinLength(1))),"CI_PUBLISHER_TOKEN").pipe(provide3(layer6(fromUnknown(input.environment))));return{organization:makeBackendManagementClient({backendUrl:input.target.apiOrigin,fetch:input.fetch,token:input.target.token}),publisher:makeBackendManagementClient({backendUrl:input.target.apiOrigin,fetch:input.fetch,token:value2(publisher)})}});class DevelopmentSessionRejectedError extends TaggedError3()("DevelopmentSessionRejectedError",{reason:Literals(["session_not_found","session_owned"])}){}var hasWireTag=(cause,tag)=>is2(TaggedStruct(tag,{}))(cause);var createDevelopmentSession=async(client,input)=>{try{const result=await developmentSessionsCreate({body:{hostOrigins:[...input.hostOrigins],packageManifest:{fqn:input.packageFqn},protocolVersion:"v1"},client,throwOnError:true});return result.data}catch(error){throw hasWireTag(error,"Conflict")?new DevelopmentSessionRejectedError({reason:"session_owned"}):error}};var updateDevelopmentSessionLocalManifest=flow((client,input)=>tryPromise2(()=>developmentSessionsUpdateLocalManifest({body:{hostedContributions:[...input.hostedContributions]},client,path:{sessionId:input.sessionId},throwOnError:true})).pipe(map5((result)=>result.data),mapError2((cause)=>hasWireTag(cause.cause,"NotFound")?new DevelopmentSessionRejectedError({reason:"session_not_found"}):cause)),runPromise2);var heartbeatDevelopmentSession=flow((client,sessionId)=>tryPromise2(()=>developmentSessionsHeartbeat({client,path:{sessionId},throwOnError:true})).pipe(asVoid2,mapError2((cause)=>hasWireTag(cause.cause,"NotFound")?new DevelopmentSessionRejectedError({reason:"session_not_found"}):cause)),runPromise2);var terminateDevelopmentSession=flow((client,sessionId)=>tryPromise2(()=>developmentSessionsTerminate({client,path:{sessionId},throwOnError:true})).pipe(asVoid2),runPromise2);class ManagementRequestError extends TaggedError3()("ManagementRequestError",{body:optional2(Unknown2),cause:optional2(Unknown2),message:String5,status:Finite}){}var BackendReason=Union2([Struct({message:String5}),Struct({detail:String5}),Struct({error_description:String5}),Struct({error:String5})]);var backendReason=(body)=>{if(!is2(BackendReason)(body)){return}if("message"in body){return body.message}if("detail"in body){return body.detail}return"error_description"in body?body.error_description:body.error};var requestFailure=(label,response,body)=>{if(response.status===401){return new ManagementRequestError({body,message:`${label} failed: the backend rejected the credential; run ci login or check CI_MANAGEMENT_TOKEN`,status:401})}const reason=backendReason(body);return new ManagementRequestError({body,message:`${label} failed (HTTP ${response.status})${reason===undefined?"":`: ${reason}`}`,status:response.status})};var requestTimeout="30 seconds";var withRequestTimeout=(label,subject)=>(effect)=>effect.pipe(timeoutOrElse2({duration:requestTimeout,orElse:()=>fail6(new ManagementRequestError({message:`${label} failed: ${subject} did not respond within ${requestTimeout}`,status:0}))}));var unreachable=(label,cause)=>new ManagementRequestError({cause,message:`${label} failed: could not reach the backend`,status:0});var sendRequest=(label,operation,options)=>tryPromise2({catch:(cause)=>unreachable(label,cause),try:async(signal)=>await operation({...options,signal})}).pipe(withRequestTimeout(label,"the backend"),flatMap4((result)=>{const{response}=result;return response===undefined?fail6(unreachable(label,result.error)):succeed6({response,result})}));var managementData=(label,operation,options)=>flatMap4(sendRequest(label,operation,options),({response,result})=>response.ok&&result.data!==undefined?succeed6(result.data):fail6(requestFailure(label,response,result.error)));var managementOk=(label,operation,options)=>flatMap4(sendRequest(label,operation,options),({response,result})=>response.ok?void_3:fail6(requestFailure(label,response,result.error)));var TenantDiscoverySchema=Struct({api_base_url:String5,dashboard_url:String5,issuer:String5,jwks_uri:String5});var JwksSchema=Struct({keys:ArraySchema(Unknown2)});var SigningKeyUnavailable=Struct({error:Literal2("signing_key_unavailable")});var send=(fetch2,label,url)=>tryPromise2({catch:(cause)=>new ManagementRequestError({cause,message:`${label} failed: could not reach ${url}`,status:0}),try:async(signal)=>{const response=await fetch2(url,{headers:{accept:"application/json"},signal});return{response,text:await response.text()}}}).pipe(withRequestTimeout(label,url));var notJson=(label,url,response,cause)=>new ManagementRequestError({cause,message:`${label} failed: ${url} did not return JSON (HTTP ${response.status})`,status:response.status});var parseJson2=(text,onFailure)=>try_2({catch:onFailure,try:()=>JSON.parse(text)});var readTenantDiscovery=fn2("BackendManagement.readTenantDiscovery")(function*readTenantDiscovery(fetch2,apiUrl){const origin=yield*try_2({catch:()=>new ManagementRequestError({message:`Invalid API URL ${apiUrl}`,status:0}),try:()=>new URL(apiUrl).origin});const label=`Tenant discovery at ${new URL(origin).host}`;const notApiUrl=(status,cause)=>new ManagementRequestError({cause,message:`${label} failed: ${apiUrl} is not a CI API URL; copy the login command from the dashboard: Organization settings \u2192 CLI`,status});const{response,text}=yield*send(fetch2,label,`${origin}/.well-known/ci-configuration`);if(response.status===404){return yield*notApiUrl(404)}const body=yield*parseJson2(text,(cause)=>response.ok?notApiUrl(response.status,cause):notJson(label,apiUrl,response,cause));if(!response.ok){return yield*requestFailure(label,response,body)}const document=yield*decodeUnknownEffect2(TenantDiscoverySchema)(body).pipe(mapError2((cause)=>notApiUrl(response.status,cause)));return{apiBaseUrl:document.api_base_url,dashboardUrl:document.dashboard_url,issuer:document.issuer,jwksUri:document.jwks_uri}});var readSigningKeyCount=fn2("BackendManagement.readSigningKeyCount")(function*readSigningKeyCount(fetch2,jwksUri){const label="JWKS read";const{response,text}=yield*send(fetch2,label,jwksUri);const body=yield*parseJson2(text,(cause)=>notJson(label,jwksUri,response,cause));if(response.status===503&&is2(SigningKeyUnavailable)(body)){return yield*new ManagementRequestError({body,message:"JWKS is unavailable: the backend has no External App signing key (set APP_EXTERNAL_APP_JWT_PRIVATE_JWK)",status:503})}if(!response.ok||!is2(JwksSchema)(body)){return yield*requestFailure(label,response,body)}return body.keys.length});var readIdentity=(client)=>managementData("Identity read",authMe,{client});var resolveManagementContext=fn2("BackendManagement.resolveContext")(function*resolveManagementContext(input){const target=yield*try_2({catch:(cause)=>is2(BackendManagementConfigurationError)(cause)?cause:new BackendManagementConfigurationError({message:"Could not resolve the backend credential"}),try:()=>resolveBackendManagementTarget({args:input.args,environment:input.environment,organizationLookup:true})});const client=makeBackendManagementClient({backendUrl:target.apiOrigin,fetch:input.fetch,token:target.token});const organizationId=target.organizationId===undefined&&isOrganizationApiKey(target.token)?(yield*readIdentity(client)).organizationId:target.organizationId;return{client,organizationId,target}});var resolveOrganizationContext=(input)=>flatMap4(resolveManagementContext(input),(context)=>{const{organizationId}=context;return organizationId===undefined?fail6(new BackendManagementConfigurationError({message:missingOrganizationMessage})):succeed6({...context,organizationId})});var explainOrganizationForbidden=(context,organizationId)=>(error)=>error.status===403&&isOrganizationApiKey(context.target.token)?readIdentity(context.client).pipe(map5((identity)=>apiKeyOrganizationMismatch({apiKey:identity.apiKeyName===undefined||identity.organizationId===undefined?undefined:{name:identity.apiKeyName,organizationId:identity.organizationId},organizationId,token:context.target.token})??error),orElseSucceed2(()=>error),flatMap4(fail6)):fail6(error);class CommandOptionsError extends TaggedError3()("CommandOptionsError",{message:String5}){}var targetOptions=["backend-url","organization","profile"];var parseCommandOptions=(args,spec)=>{const repeatable=new Set(spec.repeatable);const valueNames=new Set([...spec.values??[],...repeatable]);const switchNames=new Set(spec.switches);const values=new Map;const switches=new Set;const positionals=[];for(let index=0;index<args.length;index+=1){const argument=args[index]??"";if(!argument.startsWith("--")){positionals.push(argument);continue}const name=argument.slice(2);if(switchNames.has(name)){switches.add(name);continue}if(!valueNames.has(name)){throw new CommandOptionsError({message:`Unknown option ${argument}`})}const value=args[index+1];if(value===undefined||value.startsWith("--")||value.trim()===""){throw new CommandOptionsError({message:`Missing value for ${argument}`})}index+=1;const existing=values.get(name);if(existing!==undefined&&!repeatable.has(name)){throw new CommandOptionsError({message:`Duplicate option ${argument}`})}values.set(name,[...existing??[],value])}if(positionals.length>(spec.positionals??0)){throw new CommandOptionsError({message:`Unexpected argument ${positionals[spec.positionals??0]??""}`})}return{positionals,switches,values}};var optionValue2=(options,name)=>options.values.get(name)?.[0];var optionValues=(options,name)=>options.values.get(name)??[];var parseCommandOptionsEffect=(args,spec)=>try_2({catch:(cause)=>is2(CommandOptionsError)(cause)?cause:new CommandOptionsError({message:"Invalid options"}),try:()=>parseCommandOptions(args,spec)});class AppsCommandError extends TaggedError3()("AppsCommandError",{cause:optional2(Unknown2),message:String5}){}var usage="Usage: ci apps list | ci apps get <application-id> | ci apps rotate-secret <application-id> | ci apps disable <application-id> | ci apps enroll ... | ci apps env ... | ci apps redirect-uris ... | ci apps origins ...";var encodeJson=encodeSync(fromJsonString2(Unknown2));var applicationSummary=(application)=>({allowedOrigins:application.allowedOrigins,applicationId:application.id,applicationType:application.applicationType,audience:application.audience,clientId:application.clientId,enabled:application.enabled,fqn:application.fqn,name:application.name,postLogoutRedirectUris:application.postLogoutRedirectUris,primaryRedirectUri:application.primaryRedirectUri,redirectUris:application.redirectUris,scopes:application.scopes});var appsCommandEffect=(args,dependencies)=>gen2(function*appsCommand(){const[command,...rest]=args;const options=yield*parseCommandOptionsEffect(rest,{positionals:command==="list"?0:1,values:targetOptions});const[applicationId]=options.positionals;const applicationCommands=new Set(["disable","get","rotate-secret"]);if(command!=="list"&&(applicationId===undefined||!applicationCommands.has(command??""))){return yield*new AppsCommandError({message:usage})}const context=yield*resolveOrganizationContext({args:rest,environment:dependencies.environment,fetch:dependencies.fetch});const request={client:context.client,headers:{"x-organization-id":context.organizationId}};const operation=(id)=>gen2(function*appsOperation(){if(command==="get"){return applicationSummary(yield*managementData("External App read",organizationExternalAppsGet,{...request,path:{id}}))}if(command==="disable"){return applicationSummary(yield*managementData("External App disable",organizationExternalAppsDisable,{...request,path:{id}}))}const rotated=yield*managementData("Client secret rotation",organizationExternalAppsRotateCredential,{...request,path:{id}});return{applicationId:rotated.application.id,clientId:rotated.application.clientId,clientSecret:rotated.clientSecret}});const explainForbidden=(effect)=>effect.pipe(catchTag2("ManagementRequestError",explainOrganizationForbidden(context,context.organizationId)));const result=applicationId===undefined?yield*explainForbidden(managementData("External App list",organizationExternalAppsList,request).pipe(map5((response)=>response.data.map(applicationSummary)))):yield*explainForbidden(operation(applicationId));return yield*sync2(()=>{dependencies.writeOutput(`${encodeJson(result)}
246
+ `)})}).pipe(mapError2((cause)=>is2(AppsCommandError)(cause)?cause:new AppsCommandError({cause,message:cause.message})));var check=(name,passed,detail)=>({detail,name,passed});var redirectCheck=(applications,fqn,redirectUris)=>{if(fqn===undefined){const missing=redirectUris.filter((uri)=>!applications.some((application)=>application.enabled&&application.redirectUris.includes(uri)));return missing.length===0?check("redirect-uri",true,`registered: ${redirectUris.join(", ")}`):check("redirect-uri",false,`no enabled External App registers ${missing.join(", ")}`)}const application=applications.find((candidate)=>candidate.fqn===fqn);if(application===undefined){return check("redirect-uri",false,`no External App ${fqn} exists`)}if(!application.enabled){return check("redirect-uri",false,`External App ${fqn} is disabled`)}const expected=redirectUris.length===0?application.redirectUris:redirectUris;const missing=expected.filter((uri)=>!application.redirectUris.includes(uri));return missing.length===0&&expected.length>0?check("redirect-uri",true,`${fqn} registers ${expected.join(", ")}`):check("redirect-uri",false,`${fqn} does not register ${missing.length===0?"any redirect URI":missing.join(", ")}`)};var listApplications=(context)=>managementData("External App list",organizationExternalAppsList,{client:context.client,headers:{"x-organization-id":context.organizationId}}).pipe(map5((response)=>response.data),catchTag2("ManagementRequestError",explainOrganizationForbidden(context,context.organizationId)));var runTenantPreflight=fn2("Preflight.tenant")(function*runTenantPreflight(input){const{context}=input;const{apiOrigin}=context.target;const discovery=yield*result2(readTenantDiscovery(input.fetch,apiOrigin));const keys=yield*result2(readSigningKeyCount(input.fetch,isSuccess2(discovery)?discovery.success.jwksUri:`${apiOrigin.replace(/\/$/u,"")}/oauth/jwks`));const applications=yield*result2(listApplications(context));return{applications:isSuccess2(applications)?applications.success:undefined,checks:[isSuccess2(discovery)?check("discovery",true,`issuer ${discovery.success.issuer}`):check("discovery",false,discovery.failure.message),isFailure2(keys)?check("jwks",false,keys.failure.message):check("jwks",keys.success>0,keys.success>0?`${keys.success} signing key(s) published`:"JWKS publishes no signing key"),isSuccess2(applications)?check("organization",true,`Organization ${context.organizationId} is accessible with this credential`):check("organization",false,applications.failure.message)],discovery:isSuccess2(discovery)?discovery.success:undefined}});var runRedirectPreflight=fn2("Preflight.redirect")(function*runRedirectPreflight(input){const applications=yield*result2(listApplications(input.context));return isSuccess2(applications)?redirectCheck(applications.success,input.fqn,input.redirectUris):check("redirect-uri",false,applications.failure.message)});var runPreflight=fn2("Preflight.run")(function*runPreflight(input){const tenant=yield*runTenantPreflight(input);const checks=[...tenant.checks];if(input.fqn!==undefined||input.redirectUris.length>0){checks.push(tenant.applications===undefined?check("redirect-uri",false,"not checked: the Organization check failed"):redirectCheck(tenant.applications,input.fqn,input.redirectUris))}return{checks,discovery:tenant.discovery}});var renderPreflight=(checks)=>`${checks.map((entry)=>`${entry.passed?"PASS":"FAIL"} ${entry.name}: ${entry.detail}`).join(`
247
247
  `)}
248
248
  `;var loopbackHostnames=new Set(["localhost","127.0.0.1","[::1]"]);var exactUrlProblem=(value,kind)=>{if(!URL.canParse(value)){return`${value} is not an absolute URL`}const url=new URL(value);if(value.includes("#")){return`${value} must not contain a fragment (#)`}if(value.includes("*")){return`${value} must not contain a wildcard (*)`}const loopbackHttp=url.protocol==="http:"&&loopbackHostnames.has(url.hostname)&&url.port!=="";if(url.protocol!=="https:"&&!loopbackHttp){return`${value} must use HTTPS, or HTTP on localhost, 127.0.0.1 or [::1] with an explicit port`}if(kind==="origin"&&value!==url.origin){return`${value} is not an exact origin; use ${url.origin}`}return};var originOf=(value)=>URL.canParse(value)?new URL(value).origin:value;class AppsUrlsCommandError extends TaggedError3()("AppsUrlsCommandError",{cause:optional2(Unknown2),message:String5}){}var usage2="Usage: ci apps redirect-uris list <application> | ci apps redirect-uris add <application> <uri> [--primary] [--no-trust-origin] | ci apps redirect-uris remove <application> <uri> | ci apps redirect-uris set-primary <application> <uri> | ci apps origins list <application> | ci apps origins add <application> <origin> | ci apps origins remove <application> <origin> (<application> is an Application Id or FQN)";var actions={origins:new Set(["add","list","remove"]),"redirect-uris":new Set(["add","list","remove","set-primary"])};var isGroup=(value)=>value==="origins"||value==="redirect-uris";var applicationIdPattern=/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu;var encodeJson2=encodeSync(fromJsonString2(Unknown2));var fail11=(message)=>new AppsUrlsCommandError({message});var isPackageOwned=(application)=>application.lifecycle!==null||application.deploymentMetadata!==null;var plan=(body,notes)=>({body:Object.keys(body).length===0?undefined:body,notes});var redirectUriPlan=(application,action,uri,switches)=>{const{allowedOrigins,fqn,primaryRedirectUri,redirectUris}=application;const registered=redirectUris.includes(uri);if(action==="add"){const body={};const notes=[];if(registered){notes.push(`${uri} is already a redirect URI of ${fqn}
249
249
  `)}else{body.redirectUris=[...redirectUris,uri]}if((switches.has("primary")||primaryRedirectUri===null)&&uri!==primaryRedirectUri){body.primaryRedirectUri=uri}const origin=originOf(uri);if(!switches.has("no-trust-origin")&&!allowedOrigins.includes(origin)){body.allowedOrigins=[...allowedOrigins,origin];notes.push(`Trusted origin ${origin} for ${fqn}; pass --no-trust-origin to skip this
@@ -261,12 +261,12 @@ ${prefix}}`}return stack};var FiberTypeId="~effect/Fiber";var fiberVariance={_A:
261
261
  `:`
262
262
  `}`).join("")};class EnvFileError extends TaggedError3()("EnvFileError",{cause:Unknown2,message:String5}){}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:String5}){}var EnrollmentRejected=TaggedStruct("ExternalAppEnrollmentRejected",{message:String5,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
- `);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})));var make17=(context)=>({get:(body)=>managementData("Credential read",organizationCredentialsGet,{body,client:context.client,headers:{"x-organization-id":context.organizationId}}),list:(body)=>managementData("Credential list",organizationCredentialsList,{body,client:context.client,headers:{"x-organization-id":context.organizationId}}),revoke:(body)=>managementData("Credential revocation",organizationCredentialsRevoke,{body,client:context.client,headers:{"x-organization-id":context.organizationId}}),rotate:(body)=>managementData("Credential rotation",organizationCredentialsRotate,{body,client:context.client,headers:{"x-organization-id":context.organizationId}}),upsert:(body)=>managementData("Credential upsert",organizationCredentialsUpsert,{body,client:context.client,headers:{"x-organization-id":context.organizationId}})});class Credentials extends Service()("@ci/cli/Credentials"){}var credentialsLayer=(context)=>succeed5(Credentials,make17(context));class CredentialsCommandError extends TaggedError3()("CredentialsCommandError",{cause:optional2(Unknown2),message:String5}){}var CredentialName=NonEmptyString.pipe(brand("CliCredentialName"));var credentialName=(value)=>value===undefined?fail6(new CredentialsCommandError({message:"Missing required option --name"})):decodeEffect2(CredentialName)(value);var credentialMetadata=(credential)=>({createdAt:credential.createdAt,expiresAt:credential.expiresAt,id:credential.id,lastUsedAt:credential.lastUsedAt,name:credential.name,owner:credential.owner,prefix:credential.prefix,revokedAt:credential.revokedAt,rotatedAt:credential.rotatedAt,scopes:credential.scopes,serverRoles:credential.serverRoles});var credentialCommandEffect=(args,parsed,dependencies)=>gen2(function*executeCredentialCommand(){const command=yield*parsed;yield*readEnvFileContent(dependencies,command.envFile);const context=yield*resolveOrganizationContext({args,environment:dependencies.environment,fetch:dependencies.fetch});const target=yield*gen2(function*resolveCredentialOwner(){if(command.target.kind==="app"){const application=yield*readApplication(context,command.target.reference);return{clientId:application.clientId,owner:{appId:application.id,kind:"app"},secretKey:"CLIENT_SECRET"}}const principals=yield*managementData("Service principal list",organizationServicePrincipalsList,{client:context.client,headers:{"x-organization-id":context.organizationId}});const principal=principals.data.find((item)=>item.fqn===command.target.reference);if(principal===undefined){return yield*new CredentialsCommandError({message:`No service principal ${command.target.reference} in Organization ${context.organizationId}; pass its exact FQN`})}return{clientId:principal.id,owner:{kind:"principal",principalId:principal.id},secretKey:"MANAGEMENT_TOKEN"}});const metadataForOwner=(credential)=>({...credentialMetadata(credential),clientId:target.clientId});const result=yield*gen2(function*executeCredentialAction(){const credentials=yield*Credentials;const{owner}=target;if(command.action==="list"){const listed=yield*credentials.list({owner});return{kind:"metadata",value:{data:listed.data.map(metadataForOwner)}}}if(command.name===undefined){return yield*new CredentialsCommandError({message:"Missing required option --name"})}const named={name:command.name,owner};switch(command.action){case"get":{return{kind:"metadata",value:metadataForOwner(yield*credentials.get(named))}}case"revoke":{return{kind:"metadata",value:metadataForOwner(yield*credentials.revoke(named))}}case"rotate":{return{kind:"issued",...yield*credentials.rotate(named),created:false,rotated:true}}case"upsert":{const body={...named};if(command.target.kind==="principal"){body.scopes=command.target.scopes}else if(command.target.serverRoles.length>0){body.serverRoles=command.target.serverRoles}const upserted=yield*credentials.upsert(body);return command.rotate&&!upserted.created?{kind:"issued",...yield*credentials.rotate(named),created:false,rotated:true}:{kind:"issued",...upserted,rotated:false}}default:{const exhaustive=command.action;return exhaustive}}}).pipe(provide3(credentialsLayer(context)));if(result.kind==="metadata"){dependencies.writeOutput(`${JSON.stringify(result.value)}
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})));var make19=(context)=>({get:(body)=>managementData("Credential read",organizationCredentialsGet,{body,client:context.client,headers:{"x-organization-id":context.organizationId}}),list:(body)=>managementData("Credential list",organizationCredentialsList,{body,client:context.client,headers:{"x-organization-id":context.organizationId}}),revoke:(body)=>managementData("Credential revocation",organizationCredentialsRevoke,{body,client:context.client,headers:{"x-organization-id":context.organizationId}}),rotate:(body)=>managementData("Credential rotation",organizationCredentialsRotate,{body,client:context.client,headers:{"x-organization-id":context.organizationId}}),upsert:(body)=>managementData("Credential upsert",organizationCredentialsUpsert,{body,client:context.client,headers:{"x-organization-id":context.organizationId}})});class Credentials extends Service()("@ci/cli/Credentials"){}var credentialsLayer=(context)=>succeed5(Credentials,make19(context));class CredentialsCommandError extends TaggedError3()("CredentialsCommandError",{cause:optional2(Unknown2),message:String5}){}var CredentialName=NonEmptyString.pipe(brand("CliCredentialName"));var credentialName=(value)=>value===undefined?fail6(new CredentialsCommandError({message:"Missing required option --name"})):decodeEffect2(CredentialName)(value);var credentialMetadata=(credential)=>({createdAt:credential.createdAt,expiresAt:credential.expiresAt,id:credential.id,lastUsedAt:credential.lastUsedAt,name:credential.name,owner:credential.owner,prefix:credential.prefix,revokedAt:credential.revokedAt,rotatedAt:credential.rotatedAt,scopes:credential.scopes,serverRoles:credential.serverRoles});var credentialCommandEffect=(args,parsed,dependencies)=>gen2(function*executeCredentialCommand(){const command=yield*parsed;yield*readEnvFileContent(dependencies,command.envFile);const context=yield*resolveOrganizationContext({args,environment:dependencies.environment,fetch:dependencies.fetch});const target=yield*gen2(function*resolveCredentialOwner(){if(command.target.kind==="app"){const application=yield*readApplication(context,command.target.reference);return{clientId:application.clientId,owner:{appId:application.id,kind:"app"},secretKey:"CLIENT_SECRET"}}const principals=yield*managementData("Service principal list",organizationServicePrincipalsList,{client:context.client,headers:{"x-organization-id":context.organizationId}});const principal=principals.data.find((item)=>item.fqn===command.target.reference);if(principal===undefined){return yield*new CredentialsCommandError({message:`No service principal ${command.target.reference} in Organization ${context.organizationId}; pass its exact FQN`})}return{clientId:principal.id,owner:{kind:"principal",principalId:principal.id},secretKey:"MANAGEMENT_TOKEN"}});const metadataForOwner=(credential)=>({...credentialMetadata(credential),clientId:target.clientId});const result=yield*gen2(function*executeCredentialAction(){const credentials=yield*Credentials;const{owner}=target;if(command.action==="list"){const listed=yield*credentials.list({owner});return{kind:"metadata",value:{data:listed.data.map(metadataForOwner)}}}if(command.name===undefined){return yield*new CredentialsCommandError({message:"Missing required option --name"})}const named={name:command.name,owner};switch(command.action){case"get":{return{kind:"metadata",value:metadataForOwner(yield*credentials.get(named))}}case"revoke":{return{kind:"metadata",value:metadataForOwner(yield*credentials.revoke(named))}}case"rotate":{return{kind:"issued",...yield*credentials.rotate(named),created:false,rotated:true}}case"upsert":{const body={...named};if(command.target.kind==="principal"){body.scopes=command.target.scopes}else if(command.target.serverRoles.length>0){body.serverRoles=command.target.serverRoles}const upserted=yield*credentials.upsert(body);return command.rotate&&!upserted.created?{kind:"issued",...yield*credentials.rotate(named),created:false,rotated:true}:{kind:"issued",...upserted,rotated:false}}default:{const exhaustive=command.action;return exhaustive}}}).pipe(provide3(credentialsLayer(context)));if(result.kind==="metadata"){dependencies.writeOutput(`${JSON.stringify(result.value)}
265
265
  `);return yield*void_3}const secret=(result.created||result.rotated)&&"secret"in result?result.secret:undefined;const metadata=metadataForOwner(result.credential);if(command.envFile!==undefined){const{envFile,prefix}=command;const current=yield*readEnvFileContent(dependencies,envFile);const savedSecret=envFileValue(current,`${prefix}${target.secretKey}`);const matches=envFileValue(current,`${prefix}CLIENT_ID`)===target.clientId&&envFileValue(current,`${prefix}ISSUER`)===context.target.apiOrigin&&envFileValue(current,`${prefix}CREDENTIAL_ID`)===metadata.id;if(secret===undefined&&savedSecret!==undefined&&!matches){return yield*new CredentialsCommandError({message:`The saved secret in ${envFile} belongs to another credential or backend; choose another --env-file or use --rotate`})}const outputSecret=secret??(matches?savedSecret:undefined);if(outputSecret===undefined){return yield*new CredentialsCommandError({message:`No saved secret for ${command.name} in ${envFile}; use --rotate to issue a new secret`})}yield*try_2({catch:(cause)=>new CredentialsCommandError({cause,message:`Could not write ${envFile}; the credential was issued but its secret was not saved`}),try:()=>{dependencies.writeEnvFile(envFile,mergeEnvFile(current,prefix,[["ISSUER",context.target.apiOrigin],...target.owner.kind==="principal"?[["BACKEND_URL",context.target.apiOrigin]]:[],["CLIENT_ID",target.clientId],["CREDENTIAL_ID",metadata.id],[target.secretKey,outputSecret]]))}});dependencies.writeDiagnostic(`Wrote credential ${command.name} to ${envFile}
266
266
  `)}if(command.envFile===undefined||command.json){const output={created:result.created,credential:metadata};dependencies.writeOutput(`${JSON.stringify(secret===undefined||command.envFile!==undefined?output:{...output,secret})}
267
- `)}return yield*void_3}).pipe(mapError2((cause)=>is2(CredentialsCommandError)(cause)?cause:new CredentialsCommandError({cause,message:cause.message})));var Scope2=Literals(["knowledge_read","knowledge_manage","documents_read","documents_manage","datasets_read","datasets_manage","automations_invoke","benchmark_judge_invoke","organization_users_manage","organization_settings_manage","external_apps_manage","studio_use"]);var parseScopes=(values)=>gen2(function*parseApiKeyScopes(){const scopes=[];for(const value of new Set(values.flatMap((item)=>item.split(/[\s,]+/u).filter(Boolean)))){scopes.push(yield*decodeUnknownEffect2(Scope2)(value).pipe(mapError2(()=>new CredentialsCommandError({message:`Invalid API key scope ${value}`}))))}return scopes});var parse=(args)=>gen2(function*parseApiKeys(){const[action,...rest]=args;if(action!=="upsert"&&action!=="list"&&action!=="get"&&action!=="rotate"&&action!=="revoke"){return yield*new CredentialsCommandError({message:"Usage: ci api-keys upsert|list|get|rotate|revoke --principal <fqn> [--name <name>] [--scopes <scopes>]"})}const options=yield*parseCommandOptionsEffect(rest,{repeatable:["scopes"],switches:["json","rotate"],values:[...targetOptions,"principal","name","env-file","prefix"]});const reference=optionValue2(options,"principal");if(reference===undefined){return yield*new CredentialsCommandError({message:"Missing required option --principal <fqn>"})}if(action==="list"&&optionValue2(options,"name")!==undefined){return yield*new CredentialsCommandError({message:"--name does not apply to list"})}const name=action==="list"?undefined:yield*credentialName(optionValue2(options,"name"));const scopes=yield*parseScopes(optionValues(options,"scopes"));if(action==="upsert"&&scopes.length===0){return yield*new CredentialsCommandError({message:"Missing required option --scopes"})}if(action!=="upsert"&&(scopes.length>0||options.switches.has("rotate"))){return yield*new CredentialsCommandError({message:"--scopes and --rotate apply only to upsert"})}if(action!=="upsert"&&action!=="rotate"&&optionValue2(options,"env-file")!==undefined){return yield*new CredentialsCommandError({message:"--env-file applies only to upsert or rotate"})}const prefix=optionValue2(options,"prefix")??"CI_";if(!isEnvPrefix(prefix)){return yield*new CredentialsCommandError({message:"--prefix must be an environment variable name prefix such as CI_"})}return{action,envFile:optionValue2(options,"env-file"),json:options.switches.has("json"),name,prefix,rotate:options.switches.has("rotate"),target:{kind:"principal",reference,scopes}}});var apiKeysCommandEffect=(args,dependencies)=>credentialCommandEffect(args,parse(args),dependencies);var parse2=(args)=>gen2(function*parseAppCredentials(){const[action,...rest]=args;if(action!=="upsert"&&action!=="list"&&action!=="get"&&action!=="rotate"&&action!=="revoke"){return yield*new CredentialsCommandError({message:"Usage: ci apps credentials upsert|list|get|rotate|revoke <app> [--name <name>] [--server-role <role>]"})}const options=yield*parseCommandOptionsEffect(rest,{positionals:1,repeatable:["server-role"],switches:["json","rotate"],values:[...targetOptions,"name","env-file","prefix"]});const[reference]=options.positionals;if(reference===undefined){return yield*new CredentialsCommandError({message:"Missing required application: pass an Application Id or FQN"})}if(action==="list"&&optionValue2(options,"name")!==undefined){return yield*new CredentialsCommandError({message:"--name does not apply to list"})}const name=action==="list"?undefined:yield*credentialName(optionValue2(options,"name"));const serverRoles=[...new Set(optionValues(options,"server-role"))];const prefix=optionValue2(options,"prefix")??"CI_";if(!isEnvPrefix(prefix)){return yield*new CredentialsCommandError({message:"--prefix must be an environment variable name prefix such as CI_"})}if(action!=="upsert"&&(serverRoles.length>0||options.switches.has("rotate"))){return yield*new CredentialsCommandError({message:"--server-role and --rotate apply only to upsert"})}if(action!=="upsert"&&action!=="rotate"&&optionValue2(options,"env-file")!==undefined){return yield*new CredentialsCommandError({message:"--env-file applies only to upsert or rotate"})}return{action,envFile:optionValue2(options,"env-file"),json:options.switches.has("json"),name,prefix,rotate:options.switches.has("rotate"),target:{kind:"app",reference,serverRoles}}});var appsCredentialsCommandEffect=(args,dependencies)=>credentialCommandEffect(args,parse2(args),dependencies);class AppsEnvCommandError extends TaggedError3()("AppsEnvCommandError",{cause:optional2(Unknown2),message:String5}){}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
268
- `)}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","user_multi_select","user_select","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,connectionInstanceFqn:optional3(identity2),connectionTemplateFqn:string3,label:string3,required:optBoolean,slot:string3,visibleWhen:optional3(visibility)})));var projectionPath=refine(string3,(path)=>path.split(".").every((key)=>/^[^[\]]+(?:\[\d*\])*$/u.test(key))&&path.split("[]").length<=2?undefined:"malformed remote path");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)}case"reference":{return object({...common,op:literal(op),remote:projectionPath,target:optString})(v,p)}case"embedded":{return object({...common,fieldMap:array2((rule,path)=>{const nested=fieldMap(rule,path);if(nested.op==="embedded"){throw new TypeError(`Invalid package manifest at ${path}/op: an embedded rule cannot hold another embedded rule`)}return nested}),op:literal(op),remote:projectionPath,remoteId:string3,target:optString})(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 readOverviewBudget=(value,path)=>{const parsed=positiveSafeInteger(value,path);return parsed<=1e6?parsed:invalid4(path)};var overviewInputMaxChars=optional3(nullable(readOverviewBudget));var richEnrichment=optional3(nullable(boolean2));var fieldReferences=array2(object({field:string3,scope:literal("data","entity")}));var ownerRelationFields={autocomplete:optional3(object({baseFilters:optional3(array2(object({caseSensitive:optBoolean,field:identity2,operator:literal("contains","contains_all","contains_any","contains_none","ends_with","eq","exists","gt","gte","in","is_empty","is_not_empty","is_not_null","is_null","lt","lte","ne","nin","not_contains","not_in","starts_with"),value:json}))),fields:optional3(fieldReferences)})),display:optional3(object({fields:fieldReferences})),inverseOf:optional3((_value,path)=>invalid4(path)),onDelete:optional3(literal("clear","restrict")),targetSchemaFqn:identity2};var ownerRelation=union2(object({...ownerRelationFields,cardinality:literal("one_to_one","many_to_one"),maxItems:optional3((_value,path)=>invalid4(path))}),object({...ownerRelationFields,cardinality:literal("one_to_many","many_to_many"),maxItems:optional3(positiveSafeInteger)}));var inverseRelation=object({autocomplete:optional3((_value,path)=>invalid4(path)),cardinality:optional3((_value,path)=>invalid4(path)),display:optional3(object({fields:fieldReferences})),inverseOf:object({field:refine(identity2,(pointer)=>/^\/(?:[^~/]|~[01])+$/u.test(pointer)?undefined:"top-level pointer"),schemaFqn:identity2}),maxItems:optional3((_value,path)=>invalid4(path)),onDelete:optional3((_value,path)=>invalid4(path)),targetSchemaFqn:optional3((_value,path)=>invalid4(path))});var relation=union2(ownerRelation,inverseRelation);var fieldSemantics=object({defaultSearch:optBoolean,embedded:optBoolean,faceted:optBoolean,file:optional3(object({accepts:strings,multiple:boolean2})),includeInItemEmbedding:optBoolean,indexContent:optBoolean,indexOverview:optBoolean,indexed:optBoolean,managedProjectionSource:optional3(literal("organization_group","organization_user")),mediaVisibility:optional3(literal("private","protected","public")),overviewInputMaxChars,queryGuidance:optString,relation:optional3(relation),richEnrichment,unique:optBoolean,user:optional3(object({accounts:optional3((value,path)=>value===true?true:invalid4(path)),multiple:boolean2}))});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:fieldReferences,defaultAutocompleteFields:fieldReferences});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 absent2=(value,path)=>value===undefined?undefined:invalid4(path);var hasRelationHop=(predicate)=>{switch(predicate.op){case"and":case"or":{return predicate.args.some(hasRelationHop)}case"not":{return hasRelationHop(predicate.arg)}case"relation_field":{return"field"in predicate||hasRelationHop(predicate.inner)}default:{return false}}};var relationFieldPredicate=(value,path)=>object({field:optional3(identity2)})(value,path).field===undefined?object({direction:literal("out","in"),inner:policyPredicate,op:literal("relation_field"),relationSchemaId:uuid})(value,path):object({direction:absent2,relationSchemaId:absent2})(value,path)&&object({field:identity2,inner:policyPredicate,op:literal("relation_field")})(value,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 relationFieldPredicate(value,path)}default:{return invalid4(`${path}/op`)}}};var writableField=(value,path)=>{const field=array2(identity2)(value,path);return field.length>=2&&field[0]==="data"?field:invalid4(path)};var writableFields=(value,path)=>{const fields=array2(writableField)(value,path);return fields.length>0?fields:invalid4(path)};var subjectMatch=(value,path)=>{const predicate=policyPredicate(value,path);return hasRelationHop(predicate)?invalid4(path):predicate};var policyBody=object({rule:optional3(policyPredicate),subjectMatch,writableFields:optional3(writableFields)});var fieldWriteRule=(policy,path)=>policy.policyBody.writableFields===undefined||policy.effect==="allow"&&policy.policyType==="filter"&&(policy.targetKind==="entity_schema"||policy.targetKind==="entity_domain")?policy:invalid4(`${path}/policyBody/writableFields`);var relationScopeRule=(policy,path)=>policy.policyBody.rule===undefined||policy.targetKind==="entity_schema"||!hasRelationHop(policy.policyBody.rule)?policy:invalid4(`${path}/policyBody/rule`);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=union2(refine(varyingObject({setupKey:identity2}),(value)=>Object.keys(value).some((key)=>key!=="setupKey")?"install-only input":undefined),refine(object({connectionInstanceFqn:identity2}),(value)=>Object.keys(value).some((key)=>key!=="connectionInstanceFqn")?"declared connection reference":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"),maxRemoteDeletionsPerRun:optional3(nullable(positiveSafeInteger)),missingConnectorFieldsBehavior:optional3(literal("prune","retain")),pushEntityMatch:optional3(literal("remote_ref","unique_fields")),remoteDeletionPropagation:optional3(literal("never","full","full_and_delta")),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 assertDataAccess=(value,own,location)=>{if(value===undefined){return}if(typeof value!=="object"||value===null||Array.isArray(value)){throw new TypeError(`${location}: dataAccess must be an object`)}for(const[source,mode]of Object.entries(value)){if(!["knowledge","datasets","documents"].includes(source)){throw new TypeError(`${location}: unknown dataAccess source '${source}'`)}if(mode!=="user"&&mode!==own){throw new TypeError(`${location}: dataAccess.${source} must be 'user' or '${own}'`)}}};var readDataAccess=(own)=>(value,location)=>{assertDataAccess(value,own,location);return value};var workflowDataAccess=(outer,inner,location)=>{assertDataAccess(outer,"workflow",location);assertDataAccess(inner,"workflow",`${location}.definition`);if(outer!==undefined&&inner!==undefined){for(const source of["knowledge","datasets","documents"]){if((outer[source]??"workflow")!==(inner[source]??"workflow")){throw new TypeError(`${location}: conflicting dataAccess.${source} in declaration and definition`)}}}return outer??inner};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 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=/^[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)+$/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)?.role.parent}return ancestor===key};var permissionsOf=({appPermissions=[],platformPermissions})=>[...platformPermissions,...appPermissions];var roleViolation=(entry,roles,declared)=>{const{kind,path,role}=entry;const{assignRoles=[],key,parent,replaces}=role;const visibility=entry.kind==="User Role"?entry.role.visibility:undefined;if(key==="anonymous"&&visibility!=="declared"){return`${path}: role 'anonymous' must be a User Role with Declared Visibility`}if(visibility==="user"&&Object.hasOwn(role,"bindings")){return`${path}.bindings: role '${key}' with User Visibility declares no bindings`}const assigned=assignRoles.find((other)=>declared.get(other)?.kind!=="User Role");if(assigned!==undefined){return`${path}.assignRoles: role '${assigned}' of role '${key}' is not a User Role of this application`}if(replaces!==undefined){if(declared.has(replaces)){return`${path}.replaces: role '${key}' replaces '${replaces}', which this release declares`}const first=roles.find((other)=>other.role.replaces===replaces);if(first?.role.key!==key){return`${path}.replaces: roles '${first?.role.key}' and '${key}' replace the same role '${replaces}'`}}if(parent===undefined){return}const held=declared.get(parent);if(held?.kind!==kind){return`${path}.parent: parent '${parent}' of role '${key}' is not a declared ${kind}`}const heldPermissions=permissionsOf(held.role);const missing=permissionsOf(role).find((permission)=>!heldPermissions.includes(permission));if(missing!==undefined){return`${path}.parent: role '${parent}' must hold permission '${missing}' of its child role '${key}'`}return isOwnAncestor(role,declared)?`${path}.parent: role '${key}' is its own ancestor`:undefined};var rolesViolation=(userRoles,serverRoles)=>{const roles=[...userRoles.map((role,index)=>({kind:"User Role",path:`userRoles[${index}]`,role})),...serverRoles.map((role,index)=>({kind:"Server Role",path:`serverRoles[${index}]`,role}))];const declared=new Map;for(const entry of roles){const{path,role}=entry;const{key,platformPermissions}=role;if(key.length>64||!roleKey.test(key)){return`${path}.key: role key '${key}' must match ${roleKey.source} and hold at most 64 characters`}if(declared.has(key)){return`${path}.key: role key '${key}' is declared more than once`}declared.set(key,entry);const malformed=platformPermissions.find((permission)=>!resourceAction.test(permission));if(malformed!==undefined){return`${path}.platformPermissions: permission '${malformed}' of role '${key}' must be 'resource:action'`}}for(const entry of roles){const violation=roleViolation(entry,roles,declared);if(violation!==undefined){return violation}}return};var defaultServerRoleViolation=(defaultServerRole,serverRoles)=>{if(defaultServerRole===undefined){return serverRoles.length===0?undefined:"defaultServerRole is required with serverRoles"}return serverRoles.some(({key})=>key===defaultServerRole)?undefined:`defaultServerRole: role '${defaultServerRole}' is not a declared Server Role`};var groupBindingsViolation=(groupBindings,userRoles)=>{for(const[index,{group,role}]of groupBindings.entries()){const path=`groupBindings[${index}]`;if(group.trim()===""){return`${path}.group: the Group Role Binding of role '${role}' must name a Group`}if(!userRoles.some(({key})=>key===role)){return`${path}.role: role '${role}' of the Group Role Binding to Group '${group}' is not a declared User Role`}const first=groupBindings.findIndex((other)=>other.group===group&&other.role===role);if(first!==index){return`${path}: the Group Role Binding of role '${role}' to Group '${group}' is declared more than once`}}return};var externalApplicationViolation=({applicationConsent,defaultServerRole,groupBindings=[],primaryRedirectUri,redirectUris,serverRoles=[],userRoles})=>{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'"}return rolesViolation(userRoles,serverRoles)??defaultServerRoleViolation(defaultServerRole,serverRoles)??groupBindingsViolation(groupBindings,userRoles)};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 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 subgroupNodes=(parentFqn,subgroups=[])=>subgroups.flatMap(({description,displayName,key,subgroups:nested})=>{const fqn=`${parentFqn}.${key}`;return[{description,displayName,fqn,parentFqn},...subgroupNodes(fqn,nested)]});var organizationGroupNodes=({description,displayName,fqn,parent,subgroups})=>[{description,displayName,fqn,parentFqn:parent},...subgroupNodes(fqn,subgroups)];var fields=["answerLength","bannedQuestions","enabled","otherInstructions","toneOfVoice"];var organizationInstructionsViolation=(definition)=>fields.some((field)=>definition[field]!==undefined)?undefined:"at least one field is required";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 fields2=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)=>!fields2.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 servicePrincipalOrganizationRoles=["organization_admin","organization_operator","organization_member"];var assertServicePrincipalGroups=(primitives)=>{const groups=new Set(primitives.flatMap((primitive)=>primitive.kind==="organizationGroup"?organizationGroupNodes(primitive).map(({fqn})=>fqn):[]));for(const primitive of primitives){if(primitive.kind!=="servicePrincipal"){continue}for(const group of primitive.groups){if(!groups.has(group)){throw new TypeError(`service principal '${primitive.fqn}' references Group '${group}' that this package does not declare`)}}}};var maxStudioTriggerFormFileBytes=10*1024*1024;var studioFormKey="studioForm";var fieldKeyPattern=/^[A-Za-z][A-Za-z0-9_]*$/u;var contentTypePattern=/^[\w.+-]+\/[\w.+-]+$/u;var fieldKey=refine(identity2,(key)=>fieldKeyPattern.test(key)?undefined:"key");var fileField=object({accept:optional3(refine(array2(refine(identity2,(type)=>contentTypePattern.test(type)?undefined:"content type")),(types)=>types.length===0?"no content type":undefined)),key:fieldKey,label:identity2,maxBytes:optional3(refine(positiveSafeInteger,(bytes)=>bytes>maxStudioTriggerFormFileBytes?"above ceiling":undefined)),type:literal("file")});var valueField=object({key:fieldKey,label:identity2,type:literal("boolean","number","text","textarea")});var enumField=object({key:fieldKey,label:identity2,options:refine(array2(object({label:identity2,value:identity2})),(options)=>options.length>0&&new Set(options.map(({value})=>value)).size===options.length?undefined:"options"),type:literal("enum")});var jsonField=object({key:fieldKey,label:identity2,schema:schemaDocument,type:literal("json")});var entitiesField=object({key:fieldKey,label:identity2,labelKey:optional3(identity2),schemaFqn:identity2,type:literal("entities"),valueKey:optional3(identity2)});var richTextField=object({key:fieldKey,label:identity2,type:literal("rich_text")});var userField=object({key:fieldKey,label:identity2,multiple:optBoolean,required:optBoolean,type:literal("user_select")});var fieldReaders={boolean:valueField,entities:entitiesField,enum:enumField,file:fileField,json:jsonField,number:valueField,rich_text:richTextField,text:valueField,textarea:valueField,user_select:userField};var formField=(value,path)=>{const{type}=object({type:literal("boolean","entities","enum","file","json","number","rich_text","text","textarea","user_select")})(value,path);return fieldReaders[type](value,path)};var studioFormFields=refine(array2(formField),(fields)=>new Set(fields.map(({key})=>key)).size===fields.length?undefined:"duplicate key");var studioTriggerFormAt=(metadata,path)=>optional3(object({fields:optional3(studioFormFields),organizationGroup:identity2}))(metadata[studioFormKey],`${path}/${studioFormKey}`);var studioTriggerMetadata=(read)=>(value,path)=>{const metadata=read(value,path);studioTriggerFormAt(metadata,path);return metadata};var access3=optional3(object({groups:refine(array2(identity2),(groups)=>groups.length===0?"no group":undefined)}));var view=object({access:access3,componentRef:identity2,dataBinding:optional3(object({filter:optional3(jsonObject),kind:literal("schema"),schema:identity2})),fqn:identity2,orderIndex:number3,props:optional3(jsonObject),slot:identity2});var pageBase={access:access3,fqn:identity2,fullHeight:optBoolean,fullWidth:optBoolean,icon:optString,label:string3,orderIndex:number3,routeSegment:identity2,slug:identity2};var genericPage=object({...pageBase,kind:literal("generic"),views:array2(view)});var predefinedPage=object({...pageBase,kind:literal("predefined"),predefinedPageRef:identity2});var page=(value,path)=>object({kind:literal("generic","predefined")})(value,path).kind==="generic"?genericPage(value,path):predefinedPage(value,path);var layout=(value,path)=>object({kind:literal("custom","left_sidebar")})(value,path).kind==="custom"?object({componentRef:identity2,kind:literal("custom"),props:optional3(jsonObject)})(value,path):object({kind:literal("left_sidebar")})(value,path);var studioViewKey=(fqn)=>(fqn.split(".").at(-1)??fqn).toLowerCase().replaceAll(/[^a-z0-9]+/gu,"-").replaceAll(/^-+|-+$/gu,"").slice(0,64);var hasDuplicate=(keys)=>new Set(keys).size!==keys.length;var collision=({sections})=>{const pages=sections.map((section)=>section.pages);const views=pages.flat().map((item)=>item.kind==="generic"?item.views:[]);if(hasDuplicate([...sections.map(({fqn})=>fqn),...pages.flat().map(({fqn})=>fqn),...views.flat().map(({fqn})=>fqn)])){return"duplicate FQN"}if(hasDuplicate(sections.map(({slug})=>slug))){return"duplicate section slug"}if(pages.some((items)=>hasDuplicate(items.map(({slug})=>slug)))){return"duplicate page slug"}return views.some((items)=>hasDuplicate(items.map(({fqn,slot})=>`${slot}
269
- ${studioViewKey(fqn)}`)))?"duplicate view key":undefined};var isTrue=(value,path)=>value===true?true:invalid4(path);var studioAppDeclaration=object({...base,definition:refine(object({color:optString,description:optString,icon:optString,layout:optional3(layout),name:string3,sections:array2(object({access:access3,description:optString,fqn:identity2,icon:optString,label:string3,orderIndex:number3,pages:array2(page),slug:identity2})),slug:identity2}),collision),grants:object({groups:refine(array2(object({group:identity2,role:literal("manage","view")})),(grants)=>new Set(grants.map(({group})=>group)).size===grants.length?undefined:"duplicate Group")}),kind:literal("studioApp"),lifecycle:object({deployMode:literal("upsert"),readonly:isTrue})});var agentFormFields=(value,path)=>studioFormFields(value,path).map((field,index)=>field.type==="rich_text"||field.type==="user_select"?invalid4(`${path}/${index}/type`):field);var studioFormKey2="studioForm";var studioAgentFormAt=(metadata,path)=>optional3(object({fields:agentFormFields}))(metadata[studioFormKey2],`${path}/${studioFormKey2}`);var studioAgentMetadata=(read)=>(value,path)=>{const metadata=read(value,path);studioAgentFormAt(metadata,path);return metadata};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 studioAppTemplate=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")}))),user:optional3(object({multiple:boolean2})),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({dataAccess:readDataAccess("workflow"),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:studioTriggerMetadata(jsonObject),settings:jsonObject,templateFqn:string3,templateVersion:string3})),version:literal(1)});var onlyKeys=(...keys)=>(value)=>Object.keys(value).some((key)=>!keys.includes(key))?"unexpected member":undefined;var remoteDeletion=union2(refine(object({capability:literal("full")}),onlyKeys("capability")),refine(object({capability:literal("full_and_delta"),feed:literal("server_filtered","client_filtered")}),onlyKeys("capability","feed")));var bindingTargets=(read)=>optional3(union2(literal("all"),array2(read)));var knowledgeTargets=bindingTargets(object({fqn:identity2,policy:optional3(identity2)}));var declaredBindings=optional3(object({agents:bindingTargets(identity2),documents:bindingTargets(identity2),knowledge:optional3(object({domains:knowledgeTargets,schemas:knowledgeTargets})),skills:bindingTargets(identity2),workflows:bindingTargets(identity2)}));var roleFields={appPermissions:optStrings,assignRoles:optStrings,key:string3,parent:optString,platformPermissions:strings,replaces:optString,users:optional3(object({create:boolean2}))};var roleVisibility=object({visibility:literal("user","declared")});var userVisibilityRole=object({...roleFields,visibility:literal("user")});var declaredVisibilityRole=object({...roleFields,bindings:declaredBindings,visibility:literal("declared")});var userRole=(value,path)=>roleVisibility(value,path).visibility==="declared"?declaredVisibilityRole(value,path):userVisibilityRole(value,path);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 withoutRetiredRelationFields=(read)=>(value,path)=>{const declaration=read(value,path);if("relationFields"in declaration){throw new TypeError(`Invalid package manifest at ${path}/relationFields: relationFields is no longer supported; rebuild the package with the current extensions SDK, which declares Entity Relation Fields in fieldSemantics`)}return declaration};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_operator","organization_member"),domains:varyingStrings,enabled:boolean2,provisionMembers:boolean2}),provider:union2(object({fqn:identity2}),varyingObject({providerId:identity2}))});var organizationInstructions=object(varyingFields({...base,answerLength:optString,bannedQuestions:optString,enabled:optBoolean,kind:literal("organizationInstructions"),lifecycle,otherInstructions:optString,toneOfVoice:optString}));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 documentFolder=union2(refine(varyingObject({drive:identity2,folders:varyingArray(identity2)}),onlyKeys("drive","folders")),refine(varyingObject({remoteId:identity2}),onlyKeys("remoteId")));var declaredRule=varyingObject({effect:literal("allow","deny"),grantee:union2(refine(object({fqn:identity2,kind:literal("group","servicePrincipal")}),onlyKeys("fqn","kind")),refine(object({kind:literal("organization")}),onlyKeys("kind"))),permission:literal("manage","read","update","view_history"),target:union2(refine(object({kind:literal("collection")}),onlyKeys("kind")),refine(varyingObject({folder:documentFolder,kind:literal("folder")}),onlyKeys("folder","kind")))});var ruleAccess=({grantee,target})=>canonicalJson([grantee,target]);var unpairedHistoryRule=(rules)=>{if(rules===undefined||isVariableReference(rules)||canonicalJson(rules).includes('{"$variable":')){return}const concrete=rules.filter((rule)=>!isVariableReference(rule));const reads=new Set(concrete.filter(({effect,permission})=>effect==="allow"&&permission==="read").map(ruleAccess));const index=concrete.findIndex((rule)=>rule.effect==="allow"&&rule.permission==="view_history"&&!reads.has(ruleAccess(rule)));return index===-1?undefined:index};var documentCollection=(value,path)=>{const declaration=varyingObject({...base,connection:connection2,connectorFqn:optional3(identity2),indexContent:optBoolean,indexOverview:optBoolean,kind:literal("documentCollection"),overviewInputMaxChars,remoteRoots:varyingArray(documentFolder),richEnrichment,rules:optional3(varyingArray(declaredRule)),syncEnabled:optBoolean,title:identity2})(value,path);const unpaired=unpairedHistoryRule(declaration.rules);if(unpaired!==undefined){throw new TypeError(`Invalid package manifest at ${path}/rules/${unpaired}: an allow view_history rule needs an allow read rule for the same grantee and target`)}return declaration};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,bypassOrganizationInstructions:optional3(boolean2),dataAccess:readDataAccess("agent"),kind:literal("agent"),lifecycle,maxSteps:optional3(positiveSafeInteger),metadata:optional3(studioAgentMetadata(jsonObject)),modelTier:optional3(literal(...agentModelTiers)),objectives:strings,operatingInstructions:string3,output:optional3(object({schema:schema2})),responsibility:string3,skills:array2(identity2),tools:toolBindings2}),withoutRetiredAgentFields),connection,connectionInstance:substituted(varyingObject({...base,credentials:jsonObject,kind:literal("connectionInstance"),lifecycle,templateFqn:identity2})),datasetBlueprint,datasetConnectorInstance,datasetParser:object({...base,extensions:array2(identity2),format:datasetParserFormat,kind:literal("datasetParser"),mediaTypes:array2(identity2),parserVersion:datasetParserVersion}),datasetTableTemplate,documentCollection,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(union2(literal("aws"),literal("azure"))),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}),defaultServerRole:optString,groupBindings:optional3(array2(object({coverage:optional3(literal("direct","inherited")),group:string3,lifecycle,role:string3}))),serverRoles:optional3(array2(object({...roleFields,bindings:declaredBindings}))),userRoles:array2(userRole)}),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)),remoteDeletion:optional3(remoteDeletion),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:withoutRetiredRelationFields(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)),overviewInputMaxChars,persistFullFieldContributions:boolean2,richEnrichment,syncable:optBoolean,usableAsDocumentScope:boolean2,versioned:optBoolean,versioningEnabled:nullable(boolean2)})),knowledgePolicy:(value,path)=>relationScopeRule(fieldWriteRule(object({...base,...policyFields,kind:literal("knowledgePolicy"),priority:optNumber})(value,path),path),path),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),organizationInstructions:substituted(refine(organizationInstructions,organizationInstructionsViolation)),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),servicePrincipal:object({...base,groups:array2(identity2),kind:literal("servicePrincipal"),organizationRole:literal(...servicePrincipalOrganizationRoles)}),skill:object({dataAccess:readDataAccess("skill"),...base,instructions:string3,kind:literal("skill"),lifecycle,tools:toolBindings2}),skillTemplate:object({...base,catalogTags,kind:literal("skillTemplate"),lifecycle:optional3(lifecycle),name:string3}),studioApp:studioAppDeclaration,studioAppTemplate:object({...base,definition:studioAppTemplate,kind:literal("studioAppTemplate")}),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:refine(object({dataAccess:readDataAccess("workflow"),...base,definition:authoringDefinition,kind:literal("workflow"),lifecycle,name:string3,runDetailsRetention:optional3(literal("full","outcome_only")),servicePrincipalFqn:optional3(identity2),slug:string3}),(workflow)=>{workflowDataAccess(workflow.dataAccess,workflow.definition.dataAccess,`workflow:${workflow.fqn}`)}),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 readDependency=object({fqn:hostedIdentity});var parsePackageDependencies=(value)=>{const requirements=array2(readDependency)(value,"/dependencies");const identities=new Set;for(const requirement of requirements){if(Object.keys(requirement).some((key)=>key!=="fqn")){throw new TypeError(`package dependency '${requirement.fqn}' has unexpected fields`)}if(identities.has(requirement.fqn)){throw new TypeError(`duplicate package dependency '${requirement.fqn}'`)}identities.add(requirement.fqn)}return[...requirements].sort((left,right)=>compareUtf16CodeUnits(left.fqn,right.fqn))};var PackageManifestVersion="v4";var tenantlessSingletonKinds=["organizationInstructions","organizationSettings"];var assertTenantlessSingletonScopes=(manifest)=>{if(manifest.bindingScopes?.includes("tenant")!==true){return}const carried=tenantlessSingletonKinds.find((kind)=>manifest.primitives.some((primitive)=>primitive.kind===kind));if(carried!==undefined){throw new TypeError(`package '${manifest.fqn}' declares ${carried} and cannot bind to the tenant scope`)}};var legacyFixedDestinationTargets=new Set(["fixed-email","channel-destination","telegram-chat","whatsapp-destination"]);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 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(parsePackageDependencies),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)),"");assertServicePrincipalGroups(manifest.primitives);assertTenantlessSingletonScopes(manifest);return manifest.dependencies===undefined?manifest:{...manifest,dependencies:parsePackageDependencies(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&&current<=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 toolResultBrand=Symbol.for("@ci/tool-result");var slot=(location,profile,direction,projection)=>({direction,location,profile,projection});var optionalFormSlot=(location,form)=>form===undefined||form===null?[]:[slot(location,"interactive_form","input",form.schema)];var declarationSchemaSlots=(declaration)=>{switch(declaration.kind){case"agent":{return declaration.output===undefined?[]:[slot(`agent:${declaration.fqn}.output`,"runtime_json","output",declaration.output.schema)]}case"tool":{const inputProfile=declaration.usageScopes===undefined||declaration.usageScopes.some((scope)=>scope==="chat"||scope==="skill")?"ai_function_input":"runtime_json";return[slot(`tool:${declaration.fqn}.input`,inputProfile,"input",declaration.input),slot(`tool:${declaration.fqn}.output`,"runtime_json","output",declaration.output),...optionalFormSlot(`tool:${declaration.fqn}.bindingSettings.schema`,declaration.bindingSettings),...optionalFormSlot(`tool:${declaration.fqn}.settings.schema`,declaration.settings)]}case"connection":{return optionalFormSlot(`connection:${declaration.fqn}.credential.schema`,declaration.credential)}case"knowledgeConnector":{return optionalFormSlot(`connector:${declaration.fqn}.settings.schema`,declaration.settings)}case"notificationChannel":{return[...optionalFormSlot(`notification-channel:${declaration.fqn}.credential.schema`,declaration.credential),...optionalFormSlot(`notification-channel:${declaration.fqn}.definition.setup.setupForm.schema`,declaration.definition.setup.setupForm)]}case"workflowNode":{const prefix=`workflow_node:${declaration.fqn}.contract`;return[...declaration.contract.configSchema===undefined?[]:[slot(`${prefix}.configSchema`,"workflow_value","input",declaration.contract.configSchema)],...declaration.contract.inputSchema===undefined?[]:[slot(`${prefix}.inputSchema`,"workflow_value","input",declaration.contract.inputSchema)],...declaration.contract.outputSchema===undefined?[]:[slot(`${prefix}.outputSchema`,"workflow_value","output",declaration.contract.outputSchema)],...(declaration.contract.ports??[]).flatMap((port,index)=>[slot(`${prefix}.ports[${String(index)}].valueSchema`,"workflow_value",port.direction,port.valueSchema),...(port.schemaResolution?.variants??[]).map((variant,variantIndex)=>slot(`${prefix}.ports[${String(index)}].schemaResolution.variants[${String(variantIndex)}].schema`,"workflow_value",port.direction,variant.schema))]),...(declaration.contract.outputChannels??[]).map((channel,index)=>slot(`${prefix}.outputChannels[${String(index)}].valueSchema`,"workflow_value","output",channel.valueSchema))]}case"workflowField":{return declaration.contract.valueSchema===undefined?[]:[slot(`workflow_field:${declaration.fqn}.contract.valueSchema`,"workflow_value",declaration.contract.availableForOutput===true?"output":"input",declaration.contract.valueSchema)]}case"workflowTemplate":{return[slot(`workflow_template:${declaration.fqn}.definition.inputContract.schema`,"workflow_value","input",declaration.definition.inputContract.schema),slot(`workflow_template:${declaration.fqn}.definition.outputContract.schema`,"workflow_value","output",declaration.definition.outputContract.schema)]}case"studioComponent":{return[slot(`studio_component:${declaration.fqn}.propsSchema`,"studio_props","input",declaration.propsSchema)]}case"knowledgeEntitySchema":{return[slot(`knowledge_entity_schema:${declaration.fqn}.schema`,"knowledge_record","input",declaration.schema)]}case"knowledgeRelationSchema":{return[slot(`knowledge_relation_schema:${declaration.fqn}.schema`,"knowledge_record","input",declaration.schema)]}case"datasetTableTemplate":{const prefix=`dataset_table_template:${declaration.fqn}`;return[slot(`${prefix}.configuration`,"runtime_json","input",declaration.configuration),slot(`${prefix}.requirements`,"runtime_json","input",declaration.requirements)]}case"externalAppGateway":{const prefix=`external_app_gateway:${declaration.fqn}.expectedContract`;return declaration.expectedContract.operationDomains.flatMap((domain,domainIndex)=>domain.operations.flatMap((operation,operationIndex)=>{const operationPrefix=`${prefix}.operationDomains[${String(domainIndex)}].operations[${String(operationIndex)}]`;return[slot(`${operationPrefix}.input`,"runtime_json","input",operation.input),slot(`${operationPrefix}.output`,"runtime_json","output",operation.output)]}))}case"datasetBlueprint":case"datasetParser":case"documentCollection":case"documentsConnector":case"domain":case"domainTemplate":case"emailProvider":case"eventListener":case"externalApplication":case"externalDatasetProvider":case"fieldTransformer":case"connectionInstance":case"knowledgeConnectorInstance":case"datasetConnectorInstance":case"knowledgeConnectorOauth":case"knowledgeEntityAdapter":case"knowledgePolicy":case"knowledgeRelationAdapter":case"managedDatasetProvider":case"servicePrincipal":case"organizationGroup":case"organizationInstructions":case"organizationSettings":case"organizationSso":case"outboundMessagingProvider":case"skill":case"skillTemplate":case"studioApp":case"studioAppTemplate":case"remoteToolCollection":case"toolCollection":case"toolSettingsOptions":case"workflow":case"workflowFieldCollection":case"workflowNodeCollection":{return[]}default:{const exhaustive=declaration;return exhaustive}}};var packageSchemaSlots=(definition)=>definition.manifest.primitives.flatMap(declarationSchemaSlots);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("uninstall"),packageFqn:nonBlankString,recovery:packageOperationRecoverySchema}),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 dependencyReferenceSchema=unionType([pinSchema,objectType({fqn:nonBlankString})]);var dependencyPathsSchema=arrayType(arrayType(stringType()));var blockerMessageSchema=stringType();var rejectedDefinitionKinds={agent:"agent",application_grant:"application_grant",connection_instance:"connection_instance",dataset_connector_instance:"dataset_connector_instance",document_collection:"document_collection",external_app:"external_app",knowledge_connector_instance:"knowledge_connector_instance",organization_group:"organization_group",organization_instructions:"organization_instructions",organization_settings:"organization_settings",remote_tool_collection:"remote_tool_collection",skill:"skill",studio_app:"studio_app",workflow:"workflow"};var knownBlockerSchema=unionType([objectType({_tag:literalType("admin_principal_confirmation_required"),message:blockerMessageSchema,paths:dependencyPathsSchema,principalFqn:stringType()}),objectType({_tag:literalType("manual_prerequisite"),message:blockerMessageSchema,observed:pinSchema.nullable(),path:arrayType(dependencyReferenceSchema),paths:arrayType(arrayType(dependencyReferenceSchema)),required:dependencyReferenceSchema}),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:nativeEnumType(rejectedDefinitionKinds)})),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","dependents_present","in_use","tenant_mandatory","workflow_templates_in_use"])});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 createHash5,randomUUID}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),flatMap4((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(flatMap4((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,"@collective-intelligence/extensions-sdk-frontend-react/studio-api"]};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)=>`
267
+ `)}return yield*void_3}).pipe(mapError2((cause)=>is2(CredentialsCommandError)(cause)?cause:new CredentialsCommandError({cause,message:cause.message})));var Scope2=Literals(["knowledge_read","knowledge_manage","documents_read","documents_manage","datasets_read","datasets_manage","automations_invoke","benchmark_judge_invoke","organization_users_manage","organization_settings_manage","external_apps_manage","studio_use","organization_transfer"]);var parseScopes=(values)=>gen2(function*parseApiKeyScopes(){const scopes=[];for(const value of new Set(values.flatMap((item)=>item.split(/[\s,]+/u).filter(Boolean)))){scopes.push(yield*decodeUnknownEffect2(Scope2)(value).pipe(mapError2(()=>new CredentialsCommandError({message:`Invalid API key scope ${value}`}))))}return scopes});var parse=(args)=>gen2(function*parseApiKeys(){const[action,...rest]=args;if(action!=="upsert"&&action!=="list"&&action!=="get"&&action!=="rotate"&&action!=="revoke"){return yield*new CredentialsCommandError({message:"Usage: ci api-keys upsert|list|get|rotate|revoke --principal <fqn> [--name <name>] [--scopes <scopes>]"})}const options=yield*parseCommandOptionsEffect(rest,{repeatable:["scopes"],switches:["json","rotate"],values:[...targetOptions,"principal","name","env-file","prefix"]});const reference=optionValue2(options,"principal");if(reference===undefined){return yield*new CredentialsCommandError({message:"Missing required option --principal <fqn>"})}if(action==="list"&&optionValue2(options,"name")!==undefined){return yield*new CredentialsCommandError({message:"--name does not apply to list"})}const name=action==="list"?undefined:yield*credentialName(optionValue2(options,"name"));const scopes=yield*parseScopes(optionValues(options,"scopes"));if(action==="upsert"&&scopes.length===0){return yield*new CredentialsCommandError({message:"Missing required option --scopes"})}if(action!=="upsert"&&(scopes.length>0||options.switches.has("rotate"))){return yield*new CredentialsCommandError({message:"--scopes and --rotate apply only to upsert"})}if(action!=="upsert"&&action!=="rotate"&&optionValue2(options,"env-file")!==undefined){return yield*new CredentialsCommandError({message:"--env-file applies only to upsert or rotate"})}const prefix=optionValue2(options,"prefix")??"CI_";if(!isEnvPrefix(prefix)){return yield*new CredentialsCommandError({message:"--prefix must be an environment variable name prefix such as CI_"})}return{action,envFile:optionValue2(options,"env-file"),json:options.switches.has("json"),name,prefix,rotate:options.switches.has("rotate"),target:{kind:"principal",reference,scopes}}});var apiKeysCommandEffect=(args,dependencies)=>credentialCommandEffect(args,parse(args),dependencies);var parse2=(args)=>gen2(function*parseAppCredentials(){const[action,...rest]=args;if(action!=="upsert"&&action!=="list"&&action!=="get"&&action!=="rotate"&&action!=="revoke"){return yield*new CredentialsCommandError({message:"Usage: ci apps credentials upsert|list|get|rotate|revoke <app> [--name <name>] [--server-role <role>]"})}const options=yield*parseCommandOptionsEffect(rest,{positionals:1,repeatable:["server-role"],switches:["json","rotate"],values:[...targetOptions,"name","env-file","prefix"]});const[reference]=options.positionals;if(reference===undefined){return yield*new CredentialsCommandError({message:"Missing required application: pass an Application Id or FQN"})}if(action==="list"&&optionValue2(options,"name")!==undefined){return yield*new CredentialsCommandError({message:"--name does not apply to list"})}const name=action==="list"?undefined:yield*credentialName(optionValue2(options,"name"));const serverRoles=[...new Set(optionValues(options,"server-role"))];const prefix=optionValue2(options,"prefix")??"CI_";if(!isEnvPrefix(prefix)){return yield*new CredentialsCommandError({message:"--prefix must be an environment variable name prefix such as CI_"})}if(action!=="upsert"&&(serverRoles.length>0||options.switches.has("rotate"))){return yield*new CredentialsCommandError({message:"--server-role and --rotate apply only to upsert"})}if(action!=="upsert"&&action!=="rotate"&&optionValue2(options,"env-file")!==undefined){return yield*new CredentialsCommandError({message:"--env-file applies only to upsert or rotate"})}return{action,envFile:optionValue2(options,"env-file"),json:options.switches.has("json"),name,prefix,rotate:options.switches.has("rotate"),target:{kind:"app",reference,serverRoles}}});var appsCredentialsCommandEffect=(args,dependencies)=>credentialCommandEffect(args,parse2(args),dependencies);class AppsEnvCommandError extends TaggedError3()("AppsEnvCommandError",{cause:optional2(Unknown2),message:String5}){}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
268
+ `)}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","user_multi_select","user_select","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 union3=(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(union3(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(union3(schemaType,array2(schemaType))),unevaluatedItems:optional3(union3(boolean2,schemaDocument)),unevaluatedProperties:optional3(union3(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:union3(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(union3(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=union3(union3(plainFieldUi,selectFieldUi),union3(structuredFileUploadFieldUi,structuredFileBrowserFieldUi));var formItems=array2(union3(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:union3(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",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(union3(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,connectionInstanceFqn:optional3(identity2),connectionTemplateFqn:string3,label:string3,required:optBoolean,slot:string3,visibleWhen:optional3(visibility)})));var projectionPath=refine(string3,(path)=>path.split(".").every((key)=>/^[^[\]]+(?:\[\d*\])*$/u.test(key))&&path.split("[]").length<=2?undefined:"malformed remote path");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)}case"reference":{return object({...common,op:literal(op),remote:projectionPath,target:optString})(v,p)}case"embedded":{return object({...common,fieldMap:array2((rule,path)=>{const nested=fieldMap(rule,path);if(nested.op==="embedded"){throw new TypeError(`Invalid package manifest at ${path}/op: an embedded rule cannot hold another embedded rule`)}return nested}),op:literal(op),remote:projectionPath,remoteId:string3,target:optString})(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 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 readOverviewBudget=(value,path)=>{const parsed=positiveSafeInteger(value,path);return parsed<=1e6?parsed:invalid4(path)};var overviewInputMaxChars=optional3(nullable(readOverviewBudget));var richEnrichment=optional3(nullable(boolean2));var fieldReferences=array2(object({field:string3,scope:literal("data","entity")}));var ownerRelationFields={autocomplete:optional3(object({baseFilters:optional3(array2(object({caseSensitive:optBoolean,field:identity2,operator:literal("contains","contains_all","contains_any","contains_none","ends_with","eq","exists","gt","gte","in","is_empty","is_not_empty","is_not_null","is_null","lt","lte","ne","nin","not_contains","not_in","starts_with"),value:json}))),fields:optional3(fieldReferences)})),display:optional3(object({fields:fieldReferences})),inverseOf:optional3((_value,path)=>invalid4(path)),onDelete:optional3(literal("clear","restrict")),targetSchemaFqn:identity2};var ownerRelation=union3(object({...ownerRelationFields,cardinality:literal("one_to_one","many_to_one"),maxItems:optional3((_value,path)=>invalid4(path))}),object({...ownerRelationFields,cardinality:literal("one_to_many","many_to_many"),maxItems:optional3(positiveSafeInteger)}));var inverseRelation=object({autocomplete:optional3((_value,path)=>invalid4(path)),cardinality:optional3((_value,path)=>invalid4(path)),display:optional3(object({fields:fieldReferences})),inverseOf:object({field:refine(identity2,(pointer)=>/^\/(?:[^~/]|~[01])+$/u.test(pointer)?undefined:"top-level pointer"),schemaFqn:identity2}),maxItems:optional3((_value,path)=>invalid4(path)),onDelete:optional3((_value,path)=>invalid4(path)),targetSchemaFqn:optional3((_value,path)=>invalid4(path))});var relation=union3(ownerRelation,inverseRelation);var fieldSemantics=object({defaultSearch:optBoolean,embedded:optBoolean,faceted:optBoolean,file:optional3(object({accepts:strings,multiple:boolean2})),includeInItemEmbedding:optBoolean,indexContent:optBoolean,indexOverview:optBoolean,indexed:optBoolean,managedProjectionSource:optional3(literal("organization_group","organization_user")),mediaVisibility:optional3(literal("private","protected","public")),overviewInputMaxChars,queryGuidance:optString,relation:optional3(relation),richEnrichment,unique:optBoolean,user:optional3(object({accounts:optional3((value,path)=>value===true?true:invalid4(path)),multiple:boolean2}))});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(union3(number3,literal("full")))})),maxLines:optNumber,readOnly:optBoolean,renderer:optString,trueLabel:optString});var lifecycle=object({deployMode:literal("init_only","upsert"),readonly:boolean2});var withoutRetiredRelationKey=(read,key)=>(value,path)=>{const parsed=read(value,path);if(key in parsed){throw new TypeError(`Invalid package manifest at ${path}/${key}: ${key} is retired with Record Relations; declare a Reference Field instead`)}return parsed};var autocompleteConfiguration=object({autocompleteFields:fieldReferences,defaultAutocompleteFields:fieldReferences});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 absent2=(value,path)=>value===undefined?undefined:invalid4(path);var retiredForm=(form,path)=>{throw new TypeError(`Invalid package manifest at ${path}: ${form} is retired with Record Relations; follow a Reference Field with relation_field and field instead`)};var hasRelationHop=(predicate)=>{switch(predicate.op){case"and":case"or":{return predicate.args.some(hasRelationHop)}case"not":{return hasRelationHop(predicate.arg)}case"relation_field":{return true}default:{return false}}};var relationFieldPredicate=(value,path)=>object({relationSchemaId:optional3(json)})(value,path).relationSchemaId===undefined?object({direction:absent2,field:identity2,inner:policyPredicate,op:literal("relation_field")})(value,path):retiredForm("relation_field.relationSchemaId",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 retiredForm(op,path)}case"relation_field":{return relationFieldPredicate(value,path)}default:{return invalid4(`${path}/op`)}}};var writableField=(value,path)=>{const field=array2(identity2)(value,path);return field.length>=2&&field[0]==="data"?field:invalid4(path)};var writableFields=(value,path)=>{const fields=array2(writableField)(value,path);return fields.length>0?fields:invalid4(path)};var subjectMatch=(value,path)=>{const predicate=policyPredicate(value,path);return hasRelationHop(predicate)?invalid4(path):predicate};var policyBody=object({rule:optional3(policyPredicate),subjectMatch,writableFields:optional3(writableFields)});var fieldWriteRule=(policy,path)=>policy.policyBody.writableFields===undefined||policy.effect==="allow"&&policy.policyType==="filter"&&(policy.targetKind==="entity_schema"||policy.targetKind==="entity_domain")?policy:invalid4(`${path}/policyBody/writableFields`);var relationScopeRule=(policy,path)=>policy.policyBody.rule===undefined||policy.targetKind==="entity_schema"||!hasRelationHop(policy.policyBody.rule)?policy:invalid4(`${path}/policyBody/rule`);var targetKind=(value,path)=>{if(value==="relation_domain"||value==="relation_schema"){throw new TypeError(`Invalid package manifest at ${path}: the policy kind ${value} is retired with Record Relations`)}return literal("entity_domain","entity_schema")(value,path)};var policyFields={effect:literal("allow","deny"),policyBody,policyType:literal("filter","gate"),targetFqn:identity2,targetKind};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=union3(refine(varyingObject({setupKey:identity2}),(value)=>Object.keys(value).some((key)=>key!=="setupKey")?"install-only input":undefined),refine(object({connectionInstanceFqn:identity2}),(value)=>Object.keys(value).some((key)=>key!=="connectionInstanceFqn")?"declared connection reference":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"),maxRemoteDeletionsPerRun:optional3(nullable(positiveSafeInteger)),missingConnectorFieldsBehavior:optional3(literal("prune","retain")),pushEntityMatch:optional3(literal("remote_ref","unique_fields")),remoteDeletionPropagation:optional3(literal("never","full","full_and_delta")),schemaFqn:identity2,supportedBindingModes:optional3(varyingArray(literal("managed","external"))),suppressEntityEvents:optBoolean});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 taskKind=(value,path)=>{if(value==="relation"){throw new TypeError(`Invalid package manifest at ${path}: the pipeline task kind relation is retired with Record Relations; a task names an entity binding`)}return literal("entity")(value,path)};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:taskKind,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=withoutRetiredRelationKey(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)),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}),"relationBindings");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,entityKeys,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}if(entityKeys?.has(bindingKey)===false||tasks.has(bindingKey)){invalid4(`${path}/definition/steps`)}tasks.add(bindingKey)}}};var knowledgeConnectorInstance=(value,path)=>{const parsed=knowledge(value,path);assertPolicyLifecycle(concrete(parsed.dataPolicies),path);const entities=concrete(parsed.entityBindings);const pipelines=concrete(parsed.pipelines);uniqueKeys(entities,`${path}/entityBindings`);uniqueKeys(pipelines,`${path}/pipelines`);const entityKeys=knownKeys(parsed.entityBindings);assertEntityParents(entities,path);for(const[index,binding]of entities.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,item]of pipelines.entries()){uniqueKeys(concrete(item.schedules),`${path}/pipelines/${index}/schedules`);assertPipelineTasks(item,entityKeys,`${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=union3(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 assertDataAccess=(value,own,location)=>{if(value===undefined){return}if(typeof value!=="object"||value===null||Array.isArray(value)){throw new TypeError(`${location}: dataAccess must be an object`)}for(const[source,mode]of Object.entries(value)){if(!["knowledge","datasets","documents"].includes(source)){throw new TypeError(`${location}: unknown dataAccess source '${source}'`)}if(mode!=="user"&&mode!==own){throw new TypeError(`${location}: dataAccess.${source} must be 'user' or '${own}'`)}}};var readDataAccess=(own)=>(value,location)=>{assertDataAccess(value,own,location);return value};var workflowDataAccess=(outer,inner,location)=>{assertDataAccess(outer,"workflow",location);assertDataAccess(inner,"workflow",`${location}.definition`);if(outer!==undefined&&inner!==undefined){for(const source of["knowledge","datasets","documents"]){if((outer[source]??"workflow")!==(inner[source]??"workflow")){throw new TypeError(`${location}: conflicting dataAccess.${source} in declaration and definition`)}}}return outer??inner};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 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=/^[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)+$/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)?.role.parent}return ancestor===key};var permissionsOf=({appPermissions=[],platformPermissions})=>[...platformPermissions,...appPermissions];var roleViolation=(entry,roles,declared)=>{const{kind,path,role}=entry;const{assignRoles=[],key,parent,replaces}=role;const visibility=entry.kind==="User Role"?entry.role.visibility:undefined;if(key==="anonymous"&&visibility!=="declared"){return`${path}: role 'anonymous' must be a User Role with Declared Visibility`}if(visibility==="user"&&Object.hasOwn(role,"bindings")){return`${path}.bindings: role '${key}' with User Visibility declares no bindings`}const assigned=assignRoles.find((other)=>declared.get(other)?.kind!=="User Role");if(assigned!==undefined){return`${path}.assignRoles: role '${assigned}' of role '${key}' is not a User Role of this application`}if(replaces!==undefined){if(declared.has(replaces)){return`${path}.replaces: role '${key}' replaces '${replaces}', which this release declares`}const first=roles.find((other)=>other.role.replaces===replaces);if(first?.role.key!==key){return`${path}.replaces: roles '${first?.role.key}' and '${key}' replace the same role '${replaces}'`}}if(parent===undefined){return}const held=declared.get(parent);if(held?.kind!==kind){return`${path}.parent: parent '${parent}' of role '${key}' is not a declared ${kind}`}const heldPermissions=permissionsOf(held.role);const missing=permissionsOf(role).find((permission)=>!heldPermissions.includes(permission));if(missing!==undefined){return`${path}.parent: role '${parent}' must hold permission '${missing}' of its child role '${key}'`}return isOwnAncestor(role,declared)?`${path}.parent: role '${key}' is its own ancestor`:undefined};var rolesViolation=(userRoles,serverRoles)=>{const roles=[...userRoles.map((role,index)=>({kind:"User Role",path:`userRoles[${index}]`,role})),...serverRoles.map((role,index)=>({kind:"Server Role",path:`serverRoles[${index}]`,role}))];const declared=new Map;for(const entry of roles){const{path,role}=entry;const{key,platformPermissions}=role;if(key.length>64||!roleKey.test(key)){return`${path}.key: role key '${key}' must match ${roleKey.source} and hold at most 64 characters`}if(declared.has(key)){return`${path}.key: role key '${key}' is declared more than once`}declared.set(key,entry);const malformed=platformPermissions.find((permission)=>!resourceAction.test(permission));if(malformed!==undefined){return`${path}.platformPermissions: permission '${malformed}' of role '${key}' must be 'resource:action'`}}for(const entry of roles){const violation=roleViolation(entry,roles,declared);if(violation!==undefined){return violation}}return};var defaultServerRoleViolation=(defaultServerRole,serverRoles)=>{if(defaultServerRole===undefined){return serverRoles.length===0?undefined:"defaultServerRole is required with serverRoles"}return serverRoles.some(({key})=>key===defaultServerRole)?undefined:`defaultServerRole: role '${defaultServerRole}' is not a declared Server Role`};var groupBindingsViolation=(groupBindings,userRoles)=>{for(const[index,{group,role}]of groupBindings.entries()){const path=`groupBindings[${index}]`;if(group.trim()===""){return`${path}.group: the Group Role Binding of role '${role}' must name a Group`}if(!userRoles.some(({key})=>key===role)){return`${path}.role: role '${role}' of the Group Role Binding to Group '${group}' is not a declared User Role`}const first=groupBindings.findIndex((other)=>other.group===group&&other.role===role);if(first!==index){return`${path}: the Group Role Binding of role '${role}' to Group '${group}' is declared more than once`}}return};var externalApplicationViolation=({applicationConsent,defaultServerRole,groupBindings=[],primaryRedirectUri,redirectUris,serverRoles=[],userRoles})=>{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'"}return rolesViolation(userRoles,serverRoles)??defaultServerRoleViolation(defaultServerRole,serverRoles)??groupBindingsViolation(groupBindings,userRoles)};var uuid=/^[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)=>uuid.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 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 subgroupNodes=(parentFqn,subgroups=[])=>subgroups.flatMap(({description,displayName,key,subgroups:nested})=>{const fqn=`${parentFqn}.${key}`;return[{description,displayName,fqn,parentFqn},...subgroupNodes(fqn,nested)]});var organizationGroupNodes=({description,displayName,fqn,parent,subgroups})=>[{description,displayName,fqn,parentFqn:parent},...subgroupNodes(fqn,subgroups)];var fields=["answerLength","bannedQuestions","enabled","otherInstructions","toneOfVoice"];var organizationInstructionsViolation=(definition)=>fields.some((field)=>definition[field]!==undefined)?undefined:"at least one field is required";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 fields2=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)=>!fields2.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 servicePrincipalOrganizationRoles=["organization_admin","organization_operator","organization_member"];var assertServicePrincipalGroups=(primitives)=>{const groups=new Set(primitives.flatMap((primitive)=>primitive.kind==="organizationGroup"?organizationGroupNodes(primitive).map(({fqn})=>fqn):[]));for(const primitive of primitives){if(primitive.kind!=="servicePrincipal"){continue}for(const group of primitive.groups){if(!groups.has(group)){throw new TypeError(`service principal '${primitive.fqn}' references Group '${group}' that this package does not declare`)}}}};var maxStudioTriggerFormFileBytes=10*1024*1024;var studioFormKey="studioForm";var fieldKeyPattern=/^[A-Za-z][A-Za-z0-9_]*$/u;var contentTypePattern=/^[\w.+-]+\/[\w.+-]+$/u;var fieldKey=refine(identity2,(key)=>fieldKeyPattern.test(key)?undefined:"key");var fileField=object({accept:optional3(refine(array2(refine(identity2,(type)=>contentTypePattern.test(type)?undefined:"content type")),(types)=>types.length===0?"no content type":undefined)),key:fieldKey,label:identity2,maxBytes:optional3(refine(positiveSafeInteger,(bytes)=>bytes>maxStudioTriggerFormFileBytes?"above ceiling":undefined)),type:literal("file")});var valueField=object({key:fieldKey,label:identity2,type:literal("boolean","number","text","textarea")});var enumField=object({key:fieldKey,label:identity2,options:refine(array2(object({label:identity2,value:identity2})),(options)=>options.length>0&&new Set(options.map(({value})=>value)).size===options.length?undefined:"options"),type:literal("enum")});var jsonField=object({key:fieldKey,label:identity2,schema:schemaDocument,type:literal("json")});var entitiesField=object({key:fieldKey,label:identity2,labelKey:optional3(identity2),schemaFqn:identity2,type:literal("entities"),valueKey:optional3(identity2)});var richTextField=object({key:fieldKey,label:identity2,type:literal("rich_text")});var userField=object({key:fieldKey,label:identity2,multiple:optBoolean,required:optBoolean,type:literal("user_select")});var fieldReaders={boolean:valueField,entities:entitiesField,enum:enumField,file:fileField,json:jsonField,number:valueField,rich_text:richTextField,text:valueField,textarea:valueField,user_select:userField};var formField=(value,path)=>{const{type}=object({type:literal("boolean","entities","enum","file","json","number","rich_text","text","textarea","user_select")})(value,path);return fieldReaders[type](value,path)};var studioFormFields=refine(array2(formField),(fields)=>new Set(fields.map(({key})=>key)).size===fields.length?undefined:"duplicate key");var studioTriggerFormAt=(metadata,path)=>optional3(object({fields:optional3(studioFormFields),organizationGroup:identity2}))(metadata[studioFormKey],`${path}/${studioFormKey}`);var studioTriggerMetadata=(read)=>(value,path)=>{const metadata=read(value,path);studioTriggerFormAt(metadata,path);return metadata};var access3=optional3(object({groups:refine(array2(identity2),(groups)=>groups.length===0?"no group":undefined)}));var view=object({access:access3,componentRef:identity2,dataBinding:optional3(object({filter:optional3(jsonObject),kind:literal("schema"),schema:identity2})),fqn:identity2,orderIndex:number3,props:optional3(jsonObject),slot:identity2});var pageBase={access:access3,fqn:identity2,fullHeight:optBoolean,fullWidth:optBoolean,icon:optString,label:string3,orderIndex:number3,routeSegment:identity2,slug:identity2};var genericPage=object({...pageBase,kind:literal("generic"),views:array2(view)});var predefinedPage=object({...pageBase,kind:literal("predefined"),predefinedPageRef:identity2});var page=(value,path)=>object({kind:literal("generic","predefined")})(value,path).kind==="generic"?genericPage(value,path):predefinedPage(value,path);var layout=(value,path)=>object({kind:literal("custom","left_sidebar")})(value,path).kind==="custom"?object({componentRef:identity2,kind:literal("custom"),props:optional3(jsonObject)})(value,path):object({kind:literal("left_sidebar")})(value,path);var studioViewKey=(fqn)=>(fqn.split(".").at(-1)??fqn).toLowerCase().replaceAll(/[^a-z0-9]+/gu,"-").replaceAll(/^-+|-+$/gu,"").slice(0,64);var hasDuplicate=(keys)=>new Set(keys).size!==keys.length;var collision=({sections})=>{const pages=sections.map((section)=>section.pages);const views=pages.flat().map((item)=>item.kind==="generic"?item.views:[]);if(hasDuplicate([...sections.map(({fqn})=>fqn),...pages.flat().map(({fqn})=>fqn),...views.flat().map(({fqn})=>fqn)])){return"duplicate FQN"}if(hasDuplicate(sections.map(({slug})=>slug))){return"duplicate section slug"}if(pages.some((items)=>hasDuplicate(items.map(({slug})=>slug)))){return"duplicate page slug"}return views.some((items)=>hasDuplicate(items.map(({fqn,slot})=>`${slot}
269
+ ${studioViewKey(fqn)}`)))?"duplicate view key":undefined};var isTrue=(value,path)=>value===true?true:invalid4(path);var studioAppDeclaration=object({...base,definition:refine(object({color:optString,description:optString,icon:optString,layout:optional3(layout),name:string3,sections:array2(object({access:access3,description:optString,fqn:identity2,icon:optString,label:string3,orderIndex:number3,pages:array2(page),slug:identity2})),slug:identity2}),collision),grants:object({groups:refine(array2(object({group:identity2,role:literal("manage","view")})),(grants)=>new Set(grants.map(({group})=>group)).size===grants.length?undefined:"duplicate Group")}),kind:literal("studioApp"),lifecycle:object({deployMode:literal("upsert"),readonly:isTrue})});var agentFormFields=(value,path)=>studioFormFields(value,path).map((field,index)=>field.type==="rich_text"||field.type==="user_select"?invalid4(`${path}/${index}/type`):field);var studioFormKey2="studioForm";var studioAgentFormAt=(metadata,path)=>optional3(object({fields:agentFormFields}))(metadata[studioFormKey2],`${path}/${studioFormKey2}`);var studioAgentMetadata=(read)=>(value,path)=>{const metadata=read(value,path);studioAgentFormAt(metadata,path);return metadata};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 studioAppTemplate=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=union3(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=union3(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=union3(object({eventIngress,kind:literal("event")}),union3(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")}))),user:optional3(object({multiple:boolean2})),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=union3(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({dataAccess:readDataAccess("workflow"),edges:array2(object({id:string3,source:union3(union3(actionEndpoint,inputEndpoint),triggerEndpoint),target:union3(union3(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:studioTriggerMetadata(jsonObject),settings:jsonObject,templateFqn:string3,templateVersion:string3})),version:literal(1)});var onlyKeys=(...keys)=>(value)=>Object.keys(value).some((key)=>!keys.includes(key))?"unexpected member":undefined;var remoteDeletion=union3(refine(object({capability:literal("full")}),onlyKeys("capability")),refine(object({capability:literal("full_and_delta"),feed:literal("server_filtered","client_filtered")}),onlyKeys("capability","feed")));var bindingTargets=(read)=>optional3(union3(literal("all"),array2(read)));var knowledgeTargets=bindingTargets(object({fqn:identity2,policy:optional3(identity2)}));var declaredBindings=optional3(object({agents:bindingTargets(identity2),documents:bindingTargets(identity2),knowledge:optional3(object({domains:knowledgeTargets,schemas:knowledgeTargets})),skills:bindingTargets(identity2),workflows:bindingTargets(identity2)}));var roleFields={appPermissions:optStrings,assignRoles:optStrings,key:string3,parent:optString,platformPermissions:strings,replaces:optString,users:optional3(object({create:boolean2}))};var roleVisibility=object({visibility:literal("user","declared")});var userVisibilityRole=object({...roleFields,visibility:literal("user")});var declaredVisibilityRole=object({...roleFields,bindings:declaredBindings,visibility:literal("declared")});var userRole=(value,path)=>roleVisibility(value,path).visibility==="declared"?declaredVisibilityRole(value,path):userVisibilityRole(value,path);var knowledgeSelection=optional3(object({exclude:optional3(array2(identity2)),include:optional3(array2(identity2))}));var toolBindings2=refine(array2(union3(identity2,object({approval:optional3(union3(literal("always","never"),object({rule:identity2}))),knowledge:optional3(withoutRetiredRelationKey(object({domains:knowledgeSelection,entitySchemas:knowledgeSelection,unrestricted:optBoolean}),"relationSchemas")),name:optional3(identity2),settings:optional3(jsonObject),tool:identity2}))),(tools)=>duplicateToolBinding(tools)===undefined?undefined:"duplicate tool binding");var withoutRetiredRelationFields=(read)=>(value,path)=>{const declaration=read(value,path);if("relationFields"in declaration){throw new TypeError(`Invalid package manifest at ${path}/relationFields: relationFields is no longer supported; rebuild the package with the current extensions SDK, which declares Entity Relation Fields in fieldSemantics`)}return declaration};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=union3(object({kind:literal("echo_query_parameter"),parameter:identity2}),union3(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_operator","organization_member"),domains:varyingStrings,enabled:boolean2,provisionMembers:boolean2}),provider:union3(object({fqn:identity2}),varyingObject({providerId:identity2}))});var organizationInstructions=object(varyingFields({...base,answerLength:optString,bannedQuestions:optString,enabled:optBoolean,kind:literal("organizationInstructions"),lifecycle,otherInstructions:optString,toneOfVoice:optString}));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 documentFolder=union3(refine(varyingObject({drive:identity2,folders:varyingArray(identity2)}),onlyKeys("drive","folders")),refine(varyingObject({remoteId:identity2}),onlyKeys("remoteId")));var declaredRule=varyingObject({effect:literal("allow","deny"),grantee:union3(refine(object({fqn:identity2,kind:literal("group","servicePrincipal")}),onlyKeys("fqn","kind")),refine(object({kind:literal("organization")}),onlyKeys("kind"))),permission:literal("manage","read","update","view_history"),target:union3(refine(object({kind:literal("collection")}),onlyKeys("kind")),refine(varyingObject({folder:documentFolder,kind:literal("folder")}),onlyKeys("folder","kind")))});var ruleAccess=({grantee,target})=>canonicalJson([grantee,target]);var unpairedHistoryRule=(rules)=>{if(rules===undefined||isVariableReference(rules)||canonicalJson(rules).includes('{"$variable":')){return}const concrete=rules.filter((rule)=>!isVariableReference(rule));const reads=new Set(concrete.filter(({effect,permission})=>effect==="allow"&&permission==="read").map(ruleAccess));const index=concrete.findIndex((rule)=>rule.effect==="allow"&&rule.permission==="view_history"&&!reads.has(ruleAccess(rule)));return index===-1?undefined:index};var documentCollection=(value,path)=>{const declaration=varyingObject({...base,connection:connection2,connectorFqn:optional3(identity2),indexContent:optBoolean,indexOverview:optBoolean,kind:literal("documentCollection"),overviewInputMaxChars,remoteRoots:varyingArray(documentFolder),richEnrichment,rules:optional3(varyingArray(declaredRule)),syncEnabled:optBoolean,title:identity2})(value,path);const unpaired=unpairedHistoryRule(declaration.rules);if(unpaired!==undefined){throw new TypeError(`Invalid package manifest at ${path}/rules/${unpaired}: an allow view_history rule needs an allow read rule for the same grantee and target`)}return declaration};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,bypassOrganizationInstructions:optional3(boolean2),dataAccess:readDataAccess("agent"),kind:literal("agent"),lifecycle,maxSteps:optional3(positiveSafeInteger),metadata:optional3(studioAgentMetadata(jsonObject)),modelTier:optional3(literal(...agentModelTiers)),objectives:strings,operatingInstructions:string3,output:optional3(object({schema:schema2})),responsibility:string3,skills:array2(identity2),tools:toolBindings2}),withoutRetiredAgentFields),connection,connectionInstance:substituted(varyingObject({...base,credentials:jsonObject,kind:literal("connectionInstance"),lifecycle,templateFqn:identity2})),datasetBlueprint,datasetConnectorInstance,datasetParser:object({...base,extensions:array2(identity2),format:datasetParserFormat,kind:literal("datasetParser"),mediaTypes:array2(identity2),parserVersion:datasetParserVersion}),datasetTableTemplate,documentCollection,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:withoutRetiredRelationKey(object({...base,catalogTags,domainFqn:string3,domainName:string3,entitySchemaFqns:strings,kind:literal("domainTemplate")}),"relationSchemaFqns"),emailProvider:object({...base,connectionTemplateFqn:identity2,deploymentIdentity:optional3(union3(literal("aws"),literal("azure"))),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}),defaultServerRole:optString,groupBindings:optional3(array2(object({coverage:optional3(literal("direct","inherited")),group:string3,lifecycle,role:string3}))),serverRoles:optional3(array2(object({...roleFields,bindings:declaredBindings}))),userRoles:array2(userRole)}),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:withoutRetiredRelationKey(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),deltaOverlapSeconds:optional3(positiveSafeInteger),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")),pullPageSize:optional3(positiveSafeInteger),recommendedImportSchedules:predefinedSchedules,remoteDeletion:optional3(remoteDeletion),remoteReference:optional3(object({providerKey:identity2,urlTemplate:knowledgeRemoteReferenceUrlTemplate})),settings:optional3(form),supportedBindingModes:optional3(bindingModes)}),"relationSchemaCapabilities"),knowledgeConnectorInstance,knowledgeConnectorOauth:object({...base,connectorFqn:string3,kind:literal("knowledgeConnectorOauth")}),knowledgeEntityAdapter:object({...base,connectorFqn:string3,entitySchemaFqn:string3,kind:literal("knowledgeEntityAdapter"),normalizesFieldMapValues:optBoolean,normalizesImportedData:optBoolean}),knowledgeEntitySchema:withoutRetiredRelationFields(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)),overviewInputMaxChars,persistFullFieldContributions:boolean2,richEnrichment,syncable:optBoolean,usableAsDocumentScope:boolean2,versioned:optBoolean,versioningEnabled:nullable(boolean2)})),knowledgePolicy:(value,path)=>relationScopeRule(fieldWriteRule(object({...base,...policyFields,kind:literal("knowledgePolicy"),priority:optNumber})(value,path),path),path),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),organizationInstructions:substituted(refine(organizationInstructions,organizationInstructionsViolation)),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),servicePrincipal:object({...base,groups:array2(identity2),kind:literal("servicePrincipal"),organizationRole:literal(...servicePrincipalOrganizationRoles)}),skill:object({dataAccess:readDataAccess("skill"),...base,instructions:string3,kind:literal("skill"),lifecycle,tools:toolBindings2}),skillTemplate:object({...base,catalogTags,kind:literal("skillTemplate"),lifecycle:optional3(lifecycle),name:string3}),studioApp:studioAppDeclaration,studioAppTemplate:object({...base,definition:studioAppTemplate,kind:literal("studioAppTemplate")}),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:refine(object({dataAccess:readDataAccess("workflow"),...base,definition:authoringDefinition,kind:literal("workflow"),lifecycle,name:string3,runDetailsRetention:optional3(literal("full","outcome_only")),servicePrincipalFqn:optional3(identity2),slug:string3}),(workflow)=>{workflowDataAccess(workflow.dataAccess,workflow.definition.dataAccess,`workflow:${workflow.fqn}`)}),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 retiredRelationKinds=new Set(["knowledgeRelationAdapter","knowledgeRelationSchema"]);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)}}if(retiredRelationKinds.has(kind)){throw new TypeError(`Invalid package manifest at ${p}/kind: the component kind ${kind} is retired with Record Relations; declare a Reference Field instead`)}return invalid4(`${p}/kind`)};var readDependency=object({fqn:hostedIdentity});var parsePackageDependencies=(value)=>{const requirements=array2(readDependency)(value,"/dependencies");const identities=new Set;for(const requirement of requirements){if(Object.keys(requirement).some((key)=>key!=="fqn")){throw new TypeError(`package dependency '${requirement.fqn}' has unexpected fields`)}if(identities.has(requirement.fqn)){throw new TypeError(`duplicate package dependency '${requirement.fqn}'`)}identities.add(requirement.fqn)}return[...requirements].sort((left,right)=>compareUtf16CodeUnits(left.fqn,right.fqn))};var PackageManifestVersion="v4";var tenantlessSingletonKinds=["organizationInstructions","organizationSettings"];var assertTenantlessSingletonScopes=(manifest)=>{if(manifest.bindingScopes?.includes("tenant")!==true){return}const carried=tenantlessSingletonKinds.find((kind)=>manifest.primitives.some((primitive)=>primitive.kind===kind));if(carried!==undefined){throw new TypeError(`package '${manifest.fqn}' declares ${carried} and cannot bind to the tenant scope`)}};var legacyFixedDestinationTargets=new Set(["fixed-email","channel-destination","telegram-chat","whatsapp-destination"]);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 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(parsePackageDependencies),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)),"");assertServicePrincipalGroups(manifest.primitives);assertTenantlessSingletonScopes(manifest);return manifest.dependencies===undefined?manifest:{...manifest,dependencies:parsePackageDependencies(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&&current<=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",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 retiredRelationKinds2=new Set(["knowledgeRelationAdapter","knowledgeRelationSchema","knowledge_relation_adapter","knowledge_relation_schema"]);var retiredRelationKeys=new Map([["domainTemplate","relationSchemaFqns"],["knowledgeConnector","relationSchemaCapabilities"],["knowledgeConnectorInstance","relationBindings"]]);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 toolResultBrand=Symbol.for("@ci/tool-result");var slot=(location,profile,direction,projection)=>({direction,location,profile,projection});var optionalFormSlot=(location,form)=>form===undefined||form===null?[]:[slot(location,"interactive_form","input",form.schema)];var declarationSchemaSlots=(declaration)=>{switch(declaration.kind){case"agent":{return declaration.output===undefined?[]:[slot(`agent:${declaration.fqn}.output`,"runtime_json","output",declaration.output.schema)]}case"tool":{const inputProfile=declaration.usageScopes===undefined||declaration.usageScopes.some((scope)=>scope==="chat"||scope==="skill")?"ai_function_input":"runtime_json";return[slot(`tool:${declaration.fqn}.input`,inputProfile,"input",declaration.input),slot(`tool:${declaration.fqn}.output`,"runtime_json","output",declaration.output),...optionalFormSlot(`tool:${declaration.fqn}.bindingSettings.schema`,declaration.bindingSettings),...optionalFormSlot(`tool:${declaration.fqn}.settings.schema`,declaration.settings)]}case"connection":{return optionalFormSlot(`connection:${declaration.fqn}.credential.schema`,declaration.credential)}case"knowledgeConnector":{return optionalFormSlot(`connector:${declaration.fqn}.settings.schema`,declaration.settings)}case"notificationChannel":{return[...optionalFormSlot(`notification-channel:${declaration.fqn}.credential.schema`,declaration.credential),...optionalFormSlot(`notification-channel:${declaration.fqn}.definition.setup.setupForm.schema`,declaration.definition.setup.setupForm)]}case"workflowNode":{const prefix=`workflow_node:${declaration.fqn}.contract`;return[...declaration.contract.configSchema===undefined?[]:[slot(`${prefix}.configSchema`,"workflow_value","input",declaration.contract.configSchema)],...declaration.contract.inputSchema===undefined?[]:[slot(`${prefix}.inputSchema`,"workflow_value","input",declaration.contract.inputSchema)],...declaration.contract.outputSchema===undefined?[]:[slot(`${prefix}.outputSchema`,"workflow_value","output",declaration.contract.outputSchema)],...(declaration.contract.ports??[]).flatMap((port,index)=>[slot(`${prefix}.ports[${String(index)}].valueSchema`,"workflow_value",port.direction,port.valueSchema),...(port.schemaResolution?.variants??[]).map((variant,variantIndex)=>slot(`${prefix}.ports[${String(index)}].schemaResolution.variants[${String(variantIndex)}].schema`,"workflow_value",port.direction,variant.schema))]),...(declaration.contract.outputChannels??[]).map((channel,index)=>slot(`${prefix}.outputChannels[${String(index)}].valueSchema`,"workflow_value","output",channel.valueSchema))]}case"workflowField":{return declaration.contract.valueSchema===undefined?[]:[slot(`workflow_field:${declaration.fqn}.contract.valueSchema`,"workflow_value",declaration.contract.availableForOutput===true?"output":"input",declaration.contract.valueSchema)]}case"workflowTemplate":{return[slot(`workflow_template:${declaration.fqn}.definition.inputContract.schema`,"workflow_value","input",declaration.definition.inputContract.schema),slot(`workflow_template:${declaration.fqn}.definition.outputContract.schema`,"workflow_value","output",declaration.definition.outputContract.schema)]}case"studioComponent":{return[slot(`studio_component:${declaration.fqn}.propsSchema`,"studio_props","input",declaration.propsSchema)]}case"knowledgeEntitySchema":{return[slot(`knowledge_entity_schema:${declaration.fqn}.schema`,"knowledge_record","input",declaration.schema)]}case"datasetTableTemplate":{const prefix=`dataset_table_template:${declaration.fqn}`;return[slot(`${prefix}.configuration`,"runtime_json","input",declaration.configuration),slot(`${prefix}.requirements`,"runtime_json","input",declaration.requirements)]}case"externalAppGateway":{const prefix=`external_app_gateway:${declaration.fqn}.expectedContract`;return declaration.expectedContract.operationDomains.flatMap((domain,domainIndex)=>domain.operations.flatMap((operation,operationIndex)=>{const operationPrefix=`${prefix}.operationDomains[${String(domainIndex)}].operations[${String(operationIndex)}]`;return[slot(`${operationPrefix}.input`,"runtime_json","input",operation.input),slot(`${operationPrefix}.output`,"runtime_json","output",operation.output)]}))}case"datasetBlueprint":case"datasetParser":case"documentCollection":case"documentsConnector":case"domain":case"domainTemplate":case"emailProvider":case"eventListener":case"externalApplication":case"externalDatasetProvider":case"fieldTransformer":case"connectionInstance":case"knowledgeConnectorInstance":case"datasetConnectorInstance":case"knowledgeConnectorOauth":case"knowledgeEntityAdapter":case"knowledgePolicy":case"managedDatasetProvider":case"servicePrincipal":case"organizationGroup":case"organizationInstructions":case"organizationSettings":case"organizationSso":case"outboundMessagingProvider":case"skill":case"skillTemplate":case"studioApp":case"studioAppTemplate":case"remoteToolCollection":case"toolCollection":case"toolSettingsOptions":case"workflow":case"workflowFieldCollection":case"workflowNodeCollection":{return[]}default:{const exhaustive=declaration;return exhaustive}}};var packageSchemaSlots=(definition)=>definition.manifest.primitives.flatMap(declarationSchemaSlots);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("uninstall"),packageFqn:nonBlankString,recovery:packageOperationRecoverySchema}),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 dependencyReferenceSchema=unionType([pinSchema,objectType({fqn:nonBlankString})]);var dependencyPathsSchema=arrayType(arrayType(stringType()));var blockerMessageSchema=stringType();var rejectedDefinitionKinds={agent:"agent",application_grant:"application_grant",connection_instance:"connection_instance",dataset_connector_instance:"dataset_connector_instance",document_collection:"document_collection",external_app:"external_app",knowledge_connector_instance:"knowledge_connector_instance",organization_group:"organization_group",organization_instructions:"organization_instructions",organization_settings:"organization_settings",remote_tool_collection:"remote_tool_collection",skill:"skill",studio_app:"studio_app",workflow:"workflow"};var knownBlockerSchema=unionType([objectType({_tag:literalType("admin_principal_confirmation_required"),message:blockerMessageSchema,paths:dependencyPathsSchema,principalFqn:stringType()}),objectType({_tag:literalType("manual_prerequisite"),message:blockerMessageSchema,observed:pinSchema.nullable(),path:arrayType(dependencyReferenceSchema),paths:arrayType(arrayType(dependencyReferenceSchema)),required:dependencyReferenceSchema}),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:nativeEnumType(rejectedDefinitionKinds)})),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","dependents_present","in_use","tenant_mandatory","workflow_templates_in_use"])});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 createHash5,randomUUID}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(map5((loaded)=>isRecord2(loaded)?loaded:undefined),flatMap4((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(flatMap4((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,"@collective-intelligence/extensions-sdk-frontend-react/studio-api"]};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)=>`
270
270
  import { createBackendPackageRuntime } from "@collective-intelligence/extensions-sdk-backend";
271
271
  import * as declaration from "ci-package-declaration";
272
272
  export function createPackageRuntime() {
@@ -300,7 +300,7 @@ Defaulting to 2020, but this will stop working in the future.`)}options.ecmaVers
300
300
  `)}
301
301
  `};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 parse3(C,g="@"){if(!E)return init.then(()=>parse3(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(`
302
302
  `).length}:${E.e()-C.lastIndexOf(`
303
- `,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)=>parse3(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:String5,releaseDigest:String5,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=String5.check(isMinLength(1),makeFilter2((value)=>value.trim().length>0));var uuid3=String5.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(String5);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)&&isLiteral2(connection.setupKey)?[connection.setupKey]:[];var slotsOf=(primitive)=>{if(primitive.kind==="datasetConnectorInstance"||primitive.kind==="documentCollection"){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)}
303
+ `,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 decoder2=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)=>parse3(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=decoder2.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=decoder2.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=decoder2.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:String5,releaseDigest:String5,valid:Boolean3})))({package:manifest.package.fqn,releaseDigest:manifest.releaseDigest,valid:true})}),runPromise2);var decoder3=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))(decoder3.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=String5.check(isMinLength(1),makeFilter2((value)=>value.trim().length>0));var uuid2=String5.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:uuid2}))),connections:optionalKey2(Record(nonempty,Union2([Struct({connectionId:uuid2}),Struct({newConnection:Struct({fields:JsonObject,name:nonempty})})]))),variables:optionalKey2(Record(nonempty,variableInput))});var isLink=is2(link4);var isUuid=is2(uuid2);var isText=is2(String5);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)&&isLiteral2(connection.setupKey)?[connection.setupKey]:[];var slotsOf=(primitive)=>{if(primitive.kind==="datasetConnectorInstance"||primitive.kind==="documentCollection"){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)}
304
304
  `};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:String5,nextAction:optional2(String5),operationId:optional2(String5),recoveryFile:optional2(String5),status:optional2(String5)}){}var values=new Set(["backend-url","declaration","inputs","resume","organization","gateway-url","profile","timeout-ms","var"]);var repeatable=new Set(["gateway-url","var"]);var switches=new Set(["accept-breaking-changes","allow-admin-principals","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 validateResumeOptions=(options,vars,gatewayUrls,reject)=>{if(options.has("resume")&&(options.has("declaration")||options.has("inputs")||vars.length>0||Object.keys(gatewayUrls).length>0||options.has("accept-breaking-changes")||options.has("allow-admin-principals")||options.has("inputs-template"))){reject("--resume cannot be combined with declaration or deployment intent options")}};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")}validateResumeOptions(options,vars,gatewayUrls,reject);return{...options.has("resume")?{resume:required("resume")}:undefined,acceptBreakingChanges:options.has("accept-breaking-changes"),allowAdminPrincipals:options.has("allow-admin-principals"),declaration:options.has("resume")?"":required("declaration"),gatewayUrls,...options.has("inputs")?{inputs:required("inputs")}:undefined,inputsTemplate:options.has("inputs-template"),json,nonInteractive:options.has("non-interactive"),timeoutMs,vars}};import{createHash as createHash4,randomBytes as randomBytes2}from"crypto";import{closeSync,constants as constants2,fstatSync,fsyncSync,mkdirSync as mkdirSync2,mkdtempSync,openSync,readFileSync as readFileSync2,writeFileSync as writeFileSync2}from"fs";import nodePath4 from"path";var bodyFields={acceptBreakingChanges:Boolean3,allowAdminPrincipals:optionalKey2(Boolean3),deploymentPolicy:Literal2("strict"),gatewayUrls:Record(String5,String5),releaseId:String5.check(isMinLength(1)),setup:optionalKey2(Struct({adoptions:optionalKey2(Record(String5,Struct({instanceId:String5}))),connections:optionalKey2(Record(String5,Union2([Struct({connectionId:String5}),Struct({newConnection:Struct({fields:JsonObject,name:String5})})])))})),variables:optionalKey2(Record(String5,Json2))};var common={backendUrl:String5,credentialDigest:String5.check(isPattern2(/^[a-f0-9]{64}$/u)),credentialSalt:String5.check(isPattern2(/^[a-f0-9]{64}$/u)),idempotencyKey:String5.check(isPattern2(/^ci-deploy-(?:install|update)-[a-f0-9]{64}$/u)),organizationId:String5,packageFqn:String5,receiptVersion:Literal2(1),releaseDigest:String5,version:String5};var receiptSchema=Union2([Struct({...common,body:Struct(bodyFields),kind:Literal2("install")}),Struct({...common,body:Struct({...bodyFields,installationId:String5,protocolVersion:Literal2("v1")}),kind:Literal2("update")})]);var parseDeploymentReceipt=decodeUnknownSync(receiptSchema,{onExcessProperty:"error"});var decodeReceipt=decodeUnknownSync(fromJsonString2(receiptSchema),{onExcessProperty:"error"});var digestCredential=(salt,authorization)=>createHash4("sha256").update(salt).update("\x00").update(authorization).digest("hex");var bindDeploymentCredential=(authorization)=>{if(authorization===""){throw new Error("Missing deployment credential")}const credentialSalt=randomBytes2(32).toString("hex");return{credentialDigest:digestCredential(credentialSalt,authorization),credentialSalt}};var saveDeploymentReceipt=(directory,receipt)=>{mkdirSync2(directory,{mode:448,recursive:true});const privateDirectory=mkdtempSync(nodePath4.join(directory,"deploy-"));const file=nodePath4.join(privateDirectory,"request.json");const fd=openSync(file,"wx",384);try{writeFileSync2(fd,JSON.stringify(receipt));fsyncSync(fd)}finally{closeSync(fd)}return file};var readDeploymentReceipt=(file,backendUrl,organizationId,authorization)=>{const fd=openSync(file,constants2.O_RDONLY|constants2.O_NOFOLLOW);try{const stat=fstatSync(fd);if(!stat.isFile()||(stat.mode&63)!==0||process.getuid!==undefined&&stat.uid!==process.getuid()){throw new Error("Unsafe receipt permissions")}const receipt=decodeReceipt(readFileSync2(fd,"utf-8"));if(receipt.backendUrl!==backendUrl||receipt.organizationId!==organizationId){throw new Error("Receipt target mismatch")}if(authorization===""||digestCredential(receipt.credentialSalt,authorization)!==receipt.credentialDigest){throw new Error("Deployment recovery credential mismatch")}return receipt}finally{closeSync(fd)}};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 recoveryFile;let operationId;let lastEventId;return yield*tryPromise2({catch:(cause)=>is2(DeployCommandError)(cause)?new DeployCommandError({cause:cause.cause,json:cause.json,lastEventId:cause.lastEventId,message:cause.message,nextAction:cause.nextAction,operationId:cause.operationId,recoveryFile:cause.recoveryFile??recoveryFile,status:cause.status}):new DeployCommandError({cause,json:options.json,lastEventId,message:is2(PackageOperationCommandError)(cause)?cause.message:"Could not deploy package",operationId,recoveryFile}),try:async(signal)=>{const reject=(message)=>{throw new DeployCommandError({json:options.json,lastEventId,message,operationId})};const confirmAdminPrincipal=async(principalFqn)=>{const message=`Service principal '${principalFqn}' grants Organization Admin authority. Pass --allow-admin-principals to confirm deployment.`;if(options.nonInteractive){reject(message)}const answer=await dependencies.prompt(`${message} Confirm deployment? [y/N]: `);if(!["y","yes"].includes(answer.trim().toLowerCase())){reject(message)}};const follow=async(acceptedId,client,canConfirm=false)=>{operationId=acceptedId;lastEventId=0;writeProgress(`${JSON.stringify({kind:"progress",operationId,status:"accepted"})}
305
305
  `);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"})}
306
306
  `)}}),{signal});if(canConfirm&&followed.kind==="snapshot"&&followed.snapshot.status==="failed"&&followed.snapshot.application.state==="not_applied"&&followed.snapshot.application.blocker?._tag==="admin_principal_confirmation_required"){return followed.snapshot.application.blocker}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"})}return null};const announceRecovery=()=>{writeProgress(options.json?`${JSON.stringify({kind:"recovery",recoveryFile})}
@@ -308,7 +308,7 @@ Defaulting to 2020, but this will stop working in the future.`)}options.ecmaVers
308
308
  Resume with ci deploy --resume <receipt-file> and the same Backend and Organization.
309
309
  `)};const replay=async(receipt)=>{operationId=undefined;lastEventId=undefined;const accepted=receipt.kind==="install"?await installPackage({body:receipt.body,client:dependencies.organization,idempotencyKey:receipt.idempotencyKey,organizationId:receipt.organizationId,packageFqn:receipt.packageFqn,signal}):await updatePackage({body:receipt.body,client:dependencies.organization,idempotencyKey:receipt.idempotencyKey,organizationId:receipt.organizationId,signal});const confirmation=await follow(accepted.operationId,dependencies.organization,receipt.body.allowAdminPrincipals!==true);if(confirmation!==null){await confirmAdminPrincipal(confirmation.principalFqn);const confirmed=parseDeploymentReceipt({...receipt,body:{...receipt.body,allowAdminPrincipals:true},idempotencyKey:`ci-deploy-${receipt.kind}-${createHash5("sha256").update(randomUUID()).digest("hex")}`});recoveryFile=saveDeploymentReceipt(dependencies.recoveryDirectory,confirmed);announceRecovery();await replay(confirmed);return}const action=receipt.kind==="install"?"installed":"updated";dependencies.writeOutput(options.json?`${JSON.stringify({action,kind:"result",packageFqn:receipt.packageFqn,releaseDigest:receipt.releaseDigest,releaseId:receipt.body.releaseId,status:"succeeded"})}
310
310
  `:`Deployed ${receipt.packageFqn}@${receipt.version}: ${action} (${receipt.body.releaseId})
311
- `)};const configuration=dependencies.organization.getConfig();const backendUrl=configuration.baseUrl??"";const authorization=is2(instanceOf(Headers))(configuration.headers)?configuration.headers.get("authorization")??"":"";if(options.resume!==undefined){const receipt=(()=>{try{return readDeploymentReceipt(options.resume,backendUrl,options.organizationId,authorization)}catch{return reject("Invalid deployment recovery file, unsafe permissions, or Backend/Organization/credential mismatch")}})();recoveryFile=options.resume;announceRecovery();await replay(receipt);return}const file=options.inputs===undefined?undefined:await readInputsFile(options.inputs,reject);const release=await buildRelease(options,dependencies);let{allowAdminPrincipals}=options;for(const primitive of release.packageManifest.primitives){if(options.allowAdminPrincipals||primitive.kind!=="servicePrincipal"||primitive.organizationRole!=="organization_admin"){continue}await confirmAdminPrincipal(primitive.fqn);allowAdminPrincipals=true}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 invocationId=randomUUID();const key=(stage)=>`ci-deploy-${stage}-${createHash5("sha256").update(canonicalJson({...lookupBody,...["install","update"].includes(stage)&&{invocationId},acceptBreakingChanges:options.acceptBreakingChanges,...allowAdminPrincipals?{allowAdminPrincipals:true}:undefined,gatewayUrls,organizationId:options.organizationId,...inputs})).digest("hex")}`;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 intent={...inputs,acceptBreakingChanges:options.acceptBreakingChanges,...allowAdminPrincipals?{allowAdminPrincipals:true}:undefined,deploymentPolicy:"strict",gatewayUrls,releaseId:exact.releaseId};const common={...bindDeploymentCredential(authorization),backendUrl,organizationId:options.organizationId,packageFqn:release.manifest.package.fqn,receiptVersion:1,releaseDigest:release.releaseDigest,version:release.manifest.package.version};const receipt=parseDeploymentReceipt(existing===undefined?{...common,body:intent,idempotencyKey:key("install"),kind:"install"}:{...common,body:{...intent,installationId:existing.id,protocolVersion:"v1"},idempotencyKey:key("update"),kind:"update"});recoveryFile=saveDeploymentReceipt(dependencies.recoveryDirectory,receipt);announceRecovery();await replay(receipt)}}).pipe(timeoutOrElse2({duration:options.timeoutMs,orElse:()=>fail6(new DeployCommandError({json:options.json,lastEventId,message:"Deployment wait timed out; resume with --resume and the saved recovery file, or reconnect to its operation",operationId,recoveryFile,status:"timed_out"}))}))});class DoctorCommandError extends TaggedError3()("DoctorCommandError",{cause:optional2(Unknown2),message:String5}){}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:String5}){}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}
311
+ `)};const configuration=dependencies.organization.getConfig();const backendUrl=configuration.baseUrl??"";const authorization=is2(instanceOf(Headers))(configuration.headers)?configuration.headers.get("authorization")??"":"";if(options.resume!==undefined){const receipt=(()=>{try{return readDeploymentReceipt(options.resume,backendUrl,options.organizationId,authorization)}catch{return reject("Invalid deployment recovery file, unsafe permissions, or Backend/Organization/credential mismatch")}})();recoveryFile=options.resume;announceRecovery();await replay(receipt);return}const file=options.inputs===undefined?undefined:await readInputsFile(options.inputs,reject);const release=await buildRelease(options,dependencies);let{allowAdminPrincipals}=options;for(const primitive of release.packageManifest.primitives){if(options.allowAdminPrincipals||primitive.kind!=="servicePrincipal"||primitive.organizationRole!=="organization_admin"){continue}await confirmAdminPrincipal(primitive.fqn);allowAdminPrincipals=true}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 invocationId=randomUUID();const key=(stage)=>`ci-deploy-${stage}-${createHash5("sha256").update(canonicalJson({...lookupBody,...["install","update"].includes(stage)&&{invocationId},acceptBreakingChanges:options.acceptBreakingChanges,...allowAdminPrincipals?{allowAdminPrincipals:true}:undefined,gatewayUrls,organizationId:options.organizationId,...inputs})).digest("hex")}`;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 intent={...inputs,acceptBreakingChanges:options.acceptBreakingChanges,...allowAdminPrincipals?{allowAdminPrincipals:true}:undefined,deploymentPolicy:"strict",gatewayUrls,releaseId:exact.releaseId};const common={...bindDeploymentCredential(authorization),backendUrl,organizationId:options.organizationId,packageFqn:release.manifest.package.fqn,receiptVersion:1,releaseDigest:release.releaseDigest,version:release.manifest.package.version};const receipt=parseDeploymentReceipt(existing===undefined?{...common,body:intent,idempotencyKey:key("install"),kind:"install"}:{...common,body:{...intent,installationId:existing.id,protocolVersion:"v1"},idempotencyKey:key("update"),kind:"update"});recoveryFile=saveDeploymentReceipt(dependencies.recoveryDirectory,receipt);announceRecovery();await replay(receipt)}}).pipe(timeoutOrElse2({duration:options.timeoutMs,orElse:()=>fail6(new DeployCommandError({json:options.json,lastEventId,message:"Deployment wait timed out; resume with --resume and the saved recovery file, or reconnect to its operation",operationId,recoveryFile,status:"timed_out"}))}))});class DoctorCommandError extends TaggedError3()("DoctorCommandError",{cause:optional2(Unknown2),message:String5}){}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:String5}){}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(map5((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}
312
312
  `);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}`})
313
313
  `)})}).pipe(mapError2((cause)=>is2(LoginCommandError)(cause)?cause:new LoginCommandError({cause,message:cause.message})));class LogoutCommandError extends TaggedError3()("LogoutCommandError",{cause:optional2(Unknown2),message:String5}){}var logoutCommandEffect=(args,dependencies)=>gen2(function*logoutCommand(){yield*parseCommandOptionsEffect(args,{values:targetOptions});const selected=yield*tryConfiguration(()=>selectedProfile({args,environment:dependencies.environment}));const session=selected?.profile.session;if(selected===undefined||session===undefined){return yield*new LogoutCommandError({message:"No CLI Session is stored in the selected Profile"})}const revocation=yield*result2(managementOk("CLI Session revocation",authLogout,{client:makeBackendManagementClient({backendUrl:selected.profile.apiOrigin,fetch:dependencies.fetch,token:session.token})}));yield*tryConfiguration(()=>updateProfile(dependencies.environment,selected.name,({apiOrigin,currentOrganizationId,session:latest})=>{const signedOut=currentOrganizationId===undefined?{apiOrigin}:{apiOrigin,currentOrganizationId};return latest?.token===session.token?signedOut:undefined}));const{apiOrigin}=selected.profile;if(isFailure2(revocation)){return yield*new LogoutCommandError({cause:revocation.failure,message:`Removed the CLI Session from Profile ${selected.name}, but the backend did not revoke it (${revocation.failure.message}); it stays valid until it expires`})}return yield*sync2(()=>{dependencies.writeOutput(`Logged out of ${apiOrigin}; removed the CLI Session from Profile ${selected.name}
314
314
  `)})}).pipe(mapError2((cause)=>is2(LogoutCommandError)(cause)?cause:new LogoutCommandError({cause,message:cause.message})));var text=String5.check(isMinLength(1),makeFilter2((value)=>value.trim().length>0));var nullableText=NullOr(String5);var storageProvider=Literals(["file_system","ftp","sftp","s3","azure_blob","gcs"]);var inputSchema=Struct({embedding:optionalKey2(Struct({defaultChunkSize:optionalKey2(NullOr(Finite)),description:optionalKey2(nullableText),embeddingModelId:optionalKey2(text),name:optionalKey2(nullableText),options:optionalKey2(Record(String5,Unknown2))})),installPackages:optionalKey2(Boolean3),organization:optionalKey2(Struct({availableLanguages:optionalKey2(NullOr(ArraySchema(String5))),defaultLanguage:optionalKey2(nullableText),meta:optionalKey2(nullableText),name:optionalKey2(text),slug:optionalKey2(nullableText),timezone:optionalKey2(text)})),presetId:optionalKey2(text),storage:optionalKey2(Struct({description:optionalKey2(nullableText),mountPoint:optionalKey2(nullableText),name:optionalKey2(nullableText),providerType:optionalKey2(storageProvider),settings:optionalKey2(Record(String5,Unknown2)),useInstallationDefaults:optionalKey2(Boolean3)}))});var decodeCreateInputFile=(content)=>decodeEffect2(fromJsonString2(inputSchema),{onExcessProperty:"error"})(content).pipe(mapError2(()=>({message:"Invalid inputs file: expected partial organization, presetId, storage, embedding and installPackages setup fields with valid types; unknown structural fields are not allowed"})),flatMap4((input)=>{const chunkSize=input.embedding?.defaultChunkSize;return chunkSize!==undefined&&chunkSize!==null&&!Number.isInteger(chunkSize)?fail6({message:"Invalid inputs file: embedding.defaultChunkSize must be an integer or null"}):succeed6(input)}));var mergeCreateInputs=(options,file)=>{const organization={...file.organization};for(const key of["name","slug","timezone"]){const value=optionValue2(options,key);if(value!==undefined){organization[key]=value}}const merged={...file,organization};const preset=optionValue2(options,"preset");if(preset!==undefined){merged.presetId=preset}const provider=optionValue2(options,"storage-provider");if(provider!==undefined){merged.storage={...file.storage,providerType:decodeUnknownSync(storageProvider)(provider)}}const embeddingModelId=optionValue2(options,"embedding-model");if(embeddingModelId!==undefined){merged.embedding={...file.embedding,embeddingModelId}}return merged};var resolvedOrganization=(input)=>{const{availableLanguages,...organization}=input.organization??{};const{name}=organization;if(name===undefined){return}const slug=organization.slug===undefined?name.trim().toLowerCase().replaceAll(/[^a-z0-9]+/gu,"-").replaceAll(/^-+|-+$/gu,""):organization.slug;const result={...organization,name,slug,timezone:organization.timezone??"UTC"};if(availableLanguages!==undefined){result.availableLanguages=availableLanguages===null?null:[...availableLanguages]}return result};var resolvedStorage=(input,providerType,defaults)=>{const storage={...input,providerType};if(storage.useInstallationDefaults===undefined&&storage.settings===undefined&&defaults.storageProvider===providerType){storage.useInstallationDefaults=true}return storage};var resolveEmbedding=(input,defaults)=>{const result={...input};if(result.embeddingModelId===undefined&&defaults.embeddingModelId!==undefined){result.embeddingModelId=defaults.embeddingModelId}return result};var missingEmbedding=(embedding,defaults)=>embedding===undefined||defaults.requireEmbedding===true&&embedding.embeddingModelId===undefined&&defaults.embeddingModelId===undefined;var resolveCreateInput=(input,defaults={})=>{const organization=resolvedOrganization(input);const presetId=input.presetId??defaults.presetId;const providerType=input.storage?.providerType??defaults.storageProvider;let{embedding}=input;if(embedding===undefined&&defaults.embeddingModelId!==undefined){embedding={}}const missing=[];if(organization===undefined){missing.push("organization name (--name)")}if(organization?.slug===""){missing.push("nonempty slug (--slug)")}if(presetId===undefined){missing.push("default preset (--preset)")}if(providerType===undefined){missing.push("installation storage provider (--storage-provider)")}if(missingEmbedding(embedding,defaults)){missing.push("configured embedding model (--embedding-model or --inputs)")}if(missing.length>0||organization===undefined||presetId===undefined||providerType===undefined||embedding===undefined){return{missing}}const storage=resolvedStorage(input.storage,providerType,defaults);const resolvedEmbedding=resolveEmbedding(embedding,defaults);const body={embedding:resolvedEmbedding,organization,presetId,storage};if(input.installPackages!==undefined){body.installPackages=input.installPackages}return{body}};var nonempty2=String5.check(isMinLength(1));var trustedSetupResult=is2(Struct({embeddingProviderId:nonempty2,installedPackages:ArraySchema(Struct({fqn:nonempty2,version:nonempty2})),organization:Struct({id:nonempty2,name:nonempty2,slug:NullOr(String5),timezone:nonempty2}),presetApplicationId:nonempty2,presetId:nonempty2,storageId:nonempty2}));var createFailure=Union2([Struct({error:String5,status:Literal2("failed")}),Struct({error:String5,nextAction:String5,slug:NullOr(String5),status:Literal2("outcome_unknown")}),Struct({error:String5,nextAction:String5,result:declare((value)=>trustedSetupResult(value)),selection:Literal2("failed"),status:Literal2("created_selection_failed")})]);var presetList=is2(Struct({presets:ArraySchema(Struct({embeddingModel:NullOr(Struct({id:nonempty2})),id:nonempty2}))}));var validCatalog=is2(Struct({defaultStorageProvider:String5}));var commandArgument=(value)=>/^[a-zA-Z0-9_./:-]+$/u.test(value)?value:`'${value.replaceAll("'",`'"'"'`)}'`;var recoveryArgument=(value)=>value.trim()!==""&&!value.startsWith("--")&&!/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(value);var lookupRecovery=(slug,target)=>{const{origin}=new URL(target.apiOrigin);if(slug===null||!recoveryArgument(slug)||target.profile!==undefined&&!recoveryArgument(target.profile)){return`Recovery arguments cannot be represented safely; inspect Organizations in the Dashboard for API ${origin} before retrying. A match does not prove this request created it, and no match does not prove rollback.`}const profile=target.profile===undefined?"":` --profile ${commandArgument(target.profile)}`;return`ci orgs list --slug ${commandArgument(slug)} --json --backend-url ${commandArgument(origin)}${profile}; a match does not prove this request created it, and no match does not prove rollback`};var unknownOutcome=(slug,target)=>({error:"Organization setup outcome is unknown; creation was not retried",nextAction:lookupRecovery(slug,target),slug,status:"outcome_unknown"});var readInputs=(options,dependencies)=>gen2(function*readCreateInputs(){const file=optionValue2(options,"inputs");if(file===undefined){return{}}const content=yield*try_2({catch:()=>({message:"Could not read inputs file"}),try:()=>dependencies.readInputFile?.(file)});if(content===undefined){return yield*fail6({message:"Could not read inputs file"})}return yield*decodeCreateInputFile(content)});var configuredDefaults=(input,client)=>gen2(function*loadConfiguredDefaults(){let{presetId}=input;if(presetId===undefined){const elected=yield*managementData("Default preset",aiModelPresetsDefault,{client}).pipe(catchIf2((error)=>error.status===404,()=>void_3));if(elected!==undefined&&!is2(Struct({presetId:nonempty2}))(elected)){return yield*fail6({message:"Default preset returned invalid configuration"})}presetId=elected?.presetId}let embeddingModelId=input.embedding?.embeddingModelId;if(embeddingModelId===undefined){const presets=yield*managementData("Model presets",aiModelPresetsList,{client});if(!presetList(presets)){return yield*fail6({message:"Model presets returned invalid configuration"})}embeddingModelId=presets.presets.find((preset)=>preset.id===presetId)?.embeddingModel?.id}const defaults={embeddingModelId,presetId,requireEmbedding:true};if(input.storage?.providerType===undefined||input.storage.useInstallationDefaults===undefined&&input.storage.settings===undefined){const catalog=yield*managementData("Setup catalog",organizationSetupCatalog,{client});if(!validCatalog(catalog)){return yield*fail6({message:"Setup catalog returned invalid configuration"})}if(is2(storageProvider)(catalog.defaultStorageProvider)){defaults.storageProvider=catalog.defaultStorageProvider}}return defaults});var selectCreated=(result,target,dependencies)=>gen2(function*selectCreatedOrganization(){const{profile}=target;if(target.credentialSource!=="cli-session"||profile===undefined){return{result,selection:"not_applicable",status:"created"}}const selected=yield*tryConfiguration(()=>updateProfile(dependencies.environment,profile,(latest)=>new URL(latest.apiOrigin).origin===new URL(target.apiOrigin).origin?{...latest,currentOrganizationId:result.organization.id}:undefined)).pipe(result2);if(selected._tag==="Failure"||selected.success===undefined){return{error:"Organization was created, but the saved Profile could not be updated",nextAction:`ci orgs use ${commandArgument(result.organization.id)} --profile ${commandArgument(profile)}`,result,selection:"failed",status:"created_selection_failed"}}return{result,selection:"selected",status:"created"}});var createOrganization=(args,dependencies)=>gen2(function*createOrganizationFlow(){const options=yield*parseCommandOptionsEffect(args,{switches:["defaults","json"],values:["backend-url","profile","name","slug","timezone","preset","storage-provider","embedding-model","inputs"]});const contents=yield*readInputs(options,dependencies);const input=yield*try_2({catch:()=>({message:"Invalid --storage-provider; expected file_system, ftp, sftp, s3, azure_blob or gcs"}),try:()=>mergeCreateInputs(options,contents)});const target=yield*tryConfiguration(()=>resolveBackendManagementTarget({args,environment:dependencies.environment}));const client=makeBackendManagementClient({backendUrl:target.apiOrigin,fetch:dependencies.fetch,token:target.token});const defaults=options.switches.has("defaults")?yield*configuredDefaults(input,client):{};const resolution=resolveCreateInput(input,defaults);if(resolution.missing!==undefined){return{error:`Missing setup values: ${resolution.missing.join(", ")}`,status:"failed"}}const response=yield*managementData("Organization setup",organizationSetupSetup,{body:resolution.body,client}).pipe(result2);if(response._tag==="Failure"){const{status}=response.failure;if(status>=400&&status<500&&status!==408){return{error:`Organization setup refused (HTTP ${status}); check tenant permission, slug uniqueness and setup configuration`,status:"failed"}}return unknownOutcome(resolution.body.organization.slug??null,target)}if(!trustedSetupResult(response.success)){return unknownOutcome(resolution.body.organization.slug??null,target)}return yield*selectCreated(response.success,target,dependencies)}).pipe(catch_2((error)=>succeed6({error:is2(ManagementRequestError)(error)?`Setup prerequisite request failed (HTTP ${error.status}); check tenant authorization and configuration`:error.message,status:"failed"})));class OrgsCommandError extends TaggedError3()("OrgsCommandError",{cause:optional2(Unknown2),json:optional2(Boolean3),message:String5,outcome:optional2(createFailure)}){}var usage5=`Usage: ci orgs list [--slug <slug>] [--json] | ci orgs create [options] | ci orgs use <organization-id>
@@ -358,7 +358,7 @@ ${body.join(`
358
358
 
359
359
  `)}
360
360
  `,warnings}};var printers={effect:printEffect,types:printTypes,zod:printZod};var reservedNames={effect:["Infinity","RegExp","Schema"],types:[],zod:["Infinity","RegExp","z"]};var identifier23=/^[A-Za-z_$][A-Za-z0-9_$]*$/u;var error=(code,schemaName,pointer)=>({code,keyword:null,pointer,schemaName});var hasSlot=({name})=>name.includes("#");var compare2=(left,right)=>{if(left===right){return 0}return left<right?-1:1};var inInputOrder=(schemas,errors)=>{const position=(schemaName)=>schemas.findIndex((schema)=>schema.name===schemaName);return[...errors].sort((left,right)=>position(left.schemaName)-position(right.schemaName)||compare2(left.pointer,right.pointer))};var declarationsOf2=(models,named)=>named.flatMap(({exportName,input})=>[{name:exportName,pointer:"",schemaName:input.name},...(models.get(input)?.definitions??[]).map(({name,node})=>({name:defName(exportName,name),pointer:node.pointer,schemaName:input.name}))]);var declarationErrors=(target,declarations)=>{const uses=new Map;for(const{name}of declarations){uses.set(name,(uses.get(name)??0)+1)}const reserved=reservedNames[target];return declarations.flatMap(({name,pointer,schemaName})=>{if(!identifier23.test(name)){return[error("invalid_name",schemaName,pointer)]}if(reserved.includes(name)){return[error("reserved_name",schemaName,pointer)]}return(uses.get(name)??0)>1?[error("name_clash",schemaName,pointer)]:[]})};var withoutRepeats=(warnings)=>{const seen=new Set;return warnings.filter((warning)=>{const key=JSON.stringify([warning.schemaName,warning.pointer,warning.kind,warning.keyword]);if(seen.has(key)){return false}seen.add(key);return true})};var structuralWarning=({schemaName})=>({kind:"structural_fidelity",message:"The projection is structural: the schema can reject values that the wire shape accepts.",pointer:"",schemaName});var generateSchemaModule=({header,schemas,target})=>{const parsed=schemas.map((schema)=>[schema,parseSchema(schema)]);const models=new Map(parsed.flatMap(([schema,{model}])=>model===undefined?[]:[[schema,model]]));const named=nameSchemas(header.packageFqn,schemas.filter(hasSlot));const namedSchemas=named.named??[];const errors=[...parsed.flatMap(([,result])=>result.errors??[]),...schemas.filter((schema)=>!hasSlot(schema)).map(({name})=>error("invalid_name",name,"")),...named.errors??[],...declarationErrors(target,declarationsOf2(models,namedSchemas))];if(errors.length>0){return{errors:inInputOrder(schemas,errors)}}const printable=namedSchemas.flatMap(({exportName,input})=>{const model=models.get(input);return model===undefined?[]:[{exportName,fidelity:input.fidelity,model,schemaName:input.name}]});const printed=printable.length===0?{source:"",warnings:[]}:printers[target](printable);if("errors"in printed){return{errors:inInputOrder(schemas,printed.errors)}}return{source:`${printHeader({...header,target})}
361
- ${printed.source}`,warnings:[...printable.filter(({fidelity})=>fidelity==="structural").map(structuralWarning),...withoutRepeats(printed.warnings)]}};import path5 from"path";import path4 from"path";var codegenTargets=["types","zod","effect"];var isCodegenTarget=is2(Literals(codegenTargets));class PackageCodegenConfigError extends TaggedError3()("PackageCodegenConfigError",{cause:optional2(Unknown2),message:String5,setting:String5}){}var nonEmpty3=String5.check(isMinLength(1));var packageFile=Struct({ci:optionalKey2(Struct({codegen:optionalKey2(Struct({declaration:optionalKey2(Union2([nonEmpty3,ArraySchema(nonEmpty3)])),out:optionalKey2(nonEmpty3),target:optionalKey2(String5)}))}))});var decodePackageFile=decodeUnknownEffect2(fromJsonString2(packageFile));var missingSetting=(setting)=>new PackageCodegenConfigError({message:`Missing ${setting}: pass --${setting} or set ci.codegen.${setting} in package.json`,setting});var readSection=(ports,file)=>tryPromise2({catch:(cause)=>new PackageCodegenConfigError({cause,message:`Cannot read ${file}`,setting:"package.json"}),try:async()=>await ports.readFile(file)??"{}"}).pipe(flatMap4((content)=>decodePackageFile(content).pipe(mapError2((cause)=>new PackageCodegenConfigError({cause,message:`Invalid ${file}: ${cause.message}`,setting:"package.json"})))),map4((decoded)=>decoded.ci?.codegen??{}));var resolveSettings=(args,ports)=>gen2(function*resolveAll(){const options=yield*parseCommandOptionsEffect(args,{repeatable:["declaration"],switches:["check","verbose"],values:["out","target"]});const cwd=ports.cwd();const file=path4.join(cwd,"package.json");const section=yield*readSection(ports,file);const target=optionValue2(options,"target")??section.target;if(target===undefined){return yield*missingSetting("target")}if(!isCodegenTarget(target)){return yield*new PackageCodegenConfigError({message:`Invalid target '${target}': use ${codegenTargets.join(", ")}`,setting:"target"})}const flagOut=optionValue2(options,"out");const rawOut=flagOut??section.out;if(rawOut===undefined){return yield*missingSetting("out")}const out=path4.resolve(flagOut===undefined?path4.dirname(file):cwd,rawOut);const flagDeclarations=optionValues(options,"declaration");const fromFlags=flagDeclarations.length>0;const declarationBase=fromFlags?cwd:path4.dirname(file);const declarations=(fromFlags?flagDeclarations:ensure(section.declaration??[])).map((declaration)=>path4.resolve(declarationBase,declaration));if(!isReadonlyArrayNonEmpty(declarations)){return yield*missingSetting("declaration")}return{check:options.switches.has("check"),declarations,out,target,verbose:options.switches.has("verbose")}});class PackageCodegenPlanError extends TaggedError3()("PackageCodegenPlanError",{cause:optional2(Unknown2),message:String5,reason:Literals(["declaration_load_failed","duplicate_package","slot_location_mismatch"])}){}var traverse=forEach2;var slotLabel=(location,fqn)=>{const subject=location.slice(location.indexOf(":")+1);return location.includes(":")&&subject.startsWith(`${fqn}.`)?subject.slice(fqn.length+1):undefined};var plannedSchemas=(definition)=>traverse(definition.manifest.primitives,(primitive)=>{const slots=packageSchemaSlots({manifest:{...definition.manifest,primitives:[primitive]}});const{fqn}=primitive;return traverse(slots,({location,projection})=>{const label=slotLabel(location,fqn);return label===undefined?fail6(new PackageCodegenPlanError({message:`Schema slot '${location}' does not belong to component '${fqn}'`,reason:"slot_location_mismatch"})):succeed6({document:projection.document,fidelity:projection.fidelity,name:`${fqn}#${label}`})})}).pipe(map4(flatten2));var describeFailure=(cause)=>{if(!(cause instanceof Error)){return String(cause)}return cause.cause instanceof Error?describeFailure(cause.cause):cause.message};var loadDeclarations=(specifier,ports)=>tryPromise2({catch:(cause)=>new PackageCodegenPlanError({cause,message:`Cannot load declaration '${specifier}': ${describeFailure(cause)}`,reason:"declaration_load_failed"}),try:()=>Promise.resolve(ports.loadDeclarations(specifier))});var byPackageFqn=mapInput(String2,({packageFqn})=>packageFqn);var buildPlan=(settings,ports)=>gen2(function*planAll(){const planned=new Map;for(const specifier of settings.declarations){const definitions=yield*loadDeclarations(specifier,ports);for(const definition of definitions){const{fqn,version}=definition.manifest;const first=planned.get(fqn);if(first!==undefined){return yield*new PackageCodegenPlanError({message:`Package '${fqn}' is declared twice: in '${first.specifier}' and in '${specifier}'`,reason:"duplicate_package"})}planned.set(fqn,{packageFqn:fqn,packageVersion:version,schemas:yield*plannedSchemas(definition),specifier})}}return sort(planned.values(),byPackageFqn)});class PackageCodegenOverwriteRefusedError extends TaggedError3()("PackageCodegenOverwriteRefusedError",{message:String5,paths:ArraySchema(String5)}){}class PackageCodegenWriterIoError extends TaggedError3()("PackageCodegenWriterIoError",{cause:Unknown2,message:String5,operation:Literals(["readFile","rename","writeFile"]),path:String5}){}var traverse2=forEach2;var leadingComment=/^\s*(?:\/\*[\s\S]*?\*\/|(?:\/\/[^\n]*(?:\n|$))+)/u;var hasGeneratedHeader=(source)=>leadingComment.exec(source)?.[0].includes("@generated")??false;var checkStatus=(existing,source)=>{if(existing===undefined){return"missing"}return existing===source?"current":"different"};var io=(operation,path,call)=>tryPromise2({catch:(cause)=>new PackageCodegenWriterIoError({cause,message:`Could not ${operation} '${path}': ${cause instanceof Error?cause.message:String(cause)}`,operation,path}),try:()=>Promise.resolve(call())});var readExisting=(plan,ports)=>traverse2(plan,(file)=>io("readFile",file.path,()=>ports.readFile(file.path)).pipe(map4((existing)=>({existing,file}))));var writeOutputs=(plan,ports)=>gen2(function*writeOutputsEffect(){const compared=yield*readExisting(plan,ports);const refused=compared.filter(({existing,file})=>existing!==undefined&&existing!==file.source&&!hasGeneratedHeader(existing));if(refused.length>0){const paths=refused.map(({file})=>file.path);return yield*new PackageCodegenOverwriteRefusedError({message:`Refusing to overwrite files without the generated header: ${paths.join(", ")}`,paths})}const changes=compared.filter(({existing,file})=>existing!==file.source).map(({file})=>({...file,temporary:`${file.path}.${process.pid}.tmp`}));yield*traverse2(changes,({source,temporary})=>io("writeFile",temporary,()=>ports.writeFile(temporary,source)),{discard:true});yield*traverse2(changes,({path,temporary})=>io("rename",path,()=>ports.rename(temporary,path)),{discard:true});return compared.map(({existing,file})=>({path:file.path,status:existing===file.source?"unchanged":"written"}))});var checkOutputs=(plan,ports)=>readExisting(plan,ports).pipe(map4((compared)=>compared.map(({existing,file})=>({path:file.path,status:checkStatus(existing,file.source)}))));class PackageCodegenCommandError extends TaggedError3()("PackageCodegenCommandError",{message:String5,reason:Literals(["check_failed","generation_failed"])}){}var countOnlyKind="closed_object_unenforced";var maxExamples=3;var pointerText=(pointer)=>pointer===""?"#":pointer;var warningLocation=({keyword,pointer,schemaName})=>`${schemaName} ${pointerText(pointer)}${keyword===undefined?"":` ${keyword}`}`;var errorLine=({code,keyword,pointer,schemaName})=>`${schemaName} ${pointerText(pointer)} ${code}${keyword===null?"":` ${keyword}`}`;var warningLines=(warnings,verbose)=>verbose?warnings.map((warning)=>`warning ${warning.kind} ${warningLocation(warning)}`):[...Map.groupBy(warnings,({kind})=>kind)].flatMap(([kind,group])=>[`warning ${kind}: ${group.length}`,...kind===countOnlyKind?[]:group.slice(0,maxExamples).map((warning)=>` ${warningLocation(warning)}`)]);var generationFailed=(failures)=>new PackageCodegenCommandError({message:["Schema generation failed, no file was written:",...failures.flatMap(({errors,packageFqn})=>[`${packageFqn}:`,...errors.map((error)=>` ${errorLine(error)}`)])].join(`
361
+ ${printed.source}`,warnings:[...printable.filter(({fidelity})=>fidelity==="structural").map(structuralWarning),...withoutRepeats(printed.warnings)]}};import path5 from"path";import path4 from"path";var codegenTargets=["types","zod","effect"];var isCodegenTarget=is2(Literals(codegenTargets));class PackageCodegenConfigError extends TaggedError3()("PackageCodegenConfigError",{cause:optional2(Unknown2),message:String5,setting:String5}){}var nonEmpty3=String5.check(isMinLength(1));var packageFile=Struct({ci:optionalKey2(Struct({codegen:optionalKey2(Struct({declaration:optionalKey2(Union2([nonEmpty3,ArraySchema(nonEmpty3)])),out:optionalKey2(nonEmpty3),target:optionalKey2(String5)}))}))});var decodePackageFile=decodeUnknownEffect2(fromJsonString2(packageFile));var missingSetting=(setting)=>new PackageCodegenConfigError({message:`Missing ${setting}: pass --${setting} or set ci.codegen.${setting} in package.json`,setting});var readSection=(ports,file)=>tryPromise2({catch:(cause)=>new PackageCodegenConfigError({cause,message:`Cannot read ${file}`,setting:"package.json"}),try:async()=>await ports.readFile(file)??"{}"}).pipe(flatMap4((content)=>decodePackageFile(content).pipe(mapError2((cause)=>new PackageCodegenConfigError({cause,message:`Invalid ${file}: ${cause.message}`,setting:"package.json"})))),map5((decoded)=>decoded.ci?.codegen??{}));var resolveSettings=(args,ports)=>gen2(function*resolveAll(){const options=yield*parseCommandOptionsEffect(args,{repeatable:["declaration"],switches:["check","verbose"],values:["out","target"]});const cwd=ports.cwd();const file=path4.join(cwd,"package.json");const section=yield*readSection(ports,file);const target=optionValue2(options,"target")??section.target;if(target===undefined){return yield*missingSetting("target")}if(!isCodegenTarget(target)){return yield*new PackageCodegenConfigError({message:`Invalid target '${target}': use ${codegenTargets.join(", ")}`,setting:"target"})}const flagOut=optionValue2(options,"out");const rawOut=flagOut??section.out;if(rawOut===undefined){return yield*missingSetting("out")}const out=path4.resolve(flagOut===undefined?path4.dirname(file):cwd,rawOut);const flagDeclarations=optionValues(options,"declaration");const fromFlags=flagDeclarations.length>0;const declarationBase=fromFlags?cwd:path4.dirname(file);const declarations=(fromFlags?flagDeclarations:ensure(section.declaration??[])).map((declaration)=>path4.resolve(declarationBase,declaration));if(!isReadonlyArrayNonEmpty(declarations)){return yield*missingSetting("declaration")}return{check:options.switches.has("check"),declarations,out,target,verbose:options.switches.has("verbose")}});class PackageCodegenPlanError extends TaggedError3()("PackageCodegenPlanError",{cause:optional2(Unknown2),message:String5,reason:Literals(["declaration_load_failed","duplicate_package","slot_location_mismatch"])}){}var traverse=forEach2;var slotLabel=(location,fqn)=>{const subject=location.slice(location.indexOf(":")+1);return location.includes(":")&&subject.startsWith(`${fqn}.`)?subject.slice(fqn.length+1):undefined};var plannedSchemas=(definition)=>traverse(definition.manifest.primitives,(primitive)=>{const slots=packageSchemaSlots({manifest:{...definition.manifest,primitives:[primitive]}});const{fqn}=primitive;return traverse(slots,({location,projection})=>{const label=slotLabel(location,fqn);return label===undefined?fail6(new PackageCodegenPlanError({message:`Schema slot '${location}' does not belong to component '${fqn}'`,reason:"slot_location_mismatch"})):succeed6({document:projection.document,fidelity:projection.fidelity,name:`${fqn}#${label}`})})}).pipe(map5(flatten2));var describeFailure=(cause)=>{if(!(cause instanceof Error)){return String(cause)}return cause.cause instanceof Error?describeFailure(cause.cause):cause.message};var loadDeclarations=(specifier,ports)=>tryPromise2({catch:(cause)=>new PackageCodegenPlanError({cause,message:`Cannot load declaration '${specifier}': ${describeFailure(cause)}`,reason:"declaration_load_failed"}),try:()=>Promise.resolve(ports.loadDeclarations(specifier))});var byPackageFqn=mapInput(String2,({packageFqn})=>packageFqn);var buildPlan=(settings,ports)=>gen2(function*planAll(){const planned=new Map;for(const specifier of settings.declarations){const definitions=yield*loadDeclarations(specifier,ports);for(const definition of definitions){const{fqn,version}=definition.manifest;const first=planned.get(fqn);if(first!==undefined){return yield*new PackageCodegenPlanError({message:`Package '${fqn}' is declared twice: in '${first.specifier}' and in '${specifier}'`,reason:"duplicate_package"})}planned.set(fqn,{packageFqn:fqn,packageVersion:version,schemas:yield*plannedSchemas(definition),specifier})}}return sort(planned.values(),byPackageFqn)});class PackageCodegenOverwriteRefusedError extends TaggedError3()("PackageCodegenOverwriteRefusedError",{message:String5,paths:ArraySchema(String5)}){}class PackageCodegenWriterIoError extends TaggedError3()("PackageCodegenWriterIoError",{cause:Unknown2,message:String5,operation:Literals(["readFile","rename","writeFile"]),path:String5}){}var traverse2=forEach2;var leadingComment=/^\s*(?:\/\*[\s\S]*?\*\/|(?:\/\/[^\n]*(?:\n|$))+)/u;var hasGeneratedHeader=(source)=>leadingComment.exec(source)?.[0].includes("@generated")??false;var checkStatus=(existing,source)=>{if(existing===undefined){return"missing"}return existing===source?"current":"different"};var io=(operation,path,call)=>tryPromise2({catch:(cause)=>new PackageCodegenWriterIoError({cause,message:`Could not ${operation} '${path}': ${cause instanceof Error?cause.message:String(cause)}`,operation,path}),try:()=>Promise.resolve(call())});var readExisting=(plan,ports)=>traverse2(plan,(file)=>io("readFile",file.path,()=>ports.readFile(file.path)).pipe(map5((existing)=>({existing,file}))));var writeOutputs=(plan,ports)=>gen2(function*writeOutputsEffect(){const compared=yield*readExisting(plan,ports);const refused=compared.filter(({existing,file})=>existing!==undefined&&existing!==file.source&&!hasGeneratedHeader(existing));if(refused.length>0){const paths=refused.map(({file})=>file.path);return yield*new PackageCodegenOverwriteRefusedError({message:`Refusing to overwrite files without the generated header: ${paths.join(", ")}`,paths})}const changes=compared.filter(({existing,file})=>existing!==file.source).map(({file})=>({...file,temporary:`${file.path}.${process.pid}.tmp`}));yield*traverse2(changes,({source,temporary})=>io("writeFile",temporary,()=>ports.writeFile(temporary,source)),{discard:true});yield*traverse2(changes,({path,temporary})=>io("rename",path,()=>ports.rename(temporary,path)),{discard:true});return compared.map(({existing,file})=>({path:file.path,status:existing===file.source?"unchanged":"written"}))});var checkOutputs=(plan,ports)=>readExisting(plan,ports).pipe(map5((compared)=>compared.map(({existing,file})=>({path:file.path,status:checkStatus(existing,file.source)}))));class PackageCodegenCommandError extends TaggedError3()("PackageCodegenCommandError",{message:String5,reason:Literals(["check_failed","generation_failed"])}){}var countOnlyKind="closed_object_unenforced";var maxExamples=3;var pointerText=(pointer)=>pointer===""?"#":pointer;var warningLocation=({keyword,pointer,schemaName})=>`${schemaName} ${pointerText(pointer)}${keyword===undefined?"":` ${keyword}`}`;var errorLine=({code,keyword,pointer,schemaName})=>`${schemaName} ${pointerText(pointer)} ${code}${keyword===null?"":` ${keyword}`}`;var warningLines=(warnings,verbose)=>verbose?warnings.map((warning)=>`warning ${warning.kind} ${warningLocation(warning)}`):[...Map.groupBy(warnings,({kind})=>kind)].flatMap(([kind,group])=>[`warning ${kind}: ${group.length}`,...kind===countOnlyKind?[]:group.slice(0,maxExamples).map((warning)=>` ${warningLocation(warning)}`)]);var generationFailed=(failures)=>new PackageCodegenCommandError({message:["Schema generation failed, no file was written:",...failures.flatMap(({errors,packageFqn})=>[`${packageFqn}:`,...errors.map((error)=>` ${errorLine(error)}`)])].join(`
362
362
  `),reason:"generation_failed"});var checkCurrent=(files,ports)=>checkOutputs(files,ports).pipe(flatMap4((results)=>{const stale=results.filter(({status})=>status!=="current");return stale.length>0?new PackageCodegenCommandError({message:["Generated files are not current:",...stale.map((file)=>` ${file.status} ${file.path}`)].join(`
363
363
  `),reason:"check_failed"}):succeed6(results)}));var packageCodegenCommandEffect=(args,deps)=>gen2(function*run(){const settings=yield*resolveSettings(args,deps);const plan=yield*buildPlan(settings,deps);const files=[];const failures=[];for(const planned of plan){const{packageFqn,packageVersion,schemas}=planned;const result=generateSchemaModule({header:{packageFqn,packageVersion},schemas,target:settings.target});if(result.errors===undefined){files.push({path:path5.join(settings.out,packageFqn,`${settings.target}.ts`),schemaCount:schemas.length,source:result.source,warnings:result.warnings})}else{failures.push({errors:result.errors,packageFqn})}}if(failures.length>0){return yield*generationFailed(failures)}const results=yield*settings.check?checkCurrent(files,deps):writeOutputs(files,deps);const lines=zip(files,results).flatMap(([file,{status}])=>[settings.check?`${status} ${file.path}`:`${status} ${file.path} (${file.schemaCount} schemas)`,...warningLines(file.warnings,settings.verbose)]);yield*sync2(()=>{for(const line of lines){deps.writeOutput(line)}})});import{fileURLToPath as fileURLToPath5}from"url";var awaitValue3=(value)=>promise2(constant(Promise.resolve(value)));var nodePath5=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=nodePath5.dirname(fileURLToPath5(declarationSpecifier));const workspaceCandidate=nodePath5.resolve(process.cwd(),specifier.slice(1));const workspaceRelation=nodePath5.relative(declarationDirectory,workspaceCandidate);return workspaceRelation!==""&&!workspaceRelation.startsWith("..")&&!nodePath5.isAbsolute(workspaceRelation)?workspaceCandidate:nodePath5.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 nodePath5.resolve(nodePath5.dirname(fileURLToPath5(declarationSpecifier)),specifier)}return specifier};var entrySource=(identity)=>`export { ${moduleExport2(identity.exportName)} } from "ci-backend-contribution"`;var localModulePath=(specifier,identity)=>{if(!nodePath5.isAbsolute(specifier)){return specifier}try{return Bun.resolveSync(specifier,nodePath5.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()}
364
364
  `,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 traverse3=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)}
@@ -3239,18 +3239,20 @@ export default exportModule.__esModule ? exportModule.default : exportModule`);c
3239
3239
  export const __moduleExports = exportModule;
3240
3240
  `:nextCode}if(getIsRolldown(this))return{code};return{code,syntheticNamedExports:"__moduleExports"}};const pendingImportFalseExportUsage=id.includes("__loadShare__")?getCompleteImportFalseExportUsage(id):undefined;if(pendingImportFalseExportUsage)return pendingImportFalseExportUsage.then(loadVirtualModule);return loadVirtualModule()},generateBundle(_outputOptions,bundle,_isWrite){inlineDeferredPrebuildNamespaceHelper(bundle);for(const[fileName,fallbacks]of findEagerFallbacksInSharedChunk(bundle))mfWarn(`A shared-dependency fallback was merged into the loadShare chunk ${fileName}: ${fallbacks.join(", ")}.
3241
3241
  That fallback is no longer lazy, so consumers download their local copy even when a peer provides the share, and the container can deadlock.
3242
- Stop the shared module from statically importing another share.`);for(const[fileName,chunk]of Object.entries(bundle)){if(!isOutputChunk(chunk))continue;if(!isFederationControlChunk(fileName,filename))continue;chunk.code=sanitizeFederationControlChunk(chunk.code,fileName,filename)}const proxyChunks=collectLoadShareProxyChunks(bundle,LOAD_SHARE_TAG);if(proxyChunks.size>0){const systemProxyInfo=collectSystemProxyInfos(proxyChunks,LOAD_SHARE_TAG);for(const[fileName,chunk]of Object.entries(bundle)){if(!isOutputChunk(chunk))continue;if(proxyChunks.has(fileName))continue;let code=chunk.code;if(!fileName.includes("__loadShare__"))code=rewriteEsmProxyConsumers(code,proxyChunks);code=rewriteSystemProxyConsumers(code,systemProxyInfo);if(code!==chunk.code)chunk.code=code}}}},{name:"module-federation-strip-empty-preload-helper",enforce:"post",apply:"build",renderChunk(code,chunk){if(!isFederationControlChunk(chunk.fileName,filename))return;const nextCode=sanitizeFederationControlChunk(code,chunk.fileName,filename);return nextCode===code?null:{code:nextCode,map:null}},writeBundle(outputOptions,bundle){if(!outputOptions.dir)return;for(const chunk of Object.values(bundle)){if(!isOutputChunk(chunk))continue;if(!isFederationControlChunk(chunk.fileName,filename))continue;const outputPath=path$14.join(outputOptions.dir,chunk.fileName);writeFileSync5(outputPath,sanitizeFederationControlChunk(readFileSync6(outputPath,"utf-8"),chunk.fileName,filename))}}},{name:"module-federation-vite",enforce:"post",_options:options,config(config,{command:_command}){const isRolldown=getIsRolldown(this);isSsrBuild=_command==="build"&&Boolean(config.build?.ssr);const needsRuntimeHelpers=hasShared(options);if(needsRuntimeHelpers)appendResolveAlias(config,{find:/^@module-federation\/runtime\/helpers$/,replacement:getRuntimeHelpersImplementation(options.implementation)});appendResolveAlias(config,{find:/^@module-federation\/runtime$/,replacement:options.implementation});config.build||={};config.build.commonjsOptions||={};config.build.commonjsOptions.strictRequires??="auto";config.optimizeDeps||={};config.optimizeDeps.include||=[];config.optimizeDeps.include.push("@module-federation/runtime");if(needsRuntimeHelpers)config.optimizeDeps.include.push("@module-federation/runtime/helpers");options.runtimePlugins.forEach((p)=>{const pluginPath=getRuntimePluginSpecifier(p);if(SSR_ONLY_RUNTIME_PLUGINS.has(pluginPath))return;if(pluginPath&&!pluginPath.startsWith(".")&&!pluginPath.startsWith("/")&&!pluginPath.startsWith("\x00")&&!pluginPath.startsWith("virtual:")){let optimizeDep=pluginPath;if(pluginPath==="@module-federation/dts-plugin/dynamic-remote-type-hints-plugin")try{optimizeDep=normalizePathForImport(resolveImportPath(pluginPath))}catch{optimizeDep=pluginPath}config.optimizeDeps.include.push(optimizeDep)}});if(isRolldown){config.build??={};config.build.target??="esnext"}const isBundledDev=Boolean(config.experimental?.bundledDev);if(isRolldown&&_command==="serve"&&isBundledDev){config.build.rolldownOptions??={};config.build.rolldownOptions.experimental??={};const devMode=config.build.rolldownOptions.experimental.devMode;if(typeof devMode==="object")devMode.lazy??=false;else if(devMode===undefined)config.build.rolldownOptions.experimental.devMode={lazy:false}}const isAstro=hasPackageDependency("astro");const resolvedTarget=options.target??(config.build?.ssr?"node":"web");if(!config.define)config.define={};const userSetEnvTarget="ENV_TARGET"in config.define;applyBuildTimeRuntimeDefines(config.define,options,{target:resolvedTarget,isAstro,defaultDisableSnapshot:resolvedTarget==="node"?true:undefined});inheritedEnvTarget=userSetEnvTarget?undefined:config.define.ENV_TARGET;for(const warning of getRuntimeCapabilityConfigurationWarnings(options)){if(emittedRuntimeCapabilityWarnings.has(warning))continue;emittedRuntimeCapabilityWarnings.add(warning);mfWarn(warning)}},configResolved(config){if(!hasPackageDependency("nitro"))return;const prematureExit=config.plugins.find((plugin)=>plugin.name==="tanstack-build-exit");if(prematureExit)prematureExit.closeBundle=undefined},configEnvironment(name,config){if(!isServerEnvironment(name,config))return;const isAstro=hasPackageDependency("astro");config.define={...config.define??{}};if(inheritedEnvTarget!==undefined&&config.define.ENV_TARGET===inheritedEnvTarget)delete config.define.ENV_TARGET;applyBuildTimeRuntimeDefines(config.define,options,{target:options.target??"node",isAstro,defaultDisableSnapshot:true})}},...Manifest(options),...pluginSSRRemoteEntry(options),...VarRemoteEntry(options),{name:"module-federation-vinext-fix-rsc-preload-as",enforce:"post",configureServer(server){if(!hasPackageDependency("vinext"))return;server.middlewares.use((req,res,next)=>{if(!req.headers.accept?.includes("text/html")){next();return}const chunks=[];const end=res.end.bind(res);res.write=(chunk)=>{if(chunk)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));return true};res.end=(chunk,...args)=>{if(chunk)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));const body=normalizeVinextRscPreloadHints(Buffer.concat(chunks).toString());return end(body,...args)};next()})},generateBundle(_,bundle,_isWrite){if(!hasPackageDependency("vinext"))return;for(const chunk of Object.values(bundle)){if(!isOutputChunk(chunk))continue;if(!chunk.code.includes('case"L"'))continue;chunk.code=chunk.code.replace(/case"L":(\w+)=(\w+)\[0\],(\w+)=\2\[1\],\2\.length===3\?(\w+)\.L\(\1,\3,\2\[2\]\):\4\.L\(\1,\3\)/g,'case"L":$1=$2[0],$3=$2[1],$3==="stylesheet"&&($3="style"),$2.length===3?$4.L($1,$3,$2[2]):$4.L($1,$3)')}}},...function(){let disablePreload=false;return Object.keys(options.exposes).length>0?[{name:"module-federation-fix-preload",enforce:"post",apply:"build",config(_config,{command}){const manifest=options.manifest;const getDefaultDisableAssetsAnalyze=(cfgCommand)=>cfgCommand==="serve"&&(typeof manifest!=="object"||!Object.hasOwn(manifest,"disableAssetsAnalyze"));const getConfiguredDisableAssetsAnalyze=(cfgCommand)=>{if(typeof manifest==="object"&&manifest!==null){if(Object.hasOwn(manifest,"disableAssetsAnalyze"))return manifest.disableAssetsAnalyze===true}return getDefaultDisableAssetsAnalyze(cfgCommand)};disablePreload=getConfiguredDisableAssetsAnalyze(command)},generateBundle(_outputOptions,bundle,_isWrite){if(disablePreload)return;for(const chunk of Object.values(bundle)){if(!isOutputChunk(chunk))continue;if(!chunk.code.includes("modulepreload"))continue;const chunkDir=path$14.dirname(chunk.fileName);const prefixToRoot=chunkDir==="."?"":`${normalizePathForImport(path$14.relative(chunkDir,"."))}/`;const replacementExpr=prefixToRoot?`${escapeUnsafeJsSourceChars(JSON.stringify(prefixToRoot))}+$1`:"$1";const replacement=`=function($1){return new URL(${replacementExpr},import.meta.url).href}`;const replaced=chunk.code.replace(/=\s*\(?(\w+)(?:,\w+)?\)?\s*=>\s*[`"'][./][^`"']*[`"']\s*\+\s*\1/,replacement);if(replaced!==chunk.code){chunk.code=replaced;continue}chunk.code=chunk.code.replace(/=\s*function\((\w+)(?:,\w+)?\)\s*\{\s*return\s*[`"'][./][^`"']*[`"']\s*\+\s*\1;?\s*\}/,replacement);chunk.code=chunk.code.replace(/=function\((\w+)(?:,\w+)?\)\{return new URL\("\.\.\/"\+\1,import\.meta\.url\)\.href\}/,replacement);chunk.code=chunk.code.replace(/new URL\("\.\.\/"\+(\w+),import\.meta\.url\)\.href/g,`new URL(${replacementExpr},import.meta.url).href`)}}}]:[]}()]}import{readFileSync as readFileSync8}from"fs";import{dirname as dirname5,join as join6}from"path";import{fileURLToPath as fileURLToPath11}from"url";function exactRegex(str,flags){return new RegExp(`^${escapeRegex(str)}$`,flags)}var escapeRegexRE=/[-/\\^$*+?.()|[\]{}]/g;function escapeRegex(str){return str.replace(escapeRegexRE,"\\$&")}function makeIdFiltersToMatchWithQuery(input){if(!Array.isArray(input))return makeIdFilterToMatchWithQuery(input);return input.map((i)=>makeIdFilterToMatchWithQuery(i))}function makeIdFilterToMatchWithQuery(input){if(typeof input==="string")return`${input}{?*,}`;return makeRegexIdFilterToMatchWithQuery(input)}function makeRegexIdFilterToMatchWithQuery(input){return new RegExp(input.source.replace(/(?<!\\)\$/g,"(?:\\?.*)?$"),input.flags)}import{reactRefreshWrapperPlugin}from"vite/internal";var runtimePublicPath="/@react-refresh";var preambleCode=`import { injectIntoGlobalHook } from "__BASE__${runtimePublicPath.slice(1)}";
3242
+ Stop the shared module from statically importing another share.`);for(const[fileName,chunk]of Object.entries(bundle)){if(!isOutputChunk(chunk))continue;if(!isFederationControlChunk(fileName,filename))continue;chunk.code=sanitizeFederationControlChunk(chunk.code,fileName,filename)}const proxyChunks=collectLoadShareProxyChunks(bundle,LOAD_SHARE_TAG);if(proxyChunks.size>0){const systemProxyInfo=collectSystemProxyInfos(proxyChunks,LOAD_SHARE_TAG);for(const[fileName,chunk]of Object.entries(bundle)){if(!isOutputChunk(chunk))continue;if(proxyChunks.has(fileName))continue;let code=chunk.code;if(!fileName.includes("__loadShare__"))code=rewriteEsmProxyConsumers(code,proxyChunks);code=rewriteSystemProxyConsumers(code,systemProxyInfo);if(code!==chunk.code)chunk.code=code}}}},{name:"module-federation-strip-empty-preload-helper",enforce:"post",apply:"build",renderChunk(code,chunk){if(!isFederationControlChunk(chunk.fileName,filename))return;const nextCode=sanitizeFederationControlChunk(code,chunk.fileName,filename);return nextCode===code?null:{code:nextCode,map:null}},writeBundle(outputOptions,bundle){if(!outputOptions.dir)return;for(const chunk of Object.values(bundle)){if(!isOutputChunk(chunk))continue;if(!isFederationControlChunk(chunk.fileName,filename))continue;const outputPath=path$14.join(outputOptions.dir,chunk.fileName);writeFileSync5(outputPath,sanitizeFederationControlChunk(readFileSync6(outputPath,"utf-8"),chunk.fileName,filename))}}},{name:"module-federation-vite",enforce:"post",_options:options,config(config,{command:_command}){const isRolldown=getIsRolldown(this);isSsrBuild=_command==="build"&&Boolean(config.build?.ssr);const needsRuntimeHelpers=hasShared(options);if(needsRuntimeHelpers)appendResolveAlias(config,{find:/^@module-federation\/runtime\/helpers$/,replacement:getRuntimeHelpersImplementation(options.implementation)});appendResolveAlias(config,{find:/^@module-federation\/runtime$/,replacement:options.implementation});config.build||={};config.build.commonjsOptions||={};config.build.commonjsOptions.strictRequires??="auto";config.optimizeDeps||={};config.optimizeDeps.include||=[];config.optimizeDeps.include.push("@module-federation/runtime");if(needsRuntimeHelpers)config.optimizeDeps.include.push("@module-federation/runtime/helpers");options.runtimePlugins.forEach((p)=>{const pluginPath=getRuntimePluginSpecifier(p);if(SSR_ONLY_RUNTIME_PLUGINS.has(pluginPath))return;if(pluginPath&&!pluginPath.startsWith(".")&&!pluginPath.startsWith("/")&&!pluginPath.startsWith("\x00")&&!pluginPath.startsWith("virtual:")){let optimizeDep=pluginPath;if(pluginPath==="@module-federation/dts-plugin/dynamic-remote-type-hints-plugin")try{optimizeDep=normalizePathForImport(resolveImportPath(pluginPath))}catch{optimizeDep=pluginPath}config.optimizeDeps.include.push(optimizeDep)}});if(isRolldown){config.build??={};config.build.target??="esnext"}const isBundledDev=Boolean(config.experimental?.bundledDev);if(isRolldown&&_command==="serve"&&isBundledDev){config.build.rolldownOptions??={};config.build.rolldownOptions.experimental??={};const devMode=config.build.rolldownOptions.experimental.devMode;if(typeof devMode==="object")devMode.lazy??=false;else if(devMode===undefined)config.build.rolldownOptions.experimental.devMode={lazy:false}}const isAstro=hasPackageDependency("astro");const resolvedTarget=options.target??(config.build?.ssr?"node":"web");if(!config.define)config.define={};const userSetEnvTarget="ENV_TARGET"in config.define;applyBuildTimeRuntimeDefines(config.define,options,{target:resolvedTarget,isAstro,defaultDisableSnapshot:resolvedTarget==="node"?true:undefined});inheritedEnvTarget=userSetEnvTarget?undefined:config.define.ENV_TARGET;for(const warning of getRuntimeCapabilityConfigurationWarnings(options)){if(emittedRuntimeCapabilityWarnings.has(warning))continue;emittedRuntimeCapabilityWarnings.add(warning);mfWarn(warning)}},configResolved(config){if(!hasPackageDependency("nitro"))return;const prematureExit=config.plugins.find((plugin)=>plugin.name==="tanstack-build-exit");if(prematureExit)prematureExit.closeBundle=undefined},configEnvironment(name,config){if(!isServerEnvironment(name,config))return;const isAstro=hasPackageDependency("astro");config.define={...config.define??{}};if(inheritedEnvTarget!==undefined&&config.define.ENV_TARGET===inheritedEnvTarget)delete config.define.ENV_TARGET;applyBuildTimeRuntimeDefines(config.define,options,{target:options.target??"node",isAstro,defaultDisableSnapshot:true})}},...Manifest(options),...pluginSSRRemoteEntry(options),...VarRemoteEntry(options),{name:"module-federation-vinext-fix-rsc-preload-as",enforce:"post",configureServer(server){if(!hasPackageDependency("vinext"))return;server.middlewares.use((req,res,next)=>{if(!req.headers.accept?.includes("text/html")){next();return}const chunks=[];const end=res.end.bind(res);res.write=(chunk)=>{if(chunk)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));return true};res.end=(chunk,...args)=>{if(chunk)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));const body=normalizeVinextRscPreloadHints(Buffer.concat(chunks).toString());return end(body,...args)};next()})},generateBundle(_,bundle,_isWrite){if(!hasPackageDependency("vinext"))return;for(const chunk of Object.values(bundle)){if(!isOutputChunk(chunk))continue;if(!chunk.code.includes('case"L"'))continue;chunk.code=chunk.code.replace(/case"L":(\w+)=(\w+)\[0\],(\w+)=\2\[1\],\2\.length===3\?(\w+)\.L\(\1,\3,\2\[2\]\):\4\.L\(\1,\3\)/g,'case"L":$1=$2[0],$3=$2[1],$3==="stylesheet"&&($3="style"),$2.length===3?$4.L($1,$3,$2[2]):$4.L($1,$3)')}}},...function(){let disablePreload=false;return Object.keys(options.exposes).length>0?[{name:"module-federation-fix-preload",enforce:"post",apply:"build",config(_config,{command}){const manifest=options.manifest;const getDefaultDisableAssetsAnalyze=(cfgCommand)=>cfgCommand==="serve"&&(typeof manifest!=="object"||!Object.hasOwn(manifest,"disableAssetsAnalyze"));const getConfiguredDisableAssetsAnalyze=(cfgCommand)=>{if(typeof manifest==="object"&&manifest!==null){if(Object.hasOwn(manifest,"disableAssetsAnalyze"))return manifest.disableAssetsAnalyze===true}return getDefaultDisableAssetsAnalyze(cfgCommand)};disablePreload=getConfiguredDisableAssetsAnalyze(command)},generateBundle(_outputOptions,bundle,_isWrite){if(disablePreload)return;for(const chunk of Object.values(bundle)){if(!isOutputChunk(chunk))continue;if(!chunk.code.includes("modulepreload"))continue;const chunkDir=path$14.dirname(chunk.fileName);const prefixToRoot=chunkDir==="."?"":`${normalizePathForImport(path$14.relative(chunkDir,"."))}/`;const replacementExpr=prefixToRoot?`${escapeUnsafeJsSourceChars(JSON.stringify(prefixToRoot))}+$1`:"$1";const replacement=`=function($1){return new URL(${replacementExpr},import.meta.url).href}`;const replaced=chunk.code.replace(/=\s*\(?(\w+)(?:,\w+)?\)?\s*=>\s*[`"'][./][^`"']*[`"']\s*\+\s*\1/,replacement);if(replaced!==chunk.code){chunk.code=replaced;continue}chunk.code=chunk.code.replace(/=\s*function\((\w+)(?:,\w+)?\)\s*\{\s*return\s*[`"'][./][^`"']*[`"']\s*\+\s*\1;?\s*\}/,replacement);chunk.code=chunk.code.replace(/=function\((\w+)(?:,\w+)?\)\{return new URL\("\.\.\/"\+\1,import\.meta\.url\)\.href\}/,replacement);chunk.code=chunk.code.replace(/new URL\("\.\.\/"\+(\w+),import\.meta\.url\)\.href/g,`new URL(${replacementExpr},import.meta.url).href`)}}}]:[]}()]}import{readFileSync as readFileSync8}from"fs";import{dirname as dirname5,join as join7}from"path";import{fileURLToPath as fileURLToPath11}from"url";function exactRegex(str,flags){return new RegExp(`^${escapeRegex(str)}$`,flags)}var escapeRegexRE=/[-/\\^$*+?.()|[\]{}]/g;function escapeRegex(str){return str.replace(escapeRegexRE,"\\$&")}function makeIdFiltersToMatchWithQuery(input){if(!Array.isArray(input))return makeIdFilterToMatchWithQuery(input);return input.map((i)=>makeIdFilterToMatchWithQuery(i))}function makeIdFilterToMatchWithQuery(input){if(typeof input==="string")return`${input}{?*,}`;return makeRegexIdFilterToMatchWithQuery(input)}function makeRegexIdFilterToMatchWithQuery(input){return new RegExp(input.source.replace(/(?<!\\)\$/g,"(?:\\?.*)?$"),input.flags)}import{reactRefreshWrapperPlugin}from"vite/internal";var runtimePublicPath="/@react-refresh";var preambleCode=`import { injectIntoGlobalHook } from "__BASE__${runtimePublicPath.slice(1)}";
3243
3243
  injectIntoGlobalHook(window);
3244
3244
  window.$RefreshReg$ = () => {};
3245
- 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 readFileSync8(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 path12=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)=>`
3245
+ 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=join7(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 readFileSync8(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 path12=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)=>`
3246
3246
  import * as loaded from ${JSON.stringify(input.contributionImport)}
3247
3247
  export const ${moduleExport3(input.exportName)} = loaded[${JSON.stringify(input.exportName)}]
3248
- `;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=path12.isAbsolute(declarationPath)?path12.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:String5}){}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(flatMap4((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 createHash8}from"crypto";var awaitValue7=(value)=>promise2(constant(Promise.resolve(value)));var path13=runSync2(provide3(Path2,layer5));var readBytesEffect=(readBytes,filePath)=>tryPromise2(flow(()=>suspend2(()=>awaitValue7(readBytes(filePath))),runPromise2));class PackageReleaseCommandError extends TaggedError3()("PackageReleaseCommandError",{cause:optional2(Unknown2),message:String5}){}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)=>createHash8("sha256").update(bytes).digest("hex");var rejectInputs=(message)=>{throw new PackageReleaseCommandError({message})};var readInputs2=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"):path13.join(path13.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,path13.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 readInputs2(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 readInputs2(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:String5}){}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 path14 from"path";class UpgradeCommandError extends TaggedError3()("UpgradeCommandError",{cause:optional2(Unknown2),message:String5}){}var registryUrl="https://registry.npmjs.org";var registryTimeout="30 seconds";var RegistryVersion=Struct({version:String5});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}`}))}),flatMap4((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(path14.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
3248
+ `;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=path12.isAbsolute(declarationPath)?path12.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:String5}){}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(flatMap4((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 createHash8}from"crypto";var awaitValue7=(value)=>promise2(constant(Promise.resolve(value)));var path13=runSync2(provide3(Path2,layer5));var readBytesEffect=(readBytes,filePath)=>tryPromise2(flow(()=>suspend2(()=>awaitValue7(readBytes(filePath))),runPromise2));class PackageReleaseCommandError extends TaggedError3()("PackageReleaseCommandError",{cause:optional2(Unknown2),message:String5}){}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)=>createHash8("sha256").update(bytes).digest("hex");var rejectInputs=(message)=>{throw new PackageReleaseCommandError({message})};var readInputs2=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"):path13.join(path13.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,path13.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 readInputs2(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 readInputs2(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:String5}){}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{mkdir as mkdir4,readdir as readdir3,readFile as readFile6,rename as rename3,rm as rm3,stat as stat4}from"fs/promises";import path14 from"path";var portablePath=(value)=>value.split(path14.sep).join("/");var bunTransferFiles={kind:async(target)=>{try{const found=await stat4(target);return found.isDirectory()?"directory":"file"}catch{return null}},list:async(folder)=>{const entries=await readdir3(folder,{recursive:true,withFileTypes:true});return await Promise.all(entries.filter((entry)=>entry.isFile()).map(async(entry)=>{const file=path14.join(entry.parentPath,entry.name);const found=await stat4(file);return{path:portablePath(path14.relative(folder,file)),size:found.size}}))},openRead:(file)=>Bun.file(file).stream(),readText:async(file)=>await readFile6(file,"utf-8"),seekable:(file)=>Bun.file(file),writeStream:async(file,stream)=>{const partial=`${file}.partial`;await mkdir4(path14.dirname(file),{recursive:true});try{await Bun.write(partial,new Response(stream));await rename3(partial,file)}catch(error){await rm3(partial,{force:true});throw error}}};var messageOf2=(failure)=>{switch(failure.code){case"archive_zip_limit":{return`Cannot add ${failure.path} to the zip: a zip holds at most 4 GiB and 65535 files. Export to a folder instead.`}case"size_mismatch":{return`Archive file ${failure.path} has ${failure.actual} bytes, expected ${failure.expected}`}case"zip_manifest_missing":{return"The zip has no manifest.json"}case"manifest_invalid":{return"manifest.json is not a readable archive manifest"}case"zip_incomplete":{return`The zip lacks ${failure.missing.length} files that the manifest lists`}case"zip_malformed":{return`The zip cannot be read: ${failure.reason}`}case"download_failed":{return`Download of archive file ${failure.path} failed with HTTP ${failure.status}`}case"upload_failed":{return`Upload of archive file ${failure.path} failed with HTTP ${failure.status}`}case"run_event_invalid":{return"The transfer stream sent a frame that is not a run event"}case"preview_failed":{return`The export preview did not finish: the run is ${failure.status}`}default:{return failure}}};class TransferClientError extends Error{name="TransferClientError";failure;constructor(failure,options){super(messageOf2(failure),options);this.failure=failure}}var organizationHeaders=(scope)=>({"x-organization-id":scope.organizationId});var DEFAULT_RUN_LIMIT=50;var startTransferExport=async(scope,request)=>{const{data}=await organizationTransferExports({body:request,headers:organizationHeaders(scope),throwOnError:true});return data};var startTransferImport=async(scope,request)=>{const{data}=await organizationTransferImports({body:request,headers:organizationHeaders(scope),throwOnError:true});return data};var startTransferRollback=async(scope,request)=>{const{data}=await organizationTransferRollbacks({body:request,headers:organizationHeaders(scope),throwOnError:true});return data};var listTransferRuns=async(scope,options={})=>{const{data}=await organizationTransferRuns({headers:organizationHeaders(scope),query:{limit:String(options.limit??DEFAULT_RUN_LIMIT)},throwOnError:true});return data};var getTransferRun=async(scope,runId)=>{const{data,error,response}=await organizationTransferRun({headers:organizationHeaders(scope),path:{runId}});if(response.status===404){return}if(error!==undefined){throw error}return data};var cancelTransferRun=async(scope,runId)=>{const{data}=await organizationTransferCancel({headers:organizationHeaders(scope),path:{runId},throwOnError:true});return data};var resumeTransferRun=async(scope,runId)=>{const{data}=await organizationTransferResume({headers:organizationHeaders(scope),path:{runId},throwOnError:true});return data};var purgeTransferRun=async(scope,runId)=>{await organizationTransferPurge({headers:organizationHeaders(scope),path:{runId},throwOnError:true})};var getTransferRunReport=async(scope,runId)=>{const{data}=await organizationTransferReport({headers:organizationHeaders(scope),path:{runId},throwOnError:true});return data};var requestTransferDownloadUrls=async(input)=>{const{data}=await organizationTransferDownloadUrls({headers:organizationHeaders(input),path:{archiveId:input.archiveId},...input.signal===undefined?undefined:{signal:input.signal},throwOnError:true});return data.files};var inPairs=(paths)=>Array.from({length:Math.ceil(paths.length/2)},(_,index)=>{const first=paths[index*2]??"";return[first,paths.at(index*2+1)??first]});var requestTransferUploadUrls=async(input)=>{const answers=await Promise.all(inPairs(input.paths).map(async(paths)=>{const{data}=await organizationTransferUploadUrls({body:{paths},headers:organizationHeaders(input),path:{archiveId:input.archiveId},...input.signal===undefined?undefined:{signal:input.signal},throwOnError:true});return data.urls}));return answers.flat()};var transferRunPlan=(run)=>run.counts.plan;var importApplyRequest=(input)=>{const request={archiveId:input.plan.archiveId,mode:"apply",planRunId:input.planRunId};if(input.confirmReplace!==undefined){request.confirmReplace=input.confirmReplace}if(input.plan.options!==undefined){request.options=input.plan.options}return request};var isTransferRunActive=(run)=>run.status==="queued"||run.status==="running";var PREVIEW_POLL_MS=500;var PREVIEW_MAX_POLL_MS=5000;var wait=async(ms,signal)=>{signal?.throwIfAborted();await new Promise((resolve,reject)=>{const settled=new AbortController;const timer=globalThis.setTimeout(()=>{settled.abort();resolve()},ms);signal?.addEventListener("abort",()=>{globalThis.clearTimeout(timer);reject(signal.reason)},{once:true,signal:settled.signal})})};var previewTransferExport=async(scope,request,options={})=>{const{data:accepted}=await organizationTransferPreview({body:request,headers:organizationHeaders(scope),throwOnError:true});let run=accepted;let delay=options.pollIntervalMs??PREVIEW_POLL_MS;while(run!==undefined&&isTransferRunActive(run)){await wait(delay,options.signal);delay=Math.min(delay*2,PREVIEW_MAX_POLL_MS);run=await getTransferRun(scope,accepted.id)}const preview=run?.counts.preview;if(run?.status!=="completed"||preview===undefined){throw new TransferClientError({code:"preview_failed",status:run?.status??"missing"})}return preview};import{createRequire as createRequire4}from"module";var require2=createRequire4("/");var _a;var Worker;var isMarkedAsUntransferable;try{_a=require2("worker_threads"),Worker=_a.Worker,isMarkedAsUntransferable=_a.isMarkedAsUntransferable}catch(e){}var u8=Uint8Array;var u16=Uint16Array;var i32=Int32Array;var fleb=new u8([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]);var fdeb=new u8([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]);var clim=new u8([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);var freb=function(eb,start){var b=new u16(31);for(var i=0;i<31;++i){b[i]=start+=1<<eb[i-1]}var r=new i32(b[30]);for(var i=1;i<30;++i){for(var j=b[i];j<b[i+1];++j){r[j]=j-b[i]<<5|i}}return{b,r}};var _a=freb(fleb,2);var fl=_a.b;var revfl=_a.r;fl[28]=258,revfl[258]=28;var _b=freb(fdeb,0);var fd=_b.b;var revfd=_b.r;var rev=new u16(32768);for(i2=0;i2<32768;++i2){x=(i2&43690)>>1|(i2&21845)<<1;x=(x&52428)>>2|(x&13107)<<2;x=(x&61680)>>4|(x&3855)<<4;rev[i2]=((x&65280)>>8|(x&255)<<8)>>1}var x;var i2;var hMap=function(cd,mb,r){var s=cd.length;var i=0;var l=new u16(mb);for(;i<s;++i){if(cd[i])++l[cd[i]-1]}var le=new u16(mb);for(i=1;i<mb;++i){le[i]=le[i-1]+l[i-1]<<1}var co;if(r){co=new u16(1<<mb);var rvb=15-mb;for(i=0;i<s;++i){if(cd[i]){var sv=i<<4|cd[i];var r_1=mb-cd[i];var v=le[cd[i]-1]++<<r_1;for(var m=v|(1<<r_1)-1;v<=m;++v){co[rev[v]>>rvb]=sv}}}}else{co=new u16(s);for(i=0;i<s;++i){if(cd[i]){co[i]=rev[le[cd[i]-1]++]>>15-cd[i]}}}return co};var flt=new u8(288);for(i2=0;i2<144;++i2)flt[i2]=8;var i2;for(i2=144;i2<256;++i2)flt[i2]=9;var i2;for(i2=256;i2<280;++i2)flt[i2]=7;var i2;for(i2=280;i2<288;++i2)flt[i2]=8;var i2;var fdt=new u8(32);for(i2=0;i2<32;++i2)fdt[i2]=5;var i2;var flm=hMap(flt,9,0);var flrm=hMap(flt,9,1);var fdm=hMap(fdt,5,0);var fdrm=hMap(fdt,5,1);var max=function(a){var m=a[0];for(var i=1;i<a.length;++i){if(a[i]>m)m=a[i]}return m};var bits=function(d,p,m){var o=p/8|0;return(d[o]|d[o+1]<<8)>>(p&7)&m};var bits16=function(d,p){var o=p/8|0;return(d[o]|d[o+1]<<8|d[o+2]<<16)>>(p&7)};var shft=function(p){return(p+7)/8|0};var slc=function(v,s,e){if(s==null||s<0)s=0;if(e==null||e>v.length)e=v.length;return new u8(v.subarray(s,e))};var ec=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"];var err=function(ind,msg,nt){var e=new Error(msg||ec[ind]);e.code=ind;if(Error.captureStackTrace)Error.captureStackTrace(e,err);if(!nt)throw e;return e};var inflt=function(dat,st,buf,dict){var sl=dat.length,dl=dict?dict.length:0;if(!sl||st.f&&!st.l)return buf||new u8(0);var noBuf=!buf;var resize=noBuf||st.i!=2;var noSt=st.i;if(noBuf)buf=new u8(sl*3);var cbuf=function(l){var bl=buf.length;if(l>bl){var nbuf=new u8(Math.max(bl*2,l));nbuf.set(buf);buf=nbuf}};var final=st.f||0,pos=st.p||0,bt=st.b||0,{l:lm,d:dm,m:lbt,n:dbt}=st;var tbts=sl*8;do{if(!lm){final=bits(dat,pos,1);var type=bits(dat,pos+1,3);pos+=3;if(!type){var s=shft(pos)+4,l=dat[s-4]|dat[s-3]<<8,t=s+l;if(t>sl){if(noSt)err(0);break}if(resize)cbuf(bt+l);buf.set(dat.subarray(s,t),bt);st.b=bt+=l,st.p=pos=t*8,st.f=final;continue}else if(type==1)lm=flrm,dm=fdrm,lbt=9,dbt=5;else if(type==2){var hLit=bits(dat,pos,31)+257,hcLen=bits(dat,pos+10,15)+4;var tl=hLit+bits(dat,pos+5,31)+1;pos+=14;var ldt=new u8(tl);var clt=new u8(19);for(var i=0;i<hcLen;++i){clt[clim[i]]=bits(dat,pos+i*3,7)}pos+=hcLen*3;var clb=max(clt),clbmsk=(1<<clb)-1;var clm=hMap(clt,clb,1);for(var i=0;i<tl;){var r=clm[bits(dat,pos,clbmsk)];pos+=r&15;var s=r>>4;if(s<16){ldt[i++]=s}else{var c=0,n=0;if(s==16)n=3+bits(dat,pos,3),pos+=2,c=ldt[i-1];else if(s==17)n=3+bits(dat,pos,7),pos+=3;else if(s==18)n=11+bits(dat,pos,127),pos+=7;while(n--)ldt[i++]=c}}var lt=ldt.subarray(0,hLit),dt=ldt.subarray(hLit);lbt=max(lt);dbt=max(dt);lm=hMap(lt,lbt,1);dm=hMap(dt,dbt,1)}else err(1);if(pos>tbts){if(noSt)err(0);break}}if(resize)cbuf(bt+131072);var lms=(1<<lbt)-1,dms=(1<<dbt)-1;var lpos=pos;for(;;lpos=pos){var c=lm[bits16(dat,pos)&lms],sym=c>>4;pos+=c&15;if(pos>tbts){if(noSt)err(0);break}if(!c)err(2);if(sym<256)buf[bt++]=sym;else if(sym==256){lpos=pos,lm=null;break}else{var add=sym-254;if(sym>264){var i=sym-257,b=fleb[i];add=bits(dat,pos,(1<<b)-1)+fl[i];pos+=b}var d=dm[bits16(dat,pos)&dms],dsym=d>>4;if(!d)err(3);pos+=d&15;var dt=fd[dsym];if(dsym>3){var b=fdeb[dsym];dt+=bits16(dat,pos)&(1<<b)-1,pos+=b}if(pos>tbts){if(noSt)err(0);break}if(resize)cbuf(bt+131072);var end=bt+add;if(bt<dt){var shift=dl-dt,dend=Math.min(dt,end);if(shift+bt<0)err(3);for(;bt<dend;++bt)buf[bt]=dict[shift+bt]}for(;bt<end;++bt)buf[bt]=buf[bt-dt]}}st.l=lm,st.p=lpos,st.b=bt,st.f=final;if(lm)final=1,st.m=lbt,st.d=dm,st.n=dbt}while(!final);return bt!=buf.length&&noBuf?slc(buf,0,bt):buf.subarray(0,bt)};var wbits=function(d,p,v){v<<=p&7;var o=p/8|0;d[o]|=v;d[o+1]|=v>>8};var wbits16=function(d,p,v){v<<=p&7;var o=p/8|0;d[o]|=v;d[o+1]|=v>>8;d[o+2]|=v>>16};var hTree=function(d,mb){var t=[];for(var i=0;i<d.length;++i){if(d[i])t.push({s:i,f:d[i]})}var s=t.length;var t2=t.slice();if(!s)return{t:et,l:0};if(s==1){var v=new u8(t[0].s+1);v[t[0].s]=1;return{t:v,l:1}}t.sort(function(a,b){return a.f-b.f});t.push({s:-1,f:25001});var l=t[0],r=t[1],i0=0,i1=1,i2=2;t[0]={s:-1,f:l.f+r.f,l,r};while(i1!=s-1){l=t[t[i0].f<t[i2].f?i0++:i2++];r=t[i0!=i1&&t[i0].f<t[i2].f?i0++:i2++];t[i1++]={s:-1,f:l.f+r.f,l,r}}var maxSym=t2[0].s;for(var i=1;i<s;++i){if(t2[i].s>maxSym)maxSym=t2[i].s}var tr=new u16(maxSym+1);var mbt=ln(t[i1-1],tr,0);if(mbt>mb){var i=0,dt=0;var lft=mbt-mb,cst=1<<lft;t2.sort(function(a,b){return tr[b.s]-tr[a.s]||a.f-b.f});for(;i<s;++i){var i2_1=t2[i].s;if(tr[i2_1]>mb){dt+=cst-(1<<mbt-tr[i2_1]);tr[i2_1]=mb}else break}dt>>=lft;while(dt>0){var i2_2=t2[i].s;if(tr[i2_2]<mb)dt-=1<<mb-tr[i2_2]++-1;else++i}for(;i>=0&&dt;--i){var i2_3=t2[i].s;if(tr[i2_3]==mb){--tr[i2_3];++dt}}mbt=mb}return{t:new u8(tr),l:mbt}};var ln=function(n,l,d){return n.s==-1?Math.max(ln(n.l,l,d+1),ln(n.r,l,d+1)):l[n.s]=d};var lc=function(c){var s=c.length;while(s&&!c[--s]);var cl=new u16(++s);var cli=0,cln=c[0],cls=1;var w=function(v){cl[cli++]=v};for(var i=1;i<=s;++i){if(c[i]==cln&&i!=s)++cls;else{if(!cln&&cls>2){for(;cls>138;cls-=138)w(32754);if(cls>2){w(cls>10?cls-11<<5|28690:cls-3<<5|12305);cls=0}}else if(cls>3){w(cln),--cls;for(;cls>6;cls-=6)w(8304);if(cls>2)w(cls-3<<5|8208),cls=0}while(cls--)w(cln);cls=1;cln=c[i]}}return{c:cl.subarray(0,cli),n:s}};var clen=function(cf,cl){var l=0;for(var i=0;i<cl.length;++i)l+=cf[i]*cl[i];return l};var wfblk=function(out,pos,dat){var s=dat.length;var o=shft(pos+2);out[o]=s&255;out[o+1]=s>>8;out[o+2]=out[o]^255;out[o+3]=out[o+1]^255;for(var i=0;i<s;++i)out[o+i+4]=dat[i];return(o+4+s)*8};var wblk=function(dat,out,final,syms,lf,df,eb,li,bs,bl,p){wbits(out,p++,final);++lf[256];var _a=hTree(lf,15),{t:dlt,l:mlb}=_a;var _b=hTree(df,15),{t:ddt,l:mdb}=_b;var _c=lc(dlt),{c:lclt,n:nlc}=_c;var _d=lc(ddt),{c:lcdt,n:ndc}=_d;var lcfreq=new u16(19);for(var i=0;i<lclt.length;++i)++lcfreq[lclt[i]&31];for(var i=0;i<lcdt.length;++i)++lcfreq[lcdt[i]&31];var _e=hTree(lcfreq,7),{t:lct,l:mlcb}=_e;var nlcc=19;for(;nlcc>4&&!lct[clim[nlcc-1]];--nlcc);var flen=bl+5<<3;var ftlen=clen(lf,flt)+clen(df,fdt)+eb;var dtlen=clen(lf,dlt)+clen(df,ddt)+eb+14+3*nlcc+clen(lcfreq,lct)+2*lcfreq[16]+3*lcfreq[17]+7*lcfreq[18];if(bs>=0&&flen<=ftlen&&flen<=dtlen)return wfblk(out,p,dat.subarray(bs,bs+bl));var lm,ll,dm,dl;wbits(out,p,1+(dtlen<ftlen)),p+=2;if(dtlen<ftlen){lm=hMap(dlt,mlb,0),ll=dlt,dm=hMap(ddt,mdb,0),dl=ddt;var llm=hMap(lct,mlcb,0);wbits(out,p,nlc-257);wbits(out,p+5,ndc-1);wbits(out,p+10,nlcc-4);p+=14;for(var i=0;i<nlcc;++i)wbits(out,p+3*i,lct[clim[i]]);p+=3*nlcc;var lcts=[lclt,lcdt];for(var it=0;it<2;++it){var clct=lcts[it];for(var i=0;i<clct.length;++i){var len=clct[i]&31;wbits(out,p,llm[len]),p+=lct[len];if(len>15)wbits(out,p,clct[i]>>5&127),p+=clct[i]>>12}}}else{lm=flm,ll=flt,dm=fdm,dl=fdt}for(var i=0;i<li;++i){var sym=syms[i];if(sym>255){var len=sym>>18&31;wbits16(out,p,lm[len+257]),p+=ll[len+257];if(len>7)wbits(out,p,sym>>23&31),p+=fleb[len];var dst=sym&31;wbits16(out,p,dm[dst]),p+=dl[dst];if(dst>3)wbits16(out,p,sym>>5&8191),p+=fdeb[dst]}else{wbits16(out,p,lm[sym]),p+=ll[sym]}}wbits16(out,p,lm[256]);return p+ll[256]};var deo=new i32([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]);var et=new u8(0);var dflt=function(dat,lvl,plvl,pre,post,st){var s=st.z||dat.length;var o=new u8(pre+s+5*(1+Math.ceil(s/7000))+post);var w=o.subarray(pre,o.length-post);var lst=st.l;var pos=(st.r||0)&7;if(lvl){if(pos)w[0]=st.r>>3;var opt=deo[lvl-1];var n=opt>>13,c=opt&8191;var msk_1=(1<<plvl)-1;var prev=st.p||new u16(32768),head=st.h||new u16(msk_1+1);var bs1_1=Math.ceil(plvl/3),bs2_1=2*bs1_1;var hsh=function(i){return(dat[i]^dat[i+1]<<bs1_1^dat[i+2]<<bs2_1)&msk_1};var syms=new i32(25000);var lf=new u16(288),df=new u16(32);var lc_1=0,eb=0,i=st.i||0,li=0,wi=st.w||0,bs=0;for(;i+2<s;++i){var hv=hsh(i);var imod=i&32767,pimod=head[hv];prev[imod]=pimod;head[hv]=imod;if(wi<=i){var rem=s-i;if((lc_1>7000||li>24576)&&(rem>423||!lst)){pos=wblk(dat,w,0,syms,lf,df,eb,li,bs,i-bs,pos);li=lc_1=eb=0,bs=i;for(var j=0;j<286;++j)lf[j]=0;for(var j=0;j<30;++j)df[j]=0}var l=2,d=0,ch_1=c,dif=imod-pimod&32767;if(rem>2&&hv==hsh(i-dif)){var maxn=Math.min(n,rem)-1;var maxd=Math.min(32767,i);var ml=Math.min(258,rem);while(dif<=maxd&&--ch_1&&imod!=pimod){if(dat[i+l]==dat[i+l-dif]){var nl=0;for(;nl<ml&&dat[i+nl]==dat[i+nl-dif];++nl);if(nl>l){l=nl,d=dif;if(nl>maxn)break;var mmd=Math.min(dif,nl-2);var md=0;for(var j=0;j<mmd;++j){var ti=i-dif+j&32767;var pti=prev[ti];var cd=ti-pti&32767;if(cd>md)md=cd,pimod=ti}}}imod=pimod,pimod=prev[imod];dif+=imod-pimod&32767}}if(d){syms[li++]=268435456|revfl[l]<<18|revfd[d];var lin=revfl[l]&31,din=revfd[d]&31;eb+=fleb[lin]+fdeb[din];++lf[257+lin];++df[din];wi=i+l;++lc_1}else{syms[li++]=dat[i];++lf[dat[i]]}}}for(i=Math.max(i,wi);i<s;++i){syms[li++]=dat[i];++lf[dat[i]]}pos=wblk(dat,w,lst,syms,lf,df,eb,li,bs,i-bs,pos);if(!lst){st.r=pos&7|w[pos/8|0]<<3;pos-=7;st.h=head,st.p=prev,st.i=i,st.w=wi}}else{for(var i=st.w||0;i<s+lst;i+=65535){var e=i+65535;if(e>=s){w[pos/8|0]=lst;e=s}pos=wfblk(w,pos+1,dat.subarray(i,e))}st.i=s}return slc(o,0,pre+shft(pos)+post)};var crct=function(){var t=new Int32Array(256);for(var i=0;i<256;++i){var c=i,k=9;while(--k)c=(c&1&&-306674912)^c>>>1;t[i]=c}return t}();var crc=function(){var c=-1;return{p:function(d){var cr=c;for(var i=0;i<d.length;++i)cr=crct[cr&255^d[i]]^cr>>>8;c=cr},d:function(){return~c}}};var dopt=function(dat,opt,pre,post,st){if(!st){st={l:1};if(opt.dictionary){var dict=opt.dictionary.subarray(-32768);var newDat=new u8(dict.length+dat.length);newDat.set(dict);newDat.set(dat,dict.length);dat=newDat;st.w=dict.length}}return dflt(dat,opt.level==null?6:opt.level,opt.mem==null?st.l?Math.ceil(Math.max(8,Math.min(13,Math.log(dat.length)))*1.5):20:12+opt.mem,pre,post,st)};var mrg=function(a,b){var o={};for(var k in a)o[k]=a[k];for(var k in b)o[k]=b[k];return o};var wbytes=function(d,b,v){for(;v;++b)d[b]=v,v>>>=8};var Deflate=function(){function Deflate(opts,cb){if(typeof opts=="function")cb=opts,opts={};this.ondata=cb;this.o=opts||{};this.s={l:0,i:32768,w:32768,z:32768};this.b=new u8(98304);if(this.o.dictionary){var dict=this.o.dictionary.subarray(-32768);this.b.set(dict,32768-dict.length);this.s.i=32768-dict.length}}Deflate.prototype.p=function(c,f){this.ondata(dopt(c,this.o,0,0,this.s),f)};Deflate.prototype.push=function(chunk,final){if(!this.ondata)err(5);if(this.s.l)err(4);var endLen=chunk.length+this.s.z;if(endLen>this.b.length){if(endLen>2*this.b.length-32768){var newBuf=new u8(endLen&-32768);newBuf.set(this.b.subarray(0,this.s.z));this.b=newBuf}var split=this.b.length-this.s.z;this.b.set(chunk.subarray(0,split),this.s.z);this.s.z=this.b.length;this.p(this.b,false);this.b.set(this.b.subarray(-32768));this.b.set(chunk.subarray(split),32768);this.s.z=chunk.length-split+32768;this.s.i=32766,this.s.w=32768}else{this.b.set(chunk,this.s.z);this.s.z+=chunk.length}this.s.l=final&1;if(this.s.z>this.s.w+8191||final){this.p(this.b,final||false);this.s.w=this.s.i,this.s.i-=2}if(final){this.s=this.o={};this.b=et}};Deflate.prototype.flush=function(sync){if(!this.ondata)err(5);if(this.s.l)err(4);this.p(this.b,false);this.s.w=this.s.i,this.s.i-=2;if(sync){var c=new u8(6);c[0]=this.s.r>>3;var ep=wfblk(c,this.s.r,et);this.s.r=0;this.ondata(c.subarray(0,ep>>3),false)}};return Deflate}();var Inflate=function(){function Inflate(opts,cb){if(typeof opts=="function")cb=opts,opts={};this.ondata=cb;var dict=opts&&opts.dictionary&&opts.dictionary.subarray(-32768);this.s={i:0,b:dict?dict.length:0};this.o=new u8(32768);this.p=new u8(0);if(dict)this.o.set(dict)}Inflate.prototype.e=function(c){if(!this.ondata)err(5);if(this.d)err(4);if(!this.p.length)this.p=c;else if(c.length){var n=new u8(this.p.length+c.length);n.set(this.p),n.set(c,this.p.length),this.p=n}};Inflate.prototype.c=function(final){this.s.i=+(this.d=final||false);var bts=this.s.b;var dt=inflt(this.p,this.s,this.o);this.ondata(slc(dt,bts,this.s.b),this.d);this.o=slc(dt,this.s.b-32768),this.s.b=this.o.length;this.p=slc(this.p,this.s.p/8|0),this.s.p&=7};Inflate.prototype.push=function(chunk,final){this.e(chunk),this.c(final)};return Inflate}();var te=typeof TextEncoder!="undefined"&&new TextEncoder;var td2=typeof TextDecoder!="undefined"&&new TextDecoder;var tds=0;try{td2.decode(et,{stream:true});tds=1}catch(e){}function strToU8(str,latin1){if(latin1){var ar_1=new u8(str.length);for(var i=0;i<str.length;++i)ar_1[i]=str.charCodeAt(i);return ar_1}if(te)return te.encode(str);var l=str.length;var ar=new u8(str.length+(str.length>>1));var ai=0;var w=function(v){ar[ai++]=v};for(var i=0;i<l;++i){if(ai+5>ar.length){var n=new u8(ai+8+(l-i<<1));n.set(ar);ar=n}var c=str.charCodeAt(i);if(c<128||latin1)w(c);else if(c<2048)w(192|c>>6),w(128|c&63);else if(c>55295&&c<57344)c=65536+(c&1023<<10)|str.charCodeAt(++i)&1023,w(240|c>>18),w(128|c>>12&63),w(128|c>>6&63),w(128|c&63);else w(224|c>>12),w(128|c>>6&63),w(128|c&63)}return slc(ar,0,ai)}var dbf=function(l){return l==1?3:l<6?2:l==9?1:0};var exfl=function(ex){var le=0;if(ex){for(var k in ex){var l=ex[k].length;if(l>65535)err(9);le+=l+4}}return le};var wzh=function(d,b,f,fn,u,c,ce,co){var fl=fn.length,ex=f.extra,col=co&&co.length;var exl=exfl(ex);wbytes(d,b,ce!=null?33639248:67324752),b+=4;if(ce!=null)d[b++]=20,d[b++]=f.os;d[b]=20,b+=2;d[b++]=f.flag<<1|(c<0&&8),d[b++]=u&&8;d[b++]=f.compression&255,d[b++]=f.compression>>8;var dt=new Date(f.mtime==null?Date.now():f.mtime),y=dt.getFullYear()-1980;if(y<0||y>119)err(10);wbytes(d,b,y<<25|dt.getMonth()+1<<21|dt.getDate()<<16|dt.getHours()<<11|dt.getMinutes()<<5|dt.getSeconds()>>1),b+=4;if(c!=-1){wbytes(d,b,f.crc);wbytes(d,b+4,c<0?-c-2:c);wbytes(d,b+8,f.size)}wbytes(d,b+12,fl);wbytes(d,b+14,exl),b+=16;if(ce!=null){wbytes(d,b,col);wbytes(d,b+6,f.attrs);wbytes(d,b+10,ce),b+=14}d.set(fn,b);b+=fl;if(exl){for(var k in ex){var exf=ex[k],l=exf.length;wbytes(d,b,+k);wbytes(d,b+2,l);d.set(exf,b+4),b+=4+l}}if(col)d.set(co,b),b+=col;return b};var wzf=function(o,b,c,d,e){wbytes(o,b,101010256);wbytes(o,b+8,c);wbytes(o,b+10,c);wbytes(o,b+12,d);wbytes(o,b+16,e)};var ZipPassThrough=function(){function ZipPassThrough(filename){this.filename=filename;this.c=crc();this.size=0;this.compression=0}ZipPassThrough.prototype.process=function(chunk,final){this.ondata(null,chunk,final)};ZipPassThrough.prototype.push=function(chunk,final){if(!this.ondata)err(5);this.c.p(chunk);this.size+=chunk.length;if(final)this.crc=this.c.d();this.process(chunk,final||false)};return ZipPassThrough}();var ZipDeflate=function(){function ZipDeflate(filename,opts){var _this=this;if(!opts)opts={};ZipPassThrough.call(this,filename);this.d=new Deflate(opts,function(dat,final){_this.ondata(null,dat,final)});this.compression=8;this.flag=dbf(opts.level)}ZipDeflate.prototype.process=function(chunk,final){try{this.d.push(chunk,final)}catch(e){this.ondata(e,null,final)}};ZipDeflate.prototype.push=function(chunk,final){ZipPassThrough.prototype.push.call(this,chunk,final)};return ZipDeflate}();var Zip=function(){function Zip(cb){this.ondata=cb;this.u=[];this.d=1}Zip.prototype.add=function(file){var _this=this;if(!this.ondata)err(5);if(this.d&2)this.ondata(err(4+(this.d&1)*8,0,1),null,false);else{var f=strToU8(file.filename),fl_1=f.length;var com=file.comment,o=com&&strToU8(com);var u=fl_1!=file.filename.length||o&&com.length!=o.length;var hl_1=fl_1+exfl(file.extra)+30;if(fl_1>65535)this.ondata(err(11,0,1),null,false);var header=new u8(hl_1);wzh(header,0,file,f,u,-1);var chks_1=[header];var pAll_1=function(){for(var _i=0,chks_2=chks_1;_i<chks_2.length;_i++){var chk=chks_2[_i];_this.ondata(null,chk,false)}chks_1=[]};var tr_1=this.d;this.d=0;var ind_1=this.u.length;var uf_1=mrg(file,{f,u,o,t:function(){if(file.terminate)file.terminate()},r:function(){pAll_1();if(tr_1){var nxt=_this.u[ind_1+1];if(nxt)nxt.r();else _this.d=1}tr_1=1}});var cl_1=0;file.ondata=function(err,dat,final){if(err){_this.ondata(err,dat,final);_this.terminate()}else{cl_1+=dat.length;chks_1.push(dat);if(final){var dd=new u8(16);wbytes(dd,0,134695760);wbytes(dd,4,file.crc);wbytes(dd,8,cl_1);wbytes(dd,12,file.size);chks_1.push(dd);uf_1.c=cl_1,uf_1.b=hl_1+cl_1+16,uf_1.crc=file.crc,uf_1.size=file.size;if(tr_1)uf_1.r();tr_1=1}else if(tr_1)pAll_1()}};this.u.push(uf_1)}};Zip.prototype.end=function(){var _this=this;if(this.d&2){this.ondata(err(4+(this.d&1)*8,0,1),null,true);return}if(this.d)this.e();else this.u.push({r:function(){if(!(_this.d&1))return;_this.u.splice(-1,1);_this.e()},t:function(){}});this.d=3};Zip.prototype.e=function(){var bt=0,l=0,tl=0;for(var _i=0,_a=this.u;_i<_a.length;_i++){var f=_a[_i];tl+=46+f.f.length+exfl(f.extra)+(f.o?f.o.length:0)}var out=new u8(tl+22);for(var _b=0,_c=this.u;_b<_c.length;_b++){var f=_c[_b];wzh(out,bt,f,f.f,f.u,-f.c-2,l,f.o);bt+=46+f.f.length+exfl(f.extra)+(f.o?f.o.length:0),l+=f.b}wzf(out,bt,this.u.length,tl,l);this.ondata(null,out,true);this.d=2};Zip.prototype.terminate=function(){for(var _i=0,_a=this.u;_i<_a.length;_i++){var f=_a[_i];f.t()}this.d=2};return Zip}();var ARCHIVE_MANIFEST_PATH="manifest.json";var ARCHIVE_DEFINITIONS_PATH="definitions.json";var ZIP_MAX_BYTES=2**32-1;var ZIP_MAX_ENTRIES=65535;var LOCAL_HEADER_BYTES=30;var DATA_DESCRIPTOR_BYTES=16;var CENTRAL_RECORD_BYTES=46;var END_RECORD_BYTES=22;var STORED_PREFIX="files/";var DEFLATE_LEVEL=6;var manifestSchema=objectType({files:arrayType(objectType({sha256:stringType(),size:numberType().int().nonnegative()})),units:arrayType(objectType({chunks:arrayType(objectType({number:numberType().int().positive(),size:numberType().int().nonnegative()})),domain:stringType(),unit:stringType()}))});var parseManifest=(text)=>{try{return manifestSchema.parse(JSON.parse(text))}catch(error){throw new TransferClientError({code:"manifest_invalid"},error instanceof Error?{cause:error}:undefined)}};var archivePaths=(manifestJson)=>{const manifest=parseManifest(manifestJson);return[{path:ARCHIVE_MANIFEST_PATH},{path:ARCHIVE_DEFINITIONS_PATH},...manifest.units.flatMap(({chunks,domain,unit})=>chunks.map(({number,size})=>({path:`units/${domain}/${unit}/chunks/${String(number).padStart(6,"0")}.ndjson`,size}))),...manifest.files.map(({sha256,size})=>({path:`${STORED_PREFIX}${sha256}`,size}))]};var chunksOf=async function*chunksOf(content,signal){const reader=(content instanceof Blob?content.stream():content).getReader();let finished=false;try{for(;;){signal?.throwIfAborted();const next=await reader.read();if(next.done){finished=true;return}yield next.value}}finally{if(!finished){await reader.cancel()}reader.releaseLock()}};var sizeChecked=async function*sizeChecked(path,expected,chunks){let actual=0;for await(const chunk of chunks){actual+=chunk.byteLength;if(expected!==undefined&&actual>expected){throw new TransferClientError({actual,code:"size_mismatch",expected,path})}yield chunk}if(expected!==undefined&&actual!==expected){throw new TransferClientError({actual,code:"size_mismatch",expected,path})}};var streamOf=(chunks)=>new ReadableStream({cancel:async()=>{await chunks.return()},pull:async(controller)=>{const next=await chunks.next();if(next.done){controller.close()}else{controller.enqueue(next.value)}}});var concat=(parts)=>{const whole=new Uint8Array(parts.reduce((total,part)=>total+part.byteLength,0));let offset=0;for(const part of parts){whole.set(part,offset);offset+=part.byteLength}return whole};var bytesOf=async(chunks)=>{const parts=[];for await(const chunk of chunks){parts.push(chunk)}return concat(parts)};var memoryEntry=(path,bytes)=>({open:()=>new Blob([bytes]),path,size:bytes.byteLength});var zipLimit=(path)=>new TransferClientError({code:"archive_zip_limit",path});var utf8Length=(text)=>new TextEncoder().encode(text).byteLength;var zipChunks=async function*zipChunks(files,signal){const pending=[];let failure;let written=0;let count=0;let reserved=END_RECORD_BYTES;const zip=new Zip((error,chunk)=>{if(error===null){pending.push(chunk);written+=chunk.byteLength}else{failure=error}});const drain=()=>{if(failure!==undefined){throw failure}return pending.splice(0)};try{for await(const file of files){signal?.throwIfAborted();count+=1;const nameBytes=utf8Length(file.path);reserved+=DATA_DESCRIPTOR_BYTES+CENTRAL_RECORD_BYTES+nameBytes;if(count>ZIP_MAX_ENTRIES||written+LOCAL_HEADER_BYTES+nameBytes+(file.size??0)+reserved>ZIP_MAX_BYTES){throw zipLimit(file.path)}const entry=file.path.startsWith(STORED_PREFIX)?new ZipPassThrough(file.path):new ZipDeflate(file.path,{level:DEFLATE_LEVEL});zip.add(entry);const content=await file.open();for await(const chunk of sizeChecked(file.path,file.size,chunksOf(content,signal))){entry.push(chunk,false);yield*drain();if(written+reserved>ZIP_MAX_BYTES){throw zipLimit(file.path)}}entry.push(new Uint8Array,true);yield*drain();if(written+reserved>ZIP_MAX_BYTES){throw zipLimit(file.path)}}zip.end();yield*drain()}catch(error){zip.terminate();throw error}};var zipArchive=(files,options={})=>streamOf(zipChunks(files,options.signal));var randomAccessOf=(source)=>source instanceof Blob?{read:(start,end)=>source.slice(start,end),size:source.size}:source;var END_SIGNATURE=101010256;var END64_SIGNATURE=101075792;var END64_LOCATOR_SIGNATURE=117853008;var CENTRAL_SIGNATURE=33639248;var LOCAL_SIGNATURE=67324752;var END64_LOCATOR_BYTES=20;var END64_RECORD_BYTES=56;var MAX_COMMENT_BYTES=65535;var MAX_16=65535;var MAX_32=4294967295;var ZIP64_EXTRA_ID=1;var METHOD_STORED=0;var METHOD_DEFLATED=8;var ENCRYPTED_BIT=1;var MAX_DIRECTORY_BYTES=256*2**20;var MAX_INLINE_BYTES=128*2**20;var INFLATE_STEP_BYTES=16*1024;var zipMalformed=(reason)=>new TransferClientError({code:"zip_malformed",reason});var viewOf=(bytes)=>new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);var safeNumber=(value)=>{if(value>BigInt(Number.MAX_SAFE_INTEGER)){throw zipMalformed("an offset or size is too large")}return Number(value)};var readRange=async(zip,start,end,signal)=>{const bytes=await bytesOf(chunksOf(await zip.read(start,end),signal));if(bytes.byteLength!==end-start){throw zipMalformed("the zip ends early")}return bytes};var locateDirectory=async(zip,signal)=>{const tailStart=Math.max(0,zip.size-END_RECORD_BYTES-MAX_COMMENT_BYTES);const tail=await readRange(zip,tailStart,zip.size,signal);const view=viewOf(tail);for(let at=tail.byteLength-END_RECORD_BYTES;at>=0;at-=1){if(view.getUint32(at,true)!==END_SIGNATURE||at+END_RECORD_BYTES+view.getUint16(at+20,true)!==tail.byteLength){continue}const count=view.getUint16(at+10,true);const size=view.getUint32(at+12,true);const offset=view.getUint32(at+16,true);if(count!==MAX_16&&size!==MAX_32&&offset!==MAX_32){return{count,offset,size}}const locatorAt=tailStart+at-END64_LOCATOR_BYTES;if(locatorAt<0){throw zipMalformed("the zip64 locator is missing")}const locator=viewOf(await readRange(zip,locatorAt,locatorAt+END64_LOCATOR_BYTES,signal));if(locator.getUint32(0,true)!==END64_LOCATOR_SIGNATURE){throw zipMalformed("the zip64 locator is missing")}const recordAt=safeNumber(locator.getBigUint64(8,true));const record=viewOf(await readRange(zip,recordAt,recordAt+END64_RECORD_BYTES,signal));if(record.getUint32(0,true)!==END64_SIGNATURE){throw zipMalformed("the zip64 end record is missing")}return{count:safeNumber(record.getBigUint64(32,true)),offset:safeNumber(record.getBigUint64(48,true)),size:safeNumber(record.getBigUint64(40,true))}}throw zipMalformed("this is not a zip")};var decoder4=new TextDecoder;var zip64Fields=(view,extraAt,extraEnd,fields)=>{const result={...fields};for(let at=extraAt;at+4<=extraEnd;){const length=view.getUint16(at+2,true);if(view.getUint16(at,true)===ZIP64_EXTRA_ID){let next=at+4;for(const field of["size","compressedSize","offset"]){if(result[field]===MAX_32){if(next+8>at+4+length){throw zipMalformed("a zip64 extra field is too short")}result[field]=safeNumber(view.getBigUint64(next,true));next+=8}}break}at+=4+length}return result};var readDirectory2=async(zip,signal)=>{const{count,offset,size}=await locateDirectory(zip,signal);if(size>MAX_DIRECTORY_BYTES||offset+size>zip.size){throw zipMalformed("the central directory is out of bounds")}const view=viewOf(await readRange(zip,offset,offset+size,signal));const entries=new Map;const duplicates=new Set;let at=0;for(let index=0;index<count;index+=1){if(at+CENTRAL_RECORD_BYTES>size||view.getUint32(at,true)!==CENTRAL_SIGNATURE){throw zipMalformed("the central directory is damaged")}const nameBytes=view.getUint16(at+28,true);const extraBytes=view.getUint16(at+30,true);const next=at+CENTRAL_RECORD_BYTES+nameBytes+extraBytes+view.getUint16(at+32,true);if(next>size){throw zipMalformed("the central directory is damaged")}if(view.getUint16(at+8,true)%2===ENCRYPTED_BIT){throw zipMalformed("an entry is encrypted")}const nameAt=at+CENTRAL_RECORD_BYTES;const name=decoder4.decode(new Uint8Array(view.buffer,view.byteOffset+nameAt,nameBytes));const fields=zip64Fields(view,nameAt+nameBytes,nameAt+nameBytes+extraBytes,{compressedSize:view.getUint32(at+20,true),offset:view.getUint32(at+42,true),size:view.getUint32(at+24,true)});if(entries.has(name)){duplicates.add(name)}entries.set(name,{...fields,method:view.getUint16(at+10,true)});at=next}return{duplicates,entries}};var entryOf=(directory,path)=>{if(directory.duplicates.has(path)){throw zipMalformed(`the zip has more than one entry named ${path}`)}return directory.entries.get(path)};var dataRange=async(zip,entry,signal)=>{const header=viewOf(await readRange(zip,entry.offset,entry.offset+LOCAL_HEADER_BYTES,signal));if(header.getUint32(0,true)!==LOCAL_SIGNATURE){throw zipMalformed("a local header is damaged")}const start=entry.offset+LOCAL_HEADER_BYTES+header.getUint16(26,true)+header.getUint16(28,true);return{end:start+entry.compressedSize,start}};var inflated=async function*inflated(chunks){const out=[];const inflate=new Inflate((chunk)=>{out.push(chunk)});try{for await(const chunk of chunks){for(let at=0;at<chunk.byteLength;at+=INFLATE_STEP_BYTES){inflate.push(chunk.subarray(at,at+INFLATE_STEP_BYTES));yield*out.splice(0)}}inflate.push(new Uint8Array,true);yield*out.splice(0)}catch(error){throw error instanceof TransferClientError?error:zipMalformed("an entry is not valid deflate data")}};var dataOfEntry=async function*dataOfEntry(zip,entry,path,signal){const{end,start}=await dataRange(zip,entry,signal);if(end>zip.size){throw zipMalformed("the zip ends early")}const raw=chunksOf(await zip.read(start,end),signal);yield*sizeChecked(path,entry.size,entry.method===METHOD_DEFLATED?inflated(raw):raw)};var checkedEntry=(directory,path,expected)=>{const entry=entryOf(directory,path);if(entry===undefined){return}if(entry.method!==METHOD_STORED&&entry.method!==METHOD_DEFLATED){throw zipMalformed(`${path} uses compression method ${entry.method}`)}if(entry.method===METHOD_STORED&&entry.compressedSize!==entry.size){throw zipMalformed(`${path} is stored with two sizes`)}if(expected!==undefined&&entry.size!==expected){throw new TransferClientError({actual:entry.size,code:"size_mismatch",expected,path})}return entry};var wholeEntry=async(zip,entry,path,signal)=>{if(entry.size>MAX_INLINE_BYTES){throw zipMalformed(`${path} is too large to read whole`)}return await bytesOf(dataOfEntry(zip,entry,path,signal))};var readArchiveZip=async function*readArchiveZip(source,options={}){const{signal}=options;const zip=randomAccessOf(source);const directory=await readDirectory2(zip,signal);const manifestEntry=checkedEntry(directory,ARCHIVE_MANIFEST_PATH);if(manifestEntry===undefined){throw new TransferClientError({code:"zip_manifest_missing"})}const manifest=await wholeEntry(zip,manifestEntry,ARCHIVE_MANIFEST_PATH,signal);const listed=archivePaths(decoder4.decode(manifest)).filter(({path})=>path!==ARCHIVE_MANIFEST_PATH).map(({path,size})=>({entry:checkedEntry(directory,path,size),path,size}));const missing=listed.filter(({entry,path})=>entry===undefined&&path!==ARCHIVE_DEFINITIONS_PATH).map(({path})=>path);if(missing.length>0){throw new TransferClientError({code:"zip_incomplete",missing})}yield memoryEntry(ARCHIVE_MANIFEST_PATH,manifest);const definitions=listed.find(({path})=>path===ARCHIVE_DEFINITIONS_PATH)?.entry;if(definitions!==undefined){yield memoryEntry(ARCHIVE_DEFINITIONS_PATH,await wholeEntry(zip,definitions,ARCHIVE_DEFINITIONS_PATH,signal))}const files=listed.flatMap(({entry,path,size})=>entry===undefined||size===undefined?[]:[{entry,path,size}]);for(const{entry,path,size}of files){yield{open:()=>streamOf(dataOfEntry(zip,entry,path,signal)),path,size}}};var isFirst=(path)=>path===ARCHIVE_MANIFEST_PATH||path===ARCHIVE_DEFINITIONS_PATH;var archiveEntriesFromDownloadUrls=(files,options={})=>{const ordered=[...files.filter(({path})=>path===ARCHIVE_MANIFEST_PATH),...files.filter(({path})=>path===ARCHIVE_DEFINITIONS_PATH),...files.filter(({path})=>!isFirst(path))];return ordered.map(({path,size,url})=>{const open=async()=>{const init={};if(options.signal!==undefined){init.signal=options.signal}const response=await(options.fetch??globalThis.fetch)(url,init);if(!response.ok){throw new TransferClientError({code:"download_failed",path,status:response.status})}return response.body??new Blob([])};return size===undefined?{open,path}:{open,path,size}})};var runStatuses=["queued","running","completed","failed","stopped","expired"];var runEventSchema=objectType({createdAt:stringType(),failure:stringType().optional(),kind:enumType(["accepted","started","continued","resumed","cancel_requested","stopped","completed","failed"]),previousPrincipalId:stringType().optional(),previousPrincipalKind:enumType(["user","service_principal"]).optional(),principalId:stringType(),principalKind:enumType(["user","service_principal"]),reason:enumType(["cancelled","authority_lost","crashed"]).optional(),sequence:numberType().int().nonnegative(),status:enumType(runStatuses)});var MAX_RECONNECTS_WITHOUT_PROGRESS2=5;var isRunEventError=(error)=>error instanceof TransferClientError&&error.failure.code==="run_event_invalid";var decodedEvents=async function*decodedEvents(frames){for await(const frame of frames){const decoded=runEventSchema.safeParse(frame);if(!decoded.success){throw new TransferClientError({code:"run_event_invalid"},{cause:decoded.error})}yield decoded.data}};var followTransferRun=async(input)=>{const{organizationId,runId}=input;let cursor=input.afterSequence??0;const known=await getTransferRun({organizationId},runId);if(known!==undefined&&!isTransferRunActive(known)&&cursor>=known.lastEventSequence){return{lastEventId:input.afterSequence===undefined?undefined:String(cursor),reason:"terminal"}}return await followEventStream({connect:async(connection)=>{const response=await organizationTransferEvents({...singleConnectionSseOptions,fetch:eventStreamFetch(client.getConfig().fetch),headers:{...connection.lastEventId===undefined?undefined:{"last-event-id":connection.lastEventId},"x-organization-id":organizationId},path:{runId},signal:connection.signal,throwOnError:true});return decodedEvents(response.stream)},eventId:()=>String(cursor),isRetryableError:(error)=>!isRunEventError(error)&&isRetryableEventStreamError(error),isTerminal:(event)=>!isTransferRunActive(event),...input.afterSequence===undefined?undefined:{lastEventId:String(input.afterSequence)},maxRetries:input.maxRetries??MAX_RECONNECTS_WITHOUT_PROGRESS2,onEvent:async(event)=>{if(event.sequence<=cursor){return}cursor=event.sequence;await input.onEvent(event)},...input.retryDelayMs===undefined?undefined:{initialRetryDelayMs:input.retryDelayMs},...input.signal===undefined?undefined:{signal:input.signal}})};var ALREADY_PRESENT=new Set([409,412]);var bodyInit=(entry,body,headers)=>body instanceof Blob?{body,headers}:{body,duplex:"half",headers:{...headers,"content-length":String(entry.size)}};var archiveIds=new WeakMap;var uploadArchiveIdOf=(error)=>archiveIds.get(error);var uploadFile=async(input,entry)=>{const[signed]=await requestTransferUploadUrls({archiveId:input.archiveId,organizationId:input.organizationId,paths:[entry.path],...input.signal===undefined?undefined:{signal:input.signal}});if(signed===undefined){throw new TransferClientError({code:"upload_failed",path:entry.path,status:0})}const body=await entry.open();const init={...bodyInit(entry,body,signed.headers),method:signed.method};if(input.signal!==undefined){init.signal=input.signal}const response=await(input.fetch??globalThis.fetch)(signed.url,init);await response.body?.cancel();if(response.ok){return{outcome:"uploaded",path:entry.path,size:entry.size}}if(ALREADY_PRESENT.has(response.status)){return{outcome:"skipped",path:entry.path,size:entry.size}}throw new TransferClientError({code:"upload_failed",path:entry.path,status:response.status})};var uploadArchive=async(options)=>{const input={...options,archiveId:options.archiveId??crypto.randomUUID()};const{archiveId,signal}=input;const limit=Math.max(1,input.concurrency??1);const uploaded=[];const skipped=[];const inFlight=new Map;let manifest;let failure;let nextId=0;const attempt=async(id,entry)=>{try{const file=await uploadFile(input,entry);(file.outcome==="uploaded"?uploaded:skipped).push(file.path);input.onFile?.(file);return{id}}catch(error){return{failure:{error},id}}};const finishOne=async()=>{const done=await Promise.race(inFlight.values());inFlight.delete(done.id);return done.failure};for await(const entry of input.entries){if(signal?.aborted===true){failure={error:signal.reason};break}if(entry.path===ARCHIVE_MANIFEST_PATH){manifest=entry;continue}nextId+=1;inFlight.set(nextId,attempt(nextId,entry));if(inFlight.size>=limit){failure=await finishOne()}if(failure!==undefined){break}}const rest=await Promise.all(inFlight.values());failure??=rest.find((done)=>done.failure!==undefined)?.failure;if(failure===undefined&&manifest!==undefined){const{failure:manifestFailure}=await attempt(0,manifest);failure=manifestFailure}if(failure!==undefined){if(failure.error instanceof Error){archiveIds.set(failure.error,archiveId)}throw failure.error}return{archiveId,skipped,uploaded}};import path15 from"path";var plainWord=/^[\w@%+=:,./-]+$/u;var shellWord=(word)=>plainWord.test(word)?word:`'${word.replaceAll("'",String.raw`'\''`)}'`;var commandLine=(words)=>["ci","transfer",...words].map((word)=>shellWord(word)).join(" ");var targetArguments=(args)=>targetOptions.flatMap((name)=>{const flag=`--${name}`;const index=args.indexOf(flag);const value=index===-1?undefined:args[index+1];return value===undefined?[]:[flag,value]});class TransferCommandError extends TaggedError3()("TransferCommandError",{archiveId:optional2(String5),cause:optional2(Unknown2),code:optional2(String5),message:String5,nextAction:optional2(String5),runId:optional2(String5),status:optional2(Finite)}){}var interruptedCode="interrupted";var nonEmptyFields=(fields)=>fields;var domains=["knowledge","documents","datasets"];var boundaryModes=["reference","clear","include_referenced"];var policies=["create_only","skip_existing","update","fill_blanks"];var unresolvedReferences=["fail","continue","skip_item"];var datasetModes=["append","upsert","replace"];var userJoinFields=["email","name","id"];var groupJoinFields=["name","slug","fqn"];var archiveFormats=["zip","folder"];var traverse4=forEach2;var refuse=(message)=>new TransferCommandError({message});var choose=(flag,value,allowed)=>{const found=allowed.find((candidate)=>candidate===value);return found===undefined?fail6(refuse(`${flag} must be one of ${allowed.join(", ")}`)):succeed6(found)};var chooseAll=(flag,value,allowed)=>traverse4(value.split(",").filter((part)=>part!==""),(part)=>choose(flag,part,allowed));var positiveInteger=(flag,value,minimum=1)=>{const number=Number(value);return/^\d+$/u.test(value)&&Number.isSafeInteger(number)&&number>=minimum?succeed6(number):fail6(refuse(`${flag} must be a whole number of ${minimum} or more`))};var optionalPositive=fn2("Transfer.optionalPositive")(function*optionalPositive(options,flag){const value=optionValue2(options,flag);return value===undefined?undefined:yield*positiveInteger(`--${flag}`,value)});var pairOf=(flag,value)=>{const separator=value.indexOf("=");const left=value.slice(0,separator);const right=value.slice(separator+1);return separator>0&&right!==""?succeed6([left,right]):fail6(refuse(`${flag} must be written <left>=<right>`))};var requireValue=(options,flag)=>{const value=optionValue2(options,flag);return value===undefined?fail6(refuse(`Missing required option --${flag}`)):succeed6(value)};var optionError=(flags,message)=>fail6(refuse(`${flags} ${message}`));var exportOptionNames={repeatable:["domain","identity-field"],values:["boundary-mode","depth","format","max-dependency-items","out","run","selection"]};var boundaryOf=fn2("Transfer.boundaryOf")(function*boundaryOf(options){const modeValue=optionValue2(options,"boundary-mode");const mode=modeValue===undefined?undefined:yield*choose("--boundary-mode",modeValue,boundaryModes);const depth=yield*optionalPositive(options,"depth");const maxDependencyItems=yield*optionalPositive(options,"max-dependency-items");const identityFields={};for(const value of optionValues(options,"identity-field")){const[unit,fields]=yield*pairOf("--identity-field",value);identityFields[unit]=fields.split(",").filter((field)=>field!=="")}const boundary={...mode===undefined?undefined:{mode},...depth===undefined?undefined:{depth},...maxDependencyItems===undefined?undefined:{maxDependencyItems},...Object.keys(identityFields).length===0?undefined:{identityFields}};return Object.keys(boundary).length===0?undefined:boundary});var selectionOf=fn2("Transfer.selectionOf")(function*selectionOf(options){const file=optionValue2(options,"selection");const named=optionValues(options,"domain");if(file!==undefined&&named.length>0){return yield*optionError("--selection","already names the domains; do not combine it with --domain")}if(file!==undefined){return{kind:"file",path:file}}const chosen=yield*traverse4(named,(domain)=>choose("--domain",domain,domains));return chosen.length===0?undefined:{domains:[...new Set(chosen)],kind:"domains"}});var downloadOf=fn2("Transfer.downloadOf")(function*downloadOf(options){const out=optionValue2(options,"out");const formatValue=optionValue2(options,"format");if(out===undefined){return formatValue===undefined?undefined:yield*optionError("--format","needs --out")}return{format:formatValue===undefined?"zip":yield*choose("--format",formatValue,archiveFormats),out}});var exportCommand=fn2("Transfer.exportCommand")(function*exportCommand(args){const options=yield*parseCommandOptionsEffect(args,{...exportOptionNames,switches:["preview"],values:[...targetOptions,...exportOptionNames.values]});const download=yield*downloadOf(options);const runId=optionValue2(options,"run");if(runId!==undefined){const selecting=["boundary-mode","depth","domain","identity-field","max-dependency-items","selection"].filter((flag)=>options.values.has(flag));if(options.switches.has("preview")||selecting.length>0){return yield*optionError("--run","downloads a finished Export Run; it takes only --out and --format")}return download===undefined?yield*optionError("--run","needs --out"):{action:"export_download",download,runId}}const input={boundary:yield*boundaryOf(options),selection:yield*selectionOf(options)};if(options.switches.has("preview")){return download===undefined?{action:"export_preview",input}:yield*optionError("--preview","starts no run; do not combine with --out")}return{action:"export",download,input}});var importOptionNames={repeatable:["connector-instance","dataset-mode","force","unit"],switches:["events","no-import-origin"],values:["join-group","join-user","max-errors","policy","unresolved-reference"]};var unitChoiceOf=(value)=>{const separator=value.indexOf(":");const prefix=value.slice(0,separator);const domain=domains.find((candidate)=>candidate===prefix);return domain===undefined||separator+1===value.length?{unit:value}:{domain,unit:value.slice(separator+1)}};var unitsOf=fn2("Transfer.unitsOf")(function*unitsOf(options){const names=[...new Set(optionValues(options,"unit"))];const modes=new Map;for(const value of optionValues(options,"dataset-mode")){const[unit,mode]=yield*pairOf("--dataset-mode",value);modes.set(unit,yield*choose("--dataset-mode",mode,datasetModes))}const forced=new Set(optionValues(options,"force"));for(const unit of[...modes.keys(),...forced]){if(!names.includes(unit)){return yield*optionError(`Unit ${unit}`,"has an option but is not named by --unit; naming a unit limits the import to the listed units")}}return names.map((name)=>{const datasetMode=modes.get(name);return{...unitChoiceOf(name),...datasetMode===undefined?undefined:{datasetMode},...forced.has(name)?{force:true}:undefined}})});var importOptionsOf=fn2("Transfer.importOptionsOf")(function*importOptionsOf(options){const policyValue=optionValue2(options,"policy");const unresolvedValue=optionValue2(options,"unresolved-reference");const userValue=optionValue2(options,"join-user");const groupValue=optionValue2(options,"join-group");const maxErrors=yield*optionalPositive(options,"max-errors");const connectorInstances=yield*traverse4(optionValues(options,"connector-instance"),(value)=>map5(pairOf("--connector-instance",value),([sourceInstanceId,targetInstanceId])=>({sourceInstanceId,targetInstanceId})));const units=yield*unitsOf(options);const user=userValue===undefined?undefined:yield*chooseAll("--join-user",userValue,userJoinFields);const group=groupValue===undefined?undefined:yield*chooseAll("--join-group",groupValue,groupJoinFields);const joinFields={...user===undefined?undefined:{user},...group===undefined?undefined:{group}};const result={...connectorInstances.length===0?undefined:{connectorInstances},...options.switches.has("events")?{events:true}:undefined,...options.switches.has("no-import-origin")?{importOrigin:false}:undefined,...maxErrors===undefined?undefined:{maxErrors},...policyValue===undefined?undefined:{policy:yield*choose("--policy",policyValue,policies)},...units.length===0?undefined:{units},...unresolvedValue===undefined?undefined:{unresolvedReference:yield*choose("--unresolved-reference",unresolvedValue,unresolvedReferences)},...Object.keys(joinFields).length===0?undefined:nonEmptyFields({joinFields})};return Object.keys(result).length===0?undefined:result});var importCommand=fn2("Transfer.importCommand")(function*importCommand(args){const options=yield*parseCommandOptionsEffect(args,{repeatable:importOptionNames.repeatable,switches:[...importOptionNames.switches,"apply","confirm-replace","plan"],values:[...targetOptions,...importOptionNames.values,"archive","archive-id","plan-run"]});const plan=options.switches.has("plan");const apply=options.switches.has("apply");if(plan===apply){return yield*optionError("ci transfer import","needs exactly one of --plan or --apply")}const importOptions=yield*importOptionsOf(options);const archivePath=optionValue2(options,"archive");const archiveId=optionValue2(options,"archive-id");if(plan){if(options.switches.has("confirm-replace")){return yield*optionError("--confirm-replace","belongs to --apply")}if(options.values.has("plan-run")){return yield*optionError("--plan-run","belongs to --apply")}if(archivePath!==undefined){return{action:"import_plan",archive:{archiveId,path:archivePath},options:importOptions}}return archiveId===undefined?yield*optionError("--plan","needs --archive <folder|zip> or --archive-id <id>"):{action:"import_plan",archive:{archiveId,path:undefined},options:importOptions}}if(archivePath!==undefined){return yield*optionError("--archive","belongs to --plan; --apply uses the archive of the Plan run")}return{action:"import_apply",archiveId,confirmReplace:options.switches.has("confirm-replace"),options:importOptions,planRunId:yield*requireValue(options,"plan-run")}});var rollbackCommand=fn2("Transfer.rollbackCommand")(function*rollbackCommand(args){const options=yield*parseCommandOptionsEffect(args,{switches:["force"],values:[...targetOptions,"source-run"]});return{action:"rollback",force:options.switches.has("force"),sourceRunId:yield*requireValue(options,"source-run")}});var runsActions=["cancel","purge","report","resume"];var runsCommand=fn2("Transfer.runsCommand")(function*runsCommand(args){const options=yield*parseCommandOptionsEffect(args,{switches:runsActions,values:[...targetOptions,"limit","run"]});const limit=yield*optionalPositive(options,"limit");const runId=optionValue2(options,"run");const chosen=runsActions.filter((action)=>options.switches.has(action));if(chosen.length>1){return yield*optionError(chosen.map((action)=>`--${action}`).join(" and "),"cannot be combined")}if(runId===undefined){return chosen.length===0?{action:"runs_list",limit}:yield*optionError(`--${chosen[0]??""}`,"needs --run <run-id>")}if(limit!==undefined){return yield*optionError("--limit","only applies to the list of runs")}return{action:"runs_run",run:chosen[0]??"show",runId}});var transferUsage="Usage: ci transfer export|import|rollback|runs";var parseTransferCommand=(args)=>{const[name,...rest]=args;const parsed=(()=>{switch(name){case"export":{return exportCommand(rest)}case"import":{return importCommand(rest)}case"rollback":{return rollbackCommand(rest)}case"runs":{return runsCommand(rest)}default:{return fail6(refuse(transferUsage))}}})();return parsed.pipe(mapError2((cause)=>cause instanceof TransferCommandError?cause:refuse(cause.message)))};var blockedNote=(blocked)=>{switch(blocked){case"write_permission_denied":{return"you may not write this unit in the target Organization."}case"unit_incomplete":{return"the export stopped part-way through this unit, so the archive holds only some of its items. Export it again."}case"unit_ambiguous":{return"the target has more than one collection with this name. Rename one and plan again, or leave the unit out."}default:{return blocked}}};var warningNote=(warning)=>{switch(warning){case"no_match_key_or_origin":{return"it has no Match Key and Import Origin is off, so a rerun creates duplicates."}case"forced_duplicates":{return"it is forced, so its rows are appended again and can duplicate earlier rows."}case"earlier_run_committed":{return"a stopped run of this archive already committed batches of this unit, and this run appends them again. Resume that run instead."}case"already_imported":{return"this archive was already imported into this unit, so the unit is skipped unless you force it."}default:{return warning}}};var planNotes=(plan)=>plan.units.flatMap((unit)=>{const name=`${unit.domain}:${unit.unit}`;return[...unit.blocked===undefined?[]:[`${name} is blocked: ${blockedNote(unit.blocked)}`],...unit.warnings.map((warning)=>`${name} warns: ${warningNote(warning)}`)]});var traverse5=forEach2;var manifestUnits=fromJsonString2(Struct({units:ArraySchema(Struct({domain:Literals(domains),unit:String5}))}));var unitsOfManifest=(manifestJson)=>decodeEffect2(manifestUnits)(manifestJson).pipe(map5(({units})=>units),mapError2((cause)=>new TransferCommandError({cause,code:"manifest_invalid",message:"manifest.json is not a readable archive manifest"})));var written=({domain,unit})=>`${domain}:${unit}`;var domainOf=(choice,known,where)=>{const found=known.filter(({unit})=>unit===choice.unit);const[only]=found;if(found.length===1&&only!==undefined){return succeed6(only.domain)}return fail6(new TransferCommandError({code:"unit_domain_unknown",message:found.length===0?`Unit ${choice.unit} is not in ${where}; the units are ${known.map(written).join(", ")}`:`Unit ${choice.unit} is in several domains of ${where}; write ${found.map(written).join(" or ")}`}))};var withUnitDomains=fn2("Transfer.withUnitDomains")(function*withUnitDomains(options,source){if(options===undefined){return options}const{units:choices,...rest}=options;if(choices===undefined){return rest}const known=choices.some(({domain})=>domain===undefined)?yield*source.units:[];const units=yield*traverse5(choices,(choice)=>choice.domain===undefined?map5(domainOf(choice,known,source.where),(domain)=>({...choice,domain})):succeed6({...choice,domain:choice.domain}));return{...rest,units}});var traverse6=forEach2;var encodeJson4=encodeSync(fromJsonString2(Unknown2));var isClientFailure=is2(Struct({failure:Struct({code:String5}),message:String5,name:Literal2("TransferClientError")}));var describeFailure2=(cause)=>{if(is2(ManagementRequestError)(cause)){return cause}if(is2(TransferCommandError)(cause)){return cause}if(cause instanceof EventStreamHttpError){return new TransferCommandError({cause,message:`The transfer event stream was rejected with HTTP ${cause.status}`,status:cause.status})}if(cause instanceof EventStreamRetriesExhaustedError){return new TransferCommandError({cause,code:"event_stream_lost",message:"The transfer event stream disconnected; the run continues"})}if(isClientFailure(cause)){return new TransferCommandError({cause,code:cause.failure.code,message:cause.message})}return new TransferCommandError({cause,message:cause instanceof Error?cause.message:"Transfer request failed"})};var call2=(operation)=>tryPromise2({catch:describeFailure2,try:operation});var withTransferClient=(context,fetch2)=>(effect)=>acquireUseRelease2(sync2(()=>{const{baseUrl,headers}=context.client.getConfig();const previous=client.getConfig();client.setConfig({...baseUrl===undefined?undefined:{baseUrl},fetch:fetch2,...headers===undefined?undefined:{headers}});const interceptor=client.interceptors.error.use((body,response,request)=>{const reply=response;return reply===undefined?new ManagementRequestError({cause:body,message:"Organization transfer request failed: could not reach the backend",status:0}):requestFailure(`Organization transfer ${request.method} ${new URL(request.url).pathname}`,reply,body)});return{interceptor,previous}}),()=>effect,({interceptor,previous})=>sync2(()=>{client.interceptors.error.eject(interceptor);client.setConfig({...previous.baseUrl===undefined?undefined:{baseUrl:previous.baseUrl},...previous.fetch===undefined?undefined:{fetch:previous.fetch},headers:{authorization:null}})}));var refuse2=(message,extra={})=>new TransferCommandError({...extra,message});var withDetails=(failure,details)=>new TransferCommandError({archiveId:failure.archiveId,cause:failure.cause,code:failure.code,message:failure.message,nextAction:failure.nextAction,runId:failure.runId,status:failure.status,...details});var commandError=(cause)=>{if(is2(TransferCommandError)(cause)){return cause}return new TransferCommandError({cause,message:cause.message,...is2(ManagementRequestError)(cause)?{status:cause.status}:undefined})};var selectionFromFile=fn2("Transfer.selectionFromFile")(function*selectionFromFile(files,file){const text=yield*tryPromise2({catch:(cause)=>new TransferCommandError({cause,message:`Cannot read the selection file ${file}`}),try:()=>files.readText(file)});return yield*decodeEffect2(fromJsonString2(JsonObject))(text).pipe(mapError2((cause)=>new TransferCommandError({cause,message:`${file} is not a JSON object that names a Selection`})))});var exportRequest=fn2("Transfer.exportRequest")(function*exportRequest(input,files){const{selection}=input;const fromFile=selection?.kind==="file"?yield*selectionFromFile(files,selection.path):undefined;const selected=selection?.kind==="domains"?{domains:selection.domains}:fromFile;const request={...input.boundary===undefined?undefined:{boundary:input.boundary},...selected===undefined?undefined:nonEmptyFields({selection:selected})};return request});var findRun=fn2("Transfer.findRun")(function*findRun(scope,runId){const run=yield*call2(()=>getTransferRun(scope,runId));return run===undefined?yield*refuse2(`Run ${runId} not found; check the run id`,{code:"run_not_found"}):run});var requireCompleted=(run,runCommand,newRunCommand)=>{if(run.status==="completed"){return succeed6(run)}const reason=run.stopReason===null?"":` (${run.stopReason})`;const cannotResume=run.status==="stopped"&&run.journalExpiredAt!==null;return fail6(new TransferCommandError({code:`run_${run.status}`,message:`${run.type} run ${run.id} ${run.status}${reason}${cannotResume?"; its journal expired, so it can no longer resume":""}`,nextAction:cannotResume?newRunCommand(run):runCommand(run.id,run.status==="stopped"?"--resume":"--report"),runId:run.id}))};var manifestText=async(archiveFiles)=>{for await(const file of archiveFiles){if(file.path===ARCHIVE_MANIFEST_PATH){return await new Response(await file.open()).text()}}throw new TransferCommandError({code:"archive_incomplete",message:"The archive has no manifest.json"})};var folderOutOfBounds=(file)=>path15.isAbsolute(file)||file.split("/").includes("..");var folderEntries=fn2("Transfer.folderEntries")(function*folderEntries(files,folder){const[listed,manifest]=yield*tryPromise2({catch:describeFailure2,try:()=>Promise.all([files.list(folder),files.readText(path15.join(folder,ARCHIVE_MANIFEST_PATH))])});const wanted=yield*try_2({catch:describeFailure2,try:()=>archivePaths(manifest)});const sizes=new Map(listed.map((file)=>[file.path,file.size]));const missing=wanted.filter((file)=>file.path!==ARCHIVE_DEFINITIONS_PATH&&!sizes.has(file.path));if(missing.length>0){return yield*refuse2(`${folder} lacks ${missing.length} files that manifest.json lists, for example ${missing[0]?.path??""}`,{code:"archive_incomplete"})}return wanted.flatMap(({path:file})=>{const size=sizes.get(file);return size===undefined?[]:[{open:()=>files.openRead(path15.join(folder,file)),path:file,size}]})});var transferCommandEffect=(args,dependencies)=>gen2(function*transferCommand(){const{files,writeOutput}=dependencies;const writeLine=(line)=>{writeOutput(`${encodeJson4(line)}
3249
+ `)};const parsed=yield*parseTransferCommand(args);const context=yield*resolveOrganizationContext({args,environment:dependencies.environment,fetch:dependencies.fetch}).pipe(mapError2(commandError));const scope={organizationId:context.organizationId};const{signal}=dependencies;const backendArgs=targetArguments(args);const runCommand=(runId,flag)=>commandLine(["runs","--run",runId,...flag===undefined?[]:[flag],...backendArgs]);const newRunCommand=(stopped)=>{switch(stopped.type){case"export":{return commandLine(["export",...backendArgs])}case"rollback":{return commandLine(["rollback",...stopped.sourceRunId===null?[]:["--source-run",stopped.sourceRunId],...backendArgs])}case"import":{return commandLine(["import","--plan",...stopped.archiveId===null?[]:["--archive-id",stopped.archiveId],...backendArgs])}default:{return stopped.type}}};const interruptible=(operation)=>tryPromise2({catch:(cause)=>signal.aborted?new TransferCommandError({cause,code:interruptedCode,message:"The command was interrupted"}):describeFailure2(cause),try:operation});const finish=fn2("Transfer.finish")(function*finish(started){const followed=yield*interruptible(()=>followTransferRun({onEvent:(event)=>{writeLine({event,kind:"progress",runId:started.id,step:"run"})},organizationId:scope.organizationId,runId:started.id,signal})).pipe(mapError2((cause)=>is2(TransferCommandError)(cause)?withDetails(cause,{nextAction:runCommand(started.id),runId:started.id}):cause));if(followed.reason==="aborted"){return yield*new TransferCommandError({code:interruptedCode,message:`Interrupted; run ${started.id} continues on the backend`,nextAction:runCommand(started.id),runId:started.id})}return yield*requireCompleted(yield*findRun(scope,started.id),runCommand,newRunCommand)});const kindOf=fn2("Transfer.kindOf")(function*kindOf(source){const kind=yield*tryPromise2({catch:describeFailure2,try:()=>files.kind(source)});return kind===null?yield*refuse2(`${source} does not exist`):kind});const retryUpload=(archiveId)=>commandLine([...args,...args.includes("--archive-id")?[]:["--archive-id",archiveId]]);const resumable=(failure)=>{if(!is2(TransferCommandError)(failure)){return failure}const archiveId=failure.cause instanceof Error?uploadArchiveIdOf(failure.cause):undefined;return archiveId===undefined?failure:withDetails(failure,{archiveId,nextAction:retryUpload(archiveId)})};const upload=fn2("Transfer.upload")(function*upload(source,archiveId){const entries=(yield*kindOf(source))==="file"?readArchiveZip(files.seekable(source),{signal}):yield*folderEntries(files,source);yield*interruptible(()=>uploadArchive({archiveId,concurrency:4,entries,fetch:dependencies.fetch,onFile:(file)=>{writeLine({archiveId,kind:"progress",outcome:file.outcome,path:file.path,size:file.size,step:"upload"})},organizationId:scope.organizationId,signal})).pipe(mapError2(resumable))});const download=fn2("Transfer.download")(function*download(runId,archiveId,target){const listed=yield*interruptible(()=>requestTransferDownloadUrls({archiveId,organizationId:scope.organizationId,signal}));writeLine({archiveId,files:listed.length,format:target.format,kind:"progress",out:target.out,step:"download"});const archiveFiles=archiveEntriesFromDownloadUrls(listed,{fetch:dependencies.fetch,signal});const written=target.format==="zip"?interruptible(()=>files.writeStream(target.out,zipArchive(archiveFiles,{signal}))):traverse6(archiveFiles,(file)=>folderOutOfBounds(file.path)?fail6(refuse2(`Archive file ${file.path} points outside the folder`)):interruptible(async()=>{const content=await file.open();await files.writeStream(path15.join(target.out,file.path),content instanceof Blob?content.stream():content)}));yield*written.pipe(mapError2((cause)=>is2(TransferCommandError)(cause)&&cause.code==="archive_zip_limit"?withDetails(cause,{archiveId,nextAction:commandLine(["export","--run",runId,"--out",target.out,"--format","folder",...backendArgs]),runId}):cause))});const exportDownloaded=fn2("Transfer.exportDownloaded")(function*exportDownloaded(run,target){if(target!==undefined&&run.archiveId!==null){yield*download(run.id,run.archiveId,target)}writeLine({archiveId:run.archiveId,kind:"result",...target,run})});const archiveManifest=fn2("Transfer.archiveManifest")(function*archiveManifest(archive){if(archive.path===undefined){return yield*interruptible(async()=>manifestText(archiveEntriesFromDownloadUrls(await requestTransferDownloadUrls({archiveId:archive.archiveId,organizationId:scope.organizationId,signal}),{fetch:dependencies.fetch,signal})))}const source=archive.path;return(yield*kindOf(source))==="directory"?yield*tryPromise2({catch:describeFailure2,try:()=>files.readText(path15.join(source,ARCHIVE_MANIFEST_PATH))}):yield*interruptible(()=>manifestText(readArchiveZip(files.seekable(source),{signal})))});const importPlanned=fn2("Transfer.importPlanned")(function*importPlanned(archive,input){const options=yield*withUnitDomains(input,{units:archiveManifest(archive).pipe(mapError2(commandError),flatMap4(unitsOfManifest)),where:"the archive"});const archiveId=archive.archiveId??dependencies.newArchiveId();if(archive.path!==undefined){yield*upload(archive.path,archiveId)}const run=yield*finish(yield*call2(()=>startTransferImport(scope,{archiveId,mode:"plan",...options===undefined?undefined:{options}})));const planned=transferRunPlan(run);writeLine({archiveId,kind:"result",plan:planned,run});for(const note of planned===undefined?[]:planNotes(planned)){dependencies.writeDiagnostic(`${note}
3250
+ `)}});const planUnits=fn2("Transfer.planUnits")(function*planUnits(planRunId){const planned=transferRunPlan(yield*findRun(scope,planRunId));return planned===undefined?yield*refuse2(`Run ${planRunId} has no Plan to take the unit domains from; write each unit as <domain>:<unit>`):planned.units});const importApplied=fn2("Transfer.importApplied")(function*importApplied(apply){const archiveId=apply.archiveId??(yield*findRun(scope,apply.planRunId)).archiveId;if(archiveId===null){return yield*refuse2(`Run ${apply.planRunId} has no archive; pass --archive-id`)}const options=yield*withUnitDomains(apply.options,{units:planUnits(apply.planRunId).pipe(mapError2(commandError)),where:"the Plan"});const request=importApplyRequest({...apply.confirmReplace?{confirmReplace:true}:undefined,plan:{archiveId,mode:"plan",...options===undefined?undefined:{options}},planRunId:apply.planRunId});const run=yield*finish(yield*call2(()=>startTransferImport(scope,request)));writeLine({archiveId,kind:"result",run})});const runsRun=fn2("Transfer.runsRun")(function*runsRun(selected){const{run,runId}=selected;if(run==="report"){writeLine({kind:"result",report:yield*call2(()=>getTransferRunReport(scope,runId))})}else if(run==="purge"){yield*call2(()=>purgeTransferRun(scope,runId));writeLine({kind:"result",purged:runId})}else if(run==="cancel"){writeLine({kind:"result",run:yield*call2(()=>cancelTransferRun(scope,runId))})}else if(run==="resume"){writeLine({kind:"result",run:yield*finish(yield*call2(()=>resumeTransferRun(scope,runId)))})}else{writeLine({kind:"result",run:yield*findRun(scope,runId)})}});yield*gen2(function*selectedCommand(){switch(parsed.action){case"export_preview":{const request=yield*exportRequest(parsed.input,files);writeLine({kind:"result",preview:yield*call2(()=>previewTransferExport(scope,request))});break}case"export":{const request=yield*exportRequest(parsed.input,files);const run=yield*finish(yield*call2(()=>startTransferExport(scope,request)));yield*exportDownloaded(run,parsed.download);break}case"export_download":{const run=yield*findRun(scope,parsed.runId);if(run.type!=="export"||run.archiveId===null){return yield*refuse2(`Run ${run.id} is not a finished Export Run`)}yield*exportDownloaded(yield*requireCompleted(run,runCommand,newRunCommand),parsed.download);break}case"import_plan":{yield*importPlanned(parsed.archive,parsed.options);break}case"import_apply":{yield*importApplied(parsed);break}case"rollback":{const run=yield*finish(yield*call2(()=>startTransferRollback(scope,{...parsed.force?{force:true}:undefined,sourceRunId:parsed.sourceRunId})));writeLine({kind:"result",run});break}case"runs_list":{const list=yield*call2(()=>listTransferRuns(scope,parsed.limit===undefined?{}:{limit:parsed.limit}));writeLine({kind:"result",runs:list.data});break}case"runs_run":{yield*runsRun(parsed);break}default:{return parsed}}}).pipe(withTransferClient(context,dependencies.fetch),catchTag2("ManagementRequestError",explainOrganizationForbidden(context,context.organizationId)))}).pipe(mapError2(commandError));import path16 from"path";class UpgradeCommandError extends TaggedError3()("UpgradeCommandError",{cause:optional2(Unknown2),message:String5}){}var registryUrl="https://registry.npmjs.org";var registryTimeout="30 seconds";var RegistryVersion=Struct({version:String5});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}`}))}),flatMap4((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(path16.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
3249
3251
  `)})}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(" ")}
3250
3252
  `);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}
3251
3253
  `)})}).pipe(mapError2((cause)=>is2(UpgradeCommandError)(cause)?cause:new UpgradeCommandError({cause,message:cause.message})));class WhoamiCommandError extends TaggedError3()("WhoamiCommandError",{cause:optional2(Unknown2),message:String5}){}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(`
3252
3254
  `)}
3253
- `)}).pipe(mapError2((cause)=>new WhoamiCommandError({cause,message:cause.message})));import{fileURLToPath as fileURLToPath13}from"url";var{existsSync:existsSync9,watch:watch3}=await import("fs");var path15=runSync2(provide3(Path2,layer5));var declarationPackageRoot=(declarationPath)=>{const declarationDirectory=path15.dirname(declarationPath);let candidate=declarationDirectory;while(true){if(existsSync9(path15.join(candidate,"package.json"))){return candidate}const parent=path15.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(flatMap4(()=>{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 readFileIfPresent=(filePath)=>existsSync10(filePath)?readFileSync9(filePath,"utf-8"):undefined;var readEnvFile=readFileIfPresent;var writeEnvFile=(filePath,content)=>{const temporary=`${filePath}.${process.pid}.tmp`;writeFileSync7(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 nodePath6=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:String5})});var usage6=`Usage:
3255
+ `)}).pipe(mapError2((cause)=>new WhoamiCommandError({cause,message:cause.message})));import{fileURLToPath as fileURLToPath13}from"url";var{existsSync:existsSync9,watch:watch3}=await import("fs");var path17=runSync2(provide3(Path2,layer5));var declarationPackageRoot=(declarationPath)=>{const declarationDirectory=path17.dirname(declarationPath);let candidate=declarationDirectory;while(true){if(existsSync9(path17.join(candidate,"package.json"))){return candidate}const parent=path17.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(flatMap4(()=>{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 readFileIfPresent=(filePath)=>existsSync10(filePath)?readFileSync9(filePath,"utf-8"):undefined;var readEnvFile=readFileIfPresent;var writeEnvFile=(filePath,content)=>{const temporary=`${filePath}.${process.pid}.tmp`;writeFileSync7(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 nodePath6=runSync2(provide3(Path2,layer5));var runNative=runPromiseWith2(empty());var runFileEffect=runNative;var encodeJson5=encodeSync(fromJsonString2(Unknown2));var packagePreflightErrorTag="PackagePreflightError";var packagePreflightDiagnostic=Struct({_tag:Literal2(packagePreflightErrorTag),diagnostic:Struct({message:String5})});var usage6=`Usage:
3254
3256
  ci login <API URL> [--organization <organization-id>] [--no-browser] [--profile <name>]
3255
3257
  ci whoami
3256
3258
  ci logout
@@ -3277,6 +3279,13 @@ export const ${moduleExport3(input.exportName)} = loaded[${JSON.stringify(input.
3277
3279
  ci doctor [--fqn <fqn>] [--redirect-uri <uri>]...
3278
3280
  (whoami, logout, orgs, apps, api-keys and doctor also accept [--backend-url <url>] [--organization <organization-id>] [--profile <name>])
3279
3281
  ci upgrade (installs the latest version over a global npm, pnpm or Bun install)
3282
+ ci transfer export [--preview | --run <run-id>] [--domain <knowledge|documents|datasets>]... [--selection <file>] [--boundary-mode <reference|clear|include_referenced>] [--depth <n>] [--max-dependency-items <n>] [--identity-field <unit>=<field,...>]... [--out <path>] [--format <zip|folder>]
3283
+ ci transfer import --plan (--archive <folder|zip> [--archive-id <id>] | --archive-id <id>) [import options]
3284
+ ci transfer import --apply --plan-run <run-id> [--archive-id <id>] [--confirm-replace] [import options]
3285
+ import options: [--policy <create_only|skip_existing|update|fill_blanks>] [--unresolved-reference <fail|continue|skip_item>] [--join-user <email,name,id>] [--join-group <name,slug,fqn>] [--connector-instance <source-id>=<target-id>]... [--max-errors <n>] [--no-import-origin] [--events] [--unit <domain>:<unit>|<unit>]... [--dataset-mode <unit>=<append|upsert|replace>]... [--force <unit>]...
3286
+ ci transfer rollback --source-run <run-id> [--force]
3287
+ ci transfer runs [--limit <n>] [--run <run-id> [--report | --cancel | --resume | --purge]]
3288
+ (transfer prints JSON lines: progress, then one result or error; it also accepts [--backend-url <url>] [--organization <organization-id>] [--profile <name>])
3280
3289
  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] [--allow-admin-principals] [--timeout-ms <milliseconds>] [--non-interactive] [--json]
3281
3290
  ci deploy --backend-url <url> --organization <organization-id> --resume <receipt-file> [--timeout-ms <milliseconds>] [--json]
3282
3291
  ci deploy --declaration <module> --inputs-template (prints the Inputs File template: declared variables and connection slots; no Backend access)
@@ -3301,18 +3310,19 @@ Configuration (flag > environment > CLI Profile):
3301
3310
  CI_MANAGEMENT_TOKEN Management credential with the command's required permission; else the Profile CLI Session
3302
3311
  CI_BACKEND_URL Backend URL when --backend-url is absent; else the Profile API origin
3303
3312
  CI_PROFILE CLI Profile to use (or --profile <name>); default is the current Profile in $XDG_CONFIG_HOME/ci or ~/.config/ci
3304
- --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(nodePath6.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}
3305
- `)},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}
3313
+ --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(nodePath6.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)=>map5(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}
3314
+ `)},resolveDeclarationSpecifier:resolvedDeclarationSpecifier,startAssets:startViteDevelopmentAssetServer,terminateDevelopmentSession:flow((sessionId)=>suspend2(()=>awaitValue8(terminateDevelopmentSession(client,sessionId))).pipe(asVoid2),runNative),updateLocalManifest:flow((request)=>map5(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}
3306
3315
  `)}})}}).pipe(flatten4);class CliCommandError extends TaggedError3()("CliCommandError",{message:String5}){}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}
3307
3316
  `)}),runNative)});var renderPackageOperationResult=(result,adapters)=>{if(result.kind==="operation_accepted"){adapters.writeOutput(`Operation ID: ${result.operationId}
3308
3317
  `);return}adapters.writeOutput(`${JSON.stringify(result.snapshot)}
3309
- `);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([["api-keys",(args,environment,adapters)=>apiKeysCommandEffect(args,{...accessDependencies(environment,adapters),readEnvFile,writeEnvFile})],["apps",(args,environment,adapters)=>{const dependencies=accessDependencies(environment,adapters);if(args[0]==="credentials"){return appsCredentialsCommandEffect(args.slice(1),{...dependencies,readEnvFile,writeEnvFile})}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),readInputFile:(file)=>readFileSync9(file,"utf-8")})],["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(nodePath6.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(flatMap4((parsed)=>parsed.inputsTemplate?inputsTemplateEffect(parsed,output):resolveOrganizationContext({args:deployArgs,environment,fetch:adapters.fetch}).pipe(mapError2((cause)=>new DeployCommandError({cause,json,message:cause.message})),flatMap4((context)=>(parsed.resume===undefined?deploymentManagementClients({environment,fetch:adapters.fetch,target:context.target}):sync2(()=>{const organization=makeBackendManagementClient({backendUrl:context.target.apiOrigin,fetch:adapters.fetch,token:context.target.token});return{organization,publisher:organization}})).pipe(mapError2((cause)=>new DeployCommandError({cause,json,message:"ci deploy requires the CI_PUBLISHER_TOKEN credential"})),flatMap4((clients)=>deployCommandEffect({...parsed,organizationId:context.organizationId},{...clients,...output,prompt:adapters.prompt??promptStandardInput,recoveryDirectory:nodePath6.join(environment.XDG_STATE_HOME??nodePath6.join(environment.HOME??homedir(),".local","state"),"ci","deployments"),writeDiagnostic:adapters.writeDiagnostic??writeStandardError})))))),asVoid2)}if(group!=="package"||command===undefined){return fail6(new CliCommandError({message:usage6}))}if(command==="codegen"){return packageCodegenCommandEffect(options,{cwd:process.cwd,loadDeclarations:loadFreshPackageDeclarations,readFile:readFileIfPresent,rename:rename3,writeFile:flow((filePath,content)=>promise2(()=>Bun.write(filePath,content)).pipe(asVoid2),runNative),writeOutput:(value)=>{adapters.writeOutput(`${value}
3318
+ `);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([["api-keys",(args,environment,adapters)=>apiKeysCommandEffect(args,{...accessDependencies(environment,adapters),readEnvFile,writeEnvFile})],["apps",(args,environment,adapters)=>{const dependencies=accessDependencies(environment,adapters);if(args[0]==="credentials"){return appsCredentialsCommandEffect(args.slice(1),{...dependencies,readEnvFile,writeEnvFile})}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),readInputFile:(file)=>readFileSync9(file,"utf-8")})],["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(nodePath6.join(import.meta.dir,"..")),name,version},realPath:realPath2,runPackageManager:runPackageManager2,writeDiagnostic:adapters.writeDiagnostic??writeStandardError,writeOutput:adapters.writeOutput})}if(group==="transfer"){return transferCommandEffect(args.slice(1),{environment,fetch:adapters.fetch,files:bunTransferFiles,newArchiveId:()=>crypto.randomUUID(),signal:adapters.interrupt??new AbortController().signal,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(flatMap4((parsed)=>parsed.inputsTemplate?inputsTemplateEffect(parsed,output):resolveOrganizationContext({args:deployArgs,environment,fetch:adapters.fetch}).pipe(mapError2((cause)=>new DeployCommandError({cause,json,message:cause.message})),flatMap4((context)=>(parsed.resume===undefined?deploymentManagementClients({environment,fetch:adapters.fetch,target:context.target}):sync2(()=>{const organization=makeBackendManagementClient({backendUrl:context.target.apiOrigin,fetch:adapters.fetch,token:context.target.token});return{organization,publisher:organization}})).pipe(mapError2((cause)=>new DeployCommandError({cause,json,message:"ci deploy requires the CI_PUBLISHER_TOKEN credential"})),flatMap4((clients)=>deployCommandEffect({...parsed,organizationId:context.organizationId},{...clients,...output,prompt:adapters.prompt??promptStandardInput,recoveryDirectory:nodePath6.join(environment.XDG_STATE_HOME??nodePath6.join(environment.HOME??homedir(),".local","state"),"ci","deployments"),writeDiagnostic:adapters.writeDiagnostic??writeStandardError})))))),asVoid2)}if(group!=="package"||command===undefined){return fail6(new CliCommandError({message:usage6}))}if(command==="codegen"){return packageCodegenCommandEffect(options,{cwd:process.cwd,loadDeclarations:loadFreshPackageDeclarations,readFile:readFileIfPresent,rename:rename4,writeFile:flow((filePath,content)=>promise2(()=>Bun.write(filePath,content)).pipe(asVoid2),runNative),writeOutput:(value)=>{adapters.writeOutput(`${value}
3310
3319
  `)}})}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}
3311
- `)}})}}).pipe(flatten4,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(flatten4,tap2((releases)=>sync2(()=>{adapters.writeOutput(`${encodeJson4(releases)}
3312
- `)})),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(flatten4,tap2((diagnostic)=>sync2(()=>{adapters.writeOutput(`${encodeJson4(diagnostic)}
3313
- `)})),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(flatten4,tap2((operationId)=>sync2(()=>{adapters.writeOutput(`Operation ID: ${operationId}
3320
+ `)}})}}).pipe(flatten4,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(flatten4,tap2((releases)=>sync2(()=>{adapters.writeOutput(`${encodeJson5(releases)}
3321
+ `)})),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(flatten4,tap2((diagnostic)=>sync2(()=>{adapters.writeOutput(`${encodeJson5(diagnostic)}
3322
+ `)})),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)=>map5(suspend2(()=>awaitValue8(Bun.file(filePath).arrayBuffer())),(bytes)=>new Uint8Array(bytes)),runNative)})}}).pipe(flatten4,tap2((operationId)=>sync2(()=>{adapters.writeOutput(`Operation ID: ${operationId}
3314
3323
  `)})),asVoid2)};var renderCliCommandError=(error)=>{if((is2(PackageReleaseCommandError)(error)||is2(DeployCommandError)(error))&&is2(packagePreflightDiagnostic)(error.cause)){return`${error.message}: ${error.cause.diagnostic.message}`}return is2(DeployCommandError)(error)&&error.recoveryFile!==undefined?`${error.message}; recovery file: ${error.recoveryFile}`:error.message};var writeCliCommandError=(error,adapters=defaultCliAdapters)=>{const writeDiagnostic=adapters.writeDiagnostic??writeStandardError;if(is2(OrgsCommandError)(error)&&error.outcome!==undefined){const{outcome}=error;if(error.json===true){adapters.writeOutput(`${JSON.stringify(outcome)}
3315
3324
  `)}else{const next="nextAction"in outcome?`; ${outcome.nextAction}`:"";writeDiagnostic(`${outcome.error}${next}
3316
- `)}return}if(is2(DeployCommandError)(error)&&error.json){const record={kind:"error",lastEventId:error.lastEventId,message:renderCliCommandError(error),nextAction:error.nextAction,operationId:error.operationId,recoveryFile:error.recoveryFile,status:error.status??"failed"};adapters.writeOutput(`${JSON.stringify(record)}
3325
+ `)}return}if(is2(TransferCommandError)(error)){const record={archiveId:error.archiveId,code:error.code,kind:"error",message:error.message,nextAction:error.nextAction,runId:error.runId,status:error.status};adapters.writeOutput(`${JSON.stringify(record)}
3326
+ `);return}if(is2(DeployCommandError)(error)&&error.json){const record={kind:"error",lastEventId:error.lastEventId,message:renderCliCommandError(error),nextAction:error.nextAction,operationId:error.operationId,recoveryFile:error.recoveryFile,status:error.status??"failed"};adapters.writeOutput(`${JSON.stringify(record)}
3317
3327
  `)}else{writeDiagnostic(`${renderCliCommandError(error)}
3318
- `)}};if(import.meta.main){const run=cliEffect(Bun.argv.slice(2)).pipe(catch_2((error)=>sync2(()=>{writeCliCommandError(error);process.exitCode=1})));runPromise2(run)}export{cliEffect,renderCliCommandError,writeCliCommandError};
3328
+ `)}};var INTERRUPTED_EXIT_CODE=130;var exitCodeOf=(error)=>is2(TransferCommandError)(error)&&error.code===interruptedCode?INTERRUPTED_EXIT_CODE:1;if(import.meta.main){const interrupt=new AbortController;process.once("SIGINT",()=>{interrupt.abort()});const run=cliEffect(Bun.argv.slice(2),Bun.env,{...defaultCliAdapters,interrupt:interrupt.signal}).pipe(catch_2((error)=>sync2(()=>{writeCliCommandError(error);process.exitCode=exitCodeOf(error)})));runPromise2(run)}export{cliEffect,exitCodeOf,renderCliCommandError,writeCliCommandError};