@collective-intelligence/cli 0.1.1 → 0.1.2

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 +64 -5
  2. package/dist/cli.js +36 -20
  3. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -195,7 +195,7 @@ ${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 ${Broker2.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,head2)=>{if(req.url){const{pathname}=parse4(req.url);if(pathname==="/")this._webSocketServer?.handleUpgrade(req,socket,head2,(ws)=>{this._webSocketServer?.emit("connection",ws,req)})}});server.listen(Broker2.DEFAULT_WEB_SOCKET_PORT)}async _takeAction(action,client2){const{kind,payload}=action;if(kind===ActionKind.ADD_PUBLISHER)await this._addPublisher(payload,client2);if(kind===ActionKind.UPDATE_PUBLISHER)await this._updatePublisher(payload,client2);if(kind===ActionKind.ADD_SUBSCRIBER)await this._addSubscriber(payload,client2);if(kind===ActionKind.EXIT_SUBSCRIBER)await this._removeSubscriber(payload,client2);if(kind===ActionKind.EXIT_PUBLISHER)await this._removePublisher(payload,client2);if(kind===ActionKind.ADD_WEB_CLIENT)await this._addWebClient(payload,client2);if(kind===ActionKind.NOTIFY_WEB_CLIENT)await this._notifyWebClient(payload,client2);if(kind===ActionKind.FETCH_TYPES)await this._fetchTypes(payload,client2);if(kind===ActionKind.ADD_DYNAMIC_REMOTE)this._addDynamicRemote(payload)}async _addPublisher(context3,client2){const{name,ip,remoteTypeTarPath}=context3??{};const identifier3=getIdentifier({name,ip});if(this._publisherMap.has(identifier3)){fileLog(`[${ActionKind.ADD_PUBLISHER}] ${identifier3} has been added, this action will be ignored`,"Broker","warn");return}try{const publisher=new Publisher({name,ip,remoteTypeTarPath,ws:client2});this._publisherMap.set(identifier3,publisher);fileLog(`[${ActionKind.ADD_PUBLISHER}] ${identifier3} Adding Publisher Succeed`,"Broker","info");const tmpSubScribers=this._getTmpSubScribers(identifier3);if(tmpSubScribers){fileLog(`[${ActionKind.ADD_PUBLISHER}] consumeTmpSubscriber set ${publisher.name}\u2019s subscribers `,"Broker","info");this._consumeTmpSubScribers(publisher,tmpSubScribers);this._clearTmpSubScriberRelation(identifier3)}}catch(err){const msg=error2(err,ActionKind.ADD_PUBLISHER,"Broker");client2.send(msg);client2.close()}}async _updatePublisher(context3,client2){const{name,updateMode:updateMode2,updateKind,updateSourcePaths,remoteTypeTarPath,ip}=context3??{};const identifier3=getIdentifier({name,ip});if(!this._publisherMap.has(identifier3)){fileLog(`[${ActionKind.UPDATE_PUBLISHER}] ${identifier3} 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(identifier3);fileLog(`[${ActionKind.UPDATE_PUBLISHER}] ${identifier3} update, and notify subscribers to update`,"Broker","info");if(publisher){publisher.notifySubscribers({remoteTypeTarPath,name,updateMode:updateMode2,updateKind,updateSourcePaths:updateSourcePaths||[]});this._publisherMap.forEach((p)=>{if(p.name===publisher.name)return;const dynamicRemoteInfo=p.dynamicRemoteMap.get(identifier3);if(dynamicRemoteInfo){fileLog(`dynamicRemoteInfo: ${JSON.stringify(dynamicRemoteInfo)}, identifier:${identifier3} publish: ${p.name}`,"Broker","info");p.fetchRemoteTypes({remoteInfo:dynamicRemoteInfo,once:false})}})}}catch(err){const msg=error2(err,ActionKind.UPDATE_PUBLISHER,"Broker");client2.send(msg);client2.close()}}async _fetchTypes(context3,_client){const{name,ip,remoteInfo}=context3??{};const identifier3=getIdentifier({name,ip});try{const publisher=this._publisherMap.get(identifier3);fileLog(`[${ActionKind.FETCH_TYPES}] ${identifier3} fetch types`,"Broker","info");if(publisher)publisher.fetchRemoteTypes({remoteInfo,once:true})}catch(err){fileLog(`[${ActionKind.FETCH_TYPES}] ${identifier3} fetch types fail , error info: ${err}`,"Broker","error")}}_addDynamicRemote(context3){const{name,ip,remoteInfo,remoteIp}=context3??{};const identifier3=getIdentifier({name,ip});const publisher=this._publisherMap.get(identifier3);const remoteId=getIdentifier({name:remoteInfo.name,ip:remoteIp});fileLog(`[${ActionKind.ADD_DYNAMIC_REMOTE}] identifier:${identifier3},publisher: ${publisher.name}, remoteId:${remoteId}`,"Broker","error");if(!publisher||publisher.dynamicRemoteMap.has(remoteId))return;publisher.dynamicRemoteMap.set(remoteId,remoteInfo)}async _addSubscriber(context3,client2){const{publishers,name:subscriberName}=context3??{};publishers.forEach((publisher)=>{const{name,ip}=publisher;const identifier3=getIdentifier({name,ip});if(!this._publisherMap.has(identifier3)){fileLog(`[${ActionKind.ADD_SUBSCRIBER}]: ${identifier3} has not been started, ${subscriberName} will add the relation to tmp shelter`,"Broker","warn");this._addTmpSubScriberRelation({name:getIdentifier({name:context3.name,ip:context3.ip}),client:client2},publisher);return}try{const registeredPublisher=this._publisherMap.get(identifier3);if(registeredPublisher){registeredPublisher.addSubscriber(getIdentifier({name:subscriberName,ip:context3.ip}),client2);fileLog(`[${ActionKind.ADD_SUBSCRIBER}]: ${identifier3} 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:context3.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=error2(err,ActionKind.ADD_SUBSCRIBER,"Broker");client2.send(msg);client2.close()}})}async _removeSubscriber(context3,client2){const{publishers}=context3??{};const subscriberIdentifier=getIdentifier({name:context3?.name,ip:context3?.ip});publishers.forEach((publisher)=>{const{name,ip}=publisher;const identifier3=getIdentifier({name,ip});const registeredPublisher=this._publisherMap.get(identifier3);if(!registeredPublisher){fileLog(`[${ActionKind.EXIT_SUBSCRIBER}], ${identifier3} does not exit `,"Broker","warn");return}try{fileLog(`[${ActionKind.EXIT_SUBSCRIBER}], ${identifier3} will exit `,"Broker","INFO");registeredPublisher.removeSubscriber(subscriberIdentifier);this._clearTmpSubScriberRelation(identifier3);if(!registeredPublisher.hasSubscribes)this._publisherMap.delete(identifier3);if(!this.hasPublishers)this.exit()}catch(err){const msg=error2(err,ActionKind.EXIT_SUBSCRIBER,"Broker");client2.send(msg);client2.close()}})}async _removePublisher(context3,client2){const{name,ip}=context3??{};const identifier3=getIdentifier({name,ip});const publisher=this._publisherMap.get(identifier3);if(!publisher){fileLog(`[${ActionKind.EXIT_PUBLISHER}]: ${identifier3}} 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}]: ${identifier3} is removing , subscriber: ${subscriberIdentifier} will be add tmpSubScriberRelation`,"Broker","info")});this._publisherMap.delete(identifier3);fileLog(`[${ActionKind.EXIT_PUBLISHER}]: ${identifier3} 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=error2(err,ActionKind.EXIT_PUBLISHER,"Broker");client2.send(msg);client2.close()}}async _addWebClient(context3,client2){const{name}=context3??{};const identifier3=getIdentifier({name});if(this._webClientMap.has(identifier3))fileLog(`${identifier3}} has been added, this action will override prev WebClient`,"Broker","warn");try{this._webClientMap.set(identifier3,client2);fileLog(`${identifier3} adding WebClient Succeed`,"Broker","info")}catch(err){const msg=error2(err,ActionKind.ADD_WEB_CLIENT,"Broker");client2.send(msg);client2.close()}}async _notifyWebClient(context3,client2){const{name,updateMode:updateMode2}=context3??{};const identifier3=getIdentifier({name});const webClient=this._webClientMap.get(identifier3);if(!webClient){fileLog(`[${ActionKind.NOTIFY_WEB_CLIENT}] ${identifier3} has not been added, this action will be ignored`,"Broker","warn");return}try{const api=new ReloadWebClientAPI({name,updateMode:updateMode2});webClient.send(JSON.stringify(api));fileLog(`[${ActionKind.NOTIFY_WEB_CLIENT}] Notify ${name} WebClient Succeed`,"Broker","info")}catch(err){const msg=error2(err,ActionKind.NOTIFY_WEB_CLIENT,"Broker");client2.send(msg);client2.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 map8=new Map;map8.set(subscriberIdentifier,subscriber);this._tmpSubscriberShelter.set(publisherIdentifier,{subscribers:map8,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,identifier3)=>{fileLog(`notifyTmpSubScribers ${publisher.name} will be add a subscriber: ${identifier3} `,"Broker","warn");publisher.addSubscriber(identifier3,tmpSubScriber.client);publisher.notifySubscriber(identifier3,{updateKind:UpdateKind.UPDATE_TYPE,updateMode:UpdateMode.PASSIVE,updateSourcePaths:[publisher.name],remoteTypeTarPath:publisher.remoteTypeTarPath,name:publisher.name})})}_clearTmpSubScriberRelation(identifier3){this._tmpSubscriberShelter.delete(identifier3)}_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,identifier3)=>{fileLog(` _clearTmpSubScriberRelation ${identifier3}, ${Date.now()-tmpSubscriber.timestamp>=(process.env["GARFISH_MODULE_SERVER_TEST"]?serverTest:Broker2.DEFAULT_WAITING_TIME)}`,"Broker","info");if(Date.now()-tmpSubscriber.timestamp>=(process.env["FEDERATION_SERVER_TEST"]?serverTest:Broker2.DEFAULT_WAITING_TIME))this._clearTmpSubScriberRelation(identifier3)})},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",(error3)=>{console.error("Unhandled Rejection Error: ",error3);fileLog(`Unhandled Rejection Error: ${error3}`,"Broker","fatal");process.exit(1)});process.on("uncaughtException",(error3)=>{console.error("Unhandled Exception Error: ",error3);fileLog(`Unhandled Rejection Error: ${error3}`,"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((client2)=>{client2.send(JSON.stringify(message))});this._secureWebSocketServer?.clients.forEach((client2)=>{client2.send(JSON.stringify(message))})}}});import node_fs from"fs";import node_path from"path";function findPackageJson(startPath){let currentPath=node_path.resolve(startPath);while(true){const packageJsonPath=node_path.join(currentPath,"package.json");if(node_fs.existsSync(packageJsonPath)){return packageJsonPath}const parentPath=node_path.dirname(currentPath);if(parentPath===currentPath){return}currentPath=parentPath}}var init_findPackageJson=()=>{};import path4 from"path";import fs from"fs";class PKGJsonManager{setPKGJson(pkg){this._pkg=pkg}readPKGJson(root=process.cwd()){if(this._pkg){return this._pkg}try{const pkg=JSON.parse(fs.readFileSync(path4.resolve(root,"package.json"),"utf8"));this._pkg=pkg;return pkg}catch(_err){try{const pkgPath=findPackageJson(root);if(!pkgPath){return{}}const pkg=JSON.parse(fs.readFileSync(pkgPath,"utf8"));this._pkg=pkg;return pkg}catch(err){logger.error(err);return{}}}}getExposeGarfishModuleType(root=process.cwd()){const pkg=this.readPKGJson(root);return pkg?.["mf"]?.type===MFModuleType.NPM?MFModuleType.NPM:MFModuleType.APP}}var init_PKGJsonManager=__esm(()=>{init_dist();init_findPackageJson()});var LOCAL_BUILD_VERSION="local";var init_constant2=()=>{};var exports_utils={};__export(exports_utils,{parseOptions:()=>parseOptions2,getBuildVersion:()=>getBuildVersion,getBuildName:()=>getBuildName});function processFn(options,normalizeSimple,normalizeOptions2,fn3){const object2=(obj)=>{for(const[key,value3]of Object.entries(obj)){if(typeof value3==="string"){fn3(key,normalizeSimple(value3,key))}else{fn3(key,normalizeOptions2(value3,key))}}};const array3=(items)=>{for(const item of items){if(typeof item==="string"){fn3(item,normalizeSimple(item,item))}else if(item&&typeof item==="object"){object2(item)}else{throw new Error("Unexpected options format")}}};if(!options){return}else if(Array.isArray(options)){array3(options)}else if(typeof options==="object"){object2(options)}else{throw new Error("Unexpected options format")}}function parseOptions2(options,normalizeSimple,normalizeOptions2){const items=[];processFn(options,normalizeSimple,normalizeOptions2,(key,value3)=>{items.push([key,value3])});return items}function getBuildVersion(root){if(process.env["MF_BUILD_VERSION"]){return process.env["MF_BUILD_VERSION"]}const pkg=new PKGJsonManager().readPKGJson(root);if(pkg?.["version"]&&typeof pkg["version"]==="string"){return pkg["version"]}return LOCAL_BUILD_VERSION}function getBuildName(){return process.env["MF_BUILD_NAME"]}var init_utils2=__esm(()=>{init_PKGJsonManager();init_constant2()});var init_dist2=__esm(()=>{init_utils2()});import{copyFile as copyFile3,lstat,mkdir as mkdir2,readdir}from"fs/promises";import{existsSync as existsSync4,readFileSync as readFileSync3}from"fs";import path22 from"path";import path5 from"path";import fs2 from"fs";function getTypedName(name){return`@types/${name.replace(/^@/,"").replace("/","__")}`}function getPackageRootDir(packageName,context3=process.cwd()){if(!packageName){throw new Error("No package name provided.")}const entryFile=__require2.resolve(packageName,{paths:[context3]});const entryDir=path5.dirname(entryFile);let fallbackPackageJsonPath=path5.join(entryDir,"package.json");if(!fs2.existsSync(fallbackPackageJsonPath)){fallbackPackageJsonPath=null}const match5=packageName.match(/^@[^/]+\/(.+)$/);const localName=match5?match5[1]:packageName;let currentDir=entryDir;while(path5.basename(currentDir)!==localName&&path5.dirname(currentDir)!==currentDir){try{currentDir=path5.dirname(currentDir)}catch(err){if(err.code==="EACCES"){continue}else{throw err}}}if(path5.basename(currentDir)===localName){const candidate=path5.join(currentDir,"package.json");if(fs2.existsSync(candidate)){const pkgContent=JSON.parse(fs2.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,context3){try{return __require2.resolve(`${packageName}/package.json`,{paths:[context3]})}catch(e){let currentPath=path5.resolve(context3);while(true){const candidate=path5.join(currentPath,"node_modules",packageName,"package.json");if(fs2.existsSync(candidate)){return candidate}const parentPath=path5.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:context3=process.cwd(),exclude=[]}){this.destDir=destDir;this.context=context3;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(readFileSync3(pkgJsonPath,"utf-8"));const types2=pkg.types||pkg.typings;if(dir===this.context){return}if(types2){const typesDir=path22.dirname(path22.resolve(dir,types2));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);readFileSync3(typedPkgJsonPath,"utf-8");this.addPkgs(typedPkgName,typedDir);return typedDir}}catch(_err){return}}collectTypeImports(str){const{pattern}=this;let match5;const imports=new Set;while((match5=pattern.exec(str))!==null){imports.add(match5[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((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((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 E2(message){return function(...args2){if(args2.length){message=message.replace(/\{(\d)\}/g,(_,n2)=>args2[n2]||"")}return new Error("ADM-ZIP: "+message)}}for(const msg of Object.keys(errors)){exports[msg]=E2(errors[msg])}});var require_utils=__commonJS((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 mkdirSync3(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 stat3;try{stat3=self.fs.statSync(resolvedPath)}catch(e){if(e.message&&e.message.startsWith("ENOENT")){self.fs.mkdirSync(resolvedPath)}else{throw e}}if(stat3&&stat3.isFile())throw Errors.FILE_IN_THE_WAY(`"${resolvedPath}"`)})}mkdirSync3(folder)};Utils.prototype.writeFileTo=function(path6,content,overwrite,attr){const self=this;if(self.fs.existsSync(path6)){if(!overwrite)return false;var stat3=self.fs.statSync(path6);if(stat3.isDirectory()){return false}}var folder=pth.dirname(path6);if(!self.fs.existsSync(folder)){self.makeDir(folder)}var fd;try{fd=self.fs.openSync(path6,"w",438)}catch(e){self.fs.chmodSync(path6,438);fd=self.fs.openSync(path6,"w",438)}if(fd){try{self.fs.writeSync(fd,content,0,content.length,0)}finally{self.fs.closeSync(fd)}}self.fs.chmodSync(path6,attr||438);return true};Utils.prototype.writeFileToAsync=function(path6,content,overwrite,attr,callback4){if(typeof attr==="function"){callback4=attr;attr=undefined}const self=this;self.fs.exists(path6,function(exist){if(exist&&!overwrite)return callback4(false);self.fs.stat(path6,function(err,stat3){if(exist&&stat3&&stat3.isDirectory()){return callback4(false)}var folder=pth.dirname(path6);self.fs.exists(folder,function(exists){if(!exists){try{self.makeDir(folder)}catch(e){return callback4(false)}}const writeToFd=function(fd){self.fs.write(fd,content,0,content.length,0,function(writeErr){self.fs.close(fd,function(){if(writeErr)return callback4(false);self.fs.chmod(path6,attr||438,function(){callback4(true)})})})};self.fs.open(path6,"w",438,function(err2,fd){if(err2){self.fs.chmod(path6,438,function(){self.fs.open(path6,"w",438,function(retryErr,fd2){if(retryErr||!fd2)return callback4(false);writeToFd(fd2)})})}else if(fd){writeToFd(fd)}else{callback4(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 stat3;try{stat3=self.fs.lstatSync(cur)}catch(e){break}if(stat3.isSymbolicLink())throw Errors.FILE_IN_THE_WAY(`"${cur}"`)}};Utils.prototype.findFiles=function(path6){const self=this;const canLstat=typeof self.fs.lstatSync==="function";const rootReal=self.fs.realpathSync(path6);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 path7=pth.join(dir,file);if(escapesRoot(path7))return;const stat3=self.fs.statSync(path7);if(!pattern||pattern.test(path7)){files.push(pth.normalize(path7)+(stat3.isDirectory()?self.sep:""))}if(stat3.isDirectory()&&recursive){const realDir=self.fs.realpathSync(path7);if(!visited.has(realDir)){visited.add(realDir);files=files.concat(findSync(path7,pattern,recursive,visited))}}});return files}return findSync(path6,undefined,true,new Set([rootReal]))};Utils.prototype.findFilesAsync=function(dir,cb){const self=this;const results2=[];let finished=false;const finish=function(err){if(finished)return;finished=true;cb(err,err?undefined:results2)};const canLstat=typeof self.fs.lstat==="function";let rootReal=null;const escapesRoot=function(file,cb2){if(!canLstat)return cb2(null,false);self.fs.lstat(file,function(err,lst){if(err)return cb2(err);if(!lst||!lst.isSymbolicLink())return cb2(null,false);self.fs.realpath(file,function(err2,real){if(err2)return cb2(null,true);cb2(null,!(real===rootReal||real.startsWith(rootReal+pth.sep)))})})};const walk=function(dir2,visited,done3){self.fs.readdir(dir2,function(err,list2){if(err)return done3(err);let pending=list2.length;if(!pending)return done3();list2.forEach(function(name){const file=pth.join(dir2,name);escapesRoot(file,function(err2,escapes){if(err2)return done3(err2);if(escapes){if(!--pending)done3();return}self.fs.stat(file,function(err3,stat3){if(err3)return done3(err3);if(!stat3){if(!--pending)done3();return}results2.push(pth.normalize(file)+(stat3.isDirectory()?self.sep:""));if(!stat3.isDirectory()){if(!--pending)done3();return}self.fs.realpath(file,function(err4,realDir){if(err4)return done3(err4);if(visited.has(realDir)){if(!--pending)done3();return}visited.add(realDir);walk(file,visited,function(err5){if(err5)return done3(err5);if(!--pending)done3()})})})})})})};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(path6){if(!path6)return"";const safeSuffix=pth.posix.normalize("/"+path6.split("\\").join("/"));return pth.join(".",safeSuffix)};Utils.zipnamefix=function(path6){if(!path6)return"";const safeSuffix=pth.posix.normalize("/"+path6.split("\\").join("/"));return pth.posix.join(".",safeSuffix)};Utils.findLast=function(arr,callback4){if(!Array.isArray(arr))throw new TypeError("arr is not array");const len=arr.length>>>0;for(let i2=len-1;i2>=0;i2--){if(callback4(arr[i2],i2,arr)){return arr[i2]}}return};Utils.sanitize=function(prefix,name){prefix=pth.resolve(pth.normalize(prefix));var parts2=name.split("/");for(var i2=0,l=parts2.length;i2<l;i2++){var path6=pth.normalize(pth.join(prefix,parts2.slice(i2,l).join(pth.sep)));if(path6===prefix||path6.startsWith(prefix+pth.sep)){return path6}}return pth.normalize(pth.join(prefix,pth.basename(name)))};Utils.toBuffer=function toBuffer(input,encoder3){if(Buffer.isBuffer(input)){return input}else if(input instanceof Uint8Array){return Buffer.from(input)}else{return typeof input==="string"?encoder3(input):Buffer.alloc(0)}};Utils.readBigUInt64LE=function(buffer2,index){const lo=buffer2.readUInt32LE(index);const hi=buffer2.readUInt32LE(index+4);const value3=hi*4294967296+lo;if(value3>Number.MAX_SAFE_INTEGER){throw Errors.ZIP64_VALUE_TOO_LARGE()}return value3};Utils.writeBigUInt64LE=function(buffer2,value3,index){const lo=value3>>>0;const hi=Math.floor(value3/4294967296)>>>0;buffer2.writeUInt32LE(lo,index);buffer2.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((exports,module)=>{var pth=__require("path");module.exports=function(path6,{fs:fs3}){var _path=path6||"",_obj=newAttr(),_stat=null;function newAttr(){return{directory:false,readonly:false,hidden:false,executable:false,mtime:0,atime:0}}if(_path&&fs3.existsSync(_path)){_stat=fs3.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((exports,module)=>{module.exports={efs:true,encode:(data2)=>Buffer.from(data2,"utf8"),decode:(data2)=>data2.toString("utf8")}});var require_util=__commonJS((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((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 data2=input.slice(_offset,_offset+Constants.LOCHDR);if(data2.readUInt32LE(0)!==Constants.LOCSIG){throw Utils.Errors.INVALID_LOC()}_localHeader.version=data2.readUInt16LE(Constants.LOCVER);_localHeader.flags=data2.readUInt16LE(Constants.LOCFLG);_localHeader.flags_desc=(_localHeader.flags&Constants.FLG_DESC)>0;_localHeader.method=data2.readUInt16LE(Constants.LOCHOW);_localHeader.time=data2.readUInt32LE(Constants.LOCTIM);_localHeader.crc=data2.readUInt32LE(Constants.LOCCRC);_localHeader.compressedSize=data2.readUInt32LE(Constants.LOCSIZ);_localHeader.size=data2.readUInt32LE(Constants.LOCLEN);_localHeader.fnameLen=data2.readUInt16LE(Constants.LOCNAM);_localHeader.extraLen=data2.readUInt16LE(Constants.LOCEXT);const extraStart=_offset+Constants.LOCHDR+_localHeader.fnameLen;const extraEnd=extraStart+_localHeader.extraLen;return input.slice(extraStart,extraEnd)},loadFromBinary:function(data2){if(data2.length!==Constants.CENHDR||data2.readUInt32LE(0)!==Constants.CENSIG){throw Utils.Errors.INVALID_CEN()}_verMade=data2.readUInt16LE(Constants.CENVEM);_version=data2.readUInt16LE(Constants.CENVER);_flags=data2.readUInt16LE(Constants.CENFLG);_method=data2.readUInt16LE(Constants.CENHOW);_time=data2.readUInt32LE(Constants.CENTIM);_crc=data2.readUInt32LE(Constants.CENCRC);_compressedSize=data2.readUInt32LE(Constants.CENSIZ);_size=data2.readUInt32LE(Constants.CENLEN);_fnameLen=data2.readUInt16LE(Constants.CENNAM);_extraLen=data2.readUInt16LE(Constants.CENEXT);_comLen=data2.readUInt16LE(Constants.CENCOM);_diskStart=data2.readUInt16LE(Constants.CENDSK);_inattr=data2.readUInt16LE(Constants.CENATT);_attr=data2.readUInt32LE(Constants.CENATX);_offset=data2.readUInt32LE(Constants.CENOFF)},localHeaderToBinary:function(){var data2=Buffer.alloc(Constants.LOCHDR);data2.writeUInt32LE(Constants.LOCSIG,0);data2.writeUInt16LE(_version,Constants.LOCVER);data2.writeUInt16LE(_flags&~Constants.FLG_DESC,Constants.LOCFLG);data2.writeUInt16LE(_method,Constants.LOCHOW);data2.writeUInt32LE(_time,Constants.LOCTIM);data2.writeUInt32LE(_crc,Constants.LOCCRC);data2.writeUInt32LE(_compressedSize,Constants.LOCSIZ);data2.writeUInt32LE(_size,Constants.LOCLEN);data2.writeUInt16LE(_fnameLen,Constants.LOCNAM);data2.writeUInt16LE(_localHeader.extraLen,Constants.LOCEXT);return data2},centralHeaderToBinary:function(){var data2=Buffer.alloc(Constants.CENHDR+_fnameLen+_extraLen+_comLen);data2.writeUInt32LE(Constants.CENSIG,0);data2.writeUInt16LE(_verMade,Constants.CENVEM);data2.writeUInt16LE(_version,Constants.CENVER);data2.writeUInt16LE(_flags&~Constants.FLG_DESC,Constants.CENFLG);data2.writeUInt16LE(_method,Constants.CENHOW);data2.writeUInt32LE(_time,Constants.CENTIM);data2.writeUInt32LE(_crc,Constants.CENCRC);data2.writeUInt32LE(_compressedSize,Constants.CENSIZ);data2.writeUInt32LE(_size,Constants.CENLEN);data2.writeUInt16LE(_fnameLen,Constants.CENNAM);data2.writeUInt16LE(_extraLen,Constants.CENEXT);data2.writeUInt16LE(_comLen,Constants.CENCOM);data2.writeUInt16LE(_diskStart,Constants.CENDSK);data2.writeUInt16LE(_inattr,Constants.CENATT);data2.writeUInt32LE(_attr,Constants.CENATX);data2.writeUInt32LE(_offset,Constants.CENOFF);return data2},toJSON:function(){const bytes2=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:bytes2(_compressedSize),size:bytes2(_size),fileNameLength:bytes2(_fnameLen),extraLength:bytes2(_extraLen),commentLength:bytes2(_comLen),diskNumStart:_diskStart,inAttr:_inattr,attr:_attr,offset:_offset,centralHeaderSize:bytes2(Constants.CENHDR+_fnameLen+_extraLen+_comLen)}},toString:function(){return JSON.stringify(this.toJSON(),null,"\t")}}}});var require_mainHeader=__commonJS((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(data2){if((data2.length!==Constants.ENDHDR||data2.readUInt32LE(0)!==Constants.ENDSIG)&&(data2.length<Constants.ZIP64HDR||data2.readUInt32LE(0)!==Constants.ZIP64SIG)){throw Utils.Errors.INVALID_END()}if(data2.readUInt32LE(0)===Constants.ENDSIG){_volumeEntries=data2.readUInt16LE(Constants.ENDSUB);_totalEntries=data2.readUInt16LE(Constants.ENDTOT);_size=data2.readUInt32LE(Constants.ENDSIZ);_offset=data2.readUInt32LE(Constants.ENDOFF);_commentLength=data2.readUInt16LE(Constants.ENDCOM)}else{_volumeEntries=Utils.readBigUInt64LE(data2,Constants.ZIP64SUB);_totalEntries=Utils.readBigUInt64LE(data2,Constants.ZIP64TOT);_size=Utils.readBigUInt64LE(data2,Constants.ZIP64SIZB);_offset=Utils.readBigUInt64LE(data2,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 offset2=0;b.writeUInt32LE(Constants.ZIP64SIG,offset2);Utils.writeBigUInt64LE(b,Constants.ZIP64HDR-Constants.ZIP64LEAD,offset2+Constants.ZIP64SIZE);b.writeUInt16LE(45,offset2+Constants.ZIP64VEM);b.writeUInt16LE(45,offset2+Constants.ZIP64VER);b.writeUInt32LE(0,offset2+Constants.ZIP64DSK);b.writeUInt32LE(0,offset2+Constants.ZIP64DSKDIR);Utils.writeBigUInt64LE(b,_volumeEntries,offset2+Constants.ZIP64SUB);Utils.writeBigUInt64LE(b,_totalEntries,offset2+Constants.ZIP64TOT);Utils.writeBigUInt64LE(b,_size,offset2+Constants.ZIP64SIZB);Utils.writeBigUInt64LE(b,_offset,offset2+Constants.ZIP64OFF);const zip64EndOffset=_offset+_size;offset2+=Constants.ZIP64HDR;b.writeUInt32LE(Constants.END64SIG,offset2);b.writeUInt32LE(0,offset2+Constants.END64START);Utils.writeBigUInt64LE(b,zip64EndOffset,offset2+Constants.END64OFF);b.writeUInt32LE(1,offset2+Constants.END64NUMDISKS);offset2+=Constants.END64HDR;b.writeUInt32LE(Constants.ENDSIG,offset2);b.writeUInt32LE(0,offset2+4);b.writeUInt16LE(Math.min(_volumeEntries,Constants.EF_ZIP64_OR_16),offset2+Constants.ENDSUB);b.writeUInt16LE(Math.min(_totalEntries,Constants.EF_ZIP64_OR_16),offset2+Constants.ENDTOT);b.writeUInt32LE(Math.min(_size,Constants.EF_ZIP64_OR_32),offset2+Constants.ENDSIZ);b.writeUInt32LE(Math.min(_offset,Constants.EF_ZIP64_OR_32),offset2+Constants.ENDOFF);b.writeUInt16LE(_commentLength,offset2+Constants.ENDCOM);b.fill(" ",offset2+Constants.ENDHDR);return b},toJSON:function(){const offset2=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:offset2(_offset,4),commentLength:_commentLength}},toString:function(){return JSON.stringify(this.toJSON(),null,"\t")}}}});var require_headers=__commonJS((exports)=>{exports.EntryHeader=require_entryHeader();exports.MainHeader=require_mainHeader()});var require_deflater=__commonJS((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(callback4){var tmp=zlib.createDeflateRaw(opts),parts2=[],total=0;tmp.on("data",function(data2){parts2.push(data2);total+=data2.length});tmp.on("end",function(){var buf=Buffer.alloc(total),written=0;buf.fill(0);for(var i2=0;i2<parts2.length;i2++){var part=parts2[i2];part.copy(buf,written);written+=part.length}callback4&&callback4(buf)});tmp.end(inbuf)}}}});var require_inflater=__commonJS((exports,module)=>{var version3=+(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 option2=version3>=15?{maxOutputLength}:{};return{inflate:function(){return zlib.inflateRawSync(inbuf,option2)},inflateAsync:function(callback4){var tmp=zlib.createInflateRaw(option2),parts2=[],total=0,done3=false;const fail12=function(err){if(done3)return;done3=true;tmp.destroy();callback4&&callback4(Buffer.alloc(0),err)};tmp.on("error",function(err){fail12(err)});tmp.on("data",function(data2){if(done3)return;total+=data2.length;if(total>maxOutputLength){return fail12(Errors.MAX_OUTPUT_EXCEEDED())}parts2.push(data2)});tmp.on("end",function(){if(done3)return;done3=true;var buf=Buffer.alloc(total),written=0;buf.fill(0);for(var i2=0;i2<parts2.length;i2++){var part=parts2[i2];part.copy(buf,written);written+=part.length}callback4&&callback4(buf)});tmp.end(inbuf)}}}});var require_zipcrypto=__commonJS((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 i2=0;i2<len;i2++)salt[i2]=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 i2=0;i2<pass.length;i2++){this.updateKeys(pass[i2])}}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(data2){const result3=Buffer.alloc(data2.length);let pos=0;for(let c of data2){result3[pos++]=keys.updateKeys(c^keys.next())}return result3}}function make_encrypter(pwd){const keys=new Initkeys(pwd);return function(data2,result3,pos=0){if(!result3)result3=Buffer.alloc(data2.length);for(let c of data2){const k=keys.next();result3[pos++]=c^k;keys.updateKeys(c)}return result3}}function decrypt(data2,header,pwd){if(!data2||!Buffer.isBuffer(data2)||data2.length<12){return Buffer.alloc(0)}const decrypter=make_decrypter(pwd);const salt=decrypter(data2.slice(0,12));const verifyByte=(header.flags&8)===8?header.timeHighByte:header.crc>>>24;if(salt[11]!==verifyByte){throw Errors.WRONG_PASSWORD()}return decrypter(data2.slice(12))}function _salter(data2){if(Buffer.isBuffer(data2)&&data2.length>=12){config.genSalt=function(){return data2.slice(0,12)}}else if(data2==="node"){config.genSalt=genSalt.node}else{config.genSalt=genSalt}}function encrypt(data2,header,pwd,oldlike=false){if(data2==null)data2=Buffer.alloc(0);if(!Buffer.isBuffer(data2))data2=Buffer.from(data2.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 result3=Buffer.alloc(data2.length+12);encrypter(salt,result3);return encrypter(data2,result3,12)}module.exports={decrypt,encrypt,_salter}});var require_methods=__commonJS((exports)=>{exports.Deflater=require_deflater();exports.Inflater=require_inflater();exports.ZipCrypto=require_zipcrypto()});var require_zipEntry=__commonJS((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 decoder3=typeof opts.decoder==="object"?opts.decoder:Utils.decoder;_efs=decoder3.hasOwnProperty("efs")?decoder3.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(data2){const expectedCrc=_centralHeader.flags_desc||_centralHeader.localHeader.flags_desc?_centralHeader.crc:_centralHeader.localHeader.crc;return Utils.crc32(data2)===expectedCrc}function decompress(async,callback4,pass){if(typeof callback4==="undefined"&&typeof async==="string"){pass=async;async=undefined}if(_isDirectory){if(async&&callback4){callback4(Buffer.alloc(0),Utils.Errors.DIRECTORY_CONTENT_ERROR())}return Buffer.alloc(0)}var compressedData;try{compressedData=getCompressedDataFromZip();if(compressedData.length===0){if(async&&callback4)callback4(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&&callback4){callback4(Buffer.alloc(0),err);return Buffer.alloc(0)}throw err}var data2;switch(_centralHeader.method){case Utils.Constants.STORED:data2=Buffer.alloc(compressedData.length);compressedData.copy(data2);if(!crc32OK(data2)){if(async&&callback4)callback4(data2,Utils.Errors.BAD_CRC());throw Utils.Errors.BAD_CRC()}else{if(async&&callback4)callback4(data2);return data2}case Utils.Constants.DEFLATED:var inflater=new Methods.Inflater(compressedData,_centralHeader.size);if(!async){data2=inflater.inflate();if(!crc32OK(data2)){throw Utils.Errors.BAD_CRC(`"${decoder3.decode(_entryName)}"`)}return data2}else{inflater.inflateAsync(function(result3,err){if(!callback4)return;if(err){callback4(Buffer.alloc(0),err)}else if(!crc32OK(result3)){callback4(result3,Utils.Errors.BAD_CRC())}else{callback4(result3)}})}break;default:if(async&&callback4)callback4(Buffer.alloc(0),Utils.Errors.UNKNOWN_METHOD());throw Utils.Errors.UNKNOWN_METHOD()}}function compress(async,callback4){if((!uncompressedData||!uncompressedData.length)&&Buffer.isBuffer(input)){if(async&&callback4)callback4(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&&callback4)callback4(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(data2){compressedData=Buffer.alloc(data2.length);_centralHeader.compressedSize=data2.length;data2.copy(compressedData);callback4&&callback4(compressedData)})}deflater=null;break}}else if(async&&callback4){callback4(Buffer.alloc(0))}else{return Buffer.alloc(0)}}function readUInt64LE(buffer2,offset2){return Utils.readBigUInt64LE(buffer2,offset2)}function parseExtra(data2){try{var offset2=0;var signature,size,part;while(offset2+4<data2.length){signature=data2.readUInt16LE(offset2);offset2+=2;size=data2.readUInt16LE(offset2);offset2+=2;part=data2.slice(offset2,offset2+size);offset2+=size;if(Constants.ID_ZIP64===signature){parseZip64ExtendedInformation(part)}}}catch(error3){throw Utils.Errors.EXTRA_FIELD_PARSE_ERROR()}}function parseZip64ExtendedInformation(data2){var size,compressedSize,offset2,diskNumStart;if(data2.length>=Constants.EF_ZIP64_SCOMP){size=readUInt64LE(data2,Constants.EF_ZIP64_SUNCOMP);if(_centralHeader.size===Constants.EF_ZIP64_OR_32){_centralHeader.size=size}}if(data2.length>=Constants.EF_ZIP64_RHO){compressedSize=readUInt64LE(data2,Constants.EF_ZIP64_SCOMP);if(_centralHeader.compressedSize===Constants.EF_ZIP64_OR_32){_centralHeader.compressedSize=compressedSize}}if(data2.length>=Constants.EF_ZIP64_DSN){offset2=readUInt64LE(data2,Constants.EF_ZIP64_RHO);if(_centralHeader.offset===Constants.EF_ZIP64_OR_32){_centralHeader.offset=offset2}}if(data2.length>=Constants.EF_ZIP64_DSN+4){diskNumStart=data2.readUInt32LE(Constants.EF_ZIP64_DSN);if(_centralHeader.diskNumStart===Constants.EF_ZIP64_OR_16){_centralHeader.diskNumStart=diskNumStart}}}return{get entryName(){return decoder3.decode(_entryName)},get rawEntryName(){return _entryName},set entryName(val){_entryName=Utils.toBuffer(val,decoder3.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 decoder3.decode(_comment)},set comment(val){_comment=Utils.toBuffer(val,decoder3.encode);_centralHeader.commentLength=_comment.length;if(_comment.length>65535)throw Utils.Errors.COMMENT_TOO_LONG()},get name(){const n2=decoder3.decode(_entryName);return _isDirectory?n2.replace(/[/\\]$/,"").split("/").pop():n2.split("/").pop()},get isDirectory(){return _isDirectory},getCompressedData:function(){return compress(false,null)},getCompressedDataAsync:function(callback4){compress(true,callback4)},setData:function(value3){uncompressedData=Utils.toBuffer(value3,Utils.decoder.encode);if(!_isDirectory&&uncompressedData.length){_centralHeader.size=uncompressedData.length;_centralHeader.method=Utils.Constants.DEFLATED;_centralHeader.crc=Utils.crc32(value3);_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(callback4,pass){if(_centralHeader.changed){callback4(uncompressedData)}else{decompress(true,callback4,pass)}},set attr(attr){_centralHeader.attr=attr},get attr(){return _centralHeader.attr},set header(data2){_centralHeader.loadFromBinary(data2)},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 bytes2=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:bytes2(input),data:bytes2(uncompressedData)}},toString:function(){return JSON.stringify(this.toJSON(),null,"\t")}}}});var require_zipFile=__commonJS((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:decoder3}=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 i2=0;i2<elements.length;i2++){const sub=elements.slice(0,i2+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 i2=0;i2<entryList.length;i2++){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[i2]=entry;entryTable[entry.entryName]=entry}temporary.clear();makeTemporaryFolders()}function readMainHeader(readNow){var i2=inBuffer.length-Utils.Constants.ENDHDR,max=Math.max(0,i2-65535),n2=max,endStart=inBuffer.length,endOffset=-1,commentEnd=0;const trailingSpace=typeof opts.trailingSpace==="boolean"?opts.trailingSpace:false;if(trailingSpace)max=0;for(i2;i2>=n2;i2--){if(inBuffer[i2]!==80)continue;if(inBuffer.readUInt32LE(i2)===Utils.Constants.ENDSIG){endOffset=i2;commentEnd=i2;endStart=i2+Utils.Constants.ENDHDR;n2=i2-Utils.Constants.END64HDR;continue}if(inBuffer.readUInt32LE(i2)===Utils.Constants.END64SIG){n2=max;continue}if(inBuffer.readUInt32LE(i2)===Utils.Constants.ZIP64SIG){endOffset=i2;endStart=i2+Utils.readBigUInt64LE(inBuffer,i2+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 decoder3.decode(_comment)},set comment(val){_comment=Utils.toBuffer(val,decoder3.encode);mainHeader.commentLength=_comment.length},getEntryCount:function(){if(!loadedEntries){return mainHeader.diskEntries}return entryList.length},forEach:function(callback4){this.entries.forEach(callback4)},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 list2=this.getEntryChildren(entry,withsubfolders).map((child)=>child.entryName);list2.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 list2=[];const name=entry.entryName;for(const zipEntry of entryList){if(zipEntry.entryName.startsWith(name)){list2.push(zipEntry)}}return list2}else{return[entry]}}return[]},getChildCount:function(entry){if(entry&&entry.isDirectory){const list2=this.getEntryChildren(entry);return list2.includes(entry)?list2.length-1:list2.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((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 defaultOptions2={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),defaultOptions2);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:join4,normalize:normalize2,sep}=pth.posix;return join4(pth.isAbsolute(zipPath)?"/":".",normalize2(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,callback4){var item=getEntry(entry);if(item){item.getDataAsync(callback4)}else{callback4(null,"getEntry failed for:"+entry)}},readAsText:function(entry,encoding){var item=getEntry(entry);if(item){var data2=item.getData();if(data2&&data2.length){return data2.toString(encoding||"utf8")}}return""},readAsTextAsync:function(entry,callback4,encoding){var item=getEntry(entry);if(item){item.getDataAsync(function(data2,err){if(err){callback4(data2,err);return}if(data2&&data2.length){callback4(data2.toString(encoding||"utf8"))}else{callback4("")}})}else{callback4("")}},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 data2=_attr.isFile()?filetools.fs.readFileSync(localPath):Buffer.alloc(0);if(_attr.isDirectory())zipPath+=filetools.sep;this.addFile(zipPath,data2,comment,_attr)}else{throw Utils.Errors.FILE_NOT_FOUND(localPath)}},addLocalFileAsync:function(options2,callback4){options2=typeof options2==="object"?options2:{localPath:options2};const localPath=pth.resolve(options2.localPath);const{comment}=options2;let{zipPath,zipName}=options2;const self=this;filetools.fs.stat(localPath,function(err,stats){if(err)return callback4(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(err2,data2){if(err2)return callback4(err2,false);self.addFile(zipPath,data2,comment,stats);return setImmediate(callback4,undefined,true)})}else if(stats.isDirectory()){zipPath+=filetools.sep;self.addFile(zipPath,Buffer.alloc(0),comment,stats);return setImmediate(callback4,undefined,true)}})},addLocalFolder:function(localPath,zipPath,filter5){filter5=filenameFilter(filter5);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(filter5(p)){self.addLocalFile(filepath,pth.dirname(p))}}}}else{throw Utils.Errors.FILE_NOT_FOUND(localPath)}},addLocalFolderAsync:function(localPath,callback4,zipPath,filter5){filter5=filenameFilter(filter5);zipPath=zipPath?fixPath(zipPath):"";localPath=pth.normalize(localPath);var self=this;filetools.fs.open(localPath,"r",function(err){if(err&&err.code==="ENOENT"){callback4(undefined,Utils.Errors.FILE_NOT_FOUND(localPath))}else if(err){callback4(undefined,err)}else{var items=filetools.findFiles(localPath);var i2=-1;var next=function(){i2+=1;if(i2<items.length){var filepath=items[i2];var p=relativePath(localPath,filepath).split("\\").join("/");p=p.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"");if(filter5(p)){filetools.fs.stat(filepath,function(er0,stats){if(er0)callback4(undefined,er0);if(stats.isFile()){filetools.fs.readFile(filepath,function(er1,data2){if(er1){callback4(undefined,er1)}else{self.addFile(zipPath+p,data2,"",stats);next()}})}else{self.addFile(zipPath+p+"/",Buffer.alloc(0),"",stats);next()}})}else{process.nextTick(()=>{next()})}}else{callback4(true,undefined)}};next()}})},addLocalFolderAsync2:function(options2,callback4){const self=this;options2=typeof options2==="object"?options2:{localPath:options2};const localPath=pth.resolve(options2.localPath);let{zipPath,filter:filter5,namefix}=options2;if(filter5 instanceof RegExp){filter5=function(rx){return function(filename){return rx.test(filename)}}(filter5)}else if(typeof filter5!=="function"){filter5=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"){callback4(Utils.Errors.FILE_NOT_FOUND(localPath),false)}else if(err){callback4(err,false)}else{filetools.findFilesAsync(localPath,function(err2,fileEntries){if(err2)return callback4(err2,false);fileEntries=fileEntries.filter((dir)=>filter5(relPathFix(dir)));if(!fileEntries.length)return callback4(undefined,true);setImmediate(fileEntries.reverse().reduce(function(next,entry){return function(err3,done3){if(err3||done3===false)return setImmediate(next,err3,false);self.addLocalFileAsync({localPath:entry,zipPath:pth.dirname(relPathFix(entry)),zipName:fileNameFix(entry)},next)}},callback4))})}})},addLocalFolderPromise:function(localPath,props){return new Promise((resolve6,reject)=>{this.addLocalFolderAsync2(Object.assign({localPath},props),(err,done3)=>{if(err)return reject(err);if(done3)resolve6(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(callback4){return _zip.forEach(callback4)},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 content2=child.getData();if(!content2){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 fileAttr2=keepOriginalPermission?child.header.fileAttr:undefined;filetools.writeFileTo(childName,content2,overwrite,fileAttr2)});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,callback4){callback4=get_Fun(overwrite,keepOriginalPermission,callback4);keepOriginalPermission=get_Bool(false,keepOriginalPermission);overwrite=get_Bool(false,overwrite);if(!callback4){return new Promise((resolve6,reject)=>{this.extractAllToAsync(targetPath,overwrite,keepOriginalPermission,function(err){if(err){reject(err)}else{resolve6(this)}})})}if(!_zip){callback4(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){callback4(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 done3=(err)=>{if(!err){try{applyDirAttributes(deferredDirAttr)}catch(er){return callback4(getError("Unable to set folder permissions",er.path||""))}}callback4(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()})})}})}}},done3)()},writeZip:function(targetFileName,callback4){if(arguments.length===1){if(typeof targetFileName==="function"){callback4=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 callback4==="function")callback4(!ok?new Error("failed"):null,"")}},writeZipPromise:function(targetFileName,props){const{overwrite,perm}=Object.assign({overwrite:true},props);return new Promise((resolve6,reject)=>{if(!targetFileName&&opts.filename)targetFileName=opts.filename;if(!targetFileName)reject("ADM-ZIP: ZIP File Name Missing");this.toBufferPromise().then((zipData)=>{const ret=(done3)=>done3?resolve6(done3):reject("ADM-ZIP: Wasn't able to write zip file");filetools.writeFileToAsync(targetFileName,zipData,overwrite,perm,ret)},reject)})},toBufferPromise:function(){return new Promise((resolve6,reject)=>{_zip.toAsyncBuffer(resolve6,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,errorDescMap2,args2,originalErrorMsg)=>{const msg=[`${[errorDescMap2[errorCode]]} #${errorCode}`];args2&&msg.push(`args: ${JSON.stringify(args2)}`);msg.push(getDocsUrl(errorCode));originalErrorMsg&&msg.push(`Original Error Message:
198
+ `,"Broker","warn");return}try{const publisher=this._publisherMap.get(identifier3);fileLog(`[${ActionKind.UPDATE_PUBLISHER}] ${identifier3} update, and notify subscribers to update`,"Broker","info");if(publisher){publisher.notifySubscribers({remoteTypeTarPath,name,updateMode:updateMode2,updateKind,updateSourcePaths:updateSourcePaths||[]});this._publisherMap.forEach((p)=>{if(p.name===publisher.name)return;const dynamicRemoteInfo=p.dynamicRemoteMap.get(identifier3);if(dynamicRemoteInfo){fileLog(`dynamicRemoteInfo: ${JSON.stringify(dynamicRemoteInfo)}, identifier:${identifier3} publish: ${p.name}`,"Broker","info");p.fetchRemoteTypes({remoteInfo:dynamicRemoteInfo,once:false})}})}}catch(err){const msg=error2(err,ActionKind.UPDATE_PUBLISHER,"Broker");client2.send(msg);client2.close()}}async _fetchTypes(context3,_client){const{name,ip,remoteInfo}=context3??{};const identifier3=getIdentifier({name,ip});try{const publisher=this._publisherMap.get(identifier3);fileLog(`[${ActionKind.FETCH_TYPES}] ${identifier3} fetch types`,"Broker","info");if(publisher)publisher.fetchRemoteTypes({remoteInfo,once:true})}catch(err){fileLog(`[${ActionKind.FETCH_TYPES}] ${identifier3} fetch types fail , error info: ${err}`,"Broker","error")}}_addDynamicRemote(context3){const{name,ip,remoteInfo,remoteIp}=context3??{};const identifier3=getIdentifier({name,ip});const publisher=this._publisherMap.get(identifier3);const remoteId=getIdentifier({name:remoteInfo.name,ip:remoteIp});fileLog(`[${ActionKind.ADD_DYNAMIC_REMOTE}] identifier:${identifier3},publisher: ${publisher.name}, remoteId:${remoteId}`,"Broker","error");if(!publisher||publisher.dynamicRemoteMap.has(remoteId))return;publisher.dynamicRemoteMap.set(remoteId,remoteInfo)}async _addSubscriber(context3,client2){const{publishers,name:subscriberName}=context3??{};publishers.forEach((publisher)=>{const{name,ip}=publisher;const identifier3=getIdentifier({name,ip});if(!this._publisherMap.has(identifier3)){fileLog(`[${ActionKind.ADD_SUBSCRIBER}]: ${identifier3} has not been started, ${subscriberName} will add the relation to tmp shelter`,"Broker","warn");this._addTmpSubScriberRelation({name:getIdentifier({name:context3.name,ip:context3.ip}),client:client2},publisher);return}try{const registeredPublisher=this._publisherMap.get(identifier3);if(registeredPublisher){registeredPublisher.addSubscriber(getIdentifier({name:subscriberName,ip:context3.ip}),client2);fileLog(`[${ActionKind.ADD_SUBSCRIBER}]: ${identifier3} 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:context3.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=error2(err,ActionKind.ADD_SUBSCRIBER,"Broker");client2.send(msg);client2.close()}})}async _removeSubscriber(context3,client2){const{publishers}=context3??{};const subscriberIdentifier=getIdentifier({name:context3?.name,ip:context3?.ip});publishers.forEach((publisher)=>{const{name,ip}=publisher;const identifier3=getIdentifier({name,ip});const registeredPublisher=this._publisherMap.get(identifier3);if(!registeredPublisher){fileLog(`[${ActionKind.EXIT_SUBSCRIBER}], ${identifier3} does not exit `,"Broker","warn");return}try{fileLog(`[${ActionKind.EXIT_SUBSCRIBER}], ${identifier3} will exit `,"Broker","INFO");registeredPublisher.removeSubscriber(subscriberIdentifier);this._clearTmpSubScriberRelation(identifier3);if(!registeredPublisher.hasSubscribes)this._publisherMap.delete(identifier3);if(!this.hasPublishers)this.exit()}catch(err){const msg=error2(err,ActionKind.EXIT_SUBSCRIBER,"Broker");client2.send(msg);client2.close()}})}async _removePublisher(context3,client2){const{name,ip}=context3??{};const identifier3=getIdentifier({name,ip});const publisher=this._publisherMap.get(identifier3);if(!publisher){fileLog(`[${ActionKind.EXIT_PUBLISHER}]: ${identifier3}} 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}]: ${identifier3} is removing , subscriber: ${subscriberIdentifier} will be add tmpSubScriberRelation`,"Broker","info")});this._publisherMap.delete(identifier3);fileLog(`[${ActionKind.EXIT_PUBLISHER}]: ${identifier3} 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=error2(err,ActionKind.EXIT_PUBLISHER,"Broker");client2.send(msg);client2.close()}}async _addWebClient(context3,client2){const{name}=context3??{};const identifier3=getIdentifier({name});if(this._webClientMap.has(identifier3))fileLog(`${identifier3}} has been added, this action will override prev WebClient`,"Broker","warn");try{this._webClientMap.set(identifier3,client2);fileLog(`${identifier3} adding WebClient Succeed`,"Broker","info")}catch(err){const msg=error2(err,ActionKind.ADD_WEB_CLIENT,"Broker");client2.send(msg);client2.close()}}async _notifyWebClient(context3,client2){const{name,updateMode:updateMode2}=context3??{};const identifier3=getIdentifier({name});const webClient=this._webClientMap.get(identifier3);if(!webClient){fileLog(`[${ActionKind.NOTIFY_WEB_CLIENT}] ${identifier3} has not been added, this action will be ignored`,"Broker","warn");return}try{const api=new ReloadWebClientAPI({name,updateMode:updateMode2});webClient.send(JSON.stringify(api));fileLog(`[${ActionKind.NOTIFY_WEB_CLIENT}] Notify ${name} WebClient Succeed`,"Broker","info")}catch(err){const msg=error2(err,ActionKind.NOTIFY_WEB_CLIENT,"Broker");client2.send(msg);client2.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 map8=new Map;map8.set(subscriberIdentifier,subscriber);this._tmpSubscriberShelter.set(publisherIdentifier,{subscribers:map8,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,identifier3)=>{fileLog(`notifyTmpSubScribers ${publisher.name} will be add a subscriber: ${identifier3} `,"Broker","warn");publisher.addSubscriber(identifier3,tmpSubScriber.client);publisher.notifySubscriber(identifier3,{updateKind:UpdateKind.UPDATE_TYPE,updateMode:UpdateMode.PASSIVE,updateSourcePaths:[publisher.name],remoteTypeTarPath:publisher.remoteTypeTarPath,name:publisher.name})})}_clearTmpSubScriberRelation(identifier3){this._tmpSubscriberShelter.delete(identifier3)}_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,identifier3)=>{fileLog(` _clearTmpSubScriberRelation ${identifier3}, ${Date.now()-tmpSubscriber.timestamp>=(process.env["GARFISH_MODULE_SERVER_TEST"]?serverTest:Broker2.DEFAULT_WAITING_TIME)}`,"Broker","info");if(Date.now()-tmpSubscriber.timestamp>=(process.env["FEDERATION_SERVER_TEST"]?serverTest:Broker2.DEFAULT_WAITING_TIME))this._clearTmpSubScriberRelation(identifier3)})},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",(error3)=>{console.error("Unhandled Rejection Error: ",error3);fileLog(`Unhandled Rejection Error: ${error3}`,"Broker","fatal");process.exit(1)});process.on("uncaughtException",(error3)=>{console.error("Unhandled Exception Error: ",error3);fileLog(`Unhandled Rejection Error: ${error3}`,"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((client2)=>{client2.send(JSON.stringify(message))});this._secureWebSocketServer?.clients.forEach((client2)=>{client2.send(JSON.stringify(message))})}}});import node_fs from"fs";import node_path from"path";function findPackageJson(startPath){let currentPath=node_path.resolve(startPath);while(true){const packageJsonPath=node_path.join(currentPath,"package.json");if(node_fs.existsSync(packageJsonPath)){return packageJsonPath}const parentPath=node_path.dirname(currentPath);if(parentPath===currentPath){return}currentPath=parentPath}}var init_findPackageJson=()=>{};import path4 from"path";import fs from"fs";class PKGJsonManager{setPKGJson(pkg){this._pkg=pkg}readPKGJson(root=process.cwd()){if(this._pkg){return this._pkg}try{const pkg=JSON.parse(fs.readFileSync(path4.resolve(root,"package.json"),"utf8"));this._pkg=pkg;return pkg}catch(_err){try{const pkgPath=findPackageJson(root);if(!pkgPath){return{}}const pkg=JSON.parse(fs.readFileSync(pkgPath,"utf8"));this._pkg=pkg;return pkg}catch(err){logger.error(err);return{}}}}getExposeGarfishModuleType(root=process.cwd()){const pkg=this.readPKGJson(root);return pkg?.["mf"]?.type===MFModuleType.NPM?MFModuleType.NPM:MFModuleType.APP}}var init_PKGJsonManager=__esm(()=>{init_dist();init_findPackageJson()});var LOCAL_BUILD_VERSION="local";var init_constant2=()=>{};var exports_utils={};__export(exports_utils,{parseOptions:()=>parseOptions2,getBuildVersion:()=>getBuildVersion,getBuildName:()=>getBuildName});function processFn(options,normalizeSimple,normalizeOptions2,fn3){const object2=(obj)=>{for(const[key,value3]of Object.entries(obj)){if(typeof value3==="string"){fn3(key,normalizeSimple(value3,key))}else{fn3(key,normalizeOptions2(value3,key))}}};const array3=(items)=>{for(const item of items){if(typeof item==="string"){fn3(item,normalizeSimple(item,item))}else if(item&&typeof item==="object"){object2(item)}else{throw new Error("Unexpected options format")}}};if(!options){return}else if(Array.isArray(options)){array3(options)}else if(typeof options==="object"){object2(options)}else{throw new Error("Unexpected options format")}}function parseOptions2(options,normalizeSimple,normalizeOptions2){const items=[];processFn(options,normalizeSimple,normalizeOptions2,(key,value3)=>{items.push([key,value3])});return items}function getBuildVersion(root){if(process.env["MF_BUILD_VERSION"]){return process.env["MF_BUILD_VERSION"]}const pkg=new PKGJsonManager().readPKGJson(root);if(pkg?.["version"]&&typeof pkg["version"]==="string"){return pkg["version"]}return LOCAL_BUILD_VERSION}function getBuildName(){return process.env["MF_BUILD_NAME"]}var init_utils2=__esm(()=>{init_PKGJsonManager();init_constant2()});var init_dist2=__esm(()=>{init_utils2()});import{copyFile as copyFile3,lstat,mkdir as mkdir2,readdir}from"fs/promises";import{existsSync as existsSync4,readFileSync as readFileSync3}from"fs";import path22 from"path";import path5 from"path";import fs2 from"fs";function getTypedName(name){return`@types/${name.replace(/^@/,"").replace("/","__")}`}function getPackageRootDir(packageName,context3=process.cwd()){if(!packageName){throw new Error("No package name provided.")}const entryFile=__require2.resolve(packageName,{paths:[context3]});const entryDir=path5.dirname(entryFile);let fallbackPackageJsonPath=path5.join(entryDir,"package.json");if(!fs2.existsSync(fallbackPackageJsonPath)){fallbackPackageJsonPath=null}const match5=packageName.match(/^@[^/]+\/(.+)$/);const localName=match5?match5[1]:packageName;let currentDir=entryDir;while(path5.basename(currentDir)!==localName&&path5.dirname(currentDir)!==currentDir){try{currentDir=path5.dirname(currentDir)}catch(err){if(err.code==="EACCES"){continue}else{throw err}}}if(path5.basename(currentDir)===localName){const candidate=path5.join(currentDir,"package.json");if(fs2.existsSync(candidate)){const pkgContent=JSON.parse(fs2.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,context3){try{return __require2.resolve(`${packageName}/package.json`,{paths:[context3]})}catch(e){let currentPath=path5.resolve(context3);while(true){const candidate=path5.join(currentPath,"node_modules",packageName,"package.json");if(fs2.existsSync(candidate)){return candidate}const parentPath=path5.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:context3=process.cwd(),exclude=[]}){this.destDir=destDir;this.context=context3;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(readFileSync3(pkgJsonPath,"utf-8"));const types2=pkg.types||pkg.typings;if(dir===this.context){return}if(types2){const typesDir=path22.dirname(path22.resolve(dir,types2));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);readFileSync3(typedPkgJsonPath,"utf-8");this.addPkgs(typedPkgName,typedDir);return typedDir}}catch(_err){return}}collectTypeImports(str){const{pattern}=this;let match5;const imports=new Set;while((match5=pattern.exec(str))!==null){imports.add(match5[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((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((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 E2(message){return function(...args2){if(args2.length){message=message.replace(/\{(\d)\}/g,(_,n2)=>args2[n2]||"")}return new Error("ADM-ZIP: "+message)}}for(const msg of Object.keys(errors)){exports[msg]=E2(errors[msg])}});var require_utils=__commonJS((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 mkdirSync3(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 stat3;try{stat3=self.fs.statSync(resolvedPath)}catch(e){if(e.message&&e.message.startsWith("ENOENT")){self.fs.mkdirSync(resolvedPath)}else{throw e}}if(stat3&&stat3.isFile())throw Errors.FILE_IN_THE_WAY(`"${resolvedPath}"`)})}mkdirSync3(folder)};Utils.prototype.writeFileTo=function(path6,content,overwrite,attr){const self=this;if(self.fs.existsSync(path6)){if(!overwrite)return false;var stat3=self.fs.statSync(path6);if(stat3.isDirectory()){return false}}var folder=pth.dirname(path6);if(!self.fs.existsSync(folder)){self.makeDir(folder)}var fd;try{fd=self.fs.openSync(path6,"w",438)}catch(e){self.fs.chmodSync(path6,438);fd=self.fs.openSync(path6,"w",438)}if(fd){try{self.fs.writeSync(fd,content,0,content.length,0)}finally{self.fs.closeSync(fd)}}self.fs.chmodSync(path6,attr||438);return true};Utils.prototype.writeFileToAsync=function(path6,content,overwrite,attr,callback4){if(typeof attr==="function"){callback4=attr;attr=undefined}const self=this;self.fs.exists(path6,function(exist){if(exist&&!overwrite)return callback4(false);self.fs.stat(path6,function(err,stat3){if(exist&&stat3&&stat3.isDirectory()){return callback4(false)}var folder=pth.dirname(path6);self.fs.exists(folder,function(exists){if(!exists){try{self.makeDir(folder)}catch(e){return callback4(false)}}const writeToFd=function(fd){self.fs.write(fd,content,0,content.length,0,function(writeErr){self.fs.close(fd,function(){if(writeErr)return callback4(false);self.fs.chmod(path6,attr||438,function(){callback4(true)})})})};self.fs.open(path6,"w",438,function(err2,fd){if(err2){self.fs.chmod(path6,438,function(){self.fs.open(path6,"w",438,function(retryErr,fd2){if(retryErr||!fd2)return callback4(false);writeToFd(fd2)})})}else if(fd){writeToFd(fd)}else{callback4(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 stat3;try{stat3=self.fs.lstatSync(cur)}catch(e){break}if(stat3.isSymbolicLink())throw Errors.FILE_IN_THE_WAY(`"${cur}"`)}};Utils.prototype.findFiles=function(path6){const self=this;const canLstat=typeof self.fs.lstatSync==="function";const rootReal=self.fs.realpathSync(path6);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 path7=pth.join(dir,file);if(escapesRoot(path7))return;const stat3=self.fs.statSync(path7);if(!pattern||pattern.test(path7)){files.push(pth.normalize(path7)+(stat3.isDirectory()?self.sep:""))}if(stat3.isDirectory()&&recursive){const realDir=self.fs.realpathSync(path7);if(!visited.has(realDir)){visited.add(realDir);files=files.concat(findSync(path7,pattern,recursive,visited))}}});return files}return findSync(path6,undefined,true,new Set([rootReal]))};Utils.prototype.findFilesAsync=function(dir,cb){const self=this;const results2=[];let finished=false;const finish=function(err){if(finished)return;finished=true;cb(err,err?undefined:results2)};const canLstat=typeof self.fs.lstat==="function";let rootReal=null;const escapesRoot=function(file,cb2){if(!canLstat)return cb2(null,false);self.fs.lstat(file,function(err,lst){if(err)return cb2(err);if(!lst||!lst.isSymbolicLink())return cb2(null,false);self.fs.realpath(file,function(err2,real){if(err2)return cb2(null,true);cb2(null,!(real===rootReal||real.startsWith(rootReal+pth.sep)))})})};const walk=function(dir2,visited,done3){self.fs.readdir(dir2,function(err,list2){if(err)return done3(err);let pending=list2.length;if(!pending)return done3();list2.forEach(function(name){const file=pth.join(dir2,name);escapesRoot(file,function(err2,escapes){if(err2)return done3(err2);if(escapes){if(!--pending)done3();return}self.fs.stat(file,function(err3,stat3){if(err3)return done3(err3);if(!stat3){if(!--pending)done3();return}results2.push(pth.normalize(file)+(stat3.isDirectory()?self.sep:""));if(!stat3.isDirectory()){if(!--pending)done3();return}self.fs.realpath(file,function(err4,realDir){if(err4)return done3(err4);if(visited.has(realDir)){if(!--pending)done3();return}visited.add(realDir);walk(file,visited,function(err5){if(err5)return done3(err5);if(!--pending)done3()})})})})})})};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(path6){if(!path6)return"";const safeSuffix=pth.posix.normalize("/"+path6.split("\\").join("/"));return pth.join(".",safeSuffix)};Utils.zipnamefix=function(path6){if(!path6)return"";const safeSuffix=pth.posix.normalize("/"+path6.split("\\").join("/"));return pth.posix.join(".",safeSuffix)};Utils.findLast=function(arr,callback4){if(!Array.isArray(arr))throw new TypeError("arr is not array");const len=arr.length>>>0;for(let i2=len-1;i2>=0;i2--){if(callback4(arr[i2],i2,arr)){return arr[i2]}}return};Utils.sanitize=function(prefix,name){prefix=pth.resolve(pth.normalize(prefix));var parts2=name.split("/");for(var i2=0,l=parts2.length;i2<l;i2++){var path6=pth.normalize(pth.join(prefix,parts2.slice(i2,l).join(pth.sep)));if(path6===prefix||path6.startsWith(prefix+pth.sep)){return path6}}return pth.normalize(pth.join(prefix,pth.basename(name)))};Utils.toBuffer=function toBuffer(input,encoder3){if(Buffer.isBuffer(input)){return input}else if(input instanceof Uint8Array){return Buffer.from(input)}else{return typeof input==="string"?encoder3(input):Buffer.alloc(0)}};Utils.readBigUInt64LE=function(buffer2,index){const lo=buffer2.readUInt32LE(index);const hi=buffer2.readUInt32LE(index+4);const value3=hi*4294967296+lo;if(value3>Number.MAX_SAFE_INTEGER){throw Errors.ZIP64_VALUE_TOO_LARGE()}return value3};Utils.writeBigUInt64LE=function(buffer2,value3,index){const lo=value3>>>0;const hi=Math.floor(value3/4294967296)>>>0;buffer2.writeUInt32LE(lo,index);buffer2.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((exports,module)=>{var pth=__require("path");module.exports=function(path6,{fs:fs3}){var _path=path6||"",_obj=newAttr(),_stat=null;function newAttr(){return{directory:false,readonly:false,hidden:false,executable:false,mtime:0,atime:0}}if(_path&&fs3.existsSync(_path)){_stat=fs3.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((exports,module)=>{module.exports={efs:true,encode:(data2)=>Buffer.from(data2,"utf8"),decode:(data2)=>data2.toString("utf8")}});var require_util=__commonJS((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((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 data2=input.slice(_offset,_offset+Constants.LOCHDR);if(data2.readUInt32LE(0)!==Constants.LOCSIG){throw Utils.Errors.INVALID_LOC()}_localHeader.version=data2.readUInt16LE(Constants.LOCVER);_localHeader.flags=data2.readUInt16LE(Constants.LOCFLG);_localHeader.flags_desc=(_localHeader.flags&Constants.FLG_DESC)>0;_localHeader.method=data2.readUInt16LE(Constants.LOCHOW);_localHeader.time=data2.readUInt32LE(Constants.LOCTIM);_localHeader.crc=data2.readUInt32LE(Constants.LOCCRC);_localHeader.compressedSize=data2.readUInt32LE(Constants.LOCSIZ);_localHeader.size=data2.readUInt32LE(Constants.LOCLEN);_localHeader.fnameLen=data2.readUInt16LE(Constants.LOCNAM);_localHeader.extraLen=data2.readUInt16LE(Constants.LOCEXT);const extraStart=_offset+Constants.LOCHDR+_localHeader.fnameLen;const extraEnd=extraStart+_localHeader.extraLen;return input.slice(extraStart,extraEnd)},loadFromBinary:function(data2){if(data2.length!==Constants.CENHDR||data2.readUInt32LE(0)!==Constants.CENSIG){throw Utils.Errors.INVALID_CEN()}_verMade=data2.readUInt16LE(Constants.CENVEM);_version=data2.readUInt16LE(Constants.CENVER);_flags=data2.readUInt16LE(Constants.CENFLG);_method=data2.readUInt16LE(Constants.CENHOW);_time=data2.readUInt32LE(Constants.CENTIM);_crc=data2.readUInt32LE(Constants.CENCRC);_compressedSize=data2.readUInt32LE(Constants.CENSIZ);_size=data2.readUInt32LE(Constants.CENLEN);_fnameLen=data2.readUInt16LE(Constants.CENNAM);_extraLen=data2.readUInt16LE(Constants.CENEXT);_comLen=data2.readUInt16LE(Constants.CENCOM);_diskStart=data2.readUInt16LE(Constants.CENDSK);_inattr=data2.readUInt16LE(Constants.CENATT);_attr=data2.readUInt32LE(Constants.CENATX);_offset=data2.readUInt32LE(Constants.CENOFF)},localHeaderToBinary:function(){var data2=Buffer.alloc(Constants.LOCHDR);data2.writeUInt32LE(Constants.LOCSIG,0);data2.writeUInt16LE(_version,Constants.LOCVER);data2.writeUInt16LE(_flags&~Constants.FLG_DESC,Constants.LOCFLG);data2.writeUInt16LE(_method,Constants.LOCHOW);data2.writeUInt32LE(_time,Constants.LOCTIM);data2.writeUInt32LE(_crc,Constants.LOCCRC);data2.writeUInt32LE(_compressedSize,Constants.LOCSIZ);data2.writeUInt32LE(_size,Constants.LOCLEN);data2.writeUInt16LE(_fnameLen,Constants.LOCNAM);data2.writeUInt16LE(_localHeader.extraLen,Constants.LOCEXT);return data2},centralHeaderToBinary:function(){var data2=Buffer.alloc(Constants.CENHDR+_fnameLen+_extraLen+_comLen);data2.writeUInt32LE(Constants.CENSIG,0);data2.writeUInt16LE(_verMade,Constants.CENVEM);data2.writeUInt16LE(_version,Constants.CENVER);data2.writeUInt16LE(_flags&~Constants.FLG_DESC,Constants.CENFLG);data2.writeUInt16LE(_method,Constants.CENHOW);data2.writeUInt32LE(_time,Constants.CENTIM);data2.writeUInt32LE(_crc,Constants.CENCRC);data2.writeUInt32LE(_compressedSize,Constants.CENSIZ);data2.writeUInt32LE(_size,Constants.CENLEN);data2.writeUInt16LE(_fnameLen,Constants.CENNAM);data2.writeUInt16LE(_extraLen,Constants.CENEXT);data2.writeUInt16LE(_comLen,Constants.CENCOM);data2.writeUInt16LE(_diskStart,Constants.CENDSK);data2.writeUInt16LE(_inattr,Constants.CENATT);data2.writeUInt32LE(_attr,Constants.CENATX);data2.writeUInt32LE(_offset,Constants.CENOFF);return data2},toJSON:function(){const bytes2=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:bytes2(_compressedSize),size:bytes2(_size),fileNameLength:bytes2(_fnameLen),extraLength:bytes2(_extraLen),commentLength:bytes2(_comLen),diskNumStart:_diskStart,inAttr:_inattr,attr:_attr,offset:_offset,centralHeaderSize:bytes2(Constants.CENHDR+_fnameLen+_extraLen+_comLen)}},toString:function(){return JSON.stringify(this.toJSON(),null,"\t")}}}});var require_mainHeader=__commonJS((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(data2){if((data2.length!==Constants.ENDHDR||data2.readUInt32LE(0)!==Constants.ENDSIG)&&(data2.length<Constants.ZIP64HDR||data2.readUInt32LE(0)!==Constants.ZIP64SIG)){throw Utils.Errors.INVALID_END()}if(data2.readUInt32LE(0)===Constants.ENDSIG){_volumeEntries=data2.readUInt16LE(Constants.ENDSUB);_totalEntries=data2.readUInt16LE(Constants.ENDTOT);_size=data2.readUInt32LE(Constants.ENDSIZ);_offset=data2.readUInt32LE(Constants.ENDOFF);_commentLength=data2.readUInt16LE(Constants.ENDCOM)}else{_volumeEntries=Utils.readBigUInt64LE(data2,Constants.ZIP64SUB);_totalEntries=Utils.readBigUInt64LE(data2,Constants.ZIP64TOT);_size=Utils.readBigUInt64LE(data2,Constants.ZIP64SIZB);_offset=Utils.readBigUInt64LE(data2,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 offset2=0;b.writeUInt32LE(Constants.ZIP64SIG,offset2);Utils.writeBigUInt64LE(b,Constants.ZIP64HDR-Constants.ZIP64LEAD,offset2+Constants.ZIP64SIZE);b.writeUInt16LE(45,offset2+Constants.ZIP64VEM);b.writeUInt16LE(45,offset2+Constants.ZIP64VER);b.writeUInt32LE(0,offset2+Constants.ZIP64DSK);b.writeUInt32LE(0,offset2+Constants.ZIP64DSKDIR);Utils.writeBigUInt64LE(b,_volumeEntries,offset2+Constants.ZIP64SUB);Utils.writeBigUInt64LE(b,_totalEntries,offset2+Constants.ZIP64TOT);Utils.writeBigUInt64LE(b,_size,offset2+Constants.ZIP64SIZB);Utils.writeBigUInt64LE(b,_offset,offset2+Constants.ZIP64OFF);const zip64EndOffset=_offset+_size;offset2+=Constants.ZIP64HDR;b.writeUInt32LE(Constants.END64SIG,offset2);b.writeUInt32LE(0,offset2+Constants.END64START);Utils.writeBigUInt64LE(b,zip64EndOffset,offset2+Constants.END64OFF);b.writeUInt32LE(1,offset2+Constants.END64NUMDISKS);offset2+=Constants.END64HDR;b.writeUInt32LE(Constants.ENDSIG,offset2);b.writeUInt32LE(0,offset2+4);b.writeUInt16LE(Math.min(_volumeEntries,Constants.EF_ZIP64_OR_16),offset2+Constants.ENDSUB);b.writeUInt16LE(Math.min(_totalEntries,Constants.EF_ZIP64_OR_16),offset2+Constants.ENDTOT);b.writeUInt32LE(Math.min(_size,Constants.EF_ZIP64_OR_32),offset2+Constants.ENDSIZ);b.writeUInt32LE(Math.min(_offset,Constants.EF_ZIP64_OR_32),offset2+Constants.ENDOFF);b.writeUInt16LE(_commentLength,offset2+Constants.ENDCOM);b.fill(" ",offset2+Constants.ENDHDR);return b},toJSON:function(){const offset2=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:offset2(_offset,4),commentLength:_commentLength}},toString:function(){return JSON.stringify(this.toJSON(),null,"\t")}}}});var require_headers=__commonJS((exports)=>{exports.EntryHeader=require_entryHeader();exports.MainHeader=require_mainHeader()});var require_deflater=__commonJS((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(callback4){var tmp=zlib.createDeflateRaw(opts),parts2=[],total=0;tmp.on("data",function(data2){parts2.push(data2);total+=data2.length});tmp.on("end",function(){var buf=Buffer.alloc(total),written=0;buf.fill(0);for(var i2=0;i2<parts2.length;i2++){var part=parts2[i2];part.copy(buf,written);written+=part.length}callback4&&callback4(buf)});tmp.end(inbuf)}}}});var require_inflater=__commonJS((exports,module)=>{var version3=+(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 option2=version3>=15?{maxOutputLength}:{};return{inflate:function(){return zlib.inflateRawSync(inbuf,option2)},inflateAsync:function(callback4){var tmp=zlib.createInflateRaw(option2),parts2=[],total=0,done3=false;const fail13=function(err){if(done3)return;done3=true;tmp.destroy();callback4&&callback4(Buffer.alloc(0),err)};tmp.on("error",function(err){fail13(err)});tmp.on("data",function(data2){if(done3)return;total+=data2.length;if(total>maxOutputLength){return fail13(Errors.MAX_OUTPUT_EXCEEDED())}parts2.push(data2)});tmp.on("end",function(){if(done3)return;done3=true;var buf=Buffer.alloc(total),written=0;buf.fill(0);for(var i2=0;i2<parts2.length;i2++){var part=parts2[i2];part.copy(buf,written);written+=part.length}callback4&&callback4(buf)});tmp.end(inbuf)}}}});var require_zipcrypto=__commonJS((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 i2=0;i2<len;i2++)salt[i2]=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 i2=0;i2<pass.length;i2++){this.updateKeys(pass[i2])}}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(data2){const result3=Buffer.alloc(data2.length);let pos=0;for(let c of data2){result3[pos++]=keys.updateKeys(c^keys.next())}return result3}}function make_encrypter(pwd){const keys=new Initkeys(pwd);return function(data2,result3,pos=0){if(!result3)result3=Buffer.alloc(data2.length);for(let c of data2){const k=keys.next();result3[pos++]=c^k;keys.updateKeys(c)}return result3}}function decrypt(data2,header,pwd){if(!data2||!Buffer.isBuffer(data2)||data2.length<12){return Buffer.alloc(0)}const decrypter=make_decrypter(pwd);const salt=decrypter(data2.slice(0,12));const verifyByte=(header.flags&8)===8?header.timeHighByte:header.crc>>>24;if(salt[11]!==verifyByte){throw Errors.WRONG_PASSWORD()}return decrypter(data2.slice(12))}function _salter(data2){if(Buffer.isBuffer(data2)&&data2.length>=12){config.genSalt=function(){return data2.slice(0,12)}}else if(data2==="node"){config.genSalt=genSalt.node}else{config.genSalt=genSalt}}function encrypt(data2,header,pwd,oldlike=false){if(data2==null)data2=Buffer.alloc(0);if(!Buffer.isBuffer(data2))data2=Buffer.from(data2.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 result3=Buffer.alloc(data2.length+12);encrypter(salt,result3);return encrypter(data2,result3,12)}module.exports={decrypt,encrypt,_salter}});var require_methods=__commonJS((exports)=>{exports.Deflater=require_deflater();exports.Inflater=require_inflater();exports.ZipCrypto=require_zipcrypto()});var require_zipEntry=__commonJS((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 decoder3=typeof opts.decoder==="object"?opts.decoder:Utils.decoder;_efs=decoder3.hasOwnProperty("efs")?decoder3.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(data2){const expectedCrc=_centralHeader.flags_desc||_centralHeader.localHeader.flags_desc?_centralHeader.crc:_centralHeader.localHeader.crc;return Utils.crc32(data2)===expectedCrc}function decompress(async,callback4,pass){if(typeof callback4==="undefined"&&typeof async==="string"){pass=async;async=undefined}if(_isDirectory){if(async&&callback4){callback4(Buffer.alloc(0),Utils.Errors.DIRECTORY_CONTENT_ERROR())}return Buffer.alloc(0)}var compressedData;try{compressedData=getCompressedDataFromZip();if(compressedData.length===0){if(async&&callback4)callback4(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&&callback4){callback4(Buffer.alloc(0),err);return Buffer.alloc(0)}throw err}var data2;switch(_centralHeader.method){case Utils.Constants.STORED:data2=Buffer.alloc(compressedData.length);compressedData.copy(data2);if(!crc32OK(data2)){if(async&&callback4)callback4(data2,Utils.Errors.BAD_CRC());throw Utils.Errors.BAD_CRC()}else{if(async&&callback4)callback4(data2);return data2}case Utils.Constants.DEFLATED:var inflater=new Methods.Inflater(compressedData,_centralHeader.size);if(!async){data2=inflater.inflate();if(!crc32OK(data2)){throw Utils.Errors.BAD_CRC(`"${decoder3.decode(_entryName)}"`)}return data2}else{inflater.inflateAsync(function(result3,err){if(!callback4)return;if(err){callback4(Buffer.alloc(0),err)}else if(!crc32OK(result3)){callback4(result3,Utils.Errors.BAD_CRC())}else{callback4(result3)}})}break;default:if(async&&callback4)callback4(Buffer.alloc(0),Utils.Errors.UNKNOWN_METHOD());throw Utils.Errors.UNKNOWN_METHOD()}}function compress(async,callback4){if((!uncompressedData||!uncompressedData.length)&&Buffer.isBuffer(input)){if(async&&callback4)callback4(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&&callback4)callback4(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(data2){compressedData=Buffer.alloc(data2.length);_centralHeader.compressedSize=data2.length;data2.copy(compressedData);callback4&&callback4(compressedData)})}deflater=null;break}}else if(async&&callback4){callback4(Buffer.alloc(0))}else{return Buffer.alloc(0)}}function readUInt64LE(buffer2,offset2){return Utils.readBigUInt64LE(buffer2,offset2)}function parseExtra(data2){try{var offset2=0;var signature,size,part;while(offset2+4<data2.length){signature=data2.readUInt16LE(offset2);offset2+=2;size=data2.readUInt16LE(offset2);offset2+=2;part=data2.slice(offset2,offset2+size);offset2+=size;if(Constants.ID_ZIP64===signature){parseZip64ExtendedInformation(part)}}}catch(error3){throw Utils.Errors.EXTRA_FIELD_PARSE_ERROR()}}function parseZip64ExtendedInformation(data2){var size,compressedSize,offset2,diskNumStart;if(data2.length>=Constants.EF_ZIP64_SCOMP){size=readUInt64LE(data2,Constants.EF_ZIP64_SUNCOMP);if(_centralHeader.size===Constants.EF_ZIP64_OR_32){_centralHeader.size=size}}if(data2.length>=Constants.EF_ZIP64_RHO){compressedSize=readUInt64LE(data2,Constants.EF_ZIP64_SCOMP);if(_centralHeader.compressedSize===Constants.EF_ZIP64_OR_32){_centralHeader.compressedSize=compressedSize}}if(data2.length>=Constants.EF_ZIP64_DSN){offset2=readUInt64LE(data2,Constants.EF_ZIP64_RHO);if(_centralHeader.offset===Constants.EF_ZIP64_OR_32){_centralHeader.offset=offset2}}if(data2.length>=Constants.EF_ZIP64_DSN+4){diskNumStart=data2.readUInt32LE(Constants.EF_ZIP64_DSN);if(_centralHeader.diskNumStart===Constants.EF_ZIP64_OR_16){_centralHeader.diskNumStart=diskNumStart}}}return{get entryName(){return decoder3.decode(_entryName)},get rawEntryName(){return _entryName},set entryName(val){_entryName=Utils.toBuffer(val,decoder3.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 decoder3.decode(_comment)},set comment(val){_comment=Utils.toBuffer(val,decoder3.encode);_centralHeader.commentLength=_comment.length;if(_comment.length>65535)throw Utils.Errors.COMMENT_TOO_LONG()},get name(){const n2=decoder3.decode(_entryName);return _isDirectory?n2.replace(/[/\\]$/,"").split("/").pop():n2.split("/").pop()},get isDirectory(){return _isDirectory},getCompressedData:function(){return compress(false,null)},getCompressedDataAsync:function(callback4){compress(true,callback4)},setData:function(value3){uncompressedData=Utils.toBuffer(value3,Utils.decoder.encode);if(!_isDirectory&&uncompressedData.length){_centralHeader.size=uncompressedData.length;_centralHeader.method=Utils.Constants.DEFLATED;_centralHeader.crc=Utils.crc32(value3);_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(callback4,pass){if(_centralHeader.changed){callback4(uncompressedData)}else{decompress(true,callback4,pass)}},set attr(attr){_centralHeader.attr=attr},get attr(){return _centralHeader.attr},set header(data2){_centralHeader.loadFromBinary(data2)},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 bytes2=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:bytes2(input),data:bytes2(uncompressedData)}},toString:function(){return JSON.stringify(this.toJSON(),null,"\t")}}}});var require_zipFile=__commonJS((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:decoder3}=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 i2=0;i2<elements.length;i2++){const sub=elements.slice(0,i2+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 i2=0;i2<entryList.length;i2++){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[i2]=entry;entryTable[entry.entryName]=entry}temporary.clear();makeTemporaryFolders()}function readMainHeader(readNow){var i2=inBuffer.length-Utils.Constants.ENDHDR,max=Math.max(0,i2-65535),n2=max,endStart=inBuffer.length,endOffset=-1,commentEnd=0;const trailingSpace=typeof opts.trailingSpace==="boolean"?opts.trailingSpace:false;if(trailingSpace)max=0;for(i2;i2>=n2;i2--){if(inBuffer[i2]!==80)continue;if(inBuffer.readUInt32LE(i2)===Utils.Constants.ENDSIG){endOffset=i2;commentEnd=i2;endStart=i2+Utils.Constants.ENDHDR;n2=i2-Utils.Constants.END64HDR;continue}if(inBuffer.readUInt32LE(i2)===Utils.Constants.END64SIG){n2=max;continue}if(inBuffer.readUInt32LE(i2)===Utils.Constants.ZIP64SIG){endOffset=i2;endStart=i2+Utils.readBigUInt64LE(inBuffer,i2+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 decoder3.decode(_comment)},set comment(val){_comment=Utils.toBuffer(val,decoder3.encode);mainHeader.commentLength=_comment.length},getEntryCount:function(){if(!loadedEntries){return mainHeader.diskEntries}return entryList.length},forEach:function(callback4){this.entries.forEach(callback4)},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 list2=this.getEntryChildren(entry,withsubfolders).map((child)=>child.entryName);list2.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 list2=[];const name=entry.entryName;for(const zipEntry of entryList){if(zipEntry.entryName.startsWith(name)){list2.push(zipEntry)}}return list2}else{return[entry]}}return[]},getChildCount:function(entry){if(entry&&entry.isDirectory){const list2=this.getEntryChildren(entry);return list2.includes(entry)?list2.length-1:list2.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((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 defaultOptions2={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),defaultOptions2);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:join4,normalize:normalize2,sep}=pth.posix;return join4(pth.isAbsolute(zipPath)?"/":".",normalize2(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,callback4){var item=getEntry(entry);if(item){item.getDataAsync(callback4)}else{callback4(null,"getEntry failed for:"+entry)}},readAsText:function(entry,encoding){var item=getEntry(entry);if(item){var data2=item.getData();if(data2&&data2.length){return data2.toString(encoding||"utf8")}}return""},readAsTextAsync:function(entry,callback4,encoding){var item=getEntry(entry);if(item){item.getDataAsync(function(data2,err){if(err){callback4(data2,err);return}if(data2&&data2.length){callback4(data2.toString(encoding||"utf8"))}else{callback4("")}})}else{callback4("")}},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 data2=_attr.isFile()?filetools.fs.readFileSync(localPath):Buffer.alloc(0);if(_attr.isDirectory())zipPath+=filetools.sep;this.addFile(zipPath,data2,comment,_attr)}else{throw Utils.Errors.FILE_NOT_FOUND(localPath)}},addLocalFileAsync:function(options2,callback4){options2=typeof options2==="object"?options2:{localPath:options2};const localPath=pth.resolve(options2.localPath);const{comment}=options2;let{zipPath,zipName}=options2;const self=this;filetools.fs.stat(localPath,function(err,stats){if(err)return callback4(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(err2,data2){if(err2)return callback4(err2,false);self.addFile(zipPath,data2,comment,stats);return setImmediate(callback4,undefined,true)})}else if(stats.isDirectory()){zipPath+=filetools.sep;self.addFile(zipPath,Buffer.alloc(0),comment,stats);return setImmediate(callback4,undefined,true)}})},addLocalFolder:function(localPath,zipPath,filter5){filter5=filenameFilter(filter5);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(filter5(p)){self.addLocalFile(filepath,pth.dirname(p))}}}}else{throw Utils.Errors.FILE_NOT_FOUND(localPath)}},addLocalFolderAsync:function(localPath,callback4,zipPath,filter5){filter5=filenameFilter(filter5);zipPath=zipPath?fixPath(zipPath):"";localPath=pth.normalize(localPath);var self=this;filetools.fs.open(localPath,"r",function(err){if(err&&err.code==="ENOENT"){callback4(undefined,Utils.Errors.FILE_NOT_FOUND(localPath))}else if(err){callback4(undefined,err)}else{var items=filetools.findFiles(localPath);var i2=-1;var next=function(){i2+=1;if(i2<items.length){var filepath=items[i2];var p=relativePath(localPath,filepath).split("\\").join("/");p=p.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"");if(filter5(p)){filetools.fs.stat(filepath,function(er0,stats){if(er0)callback4(undefined,er0);if(stats.isFile()){filetools.fs.readFile(filepath,function(er1,data2){if(er1){callback4(undefined,er1)}else{self.addFile(zipPath+p,data2,"",stats);next()}})}else{self.addFile(zipPath+p+"/",Buffer.alloc(0),"",stats);next()}})}else{process.nextTick(()=>{next()})}}else{callback4(true,undefined)}};next()}})},addLocalFolderAsync2:function(options2,callback4){const self=this;options2=typeof options2==="object"?options2:{localPath:options2};const localPath=pth.resolve(options2.localPath);let{zipPath,filter:filter5,namefix}=options2;if(filter5 instanceof RegExp){filter5=function(rx){return function(filename){return rx.test(filename)}}(filter5)}else if(typeof filter5!=="function"){filter5=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"){callback4(Utils.Errors.FILE_NOT_FOUND(localPath),false)}else if(err){callback4(err,false)}else{filetools.findFilesAsync(localPath,function(err2,fileEntries){if(err2)return callback4(err2,false);fileEntries=fileEntries.filter((dir)=>filter5(relPathFix(dir)));if(!fileEntries.length)return callback4(undefined,true);setImmediate(fileEntries.reverse().reduce(function(next,entry){return function(err3,done3){if(err3||done3===false)return setImmediate(next,err3,false);self.addLocalFileAsync({localPath:entry,zipPath:pth.dirname(relPathFix(entry)),zipName:fileNameFix(entry)},next)}},callback4))})}})},addLocalFolderPromise:function(localPath,props){return new Promise((resolve6,reject)=>{this.addLocalFolderAsync2(Object.assign({localPath},props),(err,done3)=>{if(err)return reject(err);if(done3)resolve6(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(callback4){return _zip.forEach(callback4)},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 content2=child.getData();if(!content2){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 fileAttr2=keepOriginalPermission?child.header.fileAttr:undefined;filetools.writeFileTo(childName,content2,overwrite,fileAttr2)});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,callback4){callback4=get_Fun(overwrite,keepOriginalPermission,callback4);keepOriginalPermission=get_Bool(false,keepOriginalPermission);overwrite=get_Bool(false,overwrite);if(!callback4){return new Promise((resolve6,reject)=>{this.extractAllToAsync(targetPath,overwrite,keepOriginalPermission,function(err){if(err){reject(err)}else{resolve6(this)}})})}if(!_zip){callback4(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){callback4(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 done3=(err)=>{if(!err){try{applyDirAttributes(deferredDirAttr)}catch(er){return callback4(getError("Unable to set folder permissions",er.path||""))}}callback4(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()})})}})}}},done3)()},writeZip:function(targetFileName,callback4){if(arguments.length===1){if(typeof targetFileName==="function"){callback4=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 callback4==="function")callback4(!ok?new Error("failed"):null,"")}},writeZipPromise:function(targetFileName,props){const{overwrite,perm}=Object.assign({overwrite:true},props);return new Promise((resolve6,reject)=>{if(!targetFileName&&opts.filename)targetFileName=opts.filename;if(!targetFileName)reject("ADM-ZIP: ZIP File Name Missing");this.toBufferPromise().then((zipData)=>{const ret=(done3)=>done3?resolve6(done3):reject("ADM-ZIP: Wasn't able to write zip file");filetools.writeFileToAsync(targetFileName,zipData,overwrite,perm,ret)},reject)})},toBufferPromise:function(){return new Promise((resolve6,reject)=>{_zip.toAsyncBuffer(resolve6,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,errorDescMap2,args2,originalErrorMsg)=>{const msg=[`${[errorDescMap2[errorCode]]} #${errorCode}`];args2&&msg.push(`args: ${JSON.stringify(args2)}`);msg.push(getDocsUrl(errorCode));originalErrorMsg&&msg.push(`Original Error Message:
199
199
  ${originalErrorMsg}`);return msg.join(`
200
200
  `)};var init_getShortErrorMsg=()=>{};import fs3 from"fs";import path6 from"path";function reportDiagnostic(code,message,args2,context3){try{const dir=path6.resolve(process.cwd(),".mf","diagnostics");fs3.mkdirSync(dir,{recursive:true});const output={...context3,latestErrorEvent:{code,message,args:args2,timestamp:Date.now()}};fs3.writeFileSync(path6.join(dir,"latest.json"),JSON.stringify(output,null,2))}catch{}}function logAndReport(code,descMap,args2,logger2,originalErrorMsg,context3){const msg=getShortErrorMsg2(code,descMap,args2,originalErrorMsg);reportDiagnostic(code,msg,args2,context3);return logger2(msg)}var init_node=__esm(()=>{init_getShortErrorMsg()});import{createRequire as createRequire2}from"module";import fs4,{existsSync as existsSync5,mkdirSync as mkdirSync3,realpathSync as realpathSync2,rmSync,writeFileSync as writeFileSync2}from"fs";import{fileURLToPath as fileURLToPath7}from"url";import path7,{dirname as dirname3,extname,isAbsolute as isAbsolute2,join as join4,normalize as normalize2,relative,resolve as resolve6,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,context3,name,cwd){const createHash5=(contents)=>{return crypto2.createHash("md5").update(contents).digest("hex")};const hash2=createHash5(`${JSON.stringify(tsConfig)}${name}${Date.now()}`);const tempTsConfigJsonPath=resolve6(cwd??context3,"node_modules",TEMP_DIR,`tsconfig.${hash2}.json`);mkdirSync3(dirname3(tempTsConfigJsonPath),{recursive:true});writeFileSync2(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:path7.basename(zipTypesPath),apiFileName:path7.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 cache2=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(cache2.has(val))return cache2.get(val);const out=[];cache2.set(val,out);val.forEach((v,i2)=>out.push(sanitize(v,String(i2))));return out}if(val!==null&&typeof val==="object"&&Object.getPrototypeOf(val)===Object.prototype){const obj=val;if(cache2.has(obj))return cache2.get(obj);const out={};cache2.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(fn3){const sendMessage=(message)=>new Promise((resolve7,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,(error3)=>{if(error3)reject(error3);else resolve7(undefined)})});const handleMessage=async(message)=>{if(message.type===RpcGMCallTypes.CALL){if(!process$1.send)return;let value3,error3;try{value3=await fn3(...message.args)}catch(fnError){error3=fnError}try{if(error3)await sendMessage({type:RpcGMCallTypes.REJECT,id:message.id,error:error3});else await sendMessage({type:RpcGMCallTypes.RESOLVE,id:message.id,value:value3})}catch(sendError){if(error3){if(error3 instanceof Error)console.error(error3)}console.error(sendError)}}};process$1.on("message",handleMessage)}var import_adm_zip,__defProp2,__exportAll=(all4,no_symbols)=>{let target={};for(var name in all4){__defProp2(target,name,{get:all4[name],enumerable:true})}if(!no_symbols){__defProp2(target,Symbol.toStringTag,{value:"Module"})}return target},__require3,__filename2,__dirname2,parseMajorVersion=(version3)=>{const major=Number.parseInt(version3.split(".")[0],10);return Number.isNaN(major)?0:major},isMissingTypeScriptPackage=(error3)=>typeof error3==="object"&&error3!==null&&("code"in error3)&&error3.code==="MODULE_NOT_FOUND"&&("message"in error3)&&typeof error3.message==="string"&&error3.message.includes("typescript/package.json"),resolveTypeScriptPackage=(context3=process.cwd())=>{const candidateContexts=[...new Set([context3,process.cwd()])];let missingTypeScriptError;for(const candidateContext of candidateContexts){const requireFromContext=createRequire$1(resolve6(candidateContext,"package.json"));try{return{packageJsonPath:requireFromContext.resolve("typescript/package.json"),packageJson:requireFromContext("typescript/package.json"),requireFromContext}}catch(error3){if(!isMissingTypeScriptPackage(error3))throw error3;missingTypeScriptError=error3}}throw missingTypeScriptError},getTypeScriptPackageInfo=(context3=process.cwd())=>{const{packageJsonPath,packageJson}=resolveTypeScriptPackage(context3);const version3=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:version3,majorVersion:parseMajorVersion(version3),tscBinPath:resolve6(packageRoot,bin)}},requireTypeScript=(context3=process.cwd())=>{const{requireFromContext}=resolveTypeScriptPackage(context3);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("/");mkdirSync3(mfeTypeEntryDirectory,{recursive:true});await writeFile3(mfeTypeEntry,`export * from './${relativePathToOutput}';
201
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=(value3)=>{const args2=[];let current2="";let quote2=null;let escaped=false;for(const char of value3){if(escaped){current2+=char;escaped=false;continue}if(char==="\\"){escaped=true;continue}if(quote2){if(char===quote2)quote2=null;else current2+=char;continue}if(char==='"'||char==="'"){quote2=char;continue}if(char.trim()===""){if(current2){args2.push(current2);current2=""}continue}current2+=char}if(current2)args2.push(current2);return args2},formatCommandForDisplay=(executable,args2)=>{const formatArg=(arg)=>{if(/[\s'"]/.test(arg))return JSON.stringify(arg);return arg};return[executable,...args2].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 args3=[getTypeScriptPackageInfo(getTypeScriptContext$1(remoteOptions)).tscBinPath,...resolvedCompilerArgs.slice(1),"--project",tempTsConfigJsonPath];return{executable:process.execPath,args:args3,displayCommand:formatCommandForDisplay(process.execPath,args3),shell:false}}const executable=resolvePackageManagerExecutable();const args2=[...resolvedCompilerArgs,"--project",tempTsConfigJsonPath];return{executable,args:args2,displayCommand:formatCommandForDisplay(executable,args2),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:resolve6(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,resolve6(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 zip3=new import_adm_zip.default;zip3.addLocalFolder(mfTypesPath);return zip3.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 resolve6(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(error3){fileLog(`Unable to remove types folder, ${error3}`,"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(error3){fileLog(`Error during types archive download: ${error3?.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 error3;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=exports_utils.parseOptions(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:zip3,api,alias}=remoteTypeUrls[remoteName];sum[alias]={name:remoteName,url:"",zipUrl:zip3,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=path7.join(REMOTE_ALIAS_IDENTIFIER,exposeKey).split(path7.sep).join("/");exposePaths.add(`'${exposePath}'`);sum=`T extends '${exposePath}' ? typeof import('${exposePath}') :`+sum;return sum},"any;");return`
@@ -241,19 +241,27 @@ ${prefix}}`}return stack};var FiberTypeId="~effect/Fiber";var fiberVariance={_A:
241
241
 
242
242
  `);buffer2=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 sleep3(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:value3})=>{if(!explode){const joinedValues2=(allowReserved?value3:value3.map((v)=>encodeURIComponent(v))).join(separatorArrayNoExplode(style));switch(style){case"label":return`.${joinedValues2}`;case"matrix":return`;${name}=${joinedValues2}`;case"simple":return joinedValues2;default:return`${name}=${joinedValues2}`}}const separator=separatorArrayExplode(style);const joinedValues=value3.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:value3})=>{if(value3===undefined||value3===null){return""}if(typeof value3==="object"){throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.")}return`${name}=${allowReserved?value3:encodeURIComponent(value3)}`};var serializeObjectParam=({allowReserved,explode,name,style,value:value3,valueOnly})=>{if(value3 instanceof Date){return valueOnly?value3.toISOString():`${name}=${value3.toISOString()}`}if(style!=="deepObject"&&!explode){let values=[];Object.entries(value3).forEach(([key,v])=>{values=[...values,key,allowReserved?v:encodeURIComponent(v)]});const joinedValues2=values.join(",");switch(style){case"form":return`${name}=${joinedValues2}`;case"label":return`.${joinedValues2}`;case"matrix":return`;${name}=${joinedValues2}`;default:return joinedValues2}}const separator=separatorObjectExplode(style);const joinedValues=Object.entries(value3).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 match5 of matches){let explode=false;let name=match5.substring(1,match5.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 value3=path[name];if(value3===undefined||value3===null){continue}if(Array.isArray(value3)){url=url.replace(match5,serializeArrayParam({explode,name,style,value:value3}));continue}if(typeof value3==="object"){url=url.replace(match5,serializeObjectParam({explode,name,style,value:value3,valueOnly:true}));continue}if(style==="matrix"){url=url.replace(match5,`;${serializePrimitiveParam({name,value:value3})}`);continue}const replaceValue=encodeURIComponent(style==="label"?`.${value3}`:value3);url=url.replace(match5,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,callback4)=>{const token=typeof callback4==="function"?await callback4(auth):callback4;if(!token){return}if(auth.scheme==="bearer"){return`Bearer ${token}`}if(auth.scheme==="basic"){return`Basic ${btoa(token)}`}return token};var createQuerySerializer=({parameters={},...args2}={})=>{const querySerializer=(queryParams)=>{const search=[];if(queryParams&&typeof queryParams==="object"){for(const name in queryParams){const value3=queryParams[name];if(value3===undefined||value3===null){continue}const options=parameters[name]||args2;if(Array.isArray(value3)){const serializedArray=serializeArrayParam({allowReserved:options.allowReserved,explode:true,name,style:"form",value:value3,...options.array});if(serializedArray)search.push(serializedArray)}else if(typeof value3==="object"){const serializedObject=serializeObjectParam({allowReserved:options.allowReserved,explode:true,name,style:"deepObject",value:value3,...options.object});if(serializedObject)search.push(serializedObject)}else{const serializedPrimitive=serializePrimitiveParam({allowReserved:options.allowReserved,name,value:value3});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((value3,key)=>{entries.push([key,value3])});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,value3]of iterator){if(value3===null){mergedHeaders.delete(key)}else if(Array.isArray(value3)){for(const v of value3){mergedHeaders.append(key,v)}}else if(value3!==undefined){mergedHeaders.set(key,typeof value3==="object"?JSON.stringify(value3):value3)}}}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,fn3){const index=this.getInterceptorIndex(id);if(this.fns[index]){this.fns[index]=fn3;return id}return false}use(fn3){this.fns.push(fn3);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=(config2)=>{_config=mergeConfigs(_config,config2);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 request2=new Request(url,requestInit);for(const fn3 of interceptors.request.fns){if(fn3){request2=await fn3(request2,opts)}}const _fetch=opts.fetch;let response;try{response=await _fetch(request2)}catch(error2){let finalError2=error2;for(const fn3 of interceptors.error.fns){if(fn3){finalError2=await fn3(error2,undefined,request2,opts)}}finalError2=finalError2||{};if(opts.throwOnError){throw finalError2}return opts.responseStyle==="data"?undefined:{error:finalError2,request:request2,response:undefined}}for(const fn3 of interceptors.response.fns){if(fn3){response=await fn3(response,request2,opts)}}const result3={request:request2,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,...result3}}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,...result3}}if(parseAs==="json"){if(opts.responseValidator){await opts.responseValidator(data)}if(opts.responseTransformer){data=await opts.responseTransformer(data)}}return opts.responseStyle==="data"?data:{data,...result3}}const textError=await response.text();let jsonError;try{jsonError=JSON.parse(textError)}catch{}const error=jsonError??textError;let finalError=error;for(const fn3 of interceptors.error.fns){if(fn3){finalError=await fn3(error,response,request2,opts)}}finalError=finalError||{};if(opts.throwOnError){throw finalError}return opts.responseStyle==="data"?undefined:{error:finalError,...result3}};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(url2,init)=>{let request2=new Request(url2,init);for(const fn3 of interceptors.request.fns){if(fn3){request2=await fn3(request2,opts)}}return request2},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 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 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 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 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 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 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});var organizationPublicApplicationsList=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/public-applications",...options});var organizationPublicApplicationsEnroll=(options)=>(options.client??client).put({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/public-applications/by-fqn/{fqn}",...options,headers:{"Content-Type":"application/json",...options.headers}});var organizationPublicApplicationsGet=(options)=>(options.client??client).get({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/public-applications/{id}",...options});var organizationPublicApplicationsDisable=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/public-applications/{id}/disable",...options});var organizationPublicApplicationsRotateCredential=(options)=>(options.client??client).post({security:[{scheme:"bearer",type:"http"}],url:"/admin/organization/public-applications/{id}/credential/rotate",...options});var normalizedBackendUrl=(value3)=>value3.replace(/\/$/u,"");var makeBackendManagementClient=(config)=>createClient({baseUrl:normalizedBackendUrl(config.backendUrl),fetch:config.fetch,headers:config.token===undefined?{}:{authorization:`Bearer ${config.token}`}});function makeValue(value3){return{_tag:"Value",value:value3}}function makeRecord(keys,value3){return{_tag:"Record",keys,value:value3}}function makeArray(length,value3){return{_tag:"Array",length,value:value3}}var ConfigProvider=Reference("effect/ConfigProvider",{defaultValue:()=>fromEnv()});var Proto3={...PipeInspectableProto,toJSON(){return{_id:"ConfigProvider"}}};var identityPath=(path)=>path;function makeProvider(load,mapInput2){const self=Object.create(Proto3);self.load=load;self.mapInput=mapInput2;return self}function makeSource(get2,transform3){return makeProvider((path)=>get2(transform3(path)),(f)=>makeSource(get2,(path)=>f(transform3(path))))}function make14(get2){return makeSource(get2,identityPath)}var layer6=(self)=>isEffect2(self)?effect(ConfigProvider)(self):succeed5(ConfigProvider)(self);function fromUnknown(root,options){const preserveEmptyStrings=options?.preserveEmptyStrings===true;return make14((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(value3,preserveEmptyStrings){const normalized=emptyStringAsMissing(value3,preserveEmptyStrings);return normalized===undefined?undefined:makeValue(normalized)}function emptyStringAsMissing(value3,preserveEmptyStrings){return value3===""&&!preserveEmptyStrings?undefined:value3}function fromEnvRecord(env,options){const preserveEmptyStrings=options?.preserveEmptyStrings===true;const trie=buildEnvTrie(env);return make14((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,value3]of Object.entries(env)){if(value3===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(fiber2){return this.parse(fiber2.getRef(ConfigProvider))}}),[TypeId20]:TypeId20,toJSON(){return{_id:"Config"}}};function make15(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,decode2)=>decodeTo(unknown,ast,new Transformation(transformEffect((input)=>decode2(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((ast2)=>hasProviderInput(ast2,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((is3)=>_is(is3.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,(ast2)=>ast2),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(make13(toConfigCursorAST(codecStringTree.ast)));const localPath=typeof path==="string"?[path]:path??[];return make15((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:String4}){}var tryConfiguration=(evaluate2)=>try_2({catch:(cause)=>is2(BackendManagementConfigurationError)(cause)?cause:new BackendManagementConfigurationError({message:cause instanceof Error?cause.message:"CLI configuration step failed"}),try:evaluate2});import{chmodSync,existsSync,mkdirSync,readFileSync,renameSync,writeFileSync}from"fs";import path from"path";var ProfileSchema=Struct({apiOrigin:String4,currentOrganizationId:optionalKey2(String4),session:optionalKey2(Struct({expiresAt:optionalKey2(String4),token:String4}))});var ProfileStoreSchema=Struct({current:optionalKey2(String4),profiles:Record(String4,ProfileSchema)});var profileStoreJson=fromJsonString2(ProfileStoreSchema);var decodeProfileStore=decodeUnknownSync(profileStoreJson);var encodeProfileStore=encodeSync(profileStoreJson);var nonEmpty=(value3)=>value3===""?undefined:value3;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=(value3)=>value3===undefined||value3.trim()===""?undefined:value3;var optionValue=(args2,name)=>{const index=args2.indexOf(`--${name}`);const value3=index===-1?undefined:args2[index+1];return value3===undefined||value3.startsWith("--")?undefined:value3};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 profile2=storedProfile(store,requestedName);if(profile2===undefined){throw configurationError(`CLI Profile ${requestedName} does not exist; run ci login or select another --profile`)}if(explicitOrigin!==undefined&&!sameOrigin(profile2.apiOrigin,explicitOrigin)){throw configurationError(`CLI Profile ${requestedName} belongs to ${profile2.apiOrigin}, not ${explicitOrigin}`)}return{name:requestedName,profile:profile2}}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:args2,environment}=input;const explicitOrigin=nonEmpty2(optionValue(args2,"backend-url"))??nonEmpty2(environment.CI_BACKEND_URL);const environmentToken=nonEmpty2(environment.CI_MANAGEMENT_TOKEN);const explicitOrganization=nonEmpty2(optionValue(args2,"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(args2,"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*deploymentManagementClients2(input){const publisher=yield*schema(Redacted(String4.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,tag2)=>is2(TaggedStruct(tag2,{}))(cause);var createDevelopmentSession=async(client2,input)=>{try{const result3=await developmentSessionsCreate({body:{hostOrigins:[...input.hostOrigins],packageManifest:{fqn:input.packageFqn},protocolVersion:"v1"},client:client2,throwOnError:true});return result3.data}catch(error){throw hasWireTag(error,"Conflict")?new DevelopmentSessionRejectedError({reason:"session_owned"}):error}};var updateDevelopmentSessionLocalManifest=flow((client2,input)=>tryPromise2(()=>developmentSessionsUpdateLocalManifest({body:{hostedContributions:[...input.hostedContributions]},client:client2,path:{sessionId:input.sessionId},throwOnError:true})).pipe(map4((result3)=>result3.data),mapError2((cause)=>hasWireTag(cause.cause,"NotFound")?new DevelopmentSessionRejectedError({reason:"session_not_found"}):cause)),runPromise2);var heartbeatDevelopmentSession=flow((client2,sessionId)=>tryPromise2(()=>developmentSessionsHeartbeat({client:client2,path:{sessionId},throwOnError:true})).pipe(asVoid2,mapError2((cause)=>hasWireTag(cause.cause,"NotFound")?new DevelopmentSessionRejectedError({reason:"session_not_found"}):cause)),runPromise2);var terminateDevelopmentSession=flow((client2,sessionId)=>tryPromise2(()=>developmentSessionsTerminate({client:client2,path:{sessionId},throwOnError:true})).pipe(asVoid2),runPromise2);class ManagementRequestError extends TaggedError3()("ManagementRequestError",{body:optional2(Unknown2),cause:optional2(Unknown2),message:String4,status:Finite}){}var BackendReason=Union2([Struct({message:String4}),Struct({detail:String4}),Struct({error_description:String4}),Struct({error:String4})]);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)=>(effect2)=>effect2.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"),flatMap3((result3)=>{const{response}=result3;return response===undefined?fail6(unreachable(label,result3.error)):succeed6({response,result:result3})}));var managementData=(label,operation,options)=>flatMap3(sendRequest(label,operation,options),({response,result:result3})=>response.ok&&result3.data!==undefined?succeed6(result3.data):fail6(requestFailure(label,response,result3.error)));var managementOk=(label,operation,options)=>flatMap3(sendRequest(label,operation,options),({response,result:result3})=>response.ok?void_3:fail6(requestFailure(label,response,result3.error)));var TenantDiscoverySchema=Struct({api_base_url:String4,dashboard_url:String4,issuer:String4,jwks_uri:String4});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*readTenantDiscovery2(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*readSigningKeyCount2(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 Public Application signing key (set APP_PUBLIC_APPLICATION_JWT_PRIVATE_JWK)",status:503})}if(!response.ok||!is2(JwksSchema)(body)){return yield*requestFailure(label,response,body)}return body.keys.length});var readIdentity=(client2)=>managementData("Identity read",authMe,{client:client2});var resolveManagementContext=fn2("BackendManagement.resolveContext")(function*resolveManagementContext2(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 client2=makeBackendManagementClient({backendUrl:target.apiOrigin,fetch:input.fetch,token:target.token});const organizationId=target.organizationId===undefined&&isOrganizationApiKey(target.token)?(yield*readIdentity(client2)).organizationId:target.organizationId;return{client:client2,organizationId,target}});var resolveOrganizationContext=(input)=>flatMap3(resolveManagementContext(input),(context3)=>{const{organizationId}=context3;return organizationId===undefined?fail6(new BackendManagementConfigurationError({message:missingOrganizationMessage})):succeed6({...context3,organizationId})});var explainOrganizationForbidden=(context3,organizationId)=>(error)=>error.status===403&&isOrganizationApiKey(context3.target.token)?readIdentity(context3.client).pipe(map4((identity2)=>apiKeyOrganizationMismatch({apiKey:identity2.apiKeyName===undefined||identity2.organizationId===undefined?undefined:{name:identity2.apiKeyName,organizationId:identity2.organizationId},organizationId,token:context3.target.token})??error),orElseSucceed2(()=>error),flatMap3(fail6)):fail6(error);class CommandOptionsError extends TaggedError3()("CommandOptionsError",{message:String4}){}var targetOptions=["backend-url","organization","profile"];var parseCommandOptions=(args2,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<args2.length;index+=1){const argument=args2[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 value3=args2[index+1];if(value3===undefined||value3.startsWith("--")||value3.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??[],value3])}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=(args2,spec)=>try_2({catch:(cause)=>is2(CommandOptionsError)(cause)?cause:new CommandOptionsError({message:"Invalid options"}),try:()=>parseCommandOptions(args2,spec)});class AppsCommandError extends TaggedError3()("AppsCommandError",{cause:optional2(Unknown2),message:String4}){}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 ...";var encodeJson=encodeSync(fromJsonString2(Unknown2));var summary=(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,redirectUris:application.redirectUris,scopes:application.scopes});var appsCommandEffect=(args2,dependencies)=>gen2(function*appsCommand(){const[command,...rest]=args2;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 context3=yield*resolveOrganizationContext({args:rest,environment:dependencies.environment,fetch:dependencies.fetch});const request={client:context3.client,headers:{"x-organization-id":context3.organizationId}};const operation=(id)=>gen2(function*appsOperation(){if(command==="get"){return summary(yield*managementData("Public Application read",organizationPublicApplicationsGet,{...request,path:{id}}))}if(command==="disable"){return summary(yield*managementData("Public Application disable",organizationPublicApplicationsDisable,{...request,path:{id}}))}const rotated=yield*managementData("Client secret rotation",organizationPublicApplicationsRotateCredential,{...request,path:{id}});return{applicationId:rotated.application.id,clientId:rotated.application.clientId,clientSecret:rotated.clientSecret}});const explainForbidden=(effect2)=>effect2.pipe(catchTag2("ManagementRequestError",explainOrganizationForbidden(context3,context3.organizationId)));const result3=applicationId===undefined?yield*explainForbidden(managementData("Public Application list",organizationPublicApplicationsList,request).pipe(map4((response)=>response.data.map(summary)))):yield*explainForbidden(operation(applicationId));return yield*sync2(()=>{dependencies.writeOutput(`${encodeJson(result3)}
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 missing3=redirectUris.filter((uri)=>!applications.some((application2)=>application2.enabled&&application2.redirectUris.includes(uri)));return missing3.length===0?check("redirect-uri",true,`registered: ${redirectUris.join(", ")}`):check("redirect-uri",false,`no enabled Public Application registers ${missing3.join(", ")}`)}const application=applications.find((candidate)=>candidate.fqn===fqn);if(application===undefined){return check("redirect-uri",false,`no Public Application ${fqn} exists`)}if(!application.enabled){return check("redirect-uri",false,`Public Application ${fqn} is disabled`)}const expected=redirectUris.length===0?application.redirectUris:redirectUris;const missing2=expected.filter((uri)=>!application.redirectUris.includes(uri));return missing2.length===0&&expected.length>0?check("redirect-uri",true,`${fqn} registers ${expected.join(", ")}`):check("redirect-uri",false,`${fqn} does not register ${missing2.length===0?"any redirect URI":missing2.join(", ")}`)};var listApplications=(context3)=>managementData("Public Application list",organizationPublicApplicationsList,{client:context3.client,headers:{"x-organization-id":context3.organizationId}}).pipe(map4((response)=>response.data),catchTag2("ManagementRequestError",explainOrganizationForbidden(context3,context3.organizationId)));var runTenantPreflight=fn2("Preflight.tenant")(function*runTenantPreflight2(input){const{context:context3}=input;const{apiOrigin}=context3.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(context3));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 ${context3.organizationId} is accessible with this credential`):check("organization",false,applications.failure.message)],discovery:isSuccess2(discovery)?discovery.success:undefined}});var runRedirectPreflight=fn2("Preflight.redirect")(function*runRedirectPreflight2(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*runPreflight2(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 sleep3(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:value3})=>{if(!explode){const joinedValues2=(allowReserved?value3:value3.map((v)=>encodeURIComponent(v))).join(separatorArrayNoExplode(style));switch(style){case"label":return`.${joinedValues2}`;case"matrix":return`;${name}=${joinedValues2}`;case"simple":return joinedValues2;default:return`${name}=${joinedValues2}`}}const separator=separatorArrayExplode(style);const joinedValues=value3.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:value3})=>{if(value3===undefined||value3===null){return""}if(typeof value3==="object"){throw new Error("Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these.")}return`${name}=${allowReserved?value3:encodeURIComponent(value3)}`};var serializeObjectParam=({allowReserved,explode,name,style,value:value3,valueOnly})=>{if(value3 instanceof Date){return valueOnly?value3.toISOString():`${name}=${value3.toISOString()}`}if(style!=="deepObject"&&!explode){let values=[];Object.entries(value3).forEach(([key,v])=>{values=[...values,key,allowReserved?v:encodeURIComponent(v)]});const joinedValues2=values.join(",");switch(style){case"form":return`${name}=${joinedValues2}`;case"label":return`.${joinedValues2}`;case"matrix":return`;${name}=${joinedValues2}`;default:return joinedValues2}}const separator=separatorObjectExplode(style);const joinedValues=Object.entries(value3).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 match5 of matches){let explode=false;let name=match5.substring(1,match5.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 value3=path[name];if(value3===undefined||value3===null){continue}if(Array.isArray(value3)){url=url.replace(match5,serializeArrayParam({explode,name,style,value:value3}));continue}if(typeof value3==="object"){url=url.replace(match5,serializeObjectParam({explode,name,style,value:value3,valueOnly:true}));continue}if(style==="matrix"){url=url.replace(match5,`;${serializePrimitiveParam({name,value:value3})}`);continue}const replaceValue=encodeURIComponent(style==="label"?`.${value3}`:value3);url=url.replace(match5,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,callback4)=>{const token=typeof callback4==="function"?await callback4(auth):callback4;if(!token){return}if(auth.scheme==="bearer"){return`Bearer ${token}`}if(auth.scheme==="basic"){return`Basic ${btoa(token)}`}return token};var createQuerySerializer=({parameters={},...args2}={})=>{const querySerializer=(queryParams)=>{const search=[];if(queryParams&&typeof queryParams==="object"){for(const name in queryParams){const value3=queryParams[name];if(value3===undefined||value3===null){continue}const options=parameters[name]||args2;if(Array.isArray(value3)){const serializedArray=serializeArrayParam({allowReserved:options.allowReserved,explode:true,name,style:"form",value:value3,...options.array});if(serializedArray)search.push(serializedArray)}else if(typeof value3==="object"){const serializedObject=serializeObjectParam({allowReserved:options.allowReserved,explode:true,name,style:"deepObject",value:value3,...options.object});if(serializedObject)search.push(serializedObject)}else{const serializedPrimitive=serializePrimitiveParam({allowReserved:options.allowReserved,name,value:value3});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((value3,key)=>{entries.push([key,value3])});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,value3]of iterator){if(value3===null){mergedHeaders.delete(key)}else if(Array.isArray(value3)){for(const v of value3){mergedHeaders.append(key,v)}}else if(value3!==undefined){mergedHeaders.set(key,typeof value3==="object"?JSON.stringify(value3):value3)}}}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,fn3){const index=this.getInterceptorIndex(id);if(this.fns[index]){this.fns[index]=fn3;return id}return false}use(fn3){this.fns.push(fn3);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=(config2)=>{_config=mergeConfigs(_config,config2);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 request2=new Request(url,requestInit);for(const fn3 of interceptors.request.fns){if(fn3){request2=await fn3(request2,opts)}}const _fetch=opts.fetch;let response;try{response=await _fetch(request2)}catch(error2){let finalError2=error2;for(const fn3 of interceptors.error.fns){if(fn3){finalError2=await fn3(error2,undefined,request2,opts)}}finalError2=finalError2||{};if(opts.throwOnError){throw finalError2}return opts.responseStyle==="data"?undefined:{error:finalError2,request:request2,response:undefined}}for(const fn3 of interceptors.response.fns){if(fn3){response=await fn3(response,request2,opts)}}const result3={request:request2,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,...result3}}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,...result3}}if(parseAs==="json"){if(opts.responseValidator){await opts.responseValidator(data)}if(opts.responseTransformer){data=await opts.responseTransformer(data)}}return opts.responseStyle==="data"?data:{data,...result3}}const textError=await response.text();let jsonError;try{jsonError=JSON.parse(textError)}catch{}const error=jsonError??textError;let finalError=error;for(const fn3 of interceptors.error.fns){if(fn3){finalError=await fn3(error,response,request2,opts)}}finalError=finalError||{};if(opts.throwOnError){throw finalError}return opts.responseStyle==="data"?undefined:{error:finalError,...result3}};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(url2,init)=>{let request2=new Request(url2,init);for(const fn3 of interceptors.request.fns){if(fn3){request2=await fn3(request2,opts)}}return request2},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 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 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 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 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 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 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});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=(value3)=>value3.replace(/\/$/u,"");var makeBackendManagementClient=(config)=>createClient({baseUrl:normalizedBackendUrl(config.backendUrl),fetch:config.fetch,headers:config.token===undefined?{}:{authorization:`Bearer ${config.token}`}});function makeValue(value3){return{_tag:"Value",value:value3}}function makeRecord(keys,value3){return{_tag:"Record",keys,value:value3}}function makeArray(length,value3){return{_tag:"Array",length,value:value3}}var ConfigProvider=Reference("effect/ConfigProvider",{defaultValue:()=>fromEnv()});var Proto3={...PipeInspectableProto,toJSON(){return{_id:"ConfigProvider"}}};var identityPath=(path)=>path;function makeProvider(load,mapInput2){const self=Object.create(Proto3);self.load=load;self.mapInput=mapInput2;return self}function makeSource(get2,transform3){return makeProvider((path)=>get2(transform3(path)),(f)=>makeSource(get2,(path)=>f(transform3(path))))}function make14(get2){return makeSource(get2,identityPath)}var layer6=(self)=>isEffect2(self)?effect(ConfigProvider)(self):succeed5(ConfigProvider)(self);function fromUnknown(root,options){const preserveEmptyStrings=options?.preserveEmptyStrings===true;return make14((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(value3,preserveEmptyStrings){const normalized=emptyStringAsMissing(value3,preserveEmptyStrings);return normalized===undefined?undefined:makeValue(normalized)}function emptyStringAsMissing(value3,preserveEmptyStrings){return value3===""&&!preserveEmptyStrings?undefined:value3}function fromEnvRecord(env,options){const preserveEmptyStrings=options?.preserveEmptyStrings===true;const trie=buildEnvTrie(env);return make14((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,value3]of Object.entries(env)){if(value3===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(fiber2){return this.parse(fiber2.getRef(ConfigProvider))}}),[TypeId20]:TypeId20,toJSON(){return{_id:"Config"}}};function make15(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,decode2)=>decodeTo(unknown,ast,new Transformation(transformEffect((input)=>decode2(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((ast2)=>hasProviderInput(ast2,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((is3)=>_is(is3.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,(ast2)=>ast2),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(make13(toConfigCursorAST(codecStringTree.ast)));const localPath=typeof path==="string"?[path]:path??[];return make15((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:String4}){}var tryConfiguration=(evaluate2)=>try_2({catch:(cause)=>is2(BackendManagementConfigurationError)(cause)?cause:new BackendManagementConfigurationError({message:cause instanceof Error?cause.message:"CLI configuration step failed"}),try:evaluate2});import{chmodSync,existsSync,mkdirSync,readFileSync,renameSync,writeFileSync}from"fs";import path from"path";var ProfileSchema=Struct({apiOrigin:String4,currentOrganizationId:optionalKey2(String4),session:optionalKey2(Struct({expiresAt:optionalKey2(String4),token:String4}))});var ProfileStoreSchema=Struct({current:optionalKey2(String4),profiles:Record(String4,ProfileSchema)});var profileStoreJson=fromJsonString2(ProfileStoreSchema);var decodeProfileStore=decodeUnknownSync(profileStoreJson);var encodeProfileStore=encodeSync(profileStoreJson);var nonEmpty=(value3)=>value3===""?undefined:value3;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=(value3)=>value3===undefined||value3.trim()===""?undefined:value3;var optionValue=(args2,name)=>{const index=args2.indexOf(`--${name}`);const value3=index===-1?undefined:args2[index+1];return value3===undefined||value3.startsWith("--")?undefined:value3};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 profile2=storedProfile(store,requestedName);if(profile2===undefined){throw configurationError(`CLI Profile ${requestedName} does not exist; run ci login or select another --profile`)}if(explicitOrigin!==undefined&&!sameOrigin(profile2.apiOrigin,explicitOrigin)){throw configurationError(`CLI Profile ${requestedName} belongs to ${profile2.apiOrigin}, not ${explicitOrigin}`)}return{name:requestedName,profile:profile2}}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:args2,environment}=input;const explicitOrigin=nonEmpty2(optionValue(args2,"backend-url"))??nonEmpty2(environment.CI_BACKEND_URL);const environmentToken=nonEmpty2(environment.CI_MANAGEMENT_TOKEN);const explicitOrganization=nonEmpty2(optionValue(args2,"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(args2,"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*deploymentManagementClients2(input){const publisher=yield*schema(Redacted(String4.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,tag2)=>is2(TaggedStruct(tag2,{}))(cause);var createDevelopmentSession=async(client2,input)=>{try{const result3=await developmentSessionsCreate({body:{hostOrigins:[...input.hostOrigins],packageManifest:{fqn:input.packageFqn},protocolVersion:"v1"},client:client2,throwOnError:true});return result3.data}catch(error){throw hasWireTag(error,"Conflict")?new DevelopmentSessionRejectedError({reason:"session_owned"}):error}};var updateDevelopmentSessionLocalManifest=flow((client2,input)=>tryPromise2(()=>developmentSessionsUpdateLocalManifest({body:{hostedContributions:[...input.hostedContributions]},client:client2,path:{sessionId:input.sessionId},throwOnError:true})).pipe(map4((result3)=>result3.data),mapError2((cause)=>hasWireTag(cause.cause,"NotFound")?new DevelopmentSessionRejectedError({reason:"session_not_found"}):cause)),runPromise2);var heartbeatDevelopmentSession=flow((client2,sessionId)=>tryPromise2(()=>developmentSessionsHeartbeat({client:client2,path:{sessionId},throwOnError:true})).pipe(asVoid2,mapError2((cause)=>hasWireTag(cause.cause,"NotFound")?new DevelopmentSessionRejectedError({reason:"session_not_found"}):cause)),runPromise2);var terminateDevelopmentSession=flow((client2,sessionId)=>tryPromise2(()=>developmentSessionsTerminate({client:client2,path:{sessionId},throwOnError:true})).pipe(asVoid2),runPromise2);class ManagementRequestError extends TaggedError3()("ManagementRequestError",{body:optional2(Unknown2),cause:optional2(Unknown2),message:String4,status:Finite}){}var BackendReason=Union2([Struct({message:String4}),Struct({detail:String4}),Struct({error_description:String4}),Struct({error:String4})]);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)=>(effect2)=>effect2.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"),flatMap3((result3)=>{const{response}=result3;return response===undefined?fail6(unreachable(label,result3.error)):succeed6({response,result:result3})}));var managementData=(label,operation,options)=>flatMap3(sendRequest(label,operation,options),({response,result:result3})=>response.ok&&result3.data!==undefined?succeed6(result3.data):fail6(requestFailure(label,response,result3.error)));var managementOk=(label,operation,options)=>flatMap3(sendRequest(label,operation,options),({response,result:result3})=>response.ok?void_3:fail6(requestFailure(label,response,result3.error)));var TenantDiscoverySchema=Struct({api_base_url:String4,dashboard_url:String4,issuer:String4,jwks_uri:String4});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*readTenantDiscovery2(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*readSigningKeyCount2(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=(client2)=>managementData("Identity read",authMe,{client:client2});var resolveManagementContext=fn2("BackendManagement.resolveContext")(function*resolveManagementContext2(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 client2=makeBackendManagementClient({backendUrl:target.apiOrigin,fetch:input.fetch,token:target.token});const organizationId=target.organizationId===undefined&&isOrganizationApiKey(target.token)?(yield*readIdentity(client2)).organizationId:target.organizationId;return{client:client2,organizationId,target}});var resolveOrganizationContext=(input)=>flatMap3(resolveManagementContext(input),(context3)=>{const{organizationId}=context3;return organizationId===undefined?fail6(new BackendManagementConfigurationError({message:missingOrganizationMessage})):succeed6({...context3,organizationId})});var explainOrganizationForbidden=(context3,organizationId)=>(error)=>error.status===403&&isOrganizationApiKey(context3.target.token)?readIdentity(context3.client).pipe(map4((identity2)=>apiKeyOrganizationMismatch({apiKey:identity2.apiKeyName===undefined||identity2.organizationId===undefined?undefined:{name:identity2.apiKeyName,organizationId:identity2.organizationId},organizationId,token:context3.target.token})??error),orElseSucceed2(()=>error),flatMap3(fail6)):fail6(error);class CommandOptionsError extends TaggedError3()("CommandOptionsError",{message:String4}){}var targetOptions=["backend-url","organization","profile"];var parseCommandOptions=(args2,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<args2.length;index+=1){const argument=args2[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 value3=args2[index+1];if(value3===undefined||value3.startsWith("--")||value3.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??[],value3])}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=(args2,spec)=>try_2({catch:(cause)=>is2(CommandOptionsError)(cause)?cause:new CommandOptionsError({message:"Invalid options"}),try:()=>parseCommandOptions(args2,spec)});class AppsCommandError extends TaggedError3()("AppsCommandError",{cause:optional2(Unknown2),message:String4}){}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 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=(args2,dependencies)=>gen2(function*appsCommand(){const[command,...rest]=args2;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 context3=yield*resolveOrganizationContext({args:rest,environment:dependencies.environment,fetch:dependencies.fetch});const request={client:context3.client,headers:{"x-organization-id":context3.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=(effect2)=>effect2.pipe(catchTag2("ManagementRequestError",explainOrganizationForbidden(context3,context3.organizationId)));const result3=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(result3)}
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 missing3=redirectUris.filter((uri)=>!applications.some((application2)=>application2.enabled&&application2.redirectUris.includes(uri)));return missing3.length===0?check("redirect-uri",true,`registered: ${redirectUris.join(", ")}`):check("redirect-uri",false,`no enabled External App registers ${missing3.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 missing2=expected.filter((uri)=>!application.redirectUris.includes(uri));return missing2.length===0&&expected.length>0?check("redirect-uri",true,`${fqn} registers ${expected.join(", ")}`):check("redirect-uri",false,`${fqn} does not register ${missing2.length===0?"any redirect URI":missing2.join(", ")}`)};var listApplications=(context3)=>managementData("External App list",organizationExternalAppsList,{client:context3.client,headers:{"x-organization-id":context3.organizationId}}).pipe(map4((response)=>response.data),catchTag2("ManagementRequestError",explainOrganizationForbidden(context3,context3.organizationId)));var runTenantPreflight=fn2("Preflight.tenant")(function*runTenantPreflight2(input){const{context:context3}=input;const{apiOrigin}=context3.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(context3));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 ${context3.organizationId} is accessible with this credential`):check("organization",false,applications.failure.message)],discovery:isSuccess2(discovery)?discovery.success:undefined}});var runRedirectPreflight=fn2("Preflight.redirect")(function*runRedirectPreflight2(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*runPreflight2(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
- `;var plainValue=/^[\w./:@+,=-]*$/u;var assignment=/^(?<lead>\s*(?:export\s+)?)(?<key>[A-Za-z_][A-Za-z0-9_]*)\s*=(?<value>.*)$/u;var quote=(value3)=>plainValue.test(value3)?value3:`"${value3.replaceAll("\\","\\\\").replaceAll('"',"\\\"")}"`;var doubleQuoted=/^"(?<value>(?:[^"\\]|\\.)*)"/u;var singleQuoted=/^'(?<value>[^']*)'/u;var inlineComment=/(?:^|\s)#.*$/u;var unquote=(raw)=>{const value3=raw.trim();const double=doubleQuoted.exec(value3)?.groups?.value;if(double!==undefined){return double.replaceAll(/\\(?<escaped>["\\])/gu,"$<escaped>")}return singleQuoted.exec(value3)?.groups?.value??value3.replace(inlineComment,"").trim()};var prefixed=(prefix,values)=>values.map(([key,value3])=>[`${prefix}${key}`,value3]);var renderDotenv=(prefix,values)=>`${prefixed(prefix,values).map(([key,value3])=>`${key}=${quote(value3)}`).join(`
248
+ `;var loopbackHostnames=new Set(["localhost","127.0.0.1","[::1]"]);var exactUrlProblem=(value3,kind)=>{if(!URL.canParse(value3)){return`${value3} is not an absolute URL`}const url=new URL(value3);if(value3.includes("#")){return`${value3} must not contain a fragment (#)`}if(value3.includes("*")){return`${value3} must not contain a wildcard (*)`}const loopbackHttp=url.protocol==="http:"&&loopbackHostnames.has(url.hostname)&&url.port!=="";if(url.protocol!=="https:"&&!loopbackHttp){return`${value3} must use HTTPS, or HTTP on localhost, 127.0.0.1 or [::1] with an explicit port`}if(kind==="origin"&&value3!==url.origin){return`${value3} is not an exact origin; use ${url.origin}`}return};var originOf=(value3)=>URL.canParse(value3)?new URL(value3).origin:value3;class AppsUrlsCommandError extends TaggedError3()("AppsUrlsCommandError",{cause:optional2(Unknown2),message:String4}){}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=(value3)=>value3==="origins"||value3==="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
+ `)}else{body.redirectUris=[...redirectUris,uri]}if((switches.has("primary")||primaryRedirectUri===null)&&uri!==primaryRedirectUri){body.primaryRedirectUri=uri}const origin2=originOf(uri);if(!switches.has("no-trust-origin")&&!allowedOrigins.includes(origin2)){body.allowedOrigins=[...allowedOrigins,origin2];notes.push(`Trusted origin ${origin2} for ${fqn}; pass --no-trust-origin to skip this
250
+ `)}return succeed6(plan(body,notes))}if(!registered){return fail6(fail11(action==="set-primary"?`${uri} is not a redirect URI of ${fqn}; run ci apps redirect-uris add ${fqn} ${uri} --primary`:`${uri} is not a redirect URI of ${fqn}`))}if(action==="set-primary"){return succeed6(uri===primaryRedirectUri?plan({},[`${uri} is already the primary redirect URI of ${fqn}
251
+ `]):plan({primaryRedirectUri:uri},[]))}if(redirectUris.length===1){return fail6(fail11(`${uri} is the only redirect URI of ${fqn}; add another redirect URI before you remove it`))}if(uri===primaryRedirectUri){return fail6(fail11(`${uri} is the primary redirect URI of ${fqn}; run ci apps redirect-uris set-primary ${fqn} <other-uri> first`))}const remaining=redirectUris.filter((candidate)=>candidate!==uri);const origin=originOf(uri);const unusedOrigin=allowedOrigins.includes(origin)&&!remaining.some((candidate)=>originOf(candidate)===origin);return succeed6(plan({redirectUris:remaining},unusedOrigin?[`No other redirect URI of ${fqn} uses ${origin}; to stop trusting it, run ci apps origins remove ${fqn} ${origin}
252
+ `]:[]))};var originPlan=(application,action,origin)=>{const{allowedOrigins,fqn,redirectUris}=application;const trusted=allowedOrigins.includes(origin);if(action==="add"){return succeed6(trusted?plan({},[`${origin} is already a trusted origin of ${fqn}
253
+ `]):plan({allowedOrigins:[...allowedOrigins,origin]},[]))}if(!trusted){return fail6(fail11(`${origin} is not a trusted origin of ${fqn}`))}const users=redirectUris.filter((uri)=>originOf(uri)===origin);return succeed6(plan({allowedOrigins:allowedOrigins.filter((candidate)=>candidate!==origin)},users.length===0?[]:[`Warning: ${fqn} no longer trusts ${origin}, but its redirect URIs still use it: ${users.join(", ")}
254
+ `]))};var readApplication=(context3,reference)=>{const request={client:context3.client,headers:{"x-organization-id":context3.organizationId}};const notFound2=fail11(`No External App ${reference} in Organization ${context3.organizationId}; pass an Application Id or FQN from ci apps list`);return applicationIdPattern.test(reference)?managementData("External App read",organizationExternalAppsGet,{...request,path:{id:reference}}).pipe(catchIf2((error)=>error.status===404,()=>fail6(notFound2))):managementData("External App list",organizationExternalAppsList,request).pipe(flatMap3((response)=>{const found=response.data.find((application)=>application.fqn===reference);return found===undefined?fail6(notFound2):succeed6(found)}))};var parseUrlCommand=(args2)=>gen2(function*parseUrlCommandEffect(){const[group,action="",...rest]=args2;if(!isGroup(group)||!actions[group].has(action)){return yield*fail11(usage2)}const options=yield*parseCommandOptionsEffect(rest,{positionals:action==="list"?1:2,switches:group==="redirect-uris"&&action==="add"?["no-trust-origin","primary"]:[],values:targetOptions});const[reference,value3=""]=options.positionals;if(reference===undefined||action!=="list"&&value3===""){return yield*fail11(usage2)}const problem=action==="add"?exactUrlProblem(value3,group==="origins"?"origin":"url"):undefined;if(problem!==undefined){return yield*fail11(`Invalid ${group==="origins"?"origin":"redirect URI"}: ${problem}`)}return{action,group,reference,rest,switches:options.switches,value:value3}});var appsUrlsCommandEffect=(args2,dependencies)=>gen2(function*appsUrlsCommand(){const command=yield*parseUrlCommand(args2);const{action,group,value:value3}=command;const context3=yield*resolveOrganizationContext({args:command.rest,environment:dependencies.environment,fetch:dependencies.fetch});const explainForbidden=explainOrganizationForbidden(context3,context3.organizationId);const application=yield*readApplication(context3,command.reference).pipe(catchTag2("ManagementRequestError",explainForbidden));const writeJson=(output)=>sync2(()=>{dependencies.writeOutput(`${encodeJson2(output)}
255
+ `)});if(action==="list"){return yield*writeJson(group==="origins"?{allowedOrigins:application.allowedOrigins}:{primaryRedirectUri:application.primaryRedirectUri,redirectUris:application.redirectUris})}if(isPackageOwned(application)){return yield*fail11(`External App ${application.fqn} is package-owned; change it through its Extension Package`)}const change=group==="origins"?yield*originPlan(application,action,value3):yield*redirectUriPlan(application,action,value3,command.switches);const notes=change.notes.join("");const{body}=change;if(body===undefined){dependencies.writeDiagnostic(`${notes}Nothing changed for External App ${application.fqn}
256
+ `);return yield*writeJson(applicationSummary(application))}const updated=yield*managementData("External App update",organizationExternalAppsUpdate,{body,client:context3.client,headers:{"x-organization-id":context3.organizationId},path:{id:application.id}}).pipe(catchTag2("ManagementRequestError",explainForbidden));if(notes!==""){dependencies.writeDiagnostic(notes)}if(group==="redirect-uris"&&action==="add"){const redirect=yield*runRedirectPreflight({context:context3,fqn:updated.fqn,redirectUris:[value3]});dependencies.writeDiagnostic(renderPreflight([redirect]))}return yield*writeJson(applicationSummary(updated))}).pipe(mapError2((cause)=>is2(AppsUrlsCommandError)(cause)?cause:new AppsUrlsCommandError({cause,message:cause.message})));var plainValue=/^[\w./:@+,=-]*$/u;var assignment=/^(?<lead>\s*(?:export\s+)?)(?<key>[A-Za-z_][A-Za-z0-9_]*)\s*=(?<value>.*)$/u;var quote=(value3)=>plainValue.test(value3)?value3:`"${value3.replaceAll("\\","\\\\").replaceAll('"',"\\\"")}"`;var doubleQuoted=/^"(?<value>(?:[^"\\]|\\.)*)"/u;var singleQuoted=/^'(?<value>[^']*)'/u;var inlineComment=/(?:^|\s)#.*$/u;var unquote=(raw)=>{const value3=raw.trim();const double=doubleQuoted.exec(value3)?.groups?.value;if(double!==undefined){return double.replaceAll(/\\(?<escaped>["\\])/gu,"$<escaped>")}return singleQuoted.exec(value3)?.groups?.value??value3.replace(inlineComment,"").trim()};var prefixed=(prefix,values)=>values.map(([key,value3])=>[`${prefix}${key}`,value3]);var renderDotenv=(prefix,values)=>`${prefixed(prefix,values).map(([key,value3])=>`${key}=${quote(value3)}`).join(`
249
257
  `)}
250
258
  `;var renderJson=(prefix,values)=>`${JSON.stringify(Object.fromEntries(prefixed(prefix,values)))}
251
259
  `;var envLines=(content)=>{const raw=content===undefined||content===""?[]:content.split(`
252
260
  `);const body=raw.at(-1)===""?raw.slice(0,-1):raw;return body.map((line)=>line.endsWith("\r")?{crlf:true,text:line.slice(0,-1)}:{crlf:false,text:line})};var envFileValue=(content,key)=>{for(const{text}of envLines(content)){const match5=assignment.exec(text);if(match5?.groups?.key===key){const value3=unquote(match5.groups.value??"");return value3===""?undefined:value3}}return};var mergeEnvFile=(content,prefix,values)=>{const managed=new Map(prefixed(prefix,values));const written=new Set;const lines=envLines(content);const fileCrlf=lines.some((line)=>line.crlf);const merged=[];for(const line of lines){const match5=assignment.exec(line.text);const key=match5?.groups?.key;const value3=key===undefined?undefined:managed.get(key);if(key===undefined||value3===undefined){merged.push(line)}else if(!written.has(key)){written.add(key);merged.push({crlf:line.crlf,text:`${match5?.groups?.lead??""}${key}=${quote(value3)}`})}}for(const[key,value3]of managed){if(!written.has(key)){merged.push({crlf:fileCrlf,text:`${key}=${quote(value3)}`})}}return merged.map((line)=>`${line.text}${line.crlf?`\r
253
261
  `:`
254
- `}`).join("")};class AppsEnrollCommandError extends TaggedError3()("AppsEnrollCommandError",{cause:optional2(Unknown2),message:String4}){}var EnrollmentRejected=TaggedStruct("PublicApplicationEnrollmentRejected",{message:String4,reason:Literals(["application_type_changed","disabled","package_owned"])});var fail11=(message)=>new AppsEnrollCommandError({message});var enrollmentFailure=(fqn)=>(error)=>{if(error.status!==409||!is2(EnrollmentRejected)(error.body)){return fail6(error)}const reasons={application_type_changed:`Public Application ${fqn} cannot change its type: ${error.body.message}`,disabled:`Public Application ${fqn} is disabled; re-run ci apps enroll with --enable to enable it`,package_owned:`Public Application ${fqn} is package-owned; change it through its Extension Package`};return fail6(fail11(reasons[error.body.reason]))};var parseEnrollment=(args2)=>gen2(function*parseEnrollmentEffect(){const options=yield*parseCommandOptionsEffect(args2,{repeatable:["post-logout-redirect-uri","redirect-uri","scopes"],switches:["enable","json","rotate-secret"],values:[...targetOptions,"audience","env-file","fqn","name","prefix","type"]});const fqn=optionValue2(options,"fqn");const redirectUris=optionValues(options,"redirect-uri");const scopes=optionValues(options,"scopes").flatMap((value3)=>value3.split(/[\s,]+/u).filter((scope3)=>scope3!==""));if(fqn===undefined){return yield*fail11("Missing required option --fqn; the CLI never derives an FQN")}if(redirectUris.length===0){return yield*fail11("Missing required option --redirect-uri")}if(scopes.length===0){return yield*fail11("Missing required option --scopes")}const type=optionValue2(options,"type")??"public";if(type!=="public"&&type!=="confidential"){return yield*fail11("--type must be public or confidential")}if(type==="public"&&options.switches.has("rotate-secret")){return yield*fail11("--rotate-secret applies to confidential applications only")}const applicationType=type==="confidential"?"confidential":"public";const prefix=optionValue2(options,"prefix")??"CI_";if(!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(prefix)){return yield*fail11("--prefix must be an environment variable name prefix such as CI_")}const origins=yield*try_2({catch:()=>fail11(`Invalid --redirect-uri in ${redirectUris.join(", ")}`),try:()=>redirectUris.map((uri)=>new URL(uri).origin)});return{body:{allowedOrigins:[...new Set(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},envFile:optionValue2(options,"env-file"),fqn,json:options.switches.has("json"),prefix,rotateSecret:options.switches.has("rotate-secret")}});var preflightFailure=(checks)=>fail11(`Enrollment preflight failed; no connection values were written: ${checks.filter((entry)=>!entry.passed).map((entry)=>entry.detail).join("; ")}`);var appsEnrollCommandEffect=(args2,dependencies)=>gen2(function*appsEnrollCommand(){const enrollment=yield*parseEnrollment(args2);const context3=yield*resolveOrganizationContext({args:args2,environment:dependencies.environment,fetch:dependencies.fetch});const request={client:context3.client,headers:{"x-organization-id":context3.organizationId}};const explainForbidden=explainOrganizationForbidden(context3,context3.organizationId);const tenant=yield*runTenantPreflight({context:context3,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)}const enrolled=yield*managementData("Enrollment",organizationPublicApplicationsEnroll,{...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"} Public Application ${application.fqn}: Application Id ${application.id}, Client Id ${application.clientId}
255
- `);const redirect=yield*runRedirectPreflight({context:context3,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=enrollment.envFile===undefined?undefined:dependencies.readEnvFile(enrollment.envFile);const confidentialSecret=gen2(function*confidentialSecretEffect(){if(enrolled.clientSecret!==undefined){return enrolled.clientSecret}if(enrollment.rotateSecret){const rotated=yield*managementData("Client secret rotation",organizationPublicApplicationsRotateCredential,{...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*fail11(`Public Application ${application.fqn} is confidential and ${secretKey} is not in ${envFileName}; re-run with --rotate-secret to issue a new client secret`)}if(envFileValue(existingContent,`${enrollment.prefix}CLIENT_ID`)!==application.clientId||envFileValue(existingContent,`${enrollment.prefix}ISSUER`)!==discovery.issuer){return yield*fail11(`Public Application ${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;const values=[["ISSUER",discovery.issuer],["AUDIENCE",application.audience],["APPLICATION_ID",application.id],["CLIENT_ID",application.clientId],...clientSecret===undefined?[]:[["CLIENT_SECRET",clientSecret]],["ORGANIZATION_ID",context3.organizationId],["JWKS_URL",discovery.jwksUri],["SCOPES",application.scopes.join(" ")]];if(enrollment.envFile!==undefined){const path2=enrollment.envFile;yield*try_2({catch:(cause)=>new AppsEnrollCommandError({cause,message:`Could not write ${path2}`}),try:()=>{dependencies.writeEnvFile(path2,mergeEnvFile(existingContent,enrollment.prefix,values))}});dependencies.writeDiagnostic(`Wrote ${values.length} keys to ${path2}
256
- `)}return yield*sync2(()=>{if(enrollment.json){dependencies.writeOutput(renderJson(enrollment.prefix,values))}else if(enrollment.envFile===undefined){dependencies.writeOutput(renderDotenv(enrollment.prefix,values))}})}).pipe(mapError2((cause)=>is2(AppsEnrollCommandError)(cause)?cause:new AppsEnrollCommandError({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=(value3)=>Object.prototype.toString.call(value3)==="[object Object]"&&!Array.isArray(value3)&&(Object.getPrototypeOf(value3)===Object.prototype||Object.getPrototypeOf(value3)===null);var isJsonArray=(value3)=>Array.isArray(value3);var canonicalize=(value3,ancestors,_valueType)=>{if(value3===null){return"null"}if(isJsonArray(value3)){if(ancestors.has(value3)){throw new TypeError("package declarations cannot contain cyclic values")}ancestors.add(value3);try{return`[${value3.map((item)=>canonicalize(item,ancestors)).join(",")}]`}finally{ancestors.delete(value3)}}if(isJsonObject(value3)){if(ancestors.has(value3)){throw new TypeError("package declarations cannot contain cyclic values")}ancestors.add(value3);try{const record2=value3;const keys=[];for(const key of Object.keys(record2)){insertSortedKey(keys,key)}return`{${keys.map((key)=>`${JSON.stringify(key)}:${canonicalize(record2[key],ancestors)}`).join(",")}}`}finally{ancestors.delete(value3)}}if(value3 instanceof Object){throw new TypeError("package declarations must contain JSON-compatible values")}switch(Object.prototype.toString.call(value3)){case"[object Boolean]":{return value3===true?"true":"false"}case"[object Number]":{const number3=Number(value3);if(!Number.isFinite(number3)){throw new TypeError("package declarations cannot contain non-finite numbers")}return JSON.stringify(number3)}case"[object String]":{return JSON.stringify(String(value3))}default:{throw new TypeError("package declarations must contain JSON-compatible values")}}};var canonicalJson=(value3,..._typeEvidence)=>canonicalize(value3,new WeakSet);var parseJsonObject=(source)=>{const value3=JSON.parse(source);if(!isJsonObject(value3)){throw new TypeError("expected a JSON object")}return value3};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 invalid4=(path2)=>{throw new TypeError(`Invalid package manifest at ${path2}`)};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=(value3,path2)=>{const text=identity2(value3,path2);return text===text.trim()?text:invalid4(path2)};var assertDenseArrays=(value3,path2,seen)=>{if(typeof value3!=="object"||value3===null||seen.has(value3)){return}seen.add(value3);if(Array.isArray(value3)){for(let index=0;index<value3.length;index+=1){if(!Object.hasOwn(value3,index)){invalid4(`${path2}/${index}`)}}}for(const[key,child]of Object.entries(value3)){assertDenseArrays(child,`${path2}/${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=(value3,path2)=>{const parsed=number3(value3,path2);return Number.isSafeInteger(parsed)&&parsed>0?parsed:invalid4(path2)};var optional3=(read2)=>(v,p)=>v===undefined?undefined:read2(v,p);var nullable=(read2)=>(v,p)=>v===null?null:read2(v,p);var literal=(...values)=>(v,p)=>{for(const value3 of values){if(v===value3){return value3}}return invalid4(p)};var array2=(read2)=>(v,p)=>{if(!Array.isArray(v)){return invalid4(p)}return v.map((item,index)=>read2(item,`${p}/${index}`))};var record2=(read2)=>(v,p)=>{if(typeof v!=="object"||v===null||Array.isArray(v)){return invalid4(p)}return Object.fromEntries(Object.entries(v).map(([key,value3])=>[key,read2(value3,`${p}/${key}`)]))};var object=(fields)=>(v,p)=>{if(typeof v!=="object"||v===null||Array.isArray(v)){return invalid4(p)}const entries=Object.entries(v);for(const key in fields){if(!Object.hasOwn(fields,key)){continue}fields[key](entries.find(([name])=>name===key)?.[1],`${p}/${key}`)}return v};var refine=(read2,violation)=>(v,p)=>{const value3=read2(v,p);return violation(value3)===undefined?value3: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 fieldUi=object({"ui:disabled":optBoolean,"ui:help":optString,"ui:options":optional3(selectOptions),"ui:order":optNumber,"ui:placeholder":optString,"ui:readonly":optBoolean,"ui:suggestedName":optString,"ui:validation":optional3(array2(validationRule)),"ui:widget":optString});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),(value3)=>Object.keys(value3).some((key)=>!Object.hasOwn(fields,key))?"unexpected Gateway field":undefined);var identifier2=refine(string3,(value3)=>/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/u.test(value3)?undefined:"invalid identifier");var version=refine(string3,(value3)=>value3.length>0&&value3.length<=128&&value3.trim()===value3?undefined:"invalid version");var bounded2=(maximum,minimum=1)=>refine(number3,(value3)=>Number.isSafeInteger(value3)&&value3>=minimum&&value3<=maximum?undefined:"invalid limit");var unique=(read2,key)=>refine(read2,(values)=>new Set(values.map(key)).size===values.length?undefined:"duplicate identifier");var projection=refine(schema2,(value3)=>(value3.fidelity==="exact"||value3.fidelity==="structural")&&Object.keys(value3).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,(value3)=>value3.length>0&&value3.length<=256?undefined:"invalid scope")),(scope3)=>scope3)});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};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});var empty4=refine(array2(identity2),(values)=>values.length===0?undefined:"operation-only Gateway required");var emptyReader=(value3,path2)=>{empty4(value3,path2);return[]};var disabled=(value3,path2)=>boolean2(value3,path2)===false?false:invalid4(path2);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});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=(value3,path2)=>{assertDenseArrays(value3,path2,new WeakSet);const admitted=contractReader(value3,path2);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(path2)}return normalized};var deepFreeze=(value3)=>{if(value3!==null&&typeof value3==="object"&&!Object.isFrozen(value3)){Object.freeze(value3);for(const child of Object.values(value3)){deepFreeze(child)}}return value3};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=(value3)=>value3===undefined||value3===null||Number.isSafeInteger(value3)&&value3>=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((value3,index)=>values.indexOf(value3)!==index);var workflowEditorViolation=(editor)=>{const sections=editor.form?.sections??[];const duplicateSection=firstDuplicate(sections.flatMap((section)=>section.id===undefined?[]:[section.id]));if(duplicateSection!==undefined){return`workflow editor section id '${duplicateSection}' is not unique`}const fields=sections.flatMap((section)=>section.fields??[]);const keys=fields.map((field)=>workflowBindingKey(field.binding));const duplicateField=fields.find((field,index)=>keys.indexOf(workflowBindingKey(field.binding))!==index);if(duplicateField!==undefined){return`workflow editor binding ${renderWorkflowBinding(duplicateField.binding)} is not unique`}for(const field of fields){const references=[...(field.visibleWhen??[]).map((rule)=>rule.binding),...field.optionSource?.kind==="remote"?field.optionSource.dependsOn:[]];const dangling=references.find((reference)=>!keys.includes(workflowBindingKey(reference)));if(dangling!==undefined){return`workflow editor field ${renderWorkflowBinding(field.binding)} references unknown binding ${renderWorkflowBinding(dangling)}`}}return};var metadata=object({available:boolean2,label:string3});var connection=object({...base,compatibility:optional3(object({auth:optString,dialect:optString,extensions:optional3(jsonObject),provider:optString})),creationMode:optional3(literal("self_service","registration_only")),credential:form,defaultConnectionName:string3,discoveryMetadata:optional3(metadata),kind:literal("connection"),providerFamily:string3,secretFields:optStrings,testMetadata:optional3(metadata)});var pathParts=array2(union2(string3,number3));var bindingModes=array2(literal("external","managed"));var syncModes=array2(literal("delta","full"));var bindingScopes=array2(literal("organization","tenant"));var mutationPolicy=literal("always","connector_backed","never");var extraProps=literal("ignore","import","inline");var outboundStrategy=literal("local_first","remote_first");var updateMode=literal("full","partial");var localized=object({fallbackLocale:string3,values:record2(string3)});var catalogTags=optional3(record2(strings));var connectionRefs=optional3(array2(object({catalogCollection:optString,connectionTemplateFqn:string3,label:string3,required:optBoolean,slot:string3,visibleWhen:optional3(visibility)})));var fieldMap=(v,p)=>{const common={direction:literal("both","inbound","outbound"),local:string3,skipIfNull:boolean2};const{op}=object({op:string3})(v,p);switch(op){case"path":{return object({...common,op:literal(op),remote:string3})(v,p)}case"cast":{return object({...common,falseValues:optStrings,op:literal(op),remote:string3,trueValues:optStrings})(v,p)}case"default":{return object({...common,op:literal(op),remote:optString,value:json})(v,p)}case"concat":{return object({...common,op:literal(op),remote:strings,separator:optString})(v,p)}case"split":{return object({...common,discardEmpty:optBoolean,op:literal(op),remote:string3,separators:optStrings,trimItems:optBoolean,uniqueItems:optBoolean})(v,p)}case"coordinates":{return object({...common,latitudeKey:optString,longitudeKey:optString,op:literal(op),remote:(value3,location)=>{const parts2=strings(value3,location);if(parts2.length!==2){return invalid4(location)}return[string3(parts2[0],location),string3(parts2[1],location)]}})(v,p)}case"transform":{return object({...common,op:literal(op),remote:string3,transformerId:string3})(v,p)}default:{return invalid4(`${p}/op`)}}};var predefinedExtras=optional3(array2(object({displayName:nullable(string3),enabled:boolean2,id:string3,includeInEntityEmbedding:boolean2,kind:literal("linked_text","file_source"),slotKey:string3,source:jsonObject})));var predefinedSchedules=optional3(array2(object({cronExpression:string3,enabled:optBoolean,importMode:optional3(literal("delta","full")),label:optString,rationale:optString,timezone:optString})));var schemaCapability={extraPropsMode:optional3(extraProps),fieldMap:optional3(array2(fieldMap)),fqn:string3,outboundStrategy:optional3(outboundStrategy),predefinedBindingExtras:predefinedExtras,predefinedBindingKey:optString,predefinedBindingMode:optional3(literal("external","managed")),predefinedBindingRemoteCollectionId:optString,predefinedBindingRemoteCollectionName:optString,predefinedSchedules,supportedSyncModes:optional3(syncModes),supportsInbound:optBoolean,supportsOutbound:optBoolean,syncIntervalSeconds:optional3(nullable(number3)),updateMode:optional3(updateMode)};var entityCapability=object({...schemaCapability,predefinedBindingParentKey:optString,supportedBindingModes:optional3(bindingModes)});var relationCapability=object({...schemaCapability,predefinedBindingParentEntityKey:optString,predefinedBindingRelationImportMode:optional3(literal("child_binding","relation_only")),predefinedBindingSourceEntityKey:optString,predefinedBindingTargetEntityKey:optString});var discoveryDefaults=object({extraPropsMode:extraProps,outboundStrategy,supportedBindingModes:bindingModes,supportedSyncModes:syncModes,supportsInbound:boolean2,supportsOutbound:boolean2,syncIntervalSeconds:nullable(number3),updateMode});var datasetCapabilities=object({aggregates:array2(literal("count","count_distinct","sum","min","max","avg")),definitionRefresh:boolean2,grouping:boolean2,intents:array2(literal("records","aggregate","time_series")),limits:object({maxBytes:number3,maxPageRows:number3,maxRows:number3,timeoutMs:number3}),ordering:boolean2,pagination:boolean2,predicates:array2(literal("eq","ne","lt","lte","gt","gte","in","not_in","is_null","is_not_null","contains","starts_with"))});var fieldSemantics=object({defaultSearch:optBoolean,embedded:optBoolean,faceted:optBoolean,indexContent:optBoolean,indexOverview:optBoolean,indexed:optBoolean,managedProjectionSource:optional3(literal("organization_team","organization_user")),queryGuidance:optString,unique:optBoolean});var managedProjection=object({connectorPolicy:literal("allow","deny_schema"),genericMutationPolicy:literal("deny_managed_fields","deny_schema"),kind:literal("directory_person","directory_person_in_team","directory_team","directory_team_parent"),source:literal("organization_team","organization_team_hierarchy","organization_team_membership","organization_user")});var fieldLocalization=object({description:optional3(localized),help:optional3(localized),label:optional3(localized),placeholder:optional3(localized)});var fieldPresentation=object({copyable:optBoolean,editor:optString,editorOptions:optional3(object({accepts:optStrings,allowCustomValues:optBoolean,autocomplete:optString,clearable:optBoolean,falseLabel:optString,multiple:optBoolean,options:optional3(array2(object({label:string3,value:string3}))),rows:optNumber,searchable:optBoolean,showButtons:optBoolean,spellcheck:optBoolean,step:optNumber,trueLabel:optString})),emptyLabel:optString,falseLabel:optString,hidden:optBoolean,layout:optional3(object({column:optNumber,labelPlacement:optional3(literal("left","top")),order:optNumber,row:optNumber,width:optional3(union2(number3,literal("full")))})),maxLines:optNumber,readOnly:optBoolean,renderer:optString,trueLabel:optString});var lifecycle=object({deployMode:literal("init_only","upsert"),readonly:boolean2});var autocompleteConfiguration=object({autocompleteFields:array2(object({field:string3,scope:literal("data","entity")})),defaultAutocompleteFields:array2(object({field:string3,scope:literal("data","entity")}))});var knowledgeSchema={catalogTags,domainFqn:string3,fieldLocalization:optional3(record2(fieldLocalization)),fieldPresentation:optional3(record2(fieldPresentation)),fieldSemantics:optional3(record2(fieldSemantics)),localMutationPolicy:optional3(mutationPolicy),managedProjection:optional3(managedProjection),schema:schema2};var policyRef=(value3,path2)=>{const{kind}=object({kind:string3})(value3,path2);return kind==="literal"?object({kind:literal("literal"),value:json})(value3,path2):object({kind:literal("subject","resource"),path:strings})(value3,path2)};var uuid=(value3,path2)=>{const parsed=identity2(value3,path2);return/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu.test(parsed)?parsed:invalid4(path2)};var policyPredicate=(value3,path2)=>{const{op}=object({op:string3})(value3,path2);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})(value3,path2)}case"in":{return object({op:literal("in"),set:policyRef,value:policyRef})(value3,path2)}case"exists":case"is_null":{return object({op:literal("exists","is_null"),ref:policyRef})(value3,path2)}case"contains":case"starts_with":{return object({op:literal("contains","starts_with"),ref:policyRef,value:policyRef})(value3,path2)}case"const":{return object({op:literal("const"),value:boolean2})(value3,path2)}case"not":{return object({arg:policyPredicate,op:literal("not")})(value3,path2)}case"and":case"or":{return object({args:array2(policyPredicate),op:literal("and","or")})(value3,path2)}case"relation_exists":{return object({direction:literal("out","in"),op:literal("relation_exists"),relationSchemaId:uuid})(value3,path2)}case"relation_field":{return object({direction:literal("out","in"),inner:policyPredicate,op:literal("relation_field"),relationSchemaId:uuid})(value3,path2)}default:{return invalid4(`${path2}/op`)}}};var policyBody=object({rule:optional3(policyPredicate),subjectMatch:policyPredicate});var policyFields={effect:literal("allow","deny"),policyBody,policyType:literal("filter","gate"),targetFqn:identity2,targetKind:literal("entity_domain","entity_schema","relation_domain","relation_schema")};var connection2=refine(object({setupKey:identity2}),(value3)=>Object.keys(value3).some((key)=>key!=="setupKey")?"install-only input":undefined);var bindingFields={executionRole:optional3(literal("root","child")),extraPropsMode:optional3(literal("ignore","import","inline")),extras:refine(predefinedExtras,(extras)=>extras?.some((extra)=>!/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu.test(extra.id))?"invalid extra UUID":undefined),fieldMap:optional3(array2(fieldMap)),key:identity2,outboundStrategy:optional3(literal("local_first","remote_first")),parentKey:optional3(nullable(identity2)),remoteCollectionId:optional3(nullable(string3)),remoteCollectionName:optional3(nullable(string3)),supportedSyncModes:optional3(array2(literal("delta","full"))),supportsInbound:optBoolean,supportsOutbound:optBoolean,syncIntervalSeconds:optional3(nullable(positiveSafeInteger)),updateMode:optional3(literal("full","partial"))};var entityBinding=object({...bindingFields,bindingMode:literal("managed","external"),missingConnectorFieldsBehavior:optional3(literal("prune","retain")),schemaFqn:identity2,supportedBindingModes:optional3(array2(literal("managed","external"))),suppressEntityEvents:optBoolean});var relationBinding=object({...bindingFields,bindingMode:optional3(literal("managed")),relationImportMode:optional3(literal("child_binding","relation_only")),relationSchemaFqn:identity2,sourceEntityKey:optional3(nullable(identity2)),targetEntityKey:optional3(nullable(identity2))});var schedule2=object({cronExpression:identity2,enabled:optBoolean,importMode:optional3(literal("delta","full")),key:identity2,timezone:optString});var positive=refine(number3,(n)=>n>0?undefined:"positive");var budget=optional3(nullable(positiveSafeInteger));var pipeline=object({definition:object({budgets:optional3(object({maxPagesPerRun:budget,maxRemoteItemsPerRun:budget,maxRootWorkUnitsPerRun:budget,maxSecondsPerRun:optional3(nullable(positive))})),steps:refine(array2(object({tasks:array2(object({bindingKey:identity2,kind:literal("entity","relation"),modeOverride:optional3(nullable(literal("delta","full")))}))})),(steps)=>steps.length>0?undefined:"empty")}),enabled:optBoolean,key:identity2,name:optString,schedules:optional3(array2(schedule2))});var uniqueKeys=(values,path2)=>{const seen=new Set;for(const[index,value3]of values.entries()){if(seen.has(value3.key)){invalid4(`${path2}/${index}/key`)}seen.add(value3.key)}};var knowledge=object({...base,connections:optional3(record2(connection2)),dataPolicies:optional3(array2(object({...policyFields,fqn:identity2,priority:optNumber}))),enabled:optBoolean,entityBindings:optional3(array2(entityBinding)),kind:literal("knowledgeConnectorInstance"),lifecycle,pipelines:optional3(array2(pipeline)),relationBindings:optional3(array2(relationBinding)),remoteFilters:optional3(record2(object({mode:literal("all","only_selected","all_except_selected"),selected_ids:strings}))),settings:optional3(record2(object({type:literal("inline","linked"),value:json}))),templateFqn:identity2});var assertEntityParents=(entities,path2)=>{const parents=new Map(entities.map((b)=>[b.key,b.parentKey]));for(const binding of entities){const seen=new Set([binding.key]);let parent=binding.parentKey;while(parent){if(seen.has(parent)){invalid4(`${path2}/entityBindings/parentKey`)}seen.add(parent);parent=parents.get(parent)}}};var assertPolicyLifecycle=(policies,path2)=>{for(const[index,policy]of policies.entries()){if(Object.keys(policy).some((key)=>key==="lifecycle"||key==="deployMode"||key==="readonly")){invalid4(`${path2}/dataPolicies/${index}/lifecycle`)}}};var knowledgeConnectorInstance=(value3,path2)=>{const parsed=knowledge(value3,path2);assertPolicyLifecycle(parsed.dataPolicies??[],path2);const entities=parsed.entityBindings??[];const relations=parsed.relationBindings??[];const pipelines=parsed.pipelines??[];uniqueKeys(entities,`${path2}/entityBindings`);uniqueKeys(relations,`${path2}/relationBindings`);uniqueKeys(pipelines,`${path2}/pipelines`);const entityKeys=new Set(entities.map((b)=>b.key));const relationKeys=new Set(relations.map((b)=>b.key));assertEntityParents(entities,path2);for(const[index,binding]of[...entities,...relations].entries()){if(binding.parentKey&&(!entityKeys.has(binding.parentKey)||binding.parentKey===binding.key)){invalid4(`${path2}/bindings/${index}/parentKey`)}}for(const[index,relation]of relations.entries()){for(const key of[relation.sourceEntityKey,relation.targetEntityKey]){if(key&&!entityKeys.has(key)){invalid4(`${path2}/relationBindings/${index}`)}}}for(const[index,item]of pipelines.entries()){uniqueKeys(item.schedules??[],`${path2}/pipelines/${index}/schedules`);const tasks=new Set;for(const step of item.definition.steps){for(const task of step.tasks){const keys=task.kind==="entity"?entityKeys:relationKeys;const key=`${task.kind}:${task.bindingKey}`;if(!keys.has(task.bindingKey)||tasks.has(key)){invalid4(`${path2}/pipelines/${index}/definition/steps`)}tasks.add(key)}}}return parsed};var scalar=literal("boolean","string","int64","float64","decimal","date","timestamp","duration","json");var datasetDefinition=object({fields:array2(object({id:identity2,name:string3,nullable:boolean2,semantic:optString,type:scalar})),measures:array2(object({id:identity2,name:string3,resultType:scalar})),relationships:array2(object({cardinality:literal("one_to_one","one_to_many","many_to_one","many_to_many"),fromFieldId:identity2,id:identity2,toFieldId:identity2})),version:literal(1)});var location=(value3,path2)=>{const{segments}=object({segments:array2(object({kind:literal("container","dataset"),label:string3,opaqueId:identity2}))})(value3,path2);const[first]=segments;if(!first||first.kind!=="container"){return invalid4(`${path2}/segments/0`)}return{segments:[{...first,kind:"container"},...segments.slice(1)]}};var datasetValue=(value3,path2)=>{const{kind}=object({kind:string3})(value3,path2);switch(kind){case"null":{return object({kind:literal("null")})(value3,path2)}case"boolean":{return object({kind:literal("boolean"),value:boolean2})(value3,path2)}case"float64":{return object({kind:literal("float64"),value:number3})(value3,path2)}case"json":{return object({kind:literal("json"),value:json})(value3,path2)}default:{return object({kind:literal("string","int64","decimal","date","timestamp","duration"),value:string3})(value3,path2)}}};var datasetFilter=(value3,path2)=>{const{kind}=object({kind:string3})(value3,path2);if(kind==="not"){return object({filter:datasetFilter,kind:literal("not")})(value3,path2)}if(kind==="and"||kind==="or"){return object({filters:array2(datasetFilter),kind:literal("and","or")})(value3,path2)}return object({fieldId:identity2,kind:literal("predicate"),operator:literal("eq","ne","lt","lte","gt","gte","in","not_in","is_null","is_not_null","contains","starts_with"),values:array2(datasetValue)})(value3,path2)};var datasetFields={...base,connection:optional3(connection2),dataPolicy:optional3(object({allowedFields:strings,allowedOperations:array2(literal("describe","records","aggregate","time_series")),maxBytes:budget,maxRows:budget,maxTimeoutMs:budget,principals:array2(object({id:identity2,kind:literal("user","service")})),rowFilter:optional3(nullable(datasetFilter)),sensitiveFields:optional3(strings)})),kind:literal("datasetConnectorInstance"),lifecycle,providerFqn:identity2,schedules:optional3(array2(object({action:literal("health","refresh_definition"),cronExpression:identity2,enabled:optBoolean,key:identity2,timezone:optString}))),settings:optional3(jsonObject)};var datasetConnectorInstance=(value3,path2)=>{const parsed=union2(object({...datasetFields,bindingMode:literal("managed"),definition:datasetDefinition,sourceLocation:optional3(location),templateConfig:optional3(object({variant:identity2,version:literal(1)})),templateFqn:optional3(identity2)}),object({...datasetFields,bindingMode:literal("external"),definition:optional3(datasetDefinition),gatewayBindingKey:optString,sourceLocation:location,sourceMapping:optional3(object({effectiveAtFieldId:optString,entityIdFieldId:identity2,historySemantics:optional3(literal("append_history")),kind:literal("entity_snapshot","status_update"),statusFieldId:optString,version:literal(1)}))}))(value3,path2);uniqueKeys(parsed.schedules??[],`${path2}/schedules`);return parsed};var datasetParserFormat=(value3,path2)=>{if(typeof value3!=="string"||value3.length>128||value3==="external"||!/^[a-z][a-z0-9._-]*$/u.test(value3)){throw new TypeError(`Invalid dataset parser format at ${path2}`)}return value3};var datasetParserVersion=(value3,path2)=>{if(typeof value3!=="string"||value3.trim()===""||value3.length>96){throw new TypeError(`Invalid dataset parser version at ${path2}`)}return value3};var readExternalAppGateway=closedGatewayObject({...base,expectedContract:readOperationGatewayContract,kind:literal("externalAppGateway")});var identifier22=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/u;var fields=new Set(["category","defaultVisibility","description","displayName","fqn","gatewayRef","icon","kind","operationReferences","tags","version"]);var referencesGateway=(reference,gatewayId)=>{const separator=reference.indexOf("@");if(separator===-1){return false}const[gateway,domain,operation,...rest]=reference.slice(0,separator).split("/");const version2=reference.slice(separator+1);return identifier22.test(gatewayId)&&gateway===gatewayId&&domain!==undefined&&identifier22.test(domain)&&operation!==undefined&&identifier22.test(operation)&&rest.length===0&&version2.length>0&&version2.length<=128&&version2.trim()===version2};var remoteToolCollectionViolation=(declaration)=>{const unknownField=Object.keys(declaration).find((key)=>!fields.has(key));if(unknownField!==undefined){return`unsupported remote metadata field '${unknownField}'`}const{gatewayRef,operationReferences}=declaration;if(gatewayRef===undefined||gatewayRef.trim()===""||gatewayRef.trim()!==gatewayRef){return"gatewayRef must be a nonempty FQN"}if(operationReferences.length===0||new Set(operationReferences).size!==operationReferences.length||operationReferences.some((reference)=>!referencesGateway(reference,reference.split("/")[0]??""))){return"operationReferences must name unique versioned Gateway operations"}return};var readPin=object({fqn:hostedIdentity,releaseDigest:(value3,path2)=>{const digest=hostedIdentity(value3,path2);return/^[\da-f]{64}$/u.test(digest)?digest:invalid4(path2)},releaseId:hostedIdentity});var parsePackageDependencyPins=(value3)=>{const pins=array2(readPin)(value3,"/dependencies");const identities=new Set;for(const pin of pins){if(Object.keys(pin).some((key)=>!["fqn","releaseId","releaseDigest"].includes(key))){throw new TypeError(`package dependency '${pin.fqn}' has unexpected fields`)}if(identities.has(pin.fqn)){throw new TypeError(`duplicate package dependency '${pin.fqn}'`)}identities.add(pin.fqn)}return[...pins].sort((left,right)=>compareUtf16CodeUnits(left.fqn,right.fqn))};var PackageManifestVersion="v4";var legacyFixedDestinationTargets=new Set(["fixed-email","channel-destination","telegram-chat","whatsapp-destination"]);var uuid2=/^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/iu;var placeholder=/\{(?<name>[^{}]*)\}/gu;var placeholders={remoteId:(remoteId)=>encodeURIComponent(remoteId),remoteIdUuidHex:(remoteId)=>uuid2.test(remoteId)?remoteId.replaceAll("-","").toLowerCase():null};var isPlaceholderName=(name)=>Object.hasOwn(placeholders,name);var resolver=(name)=>isPlaceholderName(name)?placeholders[name]:undefined;var knowledgeRemoteReferenceUrlTemplate=(value3,path2)=>{if(typeof value3!=="string"||!value3.startsWith("https://")||/[{}]/u.test(value3.replaceAll(placeholder,(match5,name)=>resolver(name)===undefined?match5:""))){throw new TypeError(`Invalid remote reference URL template at ${path2}`)}return value3};var HOSTS=["backend","dashboard","studio"];var FRONTEND_CATALOG_CONTRACT="frontend-catalog/v1";var FRONTEND_CATALOG_EXPORT_NAME="loadFrontendCatalog";var BACKEND_EXECUTION_LANES=["interactive","job"];var packageManifestJson=(definition)=>parseJsonObject(canonicalJson(definition.manifest));var canonicalPackageManifest=(definition)=>canonicalJson(packageManifestJson(definition));var toolBindingDeclaration=(entry)=>typeof entry==="string"?{tool:entry}:entry;var duplicateToolBinding=(tools)=>{const seen=new Set;for(const entry of tools){const binding=toolBindingDeclaration(entry);const key=JSON.stringify([binding.tool,binding.name??null]);if(seen.has(key)){return binding}seen.add(key)}return};var agentAudienceViolation=(audience)=>{const applications=audience.applications??[];if(audience.anonymous===true&&applications.length===0){return"anonymous visitors need an application in audience.applications"}const repeated=applications.find((fqn,index)=>applications.indexOf(fqn)!==index);return repeated===undefined?undefined:`audience application '${repeated}' is listed more than once`};var agentModelTiers=["complex","balanced","fast","super_fast"];var notificationDefinition=object({capabilities:object({extensionReadyProviders:strings,recipientTargets:strings,supportsActionLink:boolean2,supportsAttachments:boolean2,supportsFixedDestinations:optBoolean,supportsHtml:boolean2,supportsMarkdown:boolean2,supportsMentions:boolean2,supportsReadReceipts:boolean2,supportsRouteDestinations:boolean2,supportsThreads:boolean2}),credentialProfileKey:optString,family:literal("email","im","internal"),key:string3,provider:string3,setup:object({docsUrl:nullable(string3),healthCheck:object({available:boolean2,label:optString}),instructions:string3,liveTest:object({available:boolean2,label:optString}),secretFields:strings,setupForm:nullable(form)})});var studioPage=object({fullWidth:optBoolean,icon:optString,kind:literal("predefined"),label:string3,orderIndex:number3,predefinedPageRef:string3,routeSegment:string3,slug:string3});var studioSection=object({description:optString,icon:optString,label:string3,orderIndex:number3,pages:array2(studioPage),slug:string3});var studioApp=object({color:optString,description:optString,icon:optString,isDefaultTemplate:optBoolean,name:string3,sections:array2(studioSection),slug:string3});var datasetScalarType=literal("boolean","string","int64","float64","decimal","date","timestamp","duration","json");var datasetDefinition2=object({fields:array2(object({id:string3,name:string3,nullable:boolean2,semantic:optional3(string3),type:datasetScalarType})),measures:array2(object({id:string3,name:string3,resultType:datasetScalarType})),relationships:array2(object({cardinality:literal("one_to_one","one_to_many","many_to_one","many_to_many"),fromFieldId:string3,id:string3,toFieldId:string3})),version:literal(1)});var datasetBlueprint=object({...base,blueprintVersion:positiveSafeInteger,configuration:optional3(jsonObject),definition:datasetDefinition2,kind:literal("datasetBlueprint"),templateFqn:identity2});var semanticRole=literal("dimension","effective_time","entity_reference","event_time","identity","measure","status");var hint=object({role:semanticRole});var datasetTableTemplate=object({...base,admittedIngestionModes:array2(literal("append","replace","upsert")),compatibleProviderFqns:strings,configuration:schema2,identity:object({keyRoles:array2(semanticRole),uniqueness:literal("append_only","key","none")}),indexHints:array2(hint),kind:literal("datasetTableTemplate"),partitionHints:array2(hint),physicalCode:literal("evt","fact","gen","snap","stat","ts"),requirements:schema2,semanticRoles:array2(semanticRole)});var WorkflowEditorWidgets=["checkbox","code","condition_builder","credential_selector","key_value","list","mapping_builder","multi_select","number","resource_selector","schedule_builder","schema_builder","select","text","textarea"];var WorkflowTemplateKinds=["action_node","input_node","output_node","trigger_node"];var WorkflowTriggerLifecycleAdapterIds=Object.freeze({externalApplication:"builtin.core.workflows.lifecycle.external-application",mcpOperation:"builtin.core.workflows.lifecycle.mcp-operation"});var dynamicPort=object({configPath:string3,defaultIdPath:optString,idPath:string3,requiredPath:optString,schemaPath:optString});var fieldBinding=object({path:pathParts,target:literal("input_binding","parameter")});var nonNegativeInteger=(value3,path2)=>{const parsed=number3(value3,path2);return Number.isSafeInteger(parsed)&&parsed>=0?parsed:invalid4(path2)};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=(value3)=>object({inputContractPath:pathParts,modePath:optional3(pathParts),targetWorkflowIdPath:pathParts})(value3,"/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,resumable:optBoolean,sideEffect:literal("external","none","read","write"),testable:optBoolean})),implementationId:string3,inputSchema:optional3(schema2),instancePolicy:optional3(object({maxInstances:optNumber,minInstances:optNumber,onWorkflowCreate:optBoolean})),nodeCollectionFqn:optString,nodeCollectionVersion:optString,outputChannels:optional3(array2(object({adapterId:string3,cardinality:literal("many","one"),deliveryMode:literal("asynchronous","synchronous"),key:string3,required:boolean2,valueSchema:schema2}))),outputSchema:optional3(schema2),ports:optional3(array2(nodePort)),reusableDependency:optional3(parseWorkflowReusableDependency),triggerActivation:optional3(triggerActivation)});var fieldContract=object({availableForInput:optBoolean,availableForOutput:optBoolean,clearOnDependencyChange:optBoolean,optionDependencies:optional3(array2(object({path:pathParts,target:literal("parameter","part","value")}))),valueSchema:optional3(schema2)});var graphSchema=object({bindings:optional3(array2(object({extensions:jsonObject}))),fieldProjections:array2(object({source:pathParts,target:pathParts})),schema:schema2});var graphBoundary=object({templateFqn:string3,templateVersion:string3});var graph=object({edges:array2(object({extensions:optional3(jsonObject),id:string3,source:string3,target:string3})),inputBoundary:graphBoundary,inputContract:graphSchema,metadata:object({description:nullable(string3),tags:strings,templateSource:nullable(string3)}),nodes:array2(object({extensions:optional3(jsonObject),id:string3,templateFqn:string3,templateVersion:string3})),outputBoundary:graphBoundary,outputContract:graphSchema,triggers:array2(object({config:object({extensions:optional3(jsonObject)}),id:string3,inputBindings:record2(string3),invocation:object({mode:literal("attach","detach"),timeoutMs:nullable(number3)}),metadata:object({fieldDisplayValues:record2(string3)}),settings:object({enabled:boolean2}),templateFqn:string3,templateVersion:string3})),version:literal(1)});var uiLayout=object({edges:record2(object({extensions:optional3(jsonObject)})),nodes:record2(object({position:optional3(object({x:number3,y:number3}))})),version:literal(1),viewport:nullable(object({x:number3,y:number3,zoom:number3}))});var bindingSpan=object({end:number3,start:number3});var bindingSource=object({kind:literal("input","loop_index","loop_item","merge_output","node_output","port_arrival","run","scope","trigger"),mergeId:optional3(nullable(string3)),nodeId:optional3(nullable(string3)),portId:optional3(nullable(string3)),selection:optional3(nullable(object({ancestry:literal("nearest_dominating_ancestor"),iteration:literal("aggregate","previous_iteration","same_iteration")})))});var bindingExpression=(value3,path2)=>{const{kind}=object({kind:string3})(value3,path2);switch(kind){case"array":{return object({items:array2(bindingExpression),kind:literal("array")})(value3,path2)}case"call":{return object({args:array2(bindingExpression),kind:literal("call"),name:string3})(value3,path2)}case"interpolation":{return object({kind:literal("interpolation"),parts:array2(bindingExpression),span:optional3(nullable(bindingSpan))})(value3,path2)}case"literal":{return object({kind:literal("literal"),value:json})(value3,path2)}case"object":{return object({fields:record2(bindingExpression),kind:literal("object")})(value3,path2)}case"operator":{return object({args:array2(bindingExpression),kind:literal("operator"),op:string3})(value3,path2)}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))})(value3,path2)}default:{return invalid4(`${path2}/kind`)}}};var authoredValue=union2(object({mode:literal("fixed"),value:json}),object({compiled:optional3(nullable(bindingExpression)),languageVersion:literal(1),mode:literal("expression"),source:string3}));var nodeExecutionSettings=object({dryRun:optional3(object({mode:literal("allow","block_side_effects")})),idempotencyKey:optional3(nullable(bindingExpression)),onError:optional3(object({mode:literal("continue","fail_run")})),retry:optional3(object({backoffMs:optional3(nullable(number3)),maxAttempts:optional3(nullable(number3)),mode:literal("disabled","exponential","fixed")})),timeoutMs:optional3(nullable(number3))});var authoringTemplateRef=object({templateFqn:string3,templateVersion:string3});var authoringFieldProjection=object({fieldConfig:optional3(jsonObject),fieldFqn:string3,fieldVersion:string3,path:strings});var authoringInputContract=object({fieldProjections:optional3(array2(authoringFieldProjection)),jsonSchema:jsonObject});var authoringOutputContract=object({bindings:array2(object({key:string3,kind:literal("artifact","value"),value:bindingExpression})),fieldProjections:optional3(array2(authoringFieldProjection)),jsonSchema:jsonObject});var inputEndpoint=object({kind:literal("input_node"),portId:string3});var actionEndpoint=object({kind:literal("action_node"),nodeId:string3,portId:string3});var triggerEndpoint=object({kind:literal("trigger_node"),portId:string3,triggerId:string3});var outputEndpoint=object({kind:literal("output_node"),portId:string3});var authoringDefinition=object({edges:array2(object({id:string3,source:union2(union2(actionEndpoint,inputEndpoint),triggerEndpoint),target:union2(union2(actionEndpoint,inputEndpoint),outputEndpoint)})),inputBoundary:authoringTemplateRef,inputContract:authoringInputContract,metadata:jsonObject,nodes:array2(object({config:record2(authoredValue),extensions:optional3(jsonObject),id:string3,inputs:record2(authoredValue),metadata:jsonObject,settings:nodeExecutionSettings,templateFqn:string3,templateVersion:string3,uid:optString})),outputBoundary:authoringTemplateRef,outputContract:authoringOutputContract,triggers:array2(object({config:jsonObject,id:string3,inputBindings:record2(object({overridePolicy:literal("caller_may_override","locked"),value:authoredValue})),invocation:object({mode:literal("attach","await_result","detach"),timeoutMs:optional3(nullable(number3))}),metadata:jsonObject,settings:jsonObject,templateFqn:string3,templateVersion:string3})),version:literal(1)});var knowledgeSelection=optional3(object({exclude:optional3(array2(identity2)),include:optional3(array2(identity2))}));var toolBindings2=refine(array2(union2(identity2,object({approval:optional3(union2(literal("always","never"),object({rule:identity2}))),knowledge:optional3(object({domains:knowledgeSelection,entitySchemas:knowledgeSelection,relationSchemas:knowledgeSelection,unrestricted:optBoolean})),name:optional3(identity2),settings:optional3(jsonObject),tool:identity2}))),(tools)=>duplicateToolBinding(tools)===undefined?undefined:"duplicate tool binding");var agentAudience2=refine(object({anonymous:optBoolean,applications:optional3(array2(identity2)),members:optional3(literal("all","none","selected")),organizationTeams:optional3(literal("none","selected"))}),agentAudienceViolation);var withoutRetiredAgentFields=(agent)=>["invokingApplicationFqns","modelPreset"].find((field)=>(field in agent));var primitives={agent:refine(object({...base,activity:optional3(object({heartbeat:boolean2,schedule:boolean2})),audience:optional3(agentAudience2),behavioralBoundaries:strings,kind:literal("agent"),lifecycle,maxSteps:optional3(positiveSafeInteger),modelTier:optional3(literal(...agentModelTiers)),objectives:strings,operatingInstructions:string3,output:optional3(object({schema:schema2})),responsibility:string3,skills:array2(identity2),tools:toolBindings2}),withoutRetiredAgentFields),connection,datasetBlueprint,datasetConnectorInstance,datasetParser:object({...base,extensions:array2(identity2),format:datasetParserFormat,kind:literal("datasetParser"),mediaTypes:array2(identity2),parserVersion:datasetParserVersion}),datasetTableTemplate,documentsConnector:object({...base,connectionRefs,kind:literal("documentsConnector"),providerDisplayName:optional3(identity2),providerFamily:identity2}),domain:object({...base,kind:literal("domain"),lifecycle,localMutationPolicy:optional3(mutationPolicy),versioningEnabled:nullable(boolean2)}),domainTemplate:object({...base,catalogTags,domainFqn:string3,domainName:string3,entitySchemaFqns:strings,kind:literal("domainTemplate"),relationSchemaFqns:strings}),eventListener:object({...base,capabilities:array2(literal("internal","poll","webhook")),eventKind:string3,kind:literal("eventListener"),manualWebhookState:optional3(object({keyFamily:identity2,stateKey:identity2})),runtimeState:optional3(array2(object({keyFamily:string3,stateKey:string3}))),safeOccurrenceFields:optStrings,safeSelectorFields:optStrings,webhookHandshake:optional3(object({kind:literal("echo_query_parameter"),parameter:identity2}))}),externalAppGateway:readExternalAppGateway,externalApplication:object({...base,allowedOrigins:strings,applicationType:literal("confidential","public"),audience:string3,kind:literal("externalApplication"),lifecycle,postLogoutRedirectUris:strings,redirectUris:strings,scopes:strings,setupInstructions:optString}),externalDatasetProvider:object({...base,capabilities:datasetCapabilities,connectionTemplateFqns:strings,kind:literal("externalDatasetProvider"),sourceCapabilities:optional3(array2(object({capabilities:datasetCapabilities,datasetOpaqueIdPrefix:string3})))}),fieldTransformer:object({...base,kind:literal("fieldTransformer"),sourceFieldType:string3,targetFieldType:string3}),knowledgeConnector:object({...base,autoActivate:optBoolean,autoInstantiate:optBoolean,bindingScopes:optional3(bindingScopes),connectionRefs,contributions:optional3(array2(object({capabilityFqn:string3,connectionSlot:string3,connectionTemplateFqn:string3,controlFqn:optString,displayName:string3,fqn:identity2,metadata:optional3(jsonObject)}))),defaultOutboundStrategy:optional3(outboundStrategy),defaultUpdateMode:optional3(updateMode),discoveryDefaults:optional3(discoveryDefaults),entityIdentityMode:optional3(literal("adapter","item_metadata")),entitySchemaCapabilities:optional3(array2(entityCapability)),isSingleton:optBoolean,kind:literal("knowledgeConnector"),outboundCapability:optional3(literal("declared_and_enablable","none")),recommendedImportSchedules:predefinedSchedules,relationSchemaCapabilities:optional3(array2(relationCapability)),remoteReference:optional3(object({providerKey:identity2,urlTemplate:knowledgeRemoteReferenceUrlTemplate})),settings:optional3(form),supportedBindingModes:optional3(bindingModes)}),knowledgeConnectorInstance,knowledgeConnectorOauth:object({...base,connectorFqn:string3,kind:literal("knowledgeConnectorOauth")}),knowledgeEntityAdapter:object({...base,connectorFqn:string3,entitySchemaFqn:string3,kind:literal("knowledgeEntityAdapter"),normalizesFieldMapValues:optBoolean,normalizesImportedData:optBoolean}),knowledgeEntitySchema:object({...base,...knowledgeSchema,autocompleteConfiguration,defaultSyncDirection:optString,deletionMode:optString,displayDefaults:optional3(object({collections:optStrings,details:optStrings})),displayNameExpression:nullable(string3),embedEntities:optBoolean,embeddingConfig:nullable(jsonObject),extendsSchemaFqn:optString,kind:literal("knowledgeEntitySchema"),lifecycle,maxVersionsExpirationDays:optional3(nullable(number3)),persistFullFieldContributions:boolean2,relationFields:optional3(array2(object({cardinality:literal("many","one"),field:string3,id:string3,nullable:boolean2,reference:literal("external_id"),targetEntityId:string3,targetSchemaFqn:string3}))),syncable:optBoolean,usableAsDocumentScope:boolean2,versioned:optBoolean,versioningEnabled:nullable(boolean2)}),knowledgePolicy:object({...base,...policyFields,kind:literal("knowledgePolicy"),priority:optNumber}),knowledgeRelationAdapter:object({...base,connectorFqn:string3,kind:literal("knowledgeRelationAdapter"),relationSchemaFqn:string3}),knowledgeRelationSchema:object({...base,...knowledgeSchema,kind:literal("knowledgeRelationSchema"),lifecycle:optional3(lifecycle),sourceSchemaFqn:string3,targetSchemaFqn:string3}),managedDatasetProvider:object({...base,capabilities:datasetCapabilities,connectionTemplateFqns:strings,kind:literal("managedDatasetProvider")}),notificationChannel:object({...base,credential:optional3(form),definition:notificationDefinition,kind:literal("notificationChannel")}),organizationSso:object({...base,connectionTemplateFqn:string3,kind:literal("organizationSso"),providerId:string3,requiredCredentialFields:strings,secretCredentialFields:optStrings,setupGuide:optional3(array2(object({locale:string3,markdown:string3})))}),remoteToolCollection:refine(object({...base,category:optString,defaultVisibility:optional3(array2(object({effect:literal("allow","deny"),subject:literal("organization")}))),gatewayRef:identity2,kind:literal("remoteToolCollection"),operationReferences:strings}),remoteToolCollectionViolation),skill:object({...base,instructions:string3,kind:literal("skill"),lifecycle,tools:toolBindings2}),skillTemplate:object({...base,catalogTags,kind:literal("skillTemplate"),lifecycle:optional3(lifecycle),name:string3}),studioApp:object({...base,definition:studioApp,kind:literal("studioApp")}),studioComponent:object({...base,category:literal("layout","page","primitive","view","widget"),composition:optional3(object({extensions:optional3(jsonObject),slotSource:literal("props","static"),slots:array2(object({extensions:optional3(jsonObject),key:string3,label:optional3(localized)}))})),kind:literal("studioComponent"),propsSchema:schema2,sourceRef:string3}),tool:object({...base,allowMultipleSkillBindings:optBoolean,autoActivate:optBoolean,autoInstantiate:optBoolean,bindingScopes:optional3(bindingScopes),bindingSettings:optional3(form),capabilityType:optional3(literal("delegate","external","read","write")),category:optString,connectionRefs,effectKind:optional3(literal("mutation","read_only")),extraLoaders:optional3(array2(object({bindingName:string3,inheritBindingSettings:optBoolean,toolFqn:string3}))),healthCheck:optional3(object({capabilities:optStrings,description:string3})),input:schema2,isSingleton:optBoolean,kind:literal("tool"),output:schema2,settings:optional3(form),setupInstructions:optional3(object({links:strings,markdown:string3})),toolCollectionFqns:optStrings,toolGuidance:optional3(object({inputRequirementsSummary:optString,useWhen:optString})),usageScopes:optional3(array2(literal("automation","chat","skill")))}),toolCollection:object({...base,category:optString,defaultVisibility:optional3(array2(object({effect:literal("allow","deny"),subject:literal("organization")}))),kind:literal("toolCollection"),toolFqns:strings}),toolSettingsOptions:object({...base,catalogCollection:optString,catalogConnectionSlots:optStrings,connectionSlots:optStrings,dependencies:optStrings,fieldKey:string3,formTarget:optional3(literal("binding","settings")),includeUnavailableSelectedOptions:optBoolean,kind:literal("toolSettingsOptions"),toolFqn:string3}),workflow:object({...base,definition:authoringDefinition,kind:literal("workflow"),lifecycle,name:string3,slug:string3}),workflowField:object({...base,collectionFqn:string3,collectionVersion:string3,contract:fieldContract,kind:literal("workflowField"),presentation:optional3(object({placeholder:optString,widget:optString}))}),workflowFieldCollection:object({...base,contract:object({weight:number3}),kind:literal("workflowFieldCollection"),presentation:optional3(object({categoryPath:strings,label:localized}))}),workflowNode:object({...base,contract:nodeContract,kind:literal("workflowNode"),nodeKind:literal("action","input","output","trigger"),presentation:optional3(object({categoryPath:optStrings,tags:optStrings}))}),workflowNodeCollection:object({...base,contract:object({collection:optional3(object({parentFqn:string3,parentVersion:string3,weight:number3}))}),kind:literal("workflowNodeCollection"),presentation:optional3(object({categoryPath:strings}))}),workflowTemplate:object({...base,catalogTags,category:string3,definition:graph,kind:literal("workflowTemplate"),lifecycle,name:string3,requiredSkills:strings,requiredTools:strings,skillSlots:strings,slug:string3,uiLayout:nullable(uiLayout)})};var primitive=(v,p)=>{const{kind}=object({kind:string3})(v,p);for(const[name,read2]of Object.entries(primitives)){if(name===kind){return read2(v,p)}}return invalid4(`${p}/kind`)};var readHostedContribution=(value3,path2)=>{const shared=object({compatibility:optional3(record2(string3)),contract:optString,execution:optional3(literal("interactive","job")),exportName:hostedIdentity,fqn:hostedIdentity,host:literal("backend","dashboard","studio")})(value3,path2);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 ${path2}/execution: frontend contributions cannot declare an execution lane`)}if(shared.contract!==FRONTEND_CATALOG_CONTRACT){throw new TypeError(`Invalid package manifest at ${path2}/contract: frontend contribution contract must be '${FRONTEND_CATALOG_CONTRACT}'`)}if(shared.exportName!==FRONTEND_CATALOG_EXPORT_NAME){throw new TypeError(`Invalid package manifest at ${path2}/exportName: frontend contribution export must be '${FRONTEND_CATALOG_EXPORT_NAME}'`)}return{...shared.compatibility===undefined?undefined:{compatibility:shared.compatibility},contract:FRONTEND_CATALOG_CONTRACT,exportName:FRONTEND_CATALOG_EXPORT_NAME,fqn:shared.fqn,host:shared.host}};var readManifest=object({apiVersion:literal(PackageManifestVersion),author:optString,autoInstallable:optBoolean,bindingScopes:optional3(array2(literal("organization","tenant"))),category:optString,dependencies:optional3(parsePackageDependencyPins),description:optString,documentation:optString,fqn:identity2,homepage:optString,hostedContributions:optional3(array2(readHostedContribution)),icon:optString,installationWizard:optional3(object({size:optional3(literal("lg","md","xl")),steps:array2(object({description:optString,kind:literal("connector_instance","tool_instance"),optional:optBoolean,ref:string3,title:optString}))})),name:string3,primitives:array2(primitive),requiredEnvironmentVariables:optStrings,tags:optStrings,tenantMandatory:optBoolean,tenantStandard:optBoolean,version:string3});var parsePackageManifest=(value3)=>{assertDenseArrays(value3,"",new WeakSet);const manifest=readManifest(parseJsonObject(canonicalJson(value3)),"");return manifest.dependencies===undefined?manifest:{...manifest,dependencies:parsePackageDependencyPins(manifest.dependencies)}};var assertArchivePath=(path2)=>{if(path2===""||path2.startsWith("/")||path2.includes("\\")||path2.split("/").some((part)=>part===""||part==="."||part==="..")){throw new TypeError(`Extension Release archive has unsafe path '${path2}'`)}};var assertRuntimeAssetPath=(path2)=>{if(!/^artifacts\/(?:backend|dashboard|studio)\/.+/u.test(path2)){throw new TypeError(`Extension Release archive entry '${path2}' is not a runtime asset path`)}};var PackageManifestArchivePath="package-manifest.json";var assertReleaseArchiveEntryPath=(path2)=>{assertArchivePath(path2);if(path2!==PackageManifestArchivePath){assertRuntimeAssetPath(path2)}};var ExtensionReleaseManifestVersion="v2";var sha256Pattern=/^[\da-f]{64}$/u;var isExtensionHost=(value3)=>value3==="backend"||value3==="dashboard"||value3==="studio";var isRecord=(value3)=>value3!==null&&typeof value3==="object"&&!Array.isArray(value3);var assertExactKeys=(value3,allowedKeys,label)=>{const allowed=new Set(allowedKeys);const unexpected=Object.keys(value3).find((key)=>!allowed.has(key));if(unexpected!==undefined){throw new TypeError(`${label} has unexpected field '${unexpected}'`)}};var requireRecord=(value3,label)=>{if(!isRecord(value3)){throw new TypeError(`${label} must be an object`)}return value3};var requireString=(value3,label)=>{if(typeof value3!=="string"||value3.trim()===""){throw new TypeError(`${label} must be a non-empty string`)}return value3};var requireDigest=(value3,label)=>{const digest=requireString(value3,label);if(!sha256Pattern.test(digest)){throw new TypeError(`${label} must be a lowercase SHA-256 digest`)}return digest};var requireSize=(value3,label)=>{if(typeof value3!=="number"||!Number.isSafeInteger(value3)||value3<0){throw new TypeError(`${label} must be a non-negative safe integer`)}return value3};var requireHost=(value3,label)=>{if(typeof value3!=="string"||!isExtensionHost(value3)){throw new TypeError(`${label} must identify a supported Host`)}return value3};var assertUniqueSorted=(values,keyOf,label)=>{let previous;for(const value3 of values){const current=keyOf(value3);if(previous!==undefined&&current<=previous){throw new TypeError(`${label} must be unique and sorted`)}previous=current}};var parsePrivateSourceMap=(value3,label)=>{const sourceMap=requireRecord(value3,label);assertExactKeys(sourceMap,["digest","size"],label);return{digest:requireDigest(sourceMap.digest,`${label}.digest`),size:requireSize(sourceMap.size,`${label}.size`)}};var parseAsset=(value3,index)=>{const label=`Extension Release asset ${index}`;const asset=requireRecord(value3,label);assertExactKeys(asset,["digest","host","path","privateSourceMap","size"],label);const path2=requireString(asset.path,`${label}.path`);assertArchivePath(path2);assertRuntimeAssetPath(path2);const host=requireHost(asset.host,`${label}.host`);if(!path2.startsWith(`artifacts/${host}/`)){throw new TypeError(`Extension Release asset '${path2}' does not match Host '${host}'`)}return{digest:requireDigest(asset.digest,`${label}.digest`),host,path:path2,...asset.privateSourceMap===undefined?undefined:{privateSourceMap:parsePrivateSourceMap(asset.privateSourceMap,`${label}.privateSourceMap`)},size:requireSize(asset.size,`${label}.size`)}};var parseContribution=(value3,index)=>{const label=`Extension Release contribution ${index}`;const contribution=requireRecord(value3,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=(value3)=>{const manifest=requireRecord(value3,"Extension Release manifest");assertExactKeys(manifest,["apiVersion","assets","compatibility","contributions","package","packageManifest","releaseDigest"],"Extension Release manifest");if(manifest.apiVersion!==ExtensionReleaseManifestVersion){throw new TypeError("Extension Release manifest has unsupported apiVersion")}if(!Array.isArray(manifest.assets)){throw new TypeError("Extension Release manifest assets must be an array")}if(!Array.isArray(manifest.contributions)){throw new TypeError("Extension Release manifest contributions must be an array")}const compatibilityInput=requireRecord(manifest.compatibility,"Extension Release manifest compatibility");const compatibility=Object.fromEntries(Object.entries(compatibilityInput).map(([runtime,range])=>[requireString(runtime,"Extension Release compatibility runtime"),requireString(range,`Extension Release compatibility '${runtime}'`)]));const packageInput=requireRecord(manifest.package,"Extension Release manifest package");assertExactKeys(packageInput,["fqn","version"],"Extension Release package");const packageManifest=manifest.packageManifest===undefined?undefined:parsePackageManifest(manifest.packageManifest);if(packageManifest!==undefined&&(packageManifest.fqn!==packageInput.fqn||packageManifest.version!==packageInput.version)){throw new TypeError("Extension Release retained declarations do not match package identity")}const assets=manifest.assets.map(parseAsset);const contributions=manifest.contributions.map(parseContribution);assertUniqueSorted(assets,({path:path2})=>path2,"Extension Release manifest assets");assertUniqueSorted(contributions,({fqn,host})=>`${host}\x00${fqn}`,"Extension Release manifest contributions");const assetByPath=new Map(assets.map((asset)=>[asset.path,asset]));for(const contribution of contributions){const asset=assetByPath.get(contribution.assetPath);if(asset===undefined||asset.digest!==contribution.digest||asset.host!==contribution.host||asset.size!==contribution.size){throw new TypeError(`Extension Release contribution '${contribution.fqn}' does not match its declared runtime asset`)}}return{apiVersion:ExtensionReleaseManifestVersion,assets,compatibility,contributions,package:{fqn:requireString(packageInput.fqn,"Extension Release package.fqn"),version:requireString(packageInput.version,"Extension Release package.version")},...packageManifest===undefined?undefined:{packageManifest},releaseDigest:requireDigest(manifest.releaseDigest,"Extension Release manifest.releaseDigest")}};var canonicalExtensionReleaseManifest=(manifest)=>canonicalJson(manifest);var archiveBlockSize=512;var isZeroBlock=(bytes2)=>bytes2.every((value3)=>value3===0);var decodeCanonicalTextField=(bytes2,label)=>{const terminator=bytes2.indexOf(0);const contentEnd=terminator===-1?bytes2.byteLength:terminator;if(bytes2.subarray(0,contentEnd).some((byte)=>byte>127)||terminator!==-1&&!isZeroBlock(bytes2.subarray(terminator))){throw new TypeError(`Extension Release archive has non-canonical ${label}`)}return String.fromCodePoint(...bytes2.subarray(0,contentEnd))};var parseCanonicalOctalField=(bytes2,label)=>{const digits=bytes2.subarray(0,bytes2.byteLength-1);if(bytes2.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 declared2=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!==declared2){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 path2=prefix===""?name:`${prefix}/${name}`;assertReleaseArchiveEntryPath(path2);if(paths.has(path2)||compareUtf16CodeUnits(path2,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:path2});paths.add(path2);previousPath=path2;offset=paddedBodyEnd}throw new TypeError("Extension Release archive has no canonical trailer")};var validateExtensionReleaseArchiveMetadata=(entries,manifest)=>{const metadata3=entries.filter(({path:path2})=>path2===PackageManifestArchivePath);if(manifest.packageManifest===undefined){if(metadata3.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=metadata3[0]?.bytes;if(metadata3.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:path2})=>path2!==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 util;(function(util2){util2.assertEqual=(_)=>{};function assertIs(_arg){}util2.assertIs=assertIs;function assertNever(_x){throw new Error}util2.assertNever=assertNever;util2.arrayToEnum=(items)=>{const obj={};for(const item of items){obj[item]=item}return obj};util2.getValidEnumValues=(obj)=>{const validKeys=util2.objectKeys(obj).filter((k)=>typeof obj[obj[k]]!=="number");const filtered={};for(const k of validKeys){filtered[k]=obj[k]}return util2.objectValues(filtered)};util2.objectValues=(obj)=>{return util2.objectKeys(obj).map(function(e){return obj[e]})};util2.objectKeys=typeof Object.keys==="function"?(obj)=>Object.keys(obj):(object2)=>{const keys=[];for(const key in object2){if(Object.prototype.hasOwnProperty.call(object2,key)){keys.push(key)}}return keys};util2.find=(arr,checker)=>{for(const item of arr){if(checker(item))return item}return};util2.isInteger=typeof Number.isInteger==="function"?(val)=>Number.isInteger(val):(val)=>typeof val==="number"&&Number.isFinite(val)&&Math.floor(val)===val;function joinValues(array3,separator=" | "){return array3.map((val)=>typeof val==="string"?`'${val}'`:val).join(separator)}util2.joinValues=joinValues;util2.jsonStringifyReplacer=(_,value3)=>{if(typeof value3==="bigint"){return value3.toString()}return value3}})(util||(util={}));var objectUtil;(function(objectUtil2){objectUtil2.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(value3){if(!(value3 instanceof ZodError)){throw new Error(`Not a ZodError: ${value3}`)}}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:path2,errorMaps,issueData}=params;const fullPath=[...path2,...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 map8 of maps){errorMessage=map8(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,results2){const arrayValue=[];for(const s of results2){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 value3=await pair.value;syncPairs.push({key,value:value3})}return ParseStatus.mergeObjectSync(status,syncPairs)}static mergeObjectSync(status,pairs){const finalObject={};for(const pair of pairs){const{key,value:value3}=pair;if(key.status==="aborted")return INVALID;if(value3.status==="aborted")return INVALID;if(key.status==="dirty")status.dirty();if(value3.status==="dirty")status.dirty();if(key.value!=="__proto__"&&(typeof value3.value!=="undefined"||pair.alwaysSet)){finalObject[key.value]=value3.value}}return{status:status.value,value:finalObject}}}var INVALID=Object.freeze({status:"aborted"});var DIRTY=(value3)=>({status:"dirty",value:value3});var OK=(value3)=>({status:"valid",value:value3});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(errorUtil2){errorUtil2.errToObj=(message)=>typeof message==="string"?{message}:message||{};errorUtil2.toString=(message)=>typeof message==="string"?message:message?.message})(errorUtil||(errorUtil={}));class ParseInputLazyPath{constructor(parent,value3,path2,key){this._cachedPath=[];this.parent=parent;this.data=value3;this._path=path2;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,result3)=>{if(isValid(result3)){return{success:true,data:result3.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:errorMap2,invalid_type_error,required_error,description}=params;if(errorMap2&&(invalid_type_error||required_error)){throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`)}if(errorMap2)return{errorMap:errorMap2,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 result3=this._parse(input);if(isAsync(result3)){throw new Error("Synchronous parse encountered promise.")}return result3}_parseAsync(input){const result3=this._parse(input);return Promise.resolve(result3)}parse(data,params){const result3=this.safeParse(data,params);if(result3.success)return result3.data;throw result3.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 result3=this._parseSync({data,path:ctx.path,parent:ctx});return handleResult(ctx,result3)}"~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 result3=this._parseSync({data,path:[],parent:ctx});return isValid(result3)?{value:result3.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((result3)=>isValid(result3)?{value:result3.value}:{issues:ctx.common.issues})}async parseAsync(data,params){const result3=await this.safeParseAsync(data,params);if(result3.success)return result3.data;throw result3.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 result3=await(isAsync(maybeAsyncResult)?maybeAsyncResult:Promise.resolve(maybeAsyncResult));return handleResult(ctx,result3)}refine(check2,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 result3=check2(val);const setError=()=>ctx.addIssue({code:ZodIssueCode.custom,...getIssueProperties(val)});if(typeof Promise!=="undefined"&&result3 instanceof Promise){return result3.then((data)=>{if(!data){setError();return false}else{return true}})}if(!result3){setError();return false}else{return true}})}refinement(check2,refinementData){return this._refinement((val,ctx)=>{if(!check2(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(option2){return ZodUnion.create([this,option2],this._def)}and(incoming){return ZodIntersection.create(this,incoming,this._def)}transform(transform3){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:transform3}})}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(args2){let secondsRegexSource=`[0-5]\\d`;if(args2.precision){secondsRegexSource=`${secondsRegexSource}\\.\\d{${args2.precision}}`}else if(args2.precision==null){secondsRegexSource=`${secondsRegexSource}(\\.\\d+)?`}const secondsQuantifier=args2.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`}function timeRegex(args2){return new RegExp(`^${timeRegexSource(args2)}$`)}function datetimeRegex(args2){let regex=`${dateRegexSource}T${timeRegexSource(args2)}`;const opts=[];opts.push(args2.local?`Z?`:`Z`);if(args2.offset)opts.push(`([+-]\\d{2}:?\\d{2})`);regex=`${regex}(${opts.join("|")})`;return new RegExp(`^${regex}$`)}function isValidIP(ip,version2){if((version2==="v4"||!version2)&&ipv4Regex.test(ip)){return true}if((version2==="v6"||!version2)&&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,version2){if((version2==="v4"||!version2)&&ipv4CidrRegex.test(ip)){return true}if((version2==="v6"||!version2)&&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 ctx2=this._getOrReturnCtx(input);addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:ctx2.parsedType});return INVALID}const status=new ParseStatus;let ctx=undefined;for(const check2 of this._def.checks){if(check2.kind==="min"){if(input.data.length<check2.value){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check2.value,type:"string",inclusive:true,exact:false,message:check2.message});status.dirty()}}else if(check2.kind==="max"){if(input.data.length>check2.value){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check2.value,type:"string",inclusive:true,exact:false,message:check2.message});status.dirty()}}else if(check2.kind==="length"){const tooBig=input.data.length>check2.value;const tooSmall=input.data.length<check2.value;if(tooBig||tooSmall){ctx=this._getOrReturnCtx(input,ctx);if(tooBig){addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check2.value,type:"string",inclusive:true,exact:true,message:check2.message})}else if(tooSmall){addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check2.value,type:"string",inclusive:true,exact:true,message:check2.message})}status.dirty()}}else if(check2.kind==="email"){if(!emailRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"email",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else if(check2.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:check2.message});status.dirty()}}else if(check2.kind==="uuid"){if(!uuidRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"uuid",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else if(check2.kind==="nanoid"){if(!nanoidRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else if(check2.kind==="cuid"){if(!cuidRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"cuid",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else if(check2.kind==="cuid2"){if(!cuid2Regex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else if(check2.kind==="ulid"){if(!ulidRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"ulid",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else if(check2.kind==="url"){try{new URL(input.data)}catch{ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"url",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else if(check2.kind==="regex"){check2.regex.lastIndex=0;const testResult=check2.regex.test(input.data);if(!testResult){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"regex",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else if(check2.kind==="trim"){input.data=input.data.trim()}else if(check2.kind==="includes"){if(!input.data.includes(check2.value,check2.position)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{includes:check2.value,position:check2.position},message:check2.message});status.dirty()}}else if(check2.kind==="toLowerCase"){input.data=input.data.toLowerCase()}else if(check2.kind==="toUpperCase"){input.data=input.data.toUpperCase()}else if(check2.kind==="startsWith"){if(!input.data.startsWith(check2.value)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{startsWith:check2.value},message:check2.message});status.dirty()}}else if(check2.kind==="endsWith"){if(!input.data.endsWith(check2.value)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{endsWith:check2.value},message:check2.message});status.dirty()}}else if(check2.kind==="datetime"){const regex=datetimeRegex(check2);if(!regex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"datetime",message:check2.message});status.dirty()}}else if(check2.kind==="date"){const regex=dateRegex;if(!regex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"date",message:check2.message});status.dirty()}}else if(check2.kind==="time"){const regex=timeRegex(check2);if(!regex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"time",message:check2.message});status.dirty()}}else if(check2.kind==="duration"){if(!durationRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"duration",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else if(check2.kind==="ip"){if(!isValidIP(input.data,check2.version)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"ip",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else if(check2.kind==="jwt"){if(!isValidJWT(input.data,check2.alg)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"jwt",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else if(check2.kind==="cidr"){if(!isValidCidr(input.data,check2.version)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"cidr",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else if(check2.kind==="base64"){if(!base64Regex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"base64",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else if(check2.kind==="base64url"){if(!base64urlRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"base64url",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else{util.assertNever(check2)}}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(check2){return new ZodString({...this._def,checks:[...this._def.checks,check2]})}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(value3,options){return this._addCheck({kind:"includes",value:value3,position:options?.position,...errorUtil.errToObj(options?.message)})}startsWith(value3,message){return this._addCheck({kind:"startsWith",value:value3,...errorUtil.errToObj(message)})}endsWith(value3,message){return this._addCheck({kind:"endsWith",value:value3,...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 ctx2=this._getOrReturnCtx(input);addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:ctx2.parsedType});return INVALID}let ctx=undefined;const status=new ParseStatus;for(const check2 of this._def.checks){if(check2.kind==="int"){if(!util.isInteger(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:check2.message});status.dirty()}}else if(check2.kind==="min"){const tooSmall=check2.inclusive?input.data<check2.value:input.data<=check2.value;if(tooSmall){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check2.value,type:"number",inclusive:check2.inclusive,exact:false,message:check2.message});status.dirty()}}else if(check2.kind==="max"){const tooBig=check2.inclusive?input.data>check2.value:input.data>=check2.value;if(tooBig){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check2.value,type:"number",inclusive:check2.inclusive,exact:false,message:check2.message});status.dirty()}}else if(check2.kind==="multipleOf"){if(floatSafeRemainder(input.data,check2.value)!==0){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.not_multiple_of,multipleOf:check2.value,message:check2.message});status.dirty()}}else if(check2.kind==="finite"){if(!Number.isFinite(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.not_finite,message:check2.message});status.dirty()}}else{util.assertNever(check2)}}return{status:status.value,value:input.data}}gte(value3,message){return this.setLimit("min",value3,true,errorUtil.toString(message))}gt(value3,message){return this.setLimit("min",value3,false,errorUtil.toString(message))}lte(value3,message){return this.setLimit("max",value3,true,errorUtil.toString(message))}lt(value3,message){return this.setLimit("max",value3,false,errorUtil.toString(message))}setLimit(kind,value3,inclusive,message){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind,value:value3,inclusive,message:errorUtil.toString(message)}]})}_addCheck(check2){return new ZodNumber({...this._def,checks:[...this._def.checks,check2]})}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(value3,message){return this._addCheck({kind:"multipleOf",value:value3,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 check2 of this._def.checks){if(check2.kind==="min"){const tooSmall=check2.inclusive?input.data<check2.value:input.data<=check2.value;if(tooSmall){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_small,type:"bigint",minimum:check2.value,inclusive:check2.inclusive,message:check2.message});status.dirty()}}else if(check2.kind==="max"){const tooBig=check2.inclusive?input.data>check2.value:input.data>=check2.value;if(tooBig){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_big,type:"bigint",maximum:check2.value,inclusive:check2.inclusive,message:check2.message});status.dirty()}}else if(check2.kind==="multipleOf"){if(input.data%check2.value!==BigInt(0)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.not_multiple_of,multipleOf:check2.value,message:check2.message});status.dirty()}}else{util.assertNever(check2)}}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(value3,message){return this.setLimit("min",value3,true,errorUtil.toString(message))}gt(value3,message){return this.setLimit("min",value3,false,errorUtil.toString(message))}lte(value3,message){return this.setLimit("max",value3,true,errorUtil.toString(message))}lt(value3,message){return this.setLimit("max",value3,false,errorUtil.toString(message))}setLimit(kind,value3,inclusive,message){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind,value:value3,inclusive,message:errorUtil.toString(message)}]})}_addCheck(check2){return new ZodBigInt({...this._def,checks:[...this._def.checks,check2]})}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(value3,message){return this._addCheck({kind:"multipleOf",value:value3,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 ctx2=this._getOrReturnCtx(input);addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:ctx2.parsedType});return INVALID}if(Number.isNaN(input.data.getTime())){const ctx2=this._getOrReturnCtx(input);addIssueToContext(ctx2,{code:ZodIssueCode.invalid_date});return INVALID}const status=new ParseStatus;let ctx=undefined;for(const check2 of this._def.checks){if(check2.kind==="min"){if(input.data.getTime()<check2.value){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_small,message:check2.message,inclusive:true,exact:false,minimum:check2.value,type:"date"});status.dirty()}}else if(check2.kind==="max"){if(input.data.getTime()>check2.value){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_big,message:check2.message,inclusive:true,exact:false,maximum:check2.value,type:"date"});status.dirty()}}else{util.assertNever(check2)}}return{status:status.value,value:new Date(input.data.getTime())}}_addCheck(check2){return new ZodDate({...this._def,checks:[...this._def.checks,check2]})}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((result4)=>{return ParseStatus.mergeArray(status,result4)})}const result3=[...ctx.data].map((item,i)=>{return def.type._parseSync(new ParseInputLazyPath(ctx,item,ctx.path,i))});return ParseStatus.mergeArray(status,result3)}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=(schema3,params)=>{return new ZodArray({type:schema3,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(params)})};function deepPartialify(schema3){if(schema3 instanceof ZodObject){const newShape={};for(const key in schema3.shape){const fieldSchema=schema3.shape[key];newShape[key]=ZodOptional.create(deepPartialify(fieldSchema))}return new ZodObject({...schema3._def,shape:()=>newShape})}else if(schema3 instanceof ZodArray){return new ZodArray({...schema3._def,type:deepPartialify(schema3.element)})}else if(schema3 instanceof ZodOptional){return ZodOptional.create(deepPartialify(schema3.unwrap()))}else if(schema3 instanceof ZodNullable){return ZodNullable.create(deepPartialify(schema3.unwrap()))}else if(schema3 instanceof ZodTuple){return ZodTuple.create(schema3.items.map((item)=>deepPartialify(item)))}else{return schema3}}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 ctx2=this._getOrReturnCtx(input);addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ctx2.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 value3=ctx.data[key];pairs.push({key:{status:"valid",value:key},value:keyValidator._parse(new ParseInputLazyPath(ctx,value3,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 value3=ctx.data[key];pairs.push({key:{status:"valid",value:key},value:catchall._parse(new ParseInputLazyPath(ctx,value3,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 value3=await pair.value;syncPairs.push({key,value:value3,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,schema3){return this.augment({[key]:schema3})}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(results2){for(const result3 of results2){if(result3.result.status==="valid"){return result3.result}}for(const result3 of results2){if(result3.result.status==="dirty"){ctx.common.issues.push(...result3.ctx.common.issues);return result3.result}}const unionErrors=results2.map((result3)=>new ZodError(result3.ctx.common.issues));addIssueToContext(ctx,{code:ZodIssueCode.invalid_union,unionErrors});return INVALID}if(ctx.common.async){return Promise.all(options.map(async(option2)=>{const childCtx={...ctx,common:{...ctx.common,issues:[]},parent:null};return{result:await option2._parseAsync({data:ctx.data,path:ctx.path,parent:childCtx}),ctx:childCtx}})).then(handleResults)}else{let dirty=undefined;const issues=[];for(const option2 of options){const childCtx={...ctx,common:{...ctx.common,issues:[]},parent:null};const result3=option2._parseSync({data:ctx.data,path:ctx.path,parent:childCtx});if(result3.status==="valid"){return result3}else if(result3.status==="dirty"&&!dirty){dirty={result:result3,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((issues2)=>new ZodError(issues2));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 option2=this.optionsMap.get(discriminatorValue);if(!option2){addIssueToContext(ctx,{code:ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[discriminator]});return INVALID}if(ctx.common.async){return option2._parseAsync({data:ctx.data,path:ctx.path,parent:ctx})}else{return option2._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 value3 of discriminatorValues){if(optionsMap.has(value3)){throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value3)}`)}optionsMap.set(value3,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 schema3=this._def.items[itemIndex]||this._def.rest;if(!schema3)return null;return schema3._parse(new ParseInputLazyPath(ctx,item,ctx.path,itemIndex))}).filter((x)=>!!x);if(ctx.common.async){return Promise.all(items).then((results2)=>{return ParseStatus.mergeArray(status,results2)})}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,value3],index)=>{return{key:keyType._parse(new ParseInputLazyPath(ctx,key,ctx.path,[index,"key"])),value:valueType._parse(new ParseInputLazyPath(ctx,value3,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 value3=await pair.value;if(key.status==="aborted"||value3.status==="aborted"){return INVALID}if(key.status==="dirty"||value3.status==="dirty"){status.dirty()}finalMap.set(key.value,value3.value)}return{status:status.value,value:finalMap}})}else{const finalMap=new Map;for(const pair of pairs){const key=pair.key;const value3=pair.value;if(key.status==="aborted"||value3.status==="aborted"){return INVALID}if(key.status==="dirty"||value3.status==="dirty"){status.dirty()}finalMap.set(key.value,value3.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(elements2){const parsedSet=new Set;for(const element of elements2){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((elements2)=>finalizeSet(elements2))}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(args2,error){return makeIssue({data:args2,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 fn3=ctx.data;if(this._def.returns instanceof ZodPromise){const me=this;return OK(async function(...args2){const error=new ZodError([]);const parsedArgs=await me._def.args.parseAsync(args2,params).catch((e)=>{error.addIssue(makeArgsIssue(args2,e));throw error});const result3=await Reflect.apply(fn3,this,parsedArgs);const parsedReturns=await me._def.returns._def.type.parseAsync(result3,params).catch((e)=>{error.addIssue(makeReturnsIssue(result3,e));throw error});return parsedReturns})}else{const me=this;return OK(function(...args2){const parsedArgs=me._def.args.safeParse(args2,params);if(!parsedArgs.success){throw new ZodError([makeArgsIssue(args2,parsedArgs.error)])}const result3=Reflect.apply(fn3,this,parsedArgs.data);const parsedReturns=me._def.returns.safeParse(result3,params);if(!parsedReturns.success){throw new ZodError([makeReturnsIssue(result3,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(args2,returns,params){return new ZodFunction({args:args2?args2: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=(value3,params)=>{return new ZodLiteral({value:value3,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=(schema3,params)=>{return new ZodPromise({type:schema3,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 effect2=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(effect2.type==="preprocess"){const processed=effect2.transform(ctx.data,checkCtx);if(ctx.common.async){return Promise.resolve(processed).then(async(processed2)=>{if(status.value==="aborted")return INVALID;const result3=await this._def.schema._parseAsync({data:processed2,path:ctx.path,parent:ctx});if(result3.status==="aborted")return INVALID;if(result3.status==="dirty")return DIRTY(result3.value);if(status.value==="dirty")return DIRTY(result3.value);return result3})}else{if(status.value==="aborted")return INVALID;const result3=this._def.schema._parseSync({data:processed,path:ctx.path,parent:ctx});if(result3.status==="aborted")return INVALID;if(result3.status==="dirty")return DIRTY(result3.value);if(status.value==="dirty")return DIRTY(result3.value);return result3}}if(effect2.type==="refinement"){const executeRefinement=(acc)=>{const result3=effect2.refinement(acc,checkCtx);if(ctx.common.async){return Promise.resolve(result3)}if(result3 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(effect2.type==="transform"){if(ctx.common.async===false){const base2=this._def.schema._parseSync({data:ctx.data,path:ctx.path,parent:ctx});if(!isValid(base2))return INVALID;const result3=effect2.transform(base2.value,checkCtx);if(result3 instanceof Promise){throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`)}return{status:status.value,value:result3}}else{return this._def.schema._parseAsync({data:ctx.data,path:ctx.path,parent:ctx}).then((base2)=>{if(!isValid(base2))return INVALID;return Promise.resolve(effect2.transform(base2.value,checkCtx)).then((result3)=>({status:status.value,value:result3}))})}}util.assertNever(effect2)}}ZodEffects.create=(schema3,effect2,params)=>{return new ZodEffects({schema:schema3,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:effect2,...processCreateParams(params)})};ZodEffects.createWithPreprocess=(preprocess,schema3,params)=>{return new ZodEffects({schema:schema3,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 result3=this._def.innerType._parse({data:newCtx.data,path:newCtx.path,parent:{...newCtx}});if(isAsync(result3)){return result3.then((result4)=>{return{status:"valid",value:result4.status==="valid"?result4.value:this._def.catchValue({get error(){return new ZodError(newCtx.common.issues)},input:newCtx.data})}})}else{return{status:"valid",value:result3.status==="valid"?result3.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 result3=this._def.innerType._parse(input);const freeze=(data)=>{if(isValid(data)){data.value=Object.freeze(data.value)}return data};return isAsync(result3)?result3.then((data)=>freeze(data)):freeze(result3)}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(ZodFirstPartyTypeKind2){ZodFirstPartyTypeKind2["ZodString"]="ZodString";ZodFirstPartyTypeKind2["ZodNumber"]="ZodNumber";ZodFirstPartyTypeKind2["ZodNaN"]="ZodNaN";ZodFirstPartyTypeKind2["ZodBigInt"]="ZodBigInt";ZodFirstPartyTypeKind2["ZodBoolean"]="ZodBoolean";ZodFirstPartyTypeKind2["ZodDate"]="ZodDate";ZodFirstPartyTypeKind2["ZodSymbol"]="ZodSymbol";ZodFirstPartyTypeKind2["ZodUndefined"]="ZodUndefined";ZodFirstPartyTypeKind2["ZodNull"]="ZodNull";ZodFirstPartyTypeKind2["ZodAny"]="ZodAny";ZodFirstPartyTypeKind2["ZodUnknown"]="ZodUnknown";ZodFirstPartyTypeKind2["ZodNever"]="ZodNever";ZodFirstPartyTypeKind2["ZodVoid"]="ZodVoid";ZodFirstPartyTypeKind2["ZodArray"]="ZodArray";ZodFirstPartyTypeKind2["ZodObject"]="ZodObject";ZodFirstPartyTypeKind2["ZodUnion"]="ZodUnion";ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"]="ZodDiscriminatedUnion";ZodFirstPartyTypeKind2["ZodIntersection"]="ZodIntersection";ZodFirstPartyTypeKind2["ZodTuple"]="ZodTuple";ZodFirstPartyTypeKind2["ZodRecord"]="ZodRecord";ZodFirstPartyTypeKind2["ZodMap"]="ZodMap";ZodFirstPartyTypeKind2["ZodSet"]="ZodSet";ZodFirstPartyTypeKind2["ZodFunction"]="ZodFunction";ZodFirstPartyTypeKind2["ZodLazy"]="ZodLazy";ZodFirstPartyTypeKind2["ZodLiteral"]="ZodLiteral";ZodFirstPartyTypeKind2["ZodEnum"]="ZodEnum";ZodFirstPartyTypeKind2["ZodEffects"]="ZodEffects";ZodFirstPartyTypeKind2["ZodNativeEnum"]="ZodNativeEnum";ZodFirstPartyTypeKind2["ZodOptional"]="ZodOptional";ZodFirstPartyTypeKind2["ZodNullable"]="ZodNullable";ZodFirstPartyTypeKind2["ZodDefault"]="ZodDefault";ZodFirstPartyTypeKind2["ZodCatch"]="ZodCatch";ZodFirstPartyTypeKind2["ZodPromise"]="ZodPromise";ZodFirstPartyTypeKind2["ZodBranded"]="ZodBranded";ZodFirstPartyTypeKind2["ZodPipeline"]="ZodPipeline";ZodFirstPartyTypeKind2["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((value3)=>value3.trim().length>0,"Expected a non-blank selection ID");var packageOperationRecoverySchema=enumType(["explicit_continuation","retry_safe"]);var packageOperationCommandSchema=unionType([objectType({kind:literalType("install"),packageFqn:nonBlankString,recovery:packageOperationRecoverySchema}),objectType({kind:literalType("promote"),packageId:nonBlankString,recovery:packageOperationRecoverySchema,releaseId:nonBlankString}),objectType({kind:literalType("publish"),packageFqn:nonBlankString,recovery:packageOperationRecoverySchema}),objectType({installationId:nonBlankString,kind:literalType("rollback"),packageId:nonBlankString,recovery:packageOperationRecoverySchema,releaseId:nonBlankString}),objectType({installationId:nonBlankString,kind:literalType("update"),packageId:nonBlankString,recovery:packageOperationRecoverySchema,releaseId:nonBlankString}),objectType({kind:literalType("update"),mode:literalType("sync"),packageFqn:nonBlankString,recovery:packageOperationRecoverySchema})]);var packageOperationStatusSchema=enumType(["awaiting_continuation","failed","pending","running","succeeded"]);var releaseDigestSchema=stringType().regex(/^[\da-f]{64}$/u);var releaseSelectionSchema=objectType({generation:stringType().regex(/^(?:0|[1-9][0-9]*)$/u),releaseDigest:releaseDigestSchema,releaseId:selectionIdSchema});var graphMemberSchema=releaseSelectionSchema.extend({installationId:selectionIdSchema,packageFqn:selectionIdSchema,packageId:selectionIdSchema});var pinSchema=objectType({fqn:nonBlankString,releaseDigest:releaseDigestSchema,releaseId:nonBlankString});var dependencyPathsSchema=arrayType(arrayType(stringType()));var blockerMessageSchema=stringType();var knownBlockerSchema=unionType([objectType({_tag:literalType("manual_prerequisite"),message:blockerMessageSchema,observed:pinSchema.nullable(),path:arrayType(pinSchema),paths:arrayType(arrayType(pinSchema)),required:pinSchema}),objectType({_tag:literalType("authority_denied"),boundary:enumType(["principal","publication","promotion"]),message:blockerMessageSchema,paths:dependencyPathsSchema}),objectType({_tag:enumType(["dirty_readonly","definition_rejected"]),definitions:arrayType(objectType({fqn:nonBlankString,kind:enumType(["workflow","agent","skill"])})),message:blockerMessageSchema,paths:dependencyPathsSchema}),objectType({_tag:enumType(["release_unavailable","release_identity_mismatch","conflicting_pins","cycle","installation_identity_mismatch","retained_requirement_conflict","package_identity_conflict"]),message:blockerMessageSchema,paths:dependencyPathsSchema})]);var preflightDiagnosticSchema=unionType([knownBlockerSchema,objectType({_tag:nonBlankString,message:blockerMessageSchema.optional(),paths:dependencyPathsSchema.optional()}).transform(({_tag,message,paths})=>({_tag:"unknown",message:message??`Blocked by ${_tag}.`,paths:paths??[],tag:_tag}))]);var appliedGraphFields={applicationId:nonBlankString,members:arrayType(graphMemberSchema)};var applicationStageSchema=unionType([objectType({state:enumType(["not_required","pending"])}),objectType({blocker:preflightDiagnosticSchema.optional(),state:literalType("not_applied")}).transform(({blocker,state})=>blocker===undefined?{state}:{blocker,state}),objectType({...appliedGraphFields,state:literalType("applied")})]);var hostOutcomeFieldsSchema=objectType({diagnosticId:nonBlankString.optional(),member:graphMemberSchema,observed:objectType({desired:releaseSelectionSchema.nullable(),serving:releaseSelectionSchema.nullable()}),result:enumType(["failed","pending","serving","stale"])});var hostOutcome=({diagnosticId,...outcome})=>diagnosticId===undefined?outcome:{...outcome,diagnosticId};var cleanupCandidateSchema=objectType({installationId:selectionIdSchema,packageFqn:selectionIdSchema,packageId:selectionIdSchema,releaseDigest:releaseDigestSchema,releaseId:selectionIdSchema});var cleanupProtectionSchema=unionType([objectType({dependent:pinSchema,kind:literalType("required_by"),protection:enumType(["desired","serving"])}),objectType({dependent:pinSchema,kind:literalType("unknown_requirement")}),objectType({kind:enumType(["built_in","explicit_intent","selection_changed","unknown_intent"])}),objectType({kind:literalType("workflow_use"),state:enumType(["published","draft_head","working_copy"]),template:objectType({fqn:nonBlankString,kind:nonBlankString,version:nonBlankString}),workflowId:nonBlankString}),objectType({bindingKind:enumType(["tool_instance","connection","knowledge_connector"]),id:nonBlankString,kind:literalType("live_binding")})]);var cleanupStageSchema=objectType({candidates:arrayType(cleanupCandidateSchema.extend({protections:arrayType(cleanupProtectionSchema).optional(),result:enumType(["pending","removed","retained"])}).transform(({protections,...candidate})=>protections===undefined?candidate:{...candidate,protections})),state:enumType(["pending","completed","failed"])});var failureSchema=objectType({message:nonBlankString,reason:enumType(["credential_not_found","credential_permission_denied","credential_scope_denied","credential_verification_unavailable","execution_failed","invalid_artifact","release_not_found","release_package_mismatch"])});var eventOutcomeSchema=unionType([objectType({...appliedGraphFields,kind:literalType("graph_applied")}),objectType({blocker:preflightDiagnosticSchema,kind:literalType("graph_not_applied")}),hostOutcomeFieldsSchema.extend({kind:literalType("host")}).transform(({kind,...outcome})=>({...hostOutcome(outcome),kind})),objectType({kind:literalType("retry_requested")}),failureSchema.extend({kind:literalType("command_failed")}),objectType({candidate:cleanupCandidateSchema,kind:literalType("cleanup_removed")}),objectType({candidate:cleanupCandidateSchema,kind:literalType("cleanup_retained"),protections:arrayType(cleanupProtectionSchema)})]);var packageOperationSnapshotSchema=objectType({application:applicationStageSchema,cleanup:cleanupStageSchema.optional(),command:packageOperationCommandSchema,continuationOf:nonBlankString.optional(),createdAt:stringType().datetime({offset:true}),failure:failureSchema.optional(),hosts:arrayType(hostOutcomeFieldsSchema.transform(hostOutcome)),id:nonBlankString,idempotencyKey:nonBlankString,lastEventSequence:numberType().int().nonnegative(),nextAction:enumType(["continue","none","retry","wait"]),organizationId:nonBlankString,packageFqn:nonBlankString,principal:unionType([objectType({kind:literalType("administrator"),userId:nonBlankString}),objectType({credentialId:nonBlankString,kind:literalType("publisher")}),objectType({actor:literalType("bootstrap"),kind:literalType("system")})]),publication:objectType({packageId:selectionIdSchema,releaseDigest:releaseDigestSchema,releaseId:selectionIdSchema}).optional(),recoveryReason:literalType("selection_outcome_unavailable").optional(),selection:objectType({generation:numberType().int().positive(),installationId:selectionIdSchema,releaseId:selectionIdSchema}).optional(),status:packageOperationStatusSchema,updatedAt:stringType().datetime({offset:true})});var packageOperationEventSchema=objectType({createdAt:stringType().datetime({offset:true}),operationId:nonBlankString,outcome:eventOutcomeSchema.optional(),sequence:numberType().int().nonnegative(),status:packageOperationStatusSchema});var decodePackageOperationEvent=(data)=>{const{outcome,...event}=packageOperationEventSchema.parse(JSON.parse(data));return outcome===undefined?event:{...event,outcome}};var decodePackageOperationSnapshot=(snapshot)=>{const decoded=packageOperationSnapshotSchema.parse(snapshot);const{cleanup,continuationOf,failure,publication,recoveryReason,selection,...required}=decoded;const snapshotDto=required;if(cleanup!==undefined){snapshotDto.cleanup=cleanup}if(continuationOf!==undefined){snapshotDto.continuationOf=continuationOf}if(failure!==undefined){snapshotDto.failure=failure}if(recoveryReason!==undefined){snapshotDto.recoveryReason=recoveryReason}if(publication!==undefined){snapshotDto.publication=publication}if(selection!==undefined){snapshotDto.selection=selection}return snapshotDto};import{createHash as createHash3}from"crypto";import{readFile as readFile3}from"fs/promises";var nonempty=String4.check(isMinLength(1),makeFilter2((value3)=>value3.trim().length>0));var uuid3=String4.check(isPattern2(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu));var connectorSetup=Struct({adoptions:optionalKey2(Record(nonempty,Struct({instanceId:uuid3}))),connections:optionalKey2(Record(nonempty,Union2([Struct({connectionId:uuid3}),Struct({newConnection:Struct({fields:JsonObject,name:nonempty})})])))});var parseConnectorSetup=(text)=>{try{return decodeUnknownSync(connectorSetup,{onExcessProperty:"error"})(JSON.parse(text))}catch{throw new TypeError("Invalid connector setup file; expected connections/adoptions with UUID references or newConnection name/fields")}};var readConnectorSetup=async(path2,readBytes=readFile3)=>{let bytes2;try{bytes2=await readBytes(path2)}catch{throw new TypeError("Could not read connector setup file")}return parseConnectorSetup(new TextDecoder().decode(bytes2))};var installPackage=async(input)=>{const request={client:input.client,headers:{"idempotency-key":input.idempotencyKey,"x-organization-id":input.organizationId},path:{fqn:input.packageFqn},throwOnError:true};if(input.body!==undefined){request.body=input.body}if(input.signal!==undefined){request.signal=input.signal}const response=await extensionPackagesInstall(request);return response.data};var updatePackage=async(input)=>{const request={body:input.body,client:input.client,headers:{"idempotency-key":input.idempotencyKey,"x-organization-id":input.organizationId},throwOnError:true};if(input.signal!==undefined){request.signal=input.signal}const response=await packageReleasesUpdateInstallation(request);return response.data};var publishPackage=async(input)=>{const request={body:input.body,client:input.client,headers:{"idempotency-key":input.idempotencyKey},throwOnError:true};if(input.signal!==undefined){request.signal=input.signal}const response=await packageReleasesPublish(request);return response.data};var promotePackage=async(input)=>{const request={body:input.body,client:input.client,headers:{"idempotency-key":input.idempotencyKey},throwOnError:true};if(input.signal!==undefined){request.signal=input.signal}const response=await packageReleasesPromote(request);return response.data};import{createHash}from"crypto";import{build as viteBuild,esmExternalRequirePlugin}from"vite";import{fileURLToPath as fileURLToPath2}from"url";var nodePath=runSync2(provide3(Path2,exports_NodePath.layer));var literalLazyImport=(declarationSpecifier,identity3)=>{const loaderSource=Function.prototype.toString.call(identity3.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(`${identity3.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(`${identity3.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(`${identity3.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,identity3)=>resolveLazyImportModule(declarationSpecifier,{load:identity3.load,subject:`Hosted Contribution '${identity3.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,exports_NodePath.layer));var isRecord2=(value3)=>value3!==null&&typeof value3==="object";var isPackageDefinition=(value3)=>{if(!isRecord2(value3)||!isRecord2(value3.manifest)){return false}return value3.manifest.apiVersion==="v4"&&typeof value3.manifest.fqn==="string"&&Array.isArray(value3.components)&&(value3.hostedContributions===undefined||Array.isArray(value3.hostedContributions))&&Array.isArray(value3.schemaSidecars)};var normalizePackageDefinition=(definition,packageLoader)=>({...definition,hostedContributions:definition.hostedContributions??[],...packageLoader===undefined?undefined:{packageLoader}});var isPackageLoader=(value3)=>typeof value3==="function";var packageLoaderMap=(loaders,definitions)=>{if(loaders===undefined){return}const fqns=definitions.map(({manifest})=>manifest.fqn);if(!isRecord2(loaders)){throw new TypeError("Declaration packageLoaders must be an object")}const entries=Object.entries(loaders);if(entries.length!==fqns.length||!fqns.every((fqn)=>Object.hasOwn(loaders,fqn))||!entries.every(([,loader])=>isPackageLoader(loader))){throw new TypeError(`Declaration packageLoaders must map exactly the declared packages (${fqns.join(", ")}) to lazy import functions`)}return new Map(entries.flatMap(([fqn,loader])=>isPackageLoader(loader)?[[fqn,loader]]:[]))};var declarationSpecifier=(specifier)=>{if(specifier.startsWith("data:")||specifier.startsWith("file:")||specifier.startsWith("http:")||specifier.startsWith("https:")||!specifier.startsWith(".")&&!specifier.startsWith("/")){return specifier}return pathToFileURL2(path2.resolve(process.cwd(),specifier)).href};var normalizeModuleDeclarations=(loaded)=>{const exported=loaded.packageDefinitions??loaded.packageDefinition??loaded.default;const candidate=isRecord2(exported)&&"default"in exported?exported.default:exported;const values=Array.isArray(candidate)?candidate:[candidate];if(values.length===0||!values.every(isPackageDefinition)){throw new TypeError(`Declaration module must export a PackageDefinition or PackageDefinition array; received ${JSON.stringify(candidate)}`)}const loaders=packageLoaderMap(loaded.packageLoaders,values);return values.map((definition)=>normalizePackageDefinition(definition,loaders?.get(definition.manifest.fqn)))};var loadPackageDeclarations=flow((specifier)=>tryPromise2(()=>import(declarationSpecifier(specifier))).pipe(map4((loaded)=>isRecord2(loaded)?loaded:undefined),flatMap3((loaded)=>loaded===undefined?fail6(new PackageDeclarationError({message:"Declaration module did not expose module exports"})):succeed6(normalizeModuleDeclarations(loaded)))),runPromise2);var loadFreshPackageDeclarations=flow((specifier)=>{const resolved=declarationSpecifier(specifier);if(!resolved.startsWith("file:")){return promise2(()=>loadPackageDeclarations(resolved))}const sourcePath=fileURLToPath3(resolved);const root=path2.dirname(sourcePath);return acquireUseRelease2(tryPromise2(()=>createServer({appType:"custom",configFile:false,logLevel:"silent",resolve:workspaceSourceResolve(process.execArgv),root,server:{middlewareMode:true},ssr:workspaceSourceSsrResolve(process.execArgv)})),(server)=>tryPromise2(()=>server.ssrLoadModule(`/${encodeURIComponent(path2.basename(sourcePath))}`)).pipe(flatMap3((loaded)=>isRecord2(loaded)?succeed6(normalizeModuleDeclarations(loaded)):fail6(new PackageDeclarationError({message:"Declaration module did not expose module exports"})))),(server)=>promise2(()=>server.close()))},runPromise2);var compareCanonicalText=(left,right)=>{if(left===right){return 0}return left<right?-1:1};var blockSize=512;var isAscii=(value3)=>{for(const character of value3){if((character.codePointAt(0)??128)>127){return false}}return true};var writeAscii=(target,offset,length,value3)=>{if(value3.length>length||!isAscii(value3)){throw new TypeError(`Value does not fit deterministic ustar field: ${value3}`)}for(let index=0;index<value3.length;index+=1){target[offset+index]=value3.codePointAt(index)??0}};var writeOctal=(target,offset,length,value3)=>{const source=value3.toString(8).padStart(length-1,"0");if(source.length>=length){throw new TypeError(`Value does not fit deterministic ustar number: ${value3}`)}writeAscii(target,offset,length-1,source)};var splitArchivePath=(path3)=>{if(path3===""||path3.startsWith("/")||path3.includes("\\")||path3.split("/").some((part)=>part===""||part==="."||part==="..")){throw new TypeError(`Unsafe Extension Release archive path '${path3}'`)}if(path3.length<=100){return{name:path3,prefix:""}}const separator=path3.lastIndexOf("/");const prefix=path3.slice(0,separator);const name=path3.slice(separator+1);if(separator===-1||name.length>100||prefix.length>155){throw new TypeError(`Extension Release archive path is too long: ${path3}`)}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,value3)=>total+value3,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:path3})=>path3)).size!==entries.length){throw new TypeError("Extension Release archive paths must be unique")}const size=entries.reduce((total,entry)=>total+blockSize+Math.ceil(entry.bytes.byteLength/blockSize)*blockSize,0)+blockSize*2;const archive=new Uint8Array(size);let offset=0;for(const entry of entries){archive.set(headerFor(entry),offset);offset+=blockSize;archive.set(entry.bytes,offset);offset+=Math.ceil(entry.bytes.byteLength/blockSize)*blockSize}return archive};var backendHostProvidedModules=["@collective-intelligence/extensions-sdk","@collective-intelligence/extensions-sdk-backend"];var frontendModules=["@collective-intelligence/extensions-sdk","@collective-intelligence/extensions-sdk-frontend-react","@collective-intelligence/extensions-sdk-frontend-react/workflow","@collective-intelligence/ui-react","@collective-intelligence/ui-react/icons","@collective-intelligence/ui-react/ui","@collective-intelligence/ui-react/ui-extensions","@tanstack/react-query","react","react-dom","react-dom/client","react/jsx-dev-runtime","react/jsx-runtime"];var modulesByHost={backend:backendHostProvidedModules,dashboard:[...frontendModules,"@xyflow/react"],studio:frontendModules};var FRONTEND_HOSTS=HOSTS.filter((host)=>host!=="backend");var hostProvidedModulesFor=(host)=>modulesByHost[host];var frontendHostProvidedModules=[...new Set(FRONTEND_HOSTS.flatMap(hostProvidedModulesFor))];var isHostProvidedModule=(host,specifier)=>modulesByHost[host].some((moduleName)=>moduleName===specifier);import{fileURLToPath as fileURLToPath4}from"url";var backendPackageEntry=(definition)=>{if(!definition.components.some((component)=>("implementation"in component))&&definition.schemaSidecars.length===0){return}const fqn=`${definition.manifest.fqn}.backend.package-runtime`;if(definition.hostedContributions.some(({manifest})=>manifest.fqn===fqn)){throw new TypeError(`Hosted Contribution '${fqn}' collides with the reserved Backend package runtime entry`)}return{exportName:"createPackageRuntime",fqn,host:"backend"}};var backendArtifactContributions=(definition)=>{const entry=backendPackageEntry(definition);return[...definition.hostedContributions.map(({manifest})=>manifest),...entry===undefined?[]:[entry]]};var backendPackageEntrySource=(packageFqn)=>`
262
+ `}`).join("")};class AppsEnrollCommandError extends TaggedError3()("AppsEnrollCommandError",{cause:optional2(Unknown2),message:String4}){}var EnrollmentRejected=TaggedStruct("ExternalAppEnrollmentRejected",{message:String4,reason:Literals(["application_type_changed","disabled","package_owned"])});var fail12=(message)=>new AppsEnrollCommandError({message});var enrollmentFailure=(fqn)=>(error)=>{if(error.status!==409||!is2(EnrollmentRejected)(error.body)){return fail6(error)}const reasons={application_type_changed:`External App ${fqn} cannot change its type: ${error.body.message}`,disabled:`External App ${fqn} is disabled; re-run ci apps enroll with --enable to enable it`,package_owned:`External App ${fqn} is package-owned; change it through its Extension Package`};return fail6(fail12(reasons[error.body.reason]))};var parseEnrollment=(args2)=>gen2(function*parseEnrollmentEffect(){const options=yield*parseCommandOptionsEffect(args2,{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((value3)=>value3.split(/[\s,]+/u).filter((scope3)=>scope3!==""));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(!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(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=(args2,dependencies)=>gen2(function*appsEnrollCommand(){const enrollment=yield*parseEnrollment(args2);const context3=yield*resolveOrganizationContext({args:args2,environment:dependencies.environment,fetch:dependencies.fetch});const request={client:context3.client,headers:{"x-organization-id":context3.organizationId}};const explainForbidden=explainOrganizationForbidden(context3,context3.organizationId);const tenant=yield*runTenantPreflight({context:context3,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)}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}
263
+ `);const redirect=yield*runRedirectPreflight({context:context3,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=enrollment.envFile===undefined?undefined:dependencies.readEnvFile(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(envFileValue(existingContent,`${enrollment.prefix}CLIENT_ID`)!==application.clientId||envFileValue(existingContent,`${enrollment.prefix}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;const values=[["ISSUER",discovery.issuer],["AUDIENCE",application.audience],["APPLICATION_ID",application.id],["CLIENT_ID",application.clientId],...clientSecret===undefined?[]:[["CLIENT_SECRET",clientSecret]],["ORGANIZATION_ID",context3.organizationId],["JWKS_URL",discovery.jwksUri],["SCOPES",application.scopes.join(" ")]];if(enrollment.envFile!==undefined){const path2=enrollment.envFile;yield*try_2({catch:(cause)=>new AppsEnrollCommandError({cause,message:`Could not write ${path2}`}),try:()=>{dependencies.writeEnvFile(path2,mergeEnvFile(existingContent,enrollment.prefix,values))}});dependencies.writeDiagnostic(`Wrote ${values.length} keys to ${path2}
264
+ `)}return yield*sync2(()=>{if(enrollment.json){dependencies.writeOutput(renderJson(enrollment.prefix,values))}else if(enrollment.envFile===undefined){dependencies.writeOutput(renderDotenv(enrollment.prefix,values))}})}).pipe(mapError2((cause)=>is2(AppsEnrollCommandError)(cause)?cause:new AppsEnrollCommandError({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=(value3)=>Object.prototype.toString.call(value3)==="[object Object]"&&!Array.isArray(value3)&&(Object.getPrototypeOf(value3)===Object.prototype||Object.getPrototypeOf(value3)===null);var isJsonArray=(value3)=>Array.isArray(value3);var canonicalize=(value3,ancestors,_valueType)=>{if(value3===null){return"null"}if(isJsonArray(value3)){if(ancestors.has(value3)){throw new TypeError("package declarations cannot contain cyclic values")}ancestors.add(value3);try{return`[${value3.map((item)=>canonicalize(item,ancestors)).join(",")}]`}finally{ancestors.delete(value3)}}if(isJsonObject(value3)){if(ancestors.has(value3)){throw new TypeError("package declarations cannot contain cyclic values")}ancestors.add(value3);try{const record2=value3;const keys=[];for(const key of Object.keys(record2)){insertSortedKey(keys,key)}return`{${keys.map((key)=>`${JSON.stringify(key)}:${canonicalize(record2[key],ancestors)}`).join(",")}}`}finally{ancestors.delete(value3)}}if(value3 instanceof Object){throw new TypeError("package declarations must contain JSON-compatible values")}switch(Object.prototype.toString.call(value3)){case"[object Boolean]":{return value3===true?"true":"false"}case"[object Number]":{const number3=Number(value3);if(!Number.isFinite(number3)){throw new TypeError("package declarations cannot contain non-finite numbers")}return JSON.stringify(number3)}case"[object String]":{return JSON.stringify(String(value3))}default:{throw new TypeError("package declarations must contain JSON-compatible values")}}};var canonicalJson=(value3,..._typeEvidence)=>canonicalize(value3,new WeakSet);var parseJsonObject=(source)=>{const value3=JSON.parse(source);if(!isJsonObject(value3)){throw new TypeError("expected a JSON object")}return value3};var compareUtf16CodeUnits=(left,right)=>{const length=Math.min(left.length,right.length);for(let index=0;index<length;index+=1){const difference=left.charCodeAt(index)-right.charCodeAt(index);if(difference!==0){return difference}}return left.length-right.length};var plainFormWidgets=["checkbox","color","date","date_range","datetime","email","file","hidden","number","password","structured_file_preview","switch","text","textarea","variable_references"];var selectFormWidgets=["folders_explorer","multi_select","radio","select"];var invalid4=(path2)=>{throw new TypeError(`Invalid package manifest at ${path2}`)};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=(value3,path2)=>{const text=identity2(value3,path2);return text===text.trim()?text:invalid4(path2)};var assertDenseArrays=(value3,path2,seen)=>{if(typeof value3!=="object"||value3===null||seen.has(value3)){return}seen.add(value3);if(Array.isArray(value3)){for(let index=0;index<value3.length;index+=1){if(!Object.hasOwn(value3,index)){invalid4(`${path2}/${index}`)}}}for(const[key,child]of Object.entries(value3)){assertDenseArrays(child,`${path2}/${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=(value3,path2)=>{const parsed=number3(value3,path2);return Number.isSafeInteger(parsed)&&parsed>0?parsed:invalid4(path2)};var optional3=(read2)=>(v,p)=>v===undefined?undefined:read2(v,p);var nullable=(read2)=>(v,p)=>v===null?null:read2(v,p);var literal=(...values)=>(v,p)=>{for(const value3 of values){if(v===value3){return value3}}return invalid4(p)};var array2=(read2)=>(v,p)=>{if(!Array.isArray(v)){return invalid4(p)}return v.map((item,index)=>read2(item,`${p}/${index}`))};var record2=(read2)=>(v,p)=>{if(typeof v!=="object"||v===null||Array.isArray(v)){return invalid4(p)}return Object.fromEntries(Object.entries(v).map(([key,value3])=>[key,read2(value3,`${p}/${key}`)]))};var object=(fields)=>(v,p)=>{if(typeof v!=="object"||v===null||Array.isArray(v)){return invalid4(p)}const entries=Object.entries(v);for(const key in fields){if(!Object.hasOwn(fields,key)){continue}fields[key](entries.find(([name])=>name===key)?.[1],`${p}/${key}`)}return v};var refine=(read2,violation)=>(v,p)=>{const value3=read2(v,p);return violation(value3)===undefined?value3: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),(value3)=>Object.keys(value3).some((key)=>!Object.hasOwn(fields,key))?"unexpected Gateway field":undefined);var identifier2=refine(string3,(value3)=>/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/u.test(value3)?undefined:"invalid identifier");var version=refine(string3,(value3)=>value3.length>0&&value3.length<=128&&value3.trim()===value3?undefined:"invalid version");var bounded2=(maximum,minimum=1)=>refine(number3,(value3)=>Number.isSafeInteger(value3)&&value3>=minimum&&value3<=maximum?undefined:"invalid limit");var unique=(read2,key)=>refine(read2,(values)=>new Set(values.map(key)).size===values.length?undefined:"duplicate identifier");var projection=refine(schema2,(value3)=>(value3.fidelity==="exact"||value3.fidelity==="structural")&&Object.keys(value3).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,(value3)=>value3.length>0&&value3.length<=256?undefined:"invalid scope")),(scope3)=>scope3)});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};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});var empty4=refine(array2(identity2),(values)=>values.length===0?undefined:"operation-only Gateway required");var emptyReader=(value3,path2)=>{empty4(value3,path2);return[]};var disabled=(value3,path2)=>boolean2(value3,path2)===false?false:invalid4(path2);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});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=(value3,path2)=>{assertDenseArrays(value3,path2,new WeakSet);const admitted=contractReader(value3,path2);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(path2)}return normalized};var deepFreeze=(value3)=>{if(value3!==null&&typeof value3==="object"&&!Object.isFrozen(value3)){Object.freeze(value3);for(const child of Object.values(value3)){deepFreeze(child)}}return value3};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=(value3)=>value3===undefined||value3===null||Number.isSafeInteger(value3)&&value3>=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((value3,index)=>values.indexOf(value3)!==index);var workflowEditorViolation=(editor)=>{const sections=editor.form?.sections??[];const duplicateSection=firstDuplicate(sections.flatMap((section)=>section.id===undefined?[]:[section.id]));if(duplicateSection!==undefined){return`workflow editor section id '${duplicateSection}' is not unique`}const fields=sections.flatMap((section)=>section.fields??[]);const keys=fields.map((field)=>workflowBindingKey(field.binding));const duplicateField=fields.find((field,index)=>keys.indexOf(workflowBindingKey(field.binding))!==index);if(duplicateField!==undefined){return`workflow editor binding ${renderWorkflowBinding(duplicateField.binding)} is not unique`}for(const field of fields){const references=[...(field.visibleWhen??[]).map((rule)=>rule.binding),...field.optionSource?.kind==="remote"?field.optionSource.dependsOn:[]];const dangling=references.find((reference)=>!keys.includes(workflowBindingKey(reference)));if(dangling!==undefined){return`workflow editor field ${renderWorkflowBinding(field.binding)} references unknown binding ${renderWorkflowBinding(dangling)}`}}return};var metadata=object({available:boolean2,label:string3});var connection=object({...base,compatibility:optional3(object({auth:optString,dialect:optString,extensions:optional3(jsonObject),provider:optString})),creationMode:optional3(literal("self_service","registration_only")),credential:form,defaultConnectionName:string3,discoveryMetadata:optional3(metadata),kind:literal("connection"),providerFamily:string3,secretFields:optStrings,testMetadata:optional3(metadata)});var pathParts=array2(union2(string3,number3));var bindingModes=array2(literal("external","managed"));var syncModes=array2(literal("delta","full"));var bindingScopes=array2(literal("organization","tenant"));var mutationPolicy=literal("always","connector_backed","never");var extraProps=literal("ignore","import","inline");var outboundStrategy=literal("local_first","remote_first");var updateMode=literal("full","partial");var localized=object({fallbackLocale:string3,values:record2(string3)});var catalogTags=optional3(record2(strings));var connectionRefs=optional3(array2(object({catalogCollection:optString,connectionTemplateFqn:string3,label:string3,required:optBoolean,slot:string3,visibleWhen:optional3(visibility)})));var fieldMap=(v,p)=>{const common={direction:literal("both","inbound","outbound"),local:string3,skipIfNull:boolean2};const{op}=object({op:string3})(v,p);switch(op){case"path":{return object({...common,op:literal(op),remote:string3})(v,p)}case"cast":{return object({...common,falseValues:optStrings,op:literal(op),remote:string3,trueValues:optStrings})(v,p)}case"default":{return object({...common,op:literal(op),remote:optString,value:json})(v,p)}case"concat":{return object({...common,op:literal(op),remote:strings,separator:optString})(v,p)}case"split":{return object({...common,discardEmpty:optBoolean,op:literal(op),remote:string3,separators:optStrings,trimItems:optBoolean,uniqueItems:optBoolean})(v,p)}case"coordinates":{return object({...common,latitudeKey:optString,longitudeKey:optString,op:literal(op),remote:(value3,location)=>{const parts2=strings(value3,location);if(parts2.length!==2){return invalid4(location)}return[string3(parts2[0],location),string3(parts2[1],location)]}})(v,p)}case"transform":{return object({...common,op:literal(op),remote:string3,transformerId:string3})(v,p)}default:{return invalid4(`${p}/op`)}}};var predefinedExtras=optional3(array2(object({displayName:nullable(string3),enabled:boolean2,id:string3,includeInEntityEmbedding:boolean2,kind:literal("linked_text","file_source"),slotKey:string3,source:jsonObject})));var predefinedSchedules=optional3(array2(object({cronExpression:string3,enabled:optBoolean,importMode:optional3(literal("delta","full")),label:optString,rationale:optString,timezone:optString})));var schemaCapability={extraPropsMode:optional3(extraProps),fieldMap:optional3(array2(fieldMap)),fqn:string3,outboundStrategy:optional3(outboundStrategy),predefinedBindingExtras:predefinedExtras,predefinedBindingKey:optString,predefinedBindingMode:optional3(literal("external","managed")),predefinedBindingRemoteCollectionId:optString,predefinedBindingRemoteCollectionName:optString,predefinedSchedules,supportedSyncModes:optional3(syncModes),supportsInbound:optBoolean,supportsOutbound:optBoolean,syncIntervalSeconds:optional3(nullable(number3)),updateMode:optional3(updateMode)};var entityCapability=object({...schemaCapability,predefinedBindingParentKey:optString,supportedBindingModes:optional3(bindingModes)});var relationCapability=object({...schemaCapability,predefinedBindingParentEntityKey:optString,predefinedBindingRelationImportMode:optional3(literal("child_binding","relation_only")),predefinedBindingSourceEntityKey:optString,predefinedBindingTargetEntityKey:optString});var discoveryDefaults=object({extraPropsMode:extraProps,outboundStrategy,supportedBindingModes:bindingModes,supportedSyncModes:syncModes,supportsInbound:boolean2,supportsOutbound:boolean2,syncIntervalSeconds:nullable(number3),updateMode});var datasetCapabilities=object({aggregates:array2(literal("count","count_distinct","sum","min","max","avg")),definitionRefresh:boolean2,grouping:boolean2,intents:array2(literal("records","aggregate","time_series")),limits:object({maxBytes:number3,maxPageRows:number3,maxRows:number3,timeoutMs:number3}),ordering:boolean2,pagination:boolean2,predicates:array2(literal("eq","ne","lt","lte","gt","gte","in","not_in","is_null","is_not_null","contains","starts_with"))});var fieldSemantics=object({defaultSearch:optBoolean,embedded:optBoolean,faceted:optBoolean,indexContent:optBoolean,indexOverview:optBoolean,indexed:optBoolean,managedProjectionSource:optional3(literal("organization_group","organization_user")),queryGuidance:optString,unique:optBoolean});var managedProjection=object({connectorPolicy:literal("allow","deny_schema"),genericMutationPolicy:literal("deny_managed_fields","deny_schema"),kind:literal("directory_person","directory_person_in_group","directory_group","directory_group_parent"),source:literal("organization_group","organization_group_hierarchy","organization_group_membership","organization_user")});var fieldLocalization=object({description:optional3(localized),help:optional3(localized),label:optional3(localized),placeholder:optional3(localized)});var fieldPresentation=object({copyable:optBoolean,editor:optString,editorOptions:optional3(object({accepts:optStrings,allowCustomValues:optBoolean,autocomplete:optString,clearable:optBoolean,falseLabel:optString,multiple:optBoolean,options:optional3(array2(object({label:string3,value:string3}))),rows:optNumber,searchable:optBoolean,showButtons:optBoolean,spellcheck:optBoolean,step:optNumber,trueLabel:optString})),emptyLabel:optString,falseLabel:optString,hidden:optBoolean,layout:optional3(object({column:optNumber,labelPlacement:optional3(literal("left","top")),order:optNumber,row:optNumber,width:optional3(union2(number3,literal("full")))})),maxLines:optNumber,readOnly:optBoolean,renderer:optString,trueLabel:optString});var lifecycle=object({deployMode:literal("init_only","upsert"),readonly:boolean2});var autocompleteConfiguration=object({autocompleteFields:array2(object({field:string3,scope:literal("data","entity")})),defaultAutocompleteFields:array2(object({field:string3,scope:literal("data","entity")}))});var knowledgeSchema={catalogTags,domainFqn:string3,fieldLocalization:optional3(record2(fieldLocalization)),fieldPresentation:optional3(record2(fieldPresentation)),fieldSemantics:optional3(record2(fieldSemantics)),localMutationPolicy:optional3(mutationPolicy),managedProjection:optional3(managedProjection),schema:schema2};var policyRef=(value3,path2)=>{const{kind}=object({kind:string3})(value3,path2);return kind==="literal"?object({kind:literal("literal"),value:json})(value3,path2):object({kind:literal("subject","resource"),path:strings})(value3,path2)};var uuid=(value3,path2)=>{const parsed=identity2(value3,path2);return/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu.test(parsed)?parsed:invalid4(path2)};var policyPredicate=(value3,path2)=>{const{op}=object({op:string3})(value3,path2);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})(value3,path2)}case"in":{return object({op:literal("in"),set:policyRef,value:policyRef})(value3,path2)}case"exists":case"is_null":{return object({op:literal("exists","is_null"),ref:policyRef})(value3,path2)}case"contains":case"starts_with":{return object({op:literal("contains","starts_with"),ref:policyRef,value:policyRef})(value3,path2)}case"const":{return object({op:literal("const"),value:boolean2})(value3,path2)}case"not":{return object({arg:policyPredicate,op:literal("not")})(value3,path2)}case"and":case"or":{return object({args:array2(policyPredicate),op:literal("and","or")})(value3,path2)}case"relation_exists":{return object({direction:literal("out","in"),op:literal("relation_exists"),relationSchemaId:uuid})(value3,path2)}case"relation_field":{return object({direction:literal("out","in"),inner:policyPredicate,op:literal("relation_field"),relationSchemaId:uuid})(value3,path2)}default:{return invalid4(`${path2}/op`)}}};var policyBody=object({rule:optional3(policyPredicate),subjectMatch:policyPredicate});var policyFields={effect:literal("allow","deny"),policyBody,policyType:literal("filter","gate"),targetFqn:identity2,targetKind:literal("entity_domain","entity_schema","relation_domain","relation_schema")};var connection2=refine(object({setupKey:identity2}),(value3)=>Object.keys(value3).some((key)=>key!=="setupKey")?"install-only input":undefined);var bindingFields={executionRole:optional3(literal("root","child")),extraPropsMode:optional3(literal("ignore","import","inline")),extras:refine(predefinedExtras,(extras)=>extras?.some((extra)=>!/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu.test(extra.id))?"invalid extra UUID":undefined),fieldMap:optional3(array2(fieldMap)),key:identity2,outboundStrategy:optional3(literal("local_first","remote_first")),parentKey:optional3(nullable(identity2)),remoteCollectionId:optional3(nullable(string3)),remoteCollectionName:optional3(nullable(string3)),supportedSyncModes:optional3(array2(literal("delta","full"))),supportsInbound:optBoolean,supportsOutbound:optBoolean,syncIntervalSeconds:optional3(nullable(positiveSafeInteger)),updateMode:optional3(literal("full","partial"))};var entityBinding=object({...bindingFields,bindingMode:literal("managed","external"),missingConnectorFieldsBehavior:optional3(literal("prune","retain")),pushEntityMatch:optional3(literal("remote_ref","unique_fields")),schemaFqn:identity2,supportedBindingModes:optional3(array2(literal("managed","external"))),suppressEntityEvents:optBoolean});var relationBinding=object({...bindingFields,bindingMode:optional3(literal("managed")),relationImportMode:optional3(literal("child_binding","relation_only")),relationSchemaFqn:identity2,sourceEntityKey:optional3(nullable(identity2)),targetEntityKey:optional3(nullable(identity2))});var schedule2=object({cronExpression:identity2,enabled:optBoolean,importMode:optional3(literal("delta","full")),key:identity2,timezone:optString});var positive=refine(number3,(n)=>n>0?undefined:"positive");var budget=optional3(nullable(positiveSafeInteger));var pipeline=object({definition:object({budgets:optional3(object({maxPagesPerRun:budget,maxRemoteItemsPerRun:budget,maxRootWorkUnitsPerRun:budget,maxSecondsPerRun:optional3(nullable(positive))})),steps:refine(array2(object({tasks:array2(object({bindingKey:identity2,kind:literal("entity","relation"),modeOverride:optional3(nullable(literal("delta","full")))}))})),(steps)=>steps.length>0?undefined:"empty")}),enabled:optBoolean,key:identity2,name:optString,schedules:optional3(array2(schedule2))});var uniqueKeys=(values,path2)=>{const seen=new Set;for(const[index,value3]of values.entries()){if(seen.has(value3.key)){invalid4(`${path2}/${index}/key`)}seen.add(value3.key)}};var knowledge=object({...base,connections:optional3(record2(connection2)),dataPolicies:optional3(array2(object({...policyFields,fqn:identity2,priority:optNumber}))),enabled:optBoolean,entityBindings:optional3(array2(entityBinding)),kind:literal("knowledgeConnectorInstance"),lifecycle,pipelines:optional3(array2(pipeline)),relationBindings:optional3(array2(relationBinding)),remoteFilters:optional3(record2(object({mode:literal("all","only_selected","all_except_selected"),selected_ids:strings}))),settings:optional3(record2(object({type:literal("inline","linked"),value:json}))),templateFqn:identity2});var assertEntityParents=(entities,path2)=>{const parents=new Map(entities.map((b)=>[b.key,b.parentKey]));for(const binding of entities){const seen=new Set([binding.key]);let parent=binding.parentKey;while(parent){if(seen.has(parent)){invalid4(`${path2}/entityBindings/parentKey`)}seen.add(parent);parent=parents.get(parent)}}};var assertPolicyLifecycle=(policies,path2)=>{for(const[index,policy]of policies.entries()){if(Object.keys(policy).some((key)=>key==="lifecycle"||key==="deployMode"||key==="readonly")){invalid4(`${path2}/dataPolicies/${index}/lifecycle`)}}};var knowledgeConnectorInstance=(value3,path2)=>{const parsed=knowledge(value3,path2);assertPolicyLifecycle(parsed.dataPolicies??[],path2);const entities=parsed.entityBindings??[];const relations=parsed.relationBindings??[];const pipelines=parsed.pipelines??[];uniqueKeys(entities,`${path2}/entityBindings`);uniqueKeys(relations,`${path2}/relationBindings`);uniqueKeys(pipelines,`${path2}/pipelines`);const entityKeys=new Set(entities.map((b)=>b.key));const relationKeys=new Set(relations.map((b)=>b.key));assertEntityParents(entities,path2);for(const[index,binding]of[...entities,...relations].entries()){if(binding.parentKey&&(!entityKeys.has(binding.parentKey)||binding.parentKey===binding.key)){invalid4(`${path2}/bindings/${index}/parentKey`)}}for(const[index,relation]of relations.entries()){for(const key of[relation.sourceEntityKey,relation.targetEntityKey]){if(key&&!entityKeys.has(key)){invalid4(`${path2}/relationBindings/${index}`)}}}for(const[index,item]of pipelines.entries()){uniqueKeys(item.schedules??[],`${path2}/pipelines/${index}/schedules`);const tasks=new Set;for(const step of item.definition.steps){for(const task of step.tasks){const keys=task.kind==="entity"?entityKeys:relationKeys;const key=`${task.kind}:${task.bindingKey}`;if(!keys.has(task.bindingKey)||tasks.has(key)){invalid4(`${path2}/pipelines/${index}/definition/steps`)}tasks.add(key)}}}return parsed};var scalar=literal("boolean","string","int64","float64","decimal","date","timestamp","duration","json");var datasetDefinition=object({fields:array2(object({id:identity2,name:string3,nullable:boolean2,semantic:optString,type:scalar})),measures:array2(object({id:identity2,name:string3,resultType:scalar})),relationships:array2(object({cardinality:literal("one_to_one","one_to_many","many_to_one","many_to_many"),fromFieldId:identity2,id:identity2,toFieldId:identity2})),version:literal(1)});var location=(value3,path2)=>{const{segments}=object({segments:array2(object({kind:literal("container","dataset"),label:string3,opaqueId:identity2}))})(value3,path2);const[first]=segments;if(!first||first.kind!=="container"){return invalid4(`${path2}/segments/0`)}return{segments:[{...first,kind:"container"},...segments.slice(1)]}};var datasetValue=(value3,path2)=>{const{kind}=object({kind:string3})(value3,path2);switch(kind){case"null":{return object({kind:literal("null")})(value3,path2)}case"boolean":{return object({kind:literal("boolean"),value:boolean2})(value3,path2)}case"float64":{return object({kind:literal("float64"),value:number3})(value3,path2)}case"json":{return object({kind:literal("json"),value:json})(value3,path2)}default:{return object({kind:literal("string","int64","decimal","date","timestamp","duration"),value:string3})(value3,path2)}}};var datasetFilter=(value3,path2)=>{const{kind}=object({kind:string3})(value3,path2);if(kind==="not"){return object({filter:datasetFilter,kind:literal("not")})(value3,path2)}if(kind==="and"||kind==="or"){return object({filters:array2(datasetFilter),kind:literal("and","or")})(value3,path2)}return object({fieldId:identity2,kind:literal("predicate"),operator:literal("eq","ne","lt","lte","gt","gte","in","not_in","is_null","is_not_null","contains","starts_with"),values:array2(datasetValue)})(value3,path2)};var datasetFields={...base,connection:optional3(connection2),dataPolicy:optional3(object({allowedFields:strings,allowedOperations:array2(literal("describe","records","aggregate","time_series")),maxBytes:budget,maxRows:budget,maxTimeoutMs:budget,principals:array2(object({id:identity2,kind:literal("user","service")})),rowFilter:optional3(nullable(datasetFilter)),sensitiveFields:optional3(strings)})),kind:literal("datasetConnectorInstance"),lifecycle,providerFqn:identity2,schedules:optional3(array2(object({action:literal("health","refresh_definition"),cronExpression:identity2,enabled:optBoolean,key:identity2,timezone:optString}))),settings:optional3(jsonObject)};var datasetConnectorInstance=(value3,path2)=>{const parsed=union2(object({...datasetFields,bindingMode:literal("managed"),definition:datasetDefinition,sourceLocation:optional3(location),templateConfig:optional3(object({variant:identity2,version:literal(1)})),templateFqn:optional3(identity2)}),object({...datasetFields,bindingMode:literal("external"),definition:optional3(datasetDefinition),gatewayBindingKey:optString,sourceLocation:location,sourceMapping:optional3(object({effectiveAtFieldId:optString,entityIdFieldId:identity2,historySemantics:optional3(literal("append_history")),kind:literal("entity_snapshot","status_update"),statusFieldId:optString,version:literal(1)}))}))(value3,path2);uniqueKeys(parsed.schedules??[],`${path2}/schedules`);return parsed};var datasetParserFormat=(value3,path2)=>{if(typeof value3!=="string"||value3.length>128||value3==="external"||!/^[a-z][a-z0-9._-]*$/u.test(value3)){throw new TypeError(`Invalid dataset parser format at ${path2}`)}return value3};var datasetParserVersion=(value3,path2)=>{if(typeof value3!=="string"||value3.trim()===""||value3.length>96){throw new TypeError(`Invalid dataset parser version at ${path2}`)}return value3};var readExternalAppGateway=closedGatewayObject({...base,expectedContract:readOperationGatewayContract,kind:literal("externalAppGateway")});var externalApplicationViolation=({primaryRedirectUri,redirectUris})=>primaryRedirectUri===undefined||redirectUris.includes(primaryRedirectUri)?undefined:"primaryRedirectUri must be one of redirectUris";var identifier22=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/u;var fields=new Set(["category","defaultVisibility","description","displayName","fqn","gatewayRef","icon","kind","operationReferences","tags","version"]);var referencesGateway=(reference,gatewayId)=>{const separator=reference.indexOf("@");if(separator===-1){return false}const[gateway,domain,operation,...rest]=reference.slice(0,separator).split("/");const version2=reference.slice(separator+1);return identifier22.test(gatewayId)&&gateway===gatewayId&&domain!==undefined&&identifier22.test(domain)&&operation!==undefined&&identifier22.test(operation)&&rest.length===0&&version2.length>0&&version2.length<=128&&version2.trim()===version2};var remoteToolCollectionViolation=(declaration)=>{const unknownField=Object.keys(declaration).find((key)=>!fields.has(key));if(unknownField!==undefined){return`unsupported remote metadata field '${unknownField}'`}const{gatewayRef,operationReferences}=declaration;if(gatewayRef===undefined||gatewayRef.trim()===""||gatewayRef.trim()!==gatewayRef){return"gatewayRef must be a nonempty FQN"}if(operationReferences.length===0||new Set(operationReferences).size!==operationReferences.length||operationReferences.some((reference)=>!referencesGateway(reference,reference.split("/")[0]??""))){return"operationReferences must name unique versioned Gateway operations"}return};var readPin=object({fqn:hostedIdentity,releaseDigest:(value3,path2)=>{const digest=hostedIdentity(value3,path2);return/^[\da-f]{64}$/u.test(digest)?digest:invalid4(path2)},releaseId:hostedIdentity});var parsePackageDependencyPins=(value3)=>{const pins=array2(readPin)(value3,"/dependencies");const identities=new Set;for(const pin of pins){if(Object.keys(pin).some((key)=>!["fqn","releaseId","releaseDigest"].includes(key))){throw new TypeError(`package dependency '${pin.fqn}' has unexpected fields`)}if(identities.has(pin.fqn)){throw new TypeError(`duplicate package dependency '${pin.fqn}'`)}identities.add(pin.fqn)}return[...pins].sort((left,right)=>compareUtf16CodeUnits(left.fqn,right.fqn))};var PackageManifestVersion="v4";var legacyFixedDestinationTargets=new Set(["fixed-email","channel-destination","telegram-chat","whatsapp-destination"]);var uuid2=/^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/iu;var placeholder=/\{(?<name>[^{}]*)\}/gu;var placeholders={remoteId:(remoteId)=>encodeURIComponent(remoteId),remoteIdUuidHex:(remoteId)=>uuid2.test(remoteId)?remoteId.replaceAll("-","").toLowerCase():null};var isPlaceholderName=(name)=>Object.hasOwn(placeholders,name);var resolver=(name)=>isPlaceholderName(name)?placeholders[name]:undefined;var knowledgeRemoteReferenceUrlTemplate=(value3,path2)=>{if(typeof value3!=="string"||!value3.startsWith("https://")||/[{}]/u.test(value3.replaceAll(placeholder,(match5,name)=>resolver(name)===undefined?match5:""))){throw new TypeError(`Invalid remote reference URL template at ${path2}`)}return value3};var HOSTS=["backend","dashboard","studio"];var FRONTEND_CATALOG_CONTRACT="frontend-catalog/v1";var FRONTEND_CATALOG_EXPORT_NAME="loadFrontendCatalog";var BACKEND_EXECUTION_LANES=["interactive","job"];var packageManifestJson=(definition)=>parseJsonObject(canonicalJson(definition.manifest));var canonicalPackageManifest=(definition)=>canonicalJson(packageManifestJson(definition));var toolBindingDeclaration=(entry)=>typeof entry==="string"?{tool:entry}:entry;var duplicateToolBinding=(tools)=>{const seen=new Set;for(const entry of tools){const binding=toolBindingDeclaration(entry);const key=JSON.stringify([binding.tool,binding.name??null]);if(seen.has(key)){return binding}seen.add(key)}return};var agentAudienceViolation=(audience)=>{const applications=audience.applications??[];if(audience.anonymous===true&&applications.length===0){return"anonymous visitors need an application in audience.applications"}const repeated=applications.find((fqn,index)=>applications.indexOf(fqn)!==index);return repeated===undefined?undefined:`audience application '${repeated}' is listed more than once`};var agentModelTiers=["complex","balanced","fast","super_fast"];var notificationDefinition=object({capabilities:object({extensionReadyProviders:strings,recipientTargets:strings,supportsActionLink:boolean2,supportsAttachments:boolean2,supportsFixedDestinations:optBoolean,supportsHtml:boolean2,supportsMarkdown:boolean2,supportsMentions:boolean2,supportsReadReceipts:boolean2,supportsRouteDestinations:boolean2,supportsThreads:boolean2}),credentialProfileKey:optString,family:literal("email","im","internal"),key:string3,provider:string3,setup:object({docsUrl:nullable(string3),healthCheck:object({available:boolean2,label:optString}),instructions:string3,liveTest:object({available:boolean2,label:optString}),secretFields:strings,setupForm:nullable(form)})});var studioPage=object({fullWidth:optBoolean,icon:optString,kind:literal("predefined"),label:string3,orderIndex:number3,predefinedPageRef:string3,routeSegment:string3,slug:string3});var studioSection=object({description:optString,icon:optString,label:string3,orderIndex:number3,pages:array2(studioPage),slug:string3});var studioApp=object({color:optString,description:optString,icon:optString,isDefaultTemplate:optBoolean,name:string3,sections:array2(studioSection),slug:string3});var datasetScalarType=literal("boolean","string","int64","float64","decimal","date","timestamp","duration","json");var datasetDefinition2=object({fields:array2(object({id:string3,name:string3,nullable:boolean2,semantic:optional3(string3),type:datasetScalarType})),measures:array2(object({id:string3,name:string3,resultType:datasetScalarType})),relationships:array2(object({cardinality:literal("one_to_one","one_to_many","many_to_one","many_to_many"),fromFieldId:string3,id:string3,toFieldId:string3})),version:literal(1)});var datasetBlueprint=object({...base,blueprintVersion:positiveSafeInteger,configuration:optional3(jsonObject),definition:datasetDefinition2,kind:literal("datasetBlueprint"),templateFqn:identity2});var semanticRole=literal("dimension","effective_time","entity_reference","event_time","identity","measure","status");var hint=object({role:semanticRole});var datasetTableTemplate=object({...base,admittedIngestionModes:array2(literal("append","replace","upsert")),compatibleProviderFqns:strings,configuration:schema2,identity:object({keyRoles:array2(semanticRole),uniqueness:literal("append_only","key","none")}),indexHints:array2(hint),kind:literal("datasetTableTemplate"),partitionHints:array2(hint),physicalCode:literal("evt","fact","gen","snap","stat","ts"),requirements:schema2,semanticRoles:array2(semanticRole)});var WorkflowEditorWidgets=["checkbox","code","condition_builder","credential_selector","key_value","list","mapping_builder","multi_select","number","resource_selector","schedule_builder","schema_builder","select","text","textarea"];var WorkflowTemplateKinds=["action_node","input_node","output_node","trigger_node"];var WorkflowTriggerLifecycleAdapterIds=Object.freeze({externalApplication:"builtin.core.workflows.lifecycle.external-application",mcpOperation:"builtin.core.workflows.lifecycle.mcp-operation"});var dynamicPort=object({configPath:string3,defaultIdPath:optString,idPath:string3,requiredPath:optString,schemaPath:optString});var fieldBinding=object({path:pathParts,target:literal("input_binding","parameter")});var nonNegativeInteger=(value3,path2)=>{const parsed=number3(value3,path2);return Number.isSafeInteger(parsed)&&parsed>=0?parsed:invalid4(path2)};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=(value3)=>object({inputContractPath:pathParts,modePath:optional3(pathParts),targetWorkflowFqnPath:optional3(pathParts),targetWorkflowIdPath:pathParts})(value3,"/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,resumable:optBoolean,sideEffect:literal("external","none","read","write"),testable:optBoolean})),implementationId:string3,inputSchema:optional3(schema2),instancePolicy:optional3(object({maxInstances:optNumber,minInstances:optNumber,onWorkflowCreate:optBoolean})),nodeCollectionFqn:optString,nodeCollectionVersion:optString,outputChannels:optional3(array2(object({adapterId:string3,cardinality:literal("many","one"),deliveryMode:literal("asynchronous","synchronous"),key:string3,required:boolean2,valueSchema:schema2}))),outputSchema:optional3(schema2),ports:optional3(array2(nodePort)),reusableDependency:optional3(parseWorkflowReusableDependency),triggerActivation:optional3(triggerActivation)});var fieldContract=object({availableForInput:optBoolean,availableForOutput:optBoolean,clearOnDependencyChange:optBoolean,optionDependencies:optional3(array2(object({path:pathParts,target:literal("parameter","part","value")}))),valueSchema:optional3(schema2)});var graphSchema=object({bindings:optional3(array2(object({extensions:jsonObject}))),fieldProjections:array2(object({source:pathParts,target:pathParts})),schema:schema2});var graphBoundary=object({templateFqn:string3,templateVersion:string3});var graph=object({edges:array2(object({extensions:optional3(jsonObject),id:string3,source:string3,target:string3})),inputBoundary:graphBoundary,inputContract:graphSchema,metadata:object({description:nullable(string3),tags:strings,templateSource:nullable(string3)}),nodes:array2(object({extensions:optional3(jsonObject),id:string3,templateFqn:string3,templateVersion:string3})),outputBoundary:graphBoundary,outputContract:graphSchema,triggers:array2(object({config:object({extensions:optional3(jsonObject)}),id:string3,inputBindings:record2(string3),invocation:object({mode:literal("attach","detach"),timeoutMs:nullable(number3)}),metadata:object({fieldDisplayValues:record2(string3)}),settings:object({enabled:boolean2}),templateFqn:string3,templateVersion:string3})),version:literal(1)});var uiLayout=object({edges:record2(object({extensions:optional3(jsonObject)})),nodes:record2(object({position:optional3(object({x:number3,y:number3}))})),version:literal(1),viewport:nullable(object({x:number3,y:number3,zoom:number3}))});var bindingSpan=object({end:number3,start:number3});var bindingSource=object({kind:literal("input","loop_index","loop_item","merge_output","node_output","port_arrival","run","scope","trigger"),mergeId:optional3(nullable(string3)),nodeId:optional3(nullable(string3)),portId:optional3(nullable(string3)),selection:optional3(nullable(object({ancestry:literal("nearest_dominating_ancestor"),iteration:literal("aggregate","previous_iteration","same_iteration")})))});var bindingExpression=(value3,path2)=>{const{kind}=object({kind:string3})(value3,path2);switch(kind){case"array":{return object({items:array2(bindingExpression),kind:literal("array")})(value3,path2)}case"call":{return object({args:array2(bindingExpression),kind:literal("call"),name:string3})(value3,path2)}case"interpolation":{return object({kind:literal("interpolation"),parts:array2(bindingExpression),span:optional3(nullable(bindingSpan))})(value3,path2)}case"literal":{return object({kind:literal("literal"),value:json})(value3,path2)}case"object":{return object({fields:record2(bindingExpression),kind:literal("object")})(value3,path2)}case"operator":{return object({args:array2(bindingExpression),kind:literal("operator"),op:string3})(value3,path2)}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))})(value3,path2)}default:{return invalid4(`${path2}/kind`)}}};var authoredValue=union2(object({mode:literal("fixed"),value:json}),object({compiled:optional3(nullable(bindingExpression)),languageVersion:literal(1),mode:literal("expression"),source:string3}));var nodeExecutionSettings=object({dryRun:optional3(object({mode:literal("allow","block_side_effects")})),idempotencyKey:optional3(nullable(bindingExpression)),onError:optional3(object({mode:literal("continue","fail_run")})),retry:optional3(object({backoffMs:optional3(nullable(number3)),maxAttempts:optional3(nullable(number3)),mode:literal("disabled","exponential","fixed")})),timeoutMs:optional3(nullable(number3))});var authoringTemplateRef=object({templateFqn:string3,templateVersion:string3});var authoringFieldProjection=object({fieldConfig:optional3(jsonObject),fieldFqn:string3,fieldVersion:string3,path:strings});var authoringInputContract=object({fieldProjections:optional3(array2(authoringFieldProjection)),jsonSchema:jsonObject});var authoringOutputContract=object({bindings:array2(object({key:string3,kind:literal("artifact","value"),value:bindingExpression})),fieldProjections:optional3(array2(authoringFieldProjection)),jsonSchema:jsonObject});var inputEndpoint=object({kind:literal("input_node"),portId:string3});var actionEndpoint=object({kind:literal("action_node"),nodeId:string3,portId:string3});var triggerEndpoint=object({kind:literal("trigger_node"),portId:string3,triggerId:string3});var outputEndpoint=object({kind:literal("output_node"),portId:string3});var authoringDefinition=object({edges:array2(object({id:string3,source:union2(union2(actionEndpoint,inputEndpoint),triggerEndpoint),target:union2(union2(actionEndpoint,inputEndpoint),outputEndpoint)})),inputBoundary:authoringTemplateRef,inputContract:authoringInputContract,metadata:jsonObject,nodes:array2(object({config:record2(authoredValue),extensions:optional3(jsonObject),id:string3,inputs:record2(authoredValue),metadata:jsonObject,settings:nodeExecutionSettings,templateFqn:string3,templateVersion:string3,uid:optString})),outputBoundary:authoringTemplateRef,outputContract:authoringOutputContract,triggers:array2(object({config:jsonObject,id:string3,inputBindings:record2(object({overridePolicy:literal("caller_may_override","locked"),value:authoredValue})),invocation:object({mode:literal("attach","await_result","detach"),timeoutMs:optional3(nullable(number3))}),metadata:jsonObject,settings:jsonObject,templateFqn:string3,templateVersion:string3})),version:literal(1)});var knowledgeSelection=optional3(object({exclude:optional3(array2(identity2)),include:optional3(array2(identity2))}));var toolBindings2=refine(array2(union2(identity2,object({approval:optional3(union2(literal("always","never"),object({rule:identity2}))),knowledge:optional3(object({domains:knowledgeSelection,entitySchemas:knowledgeSelection,relationSchemas:knowledgeSelection,unrestricted:optBoolean})),name:optional3(identity2),settings:optional3(jsonObject),tool:identity2}))),(tools)=>duplicateToolBinding(tools)===undefined?undefined:"duplicate tool binding");var agentAudience2=refine(object({anonymous:optBoolean,applications:optional3(array2(identity2)),members:optional3(literal("all","none","selected")),organizationGroups:optional3(literal("none","selected"))}),(audience)=>("organizationTeams"in audience)?"organizationTeams":agentAudienceViolation(audience));var withoutRetiredAgentFields=(agent)=>["invokingApplicationFqns","modelPreset"].find((field)=>(field in agent));var primitives={agent:refine(object({...base,activity:optional3(object({heartbeat:boolean2,schedule:boolean2})),audience:optional3(agentAudience2),behavioralBoundaries:strings,kind:literal("agent"),lifecycle,maxSteps:optional3(positiveSafeInteger),modelTier:optional3(literal(...agentModelTiers)),objectives:strings,operatingInstructions:string3,output:optional3(object({schema:schema2})),responsibility:string3,skills:array2(identity2),tools:toolBindings2}),withoutRetiredAgentFields),connection,datasetBlueprint,datasetConnectorInstance,datasetParser:object({...base,extensions:array2(identity2),format:datasetParserFormat,kind:literal("datasetParser"),mediaTypes:array2(identity2),parserVersion:datasetParserVersion}),datasetTableTemplate,documentsConnector:object({...base,connectionRefs,kind:literal("documentsConnector"),providerDisplayName:optional3(identity2),providerFamily:identity2}),domain:object({...base,kind:literal("domain"),lifecycle,localMutationPolicy:optional3(mutationPolicy),versioningEnabled:nullable(boolean2)}),domainTemplate:object({...base,catalogTags,domainFqn:string3,domainName:string3,entitySchemaFqns:strings,kind:literal("domainTemplate"),relationSchemaFqns:strings}),emailProvider:object({...base,connectionTemplateFqn:identity2,deploymentIdentity:optional3(literal("aws")),kind:literal("emailProvider"),senderKind:literal("address","mailbox")}),eventListener:object({...base,capabilities:array2(literal("internal","poll","webhook")),eventKind:string3,kind:literal("eventListener"),manualWebhookState:optional3(object({keyFamily:identity2,stateKey:identity2})),runtimeState:optional3(array2(object({keyFamily:string3,stateKey:string3}))),safeOccurrenceFields:optStrings,safeSelectorFields:optStrings,webhookHandshake:optional3(object({kind:literal("echo_query_parameter"),parameter:identity2}))}),externalAppGateway:readExternalAppGateway,externalApplication:refine(object({...base,allowedOrigins:strings,applicationType:literal("confidential","public"),audience:string3,kind:literal("externalApplication"),lifecycle,postLogoutRedirectUris:strings,primaryRedirectUri:optString,redirectUris:strings,scopes:strings,setupInstructions:optString}),externalApplicationViolation),externalDatasetProvider:object({...base,capabilities:datasetCapabilities,connectionTemplateFqns:strings,kind:literal("externalDatasetProvider"),sourceCapabilities:optional3(array2(object({capabilities:datasetCapabilities,datasetOpaqueIdPrefix:string3})))}),fieldTransformer:object({...base,kind:literal("fieldTransformer"),sourceFieldType:string3,targetFieldType:string3}),knowledgeConnector:object({...base,autoActivate:optBoolean,autoInstantiate:optBoolean,bindingScopes:optional3(bindingScopes),connectionRefs,contributions:optional3(array2(object({capabilityFqn:string3,connectionSlot:string3,connectionTemplateFqn:string3,controlFqn:optString,displayName:string3,fqn:identity2,metadata:optional3(jsonObject)}))),defaultOutboundStrategy:optional3(outboundStrategy),defaultUpdateMode:optional3(updateMode),discoveryDefaults:optional3(discoveryDefaults),entityIdentityMode:optional3(literal("adapter","item_metadata")),entitySchemaCapabilities:optional3(array2(entityCapability)),isSingleton:optBoolean,kind:literal("knowledgeConnector"),outboundCapability:optional3(literal("declared_and_enablable","none")),recommendedImportSchedules:predefinedSchedules,relationSchemaCapabilities:optional3(array2(relationCapability)),remoteReference:optional3(object({providerKey:identity2,urlTemplate:knowledgeRemoteReferenceUrlTemplate})),settings:optional3(form),supportedBindingModes:optional3(bindingModes)}),knowledgeConnectorInstance,knowledgeConnectorOauth:object({...base,connectorFqn:string3,kind:literal("knowledgeConnectorOauth")}),knowledgeEntityAdapter:object({...base,connectorFqn:string3,entitySchemaFqn:string3,kind:literal("knowledgeEntityAdapter"),normalizesFieldMapValues:optBoolean,normalizesImportedData:optBoolean}),knowledgeEntitySchema:object({...base,...knowledgeSchema,autocompleteConfiguration,defaultSyncDirection:optString,deletionMode:optString,displayDefaults:optional3(object({collections:optStrings,details:optStrings})),displayNameExpression:nullable(string3),embedEntities:optBoolean,embeddingConfig:nullable(jsonObject),extendsSchemaFqn:optString,kind:literal("knowledgeEntitySchema"),lifecycle,maxVersionsExpirationDays:optional3(nullable(number3)),persistFullFieldContributions:boolean2,relationFields:optional3(array2(object({cardinality:literal("many","one"),field:string3,id:string3,nullable:boolean2,reference:literal("external_id"),targetEntityId:string3,targetSchemaFqn:string3}))),syncable:optBoolean,usableAsDocumentScope:boolean2,versioned:optBoolean,versioningEnabled:nullable(boolean2)}),knowledgePolicy:object({...base,...policyFields,kind:literal("knowledgePolicy"),priority:optNumber}),knowledgeRelationAdapter:object({...base,connectorFqn:string3,kind:literal("knowledgeRelationAdapter"),relationSchemaFqn:string3}),knowledgeRelationSchema:object({...base,...knowledgeSchema,kind:literal("knowledgeRelationSchema"),lifecycle:optional3(lifecycle),sourceSchemaFqn:string3,targetSchemaFqn:string3}),managedDatasetProvider:object({...base,capabilities:datasetCapabilities,connectionTemplateFqns:strings,kind:literal("managedDatasetProvider")}),notificationChannel:object({...base,credential:optional3(form),definition:notificationDefinition,kind:literal("notificationChannel")}),organizationSso:object({...base,connectionTemplateFqn:string3,kind:literal("organizationSso"),providerId:string3,requiredCredentialFields:strings,secretCredentialFields:optStrings,setupGuide:optional3(array2(object({locale:string3,markdown:string3})))}),remoteToolCollection:refine(object({...base,category:optString,defaultVisibility:optional3(array2(object({effect:literal("allow","deny"),subject:literal("organization")}))),gatewayRef:identity2,kind:literal("remoteToolCollection"),operationReferences:strings}),remoteToolCollectionViolation),skill:object({...base,instructions:string3,kind:literal("skill"),lifecycle,tools:toolBindings2}),skillTemplate:object({...base,catalogTags,kind:literal("skillTemplate"),lifecycle:optional3(lifecycle),name:string3}),studioApp:object({...base,definition:studioApp,kind:literal("studioApp")}),studioComponent:object({...base,category:literal("layout","page","primitive","view","widget"),composition:optional3(object({extensions:optional3(jsonObject),slotSource:literal("props","static"),slots:array2(object({extensions:optional3(jsonObject),key:string3,label:optional3(localized)}))})),kind:literal("studioComponent"),propsSchema:schema2,sourceRef:string3}),tool:object({...base,allowMultipleSkillBindings:optBoolean,autoActivate:optBoolean,autoInstantiate:optBoolean,bindingScopes:optional3(bindingScopes),bindingSettings:optional3(form),capabilityType:optional3(literal("delegate","external","read","write")),category:optString,connectionRefs,effectKind:optional3(literal("mutation","read_only")),extraLoaders:optional3(array2(object({bindingName:string3,inheritBindingSettings:optBoolean,toolFqn:string3}))),healthCheck:optional3(object({capabilities:optStrings,description:string3})),input:schema2,isSingleton:optBoolean,kind:literal("tool"),output:schema2,settings:optional3(form),setupInstructions:optional3(object({links:strings,markdown:string3})),toolCollectionFqns:optStrings,toolGuidance:optional3(object({inputRequirementsSummary:optString,useWhen:optString})),usageScopes:optional3(array2(literal("automation","chat","skill")))}),toolCollection:object({...base,category:optString,defaultVisibility:optional3(array2(object({effect:literal("allow","deny"),subject:literal("organization")}))),kind:literal("toolCollection"),toolFqns:strings}),toolSettingsOptions:object({...base,catalogCollection:optString,catalogConnectionSlots:optStrings,connectionSlots:optStrings,dependencies:optStrings,fieldKey:string3,formTarget:optional3(literal("binding","settings")),includeUnavailableSelectedOptions:optBoolean,kind:literal("toolSettingsOptions"),toolFqn:string3}),workflow:object({...base,definition:authoringDefinition,kind:literal("workflow"),lifecycle,name:string3,slug:string3}),workflowField:object({...base,collectionFqn:string3,collectionVersion:string3,contract:fieldContract,kind:literal("workflowField"),presentation:optional3(object({placeholder:optString,widget:optString}))}),workflowFieldCollection:object({...base,contract:object({weight:number3}),kind:literal("workflowFieldCollection"),presentation:optional3(object({categoryPath:strings,label:localized}))}),workflowNode:object({...base,contract:nodeContract,kind:literal("workflowNode"),nodeKind:literal("action","input","output","trigger"),presentation:optional3(object({categoryPath:optStrings,tags:optStrings}))}),workflowNodeCollection:object({...base,contract:object({collection:optional3(object({parentFqn:string3,parentVersion:string3,weight:number3}))}),kind:literal("workflowNodeCollection"),presentation:optional3(object({categoryPath:strings}))}),workflowTemplate:object({...base,catalogTags,category:string3,definition:graph,kind:literal("workflowTemplate"),lifecycle,name:string3,requiredSkills:strings,requiredTools:strings,skillSlots:strings,slug:string3,uiLayout:nullable(uiLayout)})};var primitive=(v,p)=>{const{kind}=object({kind:string3})(v,p);for(const[name,read2]of Object.entries(primitives)){if(name===kind){return read2(v,p)}}return invalid4(`${p}/kind`)};var readHostedContribution=(value3,path2)=>{const shared=object({compatibility:optional3(record2(string3)),contract:optString,execution:optional3(literal("interactive","job")),exportName:hostedIdentity,fqn:hostedIdentity,host:literal("backend","dashboard","studio")})(value3,path2);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 ${path2}/execution: frontend contributions cannot declare an execution lane`)}if(shared.contract!==FRONTEND_CATALOG_CONTRACT){throw new TypeError(`Invalid package manifest at ${path2}/contract: frontend contribution contract must be '${FRONTEND_CATALOG_CONTRACT}'`)}if(shared.exportName!==FRONTEND_CATALOG_EXPORT_NAME){throw new TypeError(`Invalid package manifest at ${path2}/exportName: frontend contribution export must be '${FRONTEND_CATALOG_EXPORT_NAME}'`)}return{...shared.compatibility===undefined?undefined:{compatibility:shared.compatibility},contract:FRONTEND_CATALOG_CONTRACT,exportName:FRONTEND_CATALOG_EXPORT_NAME,fqn:shared.fqn,host:shared.host}};var readManifest=object({apiVersion:literal(PackageManifestVersion),author:optString,autoInstallable:optBoolean,bindingScopes:optional3(array2(literal("organization","tenant"))),category:optString,dependencies:optional3(parsePackageDependencyPins),description:optString,documentation:optString,fqn:identity2,homepage:optString,hostedContributions:optional3(array2(readHostedContribution)),icon:optString,installationWizard:optional3(object({size:optional3(literal("lg","md","xl")),steps:array2(object({description:optString,kind:literal("connector_instance","tool_instance"),optional:optBoolean,ref:string3,title:optString}))})),name:string3,primitives:array2(primitive),requiredEnvironmentVariables:optStrings,tags:optStrings,tenantMandatory:optBoolean,tenantStandard:optBoolean,version:string3});var parsePackageManifest=(value3)=>{assertDenseArrays(value3,"",new WeakSet);const manifest=readManifest(parseJsonObject(canonicalJson(value3)),"");return manifest.dependencies===undefined?manifest:{...manifest,dependencies:parsePackageDependencyPins(manifest.dependencies)}};var assertArchivePath=(path2)=>{if(path2===""||path2.startsWith("/")||path2.includes("\\")||path2.split("/").some((part)=>part===""||part==="."||part==="..")){throw new TypeError(`Extension Release archive has unsafe path '${path2}'`)}};var assertRuntimeAssetPath=(path2)=>{if(!/^artifacts\/(?:backend|dashboard|studio)\/.+/u.test(path2)){throw new TypeError(`Extension Release archive entry '${path2}' is not a runtime asset path`)}};var PackageManifestArchivePath="package-manifest.json";var assertReleaseArchiveEntryPath=(path2)=>{assertArchivePath(path2);if(path2!==PackageManifestArchivePath){assertRuntimeAssetPath(path2)}};var ExtensionReleaseManifestVersion="v2";var sha256Pattern=/^[\da-f]{64}$/u;var isExtensionHost=(value3)=>value3==="backend"||value3==="dashboard"||value3==="studio";var isRecord=(value3)=>value3!==null&&typeof value3==="object"&&!Array.isArray(value3);var assertExactKeys=(value3,allowedKeys,label)=>{const allowed=new Set(allowedKeys);const unexpected=Object.keys(value3).find((key)=>!allowed.has(key));if(unexpected!==undefined){throw new TypeError(`${label} has unexpected field '${unexpected}'`)}};var requireRecord=(value3,label)=>{if(!isRecord(value3)){throw new TypeError(`${label} must be an object`)}return value3};var requireString=(value3,label)=>{if(typeof value3!=="string"||value3.trim()===""){throw new TypeError(`${label} must be a non-empty string`)}return value3};var requireDigest=(value3,label)=>{const digest=requireString(value3,label);if(!sha256Pattern.test(digest)){throw new TypeError(`${label} must be a lowercase SHA-256 digest`)}return digest};var requireSize=(value3,label)=>{if(typeof value3!=="number"||!Number.isSafeInteger(value3)||value3<0){throw new TypeError(`${label} must be a non-negative safe integer`)}return value3};var requireHost=(value3,label)=>{if(typeof value3!=="string"||!isExtensionHost(value3)){throw new TypeError(`${label} must identify a supported Host`)}return value3};var assertUniqueSorted=(values,keyOf,label)=>{let previous;for(const value3 of values){const current=keyOf(value3);if(previous!==undefined&&current<=previous){throw new TypeError(`${label} must be unique and sorted`)}previous=current}};var parsePrivateSourceMap=(value3,label)=>{const sourceMap=requireRecord(value3,label);assertExactKeys(sourceMap,["digest","size"],label);return{digest:requireDigest(sourceMap.digest,`${label}.digest`),size:requireSize(sourceMap.size,`${label}.size`)}};var parseAsset=(value3,index)=>{const label=`Extension Release asset ${index}`;const asset=requireRecord(value3,label);assertExactKeys(asset,["digest","host","path","privateSourceMap","size"],label);const path2=requireString(asset.path,`${label}.path`);assertArchivePath(path2);assertRuntimeAssetPath(path2);const host=requireHost(asset.host,`${label}.host`);if(!path2.startsWith(`artifacts/${host}/`)){throw new TypeError(`Extension Release asset '${path2}' does not match Host '${host}'`)}return{digest:requireDigest(asset.digest,`${label}.digest`),host,path:path2,...asset.privateSourceMap===undefined?undefined:{privateSourceMap:parsePrivateSourceMap(asset.privateSourceMap,`${label}.privateSourceMap`)},size:requireSize(asset.size,`${label}.size`)}};var parseContribution=(value3,index)=>{const label=`Extension Release contribution ${index}`;const contribution=requireRecord(value3,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=(value3)=>{const manifest=requireRecord(value3,"Extension Release manifest");assertExactKeys(manifest,["apiVersion","assets","compatibility","contributions","package","packageManifest","releaseDigest"],"Extension Release manifest");if(manifest.apiVersion!==ExtensionReleaseManifestVersion){throw new TypeError("Extension Release manifest has unsupported apiVersion")}if(!Array.isArray(manifest.assets)){throw new TypeError("Extension Release manifest assets must be an array")}if(!Array.isArray(manifest.contributions)){throw new TypeError("Extension Release manifest contributions must be an array")}const compatibilityInput=requireRecord(manifest.compatibility,"Extension Release manifest compatibility");const compatibility=Object.fromEntries(Object.entries(compatibilityInput).map(([runtime,range])=>[requireString(runtime,"Extension Release compatibility runtime"),requireString(range,`Extension Release compatibility '${runtime}'`)]));const packageInput=requireRecord(manifest.package,"Extension Release manifest package");assertExactKeys(packageInput,["fqn","version"],"Extension Release package");const packageManifest=manifest.packageManifest===undefined?undefined:parsePackageManifest(manifest.packageManifest);if(packageManifest!==undefined&&(packageManifest.fqn!==packageInput.fqn||packageManifest.version!==packageInput.version)){throw new TypeError("Extension Release retained declarations do not match package identity")}const assets=manifest.assets.map(parseAsset);const contributions=manifest.contributions.map(parseContribution);assertUniqueSorted(assets,({path:path2})=>path2,"Extension Release manifest assets");assertUniqueSorted(contributions,({fqn,host})=>`${host}\x00${fqn}`,"Extension Release manifest contributions");const assetByPath=new Map(assets.map((asset)=>[asset.path,asset]));for(const contribution of contributions){const asset=assetByPath.get(contribution.assetPath);if(asset===undefined||asset.digest!==contribution.digest||asset.host!==contribution.host||asset.size!==contribution.size){throw new TypeError(`Extension Release contribution '${contribution.fqn}' does not match its declared runtime asset`)}}return{apiVersion:ExtensionReleaseManifestVersion,assets,compatibility,contributions,package:{fqn:requireString(packageInput.fqn,"Extension Release package.fqn"),version:requireString(packageInput.version,"Extension Release package.version")},...packageManifest===undefined?undefined:{packageManifest},releaseDigest:requireDigest(manifest.releaseDigest,"Extension Release manifest.releaseDigest")}};var canonicalExtensionReleaseManifest=(manifest)=>canonicalJson(manifest);var archiveBlockSize=512;var isZeroBlock=(bytes2)=>bytes2.every((value3)=>value3===0);var decodeCanonicalTextField=(bytes2,label)=>{const terminator=bytes2.indexOf(0);const contentEnd=terminator===-1?bytes2.byteLength:terminator;if(bytes2.subarray(0,contentEnd).some((byte)=>byte>127)||terminator!==-1&&!isZeroBlock(bytes2.subarray(terminator))){throw new TypeError(`Extension Release archive has non-canonical ${label}`)}return String.fromCodePoint(...bytes2.subarray(0,contentEnd))};var parseCanonicalOctalField=(bytes2,label)=>{const digits=bytes2.subarray(0,bytes2.byteLength-1);if(bytes2.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 declared2=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!==declared2){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 path2=prefix===""?name:`${prefix}/${name}`;assertReleaseArchiveEntryPath(path2);if(paths.has(path2)||compareUtf16CodeUnits(path2,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:path2});paths.add(path2);previousPath=path2;offset=paddedBodyEnd}throw new TypeError("Extension Release archive has no canonical trailer")};var validateExtensionReleaseArchiveMetadata=(entries,manifest)=>{const metadata3=entries.filter(({path:path2})=>path2===PackageManifestArchivePath);if(manifest.packageManifest===undefined){if(metadata3.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=metadata3[0]?.bytes;if(metadata3.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:path2})=>path2!==PackageManifestArchivePath)};var retiredPrimitiveKinds=new Map(Object.entries({dataset_blueprint:"datasetBlueprint",dataset_parser:"datasetParser",dataset_table_template:"datasetTableTemplate",documents_connector:"documentsConnector",domain_template:"domainTemplate",event_listener:"eventListener",external_application:"externalApplication",external_dataset_provider:"externalDatasetProvider",field_transformer:"fieldTransformer",knowledge_connector:"knowledgeConnector",knowledge_connector_oauth:"knowledgeConnectorOauth",knowledge_entity_adapter:"knowledgeEntityAdapter",knowledge_entity_schema:"knowledgeEntitySchema",knowledge_policy:"knowledgePolicy",knowledge_relation_adapter:"knowledgeRelationAdapter",knowledge_relation_schema:"knowledgeRelationSchema",managed_dataset_provider:"managedDatasetProvider","notification-channel":"notificationChannel",organization_sso:"organizationSso",skill_template:"skillTemplate",studio_app:"studioApp",studio_component:"studioComponent",tool_collection:"toolCollection",tool_settings_options:"toolSettingsOptions",workflow_field:"workflowField",workflow_field_collection:"workflowFieldCollection",workflow_node:"workflowNode",workflow_node_collection:"workflowNodeCollection",workflow_template:"workflowTemplate"}));var retiredGroupNames=new Map(Object.entries({directory_person_in_team:"directory_person_in_group",directory_team:"directory_group",directory_team_parent:"directory_group_parent",organization_team:"organization_group",organization_team_hierarchy:"organization_group_hierarchy",organization_team_membership:"organization_group_membership"}));var util;(function(util2){util2.assertEqual=(_)=>{};function assertIs(_arg){}util2.assertIs=assertIs;function assertNever(_x){throw new Error}util2.assertNever=assertNever;util2.arrayToEnum=(items)=>{const obj={};for(const item of items){obj[item]=item}return obj};util2.getValidEnumValues=(obj)=>{const validKeys=util2.objectKeys(obj).filter((k)=>typeof obj[obj[k]]!=="number");const filtered={};for(const k of validKeys){filtered[k]=obj[k]}return util2.objectValues(filtered)};util2.objectValues=(obj)=>{return util2.objectKeys(obj).map(function(e){return obj[e]})};util2.objectKeys=typeof Object.keys==="function"?(obj)=>Object.keys(obj):(object2)=>{const keys=[];for(const key in object2){if(Object.prototype.hasOwnProperty.call(object2,key)){keys.push(key)}}return keys};util2.find=(arr,checker)=>{for(const item of arr){if(checker(item))return item}return};util2.isInteger=typeof Number.isInteger==="function"?(val)=>Number.isInteger(val):(val)=>typeof val==="number"&&Number.isFinite(val)&&Math.floor(val)===val;function joinValues(array3,separator=" | "){return array3.map((val)=>typeof val==="string"?`'${val}'`:val).join(separator)}util2.joinValues=joinValues;util2.jsonStringifyReplacer=(_,value3)=>{if(typeof value3==="bigint"){return value3.toString()}return value3}})(util||(util={}));var objectUtil;(function(objectUtil2){objectUtil2.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(value3){if(!(value3 instanceof ZodError)){throw new Error(`Not a ZodError: ${value3}`)}}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:path2,errorMaps,issueData}=params;const fullPath=[...path2,...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 map8 of maps){errorMessage=map8(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,results2){const arrayValue=[];for(const s of results2){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 value3=await pair.value;syncPairs.push({key,value:value3})}return ParseStatus.mergeObjectSync(status,syncPairs)}static mergeObjectSync(status,pairs){const finalObject={};for(const pair of pairs){const{key,value:value3}=pair;if(key.status==="aborted")return INVALID;if(value3.status==="aborted")return INVALID;if(key.status==="dirty")status.dirty();if(value3.status==="dirty")status.dirty();if(key.value!=="__proto__"&&(typeof value3.value!=="undefined"||pair.alwaysSet)){finalObject[key.value]=value3.value}}return{status:status.value,value:finalObject}}}var INVALID=Object.freeze({status:"aborted"});var DIRTY=(value3)=>({status:"dirty",value:value3});var OK=(value3)=>({status:"valid",value:value3});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(errorUtil2){errorUtil2.errToObj=(message)=>typeof message==="string"?{message}:message||{};errorUtil2.toString=(message)=>typeof message==="string"?message:message?.message})(errorUtil||(errorUtil={}));class ParseInputLazyPath{constructor(parent,value3,path2,key){this._cachedPath=[];this.parent=parent;this.data=value3;this._path=path2;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,result3)=>{if(isValid(result3)){return{success:true,data:result3.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:errorMap2,invalid_type_error,required_error,description}=params;if(errorMap2&&(invalid_type_error||required_error)){throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`)}if(errorMap2)return{errorMap:errorMap2,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 result3=this._parse(input);if(isAsync(result3)){throw new Error("Synchronous parse encountered promise.")}return result3}_parseAsync(input){const result3=this._parse(input);return Promise.resolve(result3)}parse(data,params){const result3=this.safeParse(data,params);if(result3.success)return result3.data;throw result3.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 result3=this._parseSync({data,path:ctx.path,parent:ctx});return handleResult(ctx,result3)}"~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 result3=this._parseSync({data,path:[],parent:ctx});return isValid(result3)?{value:result3.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((result3)=>isValid(result3)?{value:result3.value}:{issues:ctx.common.issues})}async parseAsync(data,params){const result3=await this.safeParseAsync(data,params);if(result3.success)return result3.data;throw result3.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 result3=await(isAsync(maybeAsyncResult)?maybeAsyncResult:Promise.resolve(maybeAsyncResult));return handleResult(ctx,result3)}refine(check2,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 result3=check2(val);const setError=()=>ctx.addIssue({code:ZodIssueCode.custom,...getIssueProperties(val)});if(typeof Promise!=="undefined"&&result3 instanceof Promise){return result3.then((data)=>{if(!data){setError();return false}else{return true}})}if(!result3){setError();return false}else{return true}})}refinement(check2,refinementData){return this._refinement((val,ctx)=>{if(!check2(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(option2){return ZodUnion.create([this,option2],this._def)}and(incoming){return ZodIntersection.create(this,incoming,this._def)}transform(transform3){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:transform3}})}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(args2){let secondsRegexSource=`[0-5]\\d`;if(args2.precision){secondsRegexSource=`${secondsRegexSource}\\.\\d{${args2.precision}}`}else if(args2.precision==null){secondsRegexSource=`${secondsRegexSource}(\\.\\d+)?`}const secondsQuantifier=args2.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`}function timeRegex(args2){return new RegExp(`^${timeRegexSource(args2)}$`)}function datetimeRegex(args2){let regex=`${dateRegexSource}T${timeRegexSource(args2)}`;const opts=[];opts.push(args2.local?`Z?`:`Z`);if(args2.offset)opts.push(`([+-]\\d{2}:?\\d{2})`);regex=`${regex}(${opts.join("|")})`;return new RegExp(`^${regex}$`)}function isValidIP(ip,version2){if((version2==="v4"||!version2)&&ipv4Regex.test(ip)){return true}if((version2==="v6"||!version2)&&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,version2){if((version2==="v4"||!version2)&&ipv4CidrRegex.test(ip)){return true}if((version2==="v6"||!version2)&&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 ctx2=this._getOrReturnCtx(input);addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:ctx2.parsedType});return INVALID}const status=new ParseStatus;let ctx=undefined;for(const check2 of this._def.checks){if(check2.kind==="min"){if(input.data.length<check2.value){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check2.value,type:"string",inclusive:true,exact:false,message:check2.message});status.dirty()}}else if(check2.kind==="max"){if(input.data.length>check2.value){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check2.value,type:"string",inclusive:true,exact:false,message:check2.message});status.dirty()}}else if(check2.kind==="length"){const tooBig=input.data.length>check2.value;const tooSmall=input.data.length<check2.value;if(tooBig||tooSmall){ctx=this._getOrReturnCtx(input,ctx);if(tooBig){addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check2.value,type:"string",inclusive:true,exact:true,message:check2.message})}else if(tooSmall){addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check2.value,type:"string",inclusive:true,exact:true,message:check2.message})}status.dirty()}}else if(check2.kind==="email"){if(!emailRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"email",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else if(check2.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:check2.message});status.dirty()}}else if(check2.kind==="uuid"){if(!uuidRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"uuid",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else if(check2.kind==="nanoid"){if(!nanoidRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else if(check2.kind==="cuid"){if(!cuidRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"cuid",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else if(check2.kind==="cuid2"){if(!cuid2Regex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else if(check2.kind==="ulid"){if(!ulidRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"ulid",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else if(check2.kind==="url"){try{new URL(input.data)}catch{ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"url",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else if(check2.kind==="regex"){check2.regex.lastIndex=0;const testResult=check2.regex.test(input.data);if(!testResult){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"regex",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else if(check2.kind==="trim"){input.data=input.data.trim()}else if(check2.kind==="includes"){if(!input.data.includes(check2.value,check2.position)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{includes:check2.value,position:check2.position},message:check2.message});status.dirty()}}else if(check2.kind==="toLowerCase"){input.data=input.data.toLowerCase()}else if(check2.kind==="toUpperCase"){input.data=input.data.toUpperCase()}else if(check2.kind==="startsWith"){if(!input.data.startsWith(check2.value)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{startsWith:check2.value},message:check2.message});status.dirty()}}else if(check2.kind==="endsWith"){if(!input.data.endsWith(check2.value)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:{endsWith:check2.value},message:check2.message});status.dirty()}}else if(check2.kind==="datetime"){const regex=datetimeRegex(check2);if(!regex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"datetime",message:check2.message});status.dirty()}}else if(check2.kind==="date"){const regex=dateRegex;if(!regex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"date",message:check2.message});status.dirty()}}else if(check2.kind==="time"){const regex=timeRegex(check2);if(!regex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_string,validation:"time",message:check2.message});status.dirty()}}else if(check2.kind==="duration"){if(!durationRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"duration",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else if(check2.kind==="ip"){if(!isValidIP(input.data,check2.version)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"ip",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else if(check2.kind==="jwt"){if(!isValidJWT(input.data,check2.alg)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"jwt",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else if(check2.kind==="cidr"){if(!isValidCidr(input.data,check2.version)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"cidr",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else if(check2.kind==="base64"){if(!base64Regex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"base64",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else if(check2.kind==="base64url"){if(!base64urlRegex.test(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{validation:"base64url",code:ZodIssueCode.invalid_string,message:check2.message});status.dirty()}}else{util.assertNever(check2)}}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(check2){return new ZodString({...this._def,checks:[...this._def.checks,check2]})}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(value3,options){return this._addCheck({kind:"includes",value:value3,position:options?.position,...errorUtil.errToObj(options?.message)})}startsWith(value3,message){return this._addCheck({kind:"startsWith",value:value3,...errorUtil.errToObj(message)})}endsWith(value3,message){return this._addCheck({kind:"endsWith",value:value3,...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 ctx2=this._getOrReturnCtx(input);addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:ctx2.parsedType});return INVALID}let ctx=undefined;const status=new ParseStatus;for(const check2 of this._def.checks){if(check2.kind==="int"){if(!util.isInteger(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:check2.message});status.dirty()}}else if(check2.kind==="min"){const tooSmall=check2.inclusive?input.data<check2.value:input.data<=check2.value;if(tooSmall){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_small,minimum:check2.value,type:"number",inclusive:check2.inclusive,exact:false,message:check2.message});status.dirty()}}else if(check2.kind==="max"){const tooBig=check2.inclusive?input.data>check2.value:input.data>=check2.value;if(tooBig){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_big,maximum:check2.value,type:"number",inclusive:check2.inclusive,exact:false,message:check2.message});status.dirty()}}else if(check2.kind==="multipleOf"){if(floatSafeRemainder(input.data,check2.value)!==0){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.not_multiple_of,multipleOf:check2.value,message:check2.message});status.dirty()}}else if(check2.kind==="finite"){if(!Number.isFinite(input.data)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.not_finite,message:check2.message});status.dirty()}}else{util.assertNever(check2)}}return{status:status.value,value:input.data}}gte(value3,message){return this.setLimit("min",value3,true,errorUtil.toString(message))}gt(value3,message){return this.setLimit("min",value3,false,errorUtil.toString(message))}lte(value3,message){return this.setLimit("max",value3,true,errorUtil.toString(message))}lt(value3,message){return this.setLimit("max",value3,false,errorUtil.toString(message))}setLimit(kind,value3,inclusive,message){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind,value:value3,inclusive,message:errorUtil.toString(message)}]})}_addCheck(check2){return new ZodNumber({...this._def,checks:[...this._def.checks,check2]})}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(value3,message){return this._addCheck({kind:"multipleOf",value:value3,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 check2 of this._def.checks){if(check2.kind==="min"){const tooSmall=check2.inclusive?input.data<check2.value:input.data<=check2.value;if(tooSmall){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_small,type:"bigint",minimum:check2.value,inclusive:check2.inclusive,message:check2.message});status.dirty()}}else if(check2.kind==="max"){const tooBig=check2.inclusive?input.data>check2.value:input.data>=check2.value;if(tooBig){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_big,type:"bigint",maximum:check2.value,inclusive:check2.inclusive,message:check2.message});status.dirty()}}else if(check2.kind==="multipleOf"){if(input.data%check2.value!==BigInt(0)){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.not_multiple_of,multipleOf:check2.value,message:check2.message});status.dirty()}}else{util.assertNever(check2)}}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(value3,message){return this.setLimit("min",value3,true,errorUtil.toString(message))}gt(value3,message){return this.setLimit("min",value3,false,errorUtil.toString(message))}lte(value3,message){return this.setLimit("max",value3,true,errorUtil.toString(message))}lt(value3,message){return this.setLimit("max",value3,false,errorUtil.toString(message))}setLimit(kind,value3,inclusive,message){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind,value:value3,inclusive,message:errorUtil.toString(message)}]})}_addCheck(check2){return new ZodBigInt({...this._def,checks:[...this._def.checks,check2]})}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(value3,message){return this._addCheck({kind:"multipleOf",value:value3,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 ctx2=this._getOrReturnCtx(input);addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:ctx2.parsedType});return INVALID}if(Number.isNaN(input.data.getTime())){const ctx2=this._getOrReturnCtx(input);addIssueToContext(ctx2,{code:ZodIssueCode.invalid_date});return INVALID}const status=new ParseStatus;let ctx=undefined;for(const check2 of this._def.checks){if(check2.kind==="min"){if(input.data.getTime()<check2.value){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_small,message:check2.message,inclusive:true,exact:false,minimum:check2.value,type:"date"});status.dirty()}}else if(check2.kind==="max"){if(input.data.getTime()>check2.value){ctx=this._getOrReturnCtx(input,ctx);addIssueToContext(ctx,{code:ZodIssueCode.too_big,message:check2.message,inclusive:true,exact:false,maximum:check2.value,type:"date"});status.dirty()}}else{util.assertNever(check2)}}return{status:status.value,value:new Date(input.data.getTime())}}_addCheck(check2){return new ZodDate({...this._def,checks:[...this._def.checks,check2]})}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((result4)=>{return ParseStatus.mergeArray(status,result4)})}const result3=[...ctx.data].map((item,i)=>{return def.type._parseSync(new ParseInputLazyPath(ctx,item,ctx.path,i))});return ParseStatus.mergeArray(status,result3)}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=(schema3,params)=>{return new ZodArray({type:schema3,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(params)})};function deepPartialify(schema3){if(schema3 instanceof ZodObject){const newShape={};for(const key in schema3.shape){const fieldSchema=schema3.shape[key];newShape[key]=ZodOptional.create(deepPartialify(fieldSchema))}return new ZodObject({...schema3._def,shape:()=>newShape})}else if(schema3 instanceof ZodArray){return new ZodArray({...schema3._def,type:deepPartialify(schema3.element)})}else if(schema3 instanceof ZodOptional){return ZodOptional.create(deepPartialify(schema3.unwrap()))}else if(schema3 instanceof ZodNullable){return ZodNullable.create(deepPartialify(schema3.unwrap()))}else if(schema3 instanceof ZodTuple){return ZodTuple.create(schema3.items.map((item)=>deepPartialify(item)))}else{return schema3}}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 ctx2=this._getOrReturnCtx(input);addIssueToContext(ctx2,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:ctx2.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 value3=ctx.data[key];pairs.push({key:{status:"valid",value:key},value:keyValidator._parse(new ParseInputLazyPath(ctx,value3,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 value3=ctx.data[key];pairs.push({key:{status:"valid",value:key},value:catchall._parse(new ParseInputLazyPath(ctx,value3,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 value3=await pair.value;syncPairs.push({key,value:value3,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,schema3){return this.augment({[key]:schema3})}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(results2){for(const result3 of results2){if(result3.result.status==="valid"){return result3.result}}for(const result3 of results2){if(result3.result.status==="dirty"){ctx.common.issues.push(...result3.ctx.common.issues);return result3.result}}const unionErrors=results2.map((result3)=>new ZodError(result3.ctx.common.issues));addIssueToContext(ctx,{code:ZodIssueCode.invalid_union,unionErrors});return INVALID}if(ctx.common.async){return Promise.all(options.map(async(option2)=>{const childCtx={...ctx,common:{...ctx.common,issues:[]},parent:null};return{result:await option2._parseAsync({data:ctx.data,path:ctx.path,parent:childCtx}),ctx:childCtx}})).then(handleResults)}else{let dirty=undefined;const issues=[];for(const option2 of options){const childCtx={...ctx,common:{...ctx.common,issues:[]},parent:null};const result3=option2._parseSync({data:ctx.data,path:ctx.path,parent:childCtx});if(result3.status==="valid"){return result3}else if(result3.status==="dirty"&&!dirty){dirty={result:result3,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((issues2)=>new ZodError(issues2));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 option2=this.optionsMap.get(discriminatorValue);if(!option2){addIssueToContext(ctx,{code:ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[discriminator]});return INVALID}if(ctx.common.async){return option2._parseAsync({data:ctx.data,path:ctx.path,parent:ctx})}else{return option2._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 value3 of discriminatorValues){if(optionsMap.has(value3)){throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value3)}`)}optionsMap.set(value3,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 schema3=this._def.items[itemIndex]||this._def.rest;if(!schema3)return null;return schema3._parse(new ParseInputLazyPath(ctx,item,ctx.path,itemIndex))}).filter((x)=>!!x);if(ctx.common.async){return Promise.all(items).then((results2)=>{return ParseStatus.mergeArray(status,results2)})}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,value3],index)=>{return{key:keyType._parse(new ParseInputLazyPath(ctx,key,ctx.path,[index,"key"])),value:valueType._parse(new ParseInputLazyPath(ctx,value3,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 value3=await pair.value;if(key.status==="aborted"||value3.status==="aborted"){return INVALID}if(key.status==="dirty"||value3.status==="dirty"){status.dirty()}finalMap.set(key.value,value3.value)}return{status:status.value,value:finalMap}})}else{const finalMap=new Map;for(const pair of pairs){const key=pair.key;const value3=pair.value;if(key.status==="aborted"||value3.status==="aborted"){return INVALID}if(key.status==="dirty"||value3.status==="dirty"){status.dirty()}finalMap.set(key.value,value3.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(elements2){const parsedSet=new Set;for(const element of elements2){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((elements2)=>finalizeSet(elements2))}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(args2,error){return makeIssue({data:args2,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 fn3=ctx.data;if(this._def.returns instanceof ZodPromise){const me=this;return OK(async function(...args2){const error=new ZodError([]);const parsedArgs=await me._def.args.parseAsync(args2,params).catch((e)=>{error.addIssue(makeArgsIssue(args2,e));throw error});const result3=await Reflect.apply(fn3,this,parsedArgs);const parsedReturns=await me._def.returns._def.type.parseAsync(result3,params).catch((e)=>{error.addIssue(makeReturnsIssue(result3,e));throw error});return parsedReturns})}else{const me=this;return OK(function(...args2){const parsedArgs=me._def.args.safeParse(args2,params);if(!parsedArgs.success){throw new ZodError([makeArgsIssue(args2,parsedArgs.error)])}const result3=Reflect.apply(fn3,this,parsedArgs.data);const parsedReturns=me._def.returns.safeParse(result3,params);if(!parsedReturns.success){throw new ZodError([makeReturnsIssue(result3,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(args2,returns,params){return new ZodFunction({args:args2?args2: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=(value3,params)=>{return new ZodLiteral({value:value3,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=(schema3,params)=>{return new ZodPromise({type:schema3,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 effect2=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(effect2.type==="preprocess"){const processed=effect2.transform(ctx.data,checkCtx);if(ctx.common.async){return Promise.resolve(processed).then(async(processed2)=>{if(status.value==="aborted")return INVALID;const result3=await this._def.schema._parseAsync({data:processed2,path:ctx.path,parent:ctx});if(result3.status==="aborted")return INVALID;if(result3.status==="dirty")return DIRTY(result3.value);if(status.value==="dirty")return DIRTY(result3.value);return result3})}else{if(status.value==="aborted")return INVALID;const result3=this._def.schema._parseSync({data:processed,path:ctx.path,parent:ctx});if(result3.status==="aborted")return INVALID;if(result3.status==="dirty")return DIRTY(result3.value);if(status.value==="dirty")return DIRTY(result3.value);return result3}}if(effect2.type==="refinement"){const executeRefinement=(acc)=>{const result3=effect2.refinement(acc,checkCtx);if(ctx.common.async){return Promise.resolve(result3)}if(result3 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(effect2.type==="transform"){if(ctx.common.async===false){const base2=this._def.schema._parseSync({data:ctx.data,path:ctx.path,parent:ctx});if(!isValid(base2))return INVALID;const result3=effect2.transform(base2.value,checkCtx);if(result3 instanceof Promise){throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`)}return{status:status.value,value:result3}}else{return this._def.schema._parseAsync({data:ctx.data,path:ctx.path,parent:ctx}).then((base2)=>{if(!isValid(base2))return INVALID;return Promise.resolve(effect2.transform(base2.value,checkCtx)).then((result3)=>({status:status.value,value:result3}))})}}util.assertNever(effect2)}}ZodEffects.create=(schema3,effect2,params)=>{return new ZodEffects({schema:schema3,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:effect2,...processCreateParams(params)})};ZodEffects.createWithPreprocess=(preprocess,schema3,params)=>{return new ZodEffects({schema:schema3,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 result3=this._def.innerType._parse({data:newCtx.data,path:newCtx.path,parent:{...newCtx}});if(isAsync(result3)){return result3.then((result4)=>{return{status:"valid",value:result4.status==="valid"?result4.value:this._def.catchValue({get error(){return new ZodError(newCtx.common.issues)},input:newCtx.data})}})}else{return{status:"valid",value:result3.status==="valid"?result3.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 result3=this._def.innerType._parse(input);const freeze=(data)=>{if(isValid(data)){data.value=Object.freeze(data.value)}return data};return isAsync(result3)?result3.then((data)=>freeze(data)):freeze(result3)}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(ZodFirstPartyTypeKind2){ZodFirstPartyTypeKind2["ZodString"]="ZodString";ZodFirstPartyTypeKind2["ZodNumber"]="ZodNumber";ZodFirstPartyTypeKind2["ZodNaN"]="ZodNaN";ZodFirstPartyTypeKind2["ZodBigInt"]="ZodBigInt";ZodFirstPartyTypeKind2["ZodBoolean"]="ZodBoolean";ZodFirstPartyTypeKind2["ZodDate"]="ZodDate";ZodFirstPartyTypeKind2["ZodSymbol"]="ZodSymbol";ZodFirstPartyTypeKind2["ZodUndefined"]="ZodUndefined";ZodFirstPartyTypeKind2["ZodNull"]="ZodNull";ZodFirstPartyTypeKind2["ZodAny"]="ZodAny";ZodFirstPartyTypeKind2["ZodUnknown"]="ZodUnknown";ZodFirstPartyTypeKind2["ZodNever"]="ZodNever";ZodFirstPartyTypeKind2["ZodVoid"]="ZodVoid";ZodFirstPartyTypeKind2["ZodArray"]="ZodArray";ZodFirstPartyTypeKind2["ZodObject"]="ZodObject";ZodFirstPartyTypeKind2["ZodUnion"]="ZodUnion";ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"]="ZodDiscriminatedUnion";ZodFirstPartyTypeKind2["ZodIntersection"]="ZodIntersection";ZodFirstPartyTypeKind2["ZodTuple"]="ZodTuple";ZodFirstPartyTypeKind2["ZodRecord"]="ZodRecord";ZodFirstPartyTypeKind2["ZodMap"]="ZodMap";ZodFirstPartyTypeKind2["ZodSet"]="ZodSet";ZodFirstPartyTypeKind2["ZodFunction"]="ZodFunction";ZodFirstPartyTypeKind2["ZodLazy"]="ZodLazy";ZodFirstPartyTypeKind2["ZodLiteral"]="ZodLiteral";ZodFirstPartyTypeKind2["ZodEnum"]="ZodEnum";ZodFirstPartyTypeKind2["ZodEffects"]="ZodEffects";ZodFirstPartyTypeKind2["ZodNativeEnum"]="ZodNativeEnum";ZodFirstPartyTypeKind2["ZodOptional"]="ZodOptional";ZodFirstPartyTypeKind2["ZodNullable"]="ZodNullable";ZodFirstPartyTypeKind2["ZodDefault"]="ZodDefault";ZodFirstPartyTypeKind2["ZodCatch"]="ZodCatch";ZodFirstPartyTypeKind2["ZodPromise"]="ZodPromise";ZodFirstPartyTypeKind2["ZodBranded"]="ZodBranded";ZodFirstPartyTypeKind2["ZodPipeline"]="ZodPipeline";ZodFirstPartyTypeKind2["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((value3)=>value3.trim().length>0,"Expected a non-blank selection ID");var packageOperationRecoverySchema=enumType(["explicit_continuation","retry_safe"]);var packageOperationCommandSchema=unionType([objectType({kind:literalType("install"),packageFqn:nonBlankString,recovery:packageOperationRecoverySchema}),objectType({kind:literalType("promote"),packageId:nonBlankString,recovery:packageOperationRecoverySchema,releaseId:nonBlankString}),objectType({kind:literalType("publish"),packageFqn:nonBlankString,recovery:packageOperationRecoverySchema}),objectType({installationId:nonBlankString,kind:literalType("rollback"),packageId:nonBlankString,recovery:packageOperationRecoverySchema,releaseId:nonBlankString}),objectType({installationId:nonBlankString,kind:literalType("update"),packageId:nonBlankString,recovery:packageOperationRecoverySchema,releaseId:nonBlankString}),objectType({kind:literalType("update"),mode:literalType("sync"),packageFqn:nonBlankString,recovery:packageOperationRecoverySchema})]);var packageOperationStatusSchema=enumType(["awaiting_continuation","failed","pending","running","succeeded"]);var releaseDigestSchema=stringType().regex(/^[\da-f]{64}$/u);var releaseSelectionSchema=objectType({generation:stringType().regex(/^(?:0|[1-9][0-9]*)$/u),releaseDigest:releaseDigestSchema,releaseId:selectionIdSchema});var graphMemberSchema=releaseSelectionSchema.extend({installationId:selectionIdSchema,packageFqn:selectionIdSchema,packageId:selectionIdSchema});var pinSchema=objectType({fqn:nonBlankString,releaseDigest:releaseDigestSchema,releaseId:nonBlankString});var dependencyPathsSchema=arrayType(arrayType(stringType()));var blockerMessageSchema=stringType();var knownBlockerSchema=unionType([objectType({_tag:literalType("manual_prerequisite"),message:blockerMessageSchema,observed:pinSchema.nullable(),path:arrayType(pinSchema),paths:arrayType(arrayType(pinSchema)),required:pinSchema}),objectType({_tag:literalType("authority_denied"),boundary:enumType(["principal","publication","promotion"]),message:blockerMessageSchema,paths:dependencyPathsSchema}),objectType({_tag:enumType(["dirty_readonly","definition_rejected"]),definitions:arrayType(objectType({fqn:nonBlankString,kind:enumType(["workflow","agent","skill"])})),message:blockerMessageSchema,paths:dependencyPathsSchema}),objectType({_tag:enumType(["release_unavailable","release_identity_mismatch","conflicting_pins","cycle","installation_identity_mismatch","retained_requirement_conflict","package_identity_conflict"]),message:blockerMessageSchema,paths:dependencyPathsSchema})]);var preflightDiagnosticSchema=unionType([knownBlockerSchema,objectType({_tag:nonBlankString,message:blockerMessageSchema.optional(),paths:dependencyPathsSchema.optional()}).transform(({_tag,message,paths})=>({_tag:"unknown",message:message??`Blocked by ${_tag}.`,paths:paths??[],tag:_tag}))]);var appliedGraphFields={applicationId:nonBlankString,members:arrayType(graphMemberSchema)};var applicationStageSchema=unionType([objectType({state:enumType(["not_required","pending"])}),objectType({blocker:preflightDiagnosticSchema.optional(),state:literalType("not_applied")}).transform(({blocker,state})=>blocker===undefined?{state}:{blocker,state}),objectType({...appliedGraphFields,state:literalType("applied")})]);var hostOutcomeFieldsSchema=objectType({diagnosticId:nonBlankString.optional(),member:graphMemberSchema,observed:objectType({desired:releaseSelectionSchema.nullable(),serving:releaseSelectionSchema.nullable()}),result:enumType(["failed","pending","serving","stale"])});var hostOutcome=({diagnosticId,...outcome})=>diagnosticId===undefined?outcome:{...outcome,diagnosticId};var cleanupCandidateSchema=objectType({installationId:selectionIdSchema,packageFqn:selectionIdSchema,packageId:selectionIdSchema,releaseDigest:releaseDigestSchema,releaseId:selectionIdSchema});var cleanupProtectionSchema=unionType([objectType({dependent:pinSchema,kind:literalType("required_by"),protection:enumType(["desired","serving"])}),objectType({dependent:pinSchema,kind:literalType("unknown_requirement")}),objectType({kind:enumType(["built_in","explicit_intent","selection_changed","unknown_intent"])}),objectType({kind:literalType("workflow_use"),state:enumType(["published","draft_head","working_copy"]),template:objectType({fqn:nonBlankString,kind:nonBlankString,version:nonBlankString}),workflowId:nonBlankString}),objectType({bindingKind:enumType(["tool_instance","connection","knowledge_connector"]),id:nonBlankString,kind:literalType("live_binding")})]);var cleanupStageSchema=objectType({candidates:arrayType(cleanupCandidateSchema.extend({protections:arrayType(cleanupProtectionSchema).optional(),result:enumType(["pending","removed","retained"])}).transform(({protections,...candidate})=>protections===undefined?candidate:{...candidate,protections})),state:enumType(["pending","completed","failed"])});var failureSchema=objectType({message:nonBlankString,reason:enumType(["credential_not_found","credential_permission_denied","credential_scope_denied","credential_verification_unavailable","execution_failed","invalid_artifact","release_not_found","release_package_mismatch"])});var eventOutcomeSchema=unionType([objectType({...appliedGraphFields,kind:literalType("graph_applied")}),objectType({blocker:preflightDiagnosticSchema,kind:literalType("graph_not_applied")}),hostOutcomeFieldsSchema.extend({kind:literalType("host")}).transform(({kind,...outcome})=>({...hostOutcome(outcome),kind})),objectType({kind:literalType("retry_requested")}),failureSchema.extend({kind:literalType("command_failed")}),objectType({candidate:cleanupCandidateSchema,kind:literalType("cleanup_removed")}),objectType({candidate:cleanupCandidateSchema,kind:literalType("cleanup_retained"),protections:arrayType(cleanupProtectionSchema)})]);var packageOperationSnapshotSchema=objectType({application:applicationStageSchema,cleanup:cleanupStageSchema.optional(),command:packageOperationCommandSchema,continuationOf:nonBlankString.optional(),createdAt:stringType().datetime({offset:true}),failure:failureSchema.optional(),hosts:arrayType(hostOutcomeFieldsSchema.transform(hostOutcome)),id:nonBlankString,idempotencyKey:nonBlankString,lastEventSequence:numberType().int().nonnegative(),nextAction:enumType(["continue","none","retry","wait"]),organizationId:nonBlankString,packageFqn:nonBlankString,principal:unionType([objectType({kind:literalType("administrator"),userId:nonBlankString}),objectType({credentialId:nonBlankString,kind:literalType("publisher")}),objectType({actor:literalType("bootstrap"),kind:literalType("system")})]),publication:objectType({packageId:selectionIdSchema,releaseDigest:releaseDigestSchema,releaseId:selectionIdSchema}).optional(),recoveryReason:literalType("selection_outcome_unavailable").optional(),selection:objectType({generation:numberType().int().positive(),installationId:selectionIdSchema,releaseId:selectionIdSchema}).optional(),status:packageOperationStatusSchema,updatedAt:stringType().datetime({offset:true})});var packageOperationEventSchema=objectType({createdAt:stringType().datetime({offset:true}),operationId:nonBlankString,outcome:eventOutcomeSchema.optional(),sequence:numberType().int().nonnegative(),status:packageOperationStatusSchema});var decodePackageOperationEvent=(data)=>{const{outcome,...event}=packageOperationEventSchema.parse(JSON.parse(data));return outcome===undefined?event:{...event,outcome}};var decodePackageOperationSnapshot=(snapshot)=>{const decoded=packageOperationSnapshotSchema.parse(snapshot);const{cleanup,continuationOf,failure,publication,recoveryReason,selection,...required}=decoded;const snapshotDto=required;if(cleanup!==undefined){snapshotDto.cleanup=cleanup}if(continuationOf!==undefined){snapshotDto.continuationOf=continuationOf}if(failure!==undefined){snapshotDto.failure=failure}if(recoveryReason!==undefined){snapshotDto.recoveryReason=recoveryReason}if(publication!==undefined){snapshotDto.publication=publication}if(selection!==undefined){snapshotDto.selection=selection}return snapshotDto};import{createHash as createHash3}from"crypto";import{readFile as readFile3}from"fs/promises";var nonempty=String4.check(isMinLength(1),makeFilter2((value3)=>value3.trim().length>0));var uuid3=String4.check(isPattern2(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu));var connectorSetup=Struct({adoptions:optionalKey2(Record(nonempty,Struct({instanceId:uuid3}))),connections:optionalKey2(Record(nonempty,Union2([Struct({connectionId:uuid3}),Struct({newConnection:Struct({fields:JsonObject,name:nonempty})})])))});var parseConnectorSetup=(text)=>{try{return decodeUnknownSync(connectorSetup,{onExcessProperty:"error"})(JSON.parse(text))}catch{throw new TypeError("Invalid connector setup file; expected connections/adoptions with UUID references or newConnection name/fields")}};var readConnectorSetup=async(path2,readBytes=readFile3)=>{let bytes2;try{bytes2=await readBytes(path2)}catch{throw new TypeError("Could not read connector setup file")}return parseConnectorSetup(new TextDecoder().decode(bytes2))};var installPackage=async(input)=>{const request={client:input.client,headers:{"idempotency-key":input.idempotencyKey,"x-organization-id":input.organizationId},path:{fqn:input.packageFqn},throwOnError:true};if(input.body!==undefined){request.body=input.body}if(input.signal!==undefined){request.signal=input.signal}const response=await extensionPackagesInstall(request);return response.data};var updatePackage=async(input)=>{const request={body:input.body,client:input.client,headers:{"idempotency-key":input.idempotencyKey,"x-organization-id":input.organizationId},throwOnError:true};if(input.signal!==undefined){request.signal=input.signal}const response=await packageReleasesUpdateInstallation(request);return response.data};var publishPackage=async(input)=>{const request={body:input.body,client:input.client,headers:{"idempotency-key":input.idempotencyKey},throwOnError:true};if(input.signal!==undefined){request.signal=input.signal}const response=await packageReleasesPublish(request);return response.data};var promotePackage=async(input)=>{const request={body:input.body,client:input.client,headers:{"idempotency-key":input.idempotencyKey},throwOnError:true};if(input.signal!==undefined){request.signal=input.signal}const response=await packageReleasesPromote(request);return response.data};import{createHash}from"crypto";import{build as viteBuild,esmExternalRequirePlugin}from"vite";import{fileURLToPath as fileURLToPath2}from"url";var nodePath=runSync2(provide3(Path2,exports_NodePath.layer));var literalLazyImport=(declarationSpecifier,identity3)=>{const loaderSource=Function.prototype.toString.call(identity3.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(`${identity3.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(`${identity3.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(`${identity3.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,identity3)=>resolveLazyImportModule(declarationSpecifier,{load:identity3.load,subject:`Hosted Contribution '${identity3.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,exports_NodePath.layer));var isRecord2=(value3)=>value3!==null&&typeof value3==="object";var isPackageDefinition=(value3)=>{if(!isRecord2(value3)||!isRecord2(value3.manifest)){return false}return value3.manifest.apiVersion==="v4"&&typeof value3.manifest.fqn==="string"&&Array.isArray(value3.components)&&(value3.hostedContributions===undefined||Array.isArray(value3.hostedContributions))&&Array.isArray(value3.schemaSidecars)};var normalizePackageDefinition=(definition,packageLoader)=>({...definition,hostedContributions:definition.hostedContributions??[],...packageLoader===undefined?undefined:{packageLoader}});var isPackageLoader=(value3)=>typeof value3==="function";var packageLoaderMap=(loaders,definitions)=>{if(loaders===undefined){return}const fqns=definitions.map(({manifest})=>manifest.fqn);if(!isRecord2(loaders)){throw new TypeError("Declaration packageLoaders must be an object")}const entries=Object.entries(loaders);if(entries.length!==fqns.length||!fqns.every((fqn)=>Object.hasOwn(loaders,fqn))||!entries.every(([,loader])=>isPackageLoader(loader))){throw new TypeError(`Declaration packageLoaders must map exactly the declared packages (${fqns.join(", ")}) to lazy import functions`)}return new Map(entries.flatMap(([fqn,loader])=>isPackageLoader(loader)?[[fqn,loader]]:[]))};var declarationSpecifier=(specifier)=>{if(specifier.startsWith("data:")||specifier.startsWith("file:")||specifier.startsWith("http:")||specifier.startsWith("https:")||!specifier.startsWith(".")&&!specifier.startsWith("/")){return specifier}return pathToFileURL2(path2.resolve(process.cwd(),specifier)).href};var normalizeModuleDeclarations=(loaded)=>{const exported=loaded.packageDefinitions??loaded.packageDefinition??loaded.default;const candidate=isRecord2(exported)&&"default"in exported?exported.default:exported;const values=Array.isArray(candidate)?candidate:[candidate];if(values.length===0||!values.every(isPackageDefinition)){throw new TypeError(`Declaration module must export a PackageDefinition or PackageDefinition array; received ${JSON.stringify(candidate)}`)}const loaders=packageLoaderMap(loaded.packageLoaders,values);return values.map((definition)=>normalizePackageDefinition(definition,loaders?.get(definition.manifest.fqn)))};var loadPackageDeclarations=flow((specifier)=>tryPromise2(()=>import(declarationSpecifier(specifier))).pipe(map4((loaded)=>isRecord2(loaded)?loaded:undefined),flatMap3((loaded)=>loaded===undefined?fail6(new PackageDeclarationError({message:"Declaration module did not expose module exports"})):succeed6(normalizeModuleDeclarations(loaded)))),runPromise2);var loadFreshPackageDeclarations=flow((specifier)=>{const resolved=declarationSpecifier(specifier);if(!resolved.startsWith("file:")){return promise2(()=>loadPackageDeclarations(resolved))}const sourcePath=fileURLToPath3(resolved);const root=path2.dirname(sourcePath);return acquireUseRelease2(tryPromise2(()=>createServer({appType:"custom",configFile:false,logLevel:"silent",resolve:workspaceSourceResolve(process.execArgv),root,server:{middlewareMode:true},ssr:workspaceSourceSsrResolve(process.execArgv)})),(server)=>tryPromise2(()=>server.ssrLoadModule(`/${encodeURIComponent(path2.basename(sourcePath))}`)).pipe(flatMap3((loaded)=>isRecord2(loaded)?succeed6(normalizeModuleDeclarations(loaded)):fail6(new PackageDeclarationError({message:"Declaration module did not expose module exports"})))),(server)=>promise2(()=>server.close()))},runPromise2);var compareCanonicalText=(left,right)=>{if(left===right){return 0}return left<right?-1:1};var blockSize=512;var isAscii=(value3)=>{for(const character of value3){if((character.codePointAt(0)??128)>127){return false}}return true};var writeAscii=(target,offset,length,value3)=>{if(value3.length>length||!isAscii(value3)){throw new TypeError(`Value does not fit deterministic ustar field: ${value3}`)}for(let index=0;index<value3.length;index+=1){target[offset+index]=value3.codePointAt(index)??0}};var writeOctal=(target,offset,length,value3)=>{const source=value3.toString(8).padStart(length-1,"0");if(source.length>=length){throw new TypeError(`Value does not fit deterministic ustar number: ${value3}`)}writeAscii(target,offset,length-1,source)};var splitArchivePath=(path3)=>{if(path3===""||path3.startsWith("/")||path3.includes("\\")||path3.split("/").some((part)=>part===""||part==="."||part==="..")){throw new TypeError(`Unsafe Extension Release archive path '${path3}'`)}if(path3.length<=100){return{name:path3,prefix:""}}const separator=path3.lastIndexOf("/");const prefix=path3.slice(0,separator);const name=path3.slice(separator+1);if(separator===-1||name.length>100||prefix.length>155){throw new TypeError(`Extension Release archive path is too long: ${path3}`)}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,value3)=>total+value3,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:path3})=>path3)).size!==entries.length){throw new TypeError("Extension Release archive paths must be unique")}const size=entries.reduce((total,entry)=>total+blockSize+Math.ceil(entry.bytes.byteLength/blockSize)*blockSize,0)+blockSize*2;const archive=new Uint8Array(size);let offset=0;for(const entry of entries){archive.set(headerFor(entry),offset);offset+=blockSize;archive.set(entry.bytes,offset);offset+=Math.ceil(entry.bytes.byteLength/blockSize)*blockSize}return archive};var backendHostProvidedModules=["@collective-intelligence/extensions-sdk","@collective-intelligence/extensions-sdk-backend"];var frontendModules=["@collective-intelligence/extensions-sdk","@collective-intelligence/extensions-sdk-frontend-react","@collective-intelligence/extensions-sdk-frontend-react/workflow","@collective-intelligence/ui-react","@collective-intelligence/ui-react/icons","@collective-intelligence/ui-react/ui","@collective-intelligence/ui-react/ui-extensions","@tanstack/react-query","react","react-dom","react-dom/client","react/jsx-dev-runtime","react/jsx-runtime"];var modulesByHost={backend:backendHostProvidedModules,dashboard:[...frontendModules,"@xyflow/react"],studio:frontendModules};var FRONTEND_HOSTS=HOSTS.filter((host)=>host!=="backend");var hostProvidedModulesFor=(host)=>modulesByHost[host];var frontendHostProvidedModules=[...new Set(FRONTEND_HOSTS.flatMap(hostProvidedModulesFor))];var isHostProvidedModule=(host,specifier)=>modulesByHost[host].some((moduleName)=>moduleName===specifier);import{fileURLToPath as fileURLToPath4}from"url";var backendPackageEntry=(definition)=>{if(!definition.components.some((component)=>("implementation"in component))&&definition.schemaSidecars.length===0){return}const fqn=`${definition.manifest.fqn}.backend.package-runtime`;if(definition.hostedContributions.some(({manifest})=>manifest.fqn===fqn)){throw new TypeError(`Hosted Contribution '${fqn}' collides with the reserved Backend package runtime entry`)}return{exportName:"createPackageRuntime",fqn,host:"backend"}};var backendArtifactContributions=(definition)=>{const entry=backendPackageEntry(definition);return[...definition.hostedContributions.map(({manifest})=>manifest),...entry===undefined?[]:[entry]]};var backendPackageEntrySource=(packageFqn)=>`
257
265
  import { createBackendPackageRuntime } from "@collective-intelligence/extensions-sdk-backend";
258
266
  import * as declaration from "ci-package-declaration";
259
267
  export function createPackageRuntime() {
@@ -283,7 +291,7 @@ Defaulting to 2020, but this will stop working in the future.`)}options.ecmaVers
283
291
  `}}}else{charIndex=chunk.start;while(charIndex<end){if(!isExcluded[charIndex]){const char=this.original[charIndex];if(char===`
284
292
  `){shouldIndentNextCharacter=true}else if(char!=="\r"&&shouldIndentNextCharacter){shouldIndentNextCharacter=false;if(charIndex===chunk.start){chunk.prependRight(indentStr)}else{this._splitChunk(chunk,charIndex);chunk=chunk.next;chunk.prependRight(indentStr)}}}charIndex+=1}}charIndex=chunk.end;chunk=chunk.next}this.outro=this.outro.replace(pattern,replacer);return this}insert(){throw new Error("magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)")}insertLeft(index,content){if(!warned.insertLeft){console.warn("magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead");warned.insertLeft=true}return this.appendLeft(index,content)}insertRight(index,content){if(!warned.insertRight){console.warn("magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead");warned.insertRight=true}return this.prependRight(index,content)}move(start,end,index){start=start+this.offset;end=end+this.offset;index=index+this.offset;if(index>=start&&index<=end)throw new Error("Cannot move a selection inside itself");this._split(start);this._split(end);this._split(index);const first=this.byStart[start];const last=this.byEnd[end];const oldLeft=first.previous;const oldRight=last.next;const newRight=this.byStart[index];if(!newRight&&last===this.lastChunk)return this;const newLeft=newRight?newRight.previous:this.lastChunk;if(oldLeft)oldLeft.next=oldRight;if(oldRight)oldRight.previous=oldLeft;if(newLeft)newLeft.next=first;if(newRight)newRight.previous=last;if(!first.previous)this.firstChunk=last.next;if(!last.next){this.lastChunk=first.previous;this.lastChunk.next=null}first.previous=newLeft;last.next=newRight||null;if(!newLeft)this.firstChunk=first;if(!newRight)this.lastChunk=last;return this}overwrite(start,end,content,options){options=options||{};return this.update(start,end,content,{...options,overwrite:!options.contentOnly})}update(start,end,content,options){start=start+this.offset;end=end+this.offset;if(typeof content!=="string")throw new TypeError("replacement content must be a string");if(this.original.length!==0){while(start<0)start+=this.original.length;while(end<0)end+=this.original.length}if(end>this.original.length)throw new Error("end is out of bounds");if(start===end)throw new Error("Cannot overwrite a zero-length range \u2013 use appendLeft or prependRight instead");this._split(start);this._split(end);if(options===true){if(!warned.storeName){console.warn("The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string");warned.storeName=true}options={storeName:true}}const storeName=options!==undefined?options.storeName:false;const overwrite=options!==undefined?options.overwrite:false;if(storeName){const original=this.original.slice(start,end);Object.defineProperty(this.storedNames,original,{writable:true,value:true,enumerable:true})}const first=this.byStart[start];const last=this.byEnd[end];if(first){let chunk=first;while(chunk!==last){if(chunk.next!==this.byStart[chunk.end]){throw new Error("Cannot overwrite across a split point")}chunk=chunk.next;chunk.edit("",false)}first.edit(content,storeName,!overwrite)}else{const newChunk=new Chunk(start,end,"").edit(content,storeName);last.next=newChunk;newChunk.previous=last}return this}prepend(content){if(typeof content!=="string")throw new TypeError("outro content must be a string");this.intro=content+this.intro;return this}prependLeft(index,content){index=index+this.offset;if(typeof content!=="string")throw new TypeError("inserted content must be a string");this._split(index);const chunk=this.byEnd[index];if(chunk){chunk.prependLeft(content)}else{this.intro=content+this.intro}return this}prependRight(index,content){index=index+this.offset;if(typeof content!=="string")throw new TypeError("inserted content must be a string");this._split(index);const chunk=this.byStart[index];if(chunk){chunk.prependRight(content)}else{this.outro=content+this.outro}return this}remove(start,end){start=start+this.offset;end=end+this.offset;if(this.original.length!==0){while(start<0)start+=this.original.length;while(end<0)end+=this.original.length}if(start===end)return this;if(start<0||end>this.original.length)throw new Error("Character is out of bounds");if(start>end)throw new Error("end must be greater than start");this._split(start);this._split(end);let chunk=this.byStart[start];while(chunk){chunk.intro="";chunk.outro="";chunk.edit("");chunk=end>chunk.end?this.byStart[chunk.end]:null}return this}reset(start,end){start=start+this.offset;end=end+this.offset;if(this.original.length!==0){while(start<0)start+=this.original.length;while(end<0)end+=this.original.length}if(start===end)return this;if(start<0||end>this.original.length)throw new Error("Character is out of bounds");if(start>end)throw new Error("end must be greater than start");this._split(start);this._split(end);let chunk=this.byStart[start];while(chunk){chunk.reset();chunk=end>chunk.end?this.byStart[chunk.end]:null}return this}lastChar(){if(this.outro.length)return this.outro[this.outro.length-1];let chunk=this.lastChunk;do{if(chunk.outro.length)return chunk.outro[chunk.outro.length-1];if(chunk.content.length)return chunk.content[chunk.content.length-1];if(chunk.intro.length)return chunk.intro[chunk.intro.length-1]}while(chunk=chunk.previous);if(this.intro.length)return this.intro[this.intro.length-1];return""}lastLine(){let lineIndex=this.outro.lastIndexOf(n);if(lineIndex!==-1)return this.outro.substr(lineIndex+1);let lineStr=this.outro;let chunk=this.lastChunk;do{if(chunk.outro.length>0){lineIndex=chunk.outro.lastIndexOf(n);if(lineIndex!==-1)return chunk.outro.substr(lineIndex+1)+lineStr;lineStr=chunk.outro+lineStr}if(chunk.content.length>0){lineIndex=chunk.content.lastIndexOf(n);if(lineIndex!==-1)return chunk.content.substr(lineIndex+1)+lineStr;lineStr=chunk.content+lineStr}if(chunk.intro.length>0){lineIndex=chunk.intro.lastIndexOf(n);if(lineIndex!==-1)return chunk.intro.substr(lineIndex+1)+lineStr;lineStr=chunk.intro+lineStr}}while(chunk=chunk.previous);lineIndex=this.intro.lastIndexOf(n);if(lineIndex!==-1)return this.intro.substr(lineIndex+1)+lineStr;return this.intro+lineStr}slice(start=0,end=this.original.length-this.offset){start=start+this.offset;end=end+this.offset;if(this.original.length!==0){while(start<0)start+=this.original.length;while(end<0)end+=this.original.length}let result3="";let chunk=this.firstChunk;while(chunk&&(chunk.start>start||chunk.end<=start)){if(chunk.start<end&&chunk.end>=end){return result3}chunk=chunk.next}if(chunk&&chunk.edited&&chunk.start!==start)throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);const startChunk=chunk;while(chunk){if(chunk.intro&&(startChunk!==chunk||chunk.start===start)){result3+=chunk.intro}const containsEnd=chunk.start<end&&chunk.end>=end;if(containsEnd&&chunk.edited&&chunk.end!==end)throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);const sliceStart=startChunk===chunk?start-chunk.start:0;const sliceEnd=containsEnd?chunk.content.length+end-chunk.end:chunk.content.length;result3+=chunk.content.slice(sliceStart,sliceEnd);if(chunk.outro&&(!containsEnd||chunk.end===end)){result3+=chunk.outro}if(containsEnd){break}chunk=chunk.next}return result3}snip(start,end){const clone=this.clone();clone.remove(0,start);clone.remove(end,clone.original.length);return clone}_split(index){if(this.byStart[index]||this.byEnd[index])return;let chunk=this.lastSearchedChunk;let previousChunk=chunk;const searchForward=index>chunk.end;while(chunk){if(chunk.contains(index))return this._splitChunk(chunk,index);chunk=searchForward?this.byStart[chunk.end]:this.byEnd[chunk.start];if(chunk===previousChunk)return;previousChunk=chunk}}_splitChunk(chunk,index){if(chunk.edited&&chunk.content.length){const loc=getLocator(this.original)(index);throw new Error(`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} \u2013 "${chunk.original}")`)}const newChunk=chunk.split(index);this.byEnd[index]=chunk;this.byStart[index]=newChunk;this.byEnd[newChunk.end]=newChunk;if(chunk===this.lastChunk)this.lastChunk=newChunk;this.lastSearchedChunk=chunk;return true}toString(){let str=this.intro;let chunk=this.firstChunk;while(chunk){str+=chunk.toString();chunk=chunk.next}return str+this.outro}isEmpty(){let chunk=this.firstChunk;do{if(chunk.intro.length&&chunk.intro.trim()||chunk.content.length&&chunk.content.trim()||chunk.outro.length&&chunk.outro.trim())return false}while(chunk=chunk.next);return true}length(){let chunk=this.firstChunk;let length=0;do{length+=chunk.intro.length+chunk.content.length+chunk.outro.length}while(chunk=chunk.next);return length}trimLines(){return this.trim("[\\r\\n]")}trim(charType){return this.trimStart(charType).trimEnd(charType)}trimEndAborted(charType){const rx=new RegExp((charType||"\\s")+"+$");this.outro=this.outro.replace(rx,"");if(this.outro.length)return true;let chunk=this.lastChunk;do{const end=chunk.end;const aborted=chunk.trimEnd(rx);if(chunk.end!==end){if(this.lastChunk===chunk){this.lastChunk=chunk.next}this.byEnd[chunk.end]=chunk;this.byStart[chunk.next.start]=chunk.next;this.byEnd[chunk.next.end]=chunk.next}if(aborted)return true;chunk=chunk.previous}while(chunk);return false}trimEnd(charType){this.trimEndAborted(charType);return this}trimStartAborted(charType){const rx=new RegExp("^"+(charType||"\\s")+"+");this.intro=this.intro.replace(rx,"");if(this.intro.length)return true;let chunk=this.firstChunk;do{const end=chunk.end;const aborted=chunk.trimStart(rx);if(chunk.end!==end){if(chunk===this.lastChunk)this.lastChunk=chunk.next;this.byEnd[chunk.end]=chunk;this.byStart[chunk.next.start]=chunk.next;this.byEnd[chunk.next.end]=chunk.next}if(aborted)return true;chunk=chunk.next}while(chunk);return false}trimStart(charType){this.trimStartAborted(charType);return this}hasChanged(){return this.original!==this.toString()}_replaceRegexp(searchValue,replacement){function getReplacement(match5,str){if(typeof replacement==="string"){return replacement.replace(/\$(\$|&|\d+)/g,(_,i2)=>{if(i2==="$")return"$";if(i2==="&")return match5[0];const num=+i2;if(num<match5.length)return match5[+i2];return`$${i2}`})}else{return replacement(...match5,match5.index,str,match5.groups)}}function matchAll(re,str){let match5;const matches=[];while(match5=re.exec(str)){matches.push(match5)}return matches}if(searchValue.global){const matches=matchAll(searchValue,this.original);matches.forEach((match5)=>{if(match5.index!=null){const replacement2=getReplacement(match5,this.original);if(replacement2!==match5[0]){this.overwrite(match5.index,match5.index+match5[0].length,replacement2)}}})}else{const match5=this.original.match(searchValue);if(match5&&match5.index!=null){const replacement2=getReplacement(match5,this.original);if(replacement2!==match5[0]){this.overwrite(match5.index,match5.index+match5[0].length,replacement2)}}}return this}_replaceString(string4,replacement){const{original}=this;const index=original.indexOf(string4);if(index!==-1){if(typeof replacement==="function"){replacement=replacement(string4,index,original)}if(string4!==replacement){this.overwrite(index,index+string4.length,replacement)}}return this}replace(searchValue,replacement){if(typeof searchValue==="string"){return this._replaceString(searchValue,replacement)}return this._replaceRegexp(searchValue,replacement)}_replaceAllString(string4,replacement){const{original}=this;const stringLength=string4.length;for(let index=original.indexOf(string4);index!==-1;index=original.indexOf(string4,index+stringLength)){const previous=original.slice(index,index+stringLength);let _replacement=replacement;if(typeof replacement==="function"){_replacement=replacement(previous,index,original)}if(previous!==_replacement)this.overwrite(index,index+stringLength,_replacement)}return this}replaceAll(searchValue,replacement){if(typeof searchValue==="string"){return this._replaceAllString(searchValue,replacement)}if(!searchValue.global){throw new TypeError("MagicString.prototype.replaceAll called with a non-global RegExp argument")}return this._replaceRegexp(searchValue,replacement)}}var stableFrontendChunk=(code,host)=>{const edited=new MagicString(code);for(const match5 of code.matchAll(/^\/\/#region .*$/gmu)){if(match5.index!==undefined){edited.overwrite(match5.index,match5.index+match5[0].length,"//#region")}}if(host==="dashboard"){const scanner=tokenizer2(code,{ecmaVersion:"latest",sourceType:"module"});const tokens=[];for(let token=scanner.getToken();token.type.label!=="eof";token=scanner.getToken()){tokens.push(token)}const tokenText=(token)=>token===undefined?undefined:code.slice(token.start,token.end);const importsReactNamespace=tokens.some((token,index)=>token.type.label==="import"&&tokens[index+1]?.type.label==="*"&&tokenText(tokens[index+2])==="as"&&tokenText(tokens[index+3])==="React$1"&&tokenText(tokens[index+4])==="from"&&/^(?:"react"|'react')$/u.test(tokenText(tokens[index+5])??""));if(importsReactNamespace){if(tokens.some((token)=>token.type.label==="name"&&tokenText(token)==="React2")){throw new Error("Hosted React namespace collides with React2")}for(const token of tokens){if(token.type.label==="name"&&tokenText(token)==="React$1"){edited.overwrite(token.start,token.end,"React2")}}}}return{code:edited.toString(),map:edited.generateMap({hires:true,includeContent:true})}};var encoder2=new TextEncoder;var nodePath2=runSync2(provide3(Path2,exports_NodePath.layer));var jsonString=encodeSync(fromJsonString2(Unknown2));var writerEffect=(write2)=>sync2(write2).pipe(flatMap3((result3)=>promise2(constant(Promise.resolve(result3)))));var viteAssetBytes=(source)=>typeof source==="string"?encoder2.encode(source):source;var digest=(bytes2)=>createHash("sha256").update(bytes2).digest("hex");var runtimeModuleBytes=(code,host,relativePath)=>encoder2.encode(`${code.trimEnd()}
285
293
  //# sourceURL=extension://${host}/${encodeURIComponent(relativePath)}
286
- `);var moduleExport=(exportName)=>{if(!/^[$A-Z_a-z][$\w]*$/u.test(exportName)){throw new TypeError(`Hosted Contribution export '${exportName}' is not a JavaScript identifier`)}return exportName};var sanitizeSourceMap=(sourceMapText,assetName)=>{const parsed=decodeSync(fromJsonString2(Unknown2))(sourceMapText);if(parsed===null||typeof parsed!=="object"||!("sources"in parsed)||!Array.isArray(parsed.sources)||!("sourcesContent"in parsed)||!Array.isArray(parsed.sourcesContent)||parsed.sources.length!==parsed.sourcesContent.length){throw new Error(`Build emitted an invalid private source map for ${assetName}`)}if(parsed.sources.length===0){return}const stableFields=Object.fromEntries(Object.entries(parsed).filter(([key])=>key!=="debugId"));return encoder2.encode(jsonString({...stableFields,file:assetName,sourceRoot:"",sources:parsed.sources.map((_source,index)=>`extension://release/${encodeURIComponent(assetName)}/source-${index}.ts`)}))};var contributionIdentities=(definition,host)=>definition.hostedContributions.flatMap(({load,manifest})=>manifest.host===host?[{exportName:manifest.exportName,fqn:manifest.fqn,host,load}]:[]);var buildBackend=flow((input)=>gen2(function*buildBackendEffect(){const packageEntry=backendPackageEntry(input.definition);const identities=[...contributionIdentities(input.definition,"backend"),...packageEntry===undefined?[]:[packageEntry]];if(identities.length===0){return[]}const entrypoints=identities.map((_identity,index)=>`ci-release-backend-entry-${index}`);const entryByPath=new Map(entrypoints.map((entrypoint,index)=>[entrypoint,identities[index]]));const result3=yield*tryPromise2(Bun.build.bind(Bun,{...workspaceSourceResolve(process.execArgv),define:{"process.env.NODE_ENV":jsonString("production")},entrypoints,external:[...hostProvidedModulesFor("backend")],format:"esm",minify:{identifiers:false,syntax:true,whitespace:true},naming:{asset:"assets/[name]-[hash].[ext]",chunk:"chunks/[name]-[hash].mjs",entry:"modules/[name].mjs"},plugins:[{name:"ci-release-backend-entries",setup(builder){builder.onResolve({filter:/^ci-package-declaration$/u},()=>({path:backendPackageModulePath(input.declarationSpecifier,input.definition)}));builder.onResolve({filter:/^ci-release-backend-entry-/u},(args2)=>({namespace:"ci-release-backend-entry",path:args2.path}));builder.onLoad({filter:/.*/u,namespace:"ci-release-backend-entry"},(args2)=>{const identity3=entryByPath.get(args2.path);if(identity3===undefined){throw new Error(`Unknown Backend release entry '${args2.path}'`)}if(!("load"in identity3)){return{contents:backendPackageEntrySource(input.definition.manifest.fqn),loader:"ts"}}const contributionImport=resolveHostedContributionEntry(input.declarationSpecifier,identity3);return{contents:`export { ${moduleExport(identity3.exportName)} } from ${jsonString(contributionImport)}`,loader:"ts"}})}}],sourcemap:"external",splitting:true,target:"bun"}));if(!result3.success){throw new AggregateError(result3.logs,"Failed to build Backend release assets")}const outputByName=new Map(result3.outputs.map((artifact)=>[nodePath2.basename(artifact.path),artifact]));const runtimeFiles=[];for(const artifact of result3.outputs.filter(({path:path3})=>!path3.endsWith(".map"))){runtimeFiles.push(yield*gen2(function*readBackendArtifact(){const relativePath=artifact.path.replace(/^\.\//u,"").replace(/^\/+/u,"");const rawCode=yield*tryPromise2(artifact.text.bind(artifact));const code=rawCode.replaceAll(/\/\/# (?:debugId|sourceMappingURL)=.*$/gmu,"");const bytes2=runtimeModuleBytes(code,"backend",relativePath);const mapArtifact=outputByName.get(`${nodePath2.basename(artifact.path)}.map`);const entryMatch=/^ci-release-backend-entry-(?<index>\d+)\.mjs$/u.exec(nodePath2.basename(artifact.path));const contributionFqn=entryMatch?.groups?.index===undefined?undefined:identities[Number(entryMatch.groups.index)]?.fqn;const sourceMapBytes=mapArtifact===undefined?undefined:sanitizeSourceMap(yield*tryPromise2(mapArtifact.text.bind(mapArtifact)),relativePath);return{bytes:bytes2,...contributionFqn===undefined?undefined:{contributionFqn},host:"backend",path:`artifacts/backend/${relativePath}`,...sourceMapBytes===undefined?undefined:{sourceMapBytes}}}))}return runtimeFiles}),runPromise2);var viteOutputList=(output)=>{if(!Array.isArray(output)&&"close"in output){throw new Error("Vite unexpectedly returned a watcher for a release build")}return Array.isArray(output)?output:[output]};var buildFrontend=flow((input)=>gen2(function*buildFrontendEffect(){const identities=contributionIdentities(input.definition,input.host);if(identities.length===0){return[]}const entries=new Map;const entryNames={};for(const[index,identity3]of identities.entries()){const id=`virtual:ci-release-${input.host}-entry-${index}`;const contributionImport=resolveHostedContributionEntry(input.declarationSpecifier,identity3);entries.set(`\x00${id}`,{contributionImport,identity:identity3,source:`export { ${moduleExport(identity3.exportName)} } from ${jsonString(contributionImport)}; export * from ${jsonString(contributionImport)}`});entryNames[`contribution-${index}`]=id}const virtualEntries={load:flow(function loadFrontendEntry(id){const resolve6=this.resolve.bind(this);return gen2(function*loadFrontendEntryEffect(){const entry=entries.get(id);if(entry===undefined){return null}const resolved=yield*promise2(flow(constant(entry.contributionImport),resolve6));if(resolved===null){return yield*die3(new Error(`Frontend catalog module could not be resolved: ${entry.contributionImport}`))}const file=Bun.file(resolved.id);const source=yield*promise2(file.text.bind(file));const{exports}=new Bun.Transpiler({loader:/\.[jt]sx$/u.test(resolved.id)?"tsx":"ts"}).scan(source);return exports.includes("default")?`${entry.source}; export { default } from ${jsonString(entry.contributionImport)}`:entry.source})},runPromise2),name:"ci-hosted-release-entries",resolveId:(id)=>id.startsWith("virtual:ci-release-")?`\x00${id}`:null};const stableRegionLabels={name:"ci-hosted-release-stable-region-labels",renderChunk:(code)=>stableFrontendChunk(code,input.host)};const hostReactRequireId="\x00virtual:ci-host-react-require";const hostReactRequire={enforce:"pre",load:(id)=>id===hostReactRequireId?'import React from "react"; module.exports = React;':null,name:"ci-host-react-require",resolveId:{handler:(source,_importer,options)=>source==="react"&&options.kind==="require-call"?hostReactRequireId:null,order:"pre"}};const output=yield*tryPromise2(viteBuild.bind(undefined,{build:{assetsInlineLimit:0,cssCodeSplit:true,emptyOutDir:false,minify:false,modulePreload:false,rolldownOptions:{input:entryNames,output:{assetFileNames:"assets/[name]-[hash][extname]",chunkFileNames:"chunks/[name]-[hash].mjs",entryFileNames:"modules/[name].mjs"},preserveEntrySignatures:"strict"},sourcemap:"hidden",target:"esnext",write:false},configFile:false,define:{"process.env.NODE_ENV":jsonString("production")},logLevel:"silent",mode:"production",oxc:{jsx:{development:false}},plugins:[virtualEntries,hostReactRequire,esmExternalRequirePlugin({external:[...hostProvidedModulesFor(input.host)]}),stableRegionLabels],resolve:workspaceSourceResolve(process.execArgv),root:process.cwd(),ssr:workspaceSourceSsrResolve(process.execArgv)})).pipe(catch_2((error)=>die3(error.cause instanceof Error?error.cause:new Error("Frontend catalog build failed",{cause:error.cause}))));const files=[];for(const result3 of viteOutputList(output)){for(const artifact of result3.output){if(artifact.type==="asset"){if(!artifact.fileName.endsWith(".map")){files.push({bytes:viteAssetBytes(artifact.source),host:input.host,path:`artifacts/${input.host}/${artifact.fileName}`})}continue}const entry=artifact.facadeModuleId===null?undefined:entries.get(artifact.facadeModuleId);const sourceMapBytes=artifact.map===null?undefined:sanitizeSourceMap(artifact.map.toString(),artifact.fileName);files.push({bytes:runtimeModuleBytes(artifact.code,input.host,artifact.fileName),...entry===undefined?undefined:{contributionFqn:entry.identity.fqn},host:input.host,path:`artifacts/${input.host}/${artifact.fileName}`,...sourceMapBytes===undefined?undefined:{sourceMapBytes}})}}return files}),runPromise2);var mergeCompatibility=(definition)=>{const compatibility={};for(const{manifest}of definition.hostedContributions){for(const[runtime,range]of Object.entries(manifest.compatibility??{})){const existing=compatibility[runtime];if(existing!==undefined&&existing!==range){throw new TypeError(`Hosted Contributions declare conflicting ${runtime} compatibility ranges`)}compatibility[runtime]=range}}return Object.fromEntries(Object.entries(compatibility).toSorted(([left],[right])=>compareCanonicalText(left,right)))};var buildPackageRelease=flow((input)=>gen2(function*buildPackageReleaseEffect(){const definitions=yield*promise2(loadPackageDeclarations.bind(undefined,input.declarationSpecifier));if(definitions.length!==1){throw new TypeError("An Extension Release build requires exactly one package")}const[definition]=definitions;if(definition===undefined){throw new TypeError("Extension Package declaration was not found")}const hostFiles=yield*all2([promise2(buildBackend.bind(undefined,{declarationSpecifier:input.declarationSpecifier,definition})),...FRONTEND_HOSTS.map((host)=>promise2(buildFrontend.bind(undefined,{declarationSpecifier:input.declarationSpecifier,definition,host})))]);const files=hostFiles.flat();const assets=[];const privateSourceMaps=[];const privateMapByRuntimeDigest=new Map;for(const file of files){const runtimeDigest=digest(file.bytes);const sourceMap=file.sourceMapBytes;const privateSourceMap=sourceMap===undefined?undefined:{digest:digest(sourceMap),size:sourceMap.byteLength};assets.push({digest:runtimeDigest,host:file.host,path:file.path,...privateSourceMap===undefined?undefined:{privateSourceMap},size:file.bytes.byteLength});if(sourceMap!==undefined&&privateSourceMap!==undefined){const existing=privateMapByRuntimeDigest.get(runtimeDigest);if(existing!==undefined&&existing.digest!==privateSourceMap.digest){throw new Error(`Runtime asset '${runtimeDigest}' produced conflicting private source maps`)}if(existing===undefined){const sidecar={bytes:sourceMap,digest:privateSourceMap.digest,runtimeAssetDigest:runtimeDigest,size:privateSourceMap.size};privateMapByRuntimeDigest.set(runtimeDigest,sidecar);privateSourceMaps.push(sidecar)}}}const assetByPath=new Map(assets.map((asset)=>[asset.path,asset]));const pathByContribution=new Map(files.flatMap((file)=>file.contributionFqn===undefined?[]:[[`${file.host}:${file.contributionFqn}`,file.path]]));const contributions=backendArtifactContributions(definition).map((contribution)=>{const assetPath=pathByContribution.get(`${contribution.host}:${contribution.fqn}`);const asset=assetPath===undefined?undefined:assetByPath.get(assetPath);if(asset===undefined||assetPath===undefined){throw new Error(`No release entry asset was built for ${contribution.fqn}`)}const common={assetPath,digest:asset.digest,exportName:contribution.exportName,fqn:contribution.fqn,size:asset.size};return contribution.host==="backend"?{...common,...contribution.contract===undefined?undefined:{contract:contribution.contract},...contribution.execution===undefined?undefined:{execution:contribution.execution},exportName:contribution.exportName,host:contribution.host}:{...common,contract:contribution.contract,exportName:contribution.exportName,host:contribution.host}});const packageManifestBytes=encoder2.encode(canonicalPackageManifest(definition));const archiveBytes=createExtensionReleaseArchive([...files.map(({bytes:bytes2,path:path3})=>({bytes:bytes2,path:path3})),{bytes:packageManifestBytes,path:"package-manifest.json"}]);const releaseDigest=digest(archiveBytes);const manifest={apiVersion:"v2",assets:assets.toSorted((left,right)=>compareCanonicalText(left.path,right.path)),compatibility:mergeCompatibility(definition),contributions:contributions.toSorted((left,right)=>compareCanonicalText(left.host,right.host)||compareCanonicalText(left.fqn,right.fqn)),package:{fqn:definition.manifest.fqn,version:definition.manifest.version},packageManifest:definition.manifest,releaseDigest};return{archiveBytes,manifest,manifestBytes:encoder2.encode(canonicalExtensionReleaseManifest(manifest)),packageManifest:definition.manifest,packageManifestBytes,privateSourceMaps:privateSourceMaps.toSorted((left,right)=>compareCanonicalText(left.runtimeAssetDigest,right.runtimeAssetDigest)),releaseDigest}}),runPromise2);var materializePackageRelease=flow((input,dependencies)=>gen2(function*materializePackageReleaseEffect(){const release=yield*promise2(buildPackageRelease.bind(undefined,{declarationSpecifier:input.declarationSpecifier}));const privateMapDirectory=nodePath2.join(input.outputDirectory,"private-source-maps");yield*writerEffect(dependencies.makeDirectory.bind(dependencies,privateMapDirectory));yield*all2([writerEffect(dependencies.writeBytes.bind(dependencies,nodePath2.join(input.outputDirectory,"release.tar"),release.archiveBytes)),writerEffect(dependencies.writeBytes.bind(dependencies,nodePath2.join(input.outputDirectory,"manifest.json"),release.manifestBytes)),writerEffect(dependencies.writeBytes.bind(dependencies,nodePath2.join(input.outputDirectory,"package-manifest.json"),release.packageManifestBytes)),...release.privateSourceMaps.map((sourceMap)=>writerEffect(dependencies.writeBytes.bind(dependencies,nodePath2.join(privateMapDirectory,`${sourceMap.runtimeAssetDigest}.map`),sourceMap.bytes)))]);return{archive:nodePath2.join(input.outputDirectory,"release.tar"),manifest:nodePath2.join(input.outputDirectory,"manifest.json"),packageManifest:nodePath2.join(input.outputDirectory,"package-manifest.json"),privateSourceMaps:privateMapDirectory,releaseDigest:release.releaseDigest}}),runPromise2);var optionValue3=(args2,name)=>{const index=args2.lastIndexOf(`--${name}`);const value3=index===-1?undefined:args2[index+1];if(value3===undefined||value3===""){throw new TypeError(`Missing option --${name}`)}return value3};var runPackageBuildCommand=flow((args2,dependencies)=>gen2(function*runPackageBuildCommandEffect(){const outputDirectory=optionValue3(args2,"out");const release=yield*promise2(materializePackageRelease.bind(undefined,{declarationSpecifier:dependencies.resolveDeclarationSpecifier(optionValue3(args2,"declaration")),outputDirectory},dependencies));return yield*encodeEffect(fromJsonString2(Unknown2))({archive:release.archive,manifest:release.manifest,packageManifest:release.packageManifest,privateSourceMaps:release.privateSourceMaps,releaseDigest:release.releaseDigest})}),runPromise2);class EventStreamHttpError extends Error{status;constructor(status,statusText){super(`Event stream request failed with HTTP ${status} ${statusText}`.trimEnd());this.name="EventStreamHttpError";this.status=status}}var singleConnectionSseOptions={onSseError:(cause)=>{throw cause},sseMaxRetryAttempts:1};var eventStreamFetch=(fetch2=globalThis.fetch)=>Object.assign(async(input,init)=>{const response=await fetch2(input,init);if(!response.ok){throw new EventStreamHttpError(response.status,response.statusText)}return response},{preconnect:()=>{}});var isRetryableEventStreamError=(cause)=>!(cause instanceof EventStreamHttpError)||cause.status>=500||cause.status===408||cause.status===425||cause.status===429;class EventStreamRetriesExhaustedError extends Error{attempts;lastEventId;constructor(input){super(input.cause===undefined?"Event stream kept closing without progress":"Event stream kept failing without progress",{cause:input.cause});this.name="EventStreamRetriesExhaustedError";this.attempts=input.attempts;this.lastEventId=input.lastEventId}}var DEFAULT_INITIAL_RETRY_DELAY_MS=1000;var DEFAULT_MAX_RETRY_DELAY_MS=30000;var DEFAULT_MIN_HEALTHY_CONNECTION_MS=30000;var abortableSleep=async(milliseconds,signal)=>{if(signal.aborted){return}await new Promise((resolve6)=>{const settled=new AbortController;const timeout3=globalThis.setTimeout(()=>{settled.abort();resolve6()},milliseconds);signal.addEventListener("abort",()=>{globalThis.clearTimeout(timeout3);resolve6()},{once:true,signal:settled.signal})})};var asError=(cause)=>cause instanceof Error?cause:new Error(String(cause),{cause});var followEventStream=async(options)=>{const signal=options.signal??new AbortController().signal;const sleep3=options.sleep??abortableSleep;const initialDelay=options.initialRetryDelayMs??DEFAULT_INITIAL_RETRY_DELAY_MS;const maxDelay=options.maxRetryDelayMs??DEFAULT_MAX_RETRY_DELAY_MS;const minHealthyConnectionMs=options.minHealthyConnectionMs??DEFAULT_MIN_HEALTHY_CONNECTION_MS;const now=options.now??Date.now;let{lastEventId}=options;let attempt=0;while(!signal.aborted){const connection3=new AbortController;const stopConnection=()=>{connection3.abort()};signal.addEventListener("abort",stopConnection,{once:true});let terminal=false;let failure;const openedAt=now();try{const events=await options.connect({lastEventId,signal:connection3.signal});for await(const event of events){await options.onEvent(event);const nextEventId=options.eventId===undefined?lastEventId:options.eventId(event);if(options.eventId===undefined||nextEventId!==lastEventId){attempt=0}lastEventId=nextEventId;if(options.isTerminal?.(event)===true){terminal=true;break}}}catch(error){failure=asError(error)}finally{signal.removeEventListener("abort",stopConnection);connection3.abort()}if(terminal){return{lastEventId,reason:"terminal"}}if(signal.aborted){break}if(failure!==undefined&&options.isRetryableError!==undefined&&!options.isRetryableError(failure)){throw failure}if(failure===undefined&&now()-openedAt>=minHealthyConnectionMs){attempt=0}attempt+=1;if(options.maxRetries!==undefined&&attempt>options.maxRetries){throw new EventStreamRetriesExhaustedError({attempts:attempt,cause:failure,lastEventId})}const delayMs=Math.min(initialDelay*2**(attempt-1),maxDelay);options.onReconnect?.({attempt,cause:failure,delayMs,lastEventId});await sleep3(delayMs,signal)}return{lastEventId,reason:"aborted"}};var awaitValue=(value3)=>promise2(constant(Promise.resolve(value3)));var encodeJson2=encodeSync(fromJsonString2(Unknown2));class PackageOperationCommandError extends TaggedError3()("PackageOperationCommandError",{cause:optional2(Unknown2),message:String4}){}var requireOption=(options,name)=>{const value3=options.get(name);if(value3===undefined||value3===""){throw new PackageOperationCommandError({message:`Missing required option --${name}`})}return value3};var parseOptions=(args2)=>{const options=new Map;for(let index=1;index<args2.length;index+=2){const flag=args2[index];const value3=args2[index+1];if(!flag?.startsWith("--")||!value3||value3.startsWith("--")){throw new PackageOperationCommandError({message:"Options must be supplied as --name value pairs"})}options.set(flag.slice(2),value3)}return options};var isPackageOperationComplete=(status)=>status!=="pending"&&status!=="running";var parseLastEventId=(options)=>{const value3=options.get("last-event-id")??"0";if(!/^\d+$/u.test(value3)){throw new PackageOperationCommandError({message:"--last-event-id must be a non-negative event sequence"})}const sequence=Number(value3);if(!Number.isSafeInteger(sequence)){throw new PackageOperationCommandError({message:"--last-event-id must be a non-negative event sequence"})}return sequence};var fetchSnapshot=flow((dependencies,organizationId,operationId,signal)=>gen2(function*nativeAssetStep1(){const request={client:dependencies.client,headers:{"x-organization-id":organizationId},path:{operationId},throwOnError:true};if(signal!==undefined){request.signal=signal}const response=yield*awaitValue(packageOperationsSnapshot(request));return decodePackageOperationSnapshot(response.data)}),runPromise2);var executeSnapshot=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageOperationCommandError)(cause)?cause:new PackageOperationCommandError({cause,message:"Could not inspect package operation"}),try:async()=>({kind:"snapshot",snapshot:await fetchSnapshot(dependencies,requireOption(options,"organization"),requireOption(options,"operation"))})});var executeContinuation=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageOperationCommandError)(cause)?cause:new PackageOperationCommandError({cause,message:"Could not continue package operation"}),try:async()=>{const accepted=await packageOperationsContinueOperation({client:dependencies.client,headers:{"idempotency-key":requireOption(options,"idempotency-key"),"x-organization-id":requireOption(options,"organization")},path:{operationId:requireOption(options,"operation")},throwOnError:true});return{kind:"operation_accepted",operationId:accepted.data.operationId}}});var MAX_RECONNECTS_WITHOUT_PROGRESS=3;var isCommandError=is2(PackageOperationCommandError);var decodeOperationEvent=(wireEvent)=>{try{return decodePackageOperationEvent(encodeJson2(wireEvent))}catch(error){throw new PackageOperationCommandError({cause:error,message:"Package operation event did not match the Backend contract"})}};var followPackageOperationEffect=(input,dependencies)=>tryPromise2({catch:(cause)=>isCommandError(cause)?cause:new PackageOperationCommandError({cause,message:"Could not reconnect to package operation"}),try:async(signal)=>{let lastSequence=input.afterSequence??0;const{operationId,organizationId}=input;const snapshot=await fetchSnapshot(dependencies,organizationId,operationId,signal);if(isPackageOperationComplete(snapshot.status)&&(input.replay!==true||lastSequence>=snapshot.lastEventSequence)){return{kind:"snapshot",snapshot}}let lastEventId=input.afterSequence===undefined?undefined:String(lastSequence);let observed;try{await followEventStream({connect:async(connection3)=>{const events=await packageOperationsEvents({...singleConnectionSseOptions,client:dependencies.client,fetch:eventStreamFetch(dependencies.client.getConfig().fetch),headers:{...connection3.lastEventId===undefined?undefined:{"last-event-id":connection3.lastEventId},"x-organization-id":organizationId},path:{operationId},signal:connection3.signal,throwOnError:true});return events.stream},eventId:()=>lastEventId,isRetryableError:(error)=>!isCommandError(error)&&isRetryableEventStreamError(error),isTerminal:()=>observed!==undefined&&observed.sequence===lastSequence&&isPackageOperationComplete(observed.status),...lastEventId===undefined?undefined:{lastEventId},maxRetries:MAX_RECONNECTS_WITHOUT_PROGRESS,onEvent:(wireEvent)=>{const event=decodeOperationEvent(wireEvent);observed=event;if(event.sequence<=lastSequence){return}if(event.sequence!==lastSequence+1){throw new PackageOperationCommandError({message:`Package operation event sequence jumped from ${lastSequence} to ${event.sequence}`})}dependencies.writeEvent(encodeJson2(event));lastSequence=event.sequence;lastEventId=String(event.sequence)},signal,...dependencies.sleep===undefined?undefined:{sleep:dependencies.sleep}})}catch(error){if(error instanceof EventStreamHttpError){throw new PackageOperationCommandError({cause:error,message:`Package operation event stream was rejected with HTTP ${error.status}`})}if(error instanceof EventStreamRetriesExhaustedError){throw new PackageOperationCommandError({cause:error.cause??error,message:`Package operation event stream disconnected; reconnect with --last-event-id ${lastSequence}`})}throw error}return{kind:"snapshot",snapshot:await fetchSnapshot(dependencies,organizationId,operationId,signal)}}});var packageOperationCommandEffect=(args2,dependencies)=>{const[command]=args2;const options=parseOptions(args2);if(command==="continue"){return executeContinuation(options,dependencies)}if(command==="reconnect"){return followPackageOperationEffect({afterSequence:options.has("last-event-id")?parseLastEventId(options):undefined,operationId:requireOption(options,"operation"),organizationId:requireOption(options,"organization"),replay:true},dependencies)}if(command==="snapshot"){return executeSnapshot(options,dependencies)}return fail6(new PackageOperationCommandError({message:"Expected one of: package operation snapshot, package operation reconnect, package operation continue"}))};var renderPin=(pin)=>`${pin.fqn}@${pin.releaseId}`;var renderSelection=(selection)=>selection===null?"none":`${selection.releaseId} generation ${selection.generation}`;var renderBlocker=(blocker)=>{if(blocker._tag==="manual_prerequisite"){const observed=blocker.observed===null?"none":renderPin(blocker.observed);return`Blocker ManualPrerequisite: ${blocker.message}; requires ${renderPin(blocker.required)}, observed ${observed}; path ${blocker.path.map(renderPin).join(" -> ")}`}let label=blocker._tag;if(blocker._tag==="authority_denied"){label=`AuthorityDenied (${blocker.boundary})`}else if(blocker._tag==="unknown"){label=blocker.tag}const details=[blocker.message,..."definitions"in blocker?[`definitions ${blocker.definitions.map((definition)=>`${definition.kind} ${definition.fqn}`).join(", ")}`]:[],...blocker.paths.map((path3)=>`path ${path3.join(" -> ")}`)];return`Blocker ${label}: ${details.join("; ")}`};var renderProtection=(protection)=>{if(protection.kind==="required_by"){return`requiredBy ${renderPin(protection.dependent)} (${protection.protection})`}if(protection.kind==="unknown_requirement"){return`unknownRequirement ${renderPin(protection.dependent)}`}if(protection.kind==="workflow_use"){const{template}=protection;return`workflowUse ${protection.workflowId} (${protection.state}, template ${template.fqn}@${template.version})`}if(protection.kind==="live_binding"){return`liveBinding ${protection.bindingKind} ${protection.id}`}return protection.kind};var renderCleanupCandidate=(candidate)=>{const subject=`Cleanup ${candidate.packageFqn}@${candidate.releaseId} (${candidate.installationId}) ${candidate.result}`;const protections=candidate.protections??[];return protections.length===0?`${subject}.`:`${subject}: ${protections.map(renderProtection).join("; ")}.`};var renderCleanup=(cleanup)=>[`Cleanup ${cleanup.state}.`,...cleanup.candidates.map(renderCleanupCandidate)];var renderHost=(host,snapshot)=>{const{member,observed}=host;const outcome=`Host ${member.packageFqn} (${member.installationId}) ${host.result}: expected ${member.releaseId} generation ${member.generation}; observed Desired ${renderSelection(observed.desired)}, Serving ${renderSelection(observed.serving)}.`;return host.diagnosticId===undefined?outcome:`${outcome} Diagnostic ID ${host.diagnosticId}: ci package diagnostics trace --organization ${snapshot.organizationId} --diagnostic ${host.diagnosticId}`};var renderNextAction=(snapshot)=>{const scope3=`--organization ${snapshot.organizationId} --operation ${snapshot.id}`;const continueCommand=`ci package operation continue ${scope3} --idempotency-key <key>`;const hints={continue:`continue. Start a linked new operation with a new Operation ID: ${continueCommand}`,none:"none.",retry:`retry. Resume this same operation with its accepted plan and Operation ID: ${continueCommand}`,wait:`wait. Follow progress: ci package operation reconnect ${scope3} --last-event-id ${snapshot.lastEventSequence}`};return`Next action: ${hints[snapshot.nextAction]}`};var renderPackageOperationSummary=(snapshot)=>{const{application,failure}=snapshot;const lines=[`Package operation ${snapshot.id} is ${snapshot.status}.`,...application.state==="not_applied"&&application.blocker!==undefined?[renderBlocker(application.blocker)]:[],...snapshot.hosts.map((host)=>renderHost(host,snapshot)),...snapshot.cleanup===undefined?[]:renderCleanup(snapshot.cleanup),...failure===undefined?[]:[`Failure ${failure.reason}: ${failure.message}`],renderNextAction(snapshot)];return`${lines.join(`
294
+ `);var moduleExport=(exportName)=>{if(!/^[$A-Z_a-z][$\w]*$/u.test(exportName)){throw new TypeError(`Hosted Contribution export '${exportName}' is not a JavaScript identifier`)}return exportName};var sanitizeSourceMap=(sourceMapText,assetName)=>{const parsed=decodeSync(fromJsonString2(Unknown2))(sourceMapText);if(parsed===null||typeof parsed!=="object"||!("sources"in parsed)||!Array.isArray(parsed.sources)||!("sourcesContent"in parsed)||!Array.isArray(parsed.sourcesContent)||parsed.sources.length!==parsed.sourcesContent.length){throw new Error(`Build emitted an invalid private source map for ${assetName}`)}if(parsed.sources.length===0){return}const stableFields=Object.fromEntries(Object.entries(parsed).filter(([key])=>key!=="debugId"));return encoder2.encode(jsonString({...stableFields,file:assetName,sourceRoot:"",sources:parsed.sources.map((_source,index)=>`extension://release/${encodeURIComponent(assetName)}/source-${index}.ts`)}))};var contributionIdentities=(definition,host)=>definition.hostedContributions.flatMap(({load,manifest})=>manifest.host===host?[{exportName:manifest.exportName,fqn:manifest.fqn,host,load}]:[]);var buildBackend=flow((input)=>gen2(function*buildBackendEffect(){const packageEntry=backendPackageEntry(input.definition);const identities=[...contributionIdentities(input.definition,"backend"),...packageEntry===undefined?[]:[packageEntry]];if(identities.length===0){return[]}const entrypoints=identities.map((_identity,index)=>`ci-release-backend-entry-${index}`);const entryByPath=new Map(entrypoints.map((entrypoint,index)=>[entrypoint,identities[index]]));const result3=yield*tryPromise2(Bun.build.bind(Bun,{...workspaceSourceResolve(process.execArgv),define:{"process.env.NODE_ENV":jsonString("production")},entrypoints,external:[...hostProvidedModulesFor("backend")],format:"esm",minify:{identifiers:false,syntax:true,whitespace:true},naming:{asset:"assets/[name]-[hash].[ext]",chunk:"chunks/[name]-[hash].mjs",entry:"modules/[name].mjs"},plugins:[{name:"ci-release-backend-entries",setup(builder){builder.onResolve({filter:/^ci-package-declaration$/u},()=>({path:backendPackageModulePath(input.declarationSpecifier,input.definition)}));builder.onResolve({filter:/^ci-release-backend-entry-/u},(args2)=>({namespace:"ci-release-backend-entry",path:args2.path}));builder.onLoad({filter:/.*/u,namespace:"ci-release-backend-entry"},(args2)=>{const identity3=entryByPath.get(args2.path);if(identity3===undefined){throw new Error(`Unknown Backend release entry '${args2.path}'`)}if(!("load"in identity3)){return{contents:backendPackageEntrySource(input.definition.manifest.fqn),loader:"ts"}}const contributionImport=resolveHostedContributionEntry(input.declarationSpecifier,identity3);return{contents:`export { ${moduleExport(identity3.exportName)} } from ${jsonString(contributionImport)}`,loader:"ts"}})}}],sourcemap:"external",splitting:true,target:"bun"}));if(!result3.success){throw new AggregateError(result3.logs,"Failed to build Backend release assets")}const outputByName=new Map(result3.outputs.map((artifact)=>[nodePath2.basename(artifact.path),artifact]));const runtimeFiles=[];for(const artifact of result3.outputs.filter(({path:path3})=>!path3.endsWith(".map"))){runtimeFiles.push(yield*gen2(function*readBackendArtifact(){const relativePath=artifact.path.replace(/^\.\//u,"").replace(/^\/+/u,"");const rawCode=yield*tryPromise2(artifact.text.bind(artifact));const code=rawCode.replaceAll(/\/\/# (?:debugId|sourceMappingURL)=.*$/gmu,"");const bytes2=runtimeModuleBytes(code,"backend",relativePath);const mapArtifact=outputByName.get(`${nodePath2.basename(artifact.path)}.map`);const entryMatch=/^ci-release-backend-entry-(?<index>\d+)\.mjs$/u.exec(nodePath2.basename(artifact.path));const contributionFqn=entryMatch?.groups?.index===undefined?undefined:identities[Number(entryMatch.groups.index)]?.fqn;const sourceMapBytes=mapArtifact===undefined?undefined:sanitizeSourceMap(yield*tryPromise2(mapArtifact.text.bind(mapArtifact)),relativePath);return{bytes:bytes2,...contributionFqn===undefined?undefined:{contributionFqn},host:"backend",path:`artifacts/backend/${relativePath}`,...sourceMapBytes===undefined?undefined:{sourceMapBytes}}}))}return runtimeFiles}),runPromise2);var viteOutputList=(output)=>{if(!Array.isArray(output)&&"close"in output){throw new Error("Vite unexpectedly returned a watcher for a release build")}return Array.isArray(output)?output:[output]};var buildFrontend=flow((input)=>gen2(function*buildFrontendEffect(){const identities=contributionIdentities(input.definition,input.host);if(identities.length===0){return[]}const entries=new Map;const entryNames={};for(const[index,identity3]of identities.entries()){const id=`virtual:ci-release-${input.host}-entry-${index}`;const contributionImport=resolveHostedContributionEntry(input.declarationSpecifier,identity3);entries.set(`\x00${id}`,{contributionImport,identity:identity3,source:`export { ${moduleExport(identity3.exportName)} } from ${jsonString(contributionImport)}; export * from ${jsonString(contributionImport)}`});entryNames[`contribution-${index}`]=id}const virtualEntries={load:flow(function loadFrontendEntry(id){const resolve6=this.resolve.bind(this);return gen2(function*loadFrontendEntryEffect(){const entry=entries.get(id);if(entry===undefined){return null}const resolved=yield*promise2(flow(constant(entry.contributionImport),resolve6));if(resolved===null){return yield*die3(new Error(`Frontend catalog module could not be resolved: ${entry.contributionImport}`))}const file=Bun.file(resolved.id);const source=yield*promise2(file.text.bind(file));const{exports}=new Bun.Transpiler({loader:/\.[jt]sx$/u.test(resolved.id)?"tsx":"ts"}).scan(source);return exports.includes("default")?`${entry.source}; export { default } from ${jsonString(entry.contributionImport)}`:entry.source})},runPromise2),name:"ci-hosted-release-entries",resolveId:(id)=>id.startsWith("virtual:ci-release-")?`\x00${id}`:null};const stableRegionLabels={name:"ci-hosted-release-stable-region-labels",renderChunk:(code)=>stableFrontendChunk(code,input.host)};const hostReactRequireId="\x00virtual:ci-host-react-require";const hostReactRequire={enforce:"pre",load:(id)=>id===hostReactRequireId?'import React from "react"; module.exports = React;':null,name:"ci-host-react-require",resolveId:{handler:(source,_importer,options)=>source==="react"&&options.kind==="require-call"?hostReactRequireId:null,order:"pre"}};const output=yield*tryPromise2(viteBuild.bind(undefined,{build:{assetsInlineLimit:0,cssCodeSplit:true,emptyOutDir:false,minify:false,modulePreload:false,rolldownOptions:{input:entryNames,output:{assetFileNames:"assets/[name]-[hash][extname]",chunkFileNames:"chunks/[name]-[hash].mjs",entryFileNames:"modules/[name].mjs"},preserveEntrySignatures:"strict"},sourcemap:"hidden",target:"esnext",write:false},configFile:false,define:{"process.env.NODE_ENV":jsonString("production")},logLevel:"silent",mode:"production",oxc:{jsx:{development:false}},plugins:[virtualEntries,hostReactRequire,esmExternalRequirePlugin({external:[...hostProvidedModulesFor(input.host)]}),stableRegionLabels],resolve:workspaceSourceResolve(process.execArgv),root:process.cwd(),ssr:workspaceSourceSsrResolve(process.execArgv)})).pipe(catch_2((error)=>die3(error.cause instanceof Error?error.cause:new Error("Frontend catalog build failed",{cause:error.cause}))));const files=[];for(const result3 of viteOutputList(output)){for(const artifact of result3.output){if(artifact.type==="asset"){if(!artifact.fileName.endsWith(".map")){files.push({bytes:viteAssetBytes(artifact.source),host:input.host,path:`artifacts/${input.host}/${artifact.fileName}`})}continue}const entry=artifact.facadeModuleId===null?undefined:entries.get(artifact.facadeModuleId);const sourceMapBytes=artifact.map===null?undefined:sanitizeSourceMap(artifact.map.toString(),artifact.fileName);files.push({bytes:runtimeModuleBytes(artifact.code,input.host,artifact.fileName),...entry===undefined?undefined:{contributionFqn:entry.identity.fqn},host:input.host,path:`artifacts/${input.host}/${artifact.fileName}`,...sourceMapBytes===undefined?undefined:{sourceMapBytes}})}}return files}),runPromise2);var mergeCompatibility=(definition)=>{const compatibility={};for(const{manifest}of definition.hostedContributions){for(const[runtime,range]of Object.entries(manifest.compatibility??{})){const existing=compatibility[runtime];if(existing!==undefined&&existing!==range){throw new TypeError(`Hosted Contributions declare conflicting ${runtime} compatibility ranges`)}compatibility[runtime]=range}}return Object.fromEntries(Object.entries(compatibility).toSorted(([left],[right])=>compareCanonicalText(left,right)))};var buildPackageRelease=flow((input)=>gen2(function*buildPackageReleaseEffect(){const definitions=yield*promise2(loadPackageDeclarations.bind(undefined,input.declarationSpecifier));if(definitions.length!==1){throw new TypeError("An Extension Release build requires exactly one package")}const[definition]=definitions;if(definition===undefined){throw new TypeError("Extension Package declaration was not found")}const hostFiles=yield*all2([promise2(buildBackend.bind(undefined,{declarationSpecifier:input.declarationSpecifier,definition})),...FRONTEND_HOSTS.map((host)=>promise2(buildFrontend.bind(undefined,{declarationSpecifier:input.declarationSpecifier,definition,host})))]);const files=hostFiles.flat();const assets=[];const privateSourceMaps=[];const privateMapByRuntimeDigest=new Map;for(const file of files){const runtimeDigest=digest(file.bytes);const sourceMap=file.sourceMapBytes;const privateSourceMap=sourceMap===undefined?undefined:{digest:digest(sourceMap),size:sourceMap.byteLength};assets.push({digest:runtimeDigest,host:file.host,path:file.path,...privateSourceMap===undefined?undefined:{privateSourceMap},size:file.bytes.byteLength});if(sourceMap!==undefined&&privateSourceMap!==undefined){const existing=privateMapByRuntimeDigest.get(runtimeDigest);if(existing!==undefined&&existing.digest!==privateSourceMap.digest){throw new Error(`Runtime asset '${runtimeDigest}' produced conflicting private source maps`)}if(existing===undefined){const sidecar={bytes:sourceMap,digest:privateSourceMap.digest,runtimeAssetDigest:runtimeDigest,size:privateSourceMap.size};privateMapByRuntimeDigest.set(runtimeDigest,sidecar);privateSourceMaps.push(sidecar)}}}const assetByPath=new Map(assets.map((asset)=>[asset.path,asset]));const pathByContribution=new Map(files.flatMap((file)=>file.contributionFqn===undefined?[]:[[`${file.host}:${file.contributionFqn}`,file.path]]));const contributions=backendArtifactContributions(definition).map((contribution)=>{const assetPath=pathByContribution.get(`${contribution.host}:${contribution.fqn}`);const asset=assetPath===undefined?undefined:assetByPath.get(assetPath);if(asset===undefined||assetPath===undefined){throw new Error(`No release entry asset was built for ${contribution.fqn}`)}const common={assetPath,digest:asset.digest,exportName:contribution.exportName,fqn:contribution.fqn,size:asset.size};return contribution.host==="backend"?{...common,...contribution.contract===undefined?undefined:{contract:contribution.contract},...contribution.execution===undefined?undefined:{execution:contribution.execution},exportName:contribution.exportName,host:contribution.host}:{...common,contract:contribution.contract,exportName:contribution.exportName,host:contribution.host}});const packageManifestBytes=encoder2.encode(canonicalPackageManifest(definition));const archiveBytes=createExtensionReleaseArchive([...files.map(({bytes:bytes2,path:path3})=>({bytes:bytes2,path:path3})),{bytes:packageManifestBytes,path:"package-manifest.json"}]);const releaseDigest=digest(archiveBytes);const manifest={apiVersion:"v2",assets:assets.toSorted((left,right)=>compareCanonicalText(left.path,right.path)),compatibility:mergeCompatibility(definition),contributions:contributions.toSorted((left,right)=>compareCanonicalText(left.host,right.host)||compareCanonicalText(left.fqn,right.fqn)),package:{fqn:definition.manifest.fqn,version:definition.manifest.version},packageManifest:definition.manifest,releaseDigest};return{archiveBytes,manifest,manifestBytes:encoder2.encode(canonicalExtensionReleaseManifest(manifest)),packageManifest:definition.manifest,packageManifestBytes,privateSourceMaps:privateSourceMaps.toSorted((left,right)=>compareCanonicalText(left.runtimeAssetDigest,right.runtimeAssetDigest)),releaseDigest}}),runPromise2);var materializePackageRelease=flow((input,dependencies)=>gen2(function*materializePackageReleaseEffect(){const release=yield*promise2(buildPackageRelease.bind(undefined,{declarationSpecifier:input.declarationSpecifier}));const privateMapDirectory=nodePath2.join(input.outputDirectory,"private-source-maps");yield*writerEffect(dependencies.makeDirectory.bind(dependencies,privateMapDirectory));yield*all2([writerEffect(dependencies.writeBytes.bind(dependencies,nodePath2.join(input.outputDirectory,"release.tar"),release.archiveBytes)),writerEffect(dependencies.writeBytes.bind(dependencies,nodePath2.join(input.outputDirectory,"manifest.json"),release.manifestBytes)),writerEffect(dependencies.writeBytes.bind(dependencies,nodePath2.join(input.outputDirectory,"package-manifest.json"),release.packageManifestBytes)),...release.privateSourceMaps.map((sourceMap)=>writerEffect(dependencies.writeBytes.bind(dependencies,nodePath2.join(privateMapDirectory,`${sourceMap.runtimeAssetDigest}.map`),sourceMap.bytes)))]);return{archive:nodePath2.join(input.outputDirectory,"release.tar"),manifest:nodePath2.join(input.outputDirectory,"manifest.json"),packageManifest:nodePath2.join(input.outputDirectory,"package-manifest.json"),privateSourceMaps:privateMapDirectory,releaseDigest:release.releaseDigest}}),runPromise2);var optionValue3=(args2,name)=>{const index=args2.lastIndexOf(`--${name}`);const value3=index===-1?undefined:args2[index+1];if(value3===undefined||value3===""){throw new TypeError(`Missing option --${name}`)}return value3};var runPackageBuildCommand=flow((args2,dependencies)=>gen2(function*runPackageBuildCommandEffect(){const outputDirectory=optionValue3(args2,"out");const release=yield*promise2(materializePackageRelease.bind(undefined,{declarationSpecifier:dependencies.resolveDeclarationSpecifier(optionValue3(args2,"declaration")),outputDirectory},dependencies));return yield*encodeEffect(fromJsonString2(Unknown2))({archive:release.archive,manifest:release.manifest,packageManifest:release.packageManifest,privateSourceMaps:release.privateSourceMaps,releaseDigest:release.releaseDigest})}),runPromise2);class EventStreamHttpError extends Error{status;constructor(status,statusText){super(`Event stream request failed with HTTP ${status} ${statusText}`.trimEnd());this.name="EventStreamHttpError";this.status=status}}var singleConnectionSseOptions={onSseError:(cause)=>{throw cause},sseMaxRetryAttempts:1};var eventStreamFetch=(fetch2=globalThis.fetch)=>Object.assign(async(input,init)=>{const response=await fetch2(input,init);if(!response.ok){throw new EventStreamHttpError(response.status,response.statusText)}return response},{preconnect:()=>{}});var isRetryableEventStreamError=(cause)=>!(cause instanceof EventStreamHttpError)||cause.status>=500||cause.status===408||cause.status===425||cause.status===429;class EventStreamRetriesExhaustedError extends Error{attempts;lastEventId;constructor(input){super(input.cause===undefined?"Event stream kept closing without progress":"Event stream kept failing without progress",{cause:input.cause});this.name="EventStreamRetriesExhaustedError";this.attempts=input.attempts;this.lastEventId=input.lastEventId}}var DEFAULT_INITIAL_RETRY_DELAY_MS=1000;var DEFAULT_MAX_RETRY_DELAY_MS=30000;var DEFAULT_MIN_HEALTHY_CONNECTION_MS=30000;var abortableSleep=async(milliseconds,signal)=>{if(signal.aborted){return}await new Promise((resolve6)=>{const settled=new AbortController;const timeout3=globalThis.setTimeout(()=>{settled.abort();resolve6()},milliseconds);signal.addEventListener("abort",()=>{globalThis.clearTimeout(timeout3);resolve6()},{once:true,signal:settled.signal})})};var asError=(cause)=>cause instanceof Error?cause:new Error(String(cause),{cause});var followEventStream=async(options)=>{const signal=options.signal??new AbortController().signal;const sleep3=options.sleep??abortableSleep;const initialDelay=options.initialRetryDelayMs??DEFAULT_INITIAL_RETRY_DELAY_MS;const maxDelay=options.maxRetryDelayMs??DEFAULT_MAX_RETRY_DELAY_MS;const minHealthyConnectionMs=options.minHealthyConnectionMs??DEFAULT_MIN_HEALTHY_CONNECTION_MS;const now=options.now??Date.now;let{lastEventId}=options;let attempt=0;while(!signal.aborted){const connection3=new AbortController;const stopConnection=()=>{connection3.abort()};signal.addEventListener("abort",stopConnection,{once:true});let terminal=false;let failure;const openedAt=now();try{const events=await options.connect({lastEventId,signal:connection3.signal});for await(const event of events){await options.onEvent(event);const nextEventId=options.eventId===undefined?lastEventId:options.eventId(event);if(options.eventId===undefined||nextEventId!==lastEventId){attempt=0}lastEventId=nextEventId;if(options.isTerminal?.(event)===true){terminal=true;break}}}catch(error){failure=asError(error)}finally{signal.removeEventListener("abort",stopConnection);connection3.abort()}if(terminal){return{lastEventId,reason:"terminal"}}if(signal.aborted){break}if(failure!==undefined&&options.isRetryableError!==undefined&&!options.isRetryableError(failure)){throw failure}if(failure===undefined&&now()-openedAt>=minHealthyConnectionMs){attempt=0}attempt+=1;if(options.maxRetries!==undefined&&attempt>options.maxRetries){throw new EventStreamRetriesExhaustedError({attempts:attempt,cause:failure,lastEventId})}const delayMs=Math.min(initialDelay*2**(attempt-1),maxDelay);options.onReconnect?.({attempt,cause:failure,delayMs,lastEventId});await sleep3(delayMs,signal)}return{lastEventId,reason:"aborted"}};var awaitValue=(value3)=>promise2(constant(Promise.resolve(value3)));var encodeJson3=encodeSync(fromJsonString2(Unknown2));class PackageOperationCommandError extends TaggedError3()("PackageOperationCommandError",{cause:optional2(Unknown2),message:String4}){}var requireOption=(options,name)=>{const value3=options.get(name);if(value3===undefined||value3===""){throw new PackageOperationCommandError({message:`Missing required option --${name}`})}return value3};var parseOptions=(args2)=>{const options=new Map;for(let index=1;index<args2.length;index+=2){const flag=args2[index];const value3=args2[index+1];if(!flag?.startsWith("--")||!value3||value3.startsWith("--")){throw new PackageOperationCommandError({message:"Options must be supplied as --name value pairs"})}options.set(flag.slice(2),value3)}return options};var isPackageOperationComplete=(status)=>status!=="pending"&&status!=="running";var parseLastEventId=(options)=>{const value3=options.get("last-event-id")??"0";if(!/^\d+$/u.test(value3)){throw new PackageOperationCommandError({message:"--last-event-id must be a non-negative event sequence"})}const sequence=Number(value3);if(!Number.isSafeInteger(sequence)){throw new PackageOperationCommandError({message:"--last-event-id must be a non-negative event sequence"})}return sequence};var fetchSnapshot=flow((dependencies,organizationId,operationId,signal)=>gen2(function*nativeAssetStep1(){const request={client:dependencies.client,headers:{"x-organization-id":organizationId},path:{operationId},throwOnError:true};if(signal!==undefined){request.signal=signal}const response=yield*awaitValue(packageOperationsSnapshot(request));return decodePackageOperationSnapshot(response.data)}),runPromise2);var executeSnapshot=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageOperationCommandError)(cause)?cause:new PackageOperationCommandError({cause,message:"Could not inspect package operation"}),try:async()=>({kind:"snapshot",snapshot:await fetchSnapshot(dependencies,requireOption(options,"organization"),requireOption(options,"operation"))})});var executeContinuation=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageOperationCommandError)(cause)?cause:new PackageOperationCommandError({cause,message:"Could not continue package operation"}),try:async()=>{const accepted=await packageOperationsContinueOperation({client:dependencies.client,headers:{"idempotency-key":requireOption(options,"idempotency-key"),"x-organization-id":requireOption(options,"organization")},path:{operationId:requireOption(options,"operation")},throwOnError:true});return{kind:"operation_accepted",operationId:accepted.data.operationId}}});var MAX_RECONNECTS_WITHOUT_PROGRESS=3;var isCommandError=is2(PackageOperationCommandError);var decodeOperationEvent=(wireEvent)=>{try{return decodePackageOperationEvent(encodeJson3(wireEvent))}catch(error){throw new PackageOperationCommandError({cause:error,message:"Package operation event did not match the Backend contract"})}};var followPackageOperationEffect=(input,dependencies)=>tryPromise2({catch:(cause)=>isCommandError(cause)?cause:new PackageOperationCommandError({cause,message:"Could not reconnect to package operation"}),try:async(signal)=>{let lastSequence=input.afterSequence??0;const{operationId,organizationId}=input;const snapshot=await fetchSnapshot(dependencies,organizationId,operationId,signal);if(isPackageOperationComplete(snapshot.status)&&(input.replay!==true||lastSequence>=snapshot.lastEventSequence)){return{kind:"snapshot",snapshot}}let lastEventId=input.afterSequence===undefined?undefined:String(lastSequence);let observed;try{await followEventStream({connect:async(connection3)=>{const events=await packageOperationsEvents({...singleConnectionSseOptions,client:dependencies.client,fetch:eventStreamFetch(dependencies.client.getConfig().fetch),headers:{...connection3.lastEventId===undefined?undefined:{"last-event-id":connection3.lastEventId},"x-organization-id":organizationId},path:{operationId},signal:connection3.signal,throwOnError:true});return events.stream},eventId:()=>lastEventId,isRetryableError:(error)=>!isCommandError(error)&&isRetryableEventStreamError(error),isTerminal:()=>observed!==undefined&&observed.sequence===lastSequence&&isPackageOperationComplete(observed.status),...lastEventId===undefined?undefined:{lastEventId},maxRetries:MAX_RECONNECTS_WITHOUT_PROGRESS,onEvent:(wireEvent)=>{const event=decodeOperationEvent(wireEvent);observed=event;if(event.sequence<=lastSequence){return}if(event.sequence!==lastSequence+1){throw new PackageOperationCommandError({message:`Package operation event sequence jumped from ${lastSequence} to ${event.sequence}`})}dependencies.writeEvent(encodeJson3(event));lastSequence=event.sequence;lastEventId=String(event.sequence)},signal,...dependencies.sleep===undefined?undefined:{sleep:dependencies.sleep}})}catch(error){if(error instanceof EventStreamHttpError){throw new PackageOperationCommandError({cause:error,message:`Package operation event stream was rejected with HTTP ${error.status}`})}if(error instanceof EventStreamRetriesExhaustedError){throw new PackageOperationCommandError({cause:error.cause??error,message:`Package operation event stream disconnected; reconnect with --last-event-id ${lastSequence}`})}throw error}return{kind:"snapshot",snapshot:await fetchSnapshot(dependencies,organizationId,operationId,signal)}}});var packageOperationCommandEffect=(args2,dependencies)=>{const[command]=args2;const options=parseOptions(args2);if(command==="continue"){return executeContinuation(options,dependencies)}if(command==="reconnect"){return followPackageOperationEffect({afterSequence:options.has("last-event-id")?parseLastEventId(options):undefined,operationId:requireOption(options,"operation"),organizationId:requireOption(options,"organization"),replay:true},dependencies)}if(command==="snapshot"){return executeSnapshot(options,dependencies)}return fail6(new PackageOperationCommandError({message:"Expected one of: package operation snapshot, package operation reconnect, package operation continue"}))};var renderPin=(pin)=>`${pin.fqn}@${pin.releaseId}`;var renderSelection=(selection)=>selection===null?"none":`${selection.releaseId} generation ${selection.generation}`;var renderBlocker=(blocker)=>{if(blocker._tag==="manual_prerequisite"){const observed=blocker.observed===null?"none":renderPin(blocker.observed);return`Blocker ManualPrerequisite: ${blocker.message}; requires ${renderPin(blocker.required)}, observed ${observed}; path ${blocker.path.map(renderPin).join(" -> ")}`}let label=blocker._tag;if(blocker._tag==="authority_denied"){label=`AuthorityDenied (${blocker.boundary})`}else if(blocker._tag==="unknown"){label=blocker.tag}const details=[blocker.message,..."definitions"in blocker?[`definitions ${blocker.definitions.map((definition)=>`${definition.kind} ${definition.fqn}`).join(", ")}`]:[],...blocker.paths.map((path3)=>`path ${path3.join(" -> ")}`)];return`Blocker ${label}: ${details.join("; ")}`};var renderProtection=(protection)=>{if(protection.kind==="required_by"){return`requiredBy ${renderPin(protection.dependent)} (${protection.protection})`}if(protection.kind==="unknown_requirement"){return`unknownRequirement ${renderPin(protection.dependent)}`}if(protection.kind==="workflow_use"){const{template}=protection;return`workflowUse ${protection.workflowId} (${protection.state}, template ${template.fqn}@${template.version})`}if(protection.kind==="live_binding"){return`liveBinding ${protection.bindingKind} ${protection.id}`}return protection.kind};var renderCleanupCandidate=(candidate)=>{const subject=`Cleanup ${candidate.packageFqn}@${candidate.releaseId} (${candidate.installationId}) ${candidate.result}`;const protections=candidate.protections??[];return protections.length===0?`${subject}.`:`${subject}: ${protections.map(renderProtection).join("; ")}.`};var renderCleanup=(cleanup)=>[`Cleanup ${cleanup.state}.`,...cleanup.candidates.map(renderCleanupCandidate)];var renderHost=(host,snapshot)=>{const{member,observed}=host;const outcome=`Host ${member.packageFqn} (${member.installationId}) ${host.result}: expected ${member.releaseId} generation ${member.generation}; observed Desired ${renderSelection(observed.desired)}, Serving ${renderSelection(observed.serving)}.`;return host.diagnosticId===undefined?outcome:`${outcome} Diagnostic ID ${host.diagnosticId}: ci package diagnostics trace --organization ${snapshot.organizationId} --diagnostic ${host.diagnosticId}`};var renderNextAction=(snapshot)=>{const scope3=`--organization ${snapshot.organizationId} --operation ${snapshot.id}`;const continueCommand=`ci package operation continue ${scope3} --idempotency-key <key>`;const hints={continue:`continue. Start a linked new operation with a new Operation ID: ${continueCommand}`,none:"none.",retry:`retry. Resume this same operation with its accepted plan and Operation ID: ${continueCommand}`,wait:`wait. Follow progress: ci package operation reconnect ${scope3} --last-event-id ${snapshot.lastEventSequence}`};return`Next action: ${hints[snapshot.nextAction]}`};var renderPackageOperationSummary=(snapshot)=>{const{application,failure}=snapshot;const lines=[`Package operation ${snapshot.id} is ${snapshot.status}.`,...application.state==="not_applied"&&application.blocker!==undefined?[renderBlocker(application.blocker)]:[],...snapshot.hosts.map((host)=>renderHost(host,snapshot)),...snapshot.cleanup===undefined?[]:renderCleanup(snapshot.cleanup),...failure===undefined?[]:[`Failure ${failure.reason}: ${failure.message}`],renderNextAction(snapshot)];return`${lines.join(`
287
295
  `)}
288
296
  `};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(`
289
297
  `).length}:${E.e()-C.lastIndexOf(`
@@ -291,13 +299,13 @@ Defaulting to 2020, but this will stop working in the future.`)}options.ecmaVers
291
299
  `);const followed=await runFollower(followPackageOperationEffect({operationId,organizationId:options.organizationId},{client:client2,writeEvent:(event)=>{const decoded=decodePackageOperationEvent(event);lastEventId=decoded.sequence;writeProgress(`${JSON.stringify({...decoded,kind:"progress"})}
292
300
  `)}}),{signal});if(followed.kind!=="snapshot"||followed.snapshot.status!=="succeeded"){throw new DeployCommandError({json:options.json,lastEventId,message:followed.kind==="snapshot"?renderPackageOperationSummary(followed.snapshot).trim():"Deployment operation did not succeed",nextAction:followed.kind==="snapshot"?followed.snapshot.nextAction:undefined,operationId,status:followed.kind==="snapshot"?followed.snapshot.status:"accepted"})}};let exact=await lookup2();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);const declaredGateways=release.packageManifest.primitives.filter((primitive2)=>primitive2.kind==="externalAppGateway").map((primitive2)=>primitive2.fqn).toSorted();for(const fqn of Object.keys(options.gatewayUrls)){if(!declaredGateways.includes(fqn)){throw new DeployCommandError({json:options.json,message:`Unknown Gateway URL binding '${fqn}'`})}}gatewayUrls=Object.fromEntries(declaredGateways.map((fqn)=>{const value3=options.gatewayUrls[fqn]??existing?.gatewayUrls?.[fqn];if(value3===undefined){throw new DeployCommandError({json:options.json,message:`Missing required Gateway URL binding '${fqn}'`})}return[fqn,gatewayOrigin(value3,fqn,(message)=>{throw new DeployCommandError({json:options.json,message})})]}));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 lookup2();if(exact===null){throw new DeployCommandError({json:options.json,message:"Publication succeeded without the expected immutable release",operationId:accepted.operationId})}}if(exact.promotion.status==="unpromoted"){const accepted=await promotePackage({body:{protocolVersion:"v1",releaseId:exact.releaseId},client:dependencies.publisher,idempotencyKey:key("promote"),signal});await follow(accepted.operationId,dependencies.publisher)}const unchanged=setup===undefined&&existing!==undefined&&existing.servingReleaseId===exact.releaseId&&existing.desiredReleaseId===exact.releaseId&&existing.status==="installed"&&existing.error===null&&canonicalJson(existing.gatewayUrls??{})===canonicalJson(gatewayUrls);if(!unchanged){const intent={...setup===undefined?undefined:{setup},acceptBreakingChanges:options.acceptBreakingChanges,deploymentPolicy:"strict",gatewayUrls,releaseId:exact.releaseId};const accepted=existing===undefined?await installPackage({body:intent,client:dependencies.organization,idempotencyKey:key("install"),organizationId:options.organizationId,packageFqn:release.manifest.package.fqn,signal}):await updatePackage({body:{...intent,installationId:existing.id,protocolVersion:"v1"},client:dependencies.organization,idempotencyKey:key("update"),organizationId:options.organizationId,signal});await follow(accepted.operationId,dependencies.organization)}let action="unchanged";if(!unchanged){action=existing===undefined?"installed":"updated"}dependencies.writeOutput(options.json?`${JSON.stringify({action,kind:"result",packageFqn:release.manifest.package.fqn,releaseDigest:release.releaseDigest,releaseId:exact.releaseId,status:"succeeded"})}
293
301
  `:`Deployed ${release.manifest.package.fqn}@${release.manifest.package.version}: ${action} (${exact.releaseId})
294
- `)}}).pipe(timeoutOrElse2({duration:options.timeoutMs,orElse:()=>fail6(new DeployCommandError({json:options.json,lastEventId,message:"Deployment wait timed out; rerun the same exact deployment intent or reconnect to its operation",operationId,status:"timed_out"}))}))});class DoctorCommandError extends TaggedError3()("DoctorCommandError",{cause:optional2(Unknown2),message:String4}){}var doctorCommandEffect=(args2,dependencies)=>gen2(function*doctorCommand(){const options=yield*parseCommandOptionsEffect(args2,{repeatable:["redirect-uri"],values:[...targetOptions,"fqn"]});const context3=yield*resolveOrganizationContext({args:args2,environment:dependencies.environment,fetch:dependencies.fetch});const report=yield*runPreflight({context:context3,fetch:dependencies.fetch,fqn:optionValue2(options,"fqn"),redirectUris:optionValues(options,"redirect-uri")});dependencies.writeOutput(renderPreflight(report.checks));const failed=report.checks.filter((entry)=>!entry.passed).length;return yield*failed===0?void_3:fail6(new DoctorCommandError({message:`${failed} preflight check(s) failed`}))}).pipe(mapError2((cause)=>is2(DoctorCommandError)(cause)?cause:new DoctorCommandError({cause,message:cause.message})));class LoginCommandError extends TaggedError3()("LoginCommandError",{cause:optional2(Unknown2),message:String4}){}var usage2="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=(client2,deviceCode)=>managementData("CLI token exchange",authExchangeCliToken,{body:{device_code:deviceCode},client:client2}).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*pollForSession2(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=(args2,dependencies)=>gen2(function*loginCommand(){const options=yield*parseCommandOptionsEffect(args2,{positionals:1,switches:["no-browser"],values:["organization","profile"]});const[apiUrl]=options.positionals;if(apiUrl===undefined){return yield*new LoginCommandError({message:usage2})}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}
302
+ `)}}).pipe(timeoutOrElse2({duration:options.timeoutMs,orElse:()=>fail6(new DeployCommandError({json:options.json,lastEventId,message:"Deployment wait timed out; rerun the same exact deployment intent or reconnect to its operation",operationId,status:"timed_out"}))}))});class DoctorCommandError extends TaggedError3()("DoctorCommandError",{cause:optional2(Unknown2),message:String4}){}var doctorCommandEffect=(args2,dependencies)=>gen2(function*doctorCommand(){const options=yield*parseCommandOptionsEffect(args2,{repeatable:["redirect-uri"],values:[...targetOptions,"fqn"]});const context3=yield*resolveOrganizationContext({args:args2,environment:dependencies.environment,fetch:dependencies.fetch});const report=yield*runPreflight({context:context3,fetch:dependencies.fetch,fqn:optionValue2(options,"fqn"),redirectUris:optionValues(options,"redirect-uri")});dependencies.writeOutput(renderPreflight(report.checks));const failed=report.checks.filter((entry)=>!entry.passed).length;return yield*failed===0?void_3:fail6(new DoctorCommandError({message:`${failed} preflight check(s) failed`}))}).pipe(mapError2((cause)=>is2(DoctorCommandError)(cause)?cause:new DoctorCommandError({cause,message:cause.message})));class LoginCommandError extends TaggedError3()("LoginCommandError",{cause:optional2(Unknown2),message:String4}){}var usage3="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=(client2,deviceCode)=>managementData("CLI token exchange",authExchangeCliToken,{body:{device_code:deviceCode},client:client2}).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*pollForSession2(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=(args2,dependencies)=>gen2(function*loginCommand(){const options=yield*parseCommandOptionsEffect(args2,{positionals:1,switches:["no-browser"],values:["organization","profile"]});const[apiUrl]=options.positionals;if(apiUrl===undefined){return yield*new LoginCommandError({message:usage3})}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}
295
303
  `);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 identity3=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=identity3.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 ${identity3.email??identity3.id} (Profile ${name}${organizationId===undefined?"":`, Current Organization ${organizationId}`})
296
304
  `)})}).pipe(mapError2((cause)=>is2(LoginCommandError)(cause)?cause:new LoginCommandError({cause,message:cause.message})));class LogoutCommandError extends TaggedError3()("LogoutCommandError",{cause:optional2(Unknown2),message:String4}){}var logoutCommandEffect=(args2,dependencies)=>gen2(function*logoutCommand(){yield*parseCommandOptionsEffect(args2,{values:targetOptions});const selected=yield*tryConfiguration(()=>selectedProfile({args:args2,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:apiOrigin2,currentOrganizationId,session:latest})=>{const signedOut=currentOrganizationId===undefined?{apiOrigin:apiOrigin2}:{apiOrigin:apiOrigin2,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}
297
- `)})}).pipe(mapError2((cause)=>is2(LogoutCommandError)(cause)?cause:new LogoutCommandError({cause,message:cause.message})));class OrgsCommandError extends TaggedError3()("OrgsCommandError",{cause:optional2(Unknown2),message:String4}){}var usage3="Usage: ci orgs list | ci orgs use <organization-id>";var memberships=(args2,dependencies)=>gen2(function*readMemberships(){const target=yield*tryConfiguration(()=>resolveBackendManagementTarget({args:args2,environment:dependencies.environment,organizationLookup:true}));const response=yield*managementData("Organization membership read",authMeOrganizations,{client:makeBackendManagementClient({backendUrl:target.apiOrigin,fetch:dependencies.fetch,token:target.token})});return{organizations:response.data,target}});var orgsCommandEffect=(args2,dependencies)=>gen2(function*orgsCommand(){const[command,...rest]=args2;const options=yield*parseCommandOptionsEffect(rest,{positionals:command==="use"?1:0,values:targetOptions});if(command==="list"){const{organizations:organizations2,target}=yield*memberships(rest,dependencies);return yield*sync2(()=>{dependencies.writeOutput(organizations2.length===0?`No Organization memberships
305
+ `)})}).pipe(mapError2((cause)=>is2(LogoutCommandError)(cause)?cause:new LogoutCommandError({cause,message:cause.message})));class OrgsCommandError extends TaggedError3()("OrgsCommandError",{cause:optional2(Unknown2),message:String4}){}var usage4="Usage: ci orgs list | ci orgs use <organization-id>";var memberships=(args2,dependencies)=>gen2(function*readMemberships(){const target=yield*tryConfiguration(()=>resolveBackendManagementTarget({args:args2,environment:dependencies.environment,organizationLookup:true}));const response=yield*managementData("Organization membership read",authMeOrganizations,{client:makeBackendManagementClient({backendUrl:target.apiOrigin,fetch:dependencies.fetch,token:target.token})});return{organizations:response.data,target}});var orgsCommandEffect=(args2,dependencies)=>gen2(function*orgsCommand(){const[command,...rest]=args2;const options=yield*parseCommandOptionsEffect(rest,{positionals:command==="use"?1:0,values:targetOptions});if(command==="list"){const{organizations:organizations2,target}=yield*memberships(rest,dependencies);return yield*sync2(()=>{dependencies.writeOutput(organizations2.length===0?`No Organization memberships
298
306
  `:`${organizations2.map((organization2)=>`${organization2.id===target.organizationId?"*":" "} ${organization2.id} ${organization2.name} ${organization2.role}`).join(`
299
307
  `)}
300
- `)})}const[organizationId]=options.positionals;if(command!=="use"||organizationId===undefined){return yield*new OrgsCommandError({message:usage3})}const selected=yield*tryConfiguration(()=>selectedProfile({args:rest,environment:dependencies.environment}));if(selected===undefined){return yield*new OrgsCommandError({message:"ci orgs use stores the Current Organization in a CLI Profile; run ci login first"})}const{organizations}=yield*memberships(rest,dependencies);const organization=organizations.find((candidate)=>candidate.id===organizationId);if(organization===undefined){return yield*new OrgsCommandError({message:`Organization ${organizationId} is not one of your memberships; run ci orgs list`})}const updated=yield*tryConfiguration(()=>updateProfile(dependencies.environment,selected.name,(latest)=>({...latest,currentOrganizationId:organization.id})));if(updated===undefined){return yield*new OrgsCommandError({message:`CLI Profile ${selected.name} was removed; run ci login first`})}return yield*sync2(()=>{dependencies.writeOutput(`Current Organization of Profile ${selected.name}: ${organization.name} (${organization.id})
308
+ `)})}const[organizationId]=options.positionals;if(command!=="use"||organizationId===undefined){return yield*new OrgsCommandError({message:usage4})}const selected=yield*tryConfiguration(()=>selectedProfile({args:rest,environment:dependencies.environment}));if(selected===undefined){return yield*new OrgsCommandError({message:"ci orgs use stores the Current Organization in a CLI Profile; run ci login first"})}const{organizations}=yield*memberships(rest,dependencies);const organization=organizations.find((candidate)=>candidate.id===organizationId);if(organization===undefined){return yield*new OrgsCommandError({message:`Organization ${organizationId} is not one of your memberships; run ci orgs list`})}const updated=yield*tryConfiguration(()=>updateProfile(dependencies.environment,selected.name,(latest)=>({...latest,currentOrganizationId:organization.id})));if(updated===undefined){return yield*new OrgsCommandError({message:`CLI Profile ${selected.name} was removed; run ci login first`})}return yield*sync2(()=>{dependencies.writeOutput(`Current Organization of Profile ${selected.name}: ${organization.name} (${organization.id})
301
309
  `)})}).pipe(mapError2((cause)=>is2(OrgsCommandError)(cause)?cause:new OrgsCommandError({cause,message:cause.message})));import{fileURLToPath as fileURLToPath5}from"url";var awaitValue3=(value3)=>promise2(constant(Promise.resolve(value3)));var nodePath3=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=(declarationSpecifier2,identity3)=>{if(identity3.load===undefined){throw new Error("Package runtime entry has no hosted loader")}const loaderSource=Function.prototype.toString.call(identity3.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 '${identity3.contributionFqn}' load must be a direct literal lazy import`)}if(specifier.startsWith("file:")){return fileURLToPath5(specifier)}if(specifier.startsWith("/")){if(!declarationSpecifier2.startsWith("file:")){throw new TypeError(`Backend Contribution '${identity3.contributionFqn}' root-relative load requires a file declaration`)}const declarationDirectory=nodePath3.dirname(fileURLToPath5(declarationSpecifier2));const workspaceCandidate=nodePath3.resolve(process.cwd(),specifier.slice(1));const workspaceRelation=nodePath3.relative(declarationDirectory,workspaceCandidate);return workspaceRelation!==""&&!workspaceRelation.startsWith("..")&&!nodePath3.isAbsolute(workspaceRelation)?workspaceCandidate:nodePath3.resolve(declarationDirectory,specifier.slice(1))}if(specifier.startsWith(".")){if(!declarationSpecifier2.startsWith("file:")){throw new TypeError(`Backend Contribution '${identity3.contributionFqn}' relative load requires a file declaration`)}return nodePath3.resolve(nodePath3.dirname(fileURLToPath5(declarationSpecifier2)),specifier)}return specifier};var entrySource=(identity3)=>`export { ${moduleExport2(identity3.exportName)} } from "ci-backend-contribution"`;var localModulePath=(specifier,identity3)=>{if(!nodePath3.isAbsolute(specifier)){return specifier}try{return Bun.resolveSync(specifier,nodePath3.dirname(specifier))}catch(error){throw new TypeError(`Backend Contribution '${identity3.contributionFqn}' module could not be resolved: ${specifier}`,{cause:error})}};var isSourceMapDocument=(value3)=>value3!==null&&typeof value3==="object"&&("sources"in value3)&&Array.isArray(value3.sources)&&value3.sources.every((source)=>typeof source==="string")&&("sourcesContent"in value3)&&Array.isArray(value3.sourcesContent)&&value3.sourcesContent.every((source)=>source===null||typeof source==="string");var sanitizeSourceMap2=(rawSourceMap,identity3)=>{const parsed=JSON.parse(rawSourceMap);if(!isSourceMapDocument(parsed)){throw new Error(`Bun emitted an invalid source map for '${identity3.contributionFqn}'`)}if(parsed.sources.length!==parsed.sourcesContent.length){throw new Error(`Bun emitted an incomplete source map for '${identity3.contributionFqn}'`)}const sourceNamespace=encodeURIComponent(identity3.contributionFqn);return JSON.stringify({...parsed,file:`${sourceNamespace}.mjs`,sourceRoot:"",sources:parsed.sources.map((_source,index)=>`extension://${sourceNamespace}/source-${index}.ts`)})};var buildContribution=flow((declarationSpecifier2,identity3)=>gen2(function*buildAsset(){const contributionImport=identity3.load===undefined?undefined:localModulePath(literalLazyImport2(declarationSpecifier2,identity3),identity3);const entrypoint=`ci-backend-entry:${encodeURIComponent(`${identity3.packageFqn}:${identity3.contributionFqn}`)}`;const result3=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(declarationSpecifier2,identity3.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:identity3.load===undefined?backendPackageEntrySource(identity3.packageFqn):entrySource(identity3),loader:"ts",resolveDir:import.meta.dir}))}}],sourcemap:"external",target:"bun"})));if(!result3.success){throw new AggregateError(result3.logs,`Failed to build Backend Contribution '${identity3.contributionFqn}'`)}const codeArtifact=result3.outputs.find(({path:artifactPath})=>!artifactPath.endsWith(".map"));const mapArtifact=result3.outputs.find(({path:artifactPath})=>artifactPath.endsWith(".map"));if(codeArtifact===undefined||mapArtifact===undefined){throw new Error(`Bun did not emit code and source map for '${identity3.contributionFqn}'`)}const sourceMap=sanitizeSourceMap2(yield*suspend2(()=>awaitValue3(mapArtifact.text())),identity3);const rawBuiltCode=yield*suspend2(()=>awaitValue3(codeArtifact.text()));const builtCode=rawBuiltCode.replaceAll(/\/\/# sourceMappingURL=.*$/gmu,"");return{code:`${builtCode.trimEnd()}
302
310
  `,contributionFqn:identity3.contributionFqn,exportName:identity3.exportName,packageFqn:identity3.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((identity3)=>suspend2(()=>awaitValue3(buildContribution(input.declarationSpecifier,identity3))),runPromise2))))}),runPromise2);var awaitValue4=(value3)=>promise2(constant(Promise.resolve(value3)));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 bytes2=new Uint8Array(16);crypto.getRandomValues(bytes2);bytes2[6]=bytes2[6]%16+64;bytes2[8]=bytes2[8]%64+128;const hex=[...bytes2].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=(value3)=>promise2(constant(Promise.resolve(value3)));var developmentHeartbeatIntervalMs=5000;var ownedRetryInitialMs=1000;var ownedRetryMaxMs=5000;var systemDevelopmentClock={repeatEvery:(intervalMs,tick)=>{const fiber2=runFork2(promise2(tick).pipe(delay2(intervalMs),forever2));return()=>{runFork2(interrupt2(fiber2))}},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=(evaluate2)=>tryPromise2({catch:(cause)=>new RuntimeRefreshError({cause,message:cause instanceof Error?cause.message:String(cause)}),try:()=>evaluate2()});var effectPromise=(evaluate2)=>gen2(function*nativeRuntimeStep1(){yield*awaitValue5(Promise.resolve());return yield*awaitValue5(evaluate2())});var assertLoopbackAsset=(value3)=>{const url=new URL(value3);if(url.protocol!=="http:"&&url.protocol!=="https:"||url.hostname!=="127.0.0.1"&&url.hostname!=="::1"&&url.hostname!=="localhost"){throw new TypeError("Development assets must use loopback HTTP URLs")}};var validateAssets=(assets)=>{for(const asset of assets){assertLoopbackAsset(asset.moduleUrl);if(asset.sourceMapUrl!==undefined){assertLoopbackAsset(asset.sourceMapUrl)}}return assets};var assertUniquePackageFqns=(declarations)=>{const packageFqns=new Set;for(const definition of declarations){const packageFqn=definition.manifest.fqn;if(packageFqns.has(packageFqn)){throw new TypeError(`Duplicate Extension Package FQN: ${packageFqn}`)}packageFqns.add(packageFqn)}};var traverse=forEach2;var settleQueue=flow((current2)=>tryPromise2(()=>current2).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 run2=flow(()=>gen2(function*nativeRuntimeStep4(){yield*awaitValue5(previous);return yield*awaitValue5(work()).pipe(asVoid2)}),runPromise2);const current2=run2();queue=settleQueue(current2);return yield*awaitValue5(current2).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)}
303
311
  ${canonicalJson(assets)}`;if(graphSignatures.get(packageFqn)===signature){return yield*void_3}const publish=(sessionId)=>attempt(()=>dependencies.updateLocalManifest({hostedContributions:assets,sessionId}));const stale=session;const updated=yield*publish(stale.sessionId).pipe(catchIf2(isSessionNotFound,()=>gen2(function*recreateForgottenSession(){forget(packageFqn,stale.sessionId);const replacement=yield*createSession(packageFqn);sessions.set(packageFqn,replacement);return yield*publish(replacement.sessionId)})),mapError2((failure)=>failure.cause),orDie2);sessions.set(packageFqn,updated);graphSignatures.set(packageFqn,signature);return yield*void_3});const recoverSessions=flow((missing2)=>suspend2(()=>awaitValue5(serialized(flow(()=>gen2(function*nativeRuntimeStep5(){for(const{packageFqn,sessionId}of missing2){forget(packageFqn,sessionId)}const missingFqns=new Set(missing2.map(({packageFqn})=>packageFqn));return yield*gen2(function*resynchronizeMissingSessions(){for(const definition of latestDeclarations){if(missingFqns.has(definition.manifest.fqn)){yield*synchronizePackage(definition)}}}).pipe(asVoid2)}),runPromise2)))).pipe(asVoid2),runPromise2);const heartbeat=dependencies.heartbeatDevelopmentSession;let beating=false;const heartbeatRound=flow(()=>suspend2(()=>{if(heartbeat===undefined||closed||beating){return void_3}beating=true;return gen2(function*heartbeatRoundEffect(){const results2=yield*traverse([...sessions],([packageFqn,{sessionId}])=>attempt(()=>heartbeat(sessionId)).pipe(as2([]),catch_2((error)=>{if(isSessionNotFound(error)){return succeed6([{packageFqn,sessionId}])}report(`Development session heartbeat failed for ${packageFqn}: ${messageOf(error)}`);return succeed6([])})),{concurrency:"unbounded"});const missing2=results2.flat();if(missing2.length>0&&!closed){yield*awaitValue5(recoverSessions(missing2))}}).pipe(catchCause2((cause)=>sync2(()=>{const error=squash(cause);report(`Could not re-create development session: ${messageOf(error instanceof Error?error:{message:String(error)})}`)})),ensuring2(sync2(()=>{beating=false})))}),runPromise2);const stopHeartbeat=heartbeat===undefined?null:clock.repeatEvery(developmentHeartbeatIntervalMs,heartbeatRound);const close3=flow(()=>gen2(function*closeRuntime(){closed=true;stopHeartbeat?.();closedSignal.resolve(null);yield*suspend2(()=>awaitValue5(queue)).pipe(asVoid2);const activeSessions=[...sessions.values()];sessions.clear();yield*suspend2(()=>awaitValue5(Promise.all(activeSessions.map(({sessionId})=>dependencies.terminateDevelopmentSession(sessionId)))))}),runPromise2);const refresh=flow((declarations)=>suspend2(()=>awaitValue5(serialized(flow(()=>gen2(function*refreshRuntime(){assertUniquePackageFqns(declarations);latestDeclarations=declarations;const declaredPackageFqns=new Set(declarations.map(({manifest})=>manifest.fqn));for(const[packageFqn,session]of sessions){if(declaredPackageFqns.has(packageFqn)){continue}yield*effectPromise(()=>dependencies.terminateDevelopmentSession(session.sessionId));sessions.delete(packageFqn);graphSignatures.delete(packageFqn)}for(const definition of declarations){yield*synchronizePackage(definition)}}),runPromise2)))).pipe(asVoid2),runPromise2);return yield*gen2(function*startRuntime(){yield*tryPromise2({catch:(error)=>new RuntimeRefreshError({cause:error,message:error instanceof Error?error.message:"Package development refresh failed"}),try:()=>refresh(input.declarations)}).pipe(tapError2(()=>suspend2(()=>awaitValue5(close3())).pipe(asVoid2)));return{close:close3,refresh,sessions:()=>[...sessions.values()]}})}),runPromise2);var awaitValue6=(value3)=>promise2(constant(Promise.resolve(value3)));var runNested=runPromiseWith2(empty());var cleanupAll=flow((steps,timeoutMs)=>gen2(function*cleanResources(){const failures=[];for(const step of steps){const result3=yield*tryPromise2(flow(()=>suspend2(()=>awaitValue6(step.run())).pipe(asVoid2),runPromise2)).pipe(timeout2(timeoutMs),result2);if(result3._tag==="Failure"){failures.push(new Error(`${step.name} cleanup failed`,{cause:result3.failure}))}}if(failures.length>0){throw new AggregateError(failures,"Development cleanup failed")}}),runNested);var isRuntimeRefreshFailure=(error)=>("_tag"in error)&&error._tag==="RuntimeRefreshError"&&("cause"in error);var rethrowRuntimeRefreshCause=(cause)=>{const dieReason=cause.reasons.find(isDieReason2);if(dieReason===undefined){return failCause3(cause)}const{defect}=dieReason;return die3(defect instanceof Error&&isRuntimeRefreshFailure(defect)?defect.cause:defect)};var startPackageDevelopmentProcess=flow((input,dependencies)=>gen2(function*startProcess(){const cleanupTimeoutMs=input.cleanupTimeoutMs??1000;if(!Number.isFinite(cleanupTimeoutMs)||cleanupTimeoutMs<=0||cleanupTimeoutMs>30000){throw new RangeError("cleanupTimeoutMs must be positive and at most 30000")}let stopped=false;const heartbeat=dependencies.heartbeatDevelopmentSession;const declarations=yield*suspend2(()=>awaitValue6(dependencies.loadDeclarations(input.declarationSpecifier)));assertUniquePackageFqns(declarations);const assetInput={declarationSpecifier:input.declarationSpecifier,declarations,hostOrigins:input.hostOrigins};const assets=yield*suspend2(()=>awaitValue6(dependencies.startAssets(assetInput)));const frontendCleanup={name:"frontend",run:flow(()=>suspend2(()=>awaitValue6(assets.close())).pipe(asVoid2),runPromise2)};const backendAssets=yield*suspend2(()=>awaitValue6((dependencies.startBackendAssets??startBackendDevelopmentAssetServer)(assetInput))).pipe(tapDefect2(()=>suspend2(()=>awaitValue6(cleanupAll([frontendCleanup],cleanupTimeoutMs))).pipe(asVoid2)));const assetCleanup=[{name:"backend",run:flow(()=>suspend2(()=>awaitValue6(backendAssets.close())).pipe(asVoid2),runPromise2)},frontendCleanup];const runtime=yield*suspend2(()=>awaitValue6(startPackageDevelopmentRuntime({declarations,hostOrigins:input.hostOrigins},{assetsFor:flow((definition)=>gen2(function*nativeProcessStep1(){const[frontend,backend]=yield*awaitValue6(Promise.all([assets.assetsFor(definition),backendAssets.assetsFor(definition)]));return[...frontend,...backend]}),runPromise2),clock:dependencies.clock,createDevelopmentSession:flow((request)=>gen2(function*createSession(){if(stopped){throw new Error("Development process is closed")}const session=yield*suspend2(()=>awaitValue6(dependencies.createDevelopmentSession(request)));if(stopped){yield*suspend2(()=>awaitValue6(cleanupAll([{name:"late session",run:flow(()=>suspend2(()=>awaitValue6(dependencies.terminateDevelopmentSession(session.sessionId))).pipe(asVoid2),runPromise2)}],cleanupTimeoutMs))).pipe(asVoid2);throw new Error("Development process is closed")}return session}),runNested),heartbeatDevelopmentSession:heartbeat===undefined?undefined:flow((sessionId)=>gen2(function*nativeProcessStep2(){if(!stopped){yield*awaitValue6(heartbeat(sessionId))}}),runPromise2),reportWarning:dependencies.reportWarning,terminateDevelopmentSession:flow((sessionId)=>tryPromise2(flow(()=>suspend2(()=>awaitValue6(dependencies.terminateDevelopmentSession(sessionId))).pipe(asVoid2),runPromise2)).pipe(timeout2(cleanupTimeoutMs),orDie2),runNested),updateLocalManifest:flow((request)=>gen2(function*publishManifest(){if(stopped){throw new Error("Development process is closed")}const session=yield*suspend2(()=>awaitValue6(dependencies.updateLocalManifest(request)));if(stopped){throw new Error("Development process is closed")}return session}),runNested)}))).pipe(tapDefect2(()=>suspend2(()=>awaitValue6(cleanupAll(assetCleanup,cleanupTimeoutMs))).pipe(asVoid2)));let refreshQueue=Promise.resolve();const refresh=flow(()=>gen2(function*nativeProcessStep3(){if(stopped){return yield*void_3}const previous=refreshQueue;refreshQueue=runNested(gen2(function*refreshProcess(){yield*tryPromise2(flow(()=>suspend2(()=>awaitValue6(previous)).pipe(asVoid2),runPromise2)).pipe(ignore2);if(stopped){return yield*void_3}const refreshed=yield*suspend2(()=>awaitValue6(dependencies.loadDeclarations(input.declarationSpecifier)));if(stopped){return yield*void_3}assertUniquePackageFqns(refreshed);yield*suspend2(()=>awaitValue6(assets.rebuild(refreshed))).pipe(asVoid2);if(stopped){return yield*void_3}yield*suspend2(()=>awaitValue6(backendAssets.rebuild(refreshed))).pipe(asVoid2);if(stopped){return yield*void_3}return yield*suspend2(()=>awaitValue6(runtime.refresh(refreshed))).pipe(asVoid2)}));return yield*awaitValue6(refreshQueue).pipe(asVoid2)}),runPromise2);const runtimeCleanup=[{name:"sessions",run:flow(()=>suspend2(()=>awaitValue6(runtime.close())).pipe(asVoid2),runPromise2)},...assetCleanup];const watcher=yield*sync2(()=>dependencies.watchDeclaration(input.declarationSpecifier,refresh)).pipe(tapDefect2(()=>{stopped=true;return suspend2(()=>awaitValue6(cleanupAll(runtimeCleanup,cleanupTimeoutMs))).pipe(asVoid2)}));let closing;return{close:flow(()=>gen2(function*nativeProcessStep4(){stopped=true;closing??=cleanupAll([{name:"watcher",run:flow(()=>suspend2(()=>awaitValue6(watcher.close())).pipe(asVoid2),runPromise2)},{name:"refresh",run:flow(()=>tryPromise2(flow(()=>suspend2(()=>awaitValue6(refreshQueue)).pipe(asVoid2),runPromise2)).pipe(ignore2),runNested)},...runtimeCleanup],cleanupTimeoutMs);return yield*awaitValue6(closing).pipe(asVoid2)}),runPromise2),sessions:runtime.sessions}}).pipe(catchCause2(rethrowRuntimeRefreshCause)),runPromise2);class PackageDevelopmentCommandError extends TaggedError3()("PackageDevelopmentCommandError",{cause:optional2(Unknown2),message:String4}){}var packageDevelopmentFailureMessage=(cause)=>{if(is2(TaggedStruct("Forbidden",{}))(cause)){return"Package development failed: Forbidden. Possible causes include disabled extension development on the dedicated development backend (check APP_EXTENSIONS_DEVELOPMENT_ENABLED=true), or missing human tenant-admin / organization permissions. The backend did not identify which check failed."}return cause instanceof Error?cause.message:"Package development failed"};var packageDevelopmentError=(cause)=>is2(PackageDevelopmentCommandError)(cause)?cause:new PackageDevelopmentCommandError({cause,message:packageDevelopmentFailureMessage(cause)});var parsePackageDevelopmentOptions=(args2)=>{const[command,...options]=args2;if(command!=="dev"){throw new PackageDevelopmentCommandError({message:"Expected package dev"})}let declaration;const hostOrigins=[];for(let index=0;index<options.length;index+=2){const flag=options[index];const value3=options[index+1];if(!flag?.startsWith("--")||value3===undefined||value3.startsWith("--")){throw new PackageDevelopmentCommandError({message:"Options must be supplied as --name value pairs"})}switch(flag){case"--declaration":{declaration=value3;break}case"--host-origin":{hostOrigins.push(value3);break}default:{throw new PackageDevelopmentCommandError({message:`Unknown option ${flag}`})}}}if(declaration===undefined||declaration.trim()===""){throw new PackageDevelopmentCommandError({message:"Missing option --declaration"})}if(hostOrigins.length===0){throw new PackageDevelopmentCommandError({message:"At least one --host-origin must be explicitly attached"})}return{declaration,hostOrigins}};var packageDevelopmentCommandEffect=(args2,dependencies)=>tryPromise2({catch:packageDevelopmentError,try:async()=>{const options=parsePackageDevelopmentOptions(args2);const declarationSpecifier2=dependencies.resolveDeclarationSpecifier(options.declaration);const processRuntime=await startPackageDevelopmentProcess({declarationSpecifier:declarationSpecifier2,hostOrigins:options.hostOrigins},dependencies);try{dependencies.writeResult(await runPromise2(encodeEffect(fromJsonString2(Unknown2))(processRuntime.sessions().length===1?processRuntime.sessions()[0]:processRuntime.sessions())));await dependencies.awaitTermination()}finally{await processRuntime.close()}}});init_sharedKeyMatcher_Od_nYxJA();init_logger_DOwfTlw5();init_dtsConstants_r5OfegUr();init_dist();import{createRequire as createRequire3}from"module";import*as fs$2 from"fs";import{existsSync as existsSync7,readFileSync as readFileSync5,readdirSync as readdirSync3,realpathSync as realpathSync3,statSync,writeFileSync as writeFileSync4}from"fs";import{createRequire as createRequire$12,isBuiltin}from"module";import*as path$14 from"path";import path10,{basename as basename2}from"path";import{fileURLToPath as fileURLToPath10,pathToFileURL as pathToFileURL4}from"url";import*as vite from"vite";import{parseAst as parseAst2,version as version3}from"vite";import{createHash as createHash5}from"crypto";import*as fs$12 from"fs";import{existsSync as existsSync$1,readFileSync as readFileSync$1}from"fs";import{pathToFileURL as pathToFileURL$1}from"url";import{isIPv6}from"net";import{readFile as readFile5}from"fs/promises";var __filename="/home/runner/_work/ci-app/ci-app/node_modules/.bun/@module-federation+vite@1.23.2+6a86219a8e049704/node_modules/@module-federation/vite/lib/index.js";var REGEXP_SPECIAL_CHARS_RE=/[.*+?^${}()|[\]\\]/g;function escapeRegExp(value3){return value3.replace(REGEXP_SPECIAL_CHARS_RE,"\\$&")}function isOutputChunk$1(chunk){return chunk.type==="chunk"}function isIdentifierReferenced(name,code){return new RegExp(`(?<![$\\w])${escapeRegExp(name)}(?![$\\w])`).test(code)}function getProxyBaseName(fileName){return fileName.replace(/^.*\//,"").replace(/\.js$/,"").replace(/-[A-Za-z0-9_-]+$/,"")}function functionDeclarationRegExp(name){return new RegExp(`function\\s+${escapeRegExp(name)}\\s*\\(`)}function extractFunctionDeclaration(code,functionName){const funcRe=new RegExp(`function\\s+${escapeRegExp(functionName)}\\s*\\([^)]*\\)\\s*\\{`);const funcStart=code.search(funcRe);if(funcStart<0)return;let depth=0;for(let i2=code.indexOf("{",funcStart);i2<code.length;i2++)if(code[i2]==="{")depth++;else if(code[i2]==="}"){depth--;if(depth===0)return code.slice(funcStart,i2+1)}}function resolveProxyAlias(binding,proxyLocal,code,fullImport,claimedLocals=new Set){const codeWithoutImport=code.replace(fullImport,"");const localUsedInCode=isIdentifierReferenced(binding.local,codeWithoutImport);const claimedImportLocals=new Set;const importRe=/import\s*\{([^}]+)\}\s*from\s*["'][^"']+["']\s*;?/g;let match5;while((match5=importRe.exec(codeWithoutImport))!==null)for(const spec of match5[1].split(",")){const parts2=spec.trim().split(/\s+as\s+/);claimedImportLocals.add((parts2[1]||parts2[0]).trim())}const local=!localUsedInCode&&!claimedLocals.has(proxyLocal)&&!claimedImportLocals.has(proxyLocal)?proxyLocal:binding.local;return{imported:binding.imported,local}}function collectLoadShareProxyChunks(bundle,loadShareTag){const proxyChunks=new Map;for(const[fileName,chunk]of Object.entries(bundle)){if(!isOutputChunk$1(chunk))continue;if(fileName.includes(loadShareTag)&&fileName.includes("commonjs-proxy"))proxyChunks.set(fileName,{code:chunk.code,fileName})}return proxyChunks}function collectSystemProxyInfos(proxyChunks,loadShareTag){const systemProxyInfo=new Map;for(const[proxyFileName,proxyInfo]of Array.from(proxyChunks.entries())){const depsMatch=proxyInfo.code.match(/System\.register\(\[([\s\S]*?)\]/);if(!depsMatch)continue;const loadShareDep=Array.from(depsMatch[1].matchAll(/["']([^"']+)["']/g)).map((m)=>m[1]).find((dep)=>dep.includes(loadShareTag)&&!dep.includes("commonjs-proxy"));if(!loadShareDep)continue;const loadShareBindings={};for(const m of proxyInfo.code.matchAll(/([A-Za-z_$][\w$]*)\s*=\s*module\d+\.([A-Za-z_$][\w$]*)/g))loadShareBindings[m[1]]=m[2];const exportMap={};const objectExportMatch=proxyInfo.code.match(/exports\(\s*\{([\s\S]*?)\}\s*\)/);if(objectExportMatch)for(const m of objectExportMatch[1].matchAll(/([A-Za-z_$][\w$]*)\s*:\s*([A-Za-z_$][\w$]*)/g)){const[,exported,local]=m;const funcBody=extractFunctionDeclaration(proxyInfo.code,local);if(funcBody)exportMap[exported]={type:"helper",code:funcBody}}for(const m of proxyInfo.code.matchAll(/exports\(\s*["']([^"']+)["']\s*,([\s\S]*?)\);/g)){const exported=m[1];const expression=m[2];for(const[local,exportName]of Object.entries(loadShareBindings).reverse())if(isIdentifierReferenced(local,expression)){exportMap[exported]={type:"reexport",exportName};break}}if(Object.keys(exportMap).length>0)systemProxyInfo.set(proxyFileName,{loadShareDep,exportMap})}return systemProxyInfo}function rewriteEsmProxyConsumers(code,proxyChunks){let nextCode=code;const claimedLocals=new Set;for(const[proxyFileName,proxyInfo]of Array.from(proxyChunks.entries())){const proxyBaseName=getProxyBaseName(proxyFileName);const importMatch=new RegExp(`import\\s*\\{([^}]+)\\}\\s*from\\s*["']([^"']*${escapeRegExp(proxyBaseName)}[^"']*)["']\\s*;?`).exec(nextCode);if(!importMatch)continue;const fullImport=importMatch[0];const bindings=importMatch[1].split(",").map((s)=>{const parts2=s.trim().split(/\s+as\s+/);return{imported:parts2[0].trim(),local:(parts2[1]||parts2[0]).trim()}});const exportMapMatch=proxyInfo.code.match(/export\s*\{([^}]+)\}/);if(!exportMapMatch)continue;const exportMap={};for(const entry of exportMapMatch[1].split(",")){const parts2=entry.trim().split(/\s+as\s+/);if(parts2.length===2)exportMap[parts2[1].trim()]=parts2[0].trim()}const inlineable=[];const nonInlineable=[];const pendingLocals=new Set(bindings.map((binding)=>binding.local));for(const b of bindings){pendingLocals.delete(b.local);const proxyLocal=exportMap[b.imported];if(!proxyLocal){claimedLocals.add(b.local);nonInlineable.push(b);continue}const funcBody=extractFunctionDeclaration(proxyInfo.code,proxyLocal);if(funcBody){inlineable.push({local:b.local,funcBody:funcBody.replace(functionDeclarationRegExp(proxyLocal),()=>`function ${b.local}(`)});claimedLocals.add(b.local)}else{const unavailableLocals=new Set(claimedLocals);pendingLocals.forEach((local)=>unavailableLocals.add(local));const resolvedBinding=resolveProxyAlias(b,proxyLocal,nextCode,fullImport,unavailableLocals);claimedLocals.add(resolvedBinding.local);nonInlineable.push(resolvedBinding)}}const hasRenamedAlias=nonInlineable.some((b)=>bindings.find((ob)=>ob.imported===b.imported)?.local!==b.local);if(inlineable.length===0&&!hasRenamedAlias)continue;let replacement="";if(nonInlineable.length>0)replacement=`import{${nonInlineable.map((b)=>b.imported===b.local?b.imported:`${b.imported} as ${b.local}`).join(",")}}from"${importMatch[2]}";`;replacement+=inlineable.map((f)=>f.funcBody).join("");nextCode=nextCode.replace(fullImport,()=>replacement)}return nextCode}function rewriteSystemProxyConsumers(code,systemProxyInfo){if(!code.includes("System.register("))return code;let nextCode=code;for(const[proxyFileName,proxyInfo]of Array.from(systemProxyInfo.entries())){const proxyBaseName=getProxyBaseName(proxyFileName);const depMatch=new RegExp(`["']([^"']*${escapeRegExp(proxyBaseName)}[^"']*)["']`).exec(nextCode);if(!depMatch)continue;let setterIndex=0;const depListMatch=nextCode.match(/System\.register\(\[([\s\S]*?)\]/);if(depListMatch)setterIndex=Array.from(depListMatch[1].matchAll(/["']([^"']+)["']/g)).map((m)=>m[1]).findIndex((dep)=>dep.includes(proxyBaseName));if(setterIndex<0)continue;const settersStart=nextCode.indexOf("setters: [");if(settersStart<0)continue;const setterMatch=Array.from(nextCode.slice(settersStart).matchAll(/\((module\d+)\)\s*=>\s*\{([\s\S]*?)\}/g))[setterIndex];if(!setterMatch)continue;const[fullSetter,moduleLocal,setterBody]=setterMatch;const helpersToInline=[];const nextSetterBody=setterBody.replace(new RegExp(`([A-Za-z_$][\\w$]*)\\s*=\\s*${moduleLocal}\\.([A-Za-z_$][\\w$]*);?`,"g"),(assignment2,local,imported)=>{const mapped=proxyInfo.exportMap[imported];if(!mapped)return assignment2;if(mapped.type==="helper"){helpersToInline.push(mapped.code.replace(functionDeclarationRegExp(imported),()=>`function ${local}(`));return""}return`${local} = ${moduleLocal}.${mapped.exportName};`});if(nextSetterBody===setterBody&&helpersToInline.length===0)continue;const nextSetter=fullSetter.replace(setterBody,()=>nextSetterBody);nextCode=nextCode.replace(fullSetter,()=>nextSetter);nextCode=nextCode.replace(depMatch[0],JSON.stringify(proxyInfo.loadShareDep));if(helpersToInline.length>0)nextCode=nextCode.replace("execute: (function() {",()=>{return`execute: (function() {${helpersToInline.join("")}`})}return nextCode}function findRemoteEntryFile(filename,bundle){const strippedName=filename.replace(/[\[\]]/g,"_").replace(/\.[^/.]+$/,"");let fallback;for(const fileData of Object.values(bundle)){if(fileData.fileName===filename)return fileData.fileName;if(fallback===undefined&&(strippedName===fileData.name||fileData.name==="remoteEntry"))fallback=fileData.fileName}return fallback}async function mapCodeToCodeWithSourcemap(code){const resolvedCode=await code;if(resolvedCode===undefined)return;return{code:resolvedCode,map:createSourceMap(resolvedCode)}}function getPluginEnvironmentName(ctx){if(ctx==null||typeof ctx!=="object")return;const environment=ctx["environment"];if(environment==null||typeof environment!=="object")return;const name=environment["name"];return typeof name==="string"?name:undefined}function resolveEnvironmentConsumerTarget(ctx){if(ctx==null||typeof ctx!=="object")return;const environment=ctx["environment"];if(environment==null||typeof environment!=="object")return;const consumer=environment.config?.consumer;if(consumer==="client"||consumer==="server")return consumer;const envName=getPluginEnvironmentName(ctx);return!envName||envName==="client"?"client":"server"}function isClientEnvironment(ctx){return resolveEnvironmentConsumerTarget(ctx)!=="server"}function isServerBuildContext(ctx,config){const target=resolveEnvironmentConsumerTarget(ctx);if(target)return target==="server";return Boolean(config?.build?.ssr)}function resolveRemoteConsumer(ctx,hasMultiEnvironment){if(!hasMultiEnvironment)return"unified";return resolveEnvironmentConsumerTarget(ctx)??"client"}var IDENTIFIER=String.raw`[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}]*`;var NAMED_SPECIFIERS=String.raw`\{[^{}]*\}`;var NAMESPACE_SPECIFIER=String.raw`\*\s*as\s+${IDENTIFIER}`;var IMPORT_CLAUSE=String.raw`(?:(?<importType>type)\s+)?(?<importClause>${NAMESPACE_SPECIFIER}|${NAMED_SPECIFIERS}|${IDENTIFIER}(?:\s*,\s*(?:${NAMESPACE_SPECIFIER}|${NAMED_SPECIFIERS}))?)`;var EXPORT_CLAUSE=String.raw`(?:(?<exportType>type)\s+)?(?<exportClause>\*(?:\s*as\s+(?:${IDENTIFIER}|"[^"]*"|'[^']*'))?|${NAMED_SPECIFIERS})`;var SPECIFIER=String.raw`(?<quote>["'])(?<source>[^"'\r\n]*)\k<quote>`;var KEYWORD_BOUNDARY=String.raw`(?<![.$\w])`;var KEYWORD_GAP=String.raw`(?:\s+|(?=[{*]))`;var STATIC_PATTERN=new RegExp(String.raw`${KEYWORD_BOUNDARY}(?:import${KEYWORD_GAP}${IMPORT_CLAUSE}|export${KEYWORD_GAP}${EXPORT_CLAUSE})\s*from\s*${SPECIFIER}`,"gud");var DYNAMIC_PATTERN=new RegExp(String.raw`${KEYWORD_BOUNDARY}import\s*\(\s*${SPECIFIER}`,"gud");var REQUIRE_PATTERN=new RegExp(String.raw`${KEYWORD_BOUNDARY}require\s*\(\s*${SPECIFIER}\s*\)`,"gud");var SIDE_EFFECT_PATTERN=new RegExp(String.raw`${KEYWORD_BOUNDARY}import\s*${SPECIFIER}`,"gud");function blankNonCode(code){const codePositions=createCodePositionMap(code);const chars2=code.split("");let index=0;while(index<code.length){if(codePositions[index]){index++;continue}const start=index;while(index<code.length&&!codePositions[index])index++;const quote2=code[start];const isString2=(quote2==='"'||quote2==="'")&&index-start>=2&&code[index-1]===quote2;for(let position=start;position<index;position++)chars2[position]=isString2&&(position===start||position===index-1)?quote2:code[position]===`
@@ -615,7 +623,7 @@ if (__mfReactInternals && "A" in __mfReactInternals) {
615
623
  `))return true;const followingToken=source.slice(next).match(/^[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}]*/u)?.[0];return followingToken==="as"||followingToken==="satisfies"||!followsNamedExpression&&followingToken!==undefined}function isInvalidTypeArgumentTerminator(source,index,followsNamedExpression){const char=source[index];return char===";"||char==="="&&source[index+1]!==">"&&followsNamedExpression}function findLikelyTypeArgumentEnd(source,start,codePositions){const context3=getTypeArgumentStartContext(source,start);if(!context3)return;const state={angleDepth:1,groupDepth:0,sawTypeComma:false};for(let index=start+1;index<source.length;index++){if(!codePositions[index])continue;const char=source[index];const groupAction=updateTypeArgumentGroupDepth(char,state);if(groupAction==="invalid")return;if(groupAction==="handled")continue;const angleAction=updateTypeArgumentAngleDepth(source,index,state);if(angleAction==="invalid")return;if(angleAction==="closed")return state.sawTypeComma&&hasLikelyTypeArgumentFollower(source,index,codePositions,context3.followsNamedExpression)?index:undefined;if(angleAction==="handled")continue;if(char===","&&state.groupDepth===0){state.sawTypeComma=true;continue}if(state.angleDepth===1&&state.groupDepth===0&&isInvalidTypeArgumentTerminator(source,index,context3.followsNamedExpression))return}}var LOAD_SHARE_TAG="__loadShare__";var PREBUILD_TAG="__prebuild__";var HELPERS_MODULE_NAME="loadShareHelpers";var HELPERS_MODULE_TAG="__mf_v__";var HELPERS_MODULE_MARKER=`${HELPERS_MODULE_TAG}${HELPERS_MODULE_NAME}${HELPERS_MODULE_TAG}`;var SHARED_CHUNK_SUFFIX=`${LOAD_SHARE_TAG}shared`;var HELPER_EXPORT_LIST=["__mfGetSharedCacheDescriptor","__mfReadSharedCache","__mfSharedCacheListenersKey","__mfGetSharedCacheListeners","__mfSubscribeSharedCache","__mfSharedCacheOwnersKey","__mfGetSharedCacheOwners","__mfReadSharedCacheOwner","__mfGetSharedModuleIdentity","__mfIsSameSharedModule","__mfWriteSharedCache","__mfTreeShakingSharedCacheKey","__mfGetTreeShakingSharedCache","__mfReadTreeShakingSharedCache","__mfWriteTreeShakingSharedCache","__mfTreeShakingSelectionCacheKey","__mfGetTreeShakingSelectionCache","__mfReadTreeShakingSharedSelection","__mfWriteTreeShakingSharedSelection"].join(", ");var helperModules=new WeakMap;function getSharedCacheHelpersModule(options){let module=helperModules.get(options);if(!module){module=new VirtualModule(HELPERS_MODULE_NAME,HELPERS_MODULE_TAG,"",getFederationScopeKey(options));module.writeSync(`${sharedCacheHelperCode}
616
624
  export { ${HELPER_EXPORT_LIST} };`);helperModules.set(options,module)}return module}function getSharedCacheHelpersImportCode(options){const importId=getSharedCacheHelpersModule(options).getImportId();return`import { ${HELPER_EXPORT_LIST} } from ${JSON.stringify(importId)};`}function isSharedCacheHelpersId(id){return id.includes(HELPERS_MODULE_MARKER)}function getSharedChunkName(id){const ownerTag=isSharedCacheHelpersId(id)?HELPERS_MODULE_MARKER:LOAD_SHARE_TAG;return`${id.slice(0,id.indexOf(ownerTag))}${SHARED_CHUNK_SUFFIX}`}function isSharedChunk(chunk){return chunk.name?.endsWith(SHARED_CHUNK_SUFFIX)??false}function findEagerFallbacksInSharedChunk(bundle){const offenders=new Map;for(const[fileName,chunk]of Object.entries(bundle)){if(chunk.type!=="chunk"||!isSharedChunk(chunk))continue;const inlined=Object.keys(chunk.modules??{}).filter((id)=>id.includes(PREBUILD_TAG));if(inlined.length>0)offenders.set(fileName,inlined)}return offenders}var JS_IDENTIFIER_REGEX=new RegExp("^[$_\\p{ID_Start}][$_\\u200C\\u200D\\p{ID_Continue}]*$","u");function escapeGeneratedStringLiteral(value3){return JSON.stringify(value3).replace(/[<>\u2028\u2029]/g,(char)=>{switch(char){case"<":return"\\u003C";case">":return"\\u003E";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return char}})}function getSharedCacheDescriptorLiteral(pkg,shareItem){return JSON.stringify(getSharedCacheDescriptor(pkg,shareItem))}function isValidJsIdentifier(name){return JS_IDENTIFIER_REGEX.test(name)}function isValidEsmExportName(name){return!!name&&name!=="default"&&name!=="__esModule"&&isValidJsIdentifier(name)}var JS_IDENTIFIER_PATTERN=`[$_\\p{ID_Start}][$_\\u200C\\u200D\\p{ID_Continue}]*`;function resolvePackageEntryFromProjectRoot(pkg){try{return resolveModulePath(pkg,path$14.join(getPackageDetectionCwd(),"package.json"))}catch{return}}function getPackageEsmEntryPath(pkg){return getInstalledPackageEntry(pkg,{conditions:["browser","import","module","default"],resolveSubpathWithRequire:false})||resolvePackageEntryFromProjectRoot(pkg)}var packageNamedExportsCache=new Map;var sharedExportInspectionCache=new Map;var sharedMutableExportsCache=new Map;function invalidateSharedExportInspectionCache(filePath){if(!/(?:^|[/\\])node_modules(?:[/\\]|$)/.test(filePath)){sharedExportInspectionCache.clear();sharedMutableExportsCache.clear()}}var DEFAULT_SHARED_EXPORT_CONDITIONS=["browser","import","module","default"];function getSharedExportSource(source){const parts2=[];let offset2=0;const codePositions=createCodePositionMap(source,(start,end)=>{parts2.push(source.slice(offset2,start),source.slice(start,end).replace(/[^\r\n\u2028\u2029]/g," "));offset2=end});return{source:parts2.length?parts2.join("")+source.slice(offset2):source,codePositions}}function hasCodeMatch(source,regex,codePositions){regex.lastIndex=0;let match5;while((match5=regex.exec(source))!==null)if(codePositions[match5.index])return true;return false}function hasCommonJsExports(source){const codePositions=createCodePositionMap(source);if(hasCodeMatch(source,/\bmodule\s*(?:\.exports|\[\s*['"]exports['"]\s*\])/g,codePositions))return true;const exportsRegex=/\bexports\s*(?:\.|\[|[,)]|=(?!=|>))/g;let match5;while((match5=exportsRegex.exec(source))!==null){if(!codePositions[match5.index])continue;let previousCodeIndex=match5.index-1;while(previousCodeIndex>=0&&(/\s/.test(source[previousCodeIndex])||!codePositions[previousCodeIndex]))previousCodeIndex--;if(source[previousCodeIndex]===".")continue;return true}return false}function inspectSharedExportsFromFile(entryPath,exportConditions=DEFAULT_SHARED_EXPORT_CONDITIONS){if(!entryPath)return;const cacheKey=`${entryPath}\x00${exportConditions.join("\x00")}`;if(sharedExportInspectionCache.has(cacheKey))return sharedExportInspectionCache.get(cacheKey);try{const source=readFileSync5(entryPath,"utf-8");const scanState={complete:true};const namedExports=getNamedExportsViaRegex(source,entryPath,undefined,scanState,exportConditions);const commonJs=hasCommonJsExports(source);const inspection={namedExports:scanState.complete&&!commonJs?namedExports:undefined,commonJs};sharedExportInspectionCache.set(cacheKey,inspection);return inspection}catch{sharedExportInspectionCache.set(cacheKey,undefined);return}}function getMutableExportsFromFile(entryPath,exportConditions=DEFAULT_SHARED_EXPORT_CONDITIONS,visited=new Set){if(!entryPath||visited.has(entryPath))return[];visited.add(entryPath);try{const{source,codePositions}=getSharedExportSource(readFileSync5(entryPath,"utf-8"));const mutableBindings=new Set;const mutableExports=new Set;let match5;const declarationRegex=new RegExp(`\\b(?:export\\s+)?(?:let|var)\\s+(${JS_IDENTIFIER_PATTERN})`,"gu");let declarationScanIndex=0;let braceDepth=0;while((match5=declarationRegex.exec(source))!==null){if(!codePositions[match5.index])continue;for(let index=declarationScanIndex;index<match5.index;index++){if(!codePositions[index])continue;if(source[index]==="{")braceDepth++;else if(source[index]==="}")braceDepth--}declarationScanIndex=match5.index;if(braceDepth!==0)continue;mutableBindings.add(match5[1]);if(match5[0].trimStart().startsWith("export"))mutableExports.add(match5[1])}const listRegex=/export\s*\{([^}]+)\}(?:\s*from\s*['"]([^'"]+)['"])?/g;while((match5=listRegex.exec(source))!==null){if(!codePositions[match5.index])continue;const reExportPath=match5[2]?resolveReExportModule(entryPath,match5[2],exportConditions):undefined;const reExportedMutable=new Set(reExportPath?getMutableExportsFromFile(reExportPath,exportConditions,visited):[]);for(const rawSpecifier of match5[1].split(",")){const specifier=rawSpecifier.trim();if(!specifier||specifier.startsWith("type "))continue;const parts2=specifier.split(/\s+as\s+/);const local=parts2[0].trim();const exported=(parts2[1]||local).trim();if(isValidEsmExportName(exported)&&(mutableBindings.has(local)||reExportedMutable.has(local)))mutableExports.add(exported)}}const starExportRegex=/export\s*\*\s*from\s*['"]([^'"]+)['"]/g;while((match5=starExportRegex.exec(source))!==null){if(!codePositions[match5.index])continue;const resolved=resolveReExportModule(entryPath,match5[1],exportConditions);for(const name of getMutableExportsFromFile(resolved,exportConditions,visited))mutableExports.add(name)}visited.delete(entryPath);return Array.from(mutableExports)}catch{visited.delete(entryPath);return[]}}function getSharedMutableExports(pkg,shareItem,exportConditions=DEFAULT_SHARED_EXPORT_CONDITIONS){const configuredImport=shareItem?.shareConfig.import;const entryPath=typeof configuredImport==="string"?resolveConfiguredImportPath(configuredImport,exportConditions):getInstalledPackageEntry(pkg,{conditions:exportConditions,resolveSubpathWithRequire:false});if(!entryPath)return[];const cacheKey=`${entryPath}\x00${exportConditions.join("\x00")}`;let mutableExports=sharedMutableExportsCache.get(cacheKey);if(!mutableExports){mutableExports=getMutableExportsFromFile(entryPath,exportConditions);sharedMutableExportsCache.set(cacheKey,mutableExports)}return mutableExports}function resolveConfiguredImportPath(importSource,exportConditions=DEFAULT_SHARED_EXPORT_CONDITIONS){if(path$14.isAbsolute(importSource))return resolveFileLikeModule(importSource);const projectRoot=getPackageDetectionCwd();if(importSource.startsWith("."))return resolveFileLikeModule(path$14.resolve(projectRoot,importSource));const esmEntry=getInstalledPackageEntry(importSource,{conditions:exportConditions,resolveSubpathWithRequire:false});if(esmEntry)return esmEntry;try{return resolveModulePath(importSource,path$14.join(projectRoot,"package.json"))}catch{return}}function resolveFileLikeModule(filePath){if(existsSync7(filePath)&&!statSync(filePath).isDirectory())return filePath;const extensions=[".ts",".tsx",".js",".jsx",".mjs",".mts"];for(const ext of extensions){const candidate=filePath+ext;if(existsSync7(candidate)&&!statSync(candidate).isDirectory())return candidate}for(const ext of extensions){const candidate=path$14.join(filePath,"index"+ext);if(existsSync7(candidate)&&!statSync(candidate).isDirectory())return candidate}}function resolveRelativeModule(filePath,specifier){const dir=path$14.dirname(filePath);const exact=path$14.resolve(dir,specifier);if(existsSync7(exact)&&!statSync(exact).isDirectory())return exact;const sourceExtensions=specifier.endsWith(".mjs")?[".mts"]:specifier.endsWith(".cjs")?[".cts"]:/\.jsx?$/.test(specifier)?[".ts",".tsx"]:[];for(const ext of sourceExtensions){const candidate=exact.replace(/\.[cm]?jsx?$/,ext);if(existsSync7(candidate)&&!statSync(candidate).isDirectory())return candidate}const extensions=[".ts",".tsx",".js",".jsx",".mjs",".mts"];for(const ext of extensions){const candidate=path$14.resolve(dir,specifier+ext);if(existsSync7(candidate)&&!statSync(candidate).isDirectory())return candidate}const resolved=path$14.resolve(dir,specifier);for(const ext of extensions){const candidate=path$14.join(resolved,"index"+ext);if(existsSync7(candidate))return candidate}}function resolveReExportModule(filePath,specifier,exportConditions){if(specifier.startsWith("."))return resolveRelativeModule(filePath,specifier);const esmEntry=getInstalledPackageEntry(specifier,{cwd:path$14.dirname(filePath),conditions:exportConditions,resolveSubpathWithRequire:false});if(esmEntry)return esmEntry;try{return resolveFileLikeModule(resolveModulePath(specifier,filePath))}catch{return}}var TEMPLATE_TEXT=Symbol("templateText");function getAdditionalTopLevelDeclaratorNames(source,start,codePositions){const names=[];let depth=0;let quote2;let escaped=false;let canStartRegex=true;const templateFrames=[];const inTemplateText=()=>templateFrames[templateFrames.length-1]===TEMPLATE_TEXT;for(let index=start;index<source.length;index++){const char=source[index];if(inTemplateText()){if(escaped)escaped=false;else if(char==="\\")escaped=true;else if(char==="$"&&source[index+1]==="{"){templateFrames.push(depth);index++;canStartRegex=true}else if(char==="`"){templateFrames.pop();canStartRegex=false}continue}if(quote2){if(escaped)escaped=false;else if(char==="\\")escaped=true;else if(char===quote2)quote2=undefined;continue}if(char==="`"){templateFrames.push(TEMPLATE_TEXT);canStartRegex=false;continue}if(char==='"'||char==="'"){quote2=char;canStartRegex=false;continue}if(char==="<"&&source[index+1]==="/"){const jsxClosingTag=source.slice(index).match(/^<\/\s*(?:[$_\p{ID_Start}][$_\u200C\u200D\p{ID_Continue}.:-]*\s*)?>/u);if(jsxClosingTag){index+=jsxClosingTag[0].length-1;canStartRegex=false;continue}}if(char==="/"&&source[index+1]==="/"){index=source.indexOf(`
617
625
  `,index+2);if(index===-1)return names;continue}if(char==="/"&&source[index+1]==="*"){const commentEnd=source.indexOf("*/",index+2);if(commentEnd===-1)return;index=commentEnd+1;continue}if(char==="/"&&canStartRegex){let regexEscaped=false;let inCharacterClass=false;let closed=false;for(index++;index<source.length;index++){const regexChar=source[index];if(regexEscaped){regexEscaped=false;continue}if(regexChar==="\\"){regexEscaped=true;continue}if(regexChar==="["){inCharacterClass=true;continue}if(regexChar==="]"&&inCharacterClass){inCharacterClass=false;continue}if(regexChar==="/"&&!inCharacterClass){closed=true;while(/[$_\p{ID_Continue}]/u.test(source[index+1]||""))index++;break}if(regexChar===`
618
- `||regexChar==="\r")return}if(!closed)return;canStartRegex=false;continue}if(char==="/"){canStartRegex=true;continue}if(/[$_\p{ID_Start}]/u.test(char)){const tokenStart=index;while(/[$_\u200C\u200D\p{ID_Continue}]/u.test(source[index+1]||""))index++;const token=source.slice(tokenStart,index+1);if(depth===0&&templateFrames.length===0&&token==="export"){let previous=tokenStart-1;while(/\s/.test(source[previous]||""))previous--;if(source[previous]!=="."&&/^\s+(?:(?:async\s+)?function\b|(?:abstract\s+)?class\b|const\b|let\b|var\b|enum\b|namespace\b|module\b|interface\b|type\b|declare\b|default\b|\{|\*)/.test(source.slice(index+1)))return names}canStartRegex=/^(?:await|case|delete|in|instanceof|new|return|throw|typeof|void|yield)$/.test(token);continue}if(/\d/.test(char)){while(/[\w.]/.test(source[index+1]||""))index++;canStartRegex=false;continue}if((char==="+"||char==="-")&&source[index+1]===char){index++;continue}if(char==="!"&&source[index+1]!=="=")continue;if(char==="<"){const typeArgumentEnd=findLikelyTypeArgumentEnd(source,index,codePositions);if(typeArgumentEnd!==undefined){index=typeArgumentEnd;canStartRegex=false;continue}}if(char==="("||char==="["||char==="{"){depth++;canStartRegex=true;continue}if(char===")"||char==="]"||char==="}"){if(char==="}"&&templateFrames.length>0&&templateFrames[templateFrames.length-1]===depth){templateFrames.pop();canStartRegex=false;continue}depth=Math.max(0,depth-1);canStartRegex=false;continue}if(templateFrames.length===0&&depth===0&&char===","){let bindingStart=index+1;while(/\s/.test(source[bindingStart]||""))bindingStart++;const binding=source.slice(bindingStart).match(new RegExp(`^(${JS_IDENTIFIER_PATTERN})`,"u"));if(!binding||!isValidEsmExportName(binding[1]))return;names.push(binding[1]);index=bindingStart+binding[1].length-1;canStartRegex=false;continue}if(templateFrames.length===0&&depth===0&&char===";")return names;if(!/\s/.test(char))canStartRegex=char!=="."}return names}function hasUnsupportedBindingPattern(source,start){const opening=source[start];if(opening!=="{"&&opening!=="[")return false;let depth=0;for(let index=start;index<source.length;index++){const char=source[index];if(char==='"'||char==="'"||char==="`")return true;if(char==="("||char==="/"||char===":"&&opening==="[")return true;if(char==="{"||char==="["){depth++;if(depth>1)return true;continue}if(char==="}"||char==="]"){depth--;if(depth===0){let next=index+1;while(/\s/.test(source[next]||""))next++;return source[next]!=="="}}}return true}function getNamedExportsViaRegex(source,filePath,visited,scanState={complete:true},exportConditions=DEFAULT_SHARED_EXPORT_CONDITIONS){const names=new Set;const inspected=getSharedExportSource(source);source=inspected.source;const codePositions=inspected.codePositions;const recognizedExportStarts=new Set;visited=visited||new Set;if(filePath)visited.add(filePath);const declRegex=new RegExp(`export\\s+(?:async\\s+)?(?:function(?:\\*\\s*|\\s+\\*?\\s*)|const\\s+enum\\s+|const\\s+|let\\s+|var\\s+|class\\s+|abstract\\s+class\\s+|enum\\s+|namespace\\s+|module\\s+)(${JS_IDENTIFIER_PATTERN})`,"gu");let match5;while((match5=declRegex.exec(source))!==null){if(!codePositions[match5.index])continue;recognizedExportStarts.add(match5.index);const name=match5[1];if(isValidEsmExportName(name))names.add(name)}const exportedVariableDeclarationRegex=/export\s+(?:const|let|var)\s+/g;while((match5=exportedVariableDeclarationRegex.exec(source))!==null){if(!codePositions[match5.index])continue;const additionalNames=getAdditionalTopLevelDeclaratorNames(source,exportedVariableDeclarationRegex.lastIndex,codePositions);if(additionalNames===undefined)scanState.complete=false;else for(const name of additionalNames)names.add(name);if(hasUnsupportedBindingPattern(source,exportedVariableDeclarationRegex.lastIndex))scanState.complete=false}if(hasCodeMatch(source,/export\s+import\s+/g,codePositions)||hasCodeMatch(source,/export\s*=/g,codePositions))scanState.complete=false;if(hasCodeMatch(source,/export\s+@/g,codePositions))scanState.complete=false;const destructureRegex=/export\s+(?:const|let|var)\s+(\{[^}]*\}|\[[^\]]*\])\s*=/g;const bindingNameRegex=new RegExp(`^(${JS_IDENTIFIER_PATTERN})`,"u");while((match5=destructureRegex.exec(source))!==null){if(!codePositions[match5.index])continue;recognizedExportStarts.add(match5.index);const inner=match5[1].slice(1,-1);for(const part of inner.split(",")){let token=part.split("=")[0].trim();if(token.startsWith("..."))token=token.slice(3).trim();if(!token)continue;if(token.includes(":"))token=token.slice(token.indexOf(":")+1).trim();const bindingMatch=token.match(bindingNameRegex);if(bindingMatch&&isValidEsmExportName(bindingMatch[1]))names.add(bindingMatch[1])}}const listRegex=/export\s*\{([^}]+)\}/g;const typeOnlySpecifierRegex=new RegExp(`^type\\s+${JS_IDENTIFIER_PATTERN}(?:\\s+as\\s+${JS_IDENTIFIER_PATTERN})?$`,"u");const exportSpecifierRegex=new RegExp(`(?:\\S+\\s+as\\s+)?(${JS_IDENTIFIER_PATTERN})$`,"u");while((match5=listRegex.exec(source))!==null){if(!codePositions[match5.index])continue;recognizedExportStarts.add(match5.index);const specifiers=match5[1].split(",");for(const specifier of specifiers){const trimmed=specifier.trim();if(!trimmed)continue;if(typeOnlySpecifierRegex.test(trimmed))continue;const asMatch=trimmed.match(exportSpecifierRegex);if(!asMatch){scanState.complete=false;continue}const name=asMatch[1];if(isValidEsmExportName(name))names.add(name);else if(name==="default"||name==="__esModule"){}else scanState.complete=false}}const namespaceReExportRegex=new RegExp(`export\\s*\\*\\s*as\\s+(${JS_IDENTIFIER_PATTERN})\\s*from\\s*['"][^'"]+['"]`,"gu");while((match5=namespaceReExportRegex.exec(source))!==null){if(!codePositions[match5.index])continue;recognizedExportStarts.add(match5.index);if(isValidEsmExportName(match5[1]))names.add(match5[1])}if(hasCodeMatch(source,/export\s*\*\s*as\s*['"]/g,codePositions))scanState.complete=false;if(filePath){const starExportRegex=/export\s*\*\s*from\s*['"]([^'"]+)['"]/g;while((match5=starExportRegex.exec(source))!==null){if(!codePositions[match5.index])continue;recognizedExportStarts.add(match5.index);const specifier=match5[1];const resolvedPath=resolveReExportModule(filePath,specifier,exportConditions);if(!resolvedPath){scanState.complete=false;continue}if(visited.has(resolvedPath))continue;try{const reExportSource=readFileSync5(resolvedPath,"utf-8");if(path$14.extname(resolvedPath)===".cjs"||hasCommonJsExports(reExportSource)){const requiredNames=getRequiredNamedExports(resolvedPath);if(!requiredNames?.length){scanState.complete=false;continue}for(const name of requiredNames)names.add(name);continue}const reExportNames=getNamedExportsViaRegex(reExportSource,resolvedPath,visited,scanState,exportConditions);for(const name of reExportNames)names.add(name)}catch{scanState.complete=false}}}const noNamedExportRegex=/export(?:\s+default\b|\s*\{\s*\}|\s+(?:type|interface|declare)\b)/g;while((match5=noNamedExportRegex.exec(source))!==null){if(!codePositions[match5.index])continue;recognizedExportStarts.add(match5.index)}const exportKeywordRegex=/\bexport\b/g;while((match5=exportKeywordRegex.exec(source))!==null){if(!codePositions[match5.index])continue;if(recognizedExportStarts.has(match5.index))continue;let previousCodeIndex=match5.index-1;while(previousCodeIndex>=0&&(/\s/.test(source[previousCodeIndex])||!codePositions[previousCodeIndex]))previousCodeIndex--;if(source[previousCodeIndex]===".")continue;let nextCodeIndex=match5.index+match5[0].length;while(nextCodeIndex<source.length&&(/\s/.test(source[nextCodeIndex])||!codePositions[nextCodeIndex]))nextCodeIndex++;if(source[nextCodeIndex]==="(")continue;let memberIndex=nextCodeIndex;if(source[memberIndex]==="?"){memberIndex++;while(memberIndex<source.length&&(/\s/.test(source[memberIndex])||!codePositions[memberIndex]))memberIndex++}if(source[memberIndex]===":")continue;scanState.complete=false;break}return Array.from(names)}function getRequiredNamedExports(specifier){const getActiveHandles=process._getActiveHandles;const handlesBeforeRequire=typeof getActiveHandles==="function"?new Set(getActiveHandles.call(process)):undefined;try{const projectPackageJson=path$14.join(getPackageDetectionCwd(),"package.json");const mod=createRequire$12(pathToFileURL4(projectPackageJson))(resolveModulePath(specifier,projectPackageJson));const runtimeNamedKeys=Object.keys(mod).filter((key)=>key!=="default"&&key!=="__esModule");if(runtimeNamedKeys.some((key)=>!isValidEsmExportName(key)))return;return runtimeNamedKeys}catch{return}finally{if(handlesBeforeRequire&&typeof getActiveHandles==="function")for(const handle of getActiveHandles.call(process)){if(handlesBeforeRequire.has(handle))continue;const unref=handle?.unref;if(typeof unref==="function")unref.call(handle)}}}function getPackageNamedExports(pkg,exportConditions=DEFAULT_SHARED_EXPORT_CONDITIONS){const esmEntryPath=getInstalledPackageEntry(pkg,{conditions:exportConditions,resolveSubpathWithRequire:false});if(esmEntryPath){const cacheKey=!isWorkspaceFilePath(esmEntryPath)?`${getPackageDetectionCwd()}\x00${esmEntryPath}\x00${exportConditions.join("\x00")}`:undefined;const cached2=cacheKey?packageNamedExportsCache.get(cacheKey):undefined;if(cached2)return cached2.value;const inspection=inspectSharedExportsFromFile(esmEntryPath,exportConditions);const value3=!inspection||inspection.commonJs||path$14.extname(esmEntryPath)===".cjs"?getRequiredNamedExports(esmEntryPath):inspection.namedExports;if(cacheKey)packageNamedExportsCache.set(cacheKey,{value:value3});return value3}return getRequiredNamedExports(pkg)}function getSharedNamedExports(pkg,shareItem,exportConditions=DEFAULT_SHARED_EXPORT_CONDITIONS){const configuredImport=shareItem?.shareConfig.import;if(typeof configuredImport==="string"){const configuredImportPath=resolveConfiguredImportPath(configuredImport,exportConditions);const inspection=inspectSharedExportsFromFile(configuredImportPath,exportConditions);if(configuredImportPath&&(inspection?.commonJs||path$14.extname(configuredImportPath)===".cjs"))return getRequiredNamedExports(configuredImportPath);if(inspection?.namedExports!==undefined)return inspection.namedExports;return}return getPackageNamedExports(pkg,exportConditions)}function getLocalProviderImportPath(pkg){try{const resolved=resolveWorkspaceEsmEntry(pkg,resolveModulePath(pkg,path$14.join(getPackageDetectionCwd(),"package.json")));return isWorkspaceFilePath(resolved)?resolved:undefined}catch{const resolved=getInstalledPackageEntry(pkg,{conditions:["browser","import","module","default"],resolveSubpathWithRequire:false});return isWorkspaceFilePath(resolved)?resolved:undefined}}function getProjectResolvedImportPath(pkg){if(pkg===getPackageName(pkg)){const esmEntry=getPackageEsmEntryPath(pkg);if(esmEntry)return esmEntry}try{return resolveWorkspaceEsmEntry(pkg,resolveModulePath(pkg,path$14.join(getPackageDetectionCwd(),"package.json")))}catch{return}}function isWorkspaceFilePath(resolved){if(!resolved)return false;let realResolved=resolved;try{realResolved=realpathSync3.native(resolved)}catch{}return!normalizeNodeModulePath(realResolved).includes("/node_modules/")}function resolveWorkspaceEsmEntry(pkg,resolved,cwd=getPackageDetectionCwd()){if(!isWorkspaceFilePath(resolved))return resolved;const esmEntry=getInstalledPackageEntry(pkg,{cwd,conditions:["browser","import","module","default"],resolveSubpathWithRequire:false});if(esmEntry&&isWorkspaceFilePath(esmEntry))return esmEntry;return resolved}function isWorkspacePackageEntry(pkg,resolved){if(!resolved||!path$14.isAbsolute(resolved)||!isWorkspaceFilePath(resolved))return false;return!!getInstalledPackageJson(pkg,{packageName:getPackageName(pkg),fromResolvedEntry:resolved})}function getWorkspacePackageJson(pkg){const resolved=getLocalProviderImportPath(pkg)||getProjectResolvedImportPath(pkg);if(!isWorkspacePackageEntry(pkg,resolved))return;return getInstalledPackageJson(pkg,{packageName:getPackageName(pkg),fromResolvedEntry:resolved})?.packageJson}function getSharedDependencyGraphPackageJson(pkg){const installedPackageJson=getInstalledPackageJson(pkg,{packageName:getPackageName(pkg)})?.packageJson;if(installedPackageJson)return installedPackageJson;try{const packageJsonPath=resolveModulePath(`${getPackageName(pkg)}/package.json`,path$14.join(getPackageDetectionCwd(),"package.json"));return JSON.parse(readFileSync5(packageJsonPath,"utf-8"))}catch{}return getWorkspacePackageJson(pkg)}function isSharedSingletonConsumedByPeer(pkg,options=getNormalizeModuleFederationOptions(),requireFederationRuntimeDependency=false){const shared=options?.shared||{};if(!requireFederationRuntimeDependency&&Object.entries(shared).some(([key,item])=>key!==pkg&&key.startsWith(`${pkg}/`)&&item.shareConfig.singleton===true))return true;const sharedKeyByPackageName=new Map;Object.entries(shared).filter(([,item])=>item.shareConfig.singleton===true).forEach(([key])=>{const packageName=getPackageName(key);if(!sharedKeyByPackageName.get(packageName)||key===packageName)sharedKeyByPackageName.set(packageName,key)});const runtimeDependencyCache=new Map;const reachesFederationRuntime=(current2,seen)=>{if(runtimeDependencyCache.has(current2))return runtimeDependencyCache.get(current2);const result3=getDependencyNames(getSharedDependencyGraphPackageJson(current2)).some((dependency)=>{if(dependency==="@module-federation/enhanced"||dependency==="@module-federation/runtime"||dependency==="@module-federation/runtime-core")return true;if(seen.has(dependency))return false;seen.add(dependency);const reachable=reachesFederationRuntime(dependency,seen);seen.delete(dependency);return reachable});runtimeDependencyCache.set(current2,result3);return result3};const reachesPkg=(current2,seen)=>{const dependencies=getDependencyNames(getSharedDependencyGraphPackageJson(current2));for(const dependency of dependencies){const sharedDependency=sharedKeyByPackageName.get(dependency);if(sharedDependency===pkg)return true;if(!sharedDependency&&!requireFederationRuntimeDependency)continue;const next=sharedDependency||dependency;if(seen.has(next))continue;seen.add(next);if(reachesPkg(next,seen))return true;seen.delete(next)}return false};return Array.from(sharedKeyByPackageName.values()).some((sharedPkg)=>sharedPkg!==pkg&&(!requireFederationRuntimeDependency||reachesFederationRuntime(sharedPkg,new Set([sharedPkg])))&&reachesPkg(sharedPkg,new Set([sharedPkg])))}function tryResolveImportFromPackageRoot(pkg,root){try{return resolveWorkspaceEsmEntry(pkg,resolveModulePath(pkg,path$14.join(root,"package.json")),root)}catch{return}}var concreteSharedImportSourceCache=new Map;function resetConcreteSharedImportSourceCache(){concreteSharedImportSourceCache.clear()}function getConcreteSharedImportSource(pkg,shareItem){const configuredImport=shareItem?.shareConfig.import;if(typeof configuredImport==="string")return configuredImport;const projectRoot=getPackageDetectionCwd();const cacheKey=JSON.stringify([projectRoot,pkg]);if(concreteSharedImportSourceCache.has(cacheKey))return concreteSharedImportSourceCache.get(cacheKey);const resolved=resolveConcreteSharedImportSource(pkg,projectRoot);concreteSharedImportSourceCache.set(cacheKey,resolved);return resolved}function resolveConcreteSharedImportSource(pkg,projectRoot){if(tryResolveImportFromPackageRoot(pkg,projectRoot))return;let currentDir=path$14.dirname(projectRoot);while(currentDir!==path$14.dirname(currentDir)){const resolved=tryResolveImportFromPackageRoot(pkg,currentDir);if(resolved)return resolved;currentDir=path$14.dirname(currentDir)}return tryResolveImportFromPackageRoot(pkg,currentDir)??getInstalledPackageEntry(pkg,{conditions:DEFAULT_SHARED_EXPORT_CONDITIONS,resolveSubpathWithRequire:false})}var TREE_SHAKING_PROVIDER_TAG="__treeShakingProvider__";var TREE_SHAKING_GRAPH_QUERY="__mf_tree_shaking_graph__";var legacySharedVirtualModuleState={preBuildCacheMap:{},preBuildShareItemMap:{},treeShakingProviderCacheMap:{},materializedTreeShakingProviders:new Set,loadShareCacheMap:{},warnedMissingImportFalse:new Set,coalescableLoadShares:new Set};var sharedVirtualModuleStates=new WeakMap;var sharedVirtualModuleStatesByOwner=new Map;function getSharedVirtualModuleState(options){if(!options)try{const currentOptions=getNormalizeModuleFederationOptions();return sharedVirtualModuleStates.get(currentOptions)??legacySharedVirtualModuleState}catch{return legacySharedVirtualModuleState}let state=sharedVirtualModuleStates.get(options);if(!state){state={preBuildCacheMap:{},preBuildShareItemMap:{},treeShakingProviderCacheMap:{},materializedTreeShakingProviders:new Set,loadShareCacheMap:{},warnedMissingImportFalse:new Set,coalescableLoadShares:new Set,ownerKey:getFederationScopeKey(options)};sharedVirtualModuleStates.set(options,state);if(state.ownerKey!==undefined)sharedVirtualModuleStatesByOwner.set(state.ownerKey,state)}return state}function getSharedVirtualModuleStateForId(id,options){const ownerKey=id===undefined?undefined:VirtualModule.findById(id)?.getScopeName();return(ownerKey!==undefined?sharedVirtualModuleStatesByOwner.get(ownerKey):undefined)??getSharedVirtualModuleState(options)}function createScopedSharedVirtualModule(pkg,tag2,options){return new VirtualModule(pkg,tag2,".js",getSharedVirtualModuleState(options).ownerKey)}function getTreeShakingGraphToken(id){if(!id)return;const queryStart=id.indexOf("?");if(queryStart===-1)return;const hashStart=id.indexOf("#",queryStart);const entry=id.slice(queryStart+1,hashStart===-1?undefined:hashStart).split("&").find((part)=>part.split("=",1)[0]===TREE_SHAKING_GRAPH_QUERY);if(!entry)return;const value3=entry.slice(26);try{return decodeURIComponent(value3)}catch{return value3}}function stripTreeShakingGraphQuery(id){const queryStart=id.indexOf("?");if(queryStart===-1)return id;const hashStart=id.indexOf("#",queryStart);const pathname=id.slice(0,queryStart);const hash2=hashStart===-1?"":id.slice(hashStart);const remaining=id.slice(queryStart+1,hashStart===-1?undefined:hashStart).split("&").filter(Boolean).filter((part)=>part.split("=",1)[0]!==TREE_SHAKING_GRAPH_QUERY);return`${pathname}${remaining.length?`?${remaining.join("&")}`:""}${hash2}`}function addTreeShakingGraphQuery(id,token){const cleanId=stripTreeShakingGraphQuery(id);const hashStart=cleanId.indexOf("#");const base2=hashStart===-1?cleanId:cleanId.slice(0,hashStart);const hash2=hashStart===-1?"":cleanId.slice(hashStart);return`${base2}${base2.includes("?")?"&":"?"}${TREE_SHAKING_GRAPH_QUERY}=${encodeURIComponent(token)}${hash2}`}function getConcreteTreeShakingExportUsage(pkg,shareItem,options){return getTreeShakingExportUsage(pkg,shareItem,shareItem?.name,options)}function getTreeShakingSharedProviderName(pkg,options){const resolvedOptions=options??getNormalizeModuleFederationOptions();return`${getSharedVirtualModuleState(options).ownerKey??resolvedOptions.internalName??resolvedOptions.name}__tree_shaking__${packageNameEncode(pkg)}`}function getTreeShakingSharedProviderImportId(pkg,options){const{treeShakingProviderCacheMap}=getSharedVirtualModuleState(options);if(!treeShakingProviderCacheMap[pkg])treeShakingProviderCacheMap[pkg]=createScopedSharedVirtualModule(pkg,TREE_SHAKING_PROVIDER_TAG,options);return treeShakingProviderCacheMap[pkg].getImportId()}function hasTreeShakingSharedProvider(pkg,shareItem,options){const{materializedTreeShakingProviders}=getSharedVirtualModuleState(options);const usage4=getConcreteTreeShakingExportUsage(pkg,shareItem,options);return materializedTreeShakingProviders.has(pkg)&&usage4?.kind==="exports"}function writeTreeShakingSharedProvider(pkg,shareItem,options){const{materializedTreeShakingProviders,treeShakingProviderCacheMap}=getSharedVirtualModuleState(options);const usage4=getConcreteTreeShakingExportUsage(pkg,shareItem,options);if(usage4?.kind!=="exports"||!usage4.usedExports.length||shareItem?.shareConfig.import===false){materializedTreeShakingProviders.delete(pkg);return}const usedExports=usage4.usedExports;const unsupportedExport=usedExports.find((name)=>name!=="default"&&!isValidEsmExportName(name));if(unsupportedExport){materializedTreeShakingProviders.delete(pkg);mfWarn(`Tree-shaking shared dependency "${pkg}" was disabled because export "${unsupportedExport}" cannot be represented by the generated ESM provider.`);return}const provider=treeShakingProviderCacheMap[pkg]||(treeShakingProviderCacheMap[pkg]=createScopedSharedVirtualModule(pkg,"__treeShakingProvider__",options));const optimizedImportSource=addTreeShakingGraphQuery(getConcreteSharedImportSource(pkg,shareItem)||pkg,pkg);const namedExports=usedExports.filter((name)=>name!=="default");const namedImports=namedExports.map((name,index)=>`${name} as __mfTreeShaken_${index}`).join(", ");const importLines=[namedImports?`import { ${namedImports} } from ${escapeGeneratedStringLiteral(optimizedImportSource)};`:"",usedExports.includes("default")?`import __mfTreeShakenDefault from ${escapeGeneratedStringLiteral(optimizedImportSource)};`:""].filter(Boolean).join(`
626
+ `||regexChar==="\r")return}if(!closed)return;canStartRegex=false;continue}if(char==="/"){canStartRegex=true;continue}if(/[$_\p{ID_Start}]/u.test(char)){const tokenStart=index;while(/[$_\u200C\u200D\p{ID_Continue}]/u.test(source[index+1]||""))index++;const token=source.slice(tokenStart,index+1);if(depth===0&&templateFrames.length===0&&token==="export"){let previous=tokenStart-1;while(/\s/.test(source[previous]||""))previous--;if(source[previous]!=="."&&/^\s+(?:(?:async\s+)?function\b|(?:abstract\s+)?class\b|const\b|let\b|var\b|enum\b|namespace\b|module\b|interface\b|type\b|declare\b|default\b|\{|\*)/.test(source.slice(index+1)))return names}canStartRegex=/^(?:await|case|delete|in|instanceof|new|return|throw|typeof|void|yield)$/.test(token);continue}if(/\d/.test(char)){while(/[\w.]/.test(source[index+1]||""))index++;canStartRegex=false;continue}if((char==="+"||char==="-")&&source[index+1]===char){index++;continue}if(char==="!"&&source[index+1]!=="=")continue;if(char==="<"){const typeArgumentEnd=findLikelyTypeArgumentEnd(source,index,codePositions);if(typeArgumentEnd!==undefined){index=typeArgumentEnd;canStartRegex=false;continue}}if(char==="("||char==="["||char==="{"){depth++;canStartRegex=true;continue}if(char===")"||char==="]"||char==="}"){if(char==="}"&&templateFrames.length>0&&templateFrames[templateFrames.length-1]===depth){templateFrames.pop();canStartRegex=false;continue}depth=Math.max(0,depth-1);canStartRegex=false;continue}if(templateFrames.length===0&&depth===0&&char===","){let bindingStart=index+1;while(/\s/.test(source[bindingStart]||""))bindingStart++;const binding=source.slice(bindingStart).match(new RegExp(`^(${JS_IDENTIFIER_PATTERN})`,"u"));if(!binding||!isValidEsmExportName(binding[1]))return;names.push(binding[1]);index=bindingStart+binding[1].length-1;canStartRegex=false;continue}if(templateFrames.length===0&&depth===0&&char===";")return names;if(!/\s/.test(char))canStartRegex=char!=="."}return names}function hasUnsupportedBindingPattern(source,start){const opening=source[start];if(opening!=="{"&&opening!=="[")return false;let depth=0;for(let index=start;index<source.length;index++){const char=source[index];if(char==='"'||char==="'"||char==="`")return true;if(char==="("||char==="/"||char===":"&&opening==="[")return true;if(char==="{"||char==="["){depth++;if(depth>1)return true;continue}if(char==="}"||char==="]"){depth--;if(depth===0){let next=index+1;while(/\s/.test(source[next]||""))next++;return source[next]!=="="}}}return true}function getNamedExportsViaRegex(source,filePath,visited,scanState={complete:true},exportConditions=DEFAULT_SHARED_EXPORT_CONDITIONS){const names=new Set;const inspected=getSharedExportSource(source);source=inspected.source;const codePositions=inspected.codePositions;const recognizedExportStarts=new Set;visited=visited||new Set;if(filePath)visited.add(filePath);const declRegex=new RegExp(`export\\s+(?:async\\s+)?(?:function(?:\\*\\s*|\\s+\\*?\\s*)|const\\s+enum\\s+|const\\s+|let\\s+|var\\s+|class\\s+|abstract\\s+class\\s+|enum\\s+|namespace\\s+|module\\s+)(${JS_IDENTIFIER_PATTERN})`,"gu");let match5;while((match5=declRegex.exec(source))!==null){if(!codePositions[match5.index])continue;recognizedExportStarts.add(match5.index);const name=match5[1];if(isValidEsmExportName(name))names.add(name)}const exportedVariableDeclarationRegex=/export\s+(?:const|let|var)\s+/g;while((match5=exportedVariableDeclarationRegex.exec(source))!==null){if(!codePositions[match5.index])continue;const additionalNames=getAdditionalTopLevelDeclaratorNames(source,exportedVariableDeclarationRegex.lastIndex,codePositions);if(additionalNames===undefined)scanState.complete=false;else for(const name of additionalNames)names.add(name);if(hasUnsupportedBindingPattern(source,exportedVariableDeclarationRegex.lastIndex))scanState.complete=false}if(hasCodeMatch(source,/export\s+import\s+/g,codePositions)||hasCodeMatch(source,/export\s*=/g,codePositions))scanState.complete=false;if(hasCodeMatch(source,/export\s+@/g,codePositions))scanState.complete=false;const destructureRegex=/export\s+(?:const|let|var)\s+(\{[^}]*\}|\[[^\]]*\])\s*=/g;const bindingNameRegex=new RegExp(`^(${JS_IDENTIFIER_PATTERN})`,"u");while((match5=destructureRegex.exec(source))!==null){if(!codePositions[match5.index])continue;recognizedExportStarts.add(match5.index);const inner=match5[1].slice(1,-1);for(const part of inner.split(",")){let token=part.split("=")[0].trim();if(token.startsWith("..."))token=token.slice(3).trim();if(!token)continue;if(token.includes(":"))token=token.slice(token.indexOf(":")+1).trim();const bindingMatch=token.match(bindingNameRegex);if(bindingMatch&&isValidEsmExportName(bindingMatch[1]))names.add(bindingMatch[1])}}const listRegex=/export\s*\{([^}]+)\}/g;const typeOnlySpecifierRegex=new RegExp(`^type\\s+${JS_IDENTIFIER_PATTERN}(?:\\s+as\\s+${JS_IDENTIFIER_PATTERN})?$`,"u");const exportSpecifierRegex=new RegExp(`(?:\\S+\\s+as\\s+)?(${JS_IDENTIFIER_PATTERN})$`,"u");while((match5=listRegex.exec(source))!==null){if(!codePositions[match5.index])continue;recognizedExportStarts.add(match5.index);const specifiers=match5[1].split(",");for(const specifier of specifiers){const trimmed=specifier.trim();if(!trimmed)continue;if(typeOnlySpecifierRegex.test(trimmed))continue;const asMatch=trimmed.match(exportSpecifierRegex);if(!asMatch){scanState.complete=false;continue}const name=asMatch[1];if(isValidEsmExportName(name))names.add(name);else if(name==="default"||name==="__esModule"){}else scanState.complete=false}}const namespaceReExportRegex=new RegExp(`export\\s*\\*\\s*as\\s+(${JS_IDENTIFIER_PATTERN})\\s*from\\s*['"][^'"]+['"]`,"gu");while((match5=namespaceReExportRegex.exec(source))!==null){if(!codePositions[match5.index])continue;recognizedExportStarts.add(match5.index);if(isValidEsmExportName(match5[1]))names.add(match5[1])}if(hasCodeMatch(source,/export\s*\*\s*as\s*['"]/g,codePositions))scanState.complete=false;if(filePath){const starExportRegex=/export\s*\*\s*from\s*['"]([^'"]+)['"]/g;while((match5=starExportRegex.exec(source))!==null){if(!codePositions[match5.index])continue;recognizedExportStarts.add(match5.index);const specifier=match5[1];const resolvedPath=resolveReExportModule(filePath,specifier,exportConditions);if(!resolvedPath){scanState.complete=false;continue}if(visited.has(resolvedPath))continue;try{const reExportSource=readFileSync5(resolvedPath,"utf-8");if(path$14.extname(resolvedPath)===".cjs"||hasCommonJsExports(reExportSource)){const requiredNames=getRequiredNamedExports(resolvedPath);if(!requiredNames?.length){scanState.complete=false;continue}for(const name of requiredNames)names.add(name);continue}const reExportNames=getNamedExportsViaRegex(reExportSource,resolvedPath,visited,scanState,exportConditions);for(const name of reExportNames)names.add(name)}catch{scanState.complete=false}}}const noNamedExportRegex=/export(?:\s+default\b|\s*\{\s*\}|\s+(?:type|interface|declare)\b)/g;while((match5=noNamedExportRegex.exec(source))!==null){if(!codePositions[match5.index])continue;recognizedExportStarts.add(match5.index)}const exportKeywordRegex=/\bexport\b/g;while((match5=exportKeywordRegex.exec(source))!==null){if(!codePositions[match5.index])continue;if(recognizedExportStarts.has(match5.index))continue;let previousCodeIndex=match5.index-1;while(previousCodeIndex>=0&&(/\s/.test(source[previousCodeIndex])||!codePositions[previousCodeIndex]))previousCodeIndex--;if(source[previousCodeIndex]===".")continue;let nextCodeIndex=match5.index+match5[0].length;while(nextCodeIndex<source.length&&(/\s/.test(source[nextCodeIndex])||!codePositions[nextCodeIndex]))nextCodeIndex++;if(source[nextCodeIndex]==="(")continue;let memberIndex=nextCodeIndex;if(source[memberIndex]==="?"){memberIndex++;while(memberIndex<source.length&&(/\s/.test(source[memberIndex])||!codePositions[memberIndex]))memberIndex++}if(source[memberIndex]===":")continue;scanState.complete=false;break}return Array.from(names)}function getRequiredNamedExports(specifier){const getActiveHandles=process._getActiveHandles;const handlesBeforeRequire=typeof getActiveHandles==="function"?new Set(getActiveHandles.call(process)):undefined;try{const projectPackageJson=path$14.join(getPackageDetectionCwd(),"package.json");const mod=createRequire$12(pathToFileURL4(projectPackageJson))(resolveModulePath(specifier,projectPackageJson));const runtimeNamedKeys=Object.keys(mod).filter((key)=>key!=="default"&&key!=="__esModule");if(runtimeNamedKeys.some((key)=>!isValidEsmExportName(key)))return;return runtimeNamedKeys}catch{return}finally{if(handlesBeforeRequire&&typeof getActiveHandles==="function")for(const handle of getActiveHandles.call(process)){if(handlesBeforeRequire.has(handle))continue;const unref=handle?.unref;if(typeof unref==="function")unref.call(handle)}}}function getPackageNamedExports(pkg,exportConditions=DEFAULT_SHARED_EXPORT_CONDITIONS){const esmEntryPath=getInstalledPackageEntry(pkg,{conditions:exportConditions,resolveSubpathWithRequire:false});if(esmEntryPath){const cacheKey=!isWorkspaceFilePath(esmEntryPath)?`${getPackageDetectionCwd()}\x00${esmEntryPath}\x00${exportConditions.join("\x00")}`:undefined;const cached2=cacheKey?packageNamedExportsCache.get(cacheKey):undefined;if(cached2)return cached2.value;const inspection=inspectSharedExportsFromFile(esmEntryPath,exportConditions);const value3=!inspection||inspection.commonJs||path$14.extname(esmEntryPath)===".cjs"?getRequiredNamedExports(esmEntryPath):inspection.namedExports;if(cacheKey)packageNamedExportsCache.set(cacheKey,{value:value3});return value3}return getRequiredNamedExports(pkg)}function getSharedNamedExports(pkg,shareItem,exportConditions=DEFAULT_SHARED_EXPORT_CONDITIONS){const configuredImport=shareItem?.shareConfig.import;if(typeof configuredImport==="string"){const configuredImportPath=resolveConfiguredImportPath(configuredImport,exportConditions);const inspection=inspectSharedExportsFromFile(configuredImportPath,exportConditions);if(configuredImportPath&&(inspection?.commonJs||path$14.extname(configuredImportPath)===".cjs"))return getRequiredNamedExports(configuredImportPath);if(inspection?.namedExports!==undefined)return inspection.namedExports;return}return getPackageNamedExports(pkg,exportConditions)}function getLocalProviderImportPath(pkg){try{const resolved=resolveWorkspaceEsmEntry(pkg,resolveModulePath(pkg,path$14.join(getPackageDetectionCwd(),"package.json")));return isWorkspaceFilePath(resolved)?resolved:undefined}catch{const resolved=getInstalledPackageEntry(pkg,{conditions:["browser","import","module","default"],resolveSubpathWithRequire:false});return isWorkspaceFilePath(resolved)?resolved:undefined}}function getProjectResolvedImportPath(pkg){if(pkg===getPackageName(pkg)){const esmEntry=getPackageEsmEntryPath(pkg);if(esmEntry)return esmEntry}try{return resolveWorkspaceEsmEntry(pkg,resolveModulePath(pkg,path$14.join(getPackageDetectionCwd(),"package.json")))}catch{return}}function isWorkspaceFilePath(resolved){if(!resolved)return false;let realResolved=resolved;try{realResolved=realpathSync3.native(resolved)}catch{}return!normalizeNodeModulePath(realResolved).includes("/node_modules/")}function resolveWorkspaceEsmEntry(pkg,resolved,cwd=getPackageDetectionCwd()){if(!isWorkspaceFilePath(resolved))return resolved;const esmEntry=getInstalledPackageEntry(pkg,{cwd,conditions:["browser","import","module","default"],resolveSubpathWithRequire:false});if(esmEntry&&isWorkspaceFilePath(esmEntry))return esmEntry;return resolved}function isWorkspacePackageEntry(pkg,resolved){if(!resolved||!path$14.isAbsolute(resolved)||!isWorkspaceFilePath(resolved))return false;return!!getInstalledPackageJson(pkg,{packageName:getPackageName(pkg),fromResolvedEntry:resolved})}function getWorkspacePackageJson(pkg){const resolved=getLocalProviderImportPath(pkg)||getProjectResolvedImportPath(pkg);if(!isWorkspacePackageEntry(pkg,resolved))return;return getInstalledPackageJson(pkg,{packageName:getPackageName(pkg),fromResolvedEntry:resolved})?.packageJson}function getSharedDependencyGraphPackageJson(pkg){const installedPackageJson=getInstalledPackageJson(pkg,{packageName:getPackageName(pkg)})?.packageJson;if(installedPackageJson)return installedPackageJson;try{const packageJsonPath=resolveModulePath(`${getPackageName(pkg)}/package.json`,path$14.join(getPackageDetectionCwd(),"package.json"));return JSON.parse(readFileSync5(packageJsonPath,"utf-8"))}catch{}return getWorkspacePackageJson(pkg)}function isSharedSingletonConsumedByPeer(pkg,options=getNormalizeModuleFederationOptions(),requireFederationRuntimeDependency=false){const shared=options?.shared||{};if(!requireFederationRuntimeDependency&&Object.entries(shared).some(([key,item])=>key!==pkg&&key.startsWith(`${pkg}/`)&&item.shareConfig.singleton===true))return true;const sharedKeyByPackageName=new Map;Object.entries(shared).filter(([,item])=>item.shareConfig.singleton===true).forEach(([key])=>{const packageName=getPackageName(key);if(!sharedKeyByPackageName.get(packageName)||key===packageName)sharedKeyByPackageName.set(packageName,key)});const runtimeDependencyCache=new Map;const reachesFederationRuntime=(current2,seen)=>{if(runtimeDependencyCache.has(current2))return runtimeDependencyCache.get(current2);const result3=getDependencyNames(getSharedDependencyGraphPackageJson(current2)).some((dependency)=>{if(dependency==="@module-federation/enhanced"||dependency==="@module-federation/runtime"||dependency==="@module-federation/runtime-core")return true;if(seen.has(dependency))return false;seen.add(dependency);const reachable=reachesFederationRuntime(dependency,seen);seen.delete(dependency);return reachable});runtimeDependencyCache.set(current2,result3);return result3};const reachesPkg=(current2,seen)=>{const dependencies=getDependencyNames(getSharedDependencyGraphPackageJson(current2));for(const dependency of dependencies){const sharedDependency=sharedKeyByPackageName.get(dependency);if(sharedDependency===pkg)return true;if(!sharedDependency&&!requireFederationRuntimeDependency)continue;const next=sharedDependency||dependency;if(seen.has(next))continue;seen.add(next);if(reachesPkg(next,seen))return true;seen.delete(next)}return false};return Array.from(sharedKeyByPackageName.values()).some((sharedPkg)=>sharedPkg!==pkg&&(!requireFederationRuntimeDependency||reachesFederationRuntime(sharedPkg,new Set([sharedPkg])))&&reachesPkg(sharedPkg,new Set([sharedPkg])))}function tryResolveImportFromPackageRoot(pkg,root){try{return resolveWorkspaceEsmEntry(pkg,resolveModulePath(pkg,path$14.join(root,"package.json")),root)}catch{return}}var concreteSharedImportSourceCache=new Map;function resetConcreteSharedImportSourceCache(){concreteSharedImportSourceCache.clear()}function getConcreteSharedImportSource(pkg,shareItem){const configuredImport=shareItem?.shareConfig.import;if(typeof configuredImport==="string")return configuredImport;const projectRoot=getPackageDetectionCwd();const cacheKey=JSON.stringify([projectRoot,pkg]);if(concreteSharedImportSourceCache.has(cacheKey))return concreteSharedImportSourceCache.get(cacheKey);const resolved=resolveConcreteSharedImportSource(pkg,projectRoot);concreteSharedImportSourceCache.set(cacheKey,resolved);return resolved}function resolveConcreteSharedImportSource(pkg,projectRoot){if(tryResolveImportFromPackageRoot(pkg,projectRoot))return;let currentDir=path$14.dirname(projectRoot);while(currentDir!==path$14.dirname(currentDir)){const resolved=tryResolveImportFromPackageRoot(pkg,currentDir);if(resolved)return resolved;currentDir=path$14.dirname(currentDir)}return tryResolveImportFromPackageRoot(pkg,currentDir)??getInstalledPackageEntry(pkg,{conditions:DEFAULT_SHARED_EXPORT_CONDITIONS,resolveSubpathWithRequire:false})}var TREE_SHAKING_PROVIDER_TAG="__treeShakingProvider__";var TREE_SHAKING_GRAPH_QUERY="__mf_tree_shaking_graph__";var legacySharedVirtualModuleState={preBuildCacheMap:{},preBuildShareItemMap:{},treeShakingProviderCacheMap:{},materializedTreeShakingProviders:new Set,loadShareCacheMap:{},warnedMissingImportFalse:new Set,coalescableLoadShares:new Set};var sharedVirtualModuleStates=new WeakMap;var sharedVirtualModuleStatesByOwner=new Map;function getSharedVirtualModuleState(options){if(!options)try{const currentOptions=getNormalizeModuleFederationOptions();return sharedVirtualModuleStates.get(currentOptions)??legacySharedVirtualModuleState}catch{return legacySharedVirtualModuleState}let state=sharedVirtualModuleStates.get(options);if(!state){state={preBuildCacheMap:{},preBuildShareItemMap:{},treeShakingProviderCacheMap:{},materializedTreeShakingProviders:new Set,loadShareCacheMap:{},warnedMissingImportFalse:new Set,coalescableLoadShares:new Set,ownerKey:getFederationScopeKey(options)};sharedVirtualModuleStates.set(options,state);if(state.ownerKey!==undefined)sharedVirtualModuleStatesByOwner.set(state.ownerKey,state)}return state}function getSharedVirtualModuleStateForId(id,options){const ownerKey=id===undefined?undefined:VirtualModule.findById(id)?.getScopeName();return(ownerKey!==undefined?sharedVirtualModuleStatesByOwner.get(ownerKey):undefined)??getSharedVirtualModuleState(options)}function createScopedSharedVirtualModule(pkg,tag2,options){return new VirtualModule(pkg,tag2,".js",getSharedVirtualModuleState(options).ownerKey)}function getTreeShakingGraphToken(id){if(!id)return;const queryStart=id.indexOf("?");if(queryStart===-1)return;const hashStart=id.indexOf("#",queryStart);const entry=id.slice(queryStart+1,hashStart===-1?undefined:hashStart).split("&").find((part)=>part.split("=",1)[0]===TREE_SHAKING_GRAPH_QUERY);if(!entry)return;const value3=entry.slice(26);try{return decodeURIComponent(value3)}catch{return value3}}function stripTreeShakingGraphQuery(id){const queryStart=id.indexOf("?");if(queryStart===-1)return id;const hashStart=id.indexOf("#",queryStart);const pathname=id.slice(0,queryStart);const hash2=hashStart===-1?"":id.slice(hashStart);const remaining=id.slice(queryStart+1,hashStart===-1?undefined:hashStart).split("&").filter(Boolean).filter((part)=>part.split("=",1)[0]!==TREE_SHAKING_GRAPH_QUERY);return`${pathname}${remaining.length?`?${remaining.join("&")}`:""}${hash2}`}function addTreeShakingGraphQuery(id,token){const cleanId=stripTreeShakingGraphQuery(id);const hashStart=cleanId.indexOf("#");const base2=hashStart===-1?cleanId:cleanId.slice(0,hashStart);const hash2=hashStart===-1?"":cleanId.slice(hashStart);return`${base2}${base2.includes("?")?"&":"?"}${TREE_SHAKING_GRAPH_QUERY}=${encodeURIComponent(token)}${hash2}`}function getConcreteTreeShakingExportUsage(pkg,shareItem,options){return getTreeShakingExportUsage(pkg,shareItem,shareItem?.name,options)}function getTreeShakingSharedProviderName(pkg,options){const resolvedOptions=options??getNormalizeModuleFederationOptions();return`${getSharedVirtualModuleState(options).ownerKey??resolvedOptions.internalName??resolvedOptions.name}__tree_shaking__${packageNameEncode(pkg)}`}function getTreeShakingSharedProviderImportId(pkg,options){const{treeShakingProviderCacheMap}=getSharedVirtualModuleState(options);if(!treeShakingProviderCacheMap[pkg])treeShakingProviderCacheMap[pkg]=createScopedSharedVirtualModule(pkg,TREE_SHAKING_PROVIDER_TAG,options);return treeShakingProviderCacheMap[pkg].getImportId()}function hasTreeShakingSharedProvider(pkg,shareItem,options){const{materializedTreeShakingProviders}=getSharedVirtualModuleState(options);const usage5=getConcreteTreeShakingExportUsage(pkg,shareItem,options);return materializedTreeShakingProviders.has(pkg)&&usage5?.kind==="exports"}function writeTreeShakingSharedProvider(pkg,shareItem,options){const{materializedTreeShakingProviders,treeShakingProviderCacheMap}=getSharedVirtualModuleState(options);const usage5=getConcreteTreeShakingExportUsage(pkg,shareItem,options);if(usage5?.kind!=="exports"||!usage5.usedExports.length||shareItem?.shareConfig.import===false){materializedTreeShakingProviders.delete(pkg);return}const usedExports=usage5.usedExports;const unsupportedExport=usedExports.find((name)=>name!=="default"&&!isValidEsmExportName(name));if(unsupportedExport){materializedTreeShakingProviders.delete(pkg);mfWarn(`Tree-shaking shared dependency "${pkg}" was disabled because export "${unsupportedExport}" cannot be represented by the generated ESM provider.`);return}const provider=treeShakingProviderCacheMap[pkg]||(treeShakingProviderCacheMap[pkg]=createScopedSharedVirtualModule(pkg,"__treeShakingProvider__",options));const optimizedImportSource=addTreeShakingGraphQuery(getConcreteSharedImportSource(pkg,shareItem)||pkg,pkg);const namedExports=usedExports.filter((name)=>name!=="default");const namedImports=namedExports.map((name,index)=>`${name} as __mfTreeShaken_${index}`).join(", ");const importLines=[namedImports?`import { ${namedImports} } from ${escapeGeneratedStringLiteral(optimizedImportSource)};`:"",usedExports.includes("default")?`import __mfTreeShakenDefault from ${escapeGeneratedStringLiteral(optimizedImportSource)};`:""].filter(Boolean).join(`
619
627
  `);const namespaceEntries=[...namedExports.map((name,index)=>`[${JSON.stringify(name)}]: __mfTreeShaken_${index}`),...usedExports.includes("default")?["default: __mfTreeShakenDefault"]:[`default: { ${namedExports.map((name,index)=>`[${JSON.stringify(name)}]: __mfTreeShaken_${index}`).join(", ")} }`]];provider.writeSync(`${importLines}
620
628
  const __mfTreeShakenModule = { ${namespaceEntries.join(", ")} };
621
629
  Object.defineProperty(__mfTreeShakenModule, "__esModule", {
@@ -776,7 +784,7 @@ ${code}`}function generateDeferredHostProvidedExports(namedExports,pkg,cacheDesc
776
784
  } else {
777
785
  __mfApplyHostProvidedExports(exportModule);
778
786
  }
779
- export { __mf_default as default, exportModule as __moduleExports };${namedExportLine}`}function selectImportFalseNamedExports(detectedNamedExports,usage4){if(!detectedNamedExports||usage4?.kind!=="exports")return detectedNamedExports??[];const usedNamedExports=new Set(usage4.usedExports.filter((name)=>name!=="default"));if([...usedNamedExports].some((name)=>!detectedNamedExports.includes(name)))return detectedNamedExports;return detectedNamedExports.filter((name)=>usedNamedExports.has(name))}function generateShareModuleUnwrapCode({source,preserveNamedExports,stopWithReturn}){return`let current = ${source};
787
+ export { __mf_default as default, exportModule as __moduleExports };${namedExportLine}`}function selectImportFalseNamedExports(detectedNamedExports,usage5){if(!detectedNamedExports||usage5?.kind!=="exports")return detectedNamedExports??[];const usedNamedExports=new Set(usage5.usedExports.filter((name)=>name!=="default"));if([...usedNamedExports].some((name)=>!detectedNamedExports.includes(name)))return detectedNamedExports;return detectedNamedExports.filter((name)=>usedNamedExports.has(name))}function generateShareModuleUnwrapCode({source,preserveNamedExports,stopWithReturn}){return`let current = ${source};
780
788
  for (let i = 0; i < 5; i++) {
781
789
  const defaultExport = current?.default;
782
790
  ${stopWithReturn?`if (!defaultExport || typeof defaultExport !== "object") return ${stopWithReturn};`:`if (!defaultExport || typeof defaultExport !== "object") break;`}${preserveNamedExports?`
@@ -3135,7 +3143,7 @@ ${varLines}
3135
3143
  ${initializers}
3136
3144
  ${syncLine}
3137
3145
  ${exportLine}`);changed=true;break}case"export-all":console.warn(`[module-federation] "export * from '${imp.source}'" is not supported with Rolldown \u2014 use explicit named re-exports instead. (${id})`);break;case"dynamic":ms.overwrite(imp.start,imp.end,wrapDynamicImport(imp.originalText));changed=true;break}if(!changed)return;if(dependencyPendingIds.length>0)ms.overwrite(code.length,code.length,`
3138
- export const __mf_remote_dependency_pending = Promise.all([${dependencyPendingIds.join(", ")}]);`);return{code:ms.toString(),map:ms.generateMap(id)}}async function collectFromAST(ast,code,isRemoteImport){const result3=[];walkAST(ast,{enter(node){if(node.type==="ImportDeclaration"&&node.source?.value){if(!isRemoteImport(node.source.value))return;const specifiers=node.specifiers||[];const named=specifiers.filter((s)=>s.type==="ImportSpecifier"&&s.importKind!=="type").map((s)=>({imported:s.imported.name??s.imported.value,local:s.local.name}));const defaultSpec=specifiers.find((s)=>s.type==="ImportDefaultSpecifier");const nsSpec=specifiers.find((s)=>s.type==="ImportNamespaceSpecifier");if(named.length===0&&!nsSpec)return;result3.push({kind:"static",source:node.source.value,start:node.start,end:node.end,named,defaultLocal:defaultSpec?.local.name,namespaceLocal:nsSpec?.local.name})}if(node.type==="ExportNamedDeclaration"&&node.source?.value&&isRemoteImport(node.source.value)){const specifiers=(node.specifiers||[]).filter((s)=>s.exportKind!=="type").map((s)=>({local:s.local.name??s.local.value,exported:s.exported.name??s.exported.value}));if(specifiers.length===0)return;result3.push({kind:"reexport",source:node.source.value,start:node.start,end:node.end,specifiers})}if(node.type==="ExportAllDeclaration"&&node.source?.value&&isRemoteImport(node.source.value)){this.skip();result3.push({kind:"export-all",source:node.source.value,start:node.start,end:node.end})}if(node.type==="ImportExpression"){const source=node.source;if(source.type!=="Literal"&&source.type!=="StringLiteral"&&source.type!=="TemplateLiteral")return;const value3=source.type==="TemplateLiteral"?source.quasis?.length===1?source.quasis[0].value?.cooked:undefined:source.value;if(!value3||!isRemoteImport(value3))return;result3.push({kind:"dynamic",source:value3,start:node.start,end:node.end,originalText:code.slice(node.start,node.end)})}}});return result3}function collectFromRegex(code,isRemoteImport){const result3=[];const codePositions=createCodePositionMap(code);const importAttributes=String.raw`(?:\s+(?:with|assert)\s+\{[^;]*\})?`;const staticRe=new RegExp(String.raw`^\s*import\s+([\s\S]*?)\s+from\s+(['"])([^'"]+)\2${importAttributes}\s*;?`,"gm");for(const match5 of code.matchAll(staticRe)){const[full,specifiersPartRaw,,source]=match5;if(!codePositions[match5.index])continue;if(!isRemoteImport(source))continue;const specifiersPart=specifiersPartRaw.trim();if(/^type\s/.test(specifiersPart))continue;const nsMatch=specifiersPart.match(/^\*\s+as\s+(\w+)$/);if(nsMatch){result3.push({kind:"static",source,start:match5.index,end:match5.index+full.length,named:[],namespaceLocal:nsMatch[1]});continue}const braceMatch=specifiersPart.match(/\{([^}]*)\}/);if(!braceMatch)continue;const named=parseNamedSpecifiers(braceMatch[1],"import");if(named.length===0)continue;const defaultMatch=specifiersPart.match(/^(\w+)\s*,/);result3.push({kind:"static",source,start:match5.index,end:match5.index+full.length,named,defaultLocal:defaultMatch?.[1]})}const reexportRe=new RegExp(String.raw`^\s*export\s+\{([\s\S]*?)\}\s+from\s+(['"])([^'"]+)\2${importAttributes}\s*;?`,"gm");for(const match5 of code.matchAll(reexportRe)){const[full,specifiersRaw,,source]=match5;if(!codePositions[match5.index])continue;if(!isRemoteImport(source))continue;const specifiers=parseNamedSpecifiers(specifiersRaw,"export");if(specifiers.length===0)continue;result3.push({kind:"reexport",source,start:match5.index,end:match5.index+full.length,specifiers})}const exportAllRe=new RegExp(String.raw`^\s*export\s+\*\s+from\s+(['"])([^'"]+)\1${importAttributes}\s*;?`,"gm");for(const match5 of code.matchAll(exportAllRe)){const[full,,source]=match5;if(!codePositions[match5.index])continue;if(!isRemoteImport(source))continue;result3.push({kind:"export-all",source,start:match5.index,end:match5.index+full.length})}for(const match5 of code.matchAll(/import\(\s*(?:\/\*[\s\S]*?\*\/\s*)?(['"])([^'"]+)\1\s*\)/g)){const[full,,source]=match5;if(!codePositions[match5.index])continue;if(!isRemoteImport(source))continue;result3.push({kind:"dynamic",source,start:match5.index,end:match5.index+full.length,originalText:full})}return result3.length>0?result3:undefined}function pluginRemoteNamedExports(options){const remoteNames=Object.keys(options.remotes);let root=process.cwd();const isNodeModulesId=(id)=>id.includes("/node_modules/")||id.includes("\\node_modules\\");function isRemoteImport(source,importerId){return remoteNames.some((name)=>{if(source.startsWith(name+"/"))return true;if(source!==name)return false;return!isNodeModulesId(importerId)||!getInstalledPackageEntry(source,{cwd:root})})||source.includes("__loadRemote__")}return{name:"module-federation-remote-named-exports",enforce:"post",configResolved(config2){root=config2.root||process.cwd()},async transform(code,id){if(remoteNames.length===0)return;if(id.includes("__loadRemote__")||id.includes("__loadShare__"))return;if(!JS_EXTENSIONS_RE.test(id))return;if(!remoteNames.some((name)=>code.includes(name)))return;const matchesRemoteImport=(source)=>isRemoteImport(source,id);for(const{kind,source,typeOnly}of findModuleImportDescriptors(code))if(kind==="static"&&!typeOnly&&matchesRemoteImport(source))markStaticRemote(source,options);let imports;try{imports=await collectFromAST(this.parse(code),code,matchesRemoteImport)}catch{if((id.includes(".vue")||id.includes(".svelte"))&&/^\s*</.test(code))return;imports=collectFromRegex(code,matchesRemoteImport)}if(!imports)return;for(const remoteImport of imports)if(remoteImport.kind==="dynamic")markDynamicRemote(remoteImport.source,options);return applyRewrites(code,imports,id)}}}var MAX_RUNNER_BODY_BYTES=1048576;var MAX_RUNNER_START_OFFSET=1048576;var ALLOWED_RUNNER_INVOKE_NAMES=new Set(["fetchModule","getBuiltins"]);function isPlainObject(value3){return!!value3&&typeof value3==="object"&&!Array.isArray(value3)}function isSafeRunnerFetchModuleOptions(value3){if(!isPlainObject(value3))return false;const allowedKeys=new Set(["cached","startOffset","inlineSourceMap"]);for(const[key,option2]of Object.entries(value3)){if(!allowedKeys.has(key))return false;if(key==="startOffset"){if(typeof option2!=="number"||!Number.isSafeInteger(option2)||option2<0||option2>MAX_RUNNER_START_OFFSET)return false}else if(typeof option2!=="boolean")return false}return true}function decodeRunnerFilePath(filePath){try{return decodeURIComponent(filePath)}catch{return}}function hasRelativeTraversal(id){return id.split(/[\\/]+/).includes("..")}function getRealPathIfExists(filePath){try{return fs$12.realpathSync.native(filePath)}catch{return}}function isCanonicalPathWithinDirectory(filePath,directory){const realFilePath=getRealPathIfExists(filePath)??path$14.resolve(filePath);const realDirectory=getRealPathIfExists(directory)??path$14.resolve(directory);const relative4=path$14.relative(realDirectory,realFilePath);return relative4===""||!relative4.startsWith("..")&&!path$14.isAbsolute(relative4)}function getRunnerAllowedDirectories(config2){return[config2.root,...config2.server?.fs?.allow??[]].map((directory)=>path$14.resolve(directory))}function isPathWithinAllowedDirectories(filePath,allowedDirectories){return allowedDirectories.some((directory)=>isCanonicalPathWithinDirectory(filePath,directory))}function isSafeRunnerFetchModuleId(id,config2){if(typeof id!=="string"||!id)return false;const decoded=decodeViteId(id).replace(/^\0+/,"");if(!decoded||decoded.startsWith("virtual:"))return!!decoded;if(decoded.startsWith("file://"))try{const filePath=decodeURIComponent(new URL(decoded).pathname);return path$14.isAbsolute(filePath)&&isPathWithinAllowedDirectories(filePath,getRunnerAllowedDirectories(config2))}catch{return false}if(/^(?:https?|data|blob|javascript):/i.test(decoded)||decoded.startsWith("//"))return false;const cleanId=decodeRunnerFilePath(stripQueryAndHash(decoded));if(!cleanId||hasRelativeTraversal(cleanId))return false;const allowedDirectories=getRunnerAllowedDirectories(config2);if(cleanId.startsWith("/@fs/")){const fsPath=stripViteFsPrefix(cleanId);return path$14.isAbsolute(fsPath)&&isPathWithinAllowedDirectories(fsPath,allowedDirectories)}if(path$14.isAbsolute(cleanId)){if(isPathWithinAllowedDirectories(cleanId,allowedDirectories))return true;return!fs$12.existsSync(cleanId)}return true}function isRunnerInvokePayload(payload,config2){if(!payload||typeof payload!=="object")return false;if(payload.type!=="custom"||payload.event!=="vite:invoke")return false;const data2=payload.data;if(!data2||typeof data2!=="object")return false;const name=data2.name;const args2=data2.data;if(typeof name!=="string"||!ALLOWED_RUNNER_INVOKE_NAMES.has(name)||!Array.isArray(args2))return false;if(name==="getBuiltins")return args2.length===0;if(args2.length<1||args2.length>3)return false;const[id,importer,opts]=args2;return isSafeRunnerFetchModuleId(id,config2)&&(importer===undefined||importer===null||isSafeRunnerFetchModuleId(importer,config2))&&(opts===undefined||isSafeRunnerFetchModuleOptions(opts))}function readBoundedRunnerBody(req,res){return new Promise((resolve9)=>{const chunks=[];let size=0;let done3=false;const fail12=(statusCode,message)=>{if(done3)return;done3=true;res.statusCode=statusCode;res.end(message);resolve9(undefined)};req.on("data",(chunk)=>{if(done3)return;size+=chunk.length;if(size>MAX_RUNNER_BODY_BYTES)return fail12(413,"Payload too large");chunks.push(chunk)});req.on("end",()=>{if(done3)return;done3=true;resolve9(Buffer.concat(chunks))});req.on("error",()=>fail12(400,"Bad request"))})}function pluginSSRRemoteEntry(options){const remoteEntrySSRId=getRemoteEntrySSRId(options);const virtualExposesSSRId=getVirtualExposesSSRId(options);let cachedSsrRemoteEntrySource;const ssrOutputFilename=getSsrRemoteEntryFileName(options);const ssrExposesFileName=getSsrExposesFileName(options.filename);let ssrOutputFiles=new Set;let ssrOutputDir="";let clientOutputDir="";const mfRuntimePackages=["@module-federation/runtime","@module-federation/runtime-core","@module-federation/sdk"];const ssrOnlyExternals=[...mfRuntimePackages,...options.ssrExternals??[]];const ssrOnlyExternalPattern=new RegExp(`^(${ssrOnlyExternals.map((e)=>e.replace(/[/\\^$*+?.()|[\]{}]/g,"\\$&")).join("|")})(\\/.*)?$`);let noExternal;const isNoExternal=(id)=>{const pkg=ssrOnlyExternalPattern.exec(id)?.[1]??id;if(!noExternal||!mfRuntimePackages.includes(pkg))return false;if(noExternal===true)return true;return(Array.isArray(noExternal)?noExternal:[noExternal]).some((rule)=>typeof rule==="string"?rule===pkg:rule.test(pkg))};const ssrModuleIds=new Set([remoteEntrySSRId,virtualExposesSSRId]);const resolvedAbsToPackage=new Map;let isServe=false;let viteConfig;let isNuxtProject=false;let reactIslandExposes=new Set;const isSsrRemoteEntryBuild=(environment)=>{const environmentName=environment?.name;const hasSsrEnvironment=Boolean(viteConfig?.environments?.ssr);const isLegacySsrBuild=Boolean(environment?.config?.build?.ssr??viteConfig?.build?.ssr);return Object.keys(options.exposes).length>0&&!(hasSsrEnvironment&&environmentName!=="ssr"||!hasSsrEnvironment&&!isLegacySsrBuild)};const getSsrRemoteEntrySource=()=>{if(cachedSsrRemoteEntrySource===undefined)cachedSsrRemoteEntrySource=generateRemoteEntrySSR(options);return cachedSsrRemoteEntrySource};const findNuxtExposesChunk=(bundle)=>{const exposeKeys=Object.keys(options.exposes);if(exposeKeys.length===0)return;return Object.values(bundle).find((file)=>{if(file.type!=="chunk"||!file.fileName.startsWith("_nuxt/")||!file.fileName.endsWith(".js"))return false;const code=file.code||"";return exposeKeys.every((key)=>code.includes(JSON.stringify(key)))})?.fileName};return[{name:"mf:ssr-remote-entry:pre",enforce:"pre",configResolved(config2){isServe=config2.command==="serve";noExternal=config2.environments?.ssr?.resolve?.noExternal??config2.ssr?.noExternal;for(const pkg of ssrOnlyExternals){if(isNoExternal(pkg))continue;const aliasEntry=config2.resolve?.alias?.find((a)=>a.find===pkg||a.find instanceof RegExp&&a.find.test(pkg));if(aliasEntry?.replacement)resolvedAbsToPackage.set(aliasEntry.replacement,pkg)}},resolveId(id,importer){if(id===remoteEntrySSRId||id.startsWith(remoteEntrySSRId))return id;if(id===virtualExposesSSRId||id.startsWith(virtualExposesSSRId))return id;if(!importer||!ssrModuleIds.has(importer))return;if(ssrOnlyExternalPattern.test(id)&&!isNoExternal(id))return{id,external:true};const pkg=resolvedAbsToPackage.get(id);if(pkg)return{id:pkg,external:true};if(id.startsWith(".")||id.startsWith("/")||id.startsWith("file:"))return this.resolve(id,importer,{skipSelf:true}).then((resolved)=>{if(resolved)ssrModuleIds.add(resolved.id);return resolved})}},{name:"mf:ssr-remote-entry",sharedDuringBuild:true,configResolved(config2){viteConfig=config2;isNuxtProject=isNuxtProjectRoot(config2.root);reactIslandExposes=getReactIslandExposes(options,config2.root)},configureServer(server){const base2="/__mf_ssr__";const basePath=getBasePath(viteConfig?.base);const ssrEntryFileName=getSsrRemoteEntryFileName(options);if(isNuxtProject||isNuxtClientBase(basePath))server.middlewares.use((req,_res,next)=>{if(req.url?.replace(/\?.*/,"")===`${basePath}/${ssrEntryFileName}`)req.url=`${basePath}/__mf_ssr__/${ssrEntryFileName}`;next()});const ssrEnv=server.environments?.ssr;const clientEnv=server.environments?.client;const runnerEnv=typeof ssrEnv?.hot?.handleInvoke==="function"?ssrEnv:typeof clientEnv?.hot?.handleInvoke==="function"?clientEnv:undefined;if(typeof(ssrEnv?.fetchModule??clientEnv?.fetchModule)==="function"&&runnerEnv)server.middlewares.use("/__mf_runner__",async(req,res)=>{if(req.method!=="POST"){res.statusCode=405;res.end("Method not allowed");return}try{const rawBody=await readBoundedRunnerBody(req,res);if(!rawBody)return;let body;try{body=JSON.parse(rawBody.toString("utf8"))}catch{res.statusCode=400;res.end(JSON.stringify({error:{message:"Invalid JSON"}}));return}if(!isRunnerInvokePayload(body,server.config)){res.statusCode=400;res.end(JSON.stringify({error:{message:"Invalid runner invoke"}}));return}let result3=await runnerEnv.hot.handleInvoke(body);if("error"in result3&&body.data.name==="fetchModule"){const id=body.data.data[0];const bareId=typeof id==="string"?decodeViteId(id).replace(/^\0/,""):"";if(bareId&&!bareId.startsWith(".")&&!bareId.startsWith("/")&&!bareId.startsWith("file:")&&!/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(bareId))try{const{createRequire:createRequire4}=await import("module");const path11=await import("path");const{pathToFileURL:pathToFileURL5}=await import("url");result3={result:{externalize:pathToFileURL5(createRequire4(pathToFileURL5(path11.join(server.config.root,"package.json"))).resolve(bareId)).href,type:"module"}}}catch{}}res.setHeader("Content-Type","application/json");res.end(JSON.stringify(result3))}catch(e){res.setHeader("Content-Type","application/json");res.end(JSON.stringify({error:{message:String(e instanceof Error?e.message:e)}}))}});const ssrPath=`${base2}/${ssrEntryFileName}`;server.middlewares.use(ssrPath,(_req,res)=>{const exposesUrl=`${base2}/${ssrExposesFileName}`;const code=getSsrRemoteEntrySource().replace(JSON.stringify(virtualExposesSSRId),JSON.stringify(exposesUrl));res.setHeader("Content-Type","application/javascript");res.setHeader("Access-Control-Allow-Origin","*");res.end(code)});const exposesPath=`${base2}/${ssrExposesFileName}`;server.middlewares.use(exposesPath,(_req,res)=>{res.setHeader("Content-Type","application/javascript");res.setHeader("Access-Control-Allow-Origin","*");res.end(generateExposesSSR(options,reactIslandExposes))})},resolveId(id){if(id===remoteEntrySSRId||id.startsWith(remoteEntrySSRId))return id;if(id===virtualExposesSSRId||id.startsWith(virtualExposesSSRId))return id;if(id===`/__mf_ssr__/${getSsrRemoteEntryFileName(options)}`)return remoteEntrySSRId;if(id===`/__mf_ssr__/${ssrExposesFileName}`)return virtualExposesSSRId},load(id){if(id===remoteEntrySSRId||id.startsWith(remoteEntrySSRId))return getSsrRemoteEntrySource();if(id===virtualExposesSSRId||id.startsWith(virtualExposesSSRId))return generateExposesSSR(options,reactIslandExposes)},buildStart(){if(isServe)return;const isRolldown=getIsRolldown(this);const environment=this.environment;if(!isSsrRemoteEntryBuild(environment))return;if(isRolldown)this.emitFile({type:"chunk",id:remoteEntrySSRId,name:"ssrRemoteEntry",fileName:ssrOutputFilename,preserveSignature:"strict"})},generateBundle:{order:"post",handler(_options,bundle){const isRolldown=getIsRolldown(this);const environment=this.environment;const exposesChunk=findNuxtExposesChunk(bundle);if(!isRolldown&&isSsrRemoteEntryBuild(environment)){let source=getSsrRemoteEntrySource();if(exposesChunk)source=source.replace(/import\("virtual:mf-exposes-ssr:[^"]+"\)/g,`import("./${exposesChunk}")`);this.emitFile({type:"asset",fileName:ssrOutputFilename,source})}if(this.environment?.name==="ssr")ssrOutputFiles=collectEntryOutputFiles(bundle,ssrOutputFilename)}},writeBundle(outputOptions){const environmentName=this.environment?.name;if(environmentName==="ssr"&&outputOptions.dir)ssrOutputDir=outputOptions.dir;else if(environmentName==="client"&&outputOptions.dir)clientOutputDir=outputOptions.dir;publishSsrOutputFiles(ssrOutputDir,clientOutputDir||viteConfig?.environments?.client?.build?.outDir)}}];function publishSsrOutputFiles(ssrOutDir,clientOutDir){if(ssrOutputFiles.size===0||!ssrOutDir||!clientOutDir)return;const root=viteConfig?.root??process.cwd();const ssrDir=path$14.resolve(root,ssrOutDir);const clientDir=path$14.resolve(root,clientOutDir);if(ssrDir===clientDir||!fs$12.existsSync(ssrDir))return;fs$12.mkdirSync(clientDir,{recursive:true});for(const fileName of ssrOutputFiles){const source=path$14.resolve(ssrDir,fileName);const destination=path$14.resolve(clientDir,fileName);if(!isResolvedPathWithinDirectory(source,ssrDir)||!isResolvedPathWithinDirectory(destination,clientDir))continue;if(!fs$12.existsSync(source)||fs$12.existsSync(destination))continue;fs$12.mkdirSync(path$14.dirname(destination),{recursive:true});fs$12.copyFileSync(source,destination)}}}var RELATIVE_IMPORT_RE=/(?:\bfrom|\bimport\s*(?:\(\s*)?|\bexport\s*\*\s*from)\s*["'`](\.\.?\/[^"'`]+)["'`]/g;function collectEntryOutputFiles(bundle,entryFileName){const files=new Set;const visit=(fileName)=>{if(files.has(fileName))return;const file=bundle[fileName];if(!file)return;files.add(fileName);const dependencies=new Set([...file.imports||[],...file.dynamicImports||[],...file.implicitlyLoadedBefore||[],...file.referencedFiles||[]]);const source=typeof file.code==="string"?file.code:typeof file.source==="string"?file.source:"";if(source){const directory=path$14.posix.dirname(fileName);for(const match5 of source.matchAll(RELATIVE_IMPORT_RE))dependencies.add(path$14.posix.normalize(path$14.posix.join(directory,match5[1])))}for(const dependency of dependencies)visit(dependency)};visit(entryFileName);return files}function isResolvedPathWithinDirectory(filePath,directory){const relative4=path$14.relative(directory,filePath);return relative4!==""&&!relative4.startsWith(`..${path$14.sep}`)&&relative4!==".."}var VarRemoteEntry=(providedOptions)=>{const mfOptions=providedOptions??getNormalizeModuleFederationOptions();const{name,varFilename,filename}=mfOptions;let viteConfig;return[{name:"module-federation-var-remote-entry",apply:"serve",configResolved(config2){viteConfig=config2},configureServer(server){server.middlewares.use((req,res,next)=>{if(!varFilename){next();return}if(req.url?.replace(/\?.*/,"")===(viteConfig.base+varFilename).replace(/^\/?/,"/")){res.setHeader("Content-Type","text/javascript");res.setHeader("Access-Control-Allow-Origin","*");res.end(generateVarRemoteEntry(filename))}else next()})}},{name:"module-federation-var-remote-entry",enforce:"post",config(config2){if(!config2.build)config2.build={}},configResolved(config2){viteConfig=config2},async generateBundle(_options,bundle){if(!varFilename)return;if(!isValidVarName(name))mfWarn(`Provided remote name "${name}" is not valid for "var" remoteEntry type, thus it's placed in globalThis['${name}'].
3146
+ export const __mf_remote_dependency_pending = Promise.all([${dependencyPendingIds.join(", ")}]);`);return{code:ms.toString(),map:ms.generateMap(id)}}async function collectFromAST(ast,code,isRemoteImport){const result3=[];walkAST(ast,{enter(node){if(node.type==="ImportDeclaration"&&node.source?.value){if(!isRemoteImport(node.source.value))return;const specifiers=node.specifiers||[];const named=specifiers.filter((s)=>s.type==="ImportSpecifier"&&s.importKind!=="type").map((s)=>({imported:s.imported.name??s.imported.value,local:s.local.name}));const defaultSpec=specifiers.find((s)=>s.type==="ImportDefaultSpecifier");const nsSpec=specifiers.find((s)=>s.type==="ImportNamespaceSpecifier");if(named.length===0&&!nsSpec)return;result3.push({kind:"static",source:node.source.value,start:node.start,end:node.end,named,defaultLocal:defaultSpec?.local.name,namespaceLocal:nsSpec?.local.name})}if(node.type==="ExportNamedDeclaration"&&node.source?.value&&isRemoteImport(node.source.value)){const specifiers=(node.specifiers||[]).filter((s)=>s.exportKind!=="type").map((s)=>({local:s.local.name??s.local.value,exported:s.exported.name??s.exported.value}));if(specifiers.length===0)return;result3.push({kind:"reexport",source:node.source.value,start:node.start,end:node.end,specifiers})}if(node.type==="ExportAllDeclaration"&&node.source?.value&&isRemoteImport(node.source.value)){this.skip();result3.push({kind:"export-all",source:node.source.value,start:node.start,end:node.end})}if(node.type==="ImportExpression"){const source=node.source;if(source.type!=="Literal"&&source.type!=="StringLiteral"&&source.type!=="TemplateLiteral")return;const value3=source.type==="TemplateLiteral"?source.quasis?.length===1?source.quasis[0].value?.cooked:undefined:source.value;if(!value3||!isRemoteImport(value3))return;result3.push({kind:"dynamic",source:value3,start:node.start,end:node.end,originalText:code.slice(node.start,node.end)})}}});return result3}function collectFromRegex(code,isRemoteImport){const result3=[];const codePositions=createCodePositionMap(code);const importAttributes=String.raw`(?:\s+(?:with|assert)\s+\{[^;]*\})?`;const staticRe=new RegExp(String.raw`^\s*import\s+([\s\S]*?)\s+from\s+(['"])([^'"]+)\2${importAttributes}\s*;?`,"gm");for(const match5 of code.matchAll(staticRe)){const[full,specifiersPartRaw,,source]=match5;if(!codePositions[match5.index])continue;if(!isRemoteImport(source))continue;const specifiersPart=specifiersPartRaw.trim();if(/^type\s/.test(specifiersPart))continue;const nsMatch=specifiersPart.match(/^\*\s+as\s+(\w+)$/);if(nsMatch){result3.push({kind:"static",source,start:match5.index,end:match5.index+full.length,named:[],namespaceLocal:nsMatch[1]});continue}const braceMatch=specifiersPart.match(/\{([^}]*)\}/);if(!braceMatch)continue;const named=parseNamedSpecifiers(braceMatch[1],"import");if(named.length===0)continue;const defaultMatch=specifiersPart.match(/^(\w+)\s*,/);result3.push({kind:"static",source,start:match5.index,end:match5.index+full.length,named,defaultLocal:defaultMatch?.[1]})}const reexportRe=new RegExp(String.raw`^\s*export\s+\{([\s\S]*?)\}\s+from\s+(['"])([^'"]+)\2${importAttributes}\s*;?`,"gm");for(const match5 of code.matchAll(reexportRe)){const[full,specifiersRaw,,source]=match5;if(!codePositions[match5.index])continue;if(!isRemoteImport(source))continue;const specifiers=parseNamedSpecifiers(specifiersRaw,"export");if(specifiers.length===0)continue;result3.push({kind:"reexport",source,start:match5.index,end:match5.index+full.length,specifiers})}const exportAllRe=new RegExp(String.raw`^\s*export\s+\*\s+from\s+(['"])([^'"]+)\1${importAttributes}\s*;?`,"gm");for(const match5 of code.matchAll(exportAllRe)){const[full,,source]=match5;if(!codePositions[match5.index])continue;if(!isRemoteImport(source))continue;result3.push({kind:"export-all",source,start:match5.index,end:match5.index+full.length})}for(const match5 of code.matchAll(/import\(\s*(?:\/\*[\s\S]*?\*\/\s*)?(['"])([^'"]+)\1\s*\)/g)){const[full,,source]=match5;if(!codePositions[match5.index])continue;if(!isRemoteImport(source))continue;result3.push({kind:"dynamic",source,start:match5.index,end:match5.index+full.length,originalText:full})}return result3.length>0?result3:undefined}function pluginRemoteNamedExports(options){const remoteNames=Object.keys(options.remotes);let root=process.cwd();const isNodeModulesId=(id)=>id.includes("/node_modules/")||id.includes("\\node_modules\\");function isRemoteImport(source,importerId){return remoteNames.some((name)=>{if(source.startsWith(name+"/"))return true;if(source!==name)return false;return!isNodeModulesId(importerId)||!getInstalledPackageEntry(source,{cwd:root})})||source.includes("__loadRemote__")}return{name:"module-federation-remote-named-exports",enforce:"post",configResolved(config2){root=config2.root||process.cwd()},async transform(code,id){if(remoteNames.length===0)return;if(id.includes("__loadRemote__")||id.includes("__loadShare__"))return;if(!JS_EXTENSIONS_RE.test(id))return;if(!remoteNames.some((name)=>code.includes(name)))return;const matchesRemoteImport=(source)=>isRemoteImport(source,id);for(const{kind,source,typeOnly}of findModuleImportDescriptors(code))if(kind==="static"&&!typeOnly&&matchesRemoteImport(source))markStaticRemote(source,options);let imports;try{imports=await collectFromAST(this.parse(code),code,matchesRemoteImport)}catch{if((id.includes(".vue")||id.includes(".svelte"))&&/^\s*</.test(code))return;imports=collectFromRegex(code,matchesRemoteImport)}if(!imports)return;for(const remoteImport of imports)if(remoteImport.kind==="dynamic")markDynamicRemote(remoteImport.source,options);return applyRewrites(code,imports,id)}}}var MAX_RUNNER_BODY_BYTES=1048576;var MAX_RUNNER_START_OFFSET=1048576;var ALLOWED_RUNNER_INVOKE_NAMES=new Set(["fetchModule","getBuiltins"]);function isPlainObject(value3){return!!value3&&typeof value3==="object"&&!Array.isArray(value3)}function isSafeRunnerFetchModuleOptions(value3){if(!isPlainObject(value3))return false;const allowedKeys=new Set(["cached","startOffset","inlineSourceMap"]);for(const[key,option2]of Object.entries(value3)){if(!allowedKeys.has(key))return false;if(key==="startOffset"){if(typeof option2!=="number"||!Number.isSafeInteger(option2)||option2<0||option2>MAX_RUNNER_START_OFFSET)return false}else if(typeof option2!=="boolean")return false}return true}function decodeRunnerFilePath(filePath){try{return decodeURIComponent(filePath)}catch{return}}function hasRelativeTraversal(id){return id.split(/[\\/]+/).includes("..")}function getRealPathIfExists(filePath){try{return fs$12.realpathSync.native(filePath)}catch{return}}function isCanonicalPathWithinDirectory(filePath,directory){const realFilePath=getRealPathIfExists(filePath)??path$14.resolve(filePath);const realDirectory=getRealPathIfExists(directory)??path$14.resolve(directory);const relative4=path$14.relative(realDirectory,realFilePath);return relative4===""||!relative4.startsWith("..")&&!path$14.isAbsolute(relative4)}function getRunnerAllowedDirectories(config2){return[config2.root,...config2.server?.fs?.allow??[]].map((directory)=>path$14.resolve(directory))}function isPathWithinAllowedDirectories(filePath,allowedDirectories){return allowedDirectories.some((directory)=>isCanonicalPathWithinDirectory(filePath,directory))}function isSafeRunnerFetchModuleId(id,config2){if(typeof id!=="string"||!id)return false;const decoded=decodeViteId(id).replace(/^\0+/,"");if(!decoded||decoded.startsWith("virtual:"))return!!decoded;if(decoded.startsWith("file://"))try{const filePath=decodeURIComponent(new URL(decoded).pathname);return path$14.isAbsolute(filePath)&&isPathWithinAllowedDirectories(filePath,getRunnerAllowedDirectories(config2))}catch{return false}if(/^(?:https?|data|blob|javascript):/i.test(decoded)||decoded.startsWith("//"))return false;const cleanId=decodeRunnerFilePath(stripQueryAndHash(decoded));if(!cleanId||hasRelativeTraversal(cleanId))return false;const allowedDirectories=getRunnerAllowedDirectories(config2);if(cleanId.startsWith("/@fs/")){const fsPath=stripViteFsPrefix(cleanId);return path$14.isAbsolute(fsPath)&&isPathWithinAllowedDirectories(fsPath,allowedDirectories)}if(path$14.isAbsolute(cleanId)){if(isPathWithinAllowedDirectories(cleanId,allowedDirectories))return true;return!fs$12.existsSync(cleanId)}return true}function isRunnerInvokePayload(payload,config2){if(!payload||typeof payload!=="object")return false;if(payload.type!=="custom"||payload.event!=="vite:invoke")return false;const data2=payload.data;if(!data2||typeof data2!=="object")return false;const name=data2.name;const args2=data2.data;if(typeof name!=="string"||!ALLOWED_RUNNER_INVOKE_NAMES.has(name)||!Array.isArray(args2))return false;if(name==="getBuiltins")return args2.length===0;if(args2.length<1||args2.length>3)return false;const[id,importer,opts]=args2;return isSafeRunnerFetchModuleId(id,config2)&&(importer===undefined||importer===null||isSafeRunnerFetchModuleId(importer,config2))&&(opts===undefined||isSafeRunnerFetchModuleOptions(opts))}function readBoundedRunnerBody(req,res){return new Promise((resolve9)=>{const chunks=[];let size=0;let done3=false;const fail13=(statusCode,message)=>{if(done3)return;done3=true;res.statusCode=statusCode;res.end(message);resolve9(undefined)};req.on("data",(chunk)=>{if(done3)return;size+=chunk.length;if(size>MAX_RUNNER_BODY_BYTES)return fail13(413,"Payload too large");chunks.push(chunk)});req.on("end",()=>{if(done3)return;done3=true;resolve9(Buffer.concat(chunks))});req.on("error",()=>fail13(400,"Bad request"))})}function pluginSSRRemoteEntry(options){const remoteEntrySSRId=getRemoteEntrySSRId(options);const virtualExposesSSRId=getVirtualExposesSSRId(options);let cachedSsrRemoteEntrySource;const ssrOutputFilename=getSsrRemoteEntryFileName(options);const ssrExposesFileName=getSsrExposesFileName(options.filename);let ssrOutputFiles=new Set;let ssrOutputDir="";let clientOutputDir="";const mfRuntimePackages=["@module-federation/runtime","@module-federation/runtime-core","@module-federation/sdk"];const ssrOnlyExternals=[...mfRuntimePackages,...options.ssrExternals??[]];const ssrOnlyExternalPattern=new RegExp(`^(${ssrOnlyExternals.map((e)=>e.replace(/[/\\^$*+?.()|[\]{}]/g,"\\$&")).join("|")})(\\/.*)?$`);let noExternal;const isNoExternal=(id)=>{const pkg=ssrOnlyExternalPattern.exec(id)?.[1]??id;if(!noExternal||!mfRuntimePackages.includes(pkg))return false;if(noExternal===true)return true;return(Array.isArray(noExternal)?noExternal:[noExternal]).some((rule)=>typeof rule==="string"?rule===pkg:rule.test(pkg))};const ssrModuleIds=new Set([remoteEntrySSRId,virtualExposesSSRId]);const resolvedAbsToPackage=new Map;let isServe=false;let viteConfig;let isNuxtProject=false;let reactIslandExposes=new Set;const isSsrRemoteEntryBuild=(environment)=>{const environmentName=environment?.name;const hasSsrEnvironment=Boolean(viteConfig?.environments?.ssr);const isLegacySsrBuild=Boolean(environment?.config?.build?.ssr??viteConfig?.build?.ssr);return Object.keys(options.exposes).length>0&&!(hasSsrEnvironment&&environmentName!=="ssr"||!hasSsrEnvironment&&!isLegacySsrBuild)};const getSsrRemoteEntrySource=()=>{if(cachedSsrRemoteEntrySource===undefined)cachedSsrRemoteEntrySource=generateRemoteEntrySSR(options);return cachedSsrRemoteEntrySource};const findNuxtExposesChunk=(bundle)=>{const exposeKeys=Object.keys(options.exposes);if(exposeKeys.length===0)return;return Object.values(bundle).find((file)=>{if(file.type!=="chunk"||!file.fileName.startsWith("_nuxt/")||!file.fileName.endsWith(".js"))return false;const code=file.code||"";return exposeKeys.every((key)=>code.includes(JSON.stringify(key)))})?.fileName};return[{name:"mf:ssr-remote-entry:pre",enforce:"pre",configResolved(config2){isServe=config2.command==="serve";noExternal=config2.environments?.ssr?.resolve?.noExternal??config2.ssr?.noExternal;for(const pkg of ssrOnlyExternals){if(isNoExternal(pkg))continue;const aliasEntry=config2.resolve?.alias?.find((a)=>a.find===pkg||a.find instanceof RegExp&&a.find.test(pkg));if(aliasEntry?.replacement)resolvedAbsToPackage.set(aliasEntry.replacement,pkg)}},resolveId(id,importer){if(id===remoteEntrySSRId||id.startsWith(remoteEntrySSRId))return id;if(id===virtualExposesSSRId||id.startsWith(virtualExposesSSRId))return id;if(!importer||!ssrModuleIds.has(importer))return;if(ssrOnlyExternalPattern.test(id)&&!isNoExternal(id))return{id,external:true};const pkg=resolvedAbsToPackage.get(id);if(pkg)return{id:pkg,external:true};if(id.startsWith(".")||id.startsWith("/")||id.startsWith("file:"))return this.resolve(id,importer,{skipSelf:true}).then((resolved)=>{if(resolved)ssrModuleIds.add(resolved.id);return resolved})}},{name:"mf:ssr-remote-entry",sharedDuringBuild:true,configResolved(config2){viteConfig=config2;isNuxtProject=isNuxtProjectRoot(config2.root);reactIslandExposes=getReactIslandExposes(options,config2.root)},configureServer(server){const base2="/__mf_ssr__";const basePath=getBasePath(viteConfig?.base);const ssrEntryFileName=getSsrRemoteEntryFileName(options);if(isNuxtProject||isNuxtClientBase(basePath))server.middlewares.use((req,_res,next)=>{if(req.url?.replace(/\?.*/,"")===`${basePath}/${ssrEntryFileName}`)req.url=`${basePath}/__mf_ssr__/${ssrEntryFileName}`;next()});const ssrEnv=server.environments?.ssr;const clientEnv=server.environments?.client;const runnerEnv=typeof ssrEnv?.hot?.handleInvoke==="function"?ssrEnv:typeof clientEnv?.hot?.handleInvoke==="function"?clientEnv:undefined;if(typeof(ssrEnv?.fetchModule??clientEnv?.fetchModule)==="function"&&runnerEnv)server.middlewares.use("/__mf_runner__",async(req,res)=>{if(req.method!=="POST"){res.statusCode=405;res.end("Method not allowed");return}try{const rawBody=await readBoundedRunnerBody(req,res);if(!rawBody)return;let body;try{body=JSON.parse(rawBody.toString("utf8"))}catch{res.statusCode=400;res.end(JSON.stringify({error:{message:"Invalid JSON"}}));return}if(!isRunnerInvokePayload(body,server.config)){res.statusCode=400;res.end(JSON.stringify({error:{message:"Invalid runner invoke"}}));return}let result3=await runnerEnv.hot.handleInvoke(body);if("error"in result3&&body.data.name==="fetchModule"){const id=body.data.data[0];const bareId=typeof id==="string"?decodeViteId(id).replace(/^\0/,""):"";if(bareId&&!bareId.startsWith(".")&&!bareId.startsWith("/")&&!bareId.startsWith("file:")&&!/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(bareId))try{const{createRequire:createRequire4}=await import("module");const path11=await import("path");const{pathToFileURL:pathToFileURL5}=await import("url");result3={result:{externalize:pathToFileURL5(createRequire4(pathToFileURL5(path11.join(server.config.root,"package.json"))).resolve(bareId)).href,type:"module"}}}catch{}}res.setHeader("Content-Type","application/json");res.end(JSON.stringify(result3))}catch(e){res.setHeader("Content-Type","application/json");res.end(JSON.stringify({error:{message:String(e instanceof Error?e.message:e)}}))}});const ssrPath=`${base2}/${ssrEntryFileName}`;server.middlewares.use(ssrPath,(_req,res)=>{const exposesUrl=`${base2}/${ssrExposesFileName}`;const code=getSsrRemoteEntrySource().replace(JSON.stringify(virtualExposesSSRId),JSON.stringify(exposesUrl));res.setHeader("Content-Type","application/javascript");res.setHeader("Access-Control-Allow-Origin","*");res.end(code)});const exposesPath=`${base2}/${ssrExposesFileName}`;server.middlewares.use(exposesPath,(_req,res)=>{res.setHeader("Content-Type","application/javascript");res.setHeader("Access-Control-Allow-Origin","*");res.end(generateExposesSSR(options,reactIslandExposes))})},resolveId(id){if(id===remoteEntrySSRId||id.startsWith(remoteEntrySSRId))return id;if(id===virtualExposesSSRId||id.startsWith(virtualExposesSSRId))return id;if(id===`/__mf_ssr__/${getSsrRemoteEntryFileName(options)}`)return remoteEntrySSRId;if(id===`/__mf_ssr__/${ssrExposesFileName}`)return virtualExposesSSRId},load(id){if(id===remoteEntrySSRId||id.startsWith(remoteEntrySSRId))return getSsrRemoteEntrySource();if(id===virtualExposesSSRId||id.startsWith(virtualExposesSSRId))return generateExposesSSR(options,reactIslandExposes)},buildStart(){if(isServe)return;const isRolldown=getIsRolldown(this);const environment=this.environment;if(!isSsrRemoteEntryBuild(environment))return;if(isRolldown)this.emitFile({type:"chunk",id:remoteEntrySSRId,name:"ssrRemoteEntry",fileName:ssrOutputFilename,preserveSignature:"strict"})},generateBundle:{order:"post",handler(_options,bundle){const isRolldown=getIsRolldown(this);const environment=this.environment;const exposesChunk=findNuxtExposesChunk(bundle);if(!isRolldown&&isSsrRemoteEntryBuild(environment)){let source=getSsrRemoteEntrySource();if(exposesChunk)source=source.replace(/import\("virtual:mf-exposes-ssr:[^"]+"\)/g,`import("./${exposesChunk}")`);this.emitFile({type:"asset",fileName:ssrOutputFilename,source})}if(this.environment?.name==="ssr")ssrOutputFiles=collectEntryOutputFiles(bundle,ssrOutputFilename)}},writeBundle(outputOptions){const environmentName=this.environment?.name;if(environmentName==="ssr"&&outputOptions.dir)ssrOutputDir=outputOptions.dir;else if(environmentName==="client"&&outputOptions.dir)clientOutputDir=outputOptions.dir;publishSsrOutputFiles(ssrOutputDir,clientOutputDir||viteConfig?.environments?.client?.build?.outDir)}}];function publishSsrOutputFiles(ssrOutDir,clientOutDir){if(ssrOutputFiles.size===0||!ssrOutDir||!clientOutDir)return;const root=viteConfig?.root??process.cwd();const ssrDir=path$14.resolve(root,ssrOutDir);const clientDir=path$14.resolve(root,clientOutDir);if(ssrDir===clientDir||!fs$12.existsSync(ssrDir))return;fs$12.mkdirSync(clientDir,{recursive:true});for(const fileName of ssrOutputFiles){const source=path$14.resolve(ssrDir,fileName);const destination=path$14.resolve(clientDir,fileName);if(!isResolvedPathWithinDirectory(source,ssrDir)||!isResolvedPathWithinDirectory(destination,clientDir))continue;if(!fs$12.existsSync(source)||fs$12.existsSync(destination))continue;fs$12.mkdirSync(path$14.dirname(destination),{recursive:true});fs$12.copyFileSync(source,destination)}}}var RELATIVE_IMPORT_RE=/(?:\bfrom|\bimport\s*(?:\(\s*)?|\bexport\s*\*\s*from)\s*["'`](\.\.?\/[^"'`]+)["'`]/g;function collectEntryOutputFiles(bundle,entryFileName){const files=new Set;const visit=(fileName)=>{if(files.has(fileName))return;const file=bundle[fileName];if(!file)return;files.add(fileName);const dependencies=new Set([...file.imports||[],...file.dynamicImports||[],...file.implicitlyLoadedBefore||[],...file.referencedFiles||[]]);const source=typeof file.code==="string"?file.code:typeof file.source==="string"?file.source:"";if(source){const directory=path$14.posix.dirname(fileName);for(const match5 of source.matchAll(RELATIVE_IMPORT_RE))dependencies.add(path$14.posix.normalize(path$14.posix.join(directory,match5[1])))}for(const dependency of dependencies)visit(dependency)};visit(entryFileName);return files}function isResolvedPathWithinDirectory(filePath,directory){const relative4=path$14.relative(directory,filePath);return relative4!==""&&!relative4.startsWith(`..${path$14.sep}`)&&relative4!==".."}var VarRemoteEntry=(providedOptions)=>{const mfOptions=providedOptions??getNormalizeModuleFederationOptions();const{name,varFilename,filename}=mfOptions;let viteConfig;return[{name:"module-federation-var-remote-entry",apply:"serve",configResolved(config2){viteConfig=config2},configureServer(server){server.middlewares.use((req,res,next)=>{if(!varFilename){next();return}if(req.url?.replace(/\?.*/,"")===(viteConfig.base+varFilename).replace(/^\/?/,"/")){res.setHeader("Content-Type","text/javascript");res.setHeader("Access-Control-Allow-Origin","*");res.end(generateVarRemoteEntry(filename))}else next()})}},{name:"module-federation-var-remote-entry",enforce:"post",config(config2){if(!config2.build)config2.build={}},configResolved(config2){viteConfig=config2},async generateBundle(_options,bundle){if(!varFilename)return;if(!isValidVarName(name))mfWarn(`Provided remote name "${name}" is not valid for "var" remoteEntry type, thus it's placed in globalThis['${name}'].
3139
3147
  It may cause problems, so you would better want to use valid var name (see https://www.w3schools.com/js/js_variables.asp).`);const remoteEntryFile=findRemoteEntryFile(mfOptions.filename,bundle);if(!remoteEntryFile)throw createModuleFederationError(`Couldn't find a remoteEntry chunk file for ${mfOptions.filename}, can't generate varRemoteEntry file`);this.emitFile({type:"asset",fileName:varFilename,source:generateVarRemoteEntry(remoteEntryFile)})}}];function isValidVarName(name2){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name2)}function generateVarRemoteEntry(remoteEntryFile){const{name:name2,varFilename:varFilename2}=mfOptions;const isValidName=isValidVarName(name2);return`
3140
3148
  ${isValidName?`var ${name2};`:""}
3141
3149
  ${isValidName?name2:`globalThis['${name2}']`} = (function () {
@@ -3185,17 +3193,25 @@ import * as loaded from ${JSON.stringify(input.contributionImport)}
3185
3193
  export const ${moduleExport3(input.exportName)} = loaded[${JSON.stringify(input.exportName)}]
3186
3194
  `;var contributionKey2=(input)=>JSON.stringify([input.packageFqn,input.contributionHost,input.contributionFqn]);var exposedModule=(key)=>`./${key}`;var randomUuid2=()=>{const bytes2=new Uint8Array(16);crypto.getRandomValues(bytes2);bytes2[6]=bytes2[6]%16+64;bytes2[8]=bytes2[8]%64+128;const hex=[...bytes2].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(id2){return id2.startsWith(virtualPrefix)?entries.get(decodeURIComponent(id2.slice(virtualPrefix.length)))?.source??null:null},name:"ci-hosted-development-entries",resolveId(id2){return id2.startsWith("virtual:ci-hosted:")?`\x00${id2}`:null}};const shared=Object.fromEntries(frontendHostProvidedModules.map((moduleName)=>[moduleName,{import:false,singleton:true,suppressMissingImportWarning:true}]));const declarationPath=declarationImport(input.declarationSpecifier);const root=path11.isAbsolute(declarationPath)?path11.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 server2=frontendServer;if(server2!==undefined){yield*promise2(()=>warmFrontendServer(server2))}return yield*void_3}const previousServer=frontendServer;const port=frontendServerPort??0;frontendServer=undefined;if(previousServer!==undefined){yield*promise2(()=>previousServer.close())}frontendEntries=entries;if(entries.size===0){frontendServerPort=undefined;return yield*void_3}const server=yield*promise2(()=>startFrontendServer(entries,port));frontendServer=server;const localUrl=server.resolvedUrls?.local.at(0);if(localUrl===undefined){yield*promise2(()=>server.close());frontendServer=undefined;throw new Error("Vite did not publish a loopback development URL")}frontendServerPort=Number(new URL(localUrl).port);return yield*void_3}),runNested2);const rebuild=flow((declarations)=>gen2(function*rebuildServer(){const nextFrontendEntries=new Map;for(const definition of declarations){for(const contribution of definition.hostedContributions){if(contribution.manifest.host==="backend"){continue}const key=contributionKey2({contributionFqn:contribution.manifest.fqn,contributionHost:contribution.manifest.host,packageFqn:definition.manifest.fqn});const importPath=resolveHostedContributionEntry(input.declarationSpecifier,{fqn:contribution.manifest.fqn,load:contribution.load});const source=virtualModuleSource({contributionImport:importPath,exportName:contribution.manifest.exportName});nextFrontendEntries.set(key,{importPath,source})}}yield*promise2(()=>synchronizeFrontendServer(nextFrontendEntries))}),runNested2);yield*promise2(()=>rebuild(input.declarations)).pipe(tapError2(()=>promise2(()=>frontendServer?.close().then(()=>null).catch(()=>null)??Promise.resolve(null)).pipe(andThen2(()=>promise2(()=>removeTempDirectory(frontendCacheDirectory))))));return{assetsFor:flow((definition)=>sync2(()=>definition.hostedContributions.flatMap(({manifest})=>{if(manifest.host==="backend"){return[]}const key=contributionKey2({contributionFqn:manifest.fqn,contributionHost:manifest.host,packageFqn:definition.manifest.fqn});const localUrl=frontendServer?.resolvedUrls?.local.at(0);if(localUrl===undefined){throw new Error(`Vite federation remote was not started for ${manifest.fqn}`)}const moduleUrl=new URL("remoteEntry.js",localUrl);moduleUrl.hash=encodeURIComponent(exposedModule(key));return{...manifest.compatibility===undefined?undefined:{compatibility:manifest.compatibility},contract:manifest.contract,exportName:manifest.exportName,fqn:manifest.fqn,host:manifest.host,moduleUrl:moduleUrl.href}})),runNested2),close:flow(()=>gen2(function*closeServer(){const server=frontendServer;if(server!==undefined){yield*promise2(()=>server.close())}yield*promise2(()=>removeTempDirectory(frontendCacheDirectory))}),runPromiseWith2(empty())),rebuild}}),runPromise2);class PackageDiagnosticsCommandError extends TaggedError3()("PackageDiagnosticsCommandError",{cause:optional2(Unknown2),message:String4}){}var requireOption3=(options,name)=>{const value3=options.get(name);if(value3===undefined||value3===""){throw new PackageDiagnosticsCommandError({message:`Missing required option --${name}`})}return value3};var parseOptions3=(args2)=>{const options=new Map;for(let index=1;index<args2.length;index+=2){const flag=args2[index];const value3=args2[index+1];if(!flag?.startsWith("--")||!value3||value3.startsWith("--")){throw new PackageDiagnosticsCommandError({message:"Options must be supplied as --name value pairs"})}options.set(flag.slice(2),value3)}return options};var packageDiagnosticsCommandEffect=(args2,dependencies)=>{const[command]=args2;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(args2)}).pipe(flatMap3((options)=>tryPromise2({catch:(cause)=>new PackageDiagnosticsCommandError({cause,message:"Could not read hosted Extension diagnostic trace"}),try:async()=>{const response=await hostedExtensionDiagnosticsReadTrace({client:dependencies.client,headers:{"x-organization-id":requireOption3(options,"organization")},path:{diagnosticId:requireOption3(options,"diagnostic")},throwOnError:true});return response.data}})))};import{createHash as createHash6}from"crypto";var awaitValue7=(value3)=>promise2(constant(Promise.resolve(value3)));var path12=runSync2(provide3(Path2,exports_NodePath.layer));var readBytesEffect=(readBytes,filePath)=>tryPromise2(flow(()=>suspend2(()=>awaitValue7(readBytes(filePath))),runPromise2));class PackageReleaseCommandError extends TaggedError3()("PackageReleaseCommandError",{cause:optional2(Unknown2),message:String4}){}var requireOption4=(options,name)=>{const value3=options.get(name);if(value3===undefined||value3===""){throw new PackageReleaseCommandError({message:`Missing required option --${name}`})}return value3};var supportedOptions=new Set(["archive","backend-url","bundle","idempotency-key","installation","manifest","organization","package","package-manifest","private-maps","release","scope","setup-file","version"]);var parseOptions4=(args2)=>{const options=new Map;for(let index=1;index<args2.length;index+=2){const flag=args2[index];const value3=args2[index+1];if(!flag?.startsWith("--")||!value3||value3.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),value3)}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=(bytes2)=>createHash6("sha256").update(bytes2).digest("hex");var executePublish=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not publish package release"}),try:async()=>{rejectRetiredPublishOptions(options);const archiveBytes=await dependencies.readBytes(requireOption4(options,"archive"));const manifestPath=requireOption4(options,"manifest");const manifestBytes=await dependencies.readBytes(manifestPath);const packageManifestBytes=await dependencies.readBytes(requireOption4(options,"package-manifest"));const privateMapDirectory=options.has("private-maps")?requireOption4(options,"private-maps"):path12.join(path12.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 bytes2=yield*readBytesEffect(dependencies.readBytes,path12.join(privateMapDirectory,fileName));return{bytes:bytes2,digest:digest3(bytes2),runtimeAssetDigest:fileName.slice(0,-4),size:bytes2.byteLength}}),runPromise2)));const body=await preparePackagePublication({archiveBytes,manifestBytes,packageManifestBytes,privateSourceMaps});const accepted=await publishPackage({body,client:dependencies.client,idempotencyKey:requireOption4(options,"idempotency-key")});return accepted.operationId}});var executePromote=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not promote package release"}),try:async()=>{const body={protocolVersion:"v1",releaseId:requireOption4(options,"release")};const accepted=await promotePackage({body,client:dependencies.client,idempotencyKey:requireOption4(options,"idempotency-key")});return accepted.operationId}});var executeUpdate=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not update package installation"}),try:async()=>{const setupFile=options.get("setup-file");const setup=setupFile===undefined?undefined:await readConnectorSetup(setupFile,dependencies.readBytes);const body={...setup===undefined?undefined:{setup},installationId:requireOption4(options,"installation"),protocolVersion:"v1",releaseId:requireOption4(options,"release")};const accepted=await updatePackage({body,client:dependencies.client,idempotencyKey:requireOption4(options,"idempotency-key"),organizationId:requireOption4(options,"organization")});return accepted.operationId}});var executeInstall=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not install package"}),try:async()=>{const releaseId=options.get("release");const setupFile=options.get("setup-file");const setup=setupFile===undefined?undefined:await readConnectorSetup(setupFile,dependencies.readBytes);const accepted=await installPackage({...releaseId===undefined&&setup===undefined?undefined:{body:{...releaseId===undefined?undefined:{releaseId},...setup===undefined?undefined:{setup}}},client:dependencies.client,idempotencyKey:requireOption4(options,"idempotency-key"),organizationId:requireOption4(options,"organization"),packageFqn:requireOption4(options,"package")});return accepted.operationId}});var executeSync=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not sync package"}),try:async()=>{if(options.has("release")){throw new PackageReleaseCommandError({message:"package sync re-applies the current release and does not accept --release; use package update --release for an exact release"})}const accepted=await extensionPackagesSync({client:dependencies.client,headers:administratorHeaders(options),path:{fqn:requireOption4(options,"package")},throwOnError:true});return accepted.data.operationId}});var executeRollback=(options,dependencies)=>tryPromise2({catch:(cause)=>is2(PackageReleaseCommandError)(cause)?cause:new PackageReleaseCommandError({cause,message:"Could not roll back package installation"}),try:async()=>{const accepted=await packageReleasesRollbackInstallation({body:{installationId:requireOption4(options,"installation"),protocolVersion:"v1",releaseId:requireOption4(options,"release")},client:dependencies.client,headers:administratorHeaders(options),throwOnError:true});return accepted.data.operationId}});var packageReleaseCommandEffect=(args2,dependencies)=>{const[command]=args2;const options=parseOptions4(args2);if(options.has("setup-file")&&command!=="install"&&command!=="update"){return fail6(new PackageReleaseCommandError({message:"--setup-file is supported only for package install/update"}))}switch(command){case"install":{return executeInstall(options,dependencies)}case"publish":{return executePublish(options,dependencies)}case"promote":{return executePromote(options,dependencies)}case"rollback":{return executeRollback(options,dependencies)}case"sync":{return executeSync(options,dependencies)}case"update":{return executeUpdate(options,dependencies)}default:{return fail6(new PackageReleaseCommandError({message:"Expected one of: package publish, package promote, package install, package update, package sync, package rollback"}))}}};class PackageReleasesCommandError extends TaggedError3()("PackageReleasesCommandError",{cause:optional2(Unknown2),message:String4}){}var requireOption5=(options,name)=>{const value3=options.get(name);if(value3===undefined||value3===""){throw new PackageReleasesCommandError({message:`Missing required option --${name}`})}return value3};var parseOptions5=(args2)=>{const options=new Map;for(let index=0;index<args2.length;index+=2){const flag=args2[index];const value3=args2[index+1];if(!flag?.startsWith("--")||!value3||value3.startsWith("--")){throw new PackageReleasesCommandError({message:"Options must be supplied as --name value pairs"})}options.set(flag.slice(2),value3)}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}});class WhoamiCommandError extends TaggedError3()("WhoamiCommandError",{cause:optional2(Unknown2),message:String4}){}var whoamiCommandEffect=(args2,dependencies)=>gen2(function*whoamiCommand(){yield*parseCommandOptionsEffect(args2,{values:targetOptions});const target=yield*tryConfiguration(()=>resolveBackendManagementTarget({args:args2,environment:dependencies.environment,organizationLookup:true}));const identity3=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=identity3.organizationId===undefined?undefined:`${identity3.organizationName??identity3.organizationId} (${identity3.organizationId})`;const lines=identity3.credentialKind==="api_key"?[`Credential: ${source}`,`API key: ${identity3.apiKeyName??identity3.id}`,`API key Organization: ${keyOrganization??"unknown"}`,`Tenant: ${target.apiOrigin}`,`Current Organization: ${target.organizationId??identity3.organizationId??"none"}`]:[`Credential: ${source}`,`User: ${identity3.name??identity3.email??identity3.id}${identity3.email===null?"":` <${identity3.email}>`}`,`Tenant: ${target.apiOrigin}`,`Current Organization: ${target.organizationId??"none (run ci orgs use <organization-id>)"}`,`Session expires: ${identity3.sessionExpiresAt??"unknown"}`];dependencies.writeOutput(`${lines.join(`
3187
3195
  `)}
3188
- `)}).pipe(mapError2((cause)=>new WhoamiCommandError({cause,message:cause.message})));import{fileURLToPath as fileURLToPath13}from"url";var{existsSync:existsSync9,watch:watch3}=await import("fs");var path13=runSync2(provide3(Path2,exports_NodePath.layer));var declarationPackageRoot=(declarationPath)=>{const declarationDirectory=path13.dirname(declarationPath);let candidate=declarationDirectory;while(true){if(existsSync9(path13.join(candidate,"package.json"))){return candidate}const parent=path13.dirname(candidate);if(parent===candidate){return declarationDirectory}candidate=parent}};var watchPackageDeclaration=(specifier,refresh,reportFailure)=>{if(!specifier.startsWith("file:")){return{close:flow(()=>promise2(constant(Promise.resolve())),runPromise2)}}let closed=false;let refreshGeneration=0;let refreshQueue=Promise.resolve();const scheduleRefresh=()=>{refreshGeneration+=1;const generation=refreshGeneration;runPromise2(sleep2("25 millis").pipe(flatMap3(()=>{if(closed||generation!==refreshGeneration){return void_3}const previousRefresh=refreshQueue;refreshQueue=runPromise2(gen2(function*refreshDeclaration(){yield*promise2(constant(previousRefresh));yield*tryPromise2(refresh).pipe(catch_2((error3)=>sync2(()=>{reportFailure(error3 instanceof Error?error3:new Error(String(error3)))})))}));return void_3})))};const watcher=watch3(declarationPackageRoot(fileURLToPath13(specifier)),{recursive:true},scheduleRefresh);watcher.on("error",(error3)=>{reportFailure(error3)});return{close:flow(()=>gen2(function*closeWatcher(){closed=true;refreshGeneration+=1;watcher.close();yield*promise2(constant(refreshQueue))}),runPromise2)}};var awaitValue8=(value3)=>promise2(constant(Promise.resolve(value3)));var writeStandardError=(value3)=>{process.stderr.write(value3)};var openerCommand=(url)=>{if(process.platform==="darwin"){return["open",url]}if(process.platform==="win32"){return["rundll32","url.dll,FileProtocolHandler",url]}return["xdg-open",url]};var openWithOperatingSystem=(url)=>{const command=openerCommand(url);try{Bun.spawn(command,{stderr:"ignore",stdout:"ignore"})}catch{}};var readEnvFile=(filePath)=>existsSync10(filePath)?readFileSync8(filePath,"utf-8"):undefined;var writeEnvFile=(filePath,content)=>{const temporary=`${filePath}.${process.pid}.tmp`;writeFileSync6(temporary,content,{mode:384});if(existsSync10(filePath)){chmodSync2(temporary,statSync3(filePath).mode)}renameSync2(temporary,filePath)};var defaultCliAdapters={fetch:globalThis.fetch,writeDiagnostic:writeStandardError,writeOutput:(value3)=>{process.stdout.write(value3)}};var fileSystem=runSync2(provide3(FileSystem,exports_NodeFileSystem.layer));var nodePath4=runSync2(provide3(Path2,exports_NodePath.layer));var runNative=runPromiseWith2(empty());var runFileEffect=runNative;var encodeJson3=encodeSync(fromJsonString2(Unknown2));var packagePreflightErrorTag="PackagePreflightError";var packagePreflightDiagnostic=Struct({_tag:Literal2(packagePreflightErrorTag),diagnostic:Struct({message:String4})});var usage4=`Usage:
3196
+ `)}).pipe(mapError2((cause)=>new WhoamiCommandError({cause,message:cause.message})));import{fileURLToPath as fileURLToPath13}from"url";var{existsSync:existsSync9,watch:watch3}=await import("fs");var path13=runSync2(provide3(Path2,exports_NodePath.layer));var declarationPackageRoot=(declarationPath)=>{const declarationDirectory=path13.dirname(declarationPath);let candidate=declarationDirectory;while(true){if(existsSync9(path13.join(candidate,"package.json"))){return candidate}const parent=path13.dirname(candidate);if(parent===candidate){return declarationDirectory}candidate=parent}};var watchPackageDeclaration=(specifier,refresh,reportFailure)=>{if(!specifier.startsWith("file:")){return{close:flow(()=>promise2(constant(Promise.resolve())),runPromise2)}}let closed=false;let refreshGeneration=0;let refreshQueue=Promise.resolve();const scheduleRefresh=()=>{refreshGeneration+=1;const generation=refreshGeneration;runPromise2(sleep2("25 millis").pipe(flatMap3(()=>{if(closed||generation!==refreshGeneration){return void_3}const previousRefresh=refreshQueue;refreshQueue=runPromise2(gen2(function*refreshDeclaration(){yield*promise2(constant(previousRefresh));yield*tryPromise2(refresh).pipe(catch_2((error3)=>sync2(()=>{reportFailure(error3 instanceof Error?error3:new Error(String(error3)))})))}));return void_3})))};const watcher=watch3(declarationPackageRoot(fileURLToPath13(specifier)),{recursive:true},scheduleRefresh);watcher.on("error",(error3)=>{reportFailure(error3)});return{close:flow(()=>gen2(function*closeWatcher(){closed=true;refreshGeneration+=1;watcher.close();yield*promise2(constant(refreshQueue))}),runPromise2)}};var awaitValue8=(value3)=>promise2(constant(Promise.resolve(value3)));var writeStandardError=(value3)=>{process.stderr.write(value3)};var openerCommand=(url)=>{if(process.platform==="darwin"){return["open",url]}if(process.platform==="win32"){return["rundll32","url.dll,FileProtocolHandler",url]}return["xdg-open",url]};var openWithOperatingSystem=(url)=>{const command=openerCommand(url);try{Bun.spawn(command,{stderr:"ignore",stdout:"ignore"})}catch{}};var readEnvFile=(filePath)=>existsSync10(filePath)?readFileSync8(filePath,"utf-8"):undefined;var writeEnvFile=(filePath,content)=>{const temporary=`${filePath}.${process.pid}.tmp`;writeFileSync6(temporary,content,{mode:384});if(existsSync10(filePath)){chmodSync2(temporary,statSync3(filePath).mode)}renameSync2(temporary,filePath)};var defaultCliAdapters={fetch:globalThis.fetch,writeDiagnostic:writeStandardError,writeOutput:(value3)=>{process.stdout.write(value3)}};var fileSystem=runSync2(provide3(FileSystem,exports_NodeFileSystem.layer));var nodePath4=runSync2(provide3(Path2,exports_NodePath.layer));var runNative=runPromiseWith2(empty());var runFileEffect=runNative;var encodeJson4=encodeSync(fromJsonString2(Unknown2));var packagePreflightErrorTag="PackagePreflightError";var packagePreflightDiagnostic=Struct({_tag:Literal2(packagePreflightErrorTag),diagnostic:Struct({message:String4})});var usage5=`Usage:
3189
3197
  ci login <API URL> [--organization <organization-id>] [--no-browser] [--profile <name>]
3190
3198
  ci whoami
3191
3199
  ci logout
3192
3200
  ci orgs list
3193
3201
  ci orgs use <organization-id>
3194
- ci apps enroll --fqn <fqn> --redirect-uri <uri>... --scopes <scope...> [--name <name>] [--type public|confidential] [--audience <audience>] [--post-logout-redirect-uri <uri>]... [--enable] [--rotate-secret] [--env-file <path>] [--prefix <PREFIX_>] [--json]
3202
+ ci apps enroll --fqn <fqn> --redirect-uri <uri>... --scopes <scope...> [--primary-redirect-uri <uri>] [--allowed-origin <origin>]... [--name <name>] [--type public|confidential] [--audience <audience>] [--post-logout-redirect-uri <uri>]... [--enable] [--rotate-secret] [--env-file <path>] [--prefix <PREFIX_>] [--json]
3195
3203
  ci apps list
3196
3204
  ci apps get <application-id>
3197
3205
  ci apps rotate-secret <application-id>
3198
3206
  ci apps disable <application-id>
3207
+ ci apps redirect-uris list <application>
3208
+ ci apps redirect-uris add <application> <uri> [--primary] [--no-trust-origin]
3209
+ ci apps redirect-uris remove <application> <uri>
3210
+ ci apps redirect-uris set-primary <application> <uri>
3211
+ ci apps origins list <application>
3212
+ ci apps origins add <application> <origin>
3213
+ ci apps origins remove <application> <origin>
3214
+ (<application> is an Application Id or FQN)
3199
3215
  ci doctor [--fqn <fqn>] [--redirect-uri <uri>]...
3200
3216
  (whoami, logout, orgs, apps and doctor also accept [--backend-url <url>] [--organization <organization-id>] [--profile <name>])
3201
3217
  ci deploy --backend-url <url> --organization <organization-id> --declaration <module> [--gateway-url <GatewayFQN>=<HTTPS-origin>]... [--accept-breaking-changes] [--timeout-ms <milliseconds>] [--non-interactive] [--json]
@@ -3224,9 +3240,9 @@ Configuration (flag > environment > CLI Profile):
3224
3240
  `)}})}}).pipe(flatten3);class CliCommandError extends TaggedError3()("CliCommandError",{message:String4}){}var artifactCommandEffect=(command,options,adapters)=>tryPromise2({catch:(cause)=>new CliCommandError({message:cause instanceof Error?cause.message:`Could not ${command} package release`}),try:flow(()=>gen2(function*artifactCommand(){const output=command==="build"?yield*suspend2(()=>awaitValue8(runPackageBuildCommand(options,{makeDirectory:flow((directoryPath)=>suspend2(()=>awaitValue8(runFileEffect(fileSystem.makeDirectory(directoryPath,{recursive:true})))).pipe(asVoid2),runNative),resolveDeclarationSpecifier:resolvedDeclarationSpecifier,writeBytes:flow((filePath,bytes2)=>suspend2(()=>awaitValue8(runFileEffect(fileSystem.writeFile(filePath,bytes2)))).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}
3225
3241
  `)}),runNative)});var renderPackageOperationResult=(result3,adapters)=>{if(result3.kind==="operation_accepted"){adapters.writeOutput(`Operation ID: ${result3.operationId}
3226
3242
  `);return}adapters.writeOutput(`${JSON.stringify(result3.snapshot)}
3227
- `);const writeDiagnostic=adapters.writeDiagnostic??writeStandardError;writeDiagnostic(renderPackageOperationSummary(result3.snapshot))};var organizationScopedReleaseCommands=new Set(["install","rollback","sync","update"]);var managementInvocation=(options,environment,adapters,scope3)=>{const commandOptions=withoutOption(options,"profile");const organizationTarget=scope3==="organization"?resolveOrganizationTarget({args:options,environment}):undefined;const target=organizationTarget??resolveBackendManagementTarget({args:options,environment});return{client:makeBackendManagementClient({backendUrl:target.apiOrigin,fetch:adapters.fetch,token:target.token}),options:organizationTarget===undefined||optionValue4(commandOptions,"organization")!==undefined?commandOptions:[...commandOptions,"--organization",organizationTarget.organizationId]}};var accessDependencies=(environment,adapters)=>({environment,fetch:adapters.fetch,writeDiagnostic:adapters.writeDiagnostic??writeStandardError,writeOutput:adapters.writeOutput});var accessCommands=new Map([["apps",(args2,environment,adapters)=>args2[0]==="enroll"?appsEnrollCommandEffect(args2.slice(1),{...accessDependencies(environment,adapters),readEnvFile,writeEnvFile}):appsCommandEffect(args2,accessDependencies(environment,adapters))],["doctor",(args2,environment,adapters)=>doctorCommandEffect(args2,accessDependencies(environment,adapters))],["login",(args2,environment,adapters)=>loginCommandEffect(args2,{...accessDependencies(environment,adapters),delay:adapters.delay??Bun.sleep,deviceName:hostname(),openBrowser:adapters.openBrowser??openWithOperatingSystem})],["logout",(args2,environment,adapters)=>logoutCommandEffect(args2,accessDependencies(environment,adapters))],["orgs",(args2,environment,adapters)=>orgsCommandEffect(args2,accessDependencies(environment,adapters))],["whoami",(args2,environment,adapters)=>whoamiCommandEffect(args2,accessDependencies(environment,adapters))]]);var cliEffect=(args2,environment=Bun.env,adapters=defaultCliAdapters)=>{const[group,command,...options]=args2;const accessCommand=accessCommands.get(group??"");if(accessCommand!==undefined){return accessCommand(args2.slice(1),environment,adapters)}if(group==="deploy"){const deployArgs=args2.slice(1);return try_2({catch:(cause)=>is2(DeployCommandError)(cause)?cause:new DeployCommandError({cause,json:args2.includes("--json"),message:is2(BackendManagementConfigurationError)(cause)?cause.message:"Invalid deployment options"}),try:()=>{const parsed=parseDeployOptions(deployArgs);const target=resolveOrganizationTarget({args:deployArgs,environment});return{options:{...parsed,organizationId:target.organizationId},target}}}).pipe(flatMap3(({options:parsed,target})=>deploymentManagementClients({environment,fetch:adapters.fetch,target}).pipe(mapError2((cause)=>new DeployCommandError({cause,json:parsed.json,message:"ci deploy requires the CI_PUBLISHER_TOKEN credential"})),flatMap3((clients)=>deployCommandEffect(parsed,{...clients,resolveDeclarationSpecifier:resolvedDeclarationSpecifier,writeDiagnostic:adapters.writeDiagnostic??writeStandardError,writeOutput:adapters.writeOutput})))),asVoid2)}if(group!=="package"||command===undefined){return fail6(new CliCommandError({message:usage4}))}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}
3228
- `)}})}}).pipe(flatten3,tap2((result3)=>sync2(()=>{renderPackageOperationResult(result3,adapters)})),asVoid2)}if(command==="releases"){return try_2({catch:(cause)=>is2(PackageReleasesCommandError)(cause)?cause:new PackageReleasesCommandError({cause,message:is2(BackendManagementConfigurationError)(cause)?cause.message:"Could not configure package releases command"}),try:()=>{const invocation=managementInvocation(options,environment,adapters,"organization");return packageReleasesCommandEffect(invocation.options,{client:invocation.client})}}).pipe(flatten3,tap2((releases)=>sync2(()=>{adapters.writeOutput(`${encodeJson3(releases)}
3229
- `)})),asVoid2)}if(command==="diagnostics"){return try_2({catch:(cause)=>is2(PackageDiagnosticsCommandError)(cause)?cause:new PackageDiagnosticsCommandError({cause,message:is2(BackendManagementConfigurationError)(cause)?cause.message:"Could not configure package diagnostics command"}),try:()=>{const invocation=managementInvocation(options,environment,adapters,"organization");return packageDiagnosticsCommandEffect(invocation.options,{client:invocation.client})}}).pipe(flatten3,tap2((diagnostic)=>sync2(()=>{adapters.writeOutput(`${encodeJson3(diagnostic)}
3243
+ `);const writeDiagnostic=adapters.writeDiagnostic??writeStandardError;writeDiagnostic(renderPackageOperationSummary(result3.snapshot))};var organizationScopedReleaseCommands=new Set(["install","rollback","sync","update"]);var managementInvocation=(options,environment,adapters,scope3)=>{const commandOptions=withoutOption(options,"profile");const organizationTarget=scope3==="organization"?resolveOrganizationTarget({args:options,environment}):undefined;const target=organizationTarget??resolveBackendManagementTarget({args:options,environment});return{client:makeBackendManagementClient({backendUrl:target.apiOrigin,fetch:adapters.fetch,token:target.token}),options:organizationTarget===undefined||optionValue4(commandOptions,"organization")!==undefined?commandOptions:[...commandOptions,"--organization",organizationTarget.organizationId]}};var accessDependencies=(environment,adapters)=>({environment,fetch:adapters.fetch,writeDiagnostic:adapters.writeDiagnostic??writeStandardError,writeOutput:adapters.writeOutput});var accessCommands=new Map([["apps",(args2,environment,adapters)=>{const dependencies=accessDependencies(environment,adapters);if(args2[0]==="enroll"){return appsEnrollCommandEffect(args2.slice(1),{...dependencies,readEnvFile,writeEnvFile})}return args2[0]==="redirect-uris"||args2[0]==="origins"?appsUrlsCommandEffect(args2,dependencies):appsCommandEffect(args2,dependencies)}],["doctor",(args2,environment,adapters)=>doctorCommandEffect(args2,accessDependencies(environment,adapters))],["login",(args2,environment,adapters)=>loginCommandEffect(args2,{...accessDependencies(environment,adapters),delay:adapters.delay??Bun.sleep,deviceName:hostname(),openBrowser:adapters.openBrowser??openWithOperatingSystem})],["logout",(args2,environment,adapters)=>logoutCommandEffect(args2,accessDependencies(environment,adapters))],["orgs",(args2,environment,adapters)=>orgsCommandEffect(args2,accessDependencies(environment,adapters))],["whoami",(args2,environment,adapters)=>whoamiCommandEffect(args2,accessDependencies(environment,adapters))]]);var cliEffect=(args2,environment=Bun.env,adapters=defaultCliAdapters)=>{const[group,command,...options]=args2;const accessCommand=accessCommands.get(group??"");if(accessCommand!==undefined){return accessCommand(args2.slice(1),environment,adapters)}if(group==="deploy"){const deployArgs=args2.slice(1);return try_2({catch:(cause)=>is2(DeployCommandError)(cause)?cause:new DeployCommandError({cause,json:args2.includes("--json"),message:is2(BackendManagementConfigurationError)(cause)?cause.message:"Invalid deployment options"}),try:()=>{const parsed=parseDeployOptions(deployArgs);const target=resolveOrganizationTarget({args:deployArgs,environment});return{options:{...parsed,organizationId:target.organizationId},target}}}).pipe(flatMap3(({options:parsed,target})=>deploymentManagementClients({environment,fetch:adapters.fetch,target}).pipe(mapError2((cause)=>new DeployCommandError({cause,json:parsed.json,message:"ci deploy requires the CI_PUBLISHER_TOKEN credential"})),flatMap3((clients)=>deployCommandEffect(parsed,{...clients,resolveDeclarationSpecifier:resolvedDeclarationSpecifier,writeDiagnostic:adapters.writeDiagnostic??writeStandardError,writeOutput:adapters.writeOutput})))),asVoid2)}if(group!=="package"||command===undefined){return fail6(new CliCommandError({message:usage5}))}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}
3244
+ `)}})}}).pipe(flatten3,tap2((result3)=>sync2(()=>{renderPackageOperationResult(result3,adapters)})),asVoid2)}if(command==="releases"){return try_2({catch:(cause)=>is2(PackageReleasesCommandError)(cause)?cause:new PackageReleasesCommandError({cause,message:is2(BackendManagementConfigurationError)(cause)?cause.message:"Could not configure package releases command"}),try:()=>{const invocation=managementInvocation(options,environment,adapters,"organization");return packageReleasesCommandEffect(invocation.options,{client:invocation.client})}}).pipe(flatten3,tap2((releases)=>sync2(()=>{adapters.writeOutput(`${encodeJson4(releases)}
3245
+ `)})),asVoid2)}if(command==="diagnostics"){return try_2({catch:(cause)=>is2(PackageDiagnosticsCommandError)(cause)?cause:new PackageDiagnosticsCommandError({cause,message:is2(BackendManagementConfigurationError)(cause)?cause.message:"Could not configure package diagnostics command"}),try:()=>{const invocation=managementInvocation(options,environment,adapters,"organization");return packageDiagnosticsCommandEffect(invocation.options,{client:invocation.client})}}).pipe(flatten3,tap2((diagnostic)=>sync2(()=>{adapters.writeOutput(`${encodeJson4(diagnostic)}
3230
3246
  `)})),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())),(bytes2)=>new Uint8Array(bytes2)),runNative)})}}).pipe(flatten3,tap2((operationId)=>sync2(()=>{adapters.writeOutput(`Operation ID: ${operationId}
3231
3247
  `)})),asVoid2)};var renderCliCommandError=(error3)=>{if((is2(PackageReleaseCommandError)(error3)||is2(DeployCommandError)(error3))&&is2(packagePreflightDiagnostic)(error3.cause)){return`${error3.message}: ${error3.cause.diagnostic.message}`}return error3.message};if(import.meta.main){const run2=cliEffect(Bun.argv.slice(2)).pipe(catch_2((error3)=>sync2(()=>{if(is2(DeployCommandError)(error3)&&error3.json){const record3={kind:"error",lastEventId:error3.lastEventId,message:renderCliCommandError(error3),nextAction:error3.nextAction,operationId:error3.operationId,status:error3.status??"failed"};process.stdout.write(`${JSON.stringify(record3)}
3232
3248
  `)}else{process.stderr.write(`${renderCliCommandError(error3)}