fimo 0.9.0 → 0.10.0-staging.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/content-templates/types-template.eta +30 -3
- package/assets/skills/fimo-cli/references/content.md +76 -4
- package/assets/skills/fimo-cli/references/locales.md +2 -0
- package/assets/skills/fimo-cli/references/webhooks.md +4 -0
- package/assets/skills/fimo-code/references/content.md +62 -4
- package/assets/skills/fimo-studio/references/cms.md +13 -0
- package/assets/skills/fimo-studio/references/webhooks.md +1 -1
- package/dist/cli/bundle.json +1 -1
- package/dist/cli/index.js +14 -14
- package/dist/runtime/primitives/components/RichText.d.ts +2 -2
- package/dist/runtime/primitives/components/RichText.js +5 -3
- package/dist/runtime/primitives/lib/query.d.ts +1 -1
- package/dist/scripts/validate-schemas.js +32 -4
- package/package.json +1 -1
- package/release.json +2 -2
- package/templates/react-router/package.json +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -39,7 +39,7 @@ Expecting one of '${allowedValues.join("', '")}'`);return this._lifeCycleHooks[e
|
|
|
39
39
|
`),this.outputHelp({error:!0}));let config=errorOptions||{},exitCode=config.exitCode||1,code2=config.code||"commander.error";this._exit(exitCode,code2,message)}_parseOptionsEnv(){this.options.forEach(option=>{if(option.envVar&&option.envVar in process8.env){let optionKey=option.attributeName();(this.getOptionValue(optionKey)===void 0||["default","config","env"].includes(this.getOptionValueSource(optionKey)))&&(option.required||option.optional?this.emit(`optionEnv:${option.name()}`,process8.env[option.envVar]):this.emit(`optionEnv:${option.name()}`))}})}_parseOptionsImplied(){let dualHelper=new DualOptions(this.options),hasCustomOptionValue=__name(optionKey=>this.getOptionValue(optionKey)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(optionKey)),"hasCustomOptionValue");this.options.filter(option=>option.implied!==void 0&&hasCustomOptionValue(option.attributeName())&&dualHelper.valueFromOption(this.getOptionValue(option.attributeName()),option)).forEach(option=>{Object.keys(option.implied).filter(impliedKey=>!hasCustomOptionValue(impliedKey)).forEach(impliedKey=>{this.setOptionValueWithSource(impliedKey,option.implied[impliedKey],"implied")})})}missingArgument(name){let message=`error: missing required argument '${name}'`;this.error(message,{code:"commander.missingArgument"})}optionMissingArgument(option){let message=`error: option '${option.flags}' argument missing`;this.error(message,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(option){let message=`error: required option '${option.flags}' not specified`;this.error(message,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(option,conflictingOption){let findBestOptionFromValue=__name(option2=>{let optionKey=option2.attributeName(),optionValue=this.getOptionValue(optionKey),negativeOption=this.options.find(target=>target.negate&&optionKey===target.attributeName()),positiveOption=this.options.find(target=>!target.negate&&optionKey===target.attributeName());return negativeOption&&(negativeOption.presetArg===void 0&&optionValue===!1||negativeOption.presetArg!==void 0&&optionValue===negativeOption.presetArg)?negativeOption:positiveOption||option2},"findBestOptionFromValue"),getErrorMessage=__name(option2=>{let bestOption=findBestOptionFromValue(option2),optionKey=bestOption.attributeName();return this.getOptionValueSource(optionKey)==="env"?`environment variable '${bestOption.envVar}'`:`option '${bestOption.flags}'`},"getErrorMessage"),message=`error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;this.error(message,{code:"commander.conflictingOption"})}unknownOption(flag2){if(this._allowUnknownOption)return;let suggestion="";if(flag2.startsWith("--")&&this._showSuggestionAfterError){let candidateFlags=[],command=this;do{let moreFlags=command.createHelp().visibleOptions(command).filter(option=>option.long).map(option=>option.long);candidateFlags=candidateFlags.concat(moreFlags),command=command.parent}while(command&&!command._enablePositionalOptions);suggestion=suggestSimilar(flag2,candidateFlags)}let message=`error: unknown option '${flag2}'${suggestion}`;this.error(message,{code:"commander.unknownOption"})}_excessArguments(receivedArgs){if(this._allowExcessArguments)return;let expected=this.registeredArguments.length,s=expected===1?"":"s",message=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;this.error(message,{code:"commander.excessArguments"})}unknownCommand(){let unknownName=this.args[0],suggestion="";if(this._showSuggestionAfterError){let candidateNames=[];this.createHelp().visibleCommands(this).forEach(command=>{candidateNames.push(command.name()),command.alias()&&candidateNames.push(command.alias())}),suggestion=suggestSimilar(unknownName,candidateNames)}let message=`error: unknown command '${unknownName}'${suggestion}`;this.error(message,{code:"commander.unknownCommand"})}version(str,flags,description){if(str===void 0)return this._version;this._version=str,flags=flags||"-V, --version",description=description||"output the version number";let versionOption=this.createOption(flags,description);return this._versionOptionName=versionOption.attributeName(),this._registerOption(versionOption),this.on("option:"+versionOption.name(),()=>{this._outputConfiguration.writeOut(`${str}
|
|
40
40
|
`),this._exit(0,"commander.version",str)}),this}description(str,argsDescription){return str===void 0&&argsDescription===void 0?this._description:(this._description=str,argsDescription&&(this._argsDescription=argsDescription),this)}summary(str){return str===void 0?this._summary:(this._summary=str,this)}alias(alias){if(alias===void 0)return this._aliases[0];let command=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(command=this.commands[this.commands.length-1]),alias===command._name)throw new Error("Command alias can't be the same as its name");let matchingCommand=this.parent?._findCommand(alias);if(matchingCommand){let existingCmd=[matchingCommand.name()].concat(matchingCommand.aliases()).join("|");throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`)}return command._aliases.push(alias),this}aliases(aliases2){return aliases2===void 0?this._aliases:(aliases2.forEach(alias=>this.alias(alias)),this)}usage(str){if(str===void 0){if(this._usage)return this._usage;let args=this.registeredArguments.map(arg=>humanReadableArgName(arg));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?args:[]).join(" ")}return this._usage=str,this}name(str){return str===void 0?this._name:(this._name=str,this)}nameFromFilename(filename){return this._name=path47.basename(filename,path47.extname(filename)),this}executableDir(path48){return path48===void 0?this._executableDir:(this._executableDir=path48,this)}helpInformation(contextOptions){let helper=this.createHelp(),context=this._getOutputContext(contextOptions);helper.prepareContext({error:context.error,helpWidth:context.helpWidth,outputHasColors:context.hasColors});let text3=helper.formatHelp(this,helper);return context.hasColors?text3:this._outputConfiguration.stripColor(text3)}_getOutputContext(contextOptions){contextOptions=contextOptions||{};let error=!!contextOptions.error,baseWrite,hasColors,helpWidth;return error?(baseWrite=__name(str=>this._outputConfiguration.writeErr(str),"baseWrite"),hasColors=this._outputConfiguration.getErrHasColors(),helpWidth=this._outputConfiguration.getErrHelpWidth()):(baseWrite=__name(str=>this._outputConfiguration.writeOut(str),"baseWrite"),hasColors=this._outputConfiguration.getOutHasColors(),helpWidth=this._outputConfiguration.getOutHelpWidth()),{error,write:__name(str=>(hasColors||(str=this._outputConfiguration.stripColor(str)),baseWrite(str)),"write"),hasColors,helpWidth}}outputHelp(contextOptions){let deprecatedCallback;typeof contextOptions=="function"&&(deprecatedCallback=contextOptions,contextOptions=void 0);let outputContext=this._getOutputContext(contextOptions),eventContext={error:outputContext.error,write:outputContext.write,command:this};this._getCommandAndAncestors().reverse().forEach(command=>command.emit("beforeAllHelp",eventContext)),this.emit("beforeHelp",eventContext);let helpInformation=this.helpInformation({error:outputContext.error});if(deprecatedCallback&&(helpInformation=deprecatedCallback(helpInformation),typeof helpInformation!="string"&&!Buffer.isBuffer(helpInformation)))throw new Error("outputHelp callback must return a string or a Buffer");outputContext.write(helpInformation),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",eventContext),this._getCommandAndAncestors().forEach(command=>command.emit("afterAllHelp",eventContext))}helpOption(flags,description){return typeof flags=="boolean"?(flags?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(flags=flags??"-h, --help",description=description??"display help for command",this._helpOption=this.createOption(flags,description),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(option){return this._helpOption=option,this}help(contextOptions){this.outputHelp(contextOptions);let exitCode=Number(process8.exitCode??0);exitCode===0&&contextOptions&&typeof contextOptions!="function"&&contextOptions.error&&(exitCode=1),this._exit(exitCode,"commander.help","(outputHelp)")}addHelpText(position,text3){let allowedValues=["beforeAll","before","after","afterAll"];if(!allowedValues.includes(position))throw new Error(`Unexpected value for position to addHelpText.
|
|
41
41
|
Expecting one of '${allowedValues.join("', '")}'`);let helpEvent=`${position}Help`;return this.on(helpEvent,context=>{let helpStr;typeof text3=="function"?helpStr=text3({error:context.error,command:context.command}):helpStr=text3,helpStr&&context.write(`${helpStr}
|
|
42
|
-
`)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();helpOption&&args.find(arg=>helpOption.is(arg))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;return(match=arg.match(/^(--inspect(-brk)?)$/))!==null?debugOption=match[1]:(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(debugOption=match[1],/^\d+$/.test(match[3])?debugPort=match[3]:debugHost=match[3]):(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match[1],debugHost=match[3],debugPort=match[4]),debugOption&&debugPort!=="0"?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}__name(incrementNodeInspectorPort,"incrementNodeInspectorPort");function useColor(){if(process8.env.NO_COLOR||process8.env.FORCE_COLOR==="0"||process8.env.FORCE_COLOR==="false")return!1;if(process8.env.FORCE_COLOR||process8.env.CLICOLOR_FORCE!==void 0)return!0}__name(useColor,"useColor");exports2.Command=Command2;exports2.useColor=useColor}});var require_commander=__commonJS({"../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js"(exports2){var{Argument:Argument2}=require_argument(),{Command:Command2}=require_command(),{CommanderError:CommanderError2,InvalidArgumentError:InvalidArgumentError2}=require_error(),{Help:Help2}=require_help(),{Option:Option2}=require_option();exports2.program=new Command2;exports2.createCommand=name=>new Command2(name);exports2.createOption=(flags,description)=>new Option2(flags,description);exports2.createArgument=(name,description)=>new Argument2(name,description);exports2.Command=Command2;exports2.Option=Option2;exports2.Argument=Argument2;exports2.Help=Help2;exports2.CommanderError=CommanderError2;exports2.InvalidArgumentError=InvalidArgumentError2;exports2.InvalidOptionArgumentError=InvalidArgumentError2}});import{createHash}from"node:crypto";function normalizeApiUrl(input){let trimmed=input.trim();try{let url=new URL(trimmed),pathname=url.pathname.replace(/\/+$/,"");return`${url.protocol}//${url.host}${pathname}`}catch{return trimmed.replace(/\/+$/,"")}}function hashApiUrl(input){return createHash("sha256").update(normalizeApiUrl(input)).digest("hex").slice(0,6)}function safeHostLabel(host){return host.replace(/:/g,"-").replace(/[^a-zA-Z0-9.-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").toLowerCase()}function credentialsFilename(apiUrl){let normalized=normalizeApiUrl(apiUrl),hostLabel="unknown";try{hostLabel=safeHostLabel(new URL(normalized).host)}catch{}return hostLabel.length===0&&(hostLabel="unknown"),`${hostLabel}-${hashApiUrl(apiUrl)}.json`}var init_credentials_path=__esm({"src/cli/utils/credentials-path.ts"(){__name(normalizeApiUrl,"normalizeApiUrl");__name(hashApiUrl,"hashApiUrl");__name(safeHostLabel,"safeHostLabel");__name(credentialsFilename,"credentialsFilename")}});import fs from"node:fs";import{homedir}from"node:os";import path,{join}from"node:path";import{fileURLToPath}from"node:url";function readReleaseManifest(){try{let raw=fs.readFileSync(RELEASE_FILE,"utf8"),parsed=JSON.parse(raw),manifest={};return typeof parsed.apiUrl=="string"&&parsed.apiUrl.length>0&&(manifest.apiUrl=parsed.apiUrl),typeof parsed.webUrl=="string"&&parsed.webUrl.length>0&&(manifest.webUrl=parsed.webUrl),manifest}catch{return{}}}function loadConfig(){let baked=readReleaseManifest(),apiUrl=process.env.FIMO_API_URL?.trim()||baked.apiUrl||DEFAULT_API_URL,webUrl=process.env.FIMO_WEB_URL?.trim()||baked.webUrl||DEFAULT_WEB_URL,configDir=join(process.env.XDG_CONFIG_HOME||join(homedir(),".config"),"fimo"),credentialsDir=join(configDir,"credentials");return{apiUrl,webUrl,configDir,credentialsDir,credentialsFile:join(credentialsDir,credentialsFilename(apiUrl))}}var DEFAULT_API_URL,DEFAULT_WEB_URL,THIS_FILE,CLI_ROOT,RELEASE_FILE,init_config=__esm({"src/cli/config.ts"(){init_credentials_path();DEFAULT_API_URL="http://localhost:3000",DEFAULT_WEB_URL="http://localhost:5173",THIS_FILE=fileURLToPath(import.meta.url),CLI_ROOT=path.resolve(path.dirname(THIS_FILE),"..",".."),RELEASE_FILE=path.resolve(CLI_ROOT,"release.json");__name(readReleaseManifest,"readReleaseManifest");__name(loadConfig,"loadConfig")}});import fs2 from"node:fs";function ensureCredentialsDir(cfg){fs2.existsSync(cfg.credentialsDir)||fs2.mkdirSync(cfg.credentialsDir,{recursive:!0})}function readCredentials(cfg=loadConfig()){if(!fs2.existsSync(cfg.credentialsFile))return null;let raw=fs2.readFileSync(cfg.credentialsFile,"utf-8");return JSON.parse(raw)}function writeCredentials(credentials,cfg=loadConfig()){ensureCredentialsDir(cfg);let tmpFile=`${cfg.credentialsFile}.tmp-${process.pid}`;fs2.writeFileSync(tmpFile,JSON.stringify(credentials,null,2)),fs2.renameSync(tmpFile,cfg.credentialsFile)}function clearCredentials(cfg=loadConfig()){fs2.existsSync(cfg.credentialsFile)&&fs2.unlinkSync(cfg.credentialsFile)}function setActiveOrganization(organization,cfg=loadConfig()){let creds=requireCredentials(cfg);writeCredentials({...creds,activeOrganization:organization},cfg)}function recordAuthFailure(cfg=loadConfig()){let creds=readCredentials(cfg);creds&&writeCredentials({...creds,lastFailedAuthAt:new Date().toISOString()},cfg)}function requireToken(cfg=loadConfig()){return requireCredentials(cfg).access_token}function requireCredentials(cfg=loadConfig()){let creds=readCredentials(cfg);if(!creds?.access_token)throw new NotAuthenticatedError(cfg.apiUrl);return creds}var NotAuthenticatedError,init_auth=__esm({"src/cli/auth.ts"(){init_config();NotAuthenticatedError=class extends Error{static{__name(this,"NotAuthenticatedError")}apiUrl;constructor(apiUrl,message="You are not signed in to Fimo."){super(message),this.name="NotAuthenticatedError",this.apiUrl=apiUrl}};__name(ensureCredentialsDir,"ensureCredentialsDir");__name(readCredentials,"readCredentials");__name(writeCredentials,"writeCredentials");__name(clearCredentials,"clearCredentials");__name(setActiveOrganization,"setActiveOrganization");__name(recordAuthFailure,"recordAuthFailure");__name(requireToken,"requireToken");__name(requireCredentials,"requireCredentials")}});import{spawnSync}from"node:child_process";import fs3 from"node:fs";import path2 from"node:path";import{setTimeout as sleep}from"node:timers/promises";function isPublishedInstall(cliRoot=CLI_ROOT){return fs3.existsSync(path2.join(cliRoot,"release.json"))}function resolveGlobalFimoRoot(){let result=spawnSync("npm",["root","-g"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:GLOBAL_ROOT_TIMEOUT_MS});return result.error||result.status!==0||typeof result.stdout!="string"||result.stdout.trim().length===0?null:path2.resolve(result.stdout.trim(),"fimo")}function normalizedPath(input){try{return fs3.realpathSync(input)}catch{return path2.resolve(input)}}function autoUpgradeEnabled(options={}){let usesDefaults=Object.keys(options).length===0;if(usesDefaults&&defaultEligibility!==void 0)return defaultEligibility;let env=options.env??process.env,cliRoot=options.cliRoot??CLI_ROOT,published=options.published??isPublishedInstall(cliRoot);if(env.FIMO_AUTO_UPGRADE!=="1"||!published)return usesDefaults&&(defaultEligibility=!1),!1;let globalFimoRoot=options.globalFimoRoot===void 0?resolveGlobalFimoRoot():options.globalFimoRoot;if(!globalFimoRoot)return usesDefaults&&(defaultEligibility=!1),!1;let eligible=normalizedPath(cliRoot)===normalizedPath(globalFimoRoot);return usesDefaults&&(defaultEligibility=eligible),eligible}async function acquireLock(lockDir){let deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{fs3.mkdirSync(lockDir);return}catch(error){if(error.code!=="EEXIST")throw error}let stale=!1;try{stale=Date.now()-fs3.statSync(lockDir).mtimeMs>LOCK_STALE_MS}catch{continue}if(stale){try{fs3.rmdirSync(lockDir)}catch{}continue}if(Date.now()>=deadline)throw new Error("auto-upgrade lock timeout");await sleep(LOCK_POLL_MS)}}function readGlobalFimoVersion(){let root2=resolveGlobalFimoRoot();if(!root2)return null;try{let pkg=JSON.parse(fs3.readFileSync(path2.join(root2,"package.json"),"utf8"));return typeof pkg.version=="string"?pkg.version:null}catch{return null}}async function autoUpgradeGlobal(latest){if(!VERSION_PATTERN.test(latest))return!1;let lockDir=path2.join(loadConfig().configDir,"auto-upgrade.lock");try{fs3.mkdirSync(path2.dirname(lockDir),{recursive:!0}),await acquireLock(lockDir)}catch{return!1}try{if(readGlobalFimoVersion()===latest)return!0;let install=spawnSync("npm",["install","-g",`fimo@${latest}`],{stdio:["ignore","ignore","inherit"],timeout:INSTALL_TIMEOUT_MS});return install.error||install.status!==0?!1:readGlobalFimoVersion()===latest}finally{try{fs3.rmdirSync(lockDir)}catch{}}}var INSTALL_TIMEOUT_MS,GLOBAL_ROOT_TIMEOUT_MS,LOCK_WAIT_MS,LOCK_STALE_MS,LOCK_POLL_MS,VERSION_PATTERN,defaultEligibility,init_auto_upgrade=__esm({"src/cli/auto-upgrade.ts"(){init_config();INSTALL_TIMEOUT_MS=12e4,GLOBAL_ROOT_TIMEOUT_MS=5e3,LOCK_WAIT_MS=18e4,LOCK_STALE_MS=3e5,LOCK_POLL_MS=500,VERSION_PATTERN=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;__name(isPublishedInstall,"isPublishedInstall");__name(resolveGlobalFimoRoot,"resolveGlobalFimoRoot");__name(normalizedPath,"normalizedPath");__name(autoUpgradeEnabled,"autoUpgradeEnabled");__name(acquireLock,"acquireLock");__name(readGlobalFimoVersion,"readGlobalFimoVersion");__name(autoUpgradeGlobal,"autoUpgradeGlobal")}});import fs4 from"node:fs";import path3 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";function getCliVersion(){try{let raw=fs4.readFileSync(PACKAGE_JSON_PATH,"utf8");return JSON.parse(raw).version??"0.0.0"}catch{return"0.0.0"}}var THIS_FILE2,CLI_ROOT2,PACKAGE_JSON_PATH,init_version=__esm({"src/cli/version.ts"(){THIS_FILE2=fileURLToPath2(import.meta.url),CLI_ROOT2=path3.resolve(path3.dirname(THIS_FILE2),"..",".."),PACKAGE_JSON_PATH=path3.join(CLI_ROOT2,"package.json");__name(getCliVersion,"getCliVersion")}});function lazyFetchQs(against,extras={}){let params=new URLSearchParams;against&¶ms.set("against",against);for(let[k,v]of Object.entries(extras))params.set(k,v);return params.toString()}function throwUnauthorized(cfg,status){try{recordAuthFailure(cfg)}catch{}throw new UnauthorizedError(cfg.apiUrl,status)}async function throwPermissionDenied(cfg,response){let required=[];try{let body=await response.json();required=Array.isArray(body.required)?body.required:body.required?[body.required]:[]}catch{}throw new PermissionDeniedError(cfg.apiUrl,required)}async function fimoFetch(url,init){let headers=new Headers(init.headers);headers.delete(CLI_VERSION_HEADER),headers.delete(CLI_AUTO_UPGRADE_HEADER);let canAutoUpgrade=process.argv[2]!=="git-credential"&&autoUpgradeEnabled();canAutoUpgrade&&(headers.set(CLI_VERSION_HEADER,getCliVersion()),headers.set(CLI_AUTO_UPGRADE_HEADER,"1"));let response=await fetch(url,{...init,headers});if(canAutoUpgrade&&response.status===426){let latest=response.headers.get(CLI_LATEST_HEADER);if(latest){await autoUpgradeGlobal(latest)||ui.warn({command:process.argv[2]??"fimo",message:`Could not upgrade to ${latest}; continuing with the current command.`});let retryHeaders=new Headers(init.headers);return retryHeaders.delete(CLI_VERSION_HEADER),retryHeaders.delete(CLI_AUTO_UPGRADE_HEADER),fetch(url,{...init,headers:retryHeaders})}}return response}function formatZodIssues(parsed){if(!parsed||typeof parsed!="object")return null;let error=parsed.error,issues=error&&typeof error=="object"&&"issues"in error?error.issues:void 0;return!Array.isArray(issues)||issues.length===0?null:issues.map(issue=>{let{path:path47,message}=issue;return`${Array.isArray(path47)&&path47.length>0?`${path47.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}var ApiRequestError,UnauthorizedError,PermissionDeniedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_ENV_HEADER,FimoApiClient,init_api=__esm({"src/cli/api.ts"(){init_dist();init_auth();init_auto_upgrade();init_config();init_version();__name(lazyFetchQs,"lazyFetchQs");ApiRequestError=class extends Error{static{__name(this,"ApiRequestError")}status;method;path;detail;constructor(method,path47,status,detail){super(`API ${method} ${path47} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path47,this.status=status,this.detail=detail}},UnauthorizedError=class extends Error{static{__name(this,"UnauthorizedError")}apiUrl;status;constructor(apiUrl,status,message){super(message??`Session for ${apiUrl} expired or invalid (HTTP ${status}).`),this.name="UnauthorizedError",this.apiUrl=apiUrl,this.status=status}},PermissionDeniedError=class extends Error{static{__name(this,"PermissionDeniedError")}apiUrl;required;constructor(apiUrl,required=[],message){let detail=required.length?` Missing permission: ${required.join(", ")}.`:"";super(message??`You don't have permission to do this on ${apiUrl}.${detail}`),this.name="PermissionDeniedError",this.apiUrl=apiUrl,this.required=required}};__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");CLI_VERSION_HEADER="X-Fimo-CLI-Version",CLI_LATEST_HEADER="X-Fimo-CLI-Latest",CLI_AUTO_UPGRADE_HEADER="X-Fimo-CLI-Auto-Upgrade",FIMO_ENV_HEADER="X-Fimo-Env";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");FimoApiClient=class _FimoApiClient{constructor(cfg=loadConfig()){this.cfg=cfg}static{__name(this,"FimoApiClient")}env;withEnv(env){let next2=new _FimoApiClient(this.cfg);return next2.env=env,next2}async formatError(response){let text3=await response.text();if(!text3)return String(response.status);try{let parsed=JSON.parse(text3);if(typeof parsed.message=="string"&&parsed.message.length>0){let partial=formatPartialResult(parsed);return partial?`${parsed.message} ${partial}`:parsed.message}if(typeof parsed.error=="string"&&parsed.error.length>0)return parsed.error;if(parsed.error&&typeof parsed.error=="object"&&"message"in parsed.error&&typeof parsed.error.message=="string")return parsed.error.message;let zodIssues=formatZodIssues(parsed);if(zodIssues)return zodIssues}catch{}return text3}resolveAuthToken(){return process.env.FIMO_API_TOKEN?.trim()||requireToken(this.cfg)}async request(path47,init={},opts={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path47}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&!opts.allow403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.formatError(response);throw new ApiRequestError(init.method??"GET",path47,response.status,error)}if(response.status!==204)return await response.json()}async rawRequest(path47,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path47}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.formatError(response);throw new Error(`API ${init.method??"GET"} ${path47} failed: ${response.status} ${error}`)}return response}tenantPath(projectId,route){if(!this.env)throw new Error("FimoApiClient: tenant-scoped call requires an env. Use `client.withEnv(env)` before calling tenant CRUD methods.");return`/api/tenant/${projectId}/envs/${encodeURIComponent(this.env)}${route}`}projectEnvManagementPath(projectId,route){if(!this.env)throw new Error("FimoApiClient: env-scoped management call requires an env. Use `client.withEnv(env)` before calling env CRUD methods.");return`/api/management/projects/${projectId}/envs/${encodeURIComponent(this.env)}${route}`}async listModels(projectId,query={}){let params=new URLSearchParams;query.modality&¶ms.set("modality",query.modality);for(let t2 of query.tag??[])params.append("tag",t2);query.q&¶ms.set("q",query.q),query.category&¶ms.set("category",query.category);let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models${qs?`?${qs}`:""}`)).data}async getModel(projectId,key){try{return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/${key}`)).data}catch(err){if(err instanceof ApiRequestError&&err.status===404)return null;throw err}}async estimateModel(projectId,key,options){return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/estimate`,{method:"POST",body:JSON.stringify({model:key,options})})).data}async estimateGenerationTask(projectId,key,options){return(await this.request(this.tenantPath(projectId,"/assets/generate/estimate"),{method:"POST",body:JSON.stringify({task:key,options})})).data}async listOrganizations(){return(await this.request("/api/management/organizations")).data}async listOrganizationMembers(organizationId){return(await this.request(`/api/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`))?.members??[]}async inviteOrganizationMember(input){return this.request("/api/auth/organization/invite-member",{method:"POST",body:JSON.stringify(input)})}async getCurrentSession(){return this.request("/api/auth/get-session")}async submitSupportIssue(input){return(await this.request("/api/support/issues",{method:"POST",body:JSON.stringify(input)})).data}async getReferralSummary(userId){return(await this.request(`/api/users/${encodeURIComponent(userId)}/referrals/summary`)).data}async listProjects(organizationId){return(await this.request(`/api/management/organizations/${encodeURIComponent(organizationId)}/projects`)).data}async publishProject(projectId){await this.request(`/api/management/projects/${projectId}/publish`,{method:"POST"})}async unpublishProject(projectId){await this.request(`/api/management/projects/${projectId}/unpublish`,{method:"POST"})}async createProject(input){return(await this.request("/api/management/projects",{method:"POST",body:JSON.stringify({...input,source:"cli"})})).data}async getProject(projectId){return(await this.request(`/api/management/projects/${projectId}`)).data}async getProjectCredits(projectId){return(await this.request(`/api/management/projects/${projectId}/billing/credits`)).data}async listProjectSecretEntries(projectId,opts={}){let qs=opts.kind?`?kind=${encodeURIComponent(opts.kind)}`:"";return(await this.request(`/api/management/projects/${projectId}/secrets${qs}`)).data}async createProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets`,{method:"POST",body:JSON.stringify({key:input.key,kind:input.kind,value:input.value})})).data}async updateProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets/${encodeURIComponent(input.key)}`,{method:"PATCH",body:JSON.stringify({kind:input.kind,value:input.value})})).data}async deleteProjectSecretEntry(projectId,key,kind){let qs=`?kind=${encodeURIComponent(kind)}`;await this.request(`/api/management/projects/${projectId}/secrets/${encodeURIComponent(key)}${qs}`,{method:"DELETE"})}async listProjectIntegrations(projectId){return(await this.request(`/api/management/projects/${projectId}/integrations`)).data}async getProjectIntegrationInfo(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/info`)).data}async getProjectIntegrationStatus(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/status`)).data}async enableProjectIntegration(input){let payload={...input.authMode?{authMode:input.authMode}:{},...input.connectionAlias?{connectionAlias:input.connectionAlias}:{}};return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}`,{method:"PUT",body:JSON.stringify(payload)})).data}async connectOrganizationIntegrationWithToken(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({...input.alias?{alias:input.alias}:{},token:input.token})})).data}async startOrganizationIntegrationConnect(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({})})).data}async switchProjectIntegrationAuth(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/auth`,{method:"PATCH",body:JSON.stringify({authMode:input.authMode})})).data}async disableProjectIntegration(projectId,integrationKey){await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}`,{method:"DELETE"})}async setProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"PUT",body:JSON.stringify({value:input.value})})).data}async clearProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"DELETE"})).data}async runProjectIntegrationTool(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/run`,{method:"POST",body:JSON.stringify(input.request)})).data}async startProjectIntegrationConnect(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST"})).data}async bindProjectChannel(projectId,request){return(await this.request(`/api/management/projects/${projectId}/channels/bind`,{method:"POST",body:JSON.stringify(request)})).data}async createSchedule(projectId,request){return(await this.request(`/api/management/projects/${projectId}/schedules`,{method:"POST",body:JSON.stringify(request)})).data}async listSchedules(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules`)).data}async runSchedule(projectId,name){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(name)}/run`,{method:"POST"})).data}async listWebhookEvents(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks/events`)).data}async listProjectWebhooks(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks`)).data}async getProjectWebhook(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`)).data}async createProjectWebhook(projectId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks`,{method:"POST",body:JSON.stringify(request)})).data}async updateProjectWebhook(projectId,webhookId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"PATCH",body:JSON.stringify(request)})).data}async deleteProjectWebhook(projectId,webhookId){await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"DELETE"})}async rotateProjectWebhookSecret(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/rotate-signing-secret`,{method:"POST"})).data.signingSecret}async testProjectWebhook(projectId,webhookId,input){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/test`,{method:"POST",body:JSON.stringify(input)})).data}async listProjectWebhookDeliveries(projectId,webhookId,limit){let query=`?page=1&limit=${limit??50}`;return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries${query}`)).data.items}async getProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}`)).data}async retryProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}/retry`,{method:"POST"})).data}async deleteSchedule(projectId,name){await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(name)}`,{method:"DELETE"})}async listEnvs(projectId,opts={}){let qs=opts.includeDeleted?"?includeDeleted=true":"";return(await this.request(`/api/management/projects/${projectId}/envs${qs}`)).data}async getEnv(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`)).data}async createEnv(projectId,input){return(await this.request(`/api/management/projects/${projectId}/envs`,{method:"POST",body:JSON.stringify(input)})).data}async syncEnv(projectId,env,input={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sync`,{method:"POST",body:JSON.stringify(input)})).data}async deleteEnv(projectId,env){await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`,{method:"DELETE"})}async getEnvDiff(projectId,env,opts={}){let params=new URLSearchParams;opts.against&¶ms.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&¶ms.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff${qs?`?${qs}`:""}`)).data}async getEnvStatus(projectId,env,opts={}){let params=new URLSearchParams;opts.against&¶ms.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&¶ms.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/status${qs?`?${qs}`:""}`)).data}async getCodeFileDiff(projectId,env,path47,opts={}){let qs=lazyFetchQs(opts.against,{path:path47});return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/code/file?${qs}`)).data}async getCodeConflictDetail(projectId,env,fromEnv,filePath){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflict/code?path=${encodeURIComponent(filePath)}`)).data}async getContentRowDiff(projectId,env,collection,rowId,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getSchemaTypeDiff(projectId,env,typeName,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getAssetDiff(projectId,env,assetId,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getTranslationRowDiff(projectId,env,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getFormSchemaDiff(projectId,env,formName,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getActivationDiff(projectId,env,agentName,triggerIndex,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/activations/${encodeURIComponent(agentName)}/${triggerIndex}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async mergeEnv(projectId,env,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge`,{method:"POST",body:JSON.stringify(body)})).data}async resolveMerge(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve`,{method:"POST",body:JSON.stringify(body)})).data}async cancelMerge(projectId,env,mergeId){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/cancel`,{method:"POST",body:JSON.stringify({mergeId})})).data}async getMergeConflicts(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflicts`)).data}async putResolveDraft(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"PUT",body:JSON.stringify(body)})).data}async deleteResolveDraft(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"DELETE"})).data}async publishRelease(projectId,body){return(await this.request(`/api/management/projects/${projectId}/releases`,{method:"POST",body:JSON.stringify(body)})).data}async activateAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/activations`,{method:"POST",body:JSON.stringify(body)})).data}async deactivateAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/activations`,{method:"DELETE",body:JSON.stringify(body)})).data}async runAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/run`,{method:"POST",body:JSON.stringify(body)})).data}async listAgentSessions(projectId,opts={}){let params=new URLSearchParams;opts.agentName&¶ms.set("agent_name",opts.agentName),opts.env&¶ms.set("env",opts.env),opts.status&¶ms.set("status",opts.status),opts.limit!==void 0&¶ms.set("limit",String(opts.limit));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/agents/sessions${qs?`?${qs}`:""}`)).data}async getAgentSession(projectId,sessionId){return(await this.request(`/api/management/projects/${projectId}/agents/sessions/${encodeURIComponent(sessionId)}`)).data.session}async getFeatures(){return this.request("/api/features")}async inviteProjectUser(input){return{id:(await this.request(`/api/management/projects/${input.projectId}/invites`,{method:"POST",body:JSON.stringify({email:input.email,roleKey:input.roleKey})})).data.id}}async updateProjectSettings(projectId,settings){return(await this.request(`/api/management/projects/${projectId}/settings`,{method:"PUT",body:JSON.stringify(settings)})).data}async deleteProject(projectId){await this.request(`/api/management/projects/${projectId}`,{method:"DELETE",body:JSON.stringify({})})}async getGitRemote(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-remote`,{},{allow403:!0})).data}async getGitCredential(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-credential`,{},{allow403:!0})).data}async getPreviewUrl(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sandbox`)).data}async sandboxPull(projectId,onProgress,env,options={}){let query=options.noRestart?"?noRestart=true":"",response=await this.rawRequest(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sandbox/pull${query}`,{method:"POST",headers:{Accept:"text/event-stream"}});if(!response.body)throw new Error("Sandbox pull failed: empty response stream");let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",errorMessage3=null,completed=!1;try{for(;;){let{value,done}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});let separatorIndex=buffer.indexOf(`
|
|
42
|
+
`)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();helpOption&&args.find(arg=>helpOption.is(arg))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;return(match=arg.match(/^(--inspect(-brk)?)$/))!==null?debugOption=match[1]:(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(debugOption=match[1],/^\d+$/.test(match[3])?debugPort=match[3]:debugHost=match[3]):(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match[1],debugHost=match[3],debugPort=match[4]),debugOption&&debugPort!=="0"?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}__name(incrementNodeInspectorPort,"incrementNodeInspectorPort");function useColor(){if(process8.env.NO_COLOR||process8.env.FORCE_COLOR==="0"||process8.env.FORCE_COLOR==="false")return!1;if(process8.env.FORCE_COLOR||process8.env.CLICOLOR_FORCE!==void 0)return!0}__name(useColor,"useColor");exports2.Command=Command2;exports2.useColor=useColor}});var require_commander=__commonJS({"../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js"(exports2){var{Argument:Argument2}=require_argument(),{Command:Command2}=require_command(),{CommanderError:CommanderError2,InvalidArgumentError:InvalidArgumentError2}=require_error(),{Help:Help2}=require_help(),{Option:Option2}=require_option();exports2.program=new Command2;exports2.createCommand=name=>new Command2(name);exports2.createOption=(flags,description)=>new Option2(flags,description);exports2.createArgument=(name,description)=>new Argument2(name,description);exports2.Command=Command2;exports2.Option=Option2;exports2.Argument=Argument2;exports2.Help=Help2;exports2.CommanderError=CommanderError2;exports2.InvalidArgumentError=InvalidArgumentError2;exports2.InvalidOptionArgumentError=InvalidArgumentError2}});import{createHash}from"node:crypto";function normalizeApiUrl(input){let trimmed=input.trim();try{let url=new URL(trimmed),pathname=url.pathname.replace(/\/+$/,"");return`${url.protocol}//${url.host}${pathname}`}catch{return trimmed.replace(/\/+$/,"")}}function hashApiUrl(input){return createHash("sha256").update(normalizeApiUrl(input)).digest("hex").slice(0,6)}function safeHostLabel(host){return host.replace(/:/g,"-").replace(/[^a-zA-Z0-9.-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").toLowerCase()}function credentialsFilename(apiUrl){let normalized=normalizeApiUrl(apiUrl),hostLabel="unknown";try{hostLabel=safeHostLabel(new URL(normalized).host)}catch{}return hostLabel.length===0&&(hostLabel="unknown"),`${hostLabel}-${hashApiUrl(apiUrl)}.json`}var init_credentials_path=__esm({"src/cli/utils/credentials-path.ts"(){__name(normalizeApiUrl,"normalizeApiUrl");__name(hashApiUrl,"hashApiUrl");__name(safeHostLabel,"safeHostLabel");__name(credentialsFilename,"credentialsFilename")}});import fs from"node:fs";import{homedir}from"node:os";import path,{join}from"node:path";import{fileURLToPath}from"node:url";function readReleaseManifest(){try{let raw=fs.readFileSync(RELEASE_FILE,"utf8"),parsed=JSON.parse(raw),manifest={};return typeof parsed.apiUrl=="string"&&parsed.apiUrl.length>0&&(manifest.apiUrl=parsed.apiUrl),typeof parsed.webUrl=="string"&&parsed.webUrl.length>0&&(manifest.webUrl=parsed.webUrl),manifest}catch{return{}}}function loadConfig(){let baked=readReleaseManifest(),apiUrl=process.env.FIMO_API_URL?.trim()||baked.apiUrl||DEFAULT_API_URL,webUrl=process.env.FIMO_WEB_URL?.trim()||baked.webUrl||DEFAULT_WEB_URL,configDir=join(process.env.XDG_CONFIG_HOME||join(homedir(),".config"),"fimo"),credentialsDir=join(configDir,"credentials");return{apiUrl,webUrl,configDir,credentialsDir,credentialsFile:join(credentialsDir,credentialsFilename(apiUrl))}}var DEFAULT_API_URL,DEFAULT_WEB_URL,THIS_FILE,CLI_ROOT,RELEASE_FILE,init_config=__esm({"src/cli/config.ts"(){init_credentials_path();DEFAULT_API_URL="http://localhost:3000",DEFAULT_WEB_URL="http://localhost:5173",THIS_FILE=fileURLToPath(import.meta.url),CLI_ROOT=path.resolve(path.dirname(THIS_FILE),"..",".."),RELEASE_FILE=path.resolve(CLI_ROOT,"release.json");__name(readReleaseManifest,"readReleaseManifest");__name(loadConfig,"loadConfig")}});import fs2 from"node:fs";function ensureCredentialsDir(cfg){fs2.existsSync(cfg.credentialsDir)||fs2.mkdirSync(cfg.credentialsDir,{recursive:!0})}function readCredentials(cfg=loadConfig()){if(!fs2.existsSync(cfg.credentialsFile))return null;let raw=fs2.readFileSync(cfg.credentialsFile,"utf-8");return JSON.parse(raw)}function writeCredentials(credentials,cfg=loadConfig()){ensureCredentialsDir(cfg);let tmpFile=`${cfg.credentialsFile}.tmp-${process.pid}`;fs2.writeFileSync(tmpFile,JSON.stringify(credentials,null,2)),fs2.renameSync(tmpFile,cfg.credentialsFile)}function clearCredentials(cfg=loadConfig()){fs2.existsSync(cfg.credentialsFile)&&fs2.unlinkSync(cfg.credentialsFile)}function setActiveOrganization(organization,cfg=loadConfig()){let creds=requireCredentials(cfg);writeCredentials({...creds,activeOrganization:organization},cfg)}function recordAuthFailure(cfg=loadConfig()){let creds=readCredentials(cfg);creds&&writeCredentials({...creds,lastFailedAuthAt:new Date().toISOString()},cfg)}function requireToken(cfg=loadConfig()){return requireCredentials(cfg).access_token}function requireCredentials(cfg=loadConfig()){let creds=readCredentials(cfg);if(!creds?.access_token)throw new NotAuthenticatedError(cfg.apiUrl);return creds}var NotAuthenticatedError,init_auth=__esm({"src/cli/auth.ts"(){init_config();NotAuthenticatedError=class extends Error{static{__name(this,"NotAuthenticatedError")}apiUrl;constructor(apiUrl,message="You are not signed in to Fimo."){super(message),this.name="NotAuthenticatedError",this.apiUrl=apiUrl}};__name(ensureCredentialsDir,"ensureCredentialsDir");__name(readCredentials,"readCredentials");__name(writeCredentials,"writeCredentials");__name(clearCredentials,"clearCredentials");__name(setActiveOrganization,"setActiveOrganization");__name(recordAuthFailure,"recordAuthFailure");__name(requireToken,"requireToken");__name(requireCredentials,"requireCredentials")}});import{spawnSync}from"node:child_process";import fs3 from"node:fs";import path2 from"node:path";import{setTimeout as sleep}from"node:timers/promises";function isPublishedInstall(cliRoot=CLI_ROOT){return fs3.existsSync(path2.join(cliRoot,"release.json"))}function resolveGlobalFimoRoot(){let result=spawnSync("npm",["root","-g"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:GLOBAL_ROOT_TIMEOUT_MS});return result.error||result.status!==0||typeof result.stdout!="string"||result.stdout.trim().length===0?null:path2.resolve(result.stdout.trim(),"fimo")}function normalizedPath(input){try{return fs3.realpathSync(input)}catch{return path2.resolve(input)}}function autoUpgradeEnabled(options={}){let usesDefaults=Object.keys(options).length===0;if(usesDefaults&&defaultEligibility!==void 0)return defaultEligibility;let env=options.env??process.env,cliRoot=options.cliRoot??CLI_ROOT,published=options.published??isPublishedInstall(cliRoot);if(env.FIMO_AUTO_UPGRADE!=="1"||!published)return usesDefaults&&(defaultEligibility=!1),!1;let globalFimoRoot=options.globalFimoRoot===void 0?resolveGlobalFimoRoot():options.globalFimoRoot;if(!globalFimoRoot)return usesDefaults&&(defaultEligibility=!1),!1;let eligible=normalizedPath(cliRoot)===normalizedPath(globalFimoRoot);return usesDefaults&&(defaultEligibility=eligible),eligible}async function acquireLock(lockDir){let deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{fs3.mkdirSync(lockDir);return}catch(error){if(error.code!=="EEXIST")throw error}let stale=!1;try{stale=Date.now()-fs3.statSync(lockDir).mtimeMs>LOCK_STALE_MS}catch{continue}if(stale){try{fs3.rmdirSync(lockDir)}catch{}continue}if(Date.now()>=deadline)throw new Error("auto-upgrade lock timeout");await sleep(LOCK_POLL_MS)}}function readGlobalFimoVersion(){let root2=resolveGlobalFimoRoot();if(!root2)return null;try{let pkg=JSON.parse(fs3.readFileSync(path2.join(root2,"package.json"),"utf8"));return typeof pkg.version=="string"?pkg.version:null}catch{return null}}async function autoUpgradeGlobal(latest){if(!VERSION_PATTERN.test(latest))return!1;let lockDir=path2.join(loadConfig().configDir,"auto-upgrade.lock");try{fs3.mkdirSync(path2.dirname(lockDir),{recursive:!0}),await acquireLock(lockDir)}catch{return!1}try{if(readGlobalFimoVersion()===latest)return!0;let install=spawnSync("npm",["install","-g",`fimo@${latest}`],{stdio:["ignore","ignore","inherit"],timeout:INSTALL_TIMEOUT_MS});return install.error||install.status!==0?!1:readGlobalFimoVersion()===latest}finally{try{fs3.rmdirSync(lockDir)}catch{}}}var INSTALL_TIMEOUT_MS,GLOBAL_ROOT_TIMEOUT_MS,LOCK_WAIT_MS,LOCK_STALE_MS,LOCK_POLL_MS,VERSION_PATTERN,defaultEligibility,init_auto_upgrade=__esm({"src/cli/auto-upgrade.ts"(){init_config();INSTALL_TIMEOUT_MS=12e4,GLOBAL_ROOT_TIMEOUT_MS=5e3,LOCK_WAIT_MS=18e4,LOCK_STALE_MS=3e5,LOCK_POLL_MS=500,VERSION_PATTERN=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;__name(isPublishedInstall,"isPublishedInstall");__name(resolveGlobalFimoRoot,"resolveGlobalFimoRoot");__name(normalizedPath,"normalizedPath");__name(autoUpgradeEnabled,"autoUpgradeEnabled");__name(acquireLock,"acquireLock");__name(readGlobalFimoVersion,"readGlobalFimoVersion");__name(autoUpgradeGlobal,"autoUpgradeGlobal")}});import fs4 from"node:fs";import path3 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";function getCliVersion(){try{let raw=fs4.readFileSync(PACKAGE_JSON_PATH,"utf8");return JSON.parse(raw).version??"0.0.0"}catch{return"0.0.0"}}var THIS_FILE2,CLI_ROOT2,PACKAGE_JSON_PATH,init_version=__esm({"src/cli/version.ts"(){THIS_FILE2=fileURLToPath2(import.meta.url),CLI_ROOT2=path3.resolve(path3.dirname(THIS_FILE2),"..",".."),PACKAGE_JSON_PATH=path3.join(CLI_ROOT2,"package.json");__name(getCliVersion,"getCliVersion")}});function lazyFetchQs(against,extras={}){let params=new URLSearchParams;against&¶ms.set("against",against);for(let[k,v]of Object.entries(extras))params.set(k,v);return params.toString()}function throwUnauthorized(cfg,status){try{recordAuthFailure(cfg)}catch{}throw new UnauthorizedError(cfg.apiUrl,status)}async function throwPermissionDenied(cfg,response){let required=[];try{let body=await response.json();required=Array.isArray(body.required)?body.required:body.required?[body.required]:[]}catch{}throw new PermissionDeniedError(cfg.apiUrl,required)}async function fimoFetch(url,init){let headers=new Headers(init.headers);headers.delete(CLI_VERSION_HEADER),headers.delete(CLI_AUTO_UPGRADE_HEADER);let canAutoUpgrade=process.argv[2]!=="git-credential"&&autoUpgradeEnabled();canAutoUpgrade&&(headers.set(CLI_VERSION_HEADER,getCliVersion()),headers.set(CLI_AUTO_UPGRADE_HEADER,"1"));let response=await fetch(url,{...init,headers});if(canAutoUpgrade&&response.status===426){let latest=response.headers.get(CLI_LATEST_HEADER);if(latest){await autoUpgradeGlobal(latest)||ui.warn({command:process.argv[2]??"fimo",message:`Could not upgrade to ${latest}; continuing with the current command.`});let retryHeaders=new Headers(init.headers);return retryHeaders.delete(CLI_VERSION_HEADER),retryHeaders.delete(CLI_AUTO_UPGRADE_HEADER),fetch(url,{...init,headers:retryHeaders})}}return response}function formatZodIssues(parsed){if(!parsed||typeof parsed!="object")return null;let error=parsed.error,issues=error&&typeof error=="object"&&"issues"in error?error.issues:void 0;return!Array.isArray(issues)||issues.length===0?null:issues.map(issue=>{let{path:path47,message}=issue;return`${Array.isArray(path47)&&path47.length>0?`${path47.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}var ApiRequestError,UnauthorizedError,PermissionDeniedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_ENV_HEADER,FimoApiClient,init_api=__esm({"src/cli/api.ts"(){init_dist();init_auth();init_auto_upgrade();init_config();init_version();__name(lazyFetchQs,"lazyFetchQs");ApiRequestError=class extends Error{static{__name(this,"ApiRequestError")}status;method;path;detail;code;body;constructor(method,path47,status,detail,code2,body){super(`API ${method} ${path47} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path47,this.status=status,this.detail=detail,this.code=code2,this.body=body}},UnauthorizedError=class extends Error{static{__name(this,"UnauthorizedError")}apiUrl;status;constructor(apiUrl,status,message){super(message??`Session for ${apiUrl} expired or invalid (HTTP ${status}).`),this.name="UnauthorizedError",this.apiUrl=apiUrl,this.status=status}},PermissionDeniedError=class extends Error{static{__name(this,"PermissionDeniedError")}apiUrl;required;constructor(apiUrl,required=[],message){let detail=required.length?` Missing permission: ${required.join(", ")}.`:"";super(message??`You don't have permission to do this on ${apiUrl}.${detail}`),this.name="PermissionDeniedError",this.apiUrl=apiUrl,this.required=required}};__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");CLI_VERSION_HEADER="X-Fimo-CLI-Version",CLI_LATEST_HEADER="X-Fimo-CLI-Latest",CLI_AUTO_UPGRADE_HEADER="X-Fimo-CLI-Auto-Upgrade",FIMO_ENV_HEADER="X-Fimo-Env";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");FimoApiClient=class _FimoApiClient{constructor(cfg=loadConfig()){this.cfg=cfg}static{__name(this,"FimoApiClient")}env;withEnv(env){let next2=new _FimoApiClient(this.cfg);return next2.env=env,next2}formatError(status,text3,body){if(!text3)return String(status);if(body&&typeof body=="object"&&!Array.isArray(body)){let parsed=body;if(typeof parsed.message=="string"&&parsed.message.length>0){let partial=formatPartialResult(parsed);return partial?`${parsed.message} ${partial}`:parsed.message}if(typeof parsed.error=="string"&&parsed.error.length>0)return parsed.error;if(parsed.error&&typeof parsed.error=="object"&&"message"in parsed.error&&typeof parsed.error.message=="string")return parsed.error.message;let zodIssues=formatZodIssues(parsed);if(zodIssues)return zodIssues}return text3}async parseError(response){let text3=await response.text(),body;try{body=text3?JSON.parse(text3):void 0}catch{return{detail:this.formatError(response.status,text3)}}let code2=body&&typeof body=="object"&&!Array.isArray(body)&&typeof body.code=="string"?body.code:void 0;return{detail:this.formatError(response.status,text3,body),code:code2,body}}resolveAuthToken(){return process.env.FIMO_API_TOKEN?.trim()||requireToken(this.cfg)}async request(path47,init={},opts={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path47}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&!opts.allow403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new ApiRequestError(init.method??"GET",path47,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async rawRequest(path47,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path47}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new Error(`API ${init.method??"GET"} ${path47} failed: ${response.status} ${error.detail}`)}return response}tenantPath(projectId,route){if(!this.env)throw new Error("FimoApiClient: tenant-scoped call requires an env. Use `client.withEnv(env)` before calling tenant CRUD methods.");return`/api/tenant/${projectId}/envs/${encodeURIComponent(this.env)}${route}`}projectEnvManagementPath(projectId,route){if(!this.env)throw new Error("FimoApiClient: env-scoped management call requires an env. Use `client.withEnv(env)` before calling env CRUD methods.");return`/api/management/projects/${projectId}/envs/${encodeURIComponent(this.env)}${route}`}async listModels(projectId,query={}){let params=new URLSearchParams;query.modality&¶ms.set("modality",query.modality);for(let t2 of query.tag??[])params.append("tag",t2);query.q&¶ms.set("q",query.q),query.category&¶ms.set("category",query.category);let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models${qs?`?${qs}`:""}`)).data}async getModel(projectId,key){try{return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/${key}`)).data}catch(err){if(err instanceof ApiRequestError&&err.status===404)return null;throw err}}async estimateModel(projectId,key,options){return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/estimate`,{method:"POST",body:JSON.stringify({model:key,options})})).data}async estimateGenerationTask(projectId,key,options){return(await this.request(this.tenantPath(projectId,"/assets/generate/estimate"),{method:"POST",body:JSON.stringify({task:key,options})})).data}async listOrganizations(){return(await this.request("/api/management/organizations")).data}async listOrganizationMembers(organizationId){return(await this.request(`/api/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`))?.members??[]}async inviteOrganizationMember(input){return this.request("/api/auth/organization/invite-member",{method:"POST",body:JSON.stringify(input)})}async getCurrentSession(){return this.request("/api/auth/get-session")}async submitSupportIssue(input){return(await this.request("/api/support/issues",{method:"POST",body:JSON.stringify(input)})).data}async getReferralSummary(userId){return(await this.request(`/api/users/${encodeURIComponent(userId)}/referrals/summary`)).data}async listProjects(organizationId){return(await this.request(`/api/management/organizations/${encodeURIComponent(organizationId)}/projects`)).data}async publishProject(projectId){await this.request(`/api/management/projects/${projectId}/publish`,{method:"POST"})}async unpublishProject(projectId){await this.request(`/api/management/projects/${projectId}/unpublish`,{method:"POST"})}async createProject(input){return(await this.request("/api/management/projects",{method:"POST",body:JSON.stringify({...input,source:"cli"})})).data}async getProject(projectId){return(await this.request(`/api/management/projects/${projectId}`)).data}async getProjectCredits(projectId){return(await this.request(`/api/management/projects/${projectId}/billing/credits`)).data}async listProjectSecretEntries(projectId,opts={}){let qs=opts.kind?`?kind=${encodeURIComponent(opts.kind)}`:"";return(await this.request(`/api/management/projects/${projectId}/secrets${qs}`)).data}async createProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets`,{method:"POST",body:JSON.stringify({key:input.key,kind:input.kind,value:input.value})})).data}async updateProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets/${encodeURIComponent(input.key)}`,{method:"PATCH",body:JSON.stringify({kind:input.kind,value:input.value})})).data}async deleteProjectSecretEntry(projectId,key,kind){let qs=`?kind=${encodeURIComponent(kind)}`;await this.request(`/api/management/projects/${projectId}/secrets/${encodeURIComponent(key)}${qs}`,{method:"DELETE"})}async listProjectIntegrations(projectId){return(await this.request(`/api/management/projects/${projectId}/integrations`)).data}async getProjectIntegrationInfo(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/info`)).data}async getProjectIntegrationStatus(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/status`)).data}async enableProjectIntegration(input){let payload={...input.authMode?{authMode:input.authMode}:{},...input.connectionAlias?{connectionAlias:input.connectionAlias}:{}};return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}`,{method:"PUT",body:JSON.stringify(payload)})).data}async connectOrganizationIntegrationWithToken(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({...input.alias?{alias:input.alias}:{},token:input.token})})).data}async startOrganizationIntegrationConnect(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({})})).data}async switchProjectIntegrationAuth(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/auth`,{method:"PATCH",body:JSON.stringify({authMode:input.authMode})})).data}async disableProjectIntegration(projectId,integrationKey){await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}`,{method:"DELETE"})}async setProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"PUT",body:JSON.stringify({value:input.value})})).data}async clearProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"DELETE"})).data}async runProjectIntegrationTool(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/run`,{method:"POST",body:JSON.stringify(input.request)})).data}async startProjectIntegrationConnect(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST"})).data}async bindProjectChannel(projectId,request){return(await this.request(`/api/management/projects/${projectId}/channels/bind`,{method:"POST",body:JSON.stringify(request)})).data}async createSchedule(projectId,request){return(await this.request(`/api/management/projects/${projectId}/schedules`,{method:"POST",body:JSON.stringify(request)})).data}async listSchedules(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules`)).data}async runSchedule(projectId,name){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(name)}/run`,{method:"POST"})).data}async listWebhookEvents(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks/events`)).data}async listProjectWebhooks(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks`)).data}async getProjectWebhook(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`)).data}async createProjectWebhook(projectId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks`,{method:"POST",body:JSON.stringify(request)})).data}async updateProjectWebhook(projectId,webhookId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"PATCH",body:JSON.stringify(request)})).data}async deleteProjectWebhook(projectId,webhookId){await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"DELETE"})}async rotateProjectWebhookSecret(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/rotate-signing-secret`,{method:"POST"})).data.signingSecret}async testProjectWebhook(projectId,webhookId,input){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/test`,{method:"POST",body:JSON.stringify(input)})).data}async listProjectWebhookDeliveries(projectId,webhookId,limit){let query=`?page=1&limit=${limit??50}`;return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries${query}`)).data.items}async getProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}`)).data}async retryProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}/retry`,{method:"POST"})).data}async deleteSchedule(projectId,name){await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(name)}`,{method:"DELETE"})}async listEnvs(projectId,opts={}){let qs=opts.includeDeleted?"?includeDeleted=true":"";return(await this.request(`/api/management/projects/${projectId}/envs${qs}`)).data}async getEnv(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`)).data}async createEnv(projectId,input){return(await this.request(`/api/management/projects/${projectId}/envs`,{method:"POST",body:JSON.stringify(input)})).data}async syncEnv(projectId,env,input={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sync`,{method:"POST",body:JSON.stringify(input)})).data}async deleteEnv(projectId,env){await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`,{method:"DELETE"})}async getEnvDiff(projectId,env,opts={}){let params=new URLSearchParams;opts.against&¶ms.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&¶ms.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff${qs?`?${qs}`:""}`)).data}async getEnvStatus(projectId,env,opts={}){let params=new URLSearchParams;opts.against&¶ms.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&¶ms.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/status${qs?`?${qs}`:""}`)).data}async getCodeFileDiff(projectId,env,path47,opts={}){let qs=lazyFetchQs(opts.against,{path:path47});return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/code/file?${qs}`)).data}async getCodeConflictDetail(projectId,env,fromEnv,filePath){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflict/code?path=${encodeURIComponent(filePath)}`)).data}async getContentRowDiff(projectId,env,collection,rowId,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getSchemaTypeDiff(projectId,env,typeName,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getAssetDiff(projectId,env,assetId,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getTranslationRowDiff(projectId,env,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getFormSchemaDiff(projectId,env,formName,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getActivationDiff(projectId,env,agentName,triggerIndex,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/activations/${encodeURIComponent(agentName)}/${triggerIndex}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async mergeEnv(projectId,env,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge`,{method:"POST",body:JSON.stringify(body)})).data}async resolveMerge(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve`,{method:"POST",body:JSON.stringify(body)})).data}async cancelMerge(projectId,env,mergeId){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/cancel`,{method:"POST",body:JSON.stringify({mergeId})})).data}async getMergeConflicts(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflicts`)).data}async putResolveDraft(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"PUT",body:JSON.stringify(body)})).data}async deleteResolveDraft(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"DELETE"})).data}async publishRelease(projectId,body){return(await this.request(`/api/management/projects/${projectId}/releases`,{method:"POST",body:JSON.stringify(body)})).data}async activateAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/activations`,{method:"POST",body:JSON.stringify(body)})).data}async deactivateAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/activations`,{method:"DELETE",body:JSON.stringify(body)})).data}async runAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/run`,{method:"POST",body:JSON.stringify(body)})).data}async listAgentSessions(projectId,opts={}){let params=new URLSearchParams;opts.agentName&¶ms.set("agent_name",opts.agentName),opts.env&¶ms.set("env",opts.env),opts.status&¶ms.set("status",opts.status),opts.limit!==void 0&¶ms.set("limit",String(opts.limit));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/agents/sessions${qs?`?${qs}`:""}`)).data}async getAgentSession(projectId,sessionId){return(await this.request(`/api/management/projects/${projectId}/agents/sessions/${encodeURIComponent(sessionId)}`)).data.session}async getFeatures(){return this.request("/api/features")}async inviteProjectUser(input){return{id:(await this.request(`/api/management/projects/${input.projectId}/invites`,{method:"POST",body:JSON.stringify({email:input.email,roleKey:input.roleKey})})).data.id}}async updateProjectSettings(projectId,settings){return(await this.request(`/api/management/projects/${projectId}/settings`,{method:"PUT",body:JSON.stringify(settings)})).data}async deleteProject(projectId){await this.request(`/api/management/projects/${projectId}`,{method:"DELETE",body:JSON.stringify({})})}async getGitRemote(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-remote`,{},{allow403:!0})).data}async getGitCredential(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-credential`,{},{allow403:!0})).data}async getPreviewUrl(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sandbox`)).data}async sandboxPull(projectId,onProgress,env,options={}){let query=options.noRestart?"?noRestart=true":"",response=await this.rawRequest(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sandbox/pull${query}`,{method:"POST",headers:{Accept:"text/event-stream"}});if(!response.body)throw new Error("Sandbox pull failed: empty response stream");let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",errorMessage3=null,completed=!1;try{for(;;){let{value,done}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});let separatorIndex=buffer.indexOf(`
|
|
43
43
|
|
|
44
44
|
`);for(;separatorIndex!==-1;){let rawEvent=buffer.slice(0,separatorIndex);buffer=buffer.slice(separatorIndex+2),separatorIndex=buffer.indexOf(`
|
|
45
45
|
|
|
@@ -192,27 +192,27 @@ description: Fimo project rules
|
|
|
192
192
|
alwaysApply: true
|
|
193
193
|
---
|
|
194
194
|
|
|
195
|
-
${agentsMdContent}`;writeIfMissing(".cursor/rules/fimo.mdc",cursorContent)}return selected.has("windsurf")&&writeIfMissing(".windsurfrules",agentsMdContent),selected.has("gemini-cli")&&writeIfMissing("GEMINI.md",agentsMdContent),result}function syncPerAgentVariants(targetDir,agents){let agentsMdPath=path9.join(targetDir,"AGENTS.md");if(!fs9.existsSync(agentsMdPath))throw new Error(`No AGENTS.md found in ${targetDir}. Run \`fimo create\` first, or create AGENTS.md manually before running \`fimo rules sync\`.`);let agentsMdContent=fs9.readFileSync(agentsMdPath,"utf8");return writePerAgentVariants(targetDir,agents,agentsMdContent)}function detectAgentsInProject(cwd){let detected=[];return fs9.existsSync(path9.join(cwd,"CLAUDE.md"))&&detected.push("claude-code"),fs9.existsSync(path9.join(cwd,".cursor","rules","fimo.mdc"))&&detected.push("cursor"),fs9.existsSync(path9.join(cwd,".windsurfrules"))&&detected.push("windsurf"),fs9.existsSync(path9.join(cwd,"GEMINI.md"))&&detected.push("gemini-cli"),detected}var TEMPLATE_ROOT,AGENT_TEMPLATES_ROOT,EXCLUDED_DIRS,init_scaffold=__esm({"src/cli/utils/scaffold.ts"(){init_templates();init_config();init_templates();TEMPLATE_ROOT=getTemplatePath("react-router"),AGENT_TEMPLATES_ROOT=path9.resolve(CLI_ROOT,"assets","agent-templates"),EXCLUDED_DIRS=new Set(["node_modules","dist","build",".turbo",".git"]);__name(resolveTemplateRoot,"resolveTemplateRoot");__name(resolveAgentTemplatesRoot,"resolveAgentTemplatesRoot");__name(resolveAgentTemplate,"resolveAgentTemplate");__name(listAgentTemplates,"listAgentTemplates");__name(copyAgentTemplate,"copyAgentTemplate");__name(copyTemplate,"copyTemplate");__name(pinFimoDependency,"pinFimoDependency");__name(copyTree,"copyTree");__name(writePerAgentVariants,"writePerAgentVariants");__name(syncPerAgentVariants,"syncPerAgentVariants");__name(detectAgentsInProject,"detectAgentsInProject")}});import{z as z5}from"zod";function filterUnknownProperties(data2,schema){if(data2==null)return data2;if(schema instanceof z5.ZodOptional||schema instanceof z5.ZodNullable||schema instanceof z5.ZodDefault)return filterUnknownProperties(data2,schema.unwrap());if(schema instanceof z5.ZodArray){if(!Array.isArray(data2))return data2;let itemSchema=schema.unwrap();return data2.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z5.ZodDiscriminatedUnion){if(typeof data2!="object"||data2===null)return data2;let unionSchema=schema,discriminator=unionSchema.def.discriminator,discriminatorValue=data2[discriminator],matchingSchema=unionSchema.options.find(option=>{let discriminatorField=option.shape[discriminator];return discriminatorField instanceof z5.ZodLiteral?discriminatorField.def.values.includes(discriminatorValue):!1});return matchingSchema?filterUnknownProperties(data2,matchingSchema):data2}if(schema instanceof z5.ZodObject){if(typeof data2!="object")return data2;let shape=schema.shape,result={};for(let key in shape)if(Object.prototype.hasOwnProperty.call(data2,key)){let fieldSchema=shape[key],fieldValue=data2[key];result[key]=filterUnknownProperties(fieldValue,fieldSchema)}if(schema.def.catchall instanceof z5.ZodUnknown)for(let[key,value]of Object.entries(data2))key in shape||(result[key]=value);return result}return data2}function createObjectDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)},partial(){let partialSchema=schema.partial();return createObjectDTO(partialSchema)},pick(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),picked=schema.pick(mask);return createObjectDTO(picked)},omit(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),omitted=schema.omit(mask);return createObjectDTO(omitted)}}}function createDiscriminatedUnionDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)}}}function createDTO(schema){if(schema instanceof z5.ZodObject)return createObjectDTO(schema);if(schema instanceof z5.ZodDiscriminatedUnion)return createDiscriminatedUnionDTO(schema);throw new Error(`Unsupported schema type: ${schema.constructor.name}. createDTO supports ZodObject and ZodDiscriminatedUnion.`)}var init_create_dto=__esm({"../../packages/api-contracts/dist/esm/utils/create-dto.js"(){"use strict";__name(filterUnknownProperties,"filterUnknownProperties");__name(createObjectDTO,"createObjectDTO");__name(createDiscriminatedUnionDTO,"createDiscriminatedUnionDTO");__name(createDTO,"createDTO")}});import{z as z6}from"zod";var createResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema=__name(dataSchema=>z6.object({data:dataSchema}),"createResponseSchema")}});import{z as z7}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z7.object({page:z7.coerce.number().int().positive().default(1),limit:z7.coerce.number().int().positive().max(100).default(20)})}});import{z as z8}from"zod";var CommonSchemas,BaseEntitySchema,ProjectRoleKeySchema,ProjectRoleKeyWithSystemSchema,ProjectPrincipalTypeSchema,ProjectVisibilitySchema,ProjectStatusSchema,ProjectInviteStatusSchema,PublicationStatusSchema,OrganizationRoleSchema,AssetTypeSchema,TemplateCodeSchema,FieldTypeSchema,RESERVED_CONTENT_FIELD_NAMES,CONTENT_TYPE_NAME_PATTERN,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION,CONTENT_FIELD_NAME_PATTERN,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION,init_common=__esm({"../../packages/api-contracts/dist/esm/types/common.js"(){"use strict";CommonSchemas={timestamp:z8.coerce.date(),positiveInt:z8.number().int().positive(),nonNegativeInt:z8.number().int().nonnegative()},BaseEntitySchema=z8.object({id:z8.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z8.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z8.enum(["full","edit","comment","view","agent"]),ProjectPrincipalTypeSchema=z8.enum(["user","org","orgRole","public","email"]),ProjectVisibilitySchema=z8.enum(["public","private"]),ProjectStatusSchema=z8.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z8.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z8.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z8.enum(["owner","admin","member"]),AssetTypeSchema=z8.enum(["file","folder"]),TemplateCodeSchema=z8.enum(["Free","Premium"]),FieldTypeSchema=z8.enum(["string","text","richtext","media","number","boolean","date","json","reference","blocks"]),RESERVED_CONTENT_FIELD_NAMES=["id","entryId","documentId","slug","locale","createdAt","updatedAt","__fimo"],CONTENT_TYPE_NAME_PATTERN=/^[A-Za-z]\w*$/,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter",CONTENT_FIELD_NAME_PATTERN=/^[A-Za-z_]\w*$/,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter or underscore"}});var ATTACHMENT_TYPES,ATTACHMENT_MIME_TYPES,ATTACHMENT_IMAGE_MIME_TYPES,ATTACHMENT_DOCUMENT_MIME_TYPES,ATTACHMENT_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image"},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image"},{mime:"image/webp",extensions:[".webp"],category:"image"},{mime:"image/avif",extensions:[".avif"],category:"image"},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:5242880},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:5242880},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:5242880}],ATTACHMENT_MIME_TYPES=ATTACHMENT_TYPES.map(t2=>t2.mime),ATTACHMENT_IMAGE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="image").map(t2=>t2.mime),ATTACHMENT_DOCUMENT_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="document").map(t2=>t2.mime),ATTACHMENT_ACCEPT_EXTENSIONS=ATTACHMENT_TYPES.flatMap(t2=>t2.extensions),ATTACHMENT_ACCEPT_STRING=[...ATTACHMENT_ACCEPT_EXTENSIONS,...ATTACHMENT_MIME_TYPES].join(","),ATTACHMENT_DROPZONE_ACCEPT=Object.fromEntries(ATTACHMENT_TYPES.map(t2=>[t2.mime,t2.extensions]))}});import{z as z9}from"zod";function isValidEnv(env){return typeof env!="string"||env.length===0||env.length>MAX_ENV_LENGTH||env.startsWith("-")||env.startsWith(".")||env.includes("//")||env.split("/").some(segment=>segment==="..")?!1:ENV_ID_REGEX.test(env)}function isProductionEnv(env){return env===PRODUCTION_ENV}var ENV_ID_REGEX,MAX_ENV_LENGTH,EnvSchema,DEFAULT_ENV,PRODUCTION_ENV,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";ENV_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_ENV_LENGTH=255;__name(isValidEnv,"isValidEnv");EnvSchema=z9.string().min(1,"env must not be empty").max(MAX_ENV_LENGTH,`env must be at most ${MAX_ENV_LENGTH} characters`).refine(isValidEnv,{error:"env must match /^[a-zA-Z0-9._/-]+$/ and must not start with `-`"}),DEFAULT_ENV="main",PRODUCTION_ENV="prod";__name(isProductionEnv,"isProductionEnv")}});var init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict"}});import{z as z10}from"zod";function referenceDocumentId(value){if(typeof value=="string")return value;if(value&&typeof value=="object"){let reference=value,hasId=Object.prototype.hasOwnProperty.call(reference,"id"),hasDocumentId=Object.prototype.hasOwnProperty.call(reference,"documentId"),id=reference.id,documentId=reference.documentId;if(hasId&&typeof id!="string"||hasDocumentId&&typeof documentId!="string"||typeof id=="string"&&typeof documentId=="string"&&id!==documentId)return null;if(typeof id=="string")return id;if(typeof documentId=="string")return documentId}return null}function toReferenceValue(value){let documentId=referenceDocumentId(value);return documentId?{documentId}:null}function referenceContentType(value){if(value&&typeof value=="object"&&"contentType"in value){let contentType=value.contentType;return typeof contentType=="string"&&contentType.length>0?contentType:null}return null}function toPolymorphicReferenceValue(value){let documentId=referenceDocumentId(value),contentType=referenceContentType(value);return documentId&&contentType?{contentType,documentId}:null}var ReferenceValueSchema,PolymorphicReferenceValueSchema,init_references=__esm({"../../packages/api-contracts/dist/esm/types/references.js"(){"use strict";__name(referenceDocumentId,"referenceDocumentId");__name(toReferenceValue,"toReferenceValue");ReferenceValueSchema=z10.preprocess(value=>{let reference=toReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},z10.object({documentId:z10.uuid()}));__name(referenceContentType,"referenceContentType");__name(toPolymorphicReferenceValue,"toPolymorphicReferenceValue");PolymorphicReferenceValueSchema=z10.preprocess(value=>{let reference=toPolymorphicReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},z10.object({contentType:z10.string().min(1),documentId:z10.uuid()}))}});import{z as z11}from"zod";function rejectFieldLocaleSettings(field,ctx){for(let key of["i18n","localized"])key in field&&ctx.addIssue({code:"custom",path:[key],message:"Field-level locale settings are not supported."})}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path47,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path47,fieldName];visit2({field,path:fieldPath,structuredDepth,insideStructuredContent});let nextDepth=structuredDepth+1;if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...fieldPath,variant.uid],nextDepth,!0);else walk(field.schema.fields,fieldPath,nextDepth,!0)}},"walk");walk(fields,[],0,!1)}var MAX_STRUCTURED_CONTENT_DEPTH,MAX_BLOCK_VARIANTS,MAX_BLOCK_ITEMS,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES,commonFieldShape,scalarFieldSchema,referenceFieldSchema,reservedStructuredContentNames,ContentFieldDefinitionSchema,blockFieldsSchema,blockVariantSchema,fixedBlocksSchema,blocksSchema,blocksFieldSchema,contentFieldDefinitionSchema,init_content_fields=__esm({"../../packages/api-contracts/dist/esm/types/content-fields.js"(){"use strict";init_common();MAX_STRUCTURED_CONTENT_DEPTH=3,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],commonFieldShape={label:z11.string().min(1).optional(),description:z11.string().optional(),editable:z11.boolean().optional(),required:z11.boolean().optional(),default:z11.unknown().optional()};__name(rejectFieldLocaleSettings,"rejectFieldLocaleSettings");scalarFieldSchema=z11.object({...commonFieldShape,type:z11.enum(["string","text","richtext","media","number","boolean","date","json"]),min:z11.number().optional(),max:z11.number().optional(),minLength:z11.number().int().nonnegative().optional(),maxLength:z11.number().int().nonnegative().optional(),regex:z11.string().optional(),multiple:z11.boolean().optional(),allowedMimeTypes:z11.array(z11.string()).optional()}).loose().superRefine((field,ctx)=>{rejectFieldLocaleSettings(field,ctx);for(let key of["target","targets","many","repeatable","schema"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on ${field.type} fields.`});if(field.type!=="number")for(let key of["min","max"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on number fields.`});if(field.type!=="string"&&field.type!=="text")for(let key of["minLength","maxLength","regex"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on string and text fields.`});field.min!==void 0&&field.max!==void 0&&field.min>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to "min".'});let effectiveMinimumLength=Math.max(field.minLength??0,field.required?1:0);if(field.maxLength!==void 0&&effectiveMinimumLength>field.maxLength&&ctx.addIssue({code:"custom",path:["maxLength"],message:'"maxLength" must be greater than or equal to the minimum required length.'}),field.regex!==void 0)try{new RegExp(field.regex)}catch{ctx.addIssue({code:"custom",path:["regex"],message:'"regex" must be a valid regular expression.'})}if(field.type!=="media")for(let key of["multiple","allowedMimeTypes"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on media fields.`})}),referenceFieldSchema=z11.object({...commonFieldShape,type:z11.literal("reference"),target:z11.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z11.array(z11.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z11.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectFieldLocaleSettings(field,ctx),!field.target&&!field.targets&&ctx.addIssue({code:"custom",path:["target"],message:'Reference fields must declare "target" or "targets".'}),field.target&&field.targets&&ctx.addIssue({code:"custom",path:["targets"],message:'A reference field declares "target" or "targets", never both.'}),field.targets&&new Set(field.targets).size!==field.targets.length&&ctx.addIssue({code:"custom",path:["targets"],message:"Reference targets must be unique."});for(let key of["repeatable","schema","min","max","minLength","maxLength","regex"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on reference fields.`})}),reservedStructuredContentNames=new Set(RESERVED_STRUCTURED_CONTENT_FIELD_NAMES),ContentFieldDefinitionSchema=z11.lazy(()=>contentFieldDefinitionSchema),blockFieldsSchema=z11.record(z11.string(),ContentFieldDefinitionSchema).superRefine((fields,ctx)=>{for(let fieldName of Object.keys(fields))CONTENT_FIELD_NAME_PATTERN.test(fieldName)||ctx.addIssue({code:"custom",path:[fieldName],message:`Field names must use ${CONTENT_FIELD_NAME_PATTERN_DESCRIPTION}.`}),reservedStructuredContentNames.has(fieldName)&&ctx.addIssue({code:"custom",path:[fieldName],message:`"${fieldName}" is reserved structured-content metadata.`})}),blockVariantSchema=z11.object({uid:z11.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z11.string().min(1),description:z11.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z11.object({fields:blockFieldsSchema}).strict(),blocksSchema=z11.object({oneOf:z11.array(blockVariantSchema).min(1).max(MAX_BLOCK_VARIANTS)}).strict().superRefine((schema,ctx)=>{let seen=new Set;for(let[index2,variant]of schema.oneOf.entries())seen.has(variant.uid)&&ctx.addIssue({code:"custom",path:["oneOf",index2,"uid"],message:"Variant UIDs must be unique."}),seen.add(variant.uid)}),blocksFieldSchema=z11.object({...commonFieldShape,type:z11.literal("blocks"),min:z11.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z11.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z11.union([fixedBlocksSchema,blocksSchema])}).loose().superRefine((field,ctx)=>{rejectFieldLocaleSettings(field,ctx);let effectiveMinimum=Math.max(field.min??0,field.required?1:0);field.max!==void 0&&effectiveMinimum>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to the minimum number of blocks.'});for(let key of["target","targets","many","repeatable","minLength","maxLength","regex"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on blocks fields.`})}),contentFieldDefinitionSchema=z11.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z12}from"zod";var AUDIT_ACTIONS,AuditActionSchema,AUDIT_OUTCOMES,AuditOutcomeSchema,AUDIT_ACTOR_KINDS,AuditActorKindSchema,init_audit_log=__esm({"../../packages/api-contracts/dist/esm/types/audit-log.js"(){"use strict";AUDIT_ACTIONS=["env_create","env_delete","env_sync","capability_check","shell_exec","git_push","git_tag","git_merge","fimo_deploy","merge_decision","session_start","session_end","cost_breach","trigger_fire","cutover_step","agent_delegate","ops_access_change","ops_service_token_change","ops_project_search","ops_project_inspect","ops_project_chat_read","ops_recent_chat_read","ops_project_snapshot","ops_support_thread_read","ops_support_report_read","ops_support_report_change","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send"],AuditActionSchema=z12.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z12.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z12.enum(AUDIT_ACTOR_KINDS)}});import{z as z13}from"zod";var OPS_BACKEND_PROFILES,OpsBackendProfileSchema,OPS_PERMISSIONS,OpsPermissionSchema,OPS_PERMISSION_PRESETS,OPS_SERVICE_PERMISSION_PRESETS,OpsAccessGrantInputSchema,OpsServiceTokenInputSchema,OpsCustomerProjectInputSchema,OPS_INVESTIGATION_STATUSES,OpsInvestigationStatusSchema,OpsInvestigationCreateInputSchema,OpsInvestigationUpdateInputSchema,OPS_KNOWN_ISSUE_STATUSES,OpsKnownIssueStatusSchema,OpsKnownIssueCreateInputSchema,OpsKnownIssueUpdateInputSchema,OPS_VALIDATION_OUTCOMES,OpsValidationOutcomeSchema,OpsValidationRunInputSchema,OpsNotificationPreviewInputSchema,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z13.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:sentry:read","ops:logs:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview","ops:notification:approve","ops:notification:send"],OpsPermissionSchema=z13.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:validations:read","ops:notification:preview"],engineer:["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:sentry:read","ops:logs:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview"],full:[...OPS_PERMISSIONS]},OPS_SERVICE_PERMISSION_PRESETS={support:OPS_PERMISSION_PRESETS.support,engineer:OPS_PERMISSION_PRESETS.engineer,full:OPS_PERMISSION_PRESETS.full.filter(permission=>permission!=="ops:notification:approve")},OpsAccessGrantInputSchema=z13.object({permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),enabled:z13.boolean().default(!0)}),OpsServiceTokenInputSchema=z13.object({name:z13.string().trim().min(1).max(120),permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),expiresAt:z13.coerce.date()}).refine(input=>!input.permissions.includes("ops:notification:approve"),{path:["permissions"],message:"Service credentials cannot approve customer notifications"}).refine(input=>input.expiresAt.getTime()>Date.now(),{path:["expiresAt"],message:"Service credential expiry must be in the future"}),OpsCustomerProjectInputSchema=z13.object({importanceReason:z13.string().trim().min(1).max(1e3),ownerUserId:z13.string().trim().min(1).nullable().optional(),framework:z13.string().trim().max(120).nullable().optional(),packageManager:z13.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z13.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z13.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z13.object({projectId:z13.uuid(),title:z13.string().trim().min(1).max(240),userReport:z13.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z13.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z13.string().trim().max(1e4).nullable().optional(),outcome:z13.string().trim().max(1e4).nullable().optional(),evidence:z13.array(z13.record(z13.string(),z13.unknown())).max(100).optional()}).refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_KNOWN_ISSUE_STATUSES=["open","monitoring","resolved"],OpsKnownIssueStatusSchema=z13.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z13.object({fingerprint:z13.string().trim().min(1).max(240),title:z13.string().trim().min(1).max(240),description:z13.string().trim().min(1).max(1e4),affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z13.array(z13.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z13.string().trim().min(1).max(64).nullable().optional(),workaround:z13.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100),detectionQueries:z13.array(z13.string().trim().min(1).max(2e3)).max(50),status:OpsKnownIssueStatusSchema}).partial().refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_VALIDATION_OUTCOMES=["passed","failed","inconclusive"],OpsValidationOutcomeSchema=z13.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z13.object({changeReference:z13.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z13.string().trim().min(1).max(1e4),evidence:z13.array(z13.record(z13.string(),z13.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z13.object({recipientEmail:z13.email().optional(),subject:z13.string().trim().min(1).max(200).default("An update from Fimo"),message:z13.string().trim().min(1).max(5e3),locale:z13.string().trim().min(2).max(20),reason:z13.string().trim().min(1).max(1e3),acknowledgePolicy:z13.literal(!0)})}});import{z as z14}from"zod";var ProjectDTOSchema,ProjectDTO,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,QuestionAnswerMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionListResponseSchema,ProjectVersionResponseSchema,VersionMutationResponseSchema,ProjectPublicationStateDTOSchema,ProjectPublicationStateDTO,PublicationMutationDTOSchema,PublicationMutationDTO,ProjectPublicationStateResponseSchema,PublicationMutationResponseSchema,ProjectResponseSchema,ProjectWithPlanResponseSchema,init_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project.dto.js"(){"use strict";init_common();init_create_dto();init_response();ProjectDTOSchema=BaseEntitySchema.extend({name:z14.string(),displayName:z14.string().nullable(),subdomain:z14.string().nullable().optional(),subdomainUpdatedAt:z14.date().nullable().optional(),organizationId:z14.string().nullable(),createdBy:z14.string().nullable(),visibility:ProjectVisibilitySchema,previewEnabled:z14.boolean().default(!0),status:ProjectStatusSchema,creationStatus:z14.string(),thumbnailUrl:z14.string().nullable(),publishedThumbnailUrl:z14.string().nullable(),category:z14.string().nullable(),appUrl:z14.string().nullable(),lastPublishedAt:z14.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z14.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z14.object({id:z14.uuid(),name:z14.string(),displayName:z14.string().nullable(),thumbnailUrl:z14.string().nullable(),visibility:ProjectVisibilitySchema,category:z14.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z14.object({id:z14.string(),name:z14.string(),avatar:z14.string().nullable(),color:z14.object({bg:z14.string(),text:z14.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z14.object({path:z14.string(),content:z14.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z14.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z14.object({id:z14.string(),messageId:z14.string(),versionId:z14.string().nullable(),role:ProjectChatMessageRole,parts:z14.array(z14.any()),createdAt:z14.coerce.date()}),MessageUserMetadataSchema=z14.object({id:z14.string(),name:z14.string().nullable().optional(),image:z14.string().nullable().optional()}).nullable().optional(),QuestionAnswerMetadataSchema=z14.object({shortTitle:z14.string().optional(),questions:z14.array(z14.object({header:z14.string(),question:z14.string(),answer:z14.string(),selectedLabels:z14.array(z14.string()),freeText:z14.string(),skipped:z14.boolean()}))}).optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z14.number(),metadata:z14.object({user:MessageUserMetadataSchema,changeManifest:z14.array(z14.any()).optional(),questionAnswer:QuestionAnswerMetadataSchema}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z14.object({id:z14.uuid(),versionId:z14.string(),projectId:z14.uuid(),commitHash:z14.string(),name:z14.string(),description:z14.string().nullable(),thumbnailUrl:z14.string().nullable(),createdAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectDocumentContentDTOSchema=z14.object({content:z14.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z14.array(ProjectDTOSchema)),ProjectVersionListResponseSchema=createResponseSchema(z14.array(ProjectVersionDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),VersionMutationResponseSchema=createResponseSchema(z14.object({success:z14.boolean(),message:z14.string().optional()})),ProjectPublicationStateDTOSchema=z14.object({isPublished:z14.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z14.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublicationMutationDTOSchema=z14.object({success:z14.boolean(),message:z14.string().optional(),publishedAt:CommonSchemas.timestamp.optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z15}from"zod";var ProjectEnvStatusSchema,ProjectEnvDTOSchema,ProjectEnvDTO,CreateProjectEnvRequestSchema,SyncProjectEnvRequestSchema,ProjectEnvResponseSchema,ProjectEnvsListResponseSchema,EnvSurfaceDiffSchema,EnvDiffResultSchema,EnvDiffResultDTO,init_project_env_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-env.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();ProjectEnvStatusSchema=z15.enum(["provisioning","active","deleted"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z15.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,previewUrl:z15.string().nullable(),parentEnv:EnvSchema.nullable(),createdBy:z15.string().nullable(),deletedAt:z15.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),CreateProjectEnvRequestSchema=z15.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z15.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z15.array(ProjectEnvDTOSchema)),EnvSurfaceDiffSchema=z15.object({surface:z15.enum(["code","schemas","content","translations","assets","forms","activations"]),status:z15.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z15.number().int().nonnegative(),conflictCount:z15.number().int().nonnegative()}),EnvDiffResultSchema=z15.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z15.coerce.date(),surfaces:z15.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z16}from"zod";var ExportProjectResponseDTOSchema,ExportProjectResponseDTO,ImportProjectResultDTOSchema,ImportProjectResultDTO,ImportPreviewCountsDTOSchema,ImportPreviewSurfaceDTOSchema,ImportPreviewDTOSchema,ImportPreviewDTO,ImportPreviewResponseDTOSchema,ImportPreviewResponseDTO,init_project_import_export_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-import-export.dto.js"(){"use strict";init_create_dto();ExportProjectResponseDTOSchema=z16.object({success:z16.literal(!0),downloadUrl:z16.string(),expiresAt:z16.string(),fileSize:z16.number(),duration:z16.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z16.object({success:z16.literal(!0),projectId:z16.string(),projectName:z16.string(),displayName:z16.string(),projectUrl:z16.string(),duration:z16.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z16.object({contentTypes:z16.number(),entries:z16.number(),assets:z16.number(),translations:z16.number(),forms:z16.number(),codeFiles:z16.number(),assetFiles:z16.number()}),ImportPreviewSurfaceDTOSchema=z16.object({name:z16.string(),included:z16.boolean(),count:z16.number().optional(),note:z16.string().optional()}),ImportPreviewDTOSchema=z16.object({projectName:z16.string(),displayName:z16.string().nullable(),visibility:z16.string().nullable(),category:z16.string().nullable(),exportedAt:z16.string(),version:z16.string(),envScope:z16.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z16.array(ImportPreviewSurfaceDTOSchema),fileSize:z16.number(),fileName:z16.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z16.object({success:z16.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z17}from"zod";var TriggerKindSchema,ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2,TriggerSchema2,init_agent_trigger_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-trigger.dto.js"(){"use strict";TriggerKindSchema=z17.enum(["manual","schedule","webhook"]),ManualTriggerSchema2=z17.object({type:z17.literal("manual")}),ScheduleTriggerSchema=z17.object({type:z17.literal("schedule"),cron:z17.string().min(1,"cron expression required").regex(/^\s*\S+\s+\S+\s+\S+\s+\S+\s+\S+\s*$/,"cron must be a 5-field expression"),tz:z17.string().optional()}),WebhookTriggerSchema2=z17.object({type:z17.literal("webhook"),path:z17.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z17.discriminatedUnion("type",[ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2])}});import{z as z18}from"zod";var ActivateRequestSchema,DeactivateRequestSchema,AgentActivationDTOSchema,AgentActivationDTO,AgentActivationsListResponseSchema,AgentActivationResponseSchema,WebhookPathTakenErrorSchema,ManualRunRequestSchema,DispatchSkippedSchema,DispatchAcceptedSchema,ManualRunResponseSchema,init_agent_activation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-activation.dto.js"(){"use strict";init_env();init_create_dto();init_response();init_agent_trigger_dto();ActivateRequestSchema=z18.object({triggerIndices:z18.array(z18.number().int().nonnegative()).optional()}),DeactivateRequestSchema=z18.object({triggerIndices:z18.array(z18.number().int().nonnegative()).optional()}),AgentActivationDTOSchema=z18.object({projectId:z18.uuid(),env:EnvSchema,agentName:z18.string().min(1),triggerIndex:z18.number().int().nonnegative(),triggerKind:TriggerKindSchema,trigger:TriggerSchema2,enabled:z18.boolean(),lastFiredAt:z18.coerce.date().nullable(),webhookPath:z18.string().nullable(),createdAt:z18.coerce.date(),updatedAt:z18.coerce.date()}),AgentActivationDTO=createDTO(AgentActivationDTOSchema),AgentActivationsListResponseSchema=createResponseSchema(z18.array(AgentActivationDTOSchema)),AgentActivationResponseSchema=createResponseSchema(AgentActivationDTOSchema),WebhookPathTakenErrorSchema=z18.object({error:z18.literal("webhook_path_taken"),conflictAgent:z18.string(),path:z18.string()}),ManualRunRequestSchema=z18.object({args:z18.unknown().optional(),requestId:z18.string().min(1).max(128).optional()}),DispatchSkippedSchema=z18.object({skipped:z18.enum(["duplicate","no-activation","agent-not-cloud","bundle-missing","trigger-stale"])}),DispatchAcceptedSchema=z18.object({sessionId:z18.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z18.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z19}from"zod";var CapabilityRiskTierSchema,CapabilitySummaryEntrySchema,AgentSubAgentSummarySchema,AgentInstallSummaryDTOSchema,AgentInstallSummaryDTO,AgentInstallSummaryResponseSchema,init_agent_install_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-install-summary.dto.js"(){"use strict";init_create_dto();init_response();CapabilityRiskTierSchema=z19.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z19.object({token:z19.string().min(1),risk:CapabilityRiskTierSchema,description:z19.string()}),AgentSubAgentSummarySchema=z19.object({name:z19.string().min(1),grant:z19.enum(["inherit","explicit"]),effectiveCaps:z19.array(z19.string().min(1))}),AgentInstallSummaryDTOSchema=z19.object({agentName:z19.string().min(1),env:z19.string().min(1),declaredCapabilities:z19.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z19.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z19.array(CapabilitySummaryEntrySchema),criticalCapabilities:z19.array(CapabilitySummaryEntrySchema),subAgents:z19.array(AgentSubAgentSummarySchema),declaresDelegate:z19.boolean(),cycle:z19.array(z19.string()).nullable(),missingSubAgents:z19.array(z19.string()),warnings:z19.array(z19.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z20}from"zod";var AgentListItemTriggerSchema,AgentListItemActivationSchema,AgentListItemDTOSchema,AgentListItemDTO,AgentListResponseSchema,init_agent_list_item_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-list-item.dto.js"(){"use strict";init_create_dto();init_response();init_agent_install_summary_dto();init_agent_trigger_dto();AgentListItemTriggerSchema=z20.object({kind:TriggerKindSchema,summary:z20.string()}),AgentListItemActivationSchema=z20.object({triggerIndex:z20.number().int().nonnegative(),triggerKind:TriggerKindSchema,env:z20.string().min(1),active:z20.boolean()}),AgentListItemDTOSchema=z20.object({name:z20.string().min(1),description:z20.string().nullable(),goalFirstLine:z20.string().nullable(),declaredCapabilities:z20.array(CapabilitySummaryEntrySchema),triggers:z20.array(AgentListItemTriggerSchema),activations:z20.array(AgentListItemActivationSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z20.array(AgentListItemDTOSchema))}});import{z as z21}from"zod";var AgentSessionStatusSchema,SessionMetricsSchema,AgentSessionDTOSchema,AgentSessionDTO,AgentSessionCheckpointDTOSchema,AgentSessionCheckpointDTO,AgentSessionResponseSchema,AgentSessionsListResponseSchema,AgentSessionCheckpointsListResponseSchema,AgentSessionWithCheckpointsResponseSchema,SessionErrorCodeSchema,CancelSessionRequestSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_env();init_create_dto();init_response();init_agent_trigger_dto();AgentSessionStatusSchema=z21.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z21.object({cpuMs:z21.number().nonnegative().default(0),netBytes:z21.number().nonnegative().default(0),walltimeMs:z21.number().nonnegative().default(0),llmTokensIn:z21.number().nonnegative().optional(),llmTokensOut:z21.number().nonnegative().optional()}),AgentSessionDTOSchema=z21.object({id:z21.uuid(),projectId:z21.uuid(),env:EnvSchema,agentName:z21.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z21.unknown().optional(),capabilities:z21.array(z21.string()).optional(),dataSources:z21.array(z21.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z21.string().nullable(),startedAt:z21.coerce.date().nullable(),finishedAt:z21.coerce.date().nullable(),cancelledAt:z21.coerce.date().nullable(),costUsd:z21.number().nonnegative(),costCeilingUsd:z21.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z21.boolean(),lastCheckpointId:z21.uuid().nullable(),branchEnvId:z21.uuid().nullable(),parentSessionId:z21.uuid().nullable(),terminalReason:z21.string().nullable(),errorMessage:z21.string().nullable(),report:z21.string().nullable(),createdAt:z21.coerce.date(),updatedAt:z21.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z21.object({id:z21.uuid(),sessionId:z21.uuid(),checkpointIdx:z21.number().int().nonnegative(),payloadRef:z21.string(),payloadSizeBytes:z21.number().int().nonnegative(),checksum:z21.string().length(64),createdAt:z21.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z21.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z21.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z21.object({session:AgentSessionDTOSchema,checkpoints:z21.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z21.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","too_many_agent_envs","env_provisioning_failed"]),CancelSessionRequestSchema=z21.object({reason:z21.string().min(1).max(120).optional()})}});import{z as z22}from"zod";var AgentBranchClassificationSchema,AgentBranchDecidedPathSchema,AgentBranchProposalDTOSchema,AgentBranchProposalDTO,DecideProposalRequestSchema,AgentBranchProposalResponseSchema,AgentBranchProposalsListResponseSchema,DecideProposalConflictResponseSchema,init_agent_proposal_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-proposal.dto.js"(){"use strict";init_create_dto();init_response();AgentBranchClassificationSchema=z22.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z22.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z22.object({id:z22.uuid(),envId:z22.uuid(),sessionId:z22.uuid().nullable(),skillName:z22.string().min(1),classification:AgentBranchClassificationSchema,rationale:z22.string().nullable(),summary:z22.string().nullable(),surfaceDeltas:z22.record(z22.string(),z22.unknown()),createdAt:z22.coerce.date(),decidedAt:z22.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z22.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z22.object({path:z22.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z22.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z22.object({code:z22.literal("merge_conflict"),message:z22.string(),conflicts:z22.record(z22.string(),z22.number().int().nonnegative())})}});import{z as z23}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,SetProjectIntegrationCredentialRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,ConnectOrganizationIntegrationRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,BindProjectChannelRequestSchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolOptionsSchema,RunProjectIntegrationToolRequestSchema,ProjectIntegrationToolRunUsageSchema,ProjectIntegrationToolRunBillingSchema,FirecrawlScrapeToolOutputSchema,FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlMonitorScheduleOutputSchema,FirecrawlMonitorTargetOutputSchema,FirecrawlMonitorOutputSchema,FirecrawlMonitorCheckOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema,FirecrawlToolKeySchema,FirecrawlToolOutputSchema,ProjectIntegrationToolRunBaseSchema,ProjectIntegrationToolRunDTOSchema,ProjectIntegrationToolRunDTO,IntegrationsListResponseSchema,IntegrationInfoResponseSchema,ProjectIntegrationStatusResponseSchema,ProjectIntegrationInstallationResponseSchema,ProjectIntegrationToolRunResponseSchema,StartProjectIntegrationConnectResponseResponseSchema,OrganizationIntegrationConnectionResponseSchema,ProjectChannelBindingResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z23.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z23.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z23.enum(["secret_text"]),IntegrationCredentialUsageSchema=z23.enum(["http_bearer","api_key"]),ProjectIntegrationCredentialStatusSchema=z23.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z23.object({mode:IntegrationAuthModeSchema,label:z23.string().min(1),description:z23.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z23.object({id:z23.string().min(1),label:z23.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z23.boolean()}),IntegrationToolDefinitionDTOSchema=z23.object({key:z23.string().min(1),name:z23.string().min(1),description:z23.string().min(1)}),IntegrationRecipeDTOSchema=z23.object({title:z23.string().min(1),description:z23.string().min(1),command:z23.string().min(1).optional()}),IntegrationInfoDTOSchema=z23.object({key:z23.string().min(1),name:z23.string().min(1),summary:z23.string().min(1),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z23.array(IntegrationAuthModeDTOSchema),credentials:z23.array(IntegrationCredentialDefinitionDTOSchema),tools:z23.array(IntegrationToolDefinitionDTOSchema),recipes:z23.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z23.object({projectId:z23.uuid(),integrationKey:z23.string().min(1),installed:z23.boolean(),enabled:z23.boolean(),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z23.string().nullable(),connectionId:z23.uuid().nullable().optional(),connectionAlias:z23.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z23.array(z23.string()),installedAt:z23.coerce.date().nullable(),updatedAt:z23.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z23.object({id:z23.uuid(),projectId:z23.uuid(),integrationKey:z23.string().min(1),enabled:z23.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z23.string(),connectionId:z23.uuid().nullable().optional(),connectionAlias:z23.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z23.array(z23.string()),createdAt:z23.coerce.date(),updatedAt:z23.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z23.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z23.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z23.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z23.object({value:z23.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z23.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z23.object({id:z23.uuid(),organizationId:z23.string().min(1),integrationKey:z23.string().min(1),alias:z23.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z23.string().min(1),externalAccountName:z23.string().nullable(),externalBotUserId:z23.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z23.array(z23.string()),connectedAt:z23.coerce.date(),updatedAt:z23.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ConnectOrganizationIntegrationRequestSchema=z23.object({alias:z23.string().min(1).max(120).optional(),token:z23.string().min(1).optional()}),StartProjectIntegrationConnectResponseSchema=z23.object({integrationKey:z23.string().min(1),connectUrl:z23.string().url(),expiresAt:z23.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),BindProjectChannelRequestSchema=z23.object({ref:z23.string().min(1),connectionAlias:z23.string().min(1).optional(),agentName:z23.string().min(1).max(160).nullable().optional(),force:z23.boolean().optional()}),ProjectChannelBindingDTOSchema=z23.object({id:z23.uuid(),projectId:z23.uuid(),integrationKey:z23.string().min(1),connectionId:z23.uuid(),externalWorkspaceId:z23.string().min(1),externalChannelId:z23.string().min(1),externalChannelName:z23.string().nullable(),agentName:z23.string().nullable(),enabled:z23.boolean(),createdAt:z23.coerce.date(),updatedAt:z23.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),FirecrawlScrapeFormatsSchema=z23.object({markdown:z23.boolean().optional(),summary:z23.boolean().optional(),links:z23.boolean().optional(),images:z23.boolean().optional(),html:z23.union([z23.literal("cleaned"),z23.literal("raw"),z23.boolean()]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z23.object({url:z23.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional(),waitForMs:z23.number().int().min(0).max(3e4).optional()}),FirecrawlSearchToolInputSchema=z23.object({query:z23.string().min(1),maxResults:z23.number().int().positive().max(20).optional(),sources:z23.array(z23.enum(["web","news","images"])).min(1).max(3).optional(),categories:z23.array(z23.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z23.array(z23.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z23.array(z23.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z23.enum(["hour","day","week","month","year"]).optional(),location:z23.string().min(1).max(160).optional(),country:z23.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlMapToolInputSchema=z23.object({url:z23.string().url(),search:z23.string().min(1).optional(),limit:z23.number().int().positive().max(200).optional(),includeSubdomains:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z23.object({url:z23.string().url(),limit:z23.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z23.object({text:z23.string().min(1).max(200).optional(),cron:z23.string().min(1).max(120).optional(),timezone:z23.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorTargetInputSchema=z23.object({type:z23.enum(["scrape","crawl"]).default("scrape"),urls:z23.array(z23.string().url()).min(1).max(50),scrapeOptions:z23.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional(),waitForMs:z23.number().int().min(0).max(3e4).optional()}).optional()}),FirecrawlMonitorCreateToolInputSchema=z23.object({name:z23.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z23.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z23.string().min(1).max(2e3).optional(),judgeEnabled:z23.boolean().optional(),retentionDays:z23.number().int().min(1).max(365).optional(),notification:z23.object({email:z23.object({enabled:z23.boolean().default(!0),recipients:z23.array(z23.string().email()).min(1).max(20),includeDiffs:z23.boolean().optional()}).optional()}).optional()}),FirecrawlMonitorIdToolInputSchema=z23.object({monitorId:z23.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z23.string().uuid()}),RunProjectIntegrationToolOptionsSchema=z23.object({connectionAlias:z23.string().min(1).optional()}),RunProjectIntegrationToolRequestSchema=z23.discriminatedUnion("tool",[RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("search"),input:FirecrawlSearchToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("scrape"),input:FirecrawlScrapeToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("map"),input:FirecrawlMapToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("crawl"),input:FirecrawlCrawlToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.create"),input:FirecrawlMonitorCreateToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.list"),input:z23.object({}).default({})}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.get"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.pause"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.resume"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.delete"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.run"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.checks"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.check"),input:FirecrawlMonitorCheckToolInputSchema})]),ProjectIntegrationToolRunUsageSchema=z23.object({provider:z23.string().min(1),providerCredits:z23.number().nonnegative().optional(),providerCostUsd:z23.number().nonnegative().optional(),requests:z23.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z23.object({credits:z23.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z23.object({url:z23.string(),provider:z23.literal("firecrawl"),title:z23.string().optional(),statusCode:z23.number().optional(),markdown:z23.string().optional(),summary:z23.string().optional(),links:z23.array(z23.string()).optional(),images:z23.array(z23.string()).optional(),html:z23.string().optional(),warning:z23.string().optional()}),FirecrawlSearchToolOutputSchema=z23.object({query:z23.string(),provider:z23.literal("firecrawl"),warning:z23.string().optional(),results:z23.array(z23.object({title:z23.string(),url:z23.string(),snippet:z23.string().optional(),content:z23.string().optional(),score:z23.number().optional(),publishedAt:z23.string().optional()}))}),FirecrawlMapToolOutputSchema=z23.object({url:z23.string(),provider:z23.literal("firecrawl"),count:z23.number(),links:z23.array(z23.object({url:z23.string(),title:z23.string().optional(),description:z23.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z23.object({url:z23.string(),provider:z23.literal("firecrawl"),total:z23.number(),pages:z23.array(z23.object({url:z23.string(),title:z23.string().optional(),statusCode:z23.number().optional(),markdown:z23.string().optional(),summary:z23.string().optional(),links:z23.array(z23.string()).optional(),images:z23.array(z23.string()).optional(),html:z23.string().optional(),warning:z23.string().optional()})),warning:z23.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z23.object({cron:z23.string().optional(),text:z23.string().optional(),timezone:z23.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z23.object({id:z23.string().optional(),urls:z23.array(z23.string()).optional(),scrapeOptions:z23.record(z23.string(),z23.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z23.object({id:z23.string(),name:z23.string(),status:z23.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z23.string().nullable().optional(),lastRunAt:z23.string().nullable().optional(),currentCheckId:z23.string().nullable().optional(),targets:z23.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z23.string().nullable().optional(),judgeEnabled:z23.boolean().optional(),estimatedCreditsPerMonth:z23.number().optional(),createdAt:z23.string().optional(),updatedAt:z23.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z23.object({id:z23.string(),monitorId:z23.string(),scheduledFor:z23.string().nullable().optional(),startedAt:z23.string().nullable().optional(),finishedAt:z23.string().nullable().optional(),estimatedCredits:z23.number().optional(),reservedCredits:z23.number().optional(),actualCredits:z23.number().optional(),billingStatus:z23.string().nullable().optional(),summary:z23.object({totalPages:z23.number().optional(),same:z23.number().optional(),changed:z23.number().optional(),new:z23.number().optional(),removed:z23.number().optional(),error:z23.number().optional()}).passthrough().optional(),error:z23.string().nullable().optional(),createdAt:z23.string().optional(),updatedAt:z23.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitors:z23.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitorId:z23.string(),deleted:z23.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitorId:z23.string(),checks:z23.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitorId:z23.string(),check:FirecrawlMonitorCheckOutputSchema,next:z23.string().optional()}),FirecrawlToolKeySchema=z23.enum(["search","scrape","map","crawl","monitor.create","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z23.union([FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z23.object({projectId:z23.uuid(),integrationKey:z23.string().min(1),tool:FirecrawlToolKeySchema,connectionAlias:z23.string().min(1).nullable().optional(),output:FirecrawlToolOutputSchema,executedAt:z23.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z23.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z23.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z23.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z23.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z23.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z23.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z23.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z23.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema)}});import{z as z24}from"zod";var ProjectScheduleStatusSchema,ProjectScheduleDTOSchema,ProjectScheduleDTO,CreateProjectScheduleRequestSchema,ProjectScheduleResponseSchema,ProjectSchedulesListResponseSchema,init_schedule_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule.dto.js"(){"use strict";init_create_dto();init_response();ProjectScheduleStatusSchema=z24.enum(["ok","failed"]),ProjectScheduleDTOSchema=z24.object({id:z24.uuid(),projectId:z24.uuid(),env:z24.string().min(1),name:z24.string().min(1),cron:z24.string().min(1),command:z24.string().min(1),enabled:z24.boolean(),lastRunAt:z24.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z24.string().nullable(),createdAt:z24.coerce.date(),updatedAt:z24.coerce.date()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z24.object({name:z24.string().min(1).max(120),cron:z24.string().min(1).max(120),command:z24.string().min(1).max(500)}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListResponseSchema=createResponseSchema(z24.array(ProjectScheduleDTOSchema))}});import{z as z25}from"zod";var AuditLogRowDTOSchema,AuditLogRowDTO,AuditLogListResponseSchema,AuditLogQuerySchema,init_audit_log_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/audit-log.dto.js"(){"use strict";init_audit_log();init_create_dto();init_response();AuditLogRowDTOSchema=z25.object({id:z25.uuid(),occurredAt:z25.coerce.date(),projectId:z25.uuid().nullable(),env:z25.string().nullable(),actor:z25.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z25.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z25.unknown().optional(),ipAddress:z25.string().nullable().optional(),userAgent:z25.string().nullable().optional(),error:z25.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z25.object({rows:z25.array(AuditLogRowDTOSchema),nextCursor:z25.string().nullable()})),AuditLogQuerySchema=z25.object({env:z25.string().optional(),action:AuditActionSchema.optional(),actor:z25.string().optional(),from:z25.coerce.date().optional(),to:z25.coerce.date().optional(),limit:z25.coerce.number().int().min(1).max(200).optional(),cursor:z25.string().optional()})}});import{z as z26}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,ActivationSnapshotSchema,ActivationDiffSchema,ActivationDiffDTO,ActivationDiffResponseSchema,ConflictSchema,FieldPickSchema,ConflictResolutionSchema,MergeResultSchema,MergeResultDTO,MergeResultResponseSchema,EngineStrategySchema,VendorStrategySchema,MergeStrategySchema,ResolvedStrategySchema,MergeRequestSchema,MergeInitiateResultSchema,MergeInitiateResultDTO,MergeInitiateResponseSchema,MergeConflictsHydrationSchema,MergeConflictsHydrationDTO,MergeConflictsHydrationResponseSchema,MergeResolveDraftRequestSchema,MergeResolveDraftResultSchema,MergeResolveDraftResultDTO,MergeResolveRequestSchema,MergeCancelRequestSchema,PublishReleaseRequestSchema,PublishReleaseResultSchema,PublishReleaseResultDTO,PublishReleaseResponseSchema,init_env_status_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-status.dto.js"(){"use strict";init_env();init_create_dto();init_response();SurfaceNameSchema=z26.enum(["code","schemas","content","translations","assets","forms","activations"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms","activations"],SurfaceDeltaVerbSchema=z26.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z26.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z26.object({verb:SurfaceDeltaVerbSchema,key:z26.string(),detail:z26.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z26.record(z26.string(),z26.unknown()).optional()}),PerSurfaceDeltaSchema=z26.object({surface:SurfaceNameSchema,status:z26.enum(["ok","timed_out","failed","unchanged"]),durationMs:z26.number().int().nonnegative().optional(),changedCount:z26.number().int().nonnegative(),conflictCount:z26.number().int().nonnegative(),items:z26.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z26.boolean().optional(),error:z26.string().optional()}),CrossSurfaceFindingSchema=z26.object({id:z26.string(),kind:z26.string(),description:z26.string(),severity:z26.enum(["warning","error"]),source:z26.object({surface:SurfaceNameSchema,key:z26.string()}),target:z26.object({surface:SurfaceNameSchema,key:z26.string()}),actions:z26.array(z26.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z26.object({env:EnvSchema,vs:EnvSchema,syncState:z26.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z26.coerce.date(),surfaces:z26.array(PerSurfaceDeltaSchema),agents:z26.array(z26.object({id:z26.string(),name:z26.string(),status:z26.enum(["active","paused","failed"]),lastRunAt:z26.coerce.date().nullable()})).optional(),crossSurface:z26.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z26.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z26.coerce.date(),surfaces:z26.array(PerSurfaceDeltaSchema),crossSurface:z26.array(CrossSurfaceFindingSchema).optional(),fingerprint:z26.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z26.object({path:z26.string(),state:z26.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z26.string(),additions:z26.number().int().nonnegative(),deletions:z26.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z26.object({oid:z26.string().optional(),content:z26.string().optional(),truncated:z26.boolean(),binary:z26.boolean()}),CodeConflictDetailSchema=z26.object({path:z26.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z26.string(),targetTipSha:z26.string(),mergeBaseSha:z26.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z26.object({id:z26.string(),slug:z26.string(),contentType:z26.string(),data:z26.record(z26.string(),z26.unknown()),updatedAt:z26.coerce.date()}),ContentRowDiffSchema=z26.object({collection:z26.string(),rowId:z26.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z26.object({name:z26.string(),label:z26.string(),isSingleton:z26.boolean(),fields:z26.record(z26.string(),z26.unknown())}),SchemaTypeDiffSchema=z26.object({typeName:z26.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z26.object({id:z26.string(),name:z26.string(),type:z26.enum(["file","folder"]),mimeType:z26.string().nullable(),storageKey:z26.string().nullable(),url:z26.string().nullable(),fileSize:z26.number().nullable(),width:z26.number().nullable(),height:z26.number().nullable(),altText:z26.string().nullable(),caption:z26.string().nullable(),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),AssetDiffSchema=z26.object({assetId:z26.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z26.object({locale:z26.string(),key:z26.string(),parent:z26.string().nullable(),child:z26.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z26.object({formName:z26.string(),label:z26.string().nullable(),schemaFingerprint:z26.string(),fields:z26.record(z26.string(),z26.unknown()),settings:z26.record(z26.string(),z26.unknown()).optional()}),FormSchemaDiffSchema=z26.object({formName:z26.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),ActivationSnapshotSchema=z26.object({agentName:z26.string(),triggerIndex:z26.number().int().nonnegative(),triggerKind:z26.string(),triggerSpec:z26.record(z26.string(),z26.unknown()),enabled:z26.boolean(),emailRecipients:z26.array(z26.string()).nullable(),qstashScheduleId:z26.string().nullable()}),ActivationDiffSchema=z26.object({agentName:z26.string(),triggerIndex:z26.number().int().nonnegative(),parent:ActivationSnapshotSchema.nullable(),child:ActivationSnapshotSchema.nullable()}),ActivationDiffDTO=createDTO(ActivationDiffSchema),ActivationDiffResponseSchema=createResponseSchema(ActivationDiffSchema),ConflictSchema=z26.object({surface:SurfaceNameSchema,key:z26.string(),kind:z26.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity"]).optional(),description:z26.string(),parentValue:z26.unknown().optional(),childValue:z26.unknown().optional(),conflictingFields:z26.array(z26.string()).optional(),code:z26.object({path:z26.string(),unresolvable:z26.boolean().optional(),reason:z26.string().optional()}).optional()}),FieldPickSchema=z26.object({field:z26.string(),choice:z26.enum(["parent","child","pick","ai-pick"]),pickedValue:z26.unknown().optional(),aiSessionId:z26.string().optional()}),ConflictResolutionSchema=z26.object({surface:SurfaceNameSchema,key:z26.string(),choice:z26.enum(["parent","child","pick"]),pickedValue:z26.unknown().optional(),fieldPicks:z26.array(FieldPickSchema).optional()}),MergeResultSchema=z26.object({ok:z26.boolean(),mergeId:z26.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z26.array(z26.object({surface:SurfaceNameSchema,count:z26.number().int().nonnegative()})),conflicts:z26.array(ConflictSchema).optional(),summary:z26.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z26.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z26.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z26.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z26.boolean().optional()}),ResolvedStrategySchema=z26.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z26.boolean()}),MergeRequestSchema=z26.object({from:EnvSchema,allowDirectMerge:z26.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z26.object({mergeId:z26.string().uuid(),streamUrl:z26.string(),strategy:ResolvedStrategySchema,acceptedAt:z26.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z26.object({mergeId:z26.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z26.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z26.array(ConflictSchema),draftResolutions:z26.array(ConflictResolutionSchema),lastEditedBy:z26.string().nullable(),lastEditedAt:z26.coerce.date().nullable(),initiator:z26.object({userId:z26.string().nullable(),role:z26.string().nullable(),agentName:z26.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z26.object({resolutions:z26.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z26.object({mergeId:z26.string().uuid(),draftResolutions:z26.array(ConflictResolutionSchema),lastEditedAt:z26.coerce.date(),lastEditedBy:z26.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z26.object({mergeId:z26.string().uuid(),resolutions:z26.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z26.object({mergeId:z26.string().uuid()}),PublishReleaseRequestSchema=z26.object({version:z26.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z26.string().max(2e4).optional()}),PublishReleaseResultSchema=z26.object({releaseTag:z26.string(),sha:z26.string(),publishedAt:z26.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z27}from"zod";var DiffRefSchema,InlineSchema,SummaryBlockSchema,EnvDiffSummarySchema,EnvDiffSummaryResultSchema,EnvDiffSummaryResultDTO,EnvDiffSummaryResponseSchema,init_env_diff_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-diff-summary.dto.js"(){"use strict";init_create_dto();init_response();init_env_status_dto();DiffRefSchema=z27.object({surface:SurfaceNameSchema,key:z27.string(),label:z27.string()}),InlineSchema=z27.object({text:z27.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z27.discriminatedUnion("type",[z27.object({type:z27.literal("paragraph"),content:z27.array(InlineSchema).max(24)}),z27.object({type:z27.literal("preview"),ref:DiffRefSchema,caption:z27.string().optional()}),z27.object({type:z27.literal("code"),code:z27.string(),lang:z27.string().optional(),caption:z27.string().optional()}),z27.object({type:z27.literal("risk"),level:z27.enum(["warning","error"]),content:z27.array(InlineSchema).max(24)}),z27.object({type:z27.literal("list"),items:z27.array(z27.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z27.object({headline:z27.string(),blocks:z27.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z27.object({summary:EnvDiffSummarySchema,fingerprint:z27.string(),generatedAt:z27.coerce.date(),cached:z27.boolean().optional(),credits:z27.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z28}from"zod";var PROJECT_ANALYTICS_PRESETS,PROJECT_ANALYTICS_GROUP_BY_OPTIONS,ProjectDailyVisitorsDTOSchema,ProjectAnalyticsBreakdownItemDTOSchema,ProjectAnalyticsPageBreakdownItemDTOSchema,ProjectAnalyticsRangeDTOSchema,ProjectAnalyticsAnnotationDTOSchema,ProjectPageviewAnalyticsDTOSchema,ProjectPageviewAnalyticsDTO,ProjectAnalyticsAnnotationDTO,init_project_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-analytics.dto.js"(){"use strict";init_create_dto();PROJECT_ANALYTICS_PRESETS=["today","yesterday","this_week","this_month","last_7_days","last_30_days","last_90_days","last_week","last_month","last_quarter","last_year","custom"],PROJECT_ANALYTICS_GROUP_BY_OPTIONS=["day","week","month","quarter"],ProjectDailyVisitorsDTOSchema=z28.object({date:z28.string(),visitors:z28.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z28.object({key:z28.string(),visitors:z28.number().int().nonnegative(),pageviews:z28.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z28.object({path:z28.string(),pageName:z28.string().nullable().optional(),visitors:z28.number().int().nonnegative(),pageviews:z28.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z28.object({preset:z28.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z28.string(),requestedTo:z28.string(),effectiveFrom:z28.string(),effectiveTo:z28.string(),isRetentionLimited:z28.boolean(),groupBy:z28.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z28.object({date:z28.string(),content:z28.string(),updatedAt:z28.string(),updatedByUserId:z28.string()}),ProjectPageviewAnalyticsDTOSchema=z28.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z28.number().int().nonnegative(),pageviews:z28.number().int().nonnegative(),bounceRate:z28.number().min(0).max(100),viewsPerVisit:z28.number().nonnegative(),averageVisitDurationSeconds:z28.number().nonnegative(),visitorsSeries:z28.array(ProjectDailyVisitorsDTOSchema),topPages:z28.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z28.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z28.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z28.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z28.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z28.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z29}from"zod";var ProjectInviteDTOSchema,ProjectInviteDTO,CreatedProjectInviteDTOSchema,CreatedProjectInviteDTO,AcceptedProjectInviteDTOSchema,AcceptedProjectInviteDTO,init_project_invite_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-invite.dto.js"(){"use strict";init_common();init_create_dto();ProjectInviteDTOSchema=z29.object({id:z29.string(),email:z29.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z29.coerce.date(),createdAt:z29.coerce.date(),inviterUserId:z29.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z29.object({id:z29.string(),token:z29.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z29.object({success:z29.boolean(),projectId:z29.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z30}from"zod";var PublicUserDTOSchema,PublicUserDTO,ReferralCountCTOSchema,ReferralCountCTO,ReferralSummaryCTOSchema,ReferralSummaryCTO,AuthenticatedUserDTOSchema,AuthenticatedUserDTO,AuthenticatedUserResponseSchema,ReferralCountResponseSchema,ReferralSummaryResponseSchema,init_user_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/user.dto.js"(){"use strict";init_create_dto();init_response();PublicUserDTOSchema=z30.object({id:z30.string(),name:z30.string(),image:z30.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z30.object({count:z30.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z30.object({counts:z30.object({signed_up:z30.int(),activated:z30.int()}),credits:z30.object({total:z30.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z30.email(),emailVerified:z30.boolean(),createdAt:z30.coerce.date(),updatedAt:z30.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z31}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,ProjectPermissionsDTOSchema,ProjectPermissionsDTO,ProjectAccessDTOSchema,ProjectAccessDTO,AccessMutationResponseSchema,InviteAcceptResponseSchema,init_project_access_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-access.dto.js"(){"use strict";init_common();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z31.object({id:z31.string(),principalType:ProjectPrincipalTypeSchema,principalId:z31.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z31.coerce.date(),expiresAt:z31.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),ProjectPermissionsDTOSchema=z31.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z31.record(z31.string(),z31.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z31.object({access:z31.array(ProjectAccessItemDTOSchema),invites:z31.array(ProjectInviteDTOSchema),organization:z31.object({name:z31.string().nullable(),logo:z31.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z31.object({success:z31.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z31.object({success:z31.boolean(),projectId:z31.uuid()}))}});import{z as z32}from"zod";var PublicationStateDTOSchema,PublicationStateDTO,init_publication_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/publication.dto.js"(){"use strict";init_common();init_create_dto();PublicationStateDTOSchema=z32.object({publicationStatus:PublicationStatusSchema,appUrl:z32.string().nullable(),lastPublishedAt:z32.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z33}from"zod";var SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,PreviewBootstrapDTOSchema,PreviewBootstrapDTO,PreviewBootstrapResponseSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();SandboxSessionDTOSchema=z33.object({url:z33.url(),expiresAt:z33.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewBootstrapDTOSchema=z33.discriminatedUnion("source",[z33.object({source:z33.literal("artifact"),artifact:SandboxSessionDTOSchema,dev:z33.null()}),z33.object({source:z33.literal("dev"),artifact:z33.null(),dev:SandboxSessionDTOSchema})]),PreviewBootstrapDTO=createDTO(PreviewBootstrapDTOSchema),PreviewBootstrapResponseSchema=createResponseSchema(PreviewBootstrapDTOSchema)}});import{z as z34}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z34.string(),slug:z34.string().nullable(),logo:z34.string().nullable(),metadata:z34.record(z34.string(),z34.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z34.object({id:z34.string(),name:z34.string(),email:z34.email(),image:z34.string().nullable()}),OrganizationMemberDTOSchema=z34.object({id:z34.string(),userId:z34.string(),organizationId:z34.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z34.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z35}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common();init_create_dto();init_response();CancellationReasonCodeSchema=z35.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z35.object({reason:CancellationReasonCodeSchema,details:z35.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z35.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),AiCreditsEntitlementSchema=z35.object({included:z35.number().optional(),unitPrice:z35.number().optional(),dailyCap:z35.number().nullable().optional()}),EntitlementsDTOSchema=z35.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z35.object({retentionDays:z35.number().int().positive(),canUseExtendedDateRanges:z35.boolean()}).optional(),members:z35.object({canInvite:z35.boolean(),maxMembers:z35.number().int().positive().nullable()}).optional(),projects:z35.object({canCreatePrivateProjects:z35.boolean(),maxPrivateProjects:z35.number().int().positive().nullable()}).optional(),domains:z35.object({canUseCustomDomains:z35.boolean(),maxDomains:z35.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z35.object({id:z35.string(),external_id:z35.string(),customerId:z35.string(),planId:z35.string(),planCode:TemplateCodeSchema,currentPeriod:z35.object({start:z35.string(),end:z35.string().nullable()}),cancelAt:z35.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z35.string(),nextPaymentAt:z35.string().nullable(),baseAmount:z35.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z35.object({totalCap:z35.number(),dailyCap:z35.number(),usedTotal:z35.number()}),CreditBalanceDTOSchema=z35.object({total:z35.number(),base:z35.number(),dailyBase:z35.number(),purchases:z35.number(),awards:z35.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z35.object({total:z35.number(),nearLimit:z35.boolean(),canChat:z35.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z35.object({dailyFreeAvailable:z35.number(),monthlyAvailable:z35.number(),purchasedAvailable:z35.number(),awardedAvailable:z35.number()}),ProjectDailyCreditAllowanceDTOSchema=z35.object({periodCap:z35.number(),dailyGrant:z35.number(),usedThisPeriod:z35.number(),remainingThisPeriod:z35.number()}),ProjectCreditBalanceDTOSchema=z35.object({projectId:z35.uuid(),organizationId:z35.string(),balance:z35.object({totalAvailable:z35.number(),nearLimit:z35.boolean(),canUseAi:z35.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z35.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),SuccessfulPurchaseDTOSchema=z35.object({invoiceId:z35.string(),newBalance:z35.int(),creditCount:z35.int(),amountUsd:z35.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z35.object({url:z35.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema)}});import{z as z36}from"zod";var PaymentMethodDTOSchema,PaymentMethodDTO,init_payment_method_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/payment-method.dto.js"(){"use strict";init_create_dto();PaymentMethodDTOSchema=z36.object({brand:z36.string(),last4:z36.string(),exp:z36.string(),isDefault:z36.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z37}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema,EntryDTO,PaginatedEntriesDTOSchema,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema,EntryListResponseSchema,MAX_BULK_ENTRIES,entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema,EntryWhereSchema,EntryMutationBodySchema,entryIdsSchema,EntrySqlQueryRequestSchema,BulkCreateEntriesRequestSchema,BulkUpdateEntriesRequestSchema,BulkDeleteEntriesRequestSchema,EntrySqlQueryResponseSchema,EntrySqlQueryResponseDTO,BulkCreateEntriesResponseSchema,BulkCreateEntriesResponseDTO,BulkUpdateEntriesResponseSchema,BulkUpdateEntriesResponseDTO,BulkDeleteEntriesResponseSchema,BulkDeleteEntriesResponseDTO,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common();init_content_fields();init_create_dto();init_response();FieldDefinitionSchema=ContentFieldDefinitionSchema,SchemaFieldPathSchema=z37.string().superRefine((path47,ctx)=>{let segments=path47.split(".");(segments.length===0||segments.some(segment=>!CONTENT_FIELD_NAME_PATTERN.test(segment)))&&ctx.addIssue({code:"custom",message:"Field paths must use dot-separated field or block variant names."})}),SchemaMigrationOperationSchema=z37.object({type:z37.literal("renameField"),contentType:z37.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z37.object({enabled:z37.boolean()}).strict(),ContentTypeDTOSchema=z37.object({id:z37.string(),name:z37.string(),label:z37.string(),isSingleton:z37.boolean(),i18n:ContentTypeI18nSchema,fields:z37.record(z37.string(),FieldDefinitionSchema),createdAt:z37.string(),updatedAt:z37.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z37.object({contentTypes:z37.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z37.object({id:z37.string(),entryId:z37.string(),documentId:z37.string(),slug:z37.string(),locale:z37.string().optional(),createdAt:z37.string(),updatedAt:z37.string(),__fimo:z37.object({contentType:z37.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z37.object({data:z37.array(EntryDTOSchema),meta:z37.object({limit:z37.number(),offset:z37.number(),total:z37.number(),hasMore:z37.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z37.object({contentType:z37.string(),count:z37.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z37.object({counts:z37.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z37.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z37.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z37.union([z37.string(),z37.number(),z37.boolean(),z37.null()]),entryWhereOperatorSchema=z37.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z37.array(entryWhereScalarSchema).optional(),$nin:z37.array(entryWhereScalarSchema).optional(),$contains:z37.string().optional(),$startsWith:z37.string().optional(),$null:z37.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z37.record(z37.string(),z37.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z37.record(z37.string(),z37.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z37.object({data:z37.record(z37.string(),z37.unknown()),locale:z37.string().min(1).optional(),documentId:z37.uuid().optional()}),entryIdsSchema=z37.array(z37.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z37.object({sql:z37.string().min(1)}),BulkCreateEntriesRequestSchema=z37.object({entries:z37.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z37.union([z37.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z37.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z37.object({updates:z37.array(z37.object({id:z37.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z37.union([z37.object({ids:entryIdsSchema,locale:z37.string().min(1).optional()}),z37.object({where:EntryWhereSchema,locale:z37.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z37.object({data:z37.array(z37.record(z37.string(),z37.unknown())),meta:z37.object({rowCount:z37.number().int().nonnegative(),truncated:z37.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z37.object({data:z37.array(EntryDTOSchema),meta:z37.object({created:z37.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z37.object({data:z37.array(EntryDTOSchema),meta:z37.object({updated:z37.number().int().nonnegative(),missing:z37.array(z37.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z37.object({data:z37.array(EntryDTOSchema),meta:z37.object({deleted:z37.number().int().nonnegative(),missing:z37.array(z37.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z38}from"zod";var CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH,CmsContentTypeNameSchema,CmsFieldNameSchema,CmsCollectionOrderSchema,CmsFieldOrderSchema,CmsListSortSchema,CmsDisplayDefaultsDTOSchema,CmsDisplayDefaultsDTO,CmsCollectionOrderRequestSchema,CmsFieldOrderRequestSchema,CmsDisplayDefaultsResponseSchema,init_cms_display_defaults_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/cms-display-defaults.dto.js"(){"use strict";init_common();init_create_dto();init_response();CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS=200,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH=255,CmsContentTypeNameSchema=z38.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z38.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z38.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z38.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z38.object({field:CmsFieldNameSchema,direction:z38.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z38.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z38.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z38.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z38.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z38.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z39}from"zod";var AssetPathItemSchema,AssetDTOSchema,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema,AssetListResponseSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common();init_create_dto();init_response();AssetPathItemSchema=z39.object({id:z39.string(),name:z39.string()}),AssetDTOSchema=z39.object({id:z39.string(),name:z39.string(),type:AssetTypeSchema,originalFileName:z39.string().nullable(),parentId:z39.string().nullable(),mimeType:z39.string().nullable(),fileSize:z39.number().nullable(),url:z39.string().nullable(),storageKey:z39.string().nullable(),createdAt:z39.string(),updatedAt:z39.string(),altText:z39.string().nullable().optional(),caption:z39.string().nullable().optional(),aiCaption:z39.string().nullable().optional(),aiAltText:z39.string().nullable().optional(),aiTags:z39.array(z39.string()).nullable().optional(),aiPrimaryColor:z39.string().nullable().optional(),aiProcessingStatus:z39.string().nullable().optional(),width:z39.number().nullable().optional(),height:z39.number().nullable().optional(),path:z39.array(AssetPathItemSchema).optional(),hasChildren:z39.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z39.lazy(()=>z39.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z39.array(AssetDTOSchema))}});import{z as z40}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z40.object({key:z40.string(),value:z40.string().optional(),defaultValue:z40.string(),locale:z40.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z41}from"zod";var DocumentNodeDTOSchema,DocumentTreeDTOSchema,DocumentPathDTOSchema,DocumentPathDTO,DocumentTreeResponseSchema,DocumentPathResponseSchema,init_document_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/document.dto.js"(){"use strict";init_create_dto();init_response();DocumentNodeDTOSchema=z41.object({id:z41.string(),name:z41.string(),type:z41.enum(["file","folder"]),path:z41.string(),children:z41.lazy(()=>z41.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z41.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z41.object({path:z41.string(),exists:z41.boolean(),type:z41.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z42}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatDeletionDTOSchema,ChatDeletionDTO,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,ChatDeletionResponseSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_create_dto();init_response();init_project_dto();ChatMessageListDTOSchema=z42.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z42.object({items:z42.array(ProjectMessagePublicDTOSchema),nextCursor:z42.string().nullable()}),ChatDeletionDTOSchema=z42.object({success:z42.boolean(),deletedCount:z42.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema)}});import{z as z43}from"zod";var UploadResultDTOSchema,UploadResultDTO,UploadResultResponseSchema,init_upload_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/upload.dto.js"(){"use strict";init_common();init_create_dto();init_response();UploadResultDTOSchema=z43.object({url:z43.string().url(),key:z43.string(),size:z43.number(),contentType:z43.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z44}from"zod";var ServicePermissionsDTOSchema,ServicePermissionsDTO,ServicePermissionsResponseSchema,init_service_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/service.dto.js"(){"use strict";init_create_dto();init_response();ServicePermissionsDTOSchema=z44.object({canAccess:z44.boolean(),permissions:z44.record(z44.string(),z44.boolean()),role:z44.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z45}from"zod";var OrganizationProjectsSearchQuerySchema,init_search_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/search.dto.js"(){"use strict";init_pagination();OrganizationProjectsSearchQuerySchema=PaginationQuerySchema.extend({q:z45.string().trim().default(""),sort:z45.enum(["recent","name","relevance"]).default("recent"),category:z45.string().optional(),visibility:z45.enum(["public","private"]).optional()})}});import{z as z46}from"zod";var DomainStatusSchema,DomainSourceSchema,PaymentStatusSchema,DomainDTOSchema,DomainDTO,DomainSearchResultDTOSchema,DomainSearchResultDTO,DomainPricingDTOSchema,DomainPricingDTO,DomainContactSchema,DomainContactDTO,UpdateDomainContactsRequestSchema,SearchDomainsRequestSchema,CheckAvailabilityRequestSchema,DOMAIN_NAME_REGEX,DomainNameSchema,PurchaseDomainRequestSchema,UpdateDomainSettingsRequestSchema,RenewDomainRequestSchema,DomainResponseSchema,DomainListResponseSchema,DomainSearchResultListResponseSchema,DomainPricingResponseSchema,DomainContactResponseSchema,ContactVerificationStatusSchema,ContactVerificationStatusResponseSchema,init_registered_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/registered-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();DomainStatusSchema=z46.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z46.enum(["fimo","external"]),PaymentStatusSchema=z46.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z46.object({id:z46.string().uuid(),domain:z46.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z46.boolean(),price:z46.number().int().nullable(),renewalPrice:z46.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z46.string().nullable(),failureReason:z46.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z46.object({domain:z46.string(),available:z46.boolean(),premium:z46.boolean(),price:z46.number().nullable(),renewalPrice:z46.number().nullable(),purchaseType:z46.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z46.object({domain:z46.string(),price:z46.number().nullable(),renewalPrice:z46.number().nullable(),premium:z46.boolean(),allowedYears:z46.array(z46.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z46.object({firstName:z46.string().max(100),lastName:z46.string().max(100),companyName:z46.string().max(100).optional(),address1:z46.string().max(255),address2:z46.string().max(255).optional(),city:z46.string().max(100),state:z46.string().max(100),zip:z46.string().max(20),country:z46.string().max(2),phone:z46.string().max(30),email:z46.union([z46.string().email().max(255),z46.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z46.object({firstName:z46.string().min(1).max(100),lastName:z46.string().min(1).max(100),companyName:z46.string().max(100).optional(),address1:z46.string().min(1).max(255),address2:z46.string().max(255).optional(),city:z46.string().min(1).max(100),state:z46.string().min(1).max(100),zip:z46.string().min(1).max(20),country:z46.string().min(1).max(2),phone:z46.string().min(1).max(30),email:z46.string().email().max(255)}),SearchDomainsRequestSchema=z46.object({keyword:z46.string().min(1).max(100),tldFilter:z46.array(z46.string()).optional()}),CheckAvailabilityRequestSchema=z46.object({domains:z46.array(z46.string()).min(1).max(50)}),DOMAIN_NAME_REGEX=/^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,DomainNameSchema=z46.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z46.object({domain:DomainNameSchema,years:z46.number().int().min(1).max(10).optional().default(3),autoRenew:z46.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z46.object({autoRenew:z46.boolean().optional()}),RenewDomainRequestSchema=z46.object({years:z46.number().int().min(1).max(10).optional().default(1),autoRenew:z46.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z46.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z46.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z46.object({verified:z46.boolean(),email:z46.string().nullable(),verifyBy:z46.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z47}from"zod";var ProjectDomainStatusSchema,SSLStatusSchema,SSLValidationRecordSchema,SSLValidationErrorSchema,OwnershipVerificationSchema,ProjectDomainSSLDTOSchema,DomainProviderSchema,DomainTypeSchema,RedirectConfigSchema,ProjectDomainDTOSchema,ProjectDomainDTO,ProjectDomainListResponseSchema,ProjectDomainResponseSchema,AddProjectDomainRequestSchema,CheckProjectDomainHostnameReasonSchema,CheckProjectDomainHostnameResponseSchema,DeleteProjectDomainResponseSchema,init_project_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();ProjectDomainStatusSchema=z47.enum(["pending","active","pending_validation","active_redeploying","moved","deleted","pending_deletion","pending_migration","pending_provisioned","test_pending","test_active","test_active_apex","test_blocked","test_failed","provisioned","blocked"]),SSLStatusSchema=z47.enum(["initializing","pending_validation","pending_issuance","pending_deployment","pending_expiration","expired","active","deleted","pending_cleanup","staging_deployment","staging_active","deactivating","inactive","backup_issued","holding_deployment"]),SSLValidationRecordSchema=z47.object({txtName:z47.string().nullable().optional(),txtValue:z47.string().nullable().optional(),httpUrl:z47.string().nullable().optional(),httpBody:z47.string().nullable().optional(),cname:z47.string().nullable().optional(),cnameTarget:z47.string().nullable().optional()}),SSLValidationErrorSchema=z47.object({message:z47.string()}),OwnershipVerificationSchema=z47.object({type:z47.string(),name:z47.string(),value:z47.string()}),ProjectDomainSSLDTOSchema=z47.object({status:z47.string(),method:z47.string().nullable(),type:z47.string().nullable(),validationRecords:z47.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z47.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z47.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z47.enum(["subdomain","apex"]),RedirectConfigSchema=z47.object({type:z47.literal("apex_to_www"),linkedDomainId:z47.string()}).nullable().optional(),ProjectDomainDTOSchema=z47.object({id:z47.string(),hostname:z47.string(),status:z47.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z47.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z47.string(),scdCnameTarget:z47.string().optional(),apexTargets:z47.array(z47.string()),dnsAutoConfigured:z47.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z47.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z47.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z47.object({hostname:z47.hostname().regex(/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,{error:"Invalid hostname"}).refine(value=>!/\.fimo\.site$/i.test(value),{error:"This is a Fimo-owned domain. Edit your built-in URL instead."}),redirectToWww:z47.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z47.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z47.object({available:z47.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z47.object({success:z47.boolean(),hostname:z47.string()}))}});import{z as z48}from"zod";var SUBDOMAIN_REGEX,SubdomainCheckReasonSchema,CheckProjectSubdomainResponseSchema,UpdateProjectSubdomainRequestSchema,UpdateProjectSubdomainErrorReasonSchema,UpdateProjectSubdomainResponseSchema,SubdomainSuggestionsQuerySchema,SubdomainSuggestionsResponseSchema,init_project_subdomain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-subdomain.dto.js"(){"use strict";init_response();SUBDOMAIN_REGEX=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,SubdomainCheckReasonSchema=z48.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z48.object({available:z48.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z48.object({slug:z48.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z48.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z48.object({subdomain:z48.string(),subdomainUpdatedAt:z48.coerce.date()})),SubdomainSuggestionsQuerySchema=z48.object({base:z48.string().max(100).optional(),max:z48.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z48.object({suggestions:z48.array(z48.string())}))}});import{z as z49}from"zod";var ProjectLocaleCoverageSchema,ProjectLocaleStatsItemSchema,ProjectLocaleStatsSchema,ProjectLocaleStatsDTO,ProjectLocaleStatsResponseSchema,AddProjectLocaleRequestSchema,RemoveProjectLocaleParamsSchema,ProjectLocaleMutationSchema,ProjectLocaleMutationDTO,ProjectLocaleMutationResponseSchema,RemoveProjectLocaleSchema,RemoveProjectLocaleDTO,RemoveProjectLocaleResponseSchema,init_project_locale_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-locale.dto.js"(){"use strict";init_create_dto();init_response();ProjectLocaleCoverageSchema=z49.object({translated:z49.number().int().nonnegative(),total:z49.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z49.object({locale:z49.string(),isDefault:z49.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z49.object({defaultLocale:z49.string(),routing:z49.object({strategy:z49.literal("path-prefix"),prefixDefaultLocale:z49.boolean()}),locales:z49.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z49.object({locale:z49.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z49.object({locale:z49.string().min(1).max(40)}),ProjectLocaleMutationSchema=z49.object({locale:z49.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z49.object({locale:z49.string(),entriesDeleted:z49.number().int().nonnegative(),labelsDeleted:z49.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z50}from"zod";function flag(key,description,options={}){return{name:key.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),key,description,type:options.type??"string",required:options.required??!1,...options.defaultValue!==void 0?{defaultValue:options.defaultValue}:{},...options.enumValues?{enumValues:[...options.enumValues]}:{},isArray:options.isArray??!1}}var GENERATION_QUALITIES,GENERATION_ASPECT_RATIOS,GENERATION_TASK_IDS,GenerationQualitySchema,GenerationTaskIdSchema,GENERATION_TASK_MANIFESTS,GenerationTaskEstimateDTOSchema,GenerationTaskEstimateDTO,init_generation_task_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation-task.dto.js"(){"use strict";init_create_dto();GENERATION_QUALITIES=["draft","standard","premium"],GENERATION_ASPECT_RATIOS=["1:1","16:9","9:16","4:3","3:4"],GENERATION_TASK_IDS=["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"],GenerationQualitySchema=z50.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z50.enum(GENERATION_TASK_IDS);__name(flag,"flag");GENERATION_TASK_MANIFESTS=[{id:"image.generate",modality:"image",operation:"generate",displayName:"Generate image",description:"Create an image from a prompt. Quality selects the appropriate generation route.",flags:[flag("prompt","Generation prompt",{required:!0}),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.edit",modality:"image",operation:"edit",displayName:"Edit image",description:"Transform up to five source images using a natural-language instruction.",flags:[flag("prompt","Editing instruction",{required:!0}),flag("images","Source asset id or absolute URL; repeatable up to five times",{required:!0,isArray:!0}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.remove-background",modality:"image",operation:"remove-background",displayName:"Remove image background",description:"Remove the background from one image and return a transparent cutout.",flags:[flag("image","Source asset id or absolute URL",{required:!0})]},{id:"image.upscale",modality:"image",operation:"upscale",displayName:"Upscale image",description:"Increase image resolution while preserving and optionally enhancing detail.",flags:[flag("image","Source asset id or absolute URL",{required:!0}),flag("targetMegapixels","Target resolution in megapixels",{type:"integer",defaultValue:4}),flag("outputFormat","Output image format",{type:"enum",defaultValue:"png",enumValues:["webp","jpg","png"]}),flag("enhanceDetails","Improve fine detail during upscaling",{type:"boolean",defaultValue:!0}),flag("enhanceRealism","Favor photorealistic detail reconstruction",{type:"boolean",defaultValue:!1})]},{id:"video.generate",modality:"video",operation:"generate",displayName:"Generate video",description:"Create a video from text or animate one source image. Loop closes the final frame back to the first.",flags:[flag("prompt","Generation and motion prompt",{required:!0}),flag("image","Optional source asset id or absolute URL"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"16:9",enumValues:GENERATION_ASPECT_RATIOS}),flag("duration","Duration in seconds; loops support 3 to 20 seconds",{type:"integer",defaultValue:5}),flag("includeAudio","Generate audio with the video",{type:"boolean",defaultValue:!1}),flag("loop","Make the final frame return to the source image",{type:"boolean",defaultValue:!1})]},{id:"video.animate",modality:"video",operation:"animate",displayName:"Animate image from video",description:"Apply the motion and camera movement from a source video to a reference image.",flags:[flag("video","Motion source asset id or absolute URL",{required:!0}),flag("image","Subject reference asset id or absolute URL",{required:!0}),flag("prompt","Optional instruction for the animation"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]},{id:"video.replace",modality:"video",operation:"replace",displayName:"Replace subjects in video",description:"Replace people in a source video with one to three reference identities while preserving motion.",flags:[flag("video","Source video asset id or absolute URL",{required:!0}),flag("images","Identity reference asset id or URL; repeatable up to three times",{required:!0,isArray:!0}),flag("prompt","Optional placement instruction"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]}],GenerationTaskEstimateDTOSchema=z50.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z50.number(),credits:z50.number().optional(),billingMode:z50.enum(["fimo-credits","provider-account"]).optional(),confidence:z50.enum(["exact","estimated","metered"]),basis:z50.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z51}from"zod";var GenerateRequestBaseSchema,GenerateRequestDTOSchema,GenerateRequestDTO,GenerateResponseDataSchema,GenerateResponseDTO,GenerateResponseSchema,GenerateErrorSchema,init_generation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation.dto.js"(){"use strict";init_create_dto();init_response();init_asset_dto();init_generation_task_dto();GenerateRequestBaseSchema=z51.object({options:z51.record(z51.string(),z51.unknown()),name:z51.string().optional(),parentId:z51.string().nullable().optional(),altText:z51.string().optional(),caption:z51.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z51.string().min(1).optional(),model:z51.string().min(1).optional()}).superRefine((value,context)=>{!!value.task==!!value.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model",path:["task"]})}),GenerateRequestDTO=createDTO(GenerateRequestDTOSchema),GenerateResponseDataSchema=z51.object({jobId:z51.string(),status:z51.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z51.string().nullable().optional(),credits:z51.number().optional(),costUsd:z51.number().optional(),billingMode:z51.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z51.object({error:z51.string(),code:z51.enum(["unknown-task","unknown-model","options-invalid","source-invalid","task-routing-failed","generation-failed","provider-error","cost-limit-exceeded","cost-estimate-unavailable","unsupported-modality"]),availableTasks:z51.array(GenerationTaskIdSchema).optional(),availableModels:z51.array(z51.string()).optional(),issues:z51.array(z51.unknown()).optional()})}});import{z as z52}from"zod";var FlagTypeSchema,FlagSpecSchema,AssetModelPriceSchema,AssetModelDTOSchema,AssetModelDTO,AssetModelEstimateDTOSchema,AssetModelEstimateDTO,init_asset_model_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset-model.dto.js"(){"use strict";init_create_dto();FlagTypeSchema=z52.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z52.object({name:z52.string(),key:z52.string(),description:z52.string(),type:FlagTypeSchema,required:z52.boolean(),defaultValue:z52.unknown().optional(),enumValues:z52.array(z52.string()).optional(),isArray:z52.boolean()}),AssetModelPriceSchema=z52.object({unitPrice:z52.number(),unit:z52.string(),confidence:z52.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z52.object({id:z52.string(),shortName:z52.string(),provider:z52.string(),source:z52.string(),modality:z52.enum(["image","video","audio"]),tags:z52.array(z52.string()),displayName:z52.string(),description:z52.string(),flags:z52.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z52.object({model:z52.string(),costUsd:z52.number(),credits:z52.number(),billingMode:z52.enum(["fimo-credits","provider-account"]),confidence:z52.enum(["exact","estimated","metered"]),basis:z52.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z53}from"zod";var UserTourDTOSchema,UserTourDTO,UserTourResponseSchema,UserTourListResponseSchema,init_tour_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/tour.dto.js"(){"use strict";init_create_dto();init_response();UserTourDTOSchema=z53.object({tourId:z53.string(),version:z53.string(),status:z53.string(),completedAt:z53.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z53.array(UserTourDTOSchema))}});import{z as z54}from"zod";var SUPPORT_REPORT_CATEGORIES,SupportReportCategorySchema,SUPPORT_REPORT_STATUSES,SupportReportStatusSchema,SupportReportSourceSchema,SupportReportDeliveryStatusSchema,SUPPORT_REPORT_LINK_KINDS,SupportReportLinkKindSchema,SupportReportEventKindSchema,SupportReportActorKindSchema,SupportReportTagSchema,SupportReportHttpUrlSchema,SupportReportContextInputSchema,CreateSupportReportInputSchema,SupportReportListQuerySchema,UpdateSupportReportInputSchema,CreateSupportReportMessageInputSchema,CreateSupportReportLinkInputSchema,SupportReportActorDTOSchema,SupportReportLinkDTOSchema,SupportReportLinkDTO,SupportReportEventDTOSchema,SupportReportEventDTO,SupportReportSummaryDTOSchema,SupportReportSummaryDTO,SupportReportDetailDTOSchema,SupportReportDetailDTO,SupportReportListDTOSchema,SupportReportListDTO,CreateSupportReportResultDTOSchema,CreateSupportReportResultDTO,init_support_report_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/support-report.dto.js"(){"use strict";init_create_dto();SUPPORT_REPORT_CATEGORIES=[{value:"account_billing",label:"Account & billing"},{value:"project_issues",label:"Project issues"},{value:"ai_prompt_output_quality",label:"AI prompt & output quality"},{value:"roles_access_collaboration",label:"Roles, access & collaboration"},{value:"code_technical_questions",label:"Code & technical questions"},{value:"others",label:"Other"}],SupportReportCategorySchema=z54.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z54.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z54.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z54.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z54.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z54.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z54.enum(["user","agent","system"]),SupportReportTagSchema=z54.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z54.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z54.object({organization:z54.object({id:z54.string().trim().min(1).max(255),name:z54.string().trim().max(240).optional()}),project:z54.object({id:z54.uuid(),name:z54.string().trim().max(240).optional(),createdAt:z54.coerce.date().optional()}).optional(),environment:z54.string().trim().max(255).optional(),clientVersion:z54.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z54.object({message:z54.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z54.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z54.string().trim().max(200).optional(),limit:z54.coerce.number().int().min(1).max(100).default(50),offset:z54.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z54.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z54.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z54.uuid().nullable().optional(),note:z54.string().trim().min(1).max(2e4).optional()}).refine(input=>Object.values(input).some(value=>value!==void 0),{message:"At least one report change is required"}),CreateSupportReportMessageInputSchema=z54.object({message:z54.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z54.object({kind:SupportReportLinkKindSchema,label:z54.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z54.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z54.object({kind:SupportReportActorKindSchema,id:z54.string().nullable(),name:z54.string().nullable()}),SupportReportLinkDTOSchema=z54.object({id:z54.uuid(),kind:SupportReportLinkKindSchema,label:z54.string(),url:SupportReportHttpUrlSchema,externalId:z54.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z54.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z54.object({id:z54.uuid(),kind:SupportReportEventKindSchema,body:z54.string().nullable(),metadata:z54.record(z54.string(),z54.unknown()),actor:SupportReportActorDTOSchema,createdAt:z54.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z54.object({id:z54.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z54.array(z54.string()),source:SupportReportSourceSchema,message:z54.string(),reporter:z54.object({id:z54.string().nullable(),name:z54.string().nullable(),email:z54.string().nullable()}),organization:z54.object({id:z54.string().nullable(),name:z54.string()}),project:z54.object({id:z54.uuid().nullable(),name:z54.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z54.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z54.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z54.string().nullable(),deliveredAt:z54.coerce.date().nullable()}).nullable(),duplicateOfReportId:z54.uuid().nullable(),resolvedAt:z54.coerce.date().nullable(),createdAt:z54.coerce.date(),updatedAt:z54.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z54.string().nullable(),clientVersion:z54.string().nullable(),links:z54.array(SupportReportLinkDTOSchema),events:z54.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z54.object({reports:z54.array(SupportReportSummaryDTOSchema),total:z54.number().int().nonnegative(),statusCounts:z54.object({new:z54.number().int().nonnegative(),in_progress:z54.number().int().nonnegative(),waiting:z54.number().int().nonnegative(),resolved:z54.number().int().nonnegative(),duplicate:z54.number().int().nonnegative(),irrelevant:z54.number().int().nonnegative(),ignored:z54.number().int().nonnegative()}),limit:z54.number().int().positive(),offset:z54.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z54.object({id:z54.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z54.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z55}from"zod";var OPS_RECENT_CHAT_MAX_WINDOW_MS,OpsChatTimestampInputSchema,OpsRecentChatInputSchema,OpsRecentChatMessageSchema,OpsRecentChatResponseSchema,OpsRecentChatResponseDTO,init_ops_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-chat.dto.js"(){"use strict";init_ops();init_create_dto();OPS_RECENT_CHAT_MAX_WINDOW_MS=10080*60*1e3,OpsChatTimestampInputSchema=z55.iso.datetime({offset:!0}).pipe(z55.coerce.date()),OpsRecentChatInputSchema=z55.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z55.string().trim().min(1).max(255).optional(),limit:z55.coerce.number().int().min(1).max(200).default(100),cursor:z55.string().trim().min(1).max(2e3).optional(),slim:z55.boolean().default(!0),reason:z55.string().trim().min(1).max(1e3)}).refine(input=>input.from<=(input.to??new Date),{message:"from must be before or equal to to",path:["from"]}).refine(input=>(input.to??new Date).getTime()-input.from.getTime()<=OPS_RECENT_CHAT_MAX_WINDOW_MS,{message:"recent chat window cannot exceed 7 days",path:["from"]}).refine(input=>!input.cursor||!!input.to,{message:"to is required when continuing with a cursor",path:["to"]}),OpsRecentChatMessageSchema=z55.object({id:z55.string(),messageId:z55.string(),env:z55.string(),versionId:z55.string().nullable(),userId:z55.string().nullable(),role:z55.string(),parts:z55.array(z55.record(z55.string(),z55.unknown())),metadata:z55.object({status:z55.string().optional(),traceUrl:z55.string().optional(),externalFileChanges:z55.array(z55.unknown()).optional()}),stats:z55.object({toolCount:z55.number().int().nonnegative(),failedToolCount:z55.number().int().nonnegative()}),createdAt:z55.iso.datetime({offset:!0}),project:z55.object({id:z55.string(),name:z55.string(),displayName:z55.string().nullable(),organizationId:z55.string().nullable()})}),OpsRecentChatResponseSchema=z55.object({target:z55.object({backendProfile:OpsBackendProfileSchema,projectEnv:z55.string().nullable()}),window:z55.object({from:z55.iso.datetime({offset:!0}),to:z55.iso.datetime({offset:!0})}),messages:z55.object({items:z55.array(OpsRecentChatMessageSchema),nextCursor:z55.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z56}from"zod";function createAgentRunWebhookEventDataSchema(status){return z56.object({run:z56.object({id:z56.string(),agentName:z56.string(),trigger:z56.string(),status:z56.literal(status),startedAt:z56.string().nullable(),finishedAt:z56.string().nullable(),reason:z56.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEntryBatchWindowSecondsSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AgentReviewRequestedWebhookEventDataSchema,AgentReviewResolvedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,MediaGeneratedWebhookEventDataSchema,MediaProcessingFailedWebhookEventDataSchema,WEBHOOK_EVENT_DATA_SCHEMAS,WebhookEventFamilySchema,WebhookDestinationKindSchema,WebhookHeaderValueInputSchema,WebhookHeaderInputSchema,WebhookHeaderDTOSchema,WebhookFilterSchema,JsonValueSchema,CreateProjectWebhookRequestSchema,UpdateProjectWebhookRequestSchema,TestProjectWebhookRequestSchema,WebhookDeliveryStatusSchema,ProjectWebhookDTOSchema,ProjectWebhookDTO,WebhookDeliveryDTOSchema,WebhookDeliveryDTO,WebhookDeliveriesPageSchema,WebhookDeliveryAttemptDTOSchema,WebhookDeliveryAttemptDTO,ProjectWebhookResponseSchema,ProjectWebhooksListResponseSchema,WebhookDeliveriesListResponseSchema,WebhookDeliveryAttemptsListResponseSchema,init_webhook_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/webhook.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();WEBHOOK_EVENT_TYPES=["entry.changed","form.submitted","publish.started","publish.succeeded","publish.failed","publish.unpublished","agent.run.started","agent.run.completed","agent.run.failed","agent.run.cancelled","agent.review.requested","agent.review.resolved","analytics.report_ready","media.uploaded","media.updated","media.deleted","media.generated","media.processing_failed"],WebhookEventTypeSchema=z56.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z56.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z56.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z56.enum(["main","all"]),WebhookEntryBatchWindowSecondsSchema=z56.union([z56.literal(0),z56.literal(5),z56.literal(30),z56.literal(60)]),EntryChangedWebhookEventDataSchema=z56.object({reason:WebhookEntryChangeReasonSchema,operationId:z56.string().optional(),batch:z56.object({index:z56.number().int().positive(),total:z56.number().int().positive()}).optional(),changes:z56.array(z56.object({action:WebhookEntryChangeActionSchema,contentType:z56.string(),id:z56.string(),documentId:z56.string(),locale:z56.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z56.object({form:z56.object({id:z56.string(),label:z56.string()}),submission:z56.object({id:z56.string(),data:z56.record(z56.string(),z56.unknown()),submittedAt:z56.string()})}),PublishStartedWebhookEventDataSchema=z56.object({publication:z56.object({status:z56.literal("publishing"),startedAt:z56.string()})}),PublishSucceededWebhookEventDataSchema=z56.object({publication:z56.object({status:z56.literal("published"),url:z56.string(),publishedAt:z56.string(),firstPublish:z56.boolean()})}),PublishFailedWebhookEventDataSchema=z56.object({publication:z56.object({status:z56.literal("failed"),reason:z56.string()})}),PublishUnpublishedWebhookEventDataSchema=z56.object({publication:z56.object({previousUrl:z56.string(),unpublishedAt:z56.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z56.object({review:z56.object({id:z56.string(),runId:z56.string(),agentName:z56.string(),classification:z56.string(),summary:z56.string(),reasons:z56.array(z56.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z56.object({review:z56.object({id:z56.string(),runId:z56.string(),agentName:z56.string(),resolution:z56.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z56.object({report:z56.object({weekStart:z56.string(),weekEnd:z56.string(),pageviews:z56.number(),visitors:z56.number(),previousPageviews:z56.number(),previousVisitors:z56.number()})}),MediaAssetWebhookEventDataSchema=z56.object({id:z56.string().nullable(),name:z56.string().nullable(),type:z56.string(),mimeType:z56.string().nullable(),fileSize:z56.number().nullable()}),MediaUploadedWebhookEventDataSchema=z56.object({asset:MediaAssetWebhookEventDataSchema,operation:z56.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z56.object({asset:MediaAssetWebhookEventDataSchema,operation:z56.enum(["updated","moved","analysis"]),analysis:z56.object({category:z56.string(),status:z56.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z56.object({asset:MediaAssetWebhookEventDataSchema,operation:z56.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z56.object({asset:MediaAssetWebhookEventDataSchema,operation:z56.literal("generated"),generation:z56.object({model:z56.string(),mode:z56.string()})}),MediaProcessingFailedWebhookEventDataSchema=z56.object({asset:MediaAssetWebhookEventDataSchema,operation:z56.enum(["analysis","generation"]),failure:z56.object({code:z56.string()})}),WEBHOOK_EVENT_DATA_SCHEMAS={"entry.changed":EntryChangedWebhookEventDataSchema,"form.submitted":FormSubmittedWebhookEventDataSchema,"publish.started":PublishStartedWebhookEventDataSchema,"publish.succeeded":PublishSucceededWebhookEventDataSchema,"publish.failed":PublishFailedWebhookEventDataSchema,"publish.unpublished":PublishUnpublishedWebhookEventDataSchema,"agent.run.started":createAgentRunWebhookEventDataSchema("running"),"agent.run.completed":createAgentRunWebhookEventDataSchema("completed"),"agent.run.failed":createAgentRunWebhookEventDataSchema("failed"),"agent.run.cancelled":createAgentRunWebhookEventDataSchema("cancelled"),"agent.review.requested":AgentReviewRequestedWebhookEventDataSchema,"agent.review.resolved":AgentReviewResolvedWebhookEventDataSchema,"analytics.report_ready":AnalyticsReportReadyWebhookEventDataSchema,"media.uploaded":MediaUploadedWebhookEventDataSchema,"media.updated":MediaUpdatedWebhookEventDataSchema,"media.deleted":MediaDeletedWebhookEventDataSchema,"media.generated":MediaGeneratedWebhookEventDataSchema,"media.processing_failed":MediaProcessingFailedWebhookEventDataSchema},WebhookEventFamilySchema=z56.enum(["entries","forms","publish","agents","analytics","media"]),WebhookDestinationKindSchema=z56.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z56.discriminatedUnion("source",[z56.object({source:z56.literal("literal"),value:z56.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z56.object({source:z56.literal("secret"),key:z56.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z56.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z56.object({name:z56.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z56.object({name:z56.string(),source:z56.enum(["literal","secret"]),secretKey:z56.string().nullable(),secretPrefix:z56.string().nullable(),configured:z56.literal(!0)}),WebhookFilterSchema=z56.object({environment:WebhookEnvironmentScopeSchema.optional(),formId:z56.string().min(1).max(255).optional(),agentName:z56.string().min(1).max(120).optional(),mediaType:z56.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z56.string().min(1).max(255).optional(),locale:z56.string().min(1).max(120).optional()}),JsonValueSchema=z56.lazy(()=>z56.union([z56.string(),z56.number(),z56.boolean(),z56.null(),z56.array(JsonValueSchema),z56.record(z56.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z56.object({name:z56.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z56.url(),enabled:z56.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z56.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z56.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z56.object({name:z56.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z56.url().optional(),enabled:z56.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z56.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z56.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z56.object({eventType:WebhookEventTypeSchema.optional(),data:z56.record(z56.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z56.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z56.uuid(),name:z56.string(),eventType:WebhookEventTypeSchema,enabled:z56.boolean(),destination:z56.object({host:z56.string(),maskedUrl:z56.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z56.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z56.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z56.coerce.date().nullable(),deliveryStats24h:z56.object({succeeded:z56.number().int().nonnegative(),failed:z56.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z56.uuid(),projectId:z56.uuid(),env:EnvSchema,eventId:z56.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z56.number().int().positive(),test:z56.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z56.number().int().nonnegative(),responseStatus:z56.number().int().nullable(),lastErrorCode:z56.string().nullable(),lastErrorMessage:z56.string().nullable(),payloadAvailable:z56.boolean(),destination:z56.object({host:z56.string(),maskedUrl:z56.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z56.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z56.string().nullable(),qstashMessageId:z56.string().nullable(),deliveredAt:z56.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z56.object({items:z56.array(WebhookDeliveryDTOSchema),pagination:z56.object({page:z56.number().int().positive(),limit:z56.number().int().positive(),total:z56.number().int().nonnegative(),totalPages:z56.number().int().positive(),hasMore:z56.boolean()}),stats:z56.object({total:z56.number().int().nonnegative(),succeeded:z56.number().int().nonnegative(),failed:z56.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z56.object({id:z56.uuid(),deliveryId:z56.uuid(),attempt:z56.number().int().positive(),status:z56.enum(["delivering","succeeded","failed"]),responseStatus:z56.number().int().nullable(),durationMs:z56.number().int().nonnegative(),responseExcerpt:z56.string().nullable(),errorCode:z56.string().nullable(),errorMessage:z56.string().nullable(),createdAt:z56.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z56.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z56.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z57}from"zod";var SubscriptionStatusSchema,CreditBalanceBreakdownDTOSchema,CreditBalanceBreakdownDTO,SubscriptionPlanDTOSchema,SubscriptionPlanDTO,SubscriptionPaymentMethodDTOSchema,SubscriptionPaymentMethodDTO,SubscriptionPricingDTOSchema,SubscriptionPricingDTO,SubscriptionDetailsDTOSchema,SubscriptionDetailsDTO,CreditAlertDTOSchema,CreditAlertDTO,PlanAllocationDTOSchema,PlanAllocationDTO,LatestCancellationDTOSchema,LatestCancellationDTO,OrganizationSubscriptionDTOSchema,OrganizationSubscriptionDTO,BaseCreditTopupRequestSchema,FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema,CreditTopupRequestDTOSchema,CreditTopupRequestDTO,CreditTopupResponseDTOSchema,CreditTopupResponseDTO,init_subscription_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/subscription.dto.js"(){"use strict";init_common();init_create_dto();init_billing_dto();SubscriptionStatusSchema=z57.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z57.object({total:z57.number(),base:z57.number(),purchases:z57.number(),awards:z57.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z57.object({id:z57.string(),name:z57.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z57.object({type:z57.string(),brand:z57.string().nullable(),last4:z57.string().nullable(),expirationDate:z57.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z57.object({currency:z57.string(),nextPaymentAmount:z57.number().nullable(),nextPaymentAt:z57.string().nullable(),billingInterval:z57.string().nullable(),totalAmount:z57.number().nullable(),discountAmount:z57.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z57.object({id:z57.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z57.string().nullable(),currentPeriodEndsAt:z57.string().nullable(),renewsAt:z57.string().nullable(),cancelAt:z57.string().nullable(),renewAutomatically:z57.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z57.object({type:z57.enum(["low_balance","critical_balance","approaching_limit"]),message:z57.string(),estimatedPromptsRemaining:z57.number().nullable(),avgCostPerPrompt:z57.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z57.object({monthlyCredits:z57.number().nullable(),usedThisPeriod:z57.number(),remainingThisPeriod:z57.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z57.object({organizationId:z57.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z57.string().nullable(),tenureDays:z57.number().int().nonnegative(),capturedAt:z57.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z57.object({hasSubscription:z57.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z57.number().nullable(),alerts:z57.array(CreditAlertDTOSchema),portalUrl:z57.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z57.object({creditCount:z57.number().int().positive(),expiresAt:z57.string().datetime().nullable().optional(),message:z57.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z57.literal("free"),amountCents:z57.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z57.literal("purchase"),amountCents:z57.number().int().positive()}),CreditTopupRequestDTOSchema=z57.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z57.object({success:z57.boolean(),transactionId:z57.string().nullable(),newBalance:z57.number(),creditCount:z57.number(),type:z57.enum(["free","purchase"]),invoiceId:z57.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z58}from"zod";var UsageSummaryDTOSchema,UsageSummaryDTO,UsageByProjectDTOSchema,UsageByProjectDTO,UsageByUserDTOSchema,UsageByUserDTO,UsageTimelineItemDTOSchema,UsageTimelineItemDTO,UsageByUserForProjectDTOSchema,UsageByUserForProjectDTO,ProjectUsageDetailDTOSchema,ProjectUsageDetailDTO,OrganizationUsageDTOSchema,OrganizationUsageDTO,init_usage_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage.dto.js"(){"use strict";init_create_dto();UsageSummaryDTOSchema=z58.object({totalCredits:z58.number(),totalCostUsd:z58.number(),totalMessages:z58.number(),avgCostPerMessage:z58.number(),periodStart:z58.string().nullable(),periodEnd:z58.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z58.object({projectId:z58.string(),projectName:z58.string(),projectDisplayName:z58.string().nullable(),credits:z58.number(),costUsd:z58.number(),messages:z58.number(),percentage:z58.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z58.object({userId:z58.string(),userName:z58.string().nullable(),userEmail:z58.string().email().nullable(),credits:z58.number(),costUsd:z58.number(),messages:z58.number(),percentage:z58.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z58.object({date:z58.string(),credits:z58.number(),costUsd:z58.number(),messages:z58.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z58.object({userId:z58.string(),userName:z58.string().nullable(),userEmail:z58.string().email().nullable(),credits:z58.number(),costUsd:z58.number(),messages:z58.number(),percentage:z58.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z58.object({projectId:z58.string(),projectName:z58.string(),projectDisplayName:z58.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z58.array(UsageByUserForProjectDTOSchema),timeline:z58.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z58.object({summary:UsageSummaryDTOSchema,byProject:z58.array(UsageByProjectDTOSchema),byUser:z58.array(UsageByUserDTOSchema),timeline:z58.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z59}from"zod";var TimeRangePresetSchema,SortOrderSchema,UsageAnalyticsQuerySchema,UsageOverviewSummaryDTOSchema,UsageOverviewSummaryDTO,UsageTimelinePointDTOSchema,UsageTimelinePointDTO,OrganizationUsageRowDTOSchema,OrganizationUsageRowDTO,UserUsageRowDTOSchema,UserUsageRowDTO,ProjectUsageRowDTOSchema,ProjectUsageRowDTO,UsageDistributionItemDTOSchema,UsageDistributionItemDTO,UsageHeatmapPointDTOSchema,UsageHeatmapPointDTO,UsageOverviewResponseDTOSchema,UsageOverviewResponseDTO,UsagePaginationDTOSchema,UsagePaginationDTO,UsageByOrganizationResponseDTOSchema,UsageByOrganizationResponseDTO,ExtendedUserUsageRowDTOSchema,ExtendedUserUsageRowDTO,UsageByUserResponseDTOSchema,UsageByUserResponseDTO,ExtendedProjectUsageRowDTOSchema,ExtendedProjectUsageRowDTO,UsageByProjectResponseDTOSchema,UsageByProjectResponseDTO,ExportFormatSchema,UsageExportQuerySchema,PeekUsageMetricsDTOSchema,PeekUsageMetricsDTO,OrganizationPeekDTOSchema,OrganizationPeekDTO,UserPeekDTOSchema,UserPeekDTO,ProjectPeekDTOSchema,ProjectPeekDTO,init_usage_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage-analytics.dto.js"(){"use strict";init_create_dto();TimeRangePresetSchema=z59.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z59.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z59.object({startDate:z59.string().optional(),endDate:z59.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z59.coerce.number().int().positive().default(1),limit:z59.coerce.number().int().positive().max(100).default(20),sortBy:z59.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z59.string().optional()}),UsageOverviewSummaryDTOSchema=z59.object({totalCredits:z59.number(),totalCostUsd:z59.number(),totalMessages:z59.number(),avgCostPerMessage:z59.number(),avgCreditsPerMessage:z59.number(),periodStart:z59.string(),periodEnd:z59.string(),creditsChange:z59.number().nullable(),costChange:z59.number().nullable(),messagesChange:z59.number().nullable()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z59.object({date:z59.string(),credits:z59.number(),costUsd:z59.number(),messages:z59.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z59.object({organizationId:z59.string(),organizationName:z59.string(),credits:z59.number(),costUsd:z59.number(),messages:z59.number(),percentage:z59.number(),userCount:z59.number(),projectCount:z59.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z59.object({userId:z59.string(),userName:z59.string().nullable(),userEmail:z59.string().nullable(),userImage:z59.string().nullable(),organizationId:z59.string().nullable(),organizationName:z59.string().nullable(),credits:z59.number(),costUsd:z59.number(),messages:z59.number(),percentage:z59.number(),projectCount:z59.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z59.object({projectId:z59.string(),projectName:z59.string(),projectDisplayName:z59.string().nullable(),organizationId:z59.string(),organizationName:z59.string(),credits:z59.number(),costUsd:z59.number(),messages:z59.number(),percentage:z59.number(),userCount:z59.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z59.object({id:z59.string(),name:z59.string(),value:z59.number(),percentage:z59.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z59.object({day:z59.number(),hour:z59.number(),value:z59.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z59.object({summary:UsageOverviewSummaryDTOSchema,timeline:z59.array(UsageTimelinePointDTOSchema),topOrganizations:z59.array(OrganizationUsageRowDTOSchema),topUsers:z59.array(UserUsageRowDTOSchema),topProjects:z59.array(ProjectUsageRowDTOSchema),creditDistribution:z59.array(UsageDistributionItemDTOSchema),heatmap:z59.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z59.object({page:z59.number(),limit:z59.number(),totalItems:z59.number(),totalPages:z59.number(),hasMore:z59.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z59.object({organizations:z59.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z59.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z59.object({users:z59.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z59.string(),ownerName:z59.string().nullable(),ownerEmail:z59.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z59.object({projects:z59.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z59.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z59.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z59.object({credits:z59.number(),costUsd:z59.number(),messages:z59.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z59.object({id:z59.string(),name:z59.string(),createdAt:z59.string(),memberCount:z59.number(),projectCount:z59.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z59.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z59.object({id:z59.string(),name:z59.string().nullable(),email:z59.string(),image:z59.string().nullable(),createdAt:z59.string(),organizationCount:z59.number(),projectCount:z59.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z59.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z59.object({id:z59.string(),name:z59.string(),displayName:z59.string().nullable(),createdAt:z59.string(),organizationId:z59.string(),organizationName:z59.string(),ownerId:z59.string(),ownerName:z59.string().nullable(),ownerEmail:z59.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z59.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z60}from"zod";var SandboxProcessStatusSchema,PresetSandboxCommandSchema,ExecuteSandboxCommandRequestDTOSchema,ExecuteSandboxCommandRequestDTO,SandboxProcessInfoDTOSchema,SandboxProcessInfoDTO,SandboxProcessInfoResponseSchema,SandboxProcessListDTOSchema,SandboxProcessListDTO,SandboxProcessListResponseSchema,ExecuteSandboxCommandResponseDTOSchema,ExecuteSandboxCommandResponseDTO,PresetCommandResponseDTOSchema,PresetCommandResponseDTO,PresetCommandResponseSchema,init_sandbox_command_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/sandbox-command.dto.js"(){"use strict";init_env();init_create_dto();init_response();SandboxProcessStatusSchema=z60.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z60.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z60.object({command:z60.string().min(1).max(1e4),cwd:z60.string().optional(),projectEnv:EnvSchema.optional(),env:z60.record(z60.string(),z60.string()).optional(),name:z60.string().optional(),waitForCompletion:z60.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z60.object({identifier:z60.string(),status:SandboxProcessStatusSchema,command:z60.string().optional(),startedAt:z60.string().optional(),exitCode:z60.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z60.object({processes:z60.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z60.object({processId:z60.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z60.object({success:z60.boolean(),message:z60.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z61}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common();init_attachments();init_env();init_realtime();init_references();init_content_fields();init_audit_log();init_ops();init_project_dto();init_project_env_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_activation_dto();init_agent_list_item_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_audit_log_dto();init_env_status_dto();init_env_diff_summary_dto();init_project_analytics_dto();init_project_access_dto();init_project_invite_dto();init_publication_dto();init_sandbox_dto();init_organization_dto();init_billing_dto();init_payment_method_dto();init_user_dto();init_content_dto();init_cms_display_defaults_dto();init_asset_dto();init_translation_dto();init_document_dto();init_chat_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_webhook_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto()}});import{execFile as execFile2}from"node:child_process";import{promisify as promisify2}from"node:util";async function runGit(args,cwd){let{stdout}=await execFileAsync2("git",args,{cwd});return stdout.trim()}async function isGitRepo(cwd){try{return await runGit(["rev-parse","--is-inside-work-tree"],cwd),!0}catch{return!1}}async function hasUncommittedChanges(cwd){return(await runGit(["status","--porcelain"],cwd)).length>0}async function cloneRepo(args){await execFileAsync2("git",["clone","--branch",args.branch,"--single-branch",args.url,args.targetDir])}function isMissingRemoteBranch(error){let stderr=extractStderr(error).toLowerCase();return stderr.includes("remote branch")&&stderr.includes("not found")}async function remoteHasBranch(remoteUrl,branch){let{stdout}=await execFileAsync2("git",["ls-remote","--heads",remoteUrl,branch]);return stdout.trim().length>0}async function currentBranch(cwd){return runGit(["rev-parse","--abbrev-ref","HEAD"],cwd)}async function currentTagOrNull(cwd){try{return await runGit(["describe","--tags","--exact-match","HEAD"],cwd)||null}catch{return null}}function isReleaseTag(tag){return tag?/^release\/.+/.test(tag):!1}function classifyPushError(error){let stderr=extractStderr(error),lower=stderr.toLowerCase();return lower.includes("invalid or expired token")||lower.includes("expired token")||lower.includes("invalid token")||lower.includes("could not obtain git credentials")||lower.includes("not signed in")?{kind:"auth",stderr}:lower.includes("remote rejected")||lower.includes("protected")||lower.includes("no-push")||lower.includes("push declined")||lower.includes("not allowed to push")||lower.includes("permission to push")||lower.includes("forbidden")||lower.includes("403")?{kind:"protected",stderr}:lower.includes("non-fast-forward")||lower.includes("rejected")||lower.includes("fetch first")||lower.includes("updates were rejected")?{kind:"non-fast-forward",stderr}:lower.includes("authentication")||lower.includes("permission denied")?{kind:"auth",stderr}:lower.includes("could not resolve host")||lower.includes("timed out")||lower.includes("connection")?{kind:"network",stderr}:{kind:"unknown",stderr}}function extractStderr(error){if(error&&typeof error=="object"&&"stderr"in error){let value=error.stderr;if(typeof value=="string")return value;if(Buffer.isBuffer(value))return value.toString("utf8")}return error instanceof Error?error.message:String(error)}var execFileAsync2,init_git=__esm({"src/cli/utils/git.ts"(){execFileAsync2=promisify2(execFile2);__name(runGit,"runGit");__name(isGitRepo,"isGitRepo");__name(hasUncommittedChanges,"hasUncommittedChanges");__name(cloneRepo,"cloneRepo");__name(isMissingRemoteBranch,"isMissingRemoteBranch");__name(remoteHasBranch,"remoteHasBranch");__name(currentBranch,"currentBranch");__name(currentTagOrNull,"currentTagOrNull");__name(isReleaseTag,"isReleaseTag");__name(classifyPushError,"classifyPushError");__name(extractStderr,"extractStderr")}});function projectSettingsFromEnv(){let projectId=process.env.FIMO_PROJECT_ID?.trim();return projectId?{projectId,organizationId:process.env.FIMO_ORGANIZATION_ID?.trim()??"",name:process.env.FIMO_PROJECT_NAME?.trim()??projectId,apiUrl:process.env.FIMO_API_URL?.trim()??loadConfig().apiUrl}:null}async function resolveEnvFromGit(cwd){if(!await isGitRepo(cwd))return null;try{let tag=await currentTagOrNull(cwd);if(isReleaseTag(tag))return{env:"prod",source:"tag",readOnly:!0};let branch=await currentBranch(cwd);return!branch||branch==="HEAD"||!isValidEnv(branch)?null:{env:branch,source:"branch"}}catch{return null}}async function getProjectContext(opts={}){let cwd=resolveProjectCwd(opts.cwd),settings;try{settings=loadProjectSettings(cwd)}catch{let fromEnv=projectSettingsFromEnv();if(!fromEnv)throw new NotInProjectError;settings=fromEnv}let env,source,readOnly=!1;if(opts.envOverride!==void 0){if(!isValidEnv(opts.envOverride))throw new InvalidEnvOverrideError(opts.envOverride);env=opts.envOverride,source="flag"}else{let fromGit=await resolveEnvFromGit(cwd);if(fromGit)env=fromGit.env,source=fromGit.source,readOnly=fromGit.readOnly===!0;else{if(opts.requireBranch)throw await isGitRepo(cwd)?new GitBranchUndetectedError:new NotInProjectError;env=DEFAULT_ENV,source="fallback"}}if(opts.api&&env!=="prod")try{let names=(await opts.api.listEnvs(settings.projectId)).map(e=>e.env);if(!names.includes(env)&&source==="flag")throw new EnvNotFoundError(env,names)}catch(err){if(err instanceof EnvNotFoundError)throw err}return{projectId:settings.projectId,organizationId:settings.organizationId,name:settings.name,apiUrl:settings.apiUrl,env,source,readOnly:readOnly||void 0}}function envSourceBanner(ctx){let sourceHint=ctx.source==="flag"?"--env":ctx.source==="branch"?"git branch":ctx.source==="tag"?"git tag":"default",ro=ctx.readOnly?" \xB7 read-only":"";return`\u2192 env: ${ctx.env} (from ${sourceHint}${ro})`}function envOverrideFromCommand(cmd){let cur=cmd??void 0;for(;cur;){let env=cur.opts().env;if(typeof env=="string"&&env.length>0)return env;cur=cur.parent??null}}async function bootstrapProjectCommand(options={},cmd,bootstrapOpts={}){let envOverride2=envOverrideFromCommand(cmd),baseApi=new FimoApiClient(loadConfig()),ctx=await getProjectContext({cwd:options.cwd,envOverride:envOverride2,requireBranch:bootstrapOpts.requireBranch,api:baseApi});if(!bootstrapOpts.quiet){let{currentMode:currentMode2}=await Promise.resolve().then(()=>(init_dist(),dist_exports));currentMode2().format==="pretty"&&process.stderr.write(`${envSourceBanner(ctx)}
|
|
195
|
+
${agentsMdContent}`;writeIfMissing(".cursor/rules/fimo.mdc",cursorContent)}return selected.has("windsurf")&&writeIfMissing(".windsurfrules",agentsMdContent),selected.has("gemini-cli")&&writeIfMissing("GEMINI.md",agentsMdContent),result}function syncPerAgentVariants(targetDir,agents){let agentsMdPath=path9.join(targetDir,"AGENTS.md");if(!fs9.existsSync(agentsMdPath))throw new Error(`No AGENTS.md found in ${targetDir}. Run \`fimo create\` first, or create AGENTS.md manually before running \`fimo rules sync\`.`);let agentsMdContent=fs9.readFileSync(agentsMdPath,"utf8");return writePerAgentVariants(targetDir,agents,agentsMdContent)}function detectAgentsInProject(cwd){let detected=[];return fs9.existsSync(path9.join(cwd,"CLAUDE.md"))&&detected.push("claude-code"),fs9.existsSync(path9.join(cwd,".cursor","rules","fimo.mdc"))&&detected.push("cursor"),fs9.existsSync(path9.join(cwd,".windsurfrules"))&&detected.push("windsurf"),fs9.existsSync(path9.join(cwd,"GEMINI.md"))&&detected.push("gemini-cli"),detected}var TEMPLATE_ROOT,AGENT_TEMPLATES_ROOT,EXCLUDED_DIRS,init_scaffold=__esm({"src/cli/utils/scaffold.ts"(){init_templates();init_config();init_templates();TEMPLATE_ROOT=getTemplatePath("react-router"),AGENT_TEMPLATES_ROOT=path9.resolve(CLI_ROOT,"assets","agent-templates"),EXCLUDED_DIRS=new Set(["node_modules","dist","build",".turbo",".git"]);__name(resolveTemplateRoot,"resolveTemplateRoot");__name(resolveAgentTemplatesRoot,"resolveAgentTemplatesRoot");__name(resolveAgentTemplate,"resolveAgentTemplate");__name(listAgentTemplates,"listAgentTemplates");__name(copyAgentTemplate,"copyAgentTemplate");__name(copyTemplate,"copyTemplate");__name(pinFimoDependency,"pinFimoDependency");__name(copyTree,"copyTree");__name(writePerAgentVariants,"writePerAgentVariants");__name(syncPerAgentVariants,"syncPerAgentVariants");__name(detectAgentsInProject,"detectAgentsInProject")}});import{z as z5}from"zod";function filterUnknownProperties(data2,schema){if(data2==null)return data2;if(schema instanceof z5.ZodOptional||schema instanceof z5.ZodNullable||schema instanceof z5.ZodDefault)return filterUnknownProperties(data2,schema.unwrap());if(schema instanceof z5.ZodArray){if(!Array.isArray(data2))return data2;let itemSchema=schema.unwrap();return data2.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z5.ZodDiscriminatedUnion){if(typeof data2!="object"||data2===null)return data2;let unionSchema=schema,discriminator=unionSchema.def.discriminator,discriminatorValue=data2[discriminator],matchingSchema=unionSchema.options.find(option=>{let discriminatorField=option.shape[discriminator];return discriminatorField instanceof z5.ZodLiteral?discriminatorField.def.values.includes(discriminatorValue):!1});return matchingSchema?filterUnknownProperties(data2,matchingSchema):data2}if(schema instanceof z5.ZodObject){if(typeof data2!="object")return data2;let shape=schema.shape,result={};for(let key in shape)if(Object.prototype.hasOwnProperty.call(data2,key)){let fieldSchema=shape[key],fieldValue=data2[key];result[key]=filterUnknownProperties(fieldValue,fieldSchema)}if(schema.def.catchall instanceof z5.ZodUnknown)for(let[key,value]of Object.entries(data2))key in shape||(result[key]=value);return result}return data2}function createObjectDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)},partial(){let partialSchema=schema.partial();return createObjectDTO(partialSchema)},pick(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),picked=schema.pick(mask);return createObjectDTO(picked)},omit(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),omitted=schema.omit(mask);return createObjectDTO(omitted)}}}function createDiscriminatedUnionDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)}}}function createDTO(schema){if(schema instanceof z5.ZodObject)return createObjectDTO(schema);if(schema instanceof z5.ZodDiscriminatedUnion)return createDiscriminatedUnionDTO(schema);throw new Error(`Unsupported schema type: ${schema.constructor.name}. createDTO supports ZodObject and ZodDiscriminatedUnion.`)}var init_create_dto=__esm({"../../packages/api-contracts/dist/esm/utils/create-dto.js"(){"use strict";__name(filterUnknownProperties,"filterUnknownProperties");__name(createObjectDTO,"createObjectDTO");__name(createDiscriminatedUnionDTO,"createDiscriminatedUnionDTO");__name(createDTO,"createDTO")}});import{z as z6}from"zod";var createResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema=__name(dataSchema=>z6.object({data:dataSchema}),"createResponseSchema")}});import{z as z7}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z7.object({page:z7.coerce.number().int().positive().default(1),limit:z7.coerce.number().int().positive().max(100).default(20)})}});import{z as z8}from"zod";var CommonSchemas,BaseEntitySchema,ProjectRoleKeySchema,ProjectRoleKeyWithSystemSchema,ProjectPrincipalTypeSchema,ProjectVisibilitySchema,ProjectStatusSchema,ProjectInviteStatusSchema,PublicationStatusSchema,OrganizationRoleSchema,AssetTypeSchema,TemplateCodeSchema,FieldTypeSchema,RESERVED_CONTENT_FIELD_NAMES,CONTENT_TYPE_NAME_PATTERN,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION,CONTENT_FIELD_NAME_PATTERN,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION,init_common=__esm({"../../packages/api-contracts/dist/esm/types/common.js"(){"use strict";CommonSchemas={timestamp:z8.coerce.date(),positiveInt:z8.number().int().positive(),nonNegativeInt:z8.number().int().nonnegative()},BaseEntitySchema=z8.object({id:z8.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z8.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z8.enum(["full","edit","comment","view","agent"]),ProjectPrincipalTypeSchema=z8.enum(["user","org","orgRole","public","email"]),ProjectVisibilitySchema=z8.enum(["public","private"]),ProjectStatusSchema=z8.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z8.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z8.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z8.enum(["owner","admin","member"]),AssetTypeSchema=z8.enum(["file","folder"]),TemplateCodeSchema=z8.enum(["Free","Premium"]),FieldTypeSchema=z8.enum(["string","text","richtext","media","number","boolean","date","json","reference","blocks"]),RESERVED_CONTENT_FIELD_NAMES=["id","entryId","documentId","slug","locale","createdAt","updatedAt","__fimo"],CONTENT_TYPE_NAME_PATTERN=/^[A-Za-z]\w*$/,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter",CONTENT_FIELD_NAME_PATTERN=/^[A-Za-z_]\w*$/,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter or underscore"}});var ATTACHMENT_TYPES,ATTACHMENT_MIME_TYPES,ATTACHMENT_IMAGE_MIME_TYPES,ATTACHMENT_DOCUMENT_MIME_TYPES,ATTACHMENT_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image"},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image"},{mime:"image/webp",extensions:[".webp"],category:"image"},{mime:"image/avif",extensions:[".avif"],category:"image"},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:5242880},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:5242880},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:5242880}],ATTACHMENT_MIME_TYPES=ATTACHMENT_TYPES.map(t2=>t2.mime),ATTACHMENT_IMAGE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="image").map(t2=>t2.mime),ATTACHMENT_DOCUMENT_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="document").map(t2=>t2.mime),ATTACHMENT_ACCEPT_EXTENSIONS=ATTACHMENT_TYPES.flatMap(t2=>t2.extensions),ATTACHMENT_ACCEPT_STRING=[...ATTACHMENT_ACCEPT_EXTENSIONS,...ATTACHMENT_MIME_TYPES].join(","),ATTACHMENT_DROPZONE_ACCEPT=Object.fromEntries(ATTACHMENT_TYPES.map(t2=>[t2.mime,t2.extensions]))}});import{z as z9}from"zod";function isValidEnv(env){return typeof env!="string"||env.length===0||env.length>MAX_ENV_LENGTH||env.startsWith("-")||env.startsWith(".")||env.includes("//")||env.split("/").some(segment=>segment==="..")?!1:ENV_ID_REGEX.test(env)}function isProductionEnv(env){return env===PRODUCTION_ENV}var ENV_ID_REGEX,MAX_ENV_LENGTH,EnvSchema,DEFAULT_ENV,PRODUCTION_ENV,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";ENV_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_ENV_LENGTH=255;__name(isValidEnv,"isValidEnv");EnvSchema=z9.string().min(1,"env must not be empty").max(MAX_ENV_LENGTH,`env must be at most ${MAX_ENV_LENGTH} characters`).refine(isValidEnv,{error:"env must match /^[a-zA-Z0-9._/-]+$/ and must not start with `-`"}),DEFAULT_ENV="main",PRODUCTION_ENV="prod";__name(isProductionEnv,"isProductionEnv")}});var init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict"}});import{z as z10}from"zod";function referenceDocumentId(value){if(typeof value=="string")return value;if(value&&typeof value=="object"){let reference=value,hasId=Object.prototype.hasOwnProperty.call(reference,"id"),hasDocumentId=Object.prototype.hasOwnProperty.call(reference,"documentId"),id=reference.id,documentId=reference.documentId;if(hasId&&typeof id!="string"||hasDocumentId&&typeof documentId!="string"||typeof id=="string"&&typeof documentId=="string"&&id!==documentId)return null;if(typeof id=="string")return id;if(typeof documentId=="string")return documentId}return null}function toReferenceValue(value){let documentId=referenceDocumentId(value);return documentId?{documentId}:null}function referenceContentType(value){if(value&&typeof value=="object"&&"contentType"in value){let contentType=value.contentType;return typeof contentType=="string"&&contentType.length>0?contentType:null}return null}function toPolymorphicReferenceValue(value){let documentId=referenceDocumentId(value),contentType=referenceContentType(value);return documentId&&contentType?{contentType,documentId}:null}var referenceValuePreprocess,ReferenceValueSchema,ReferenceInputValueSchema,polymorphicReferenceValuePreprocess,PolymorphicReferenceValueSchema,PolymorphicReferenceInputValueSchema,init_references=__esm({"../../packages/api-contracts/dist/esm/types/references.js"(){"use strict";__name(referenceDocumentId,"referenceDocumentId");__name(toReferenceValue,"toReferenceValue");referenceValuePreprocess=__name(value=>{let reference=toReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"referenceValuePreprocess"),ReferenceValueSchema=z10.preprocess(referenceValuePreprocess,z10.object({documentId:z10.uuid()})),ReferenceInputValueSchema=z10.preprocess(referenceValuePreprocess,z10.union([z10.object({documentId:z10.uuid()}),z10.object({slug:z10.string().min(1)})]));__name(referenceContentType,"referenceContentType");__name(toPolymorphicReferenceValue,"toPolymorphicReferenceValue");polymorphicReferenceValuePreprocess=__name(value=>{let reference=toPolymorphicReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"polymorphicReferenceValuePreprocess"),PolymorphicReferenceValueSchema=z10.preprocess(polymorphicReferenceValuePreprocess,z10.object({contentType:z10.string().min(1),documentId:z10.uuid()})),PolymorphicReferenceInputValueSchema=z10.preprocess(polymorphicReferenceValuePreprocess,z10.union([z10.object({contentType:z10.string().min(1),documentId:z10.uuid()}),z10.object({contentType:z10.string().min(1),slug:z10.string().min(1)})]))}});import{z as z11}from"zod";function rejectLegacyLocaleSettings(field,ctx){"localized"in field&&ctx.addIssue({code:"custom",path:["localized"],message:'Field-level locale settings use "i18n".'})}function rejectFieldI18n(field,ctx){"i18n"in field&&ctx.addIssue({code:"custom",path:["i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}function refineConditions(field,ctx){if(field.showIf!==void 0&&field.showIfAny!==void 0&&ctx.addIssue({code:"custom",path:["showIfAny"],message:'A field declares "showIf" or "showIfAny", never both.'}),Array.isArray(field.showIf)){let fields=field.showIf.map(clause=>clause.field);new Set(fields).size!==fields.length&&ctx.addIssue({code:"custom",path:["showIf"],message:'"showIf" clauses must each name a different field. Use "in" for several values of one field.'})}}function rejectUnsupportedUnique(field,ctx,type){"unique"in field&&!uniqueFieldTypes.has(type)&&ctx.addIssue({code:"custom",path:["unique"],message:UNSUPPORTED_UNIQUE_MESSAGE})}function getConditionDefinition(field){if(field.showIfAny!==void 0)return{key:"showIfAny",clauses:field.showIfAny};if(field.showIf!==void 0)return{key:"showIf",clauses:Array.isArray(field.showIf)?field.showIf:[field.showIf]}}function getConditionValues(clause){return"equals"in clause?[clause.equals]:clause.in}function collectClauseProblems(fieldName,condition,clause,fields,path47){let conditionPath=[...path47,fieldName,condition.key],trigger=fields[clause.field];if(trigger===void 0)return[{path:conditionPath,message:`"${condition.key}" references unknown field "${clause.field}".`}];if(trigger.showIf!==void 0||trigger.showIfAny!==void 0)return[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is conditional too. Conditions are one level deep.`}];if(trigger.type!=="boolean"&&trigger.type!=="number"&&trigger.type!=="string")return[{path:conditionPath,message:`"${condition.key}" can only reference boolean, number, and string fields. "${clause.field}" is a ${trigger.type} field.`}];let triggerOptions=trigger.type==="string"?trigger.options:void 0;if(trigger.type==="string"&&triggerOptions===void 0)return[{path:conditionPath,message:`"${condition.key}" can only reference a string field that declares "options". Add options to "${clause.field}".`}];let values=getConditionValues(clause);if(values.some(value=>typeof value!==trigger.type))return[{path:conditionPath,message:`"${condition.key}" on "${clause.field}" expects a ${trigger.type} value.`}];if(triggerOptions!==void 0){let invalidValues=values.filter(value=>!triggerOptions.includes(value));if(invalidValues.length>0)return invalidValues.map(value=>({path:conditionPath,message:`"${value}" is not one of the options declared by "${clause.field}".`}))}return trigger.editable===!1?[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is not editable.`}]:[]}function collectConditionProblems(fields){let problems=[],walk=__name((currentFields,path47)=>{for(let[fieldName,field]of Object.entries(currentFields)){let condition=getConditionDefinition(field);if(condition!==void 0)for(let clause of condition.clauses)problems.push(...collectClauseProblems(fieldName,condition,clause,currentFields,path47));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path47,fieldName,variant.uid]);else walk(field.schema.fields,[...path47,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path47,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path47,fieldName];visit2({field,path:fieldPath,structuredDepth,insideStructuredContent});let nextDepth=structuredDepth+1;if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...fieldPath,variant.uid],nextDepth,!0);else walk(field.schema.fields,fieldPath,nextDepth,!0)}},"walk");walk(fields,[],0,!1)}var UNIQUE_FIELD_TYPES,utf8,MAX_STRUCTURED_CONTENT_DEPTH,MAX_BLOCK_VARIANTS,MAX_BLOCK_ITEMS,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES,showIfClauseSchema,commonFieldShape,FIELD_I18N_UNSUPPORTED_MESSAGE,uniqueFieldTypes,UNSUPPORTED_UNIQUE_MESSAGE,scalarFieldSchema,referenceFieldSchema,reservedStructuredContentNames,ContentFieldDefinitionSchema,blockFieldsSchema,blockVariantSchema,fixedBlocksSchema,blocksSchema,blocksFieldSchema,contentFieldDefinitionSchema,init_content_fields=__esm({"../../packages/api-contracts/dist/esm/types/content-fields.js"(){"use strict";init_common();UNIQUE_FIELD_TYPES=["string","text","number","boolean","date"],utf8=new TextEncoder,MAX_STRUCTURED_CONTENT_DEPTH=3,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],showIfClauseSchema=z11.union([z11.object({field:z11.string().min(1),equals:z11.union([z11.string(),z11.number(),z11.boolean()])}).strict(),z11.object({field:z11.string().min(1),in:z11.array(z11.union([z11.string(),z11.number(),z11.boolean()])).min(1)}).strict()]),commonFieldShape={label:z11.string().min(1).optional(),description:z11.string().optional(),editable:z11.boolean().optional(),required:z11.boolean().optional(),default:z11.unknown().optional(),showIf:z11.union([showIfClauseSchema,z11.array(showIfClauseSchema).min(1)]).optional(),showIfAny:z11.array(showIfClauseSchema).min(1).optional()},FIELD_I18N_UNSUPPORTED_MESSAGE='"i18n" is only supported on top-level scalar and reference fields.';__name(rejectLegacyLocaleSettings,"rejectLegacyLocaleSettings");__name(rejectFieldI18n,"rejectFieldI18n");__name(refineConditions,"refineConditions");uniqueFieldTypes=new Set(UNIQUE_FIELD_TYPES),UNSUPPORTED_UNIQUE_MESSAGE=`"unique" is only supported on ${UNIQUE_FIELD_TYPES.join(", ")} fields.`;__name(rejectUnsupportedUnique,"rejectUnsupportedUnique");scalarFieldSchema=z11.object({...commonFieldShape,type:z11.enum(["string","text","richtext","media","number","boolean","date","json"]),min:z11.number().optional(),max:z11.number().optional(),minLength:z11.number().int().nonnegative().optional(),maxLength:z11.number().int().nonnegative().optional(),regex:z11.string().optional(),multiple:z11.boolean().optional(),allowedMimeTypes:z11.array(z11.string()).optional(),options:z11.array(z11.string().min(1)).min(1).optional(),unique:z11.boolean().optional(),i18n:z11.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),rejectUnsupportedUnique(field,ctx,field.type);for(let key of["target","targets","many","repeatable","schema"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on ${field.type} fields.`});if(field.type!=="number")for(let key of["min","max"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on number fields.`});if(field.type!=="string"&&field.type!=="text")for(let key of["minLength","maxLength","regex"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on string and text fields.`});field.min!==void 0&&field.max!==void 0&&field.min>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to "min".'});let effectiveMinimumLength=Math.max(field.minLength??0,field.required?1:0);if(field.maxLength!==void 0&&effectiveMinimumLength>field.maxLength&&ctx.addIssue({code:"custom",path:["maxLength"],message:'"maxLength" must be greater than or equal to the minimum required length.'}),field.regex!==void 0)try{new RegExp(field.regex)}catch{ctx.addIssue({code:"custom",path:["regex"],message:'"regex" must be a valid regular expression.'})}if(field.type!=="media")for(let key of["multiple","allowedMimeTypes"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on media fields.`});if(field.type!=="string"&&"options"in field&&ctx.addIssue({code:"custom",path:["options"],message:'"options" is only supported on string fields.'}),field.options!==void 0){new Set(field.options).size!==field.options.length&&ctx.addIssue({code:"custom",path:["options"],message:"Options must be unique."});for(let key of["regex","minLength","maxLength"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported alongside "options".`});field.default!==void 0&&!field.options.includes(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:'"default" must be one of the declared options.'})}}),referenceFieldSchema=z11.object({...commonFieldShape,type:z11.literal("reference"),target:z11.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z11.array(z11.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z11.boolean().optional(),i18n:z11.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),!field.target&&!field.targets&&ctx.addIssue({code:"custom",path:["target"],message:'Reference fields must declare "target" or "targets".'}),field.target&&field.targets&&ctx.addIssue({code:"custom",path:["targets"],message:'A reference field declares "target" or "targets", never both.'}),field.targets&&new Set(field.targets).size!==field.targets.length&&ctx.addIssue({code:"custom",path:["targets"],message:"Reference targets must be unique."});for(let key of["repeatable","schema","min","max","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on reference fields.`})}),reservedStructuredContentNames=new Set(RESERVED_STRUCTURED_CONTENT_FIELD_NAMES),ContentFieldDefinitionSchema=z11.lazy(()=>contentFieldDefinitionSchema);__name(getConditionDefinition,"getConditionDefinition");__name(getConditionValues,"getConditionValues");__name(collectClauseProblems,"collectClauseProblems");__name(collectConditionProblems,"collectConditionProblems");blockFieldsSchema=z11.record(z11.string(),ContentFieldDefinitionSchema).superRefine((fields,ctx)=>{for(let fieldName of Object.keys(fields))CONTENT_FIELD_NAME_PATTERN.test(fieldName)||ctx.addIssue({code:"custom",path:[fieldName],message:`Field names must use ${CONTENT_FIELD_NAME_PATTERN_DESCRIPTION}.`}),reservedStructuredContentNames.has(fieldName)&&ctx.addIssue({code:"custom",path:[fieldName],message:`"${fieldName}" is reserved structured-content metadata.`}),"unique"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"unique"],message:'"unique" is only supported on top-level fields.'}),"i18n"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}),blockVariantSchema=z11.object({uid:z11.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z11.string().min(1),description:z11.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z11.object({fields:blockFieldsSchema}).strict(),blocksSchema=z11.object({oneOf:z11.array(blockVariantSchema).min(1).max(MAX_BLOCK_VARIANTS)}).strict().superRefine((schema,ctx)=>{let seen=new Set;for(let[index2,variant]of schema.oneOf.entries())seen.has(variant.uid)&&ctx.addIssue({code:"custom",path:["oneOf",index2,"uid"],message:"Variant UIDs must be unique."}),seen.add(variant.uid)}),blocksFieldSchema=z11.object({...commonFieldShape,type:z11.literal("blocks"),min:z11.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z11.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z11.union([fixedBlocksSchema,blocksSchema])}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),rejectFieldI18n(field,ctx),refineConditions(field,ctx);let effectiveMinimum=Math.max(field.min??0,field.required?1:0);field.max!==void 0&&effectiveMinimum>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to the minimum number of blocks.'});for(let key of["target","targets","many","repeatable","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on blocks fields.`})}),contentFieldDefinitionSchema=z11.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z12}from"zod";var AUDIT_ACTIONS,AuditActionSchema,AUDIT_OUTCOMES,AuditOutcomeSchema,AUDIT_ACTOR_KINDS,AuditActorKindSchema,init_audit_log=__esm({"../../packages/api-contracts/dist/esm/types/audit-log.js"(){"use strict";AUDIT_ACTIONS=["env_create","env_delete","env_sync","capability_check","shell_exec","git_push","git_tag","git_merge","fimo_deploy","merge_decision","session_start","session_end","cost_breach","trigger_fire","cutover_step","agent_delegate","ops_access_change","ops_service_token_change","ops_project_search","ops_project_inspect","ops_project_chat_read","ops_recent_chat_read","ops_project_snapshot","ops_support_thread_read","ops_support_report_read","ops_support_report_change","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send"],AuditActionSchema=z12.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z12.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z12.enum(AUDIT_ACTOR_KINDS)}});import{z as z13}from"zod";var OPS_BACKEND_PROFILES,OpsBackendProfileSchema,OPS_PERMISSIONS,OpsPermissionSchema,OPS_PERMISSION_PRESETS,OPS_SERVICE_PERMISSION_PRESETS,OpsAccessGrantInputSchema,OpsServiceTokenInputSchema,OpsCustomerProjectInputSchema,OPS_INVESTIGATION_STATUSES,OpsInvestigationStatusSchema,OpsInvestigationCreateInputSchema,OpsInvestigationUpdateInputSchema,OPS_KNOWN_ISSUE_STATUSES,OpsKnownIssueStatusSchema,OpsKnownIssueCreateInputSchema,OpsKnownIssueUpdateInputSchema,OPS_VALIDATION_OUTCOMES,OpsValidationOutcomeSchema,OpsValidationRunInputSchema,OpsNotificationPreviewInputSchema,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z13.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:sentry:read","ops:logs:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview","ops:notification:approve","ops:notification:send"],OpsPermissionSchema=z13.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:validations:read","ops:notification:preview"],engineer:["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:sentry:read","ops:logs:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview"],full:[...OPS_PERMISSIONS]},OPS_SERVICE_PERMISSION_PRESETS={support:OPS_PERMISSION_PRESETS.support,engineer:OPS_PERMISSION_PRESETS.engineer,full:OPS_PERMISSION_PRESETS.full.filter(permission=>permission!=="ops:notification:approve")},OpsAccessGrantInputSchema=z13.object({permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),enabled:z13.boolean().default(!0)}),OpsServiceTokenInputSchema=z13.object({name:z13.string().trim().min(1).max(120),permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),expiresAt:z13.coerce.date()}).refine(input=>!input.permissions.includes("ops:notification:approve"),{path:["permissions"],message:"Service credentials cannot approve customer notifications"}).refine(input=>input.expiresAt.getTime()>Date.now(),{path:["expiresAt"],message:"Service credential expiry must be in the future"}),OpsCustomerProjectInputSchema=z13.object({importanceReason:z13.string().trim().min(1).max(1e3),ownerUserId:z13.string().trim().min(1).nullable().optional(),framework:z13.string().trim().max(120).nullable().optional(),packageManager:z13.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z13.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z13.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z13.object({projectId:z13.uuid(),title:z13.string().trim().min(1).max(240),userReport:z13.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z13.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z13.string().trim().max(1e4).nullable().optional(),outcome:z13.string().trim().max(1e4).nullable().optional(),evidence:z13.array(z13.record(z13.string(),z13.unknown())).max(100).optional()}).refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_KNOWN_ISSUE_STATUSES=["open","monitoring","resolved"],OpsKnownIssueStatusSchema=z13.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z13.object({fingerprint:z13.string().trim().min(1).max(240),title:z13.string().trim().min(1).max(240),description:z13.string().trim().min(1).max(1e4),affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z13.array(z13.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z13.string().trim().min(1).max(64).nullable().optional(),workaround:z13.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100),detectionQueries:z13.array(z13.string().trim().min(1).max(2e3)).max(50),status:OpsKnownIssueStatusSchema}).partial().refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_VALIDATION_OUTCOMES=["passed","failed","inconclusive"],OpsValidationOutcomeSchema=z13.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z13.object({changeReference:z13.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z13.string().trim().min(1).max(1e4),evidence:z13.array(z13.record(z13.string(),z13.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z13.object({recipientEmail:z13.email().optional(),subject:z13.string().trim().min(1).max(200).default("An update from Fimo"),message:z13.string().trim().min(1).max(5e3),locale:z13.string().trim().min(2).max(20),reason:z13.string().trim().min(1).max(1e3),acknowledgePolicy:z13.literal(!0)})}});import{z as z14}from"zod";var ProjectDTOSchema,ProjectDTO,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,QuestionAnswerMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionListResponseSchema,ProjectVersionResponseSchema,VersionMutationResponseSchema,ProjectPublicationStateDTOSchema,ProjectPublicationStateDTO,PublicationMutationDTOSchema,PublicationMutationDTO,ProjectPublicationStateResponseSchema,PublicationMutationResponseSchema,ProjectResponseSchema,ProjectWithPlanResponseSchema,init_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project.dto.js"(){"use strict";init_common();init_create_dto();init_response();ProjectDTOSchema=BaseEntitySchema.extend({name:z14.string(),displayName:z14.string().nullable(),subdomain:z14.string().nullable().optional(),subdomainUpdatedAt:z14.date().nullable().optional(),organizationId:z14.string().nullable(),createdBy:z14.string().nullable(),visibility:ProjectVisibilitySchema,previewEnabled:z14.boolean().default(!0),status:ProjectStatusSchema,creationStatus:z14.string(),thumbnailUrl:z14.string().nullable(),publishedThumbnailUrl:z14.string().nullable(),category:z14.string().nullable(),appUrl:z14.string().nullable(),lastPublishedAt:z14.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z14.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z14.object({id:z14.uuid(),name:z14.string(),displayName:z14.string().nullable(),thumbnailUrl:z14.string().nullable(),visibility:ProjectVisibilitySchema,category:z14.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z14.object({id:z14.string(),name:z14.string(),avatar:z14.string().nullable(),color:z14.object({bg:z14.string(),text:z14.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z14.object({path:z14.string(),content:z14.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z14.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z14.object({id:z14.string(),messageId:z14.string(),versionId:z14.string().nullable(),role:ProjectChatMessageRole,parts:z14.array(z14.any()),createdAt:z14.coerce.date()}),MessageUserMetadataSchema=z14.object({id:z14.string(),name:z14.string().nullable().optional(),image:z14.string().nullable().optional()}).nullable().optional(),QuestionAnswerMetadataSchema=z14.object({shortTitle:z14.string().optional(),questions:z14.array(z14.object({header:z14.string(),question:z14.string(),answer:z14.string(),selectedLabels:z14.array(z14.string()),freeText:z14.string(),skipped:z14.boolean()}))}).optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z14.number(),metadata:z14.object({user:MessageUserMetadataSchema,changeManifest:z14.array(z14.any()).optional(),questionAnswer:QuestionAnswerMetadataSchema}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z14.object({id:z14.uuid(),versionId:z14.string(),projectId:z14.uuid(),commitHash:z14.string(),name:z14.string(),description:z14.string().nullable(),thumbnailUrl:z14.string().nullable(),createdAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectDocumentContentDTOSchema=z14.object({content:z14.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z14.array(ProjectDTOSchema)),ProjectVersionListResponseSchema=createResponseSchema(z14.array(ProjectVersionDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),VersionMutationResponseSchema=createResponseSchema(z14.object({success:z14.boolean(),message:z14.string().optional()})),ProjectPublicationStateDTOSchema=z14.object({isPublished:z14.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z14.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublicationMutationDTOSchema=z14.object({success:z14.boolean(),message:z14.string().optional(),publishedAt:CommonSchemas.timestamp.optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z15}from"zod";var ProjectEnvStatusSchema,ProjectEnvDTOSchema,ProjectEnvDTO,CreateProjectEnvRequestSchema,SyncProjectEnvRequestSchema,ProjectEnvResponseSchema,ProjectEnvsListResponseSchema,EnvSurfaceDiffSchema,EnvDiffResultSchema,EnvDiffResultDTO,init_project_env_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-env.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();ProjectEnvStatusSchema=z15.enum(["provisioning","active","deleted"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z15.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,previewUrl:z15.string().nullable(),parentEnv:EnvSchema.nullable(),createdBy:z15.string().nullable(),deletedAt:z15.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),CreateProjectEnvRequestSchema=z15.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z15.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z15.array(ProjectEnvDTOSchema)),EnvSurfaceDiffSchema=z15.object({surface:z15.enum(["code","schemas","content","translations","assets","forms","activations"]),status:z15.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z15.number().int().nonnegative(),conflictCount:z15.number().int().nonnegative()}),EnvDiffResultSchema=z15.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z15.coerce.date(),surfaces:z15.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z16}from"zod";var ExportProjectResponseDTOSchema,ExportProjectResponseDTO,ImportProjectResultDTOSchema,ImportProjectResultDTO,ImportPreviewCountsDTOSchema,ImportPreviewSurfaceDTOSchema,ImportPreviewDTOSchema,ImportPreviewDTO,ImportPreviewResponseDTOSchema,ImportPreviewResponseDTO,init_project_import_export_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-import-export.dto.js"(){"use strict";init_create_dto();ExportProjectResponseDTOSchema=z16.object({success:z16.literal(!0),downloadUrl:z16.string(),expiresAt:z16.string(),fileSize:z16.number(),duration:z16.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z16.object({success:z16.literal(!0),projectId:z16.string(),projectName:z16.string(),displayName:z16.string(),projectUrl:z16.string(),duration:z16.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z16.object({contentTypes:z16.number(),entries:z16.number(),assets:z16.number(),translations:z16.number(),forms:z16.number(),codeFiles:z16.number(),assetFiles:z16.number()}),ImportPreviewSurfaceDTOSchema=z16.object({name:z16.string(),included:z16.boolean(),count:z16.number().optional(),note:z16.string().optional()}),ImportPreviewDTOSchema=z16.object({projectName:z16.string(),displayName:z16.string().nullable(),visibility:z16.string().nullable(),category:z16.string().nullable(),exportedAt:z16.string(),version:z16.string(),envScope:z16.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z16.array(ImportPreviewSurfaceDTOSchema),fileSize:z16.number(),fileName:z16.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z16.object({success:z16.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z17}from"zod";var TriggerKindSchema,ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2,TriggerSchema2,init_agent_trigger_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-trigger.dto.js"(){"use strict";TriggerKindSchema=z17.enum(["manual","schedule","webhook"]),ManualTriggerSchema2=z17.object({type:z17.literal("manual")}),ScheduleTriggerSchema=z17.object({type:z17.literal("schedule"),cron:z17.string().min(1,"cron expression required").regex(/^\s*\S+\s+\S+\s+\S+\s+\S+\s+\S+\s*$/,"cron must be a 5-field expression"),tz:z17.string().optional()}),WebhookTriggerSchema2=z17.object({type:z17.literal("webhook"),path:z17.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z17.discriminatedUnion("type",[ManualTriggerSchema2,ScheduleTriggerSchema,WebhookTriggerSchema2])}});import{z as z18}from"zod";var ActivateRequestSchema,DeactivateRequestSchema,AgentActivationDTOSchema,AgentActivationDTO,AgentActivationsListResponseSchema,AgentActivationResponseSchema,WebhookPathTakenErrorSchema,ManualRunRequestSchema,DispatchSkippedSchema,DispatchAcceptedSchema,ManualRunResponseSchema,init_agent_activation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-activation.dto.js"(){"use strict";init_env();init_create_dto();init_response();init_agent_trigger_dto();ActivateRequestSchema=z18.object({triggerIndices:z18.array(z18.number().int().nonnegative()).optional()}),DeactivateRequestSchema=z18.object({triggerIndices:z18.array(z18.number().int().nonnegative()).optional()}),AgentActivationDTOSchema=z18.object({projectId:z18.uuid(),env:EnvSchema,agentName:z18.string().min(1),triggerIndex:z18.number().int().nonnegative(),triggerKind:TriggerKindSchema,trigger:TriggerSchema2,enabled:z18.boolean(),lastFiredAt:z18.coerce.date().nullable(),webhookPath:z18.string().nullable(),createdAt:z18.coerce.date(),updatedAt:z18.coerce.date()}),AgentActivationDTO=createDTO(AgentActivationDTOSchema),AgentActivationsListResponseSchema=createResponseSchema(z18.array(AgentActivationDTOSchema)),AgentActivationResponseSchema=createResponseSchema(AgentActivationDTOSchema),WebhookPathTakenErrorSchema=z18.object({error:z18.literal("webhook_path_taken"),conflictAgent:z18.string(),path:z18.string()}),ManualRunRequestSchema=z18.object({args:z18.unknown().optional(),requestId:z18.string().min(1).max(128).optional()}),DispatchSkippedSchema=z18.object({skipped:z18.enum(["duplicate","no-activation","agent-not-cloud","bundle-missing","trigger-stale"])}),DispatchAcceptedSchema=z18.object({sessionId:z18.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z18.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z19}from"zod";var CapabilityRiskTierSchema,CapabilitySummaryEntrySchema,AgentSubAgentSummarySchema,AgentInstallSummaryDTOSchema,AgentInstallSummaryDTO,AgentInstallSummaryResponseSchema,init_agent_install_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-install-summary.dto.js"(){"use strict";init_create_dto();init_response();CapabilityRiskTierSchema=z19.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z19.object({token:z19.string().min(1),risk:CapabilityRiskTierSchema,description:z19.string()}),AgentSubAgentSummarySchema=z19.object({name:z19.string().min(1),grant:z19.enum(["inherit","explicit"]),effectiveCaps:z19.array(z19.string().min(1))}),AgentInstallSummaryDTOSchema=z19.object({agentName:z19.string().min(1),env:z19.string().min(1),declaredCapabilities:z19.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z19.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z19.array(CapabilitySummaryEntrySchema),criticalCapabilities:z19.array(CapabilitySummaryEntrySchema),subAgents:z19.array(AgentSubAgentSummarySchema),declaresDelegate:z19.boolean(),cycle:z19.array(z19.string()).nullable(),missingSubAgents:z19.array(z19.string()),warnings:z19.array(z19.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z20}from"zod";var AgentListItemTriggerSchema,AgentListItemActivationSchema,AgentListItemDTOSchema,AgentListItemDTO,AgentListResponseSchema,init_agent_list_item_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-list-item.dto.js"(){"use strict";init_create_dto();init_response();init_agent_install_summary_dto();init_agent_trigger_dto();AgentListItemTriggerSchema=z20.object({kind:TriggerKindSchema,summary:z20.string()}),AgentListItemActivationSchema=z20.object({triggerIndex:z20.number().int().nonnegative(),triggerKind:TriggerKindSchema,env:z20.string().min(1),active:z20.boolean()}),AgentListItemDTOSchema=z20.object({name:z20.string().min(1),description:z20.string().nullable(),goalFirstLine:z20.string().nullable(),declaredCapabilities:z20.array(CapabilitySummaryEntrySchema),triggers:z20.array(AgentListItemTriggerSchema),activations:z20.array(AgentListItemActivationSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z20.array(AgentListItemDTOSchema))}});import{z as z21}from"zod";var AgentSessionStatusSchema,SessionMetricsSchema,AgentSessionDTOSchema,AgentSessionDTO,AgentSessionCheckpointDTOSchema,AgentSessionCheckpointDTO,AgentSessionResponseSchema,AgentSessionsListResponseSchema,AgentSessionCheckpointsListResponseSchema,AgentSessionWithCheckpointsResponseSchema,SessionErrorCodeSchema,CancelSessionRequestSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_env();init_create_dto();init_response();init_agent_trigger_dto();AgentSessionStatusSchema=z21.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z21.object({cpuMs:z21.number().nonnegative().default(0),netBytes:z21.number().nonnegative().default(0),walltimeMs:z21.number().nonnegative().default(0),llmTokensIn:z21.number().nonnegative().optional(),llmTokensOut:z21.number().nonnegative().optional()}),AgentSessionDTOSchema=z21.object({id:z21.uuid(),projectId:z21.uuid(),env:EnvSchema,agentName:z21.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z21.unknown().optional(),capabilities:z21.array(z21.string()).optional(),dataSources:z21.array(z21.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z21.string().nullable(),startedAt:z21.coerce.date().nullable(),finishedAt:z21.coerce.date().nullable(),cancelledAt:z21.coerce.date().nullable(),costUsd:z21.number().nonnegative(),costCeilingUsd:z21.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z21.boolean(),lastCheckpointId:z21.uuid().nullable(),branchEnvId:z21.uuid().nullable(),parentSessionId:z21.uuid().nullable(),terminalReason:z21.string().nullable(),errorMessage:z21.string().nullable(),report:z21.string().nullable(),createdAt:z21.coerce.date(),updatedAt:z21.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z21.object({id:z21.uuid(),sessionId:z21.uuid(),checkpointIdx:z21.number().int().nonnegative(),payloadRef:z21.string(),payloadSizeBytes:z21.number().int().nonnegative(),checksum:z21.string().length(64),createdAt:z21.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z21.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z21.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z21.object({session:AgentSessionDTOSchema,checkpoints:z21.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z21.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","too_many_agent_envs","env_provisioning_failed"]),CancelSessionRequestSchema=z21.object({reason:z21.string().min(1).max(120).optional()})}});import{z as z22}from"zod";var AgentBranchClassificationSchema,AgentBranchDecidedPathSchema,AgentBranchProposalDTOSchema,AgentBranchProposalDTO,DecideProposalRequestSchema,AgentBranchProposalResponseSchema,AgentBranchProposalsListResponseSchema,DecideProposalConflictResponseSchema,init_agent_proposal_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-proposal.dto.js"(){"use strict";init_create_dto();init_response();AgentBranchClassificationSchema=z22.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z22.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z22.object({id:z22.uuid(),envId:z22.uuid(),sessionId:z22.uuid().nullable(),skillName:z22.string().min(1),classification:AgentBranchClassificationSchema,rationale:z22.string().nullable(),summary:z22.string().nullable(),surfaceDeltas:z22.record(z22.string(),z22.unknown()),createdAt:z22.coerce.date(),decidedAt:z22.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z22.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z22.object({path:z22.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z22.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z22.object({code:z22.literal("merge_conflict"),message:z22.string(),conflicts:z22.record(z22.string(),z22.number().int().nonnegative())})}});import{z as z23}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,SetProjectIntegrationCredentialRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,ConnectOrganizationIntegrationRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,BindProjectChannelRequestSchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolOptionsSchema,RunProjectIntegrationToolRequestSchema,ProjectIntegrationToolRunUsageSchema,ProjectIntegrationToolRunBillingSchema,FirecrawlScrapeToolOutputSchema,FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlMonitorScheduleOutputSchema,FirecrawlMonitorTargetOutputSchema,FirecrawlMonitorOutputSchema,FirecrawlMonitorCheckOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema,FirecrawlToolKeySchema,FirecrawlToolOutputSchema,ProjectIntegrationToolRunBaseSchema,ProjectIntegrationToolRunDTOSchema,ProjectIntegrationToolRunDTO,IntegrationsListResponseSchema,IntegrationInfoResponseSchema,ProjectIntegrationStatusResponseSchema,ProjectIntegrationInstallationResponseSchema,ProjectIntegrationToolRunResponseSchema,StartProjectIntegrationConnectResponseResponseSchema,OrganizationIntegrationConnectionResponseSchema,ProjectChannelBindingResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z23.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z23.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z23.enum(["secret_text"]),IntegrationCredentialUsageSchema=z23.enum(["http_bearer","api_key"]),ProjectIntegrationCredentialStatusSchema=z23.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z23.object({mode:IntegrationAuthModeSchema,label:z23.string().min(1),description:z23.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z23.object({id:z23.string().min(1),label:z23.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z23.boolean()}),IntegrationToolDefinitionDTOSchema=z23.object({key:z23.string().min(1),name:z23.string().min(1),description:z23.string().min(1)}),IntegrationRecipeDTOSchema=z23.object({title:z23.string().min(1),description:z23.string().min(1),command:z23.string().min(1).optional()}),IntegrationInfoDTOSchema=z23.object({key:z23.string().min(1),name:z23.string().min(1),summary:z23.string().min(1),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z23.array(IntegrationAuthModeDTOSchema),credentials:z23.array(IntegrationCredentialDefinitionDTOSchema),tools:z23.array(IntegrationToolDefinitionDTOSchema),recipes:z23.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z23.object({projectId:z23.uuid(),integrationKey:z23.string().min(1),installed:z23.boolean(),enabled:z23.boolean(),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z23.string().nullable(),connectionId:z23.uuid().nullable().optional(),connectionAlias:z23.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z23.array(z23.string()),installedAt:z23.coerce.date().nullable(),updatedAt:z23.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z23.object({id:z23.uuid(),projectId:z23.uuid(),integrationKey:z23.string().min(1),enabled:z23.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z23.string(),connectionId:z23.uuid().nullable().optional(),connectionAlias:z23.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z23.array(z23.string()),createdAt:z23.coerce.date(),updatedAt:z23.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z23.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z23.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z23.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z23.object({value:z23.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z23.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z23.object({id:z23.uuid(),organizationId:z23.string().min(1),integrationKey:z23.string().min(1),alias:z23.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z23.string().min(1),externalAccountName:z23.string().nullable(),externalBotUserId:z23.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z23.array(z23.string()),connectedAt:z23.coerce.date(),updatedAt:z23.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ConnectOrganizationIntegrationRequestSchema=z23.object({alias:z23.string().min(1).max(120).optional(),token:z23.string().min(1).optional()}),StartProjectIntegrationConnectResponseSchema=z23.object({integrationKey:z23.string().min(1),connectUrl:z23.string().url(),expiresAt:z23.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),BindProjectChannelRequestSchema=z23.object({ref:z23.string().min(1),connectionAlias:z23.string().min(1).optional(),agentName:z23.string().min(1).max(160).nullable().optional(),force:z23.boolean().optional()}),ProjectChannelBindingDTOSchema=z23.object({id:z23.uuid(),projectId:z23.uuid(),integrationKey:z23.string().min(1),connectionId:z23.uuid(),externalWorkspaceId:z23.string().min(1),externalChannelId:z23.string().min(1),externalChannelName:z23.string().nullable(),agentName:z23.string().nullable(),enabled:z23.boolean(),createdAt:z23.coerce.date(),updatedAt:z23.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),FirecrawlScrapeFormatsSchema=z23.object({markdown:z23.boolean().optional(),summary:z23.boolean().optional(),links:z23.boolean().optional(),images:z23.boolean().optional(),html:z23.union([z23.literal("cleaned"),z23.literal("raw"),z23.boolean()]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z23.object({url:z23.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional(),waitForMs:z23.number().int().min(0).max(3e4).optional()}),FirecrawlSearchToolInputSchema=z23.object({query:z23.string().min(1),maxResults:z23.number().int().positive().max(20).optional(),sources:z23.array(z23.enum(["web","news","images"])).min(1).max(3).optional(),categories:z23.array(z23.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z23.array(z23.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z23.array(z23.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z23.enum(["hour","day","week","month","year"]).optional(),location:z23.string().min(1).max(160).optional(),country:z23.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlMapToolInputSchema=z23.object({url:z23.string().url(),search:z23.string().min(1).optional(),limit:z23.number().int().positive().max(200).optional(),includeSubdomains:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z23.object({url:z23.string().url(),limit:z23.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z23.object({text:z23.string().min(1).max(200).optional(),cron:z23.string().min(1).max(120).optional(),timezone:z23.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorTargetInputSchema=z23.object({type:z23.enum(["scrape","crawl"]).default("scrape"),urls:z23.array(z23.string().url()).min(1).max(50),scrapeOptions:z23.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z23.boolean().optional(),timeoutMs:z23.number().int().positive().max(12e4).optional(),waitForMs:z23.number().int().min(0).max(3e4).optional()}).optional()}),FirecrawlMonitorCreateToolInputSchema=z23.object({name:z23.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z23.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z23.string().min(1).max(2e3).optional(),judgeEnabled:z23.boolean().optional(),retentionDays:z23.number().int().min(1).max(365).optional(),notification:z23.object({email:z23.object({enabled:z23.boolean().default(!0),recipients:z23.array(z23.string().email()).min(1).max(20),includeDiffs:z23.boolean().optional()}).optional()}).optional()}),FirecrawlMonitorIdToolInputSchema=z23.object({monitorId:z23.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z23.string().uuid()}),RunProjectIntegrationToolOptionsSchema=z23.object({connectionAlias:z23.string().min(1).optional()}),RunProjectIntegrationToolRequestSchema=z23.discriminatedUnion("tool",[RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("search"),input:FirecrawlSearchToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("scrape"),input:FirecrawlScrapeToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("map"),input:FirecrawlMapToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("crawl"),input:FirecrawlCrawlToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.create"),input:FirecrawlMonitorCreateToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.list"),input:z23.object({}).default({})}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.get"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.pause"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.resume"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.delete"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.run"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.checks"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z23.literal("monitor.check"),input:FirecrawlMonitorCheckToolInputSchema})]),ProjectIntegrationToolRunUsageSchema=z23.object({provider:z23.string().min(1),providerCredits:z23.number().nonnegative().optional(),providerCostUsd:z23.number().nonnegative().optional(),requests:z23.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z23.object({credits:z23.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z23.object({url:z23.string(),provider:z23.literal("firecrawl"),title:z23.string().optional(),statusCode:z23.number().optional(),markdown:z23.string().optional(),summary:z23.string().optional(),links:z23.array(z23.string()).optional(),images:z23.array(z23.string()).optional(),html:z23.string().optional(),warning:z23.string().optional()}),FirecrawlSearchToolOutputSchema=z23.object({query:z23.string(),provider:z23.literal("firecrawl"),warning:z23.string().optional(),results:z23.array(z23.object({title:z23.string(),url:z23.string(),snippet:z23.string().optional(),content:z23.string().optional(),score:z23.number().optional(),publishedAt:z23.string().optional()}))}),FirecrawlMapToolOutputSchema=z23.object({url:z23.string(),provider:z23.literal("firecrawl"),count:z23.number(),links:z23.array(z23.object({url:z23.string(),title:z23.string().optional(),description:z23.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z23.object({url:z23.string(),provider:z23.literal("firecrawl"),total:z23.number(),pages:z23.array(z23.object({url:z23.string(),title:z23.string().optional(),statusCode:z23.number().optional(),markdown:z23.string().optional(),summary:z23.string().optional(),links:z23.array(z23.string()).optional(),images:z23.array(z23.string()).optional(),html:z23.string().optional(),warning:z23.string().optional()})),warning:z23.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z23.object({cron:z23.string().optional(),text:z23.string().optional(),timezone:z23.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z23.object({id:z23.string().optional(),urls:z23.array(z23.string()).optional(),scrapeOptions:z23.record(z23.string(),z23.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z23.object({id:z23.string(),name:z23.string(),status:z23.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z23.string().nullable().optional(),lastRunAt:z23.string().nullable().optional(),currentCheckId:z23.string().nullable().optional(),targets:z23.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z23.string().nullable().optional(),judgeEnabled:z23.boolean().optional(),estimatedCreditsPerMonth:z23.number().optional(),createdAt:z23.string().optional(),updatedAt:z23.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z23.object({id:z23.string(),monitorId:z23.string(),scheduledFor:z23.string().nullable().optional(),startedAt:z23.string().nullable().optional(),finishedAt:z23.string().nullable().optional(),estimatedCredits:z23.number().optional(),reservedCredits:z23.number().optional(),actualCredits:z23.number().optional(),billingStatus:z23.string().nullable().optional(),summary:z23.object({totalPages:z23.number().optional(),same:z23.number().optional(),changed:z23.number().optional(),new:z23.number().optional(),removed:z23.number().optional(),error:z23.number().optional()}).passthrough().optional(),error:z23.string().nullable().optional(),createdAt:z23.string().optional(),updatedAt:z23.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitors:z23.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitorId:z23.string(),deleted:z23.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitorId:z23.string(),checks:z23.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z23.object({provider:z23.literal("firecrawl"),monitorId:z23.string(),check:FirecrawlMonitorCheckOutputSchema,next:z23.string().optional()}),FirecrawlToolKeySchema=z23.enum(["search","scrape","map","crawl","monitor.create","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z23.union([FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z23.object({projectId:z23.uuid(),integrationKey:z23.string().min(1),tool:FirecrawlToolKeySchema,connectionAlias:z23.string().min(1).nullable().optional(),output:FirecrawlToolOutputSchema,executedAt:z23.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z23.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z23.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z23.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z23.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z23.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z23.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z23.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z23.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema)}});import{z as z24}from"zod";var ProjectScheduleStatusSchema,ProjectScheduleDTOSchema,ProjectScheduleDTO,CreateProjectScheduleRequestSchema,ProjectScheduleResponseSchema,ProjectSchedulesListResponseSchema,init_schedule_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule.dto.js"(){"use strict";init_create_dto();init_response();ProjectScheduleStatusSchema=z24.enum(["ok","failed"]),ProjectScheduleDTOSchema=z24.object({id:z24.uuid(),projectId:z24.uuid(),env:z24.string().min(1),name:z24.string().min(1),cron:z24.string().min(1),command:z24.string().min(1),enabled:z24.boolean(),lastRunAt:z24.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z24.string().nullable(),createdAt:z24.coerce.date(),updatedAt:z24.coerce.date()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z24.object({name:z24.string().min(1).max(120),cron:z24.string().min(1).max(120),command:z24.string().min(1).max(500)}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListResponseSchema=createResponseSchema(z24.array(ProjectScheduleDTOSchema))}});import{z as z25}from"zod";var AuditLogRowDTOSchema,AuditLogRowDTO,AuditLogListResponseSchema,AuditLogQuerySchema,init_audit_log_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/audit-log.dto.js"(){"use strict";init_audit_log();init_create_dto();init_response();AuditLogRowDTOSchema=z25.object({id:z25.uuid(),occurredAt:z25.coerce.date(),projectId:z25.uuid().nullable(),env:z25.string().nullable(),actor:z25.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z25.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z25.unknown().optional(),ipAddress:z25.string().nullable().optional(),userAgent:z25.string().nullable().optional(),error:z25.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z25.object({rows:z25.array(AuditLogRowDTOSchema),nextCursor:z25.string().nullable()})),AuditLogQuerySchema=z25.object({env:z25.string().optional(),action:AuditActionSchema.optional(),actor:z25.string().optional(),from:z25.coerce.date().optional(),to:z25.coerce.date().optional(),limit:z25.coerce.number().int().min(1).max(200).optional(),cursor:z25.string().optional()})}});import{z as z26}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,ActivationSnapshotSchema,ActivationDiffSchema,ActivationDiffDTO,ActivationDiffResponseSchema,ConflictSchema,FieldPickSchema,ConflictResolutionSchema,MergeResultSchema,MergeResultDTO,MergeResultResponseSchema,EngineStrategySchema,VendorStrategySchema,MergeStrategySchema,ResolvedStrategySchema,MergeRequestSchema,MergeInitiateResultSchema,MergeInitiateResultDTO,MergeInitiateResponseSchema,MergeConflictsHydrationSchema,MergeConflictsHydrationDTO,MergeConflictsHydrationResponseSchema,MergeResolveDraftRequestSchema,MergeResolveDraftResultSchema,MergeResolveDraftResultDTO,MergeResolveRequestSchema,MergeCancelRequestSchema,PublishReleaseRequestSchema,PublishReleaseResultSchema,PublishReleaseResultDTO,PublishReleaseResponseSchema,init_env_status_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-status.dto.js"(){"use strict";init_env();init_create_dto();init_response();SurfaceNameSchema=z26.enum(["code","schemas","content","translations","assets","forms","activations"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms","activations"],SurfaceDeltaVerbSchema=z26.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z26.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z26.object({verb:SurfaceDeltaVerbSchema,key:z26.string(),detail:z26.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z26.record(z26.string(),z26.unknown()).optional()}),PerSurfaceDeltaSchema=z26.object({surface:SurfaceNameSchema,status:z26.enum(["ok","timed_out","failed","unchanged"]),durationMs:z26.number().int().nonnegative().optional(),changedCount:z26.number().int().nonnegative(),conflictCount:z26.number().int().nonnegative(),items:z26.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z26.boolean().optional(),error:z26.string().optional()}),CrossSurfaceFindingSchema=z26.object({id:z26.string(),kind:z26.string(),description:z26.string(),severity:z26.enum(["warning","error"]),source:z26.object({surface:SurfaceNameSchema,key:z26.string()}),target:z26.object({surface:SurfaceNameSchema,key:z26.string()}),actions:z26.array(z26.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z26.object({env:EnvSchema,vs:EnvSchema,syncState:z26.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z26.coerce.date(),surfaces:z26.array(PerSurfaceDeltaSchema),agents:z26.array(z26.object({id:z26.string(),name:z26.string(),status:z26.enum(["active","paused","failed"]),lastRunAt:z26.coerce.date().nullable()})).optional(),crossSurface:z26.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z26.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z26.coerce.date(),surfaces:z26.array(PerSurfaceDeltaSchema),crossSurface:z26.array(CrossSurfaceFindingSchema).optional(),fingerprint:z26.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z26.object({path:z26.string(),state:z26.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z26.string(),additions:z26.number().int().nonnegative(),deletions:z26.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z26.object({oid:z26.string().optional(),content:z26.string().optional(),truncated:z26.boolean(),binary:z26.boolean()}),CodeConflictDetailSchema=z26.object({path:z26.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z26.string(),targetTipSha:z26.string(),mergeBaseSha:z26.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z26.object({id:z26.string(),slug:z26.string(),contentType:z26.string(),data:z26.record(z26.string(),z26.unknown()),updatedAt:z26.coerce.date()}),ContentRowDiffSchema=z26.object({collection:z26.string(),rowId:z26.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z26.object({name:z26.string(),label:z26.string(),isSingleton:z26.boolean(),fields:z26.record(z26.string(),z26.unknown())}),SchemaTypeDiffSchema=z26.object({typeName:z26.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z26.object({id:z26.string(),name:z26.string(),type:z26.enum(["file","folder"]),mimeType:z26.string().nullable(),storageKey:z26.string().nullable(),url:z26.string().nullable(),fileSize:z26.number().nullable(),width:z26.number().nullable(),height:z26.number().nullable(),altText:z26.string().nullable(),caption:z26.string().nullable(),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),AssetDiffSchema=z26.object({assetId:z26.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z26.object({locale:z26.string(),key:z26.string(),parent:z26.string().nullable(),child:z26.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z26.object({formName:z26.string(),label:z26.string().nullable(),schemaFingerprint:z26.string(),fields:z26.record(z26.string(),z26.unknown()),settings:z26.record(z26.string(),z26.unknown()).optional()}),FormSchemaDiffSchema=z26.object({formName:z26.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),ActivationSnapshotSchema=z26.object({agentName:z26.string(),triggerIndex:z26.number().int().nonnegative(),triggerKind:z26.string(),triggerSpec:z26.record(z26.string(),z26.unknown()),enabled:z26.boolean(),emailRecipients:z26.array(z26.string()).nullable(),qstashScheduleId:z26.string().nullable()}),ActivationDiffSchema=z26.object({agentName:z26.string(),triggerIndex:z26.number().int().nonnegative(),parent:ActivationSnapshotSchema.nullable(),child:ActivationSnapshotSchema.nullable()}),ActivationDiffDTO=createDTO(ActivationDiffSchema),ActivationDiffResponseSchema=createResponseSchema(ActivationDiffSchema),ConflictSchema=z26.object({surface:SurfaceNameSchema,key:z26.string(),kind:z26.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity"]).optional(),description:z26.string(),parentValue:z26.unknown().optional(),childValue:z26.unknown().optional(),conflictingFields:z26.array(z26.string()).optional(),code:z26.object({path:z26.string(),unresolvable:z26.boolean().optional(),reason:z26.string().optional()}).optional()}),FieldPickSchema=z26.object({field:z26.string(),choice:z26.enum(["parent","child","pick","ai-pick"]),pickedValue:z26.unknown().optional(),aiSessionId:z26.string().optional()}),ConflictResolutionSchema=z26.object({surface:SurfaceNameSchema,key:z26.string(),choice:z26.enum(["parent","child","pick"]),pickedValue:z26.unknown().optional(),fieldPicks:z26.array(FieldPickSchema).optional()}),MergeResultSchema=z26.object({ok:z26.boolean(),mergeId:z26.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z26.array(z26.object({surface:SurfaceNameSchema,count:z26.number().int().nonnegative()})),conflicts:z26.array(ConflictSchema).optional(),summary:z26.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z26.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z26.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z26.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z26.boolean().optional()}),ResolvedStrategySchema=z26.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z26.boolean()}),MergeRequestSchema=z26.object({from:EnvSchema,allowDirectMerge:z26.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z26.object({mergeId:z26.string().uuid(),streamUrl:z26.string(),strategy:ResolvedStrategySchema,acceptedAt:z26.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z26.object({mergeId:z26.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z26.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z26.array(ConflictSchema),draftResolutions:z26.array(ConflictResolutionSchema),lastEditedBy:z26.string().nullable(),lastEditedAt:z26.coerce.date().nullable(),initiator:z26.object({userId:z26.string().nullable(),role:z26.string().nullable(),agentName:z26.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z26.object({resolutions:z26.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z26.object({mergeId:z26.string().uuid(),draftResolutions:z26.array(ConflictResolutionSchema),lastEditedAt:z26.coerce.date(),lastEditedBy:z26.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z26.object({mergeId:z26.string().uuid(),resolutions:z26.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z26.object({mergeId:z26.string().uuid()}),PublishReleaseRequestSchema=z26.object({version:z26.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z26.string().max(2e4).optional()}),PublishReleaseResultSchema=z26.object({releaseTag:z26.string(),sha:z26.string(),publishedAt:z26.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z27}from"zod";var DiffRefSchema,InlineSchema,SummaryBlockSchema,EnvDiffSummarySchema,EnvDiffSummaryResultSchema,EnvDiffSummaryResultDTO,EnvDiffSummaryResponseSchema,init_env_diff_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-diff-summary.dto.js"(){"use strict";init_create_dto();init_response();init_env_status_dto();DiffRefSchema=z27.object({surface:SurfaceNameSchema,key:z27.string(),label:z27.string()}),InlineSchema=z27.object({text:z27.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z27.discriminatedUnion("type",[z27.object({type:z27.literal("paragraph"),content:z27.array(InlineSchema).max(24)}),z27.object({type:z27.literal("preview"),ref:DiffRefSchema,caption:z27.string().optional()}),z27.object({type:z27.literal("code"),code:z27.string(),lang:z27.string().optional(),caption:z27.string().optional()}),z27.object({type:z27.literal("risk"),level:z27.enum(["warning","error"]),content:z27.array(InlineSchema).max(24)}),z27.object({type:z27.literal("list"),items:z27.array(z27.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z27.object({headline:z27.string(),blocks:z27.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z27.object({summary:EnvDiffSummarySchema,fingerprint:z27.string(),generatedAt:z27.coerce.date(),cached:z27.boolean().optional(),credits:z27.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z28}from"zod";var PROJECT_ANALYTICS_PRESETS,PROJECT_ANALYTICS_GROUP_BY_OPTIONS,ProjectDailyVisitorsDTOSchema,ProjectAnalyticsBreakdownItemDTOSchema,ProjectAnalyticsPageBreakdownItemDTOSchema,ProjectAnalyticsRangeDTOSchema,ProjectAnalyticsAnnotationDTOSchema,ProjectPageviewAnalyticsDTOSchema,ProjectPageviewAnalyticsDTO,ProjectAnalyticsAnnotationDTO,init_project_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-analytics.dto.js"(){"use strict";init_create_dto();PROJECT_ANALYTICS_PRESETS=["today","yesterday","this_week","this_month","last_7_days","last_30_days","last_90_days","last_week","last_month","last_quarter","last_year","custom"],PROJECT_ANALYTICS_GROUP_BY_OPTIONS=["day","week","month","quarter"],ProjectDailyVisitorsDTOSchema=z28.object({date:z28.string(),visitors:z28.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z28.object({key:z28.string(),visitors:z28.number().int().nonnegative(),pageviews:z28.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z28.object({path:z28.string(),pageName:z28.string().nullable().optional(),visitors:z28.number().int().nonnegative(),pageviews:z28.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z28.object({preset:z28.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z28.string(),requestedTo:z28.string(),effectiveFrom:z28.string(),effectiveTo:z28.string(),isRetentionLimited:z28.boolean(),groupBy:z28.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z28.object({date:z28.string(),content:z28.string(),updatedAt:z28.string(),updatedByUserId:z28.string()}),ProjectPageviewAnalyticsDTOSchema=z28.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z28.number().int().nonnegative(),pageviews:z28.number().int().nonnegative(),bounceRate:z28.number().min(0).max(100),viewsPerVisit:z28.number().nonnegative(),averageVisitDurationSeconds:z28.number().nonnegative(),visitorsSeries:z28.array(ProjectDailyVisitorsDTOSchema),topPages:z28.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z28.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z28.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z28.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z28.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z28.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z29}from"zod";var ProjectInviteDTOSchema,ProjectInviteDTO,CreatedProjectInviteDTOSchema,CreatedProjectInviteDTO,AcceptedProjectInviteDTOSchema,AcceptedProjectInviteDTO,init_project_invite_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-invite.dto.js"(){"use strict";init_common();init_create_dto();ProjectInviteDTOSchema=z29.object({id:z29.string(),email:z29.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z29.coerce.date(),createdAt:z29.coerce.date(),inviterUserId:z29.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z29.object({id:z29.string(),token:z29.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z29.object({success:z29.boolean(),projectId:z29.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z30}from"zod";var PublicUserDTOSchema,PublicUserDTO,ReferralCountCTOSchema,ReferralCountCTO,ReferralSummaryCTOSchema,ReferralSummaryCTO,AuthenticatedUserDTOSchema,AuthenticatedUserDTO,AuthenticatedUserResponseSchema,ReferralCountResponseSchema,ReferralSummaryResponseSchema,init_user_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/user.dto.js"(){"use strict";init_create_dto();init_response();PublicUserDTOSchema=z30.object({id:z30.string(),name:z30.string(),image:z30.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z30.object({count:z30.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z30.object({counts:z30.object({signed_up:z30.int(),activated:z30.int()}),credits:z30.object({total:z30.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z30.email(),emailVerified:z30.boolean(),createdAt:z30.coerce.date(),updatedAt:z30.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z31}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,ProjectPermissionsDTOSchema,ProjectPermissionsDTO,ProjectAccessDTOSchema,ProjectAccessDTO,AccessMutationResponseSchema,InviteAcceptResponseSchema,init_project_access_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-access.dto.js"(){"use strict";init_common();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z31.object({id:z31.string(),principalType:ProjectPrincipalTypeSchema,principalId:z31.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z31.coerce.date(),expiresAt:z31.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),ProjectPermissionsDTOSchema=z31.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z31.record(z31.string(),z31.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z31.object({access:z31.array(ProjectAccessItemDTOSchema),invites:z31.array(ProjectInviteDTOSchema),organization:z31.object({name:z31.string().nullable(),logo:z31.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z31.object({success:z31.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z31.object({success:z31.boolean(),projectId:z31.uuid()}))}});import{z as z32}from"zod";var PublicationStateDTOSchema,PublicationStateDTO,init_publication_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/publication.dto.js"(){"use strict";init_common();init_create_dto();PublicationStateDTOSchema=z32.object({publicationStatus:PublicationStatusSchema,appUrl:z32.string().nullable(),lastPublishedAt:z32.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z33}from"zod";var SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,PreviewBootstrapDTOSchema,PreviewBootstrapDTO,PreviewBootstrapResponseSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();SandboxSessionDTOSchema=z33.object({url:z33.url(),expiresAt:z33.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewBootstrapDTOSchema=z33.discriminatedUnion("source",[z33.object({source:z33.literal("artifact"),artifact:SandboxSessionDTOSchema,dev:z33.null()}),z33.object({source:z33.literal("dev"),artifact:z33.null(),dev:SandboxSessionDTOSchema})]),PreviewBootstrapDTO=createDTO(PreviewBootstrapDTOSchema),PreviewBootstrapResponseSchema=createResponseSchema(PreviewBootstrapDTOSchema)}});import{z as z34}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z34.string(),slug:z34.string().nullable(),logo:z34.string().nullable(),metadata:z34.record(z34.string(),z34.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z34.object({id:z34.string(),name:z34.string(),email:z34.email(),image:z34.string().nullable()}),OrganizationMemberDTOSchema=z34.object({id:z34.string(),userId:z34.string(),organizationId:z34.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z34.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z35}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common();init_create_dto();init_response();CancellationReasonCodeSchema=z35.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z35.object({reason:CancellationReasonCodeSchema,details:z35.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z35.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),AiCreditsEntitlementSchema=z35.object({included:z35.number().optional(),unitPrice:z35.number().optional(),dailyCap:z35.number().nullable().optional()}),EntitlementsDTOSchema=z35.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z35.object({retentionDays:z35.number().int().positive(),canUseExtendedDateRanges:z35.boolean()}).optional(),members:z35.object({canInvite:z35.boolean(),maxMembers:z35.number().int().positive().nullable()}).optional(),projects:z35.object({canCreatePrivateProjects:z35.boolean(),maxPrivateProjects:z35.number().int().positive().nullable()}).optional(),domains:z35.object({canUseCustomDomains:z35.boolean(),maxDomains:z35.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z35.object({id:z35.string(),external_id:z35.string(),customerId:z35.string(),planId:z35.string(),planCode:TemplateCodeSchema,currentPeriod:z35.object({start:z35.string(),end:z35.string().nullable()}),cancelAt:z35.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z35.string(),nextPaymentAt:z35.string().nullable(),baseAmount:z35.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z35.object({totalCap:z35.number(),dailyCap:z35.number(),usedTotal:z35.number()}),CreditBalanceDTOSchema=z35.object({total:z35.number(),base:z35.number(),dailyBase:z35.number(),purchases:z35.number(),awards:z35.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z35.object({total:z35.number(),nearLimit:z35.boolean(),canChat:z35.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z35.object({dailyFreeAvailable:z35.number(),monthlyAvailable:z35.number(),purchasedAvailable:z35.number(),awardedAvailable:z35.number()}),ProjectDailyCreditAllowanceDTOSchema=z35.object({periodCap:z35.number(),dailyGrant:z35.number(),usedThisPeriod:z35.number(),remainingThisPeriod:z35.number()}),ProjectCreditBalanceDTOSchema=z35.object({projectId:z35.uuid(),organizationId:z35.string(),balance:z35.object({totalAvailable:z35.number(),nearLimit:z35.boolean(),canUseAi:z35.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z35.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),SuccessfulPurchaseDTOSchema=z35.object({invoiceId:z35.string(),newBalance:z35.int(),creditCount:z35.int(),amountUsd:z35.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z35.object({url:z35.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema)}});import{z as z36}from"zod";var PaymentMethodDTOSchema,PaymentMethodDTO,init_payment_method_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/payment-method.dto.js"(){"use strict";init_create_dto();PaymentMethodDTOSchema=z36.object({brand:z36.string(),last4:z36.string(),exp:z36.string(),isDefault:z36.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z37}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema,EntryDTO,PaginatedEntriesDTOSchema,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,EntryTranslationGapDTOSchema,EntryTranslationGapDTO,EntryTranslationGapResponseSchema,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema,EntryListResponseSchema,MAX_BULK_ENTRIES,entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema,EntryWhereSchema,EntryMutationBodySchema,entryIdsSchema,EntrySqlQueryRequestSchema,BulkCreateEntriesRequestSchema,BulkUpdateEntriesRequestSchema,BulkDeleteEntriesRequestSchema,EntrySqlQueryResponseSchema,EntrySqlQueryResponseDTO,BulkCreateEntriesResponseSchema,BulkCreateEntriesResponseDTO,BulkUpdateEntriesResponseSchema,BulkUpdateEntriesResponseDTO,BulkDeleteEntriesResponseSchema,BulkDeleteEntriesResponseDTO,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common();init_content_fields();init_create_dto();init_response();FieldDefinitionSchema=ContentFieldDefinitionSchema,SchemaFieldPathSchema=z37.string().superRefine((path47,ctx)=>{let segments=path47.split(".");(segments.length===0||segments.some(segment=>!CONTENT_FIELD_NAME_PATTERN.test(segment)))&&ctx.addIssue({code:"custom",message:"Field paths must use dot-separated field or block variant names."})}),SchemaMigrationOperationSchema=z37.object({type:z37.literal("renameField"),contentType:z37.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z37.object({enabled:z37.boolean()}).strict(),ContentTypeDTOSchema=z37.object({id:z37.string(),name:z37.string(),label:z37.string(),isSingleton:z37.boolean(),i18n:ContentTypeI18nSchema,fields:z37.record(z37.string(),FieldDefinitionSchema),createdAt:z37.string(),updatedAt:z37.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z37.object({contentTypes:z37.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z37.object({id:z37.string(),entryId:z37.string(),documentId:z37.string(),slug:z37.string(),locale:z37.string().optional(),createdAt:z37.string(),updatedAt:z37.string(),__fimo:z37.object({contentType:z37.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z37.object({data:z37.array(EntryDTOSchema),meta:z37.object({limit:z37.number(),offset:z37.number(),total:z37.number(),hasMore:z37.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z37.object({contentType:z37.string(),count:z37.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z37.object({counts:z37.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z37.object({count:z37.number().int().nonnegative(),sourceLocale:z37.string(),targetLocale:z37.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z37.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z37.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z37.union([z37.string(),z37.number(),z37.boolean(),z37.null()]),entryWhereOperatorSchema=z37.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z37.array(entryWhereScalarSchema).optional(),$nin:z37.array(entryWhereScalarSchema).optional(),$contains:z37.string().optional(),$startsWith:z37.string().optional(),$null:z37.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z37.record(z37.string(),z37.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z37.record(z37.string(),z37.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z37.object({data:z37.record(z37.string(),z37.unknown()),locale:z37.string().min(1).optional(),documentId:z37.uuid().optional()}),entryIdsSchema=z37.array(z37.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z37.object({sql:z37.string().min(1)}),BulkCreateEntriesRequestSchema=z37.object({entries:z37.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z37.union([z37.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z37.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z37.object({updates:z37.array(z37.object({id:z37.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z37.union([z37.object({ids:entryIdsSchema,locale:z37.string().min(1).optional()}),z37.object({where:EntryWhereSchema,locale:z37.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z37.object({data:z37.array(z37.record(z37.string(),z37.unknown())),meta:z37.object({rowCount:z37.number().int().nonnegative(),truncated:z37.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z37.object({data:z37.array(EntryDTOSchema),meta:z37.object({created:z37.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z37.object({data:z37.array(EntryDTOSchema),meta:z37.object({updated:z37.number().int().nonnegative(),missing:z37.array(z37.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z37.object({data:z37.array(EntryDTOSchema),meta:z37.object({deleted:z37.number().int().nonnegative(),missing:z37.array(z37.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z38}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z38.object({index:z38.number().int().nonnegative(),contentType:z38.string(),field:z38.string(),value:z38.string(),against:z38.enum(["stored","batch"]),ownerDocumentId:z38.uuid().optional(),ownerIndex:z38.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z38.object({code:z38.literal("unique_conflict"),message:z38.string(),conflicts:z38.array(UniqueConflictSchema),truncated:z38.boolean().optional()})}});import{z as z39}from"zod";var UniqueConflictIssueSchema,SchemaTransitionIssueSchema,SchemaTransitionRejectedErrorSchema,init_schema_transition_rejected_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schema-transition-rejected.dto.js"(){"use strict";UniqueConflictIssueSchema=z39.object({kind:z39.literal("unique_conflict"),contentType:z39.string(),field:z39.string(),value:z39.string(),documentCount:z39.number().int().positive(),documentIds:z39.array(z39.uuid()),documentIdsTruncated:z39.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z39.object({code:z39.literal("schema_transition_rejected"),message:z39.string(),issues:z39.array(SchemaTransitionIssueSchema),truncated:z39.boolean().optional()})}});import{z as z40}from"zod";var CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH,CmsContentTypeNameSchema,CmsFieldNameSchema,CmsCollectionOrderSchema,CmsFieldOrderSchema,CmsListSortSchema,CmsDisplayDefaultsDTOSchema,CmsDisplayDefaultsDTO,CmsCollectionOrderRequestSchema,CmsFieldOrderRequestSchema,CmsDisplayDefaultsResponseSchema,init_cms_display_defaults_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/cms-display-defaults.dto.js"(){"use strict";init_common();init_create_dto();init_response();CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS=200,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH=255,CmsContentTypeNameSchema=z40.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z40.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z40.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z40.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z40.object({field:CmsFieldNameSchema,direction:z40.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z40.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z40.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z40.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z40.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z40.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z41}from"zod";var AssetPathItemSchema,AssetDTOSchema,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema,AssetListResponseSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common();init_create_dto();init_response();AssetPathItemSchema=z41.object({id:z41.string(),name:z41.string()}),AssetDTOSchema=z41.object({id:z41.string(),name:z41.string(),type:AssetTypeSchema,originalFileName:z41.string().nullable(),parentId:z41.string().nullable(),mimeType:z41.string().nullable(),fileSize:z41.number().nullable(),url:z41.string().nullable(),storageKey:z41.string().nullable(),createdAt:z41.string(),updatedAt:z41.string(),altText:z41.string().nullable().optional(),caption:z41.string().nullable().optional(),aiCaption:z41.string().nullable().optional(),aiAltText:z41.string().nullable().optional(),aiTags:z41.array(z41.string()).nullable().optional(),aiPrimaryColor:z41.string().nullable().optional(),aiProcessingStatus:z41.string().nullable().optional(),width:z41.number().nullable().optional(),height:z41.number().nullable().optional(),path:z41.array(AssetPathItemSchema).optional(),hasChildren:z41.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z41.lazy(()=>z41.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z41.array(AssetDTOSchema))}});import{z as z42}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z42.object({key:z42.string(),value:z42.string().optional(),defaultValue:z42.string(),locale:z42.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z43}from"zod";var DocumentNodeDTOSchema,DocumentTreeDTOSchema,DocumentPathDTOSchema,DocumentPathDTO,DocumentTreeResponseSchema,DocumentPathResponseSchema,init_document_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/document.dto.js"(){"use strict";init_create_dto();init_response();DocumentNodeDTOSchema=z43.object({id:z43.string(),name:z43.string(),type:z43.enum(["file","folder"]),path:z43.string(),children:z43.lazy(()=>z43.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z43.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z43.object({path:z43.string(),exists:z43.boolean(),type:z43.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z44}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatDeletionDTOSchema,ChatDeletionDTO,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,ChatDeletionResponseSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_create_dto();init_response();init_project_dto();ChatMessageListDTOSchema=z44.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z44.object({items:z44.array(ProjectMessagePublicDTOSchema),nextCursor:z44.string().nullable()}),ChatDeletionDTOSchema=z44.object({success:z44.boolean(),deletedCount:z44.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema)}});import{z as z45}from"zod";var UploadResultDTOSchema,UploadResultDTO,UploadResultResponseSchema,init_upload_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/upload.dto.js"(){"use strict";init_common();init_create_dto();init_response();UploadResultDTOSchema=z45.object({url:z45.string().url(),key:z45.string(),size:z45.number(),contentType:z45.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z46}from"zod";var ServicePermissionsDTOSchema,ServicePermissionsDTO,ServicePermissionsResponseSchema,init_service_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/service.dto.js"(){"use strict";init_create_dto();init_response();ServicePermissionsDTOSchema=z46.object({canAccess:z46.boolean(),permissions:z46.record(z46.string(),z46.boolean()),role:z46.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z47}from"zod";var OrganizationProjectsSearchQuerySchema,init_search_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/search.dto.js"(){"use strict";init_pagination();OrganizationProjectsSearchQuerySchema=PaginationQuerySchema.extend({q:z47.string().trim().default(""),sort:z47.enum(["recent","name","relevance"]).default("recent"),category:z47.string().optional(),visibility:z47.enum(["public","private"]).optional()})}});import{z as z48}from"zod";var DomainStatusSchema,DomainSourceSchema,PaymentStatusSchema,DomainDTOSchema,DomainDTO,DomainSearchResultDTOSchema,DomainSearchResultDTO,DomainPricingDTOSchema,DomainPricingDTO,DomainContactSchema,DomainContactDTO,UpdateDomainContactsRequestSchema,SearchDomainsRequestSchema,CheckAvailabilityRequestSchema,DOMAIN_NAME_REGEX,DomainNameSchema,PurchaseDomainRequestSchema,UpdateDomainSettingsRequestSchema,RenewDomainRequestSchema,DomainResponseSchema,DomainListResponseSchema,DomainSearchResultListResponseSchema,DomainPricingResponseSchema,DomainContactResponseSchema,ContactVerificationStatusSchema,ContactVerificationStatusResponseSchema,init_registered_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/registered-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();DomainStatusSchema=z48.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z48.enum(["fimo","external"]),PaymentStatusSchema=z48.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z48.object({id:z48.string().uuid(),domain:z48.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z48.boolean(),price:z48.number().int().nullable(),renewalPrice:z48.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z48.string().nullable(),failureReason:z48.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z48.object({domain:z48.string(),available:z48.boolean(),premium:z48.boolean(),price:z48.number().nullable(),renewalPrice:z48.number().nullable(),purchaseType:z48.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z48.object({domain:z48.string(),price:z48.number().nullable(),renewalPrice:z48.number().nullable(),premium:z48.boolean(),allowedYears:z48.array(z48.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z48.object({firstName:z48.string().max(100),lastName:z48.string().max(100),companyName:z48.string().max(100).optional(),address1:z48.string().max(255),address2:z48.string().max(255).optional(),city:z48.string().max(100),state:z48.string().max(100),zip:z48.string().max(20),country:z48.string().max(2),phone:z48.string().max(30),email:z48.union([z48.string().email().max(255),z48.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z48.object({firstName:z48.string().min(1).max(100),lastName:z48.string().min(1).max(100),companyName:z48.string().max(100).optional(),address1:z48.string().min(1).max(255),address2:z48.string().max(255).optional(),city:z48.string().min(1).max(100),state:z48.string().min(1).max(100),zip:z48.string().min(1).max(20),country:z48.string().min(1).max(2),phone:z48.string().min(1).max(30),email:z48.string().email().max(255)}),SearchDomainsRequestSchema=z48.object({keyword:z48.string().min(1).max(100),tldFilter:z48.array(z48.string()).optional()}),CheckAvailabilityRequestSchema=z48.object({domains:z48.array(z48.string()).min(1).max(50)}),DOMAIN_NAME_REGEX=/^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,DomainNameSchema=z48.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z48.object({domain:DomainNameSchema,years:z48.number().int().min(1).max(10).optional().default(3),autoRenew:z48.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z48.object({autoRenew:z48.boolean().optional()}),RenewDomainRequestSchema=z48.object({years:z48.number().int().min(1).max(10).optional().default(1),autoRenew:z48.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z48.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z48.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z48.object({verified:z48.boolean(),email:z48.string().nullable(),verifyBy:z48.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z49}from"zod";var ProjectDomainStatusSchema,SSLStatusSchema,SSLValidationRecordSchema,SSLValidationErrorSchema,OwnershipVerificationSchema,ProjectDomainSSLDTOSchema,DomainProviderSchema,DomainTypeSchema,RedirectConfigSchema,ProjectDomainDTOSchema,ProjectDomainDTO,ProjectDomainListResponseSchema,ProjectDomainResponseSchema,AddProjectDomainRequestSchema,CheckProjectDomainHostnameReasonSchema,CheckProjectDomainHostnameResponseSchema,DeleteProjectDomainResponseSchema,init_project_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();ProjectDomainStatusSchema=z49.enum(["pending","active","pending_validation","active_redeploying","moved","deleted","pending_deletion","pending_migration","pending_provisioned","test_pending","test_active","test_active_apex","test_blocked","test_failed","provisioned","blocked"]),SSLStatusSchema=z49.enum(["initializing","pending_validation","pending_issuance","pending_deployment","pending_expiration","expired","active","deleted","pending_cleanup","staging_deployment","staging_active","deactivating","inactive","backup_issued","holding_deployment"]),SSLValidationRecordSchema=z49.object({txtName:z49.string().nullable().optional(),txtValue:z49.string().nullable().optional(),httpUrl:z49.string().nullable().optional(),httpBody:z49.string().nullable().optional(),cname:z49.string().nullable().optional(),cnameTarget:z49.string().nullable().optional()}),SSLValidationErrorSchema=z49.object({message:z49.string()}),OwnershipVerificationSchema=z49.object({type:z49.string(),name:z49.string(),value:z49.string()}),ProjectDomainSSLDTOSchema=z49.object({status:z49.string(),method:z49.string().nullable(),type:z49.string().nullable(),validationRecords:z49.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z49.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z49.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z49.enum(["subdomain","apex"]),RedirectConfigSchema=z49.object({type:z49.literal("apex_to_www"),linkedDomainId:z49.string()}).nullable().optional(),ProjectDomainDTOSchema=z49.object({id:z49.string(),hostname:z49.string(),status:z49.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z49.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z49.string(),scdCnameTarget:z49.string().optional(),apexTargets:z49.array(z49.string()),dnsAutoConfigured:z49.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z49.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z49.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z49.object({hostname:z49.hostname().regex(/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,{error:"Invalid hostname"}).refine(value=>!/\.fimo\.site$/i.test(value),{error:"This is a Fimo-owned domain. Edit your built-in URL instead."}),redirectToWww:z49.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z49.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z49.object({available:z49.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z49.object({success:z49.boolean(),hostname:z49.string()}))}});import{z as z50}from"zod";var SUBDOMAIN_REGEX,SubdomainCheckReasonSchema,CheckProjectSubdomainResponseSchema,UpdateProjectSubdomainRequestSchema,UpdateProjectSubdomainErrorReasonSchema,UpdateProjectSubdomainResponseSchema,SubdomainSuggestionsQuerySchema,SubdomainSuggestionsResponseSchema,init_project_subdomain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-subdomain.dto.js"(){"use strict";init_response();SUBDOMAIN_REGEX=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,SubdomainCheckReasonSchema=z50.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z50.object({available:z50.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z50.object({slug:z50.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z50.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z50.object({subdomain:z50.string(),subdomainUpdatedAt:z50.coerce.date()})),SubdomainSuggestionsQuerySchema=z50.object({base:z50.string().max(100).optional(),max:z50.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z50.object({suggestions:z50.array(z50.string())}))}});import{z as z51}from"zod";var ProjectLocaleCoverageSchema,ProjectLocaleStatsItemSchema,ProjectLocaleStatsSchema,ProjectLocaleStatsDTO,ProjectLocaleStatsResponseSchema,AddProjectLocaleRequestSchema,RemoveProjectLocaleParamsSchema,ProjectLocaleMutationSchema,ProjectLocaleMutationDTO,ProjectLocaleMutationResponseSchema,RemoveProjectLocaleSchema,RemoveProjectLocaleDTO,RemoveProjectLocaleResponseSchema,init_project_locale_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-locale.dto.js"(){"use strict";init_create_dto();init_response();ProjectLocaleCoverageSchema=z51.object({translated:z51.number().int().nonnegative(),total:z51.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z51.object({locale:z51.string(),isDefault:z51.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z51.object({defaultLocale:z51.string(),routing:z51.object({strategy:z51.literal("path-prefix"),prefixDefaultLocale:z51.boolean()}),locales:z51.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z51.object({locale:z51.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z51.object({locale:z51.string().min(1).max(40)}),ProjectLocaleMutationSchema=z51.object({locale:z51.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z51.object({locale:z51.string(),entriesDeleted:z51.number().int().nonnegative(),labelsDeleted:z51.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z52}from"zod";function flag(key,description,options={}){return{name:key.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),key,description,type:options.type??"string",required:options.required??!1,...options.defaultValue!==void 0?{defaultValue:options.defaultValue}:{},...options.enumValues?{enumValues:[...options.enumValues]}:{},isArray:options.isArray??!1}}var GENERATION_QUALITIES,GENERATION_ASPECT_RATIOS,GENERATION_TASK_IDS,GenerationQualitySchema,GenerationTaskIdSchema,GENERATION_TASK_MANIFESTS,GenerationTaskEstimateDTOSchema,GenerationTaskEstimateDTO,init_generation_task_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation-task.dto.js"(){"use strict";init_create_dto();GENERATION_QUALITIES=["draft","standard","premium"],GENERATION_ASPECT_RATIOS=["1:1","16:9","9:16","4:3","3:4"],GENERATION_TASK_IDS=["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"],GenerationQualitySchema=z52.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z52.enum(GENERATION_TASK_IDS);__name(flag,"flag");GENERATION_TASK_MANIFESTS=[{id:"image.generate",modality:"image",operation:"generate",displayName:"Generate image",description:"Create an image from a prompt. Quality selects the appropriate generation route.",flags:[flag("prompt","Generation prompt",{required:!0}),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.edit",modality:"image",operation:"edit",displayName:"Edit image",description:"Transform up to five source images using a natural-language instruction.",flags:[flag("prompt","Editing instruction",{required:!0}),flag("images","Source asset id or absolute URL; repeatable up to five times",{required:!0,isArray:!0}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.remove-background",modality:"image",operation:"remove-background",displayName:"Remove image background",description:"Remove the background from one image and return a transparent cutout.",flags:[flag("image","Source asset id or absolute URL",{required:!0})]},{id:"image.upscale",modality:"image",operation:"upscale",displayName:"Upscale image",description:"Increase image resolution while preserving and optionally enhancing detail.",flags:[flag("image","Source asset id or absolute URL",{required:!0}),flag("targetMegapixels","Target resolution in megapixels",{type:"integer",defaultValue:4}),flag("outputFormat","Output image format",{type:"enum",defaultValue:"png",enumValues:["webp","jpg","png"]}),flag("enhanceDetails","Improve fine detail during upscaling",{type:"boolean",defaultValue:!0}),flag("enhanceRealism","Favor photorealistic detail reconstruction",{type:"boolean",defaultValue:!1})]},{id:"video.generate",modality:"video",operation:"generate",displayName:"Generate video",description:"Create a video from text or animate one source image. Loop closes the final frame back to the first.",flags:[flag("prompt","Generation and motion prompt",{required:!0}),flag("image","Optional source asset id or absolute URL"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"16:9",enumValues:GENERATION_ASPECT_RATIOS}),flag("duration","Duration in seconds; loops support 3 to 20 seconds",{type:"integer",defaultValue:5}),flag("includeAudio","Generate audio with the video",{type:"boolean",defaultValue:!1}),flag("loop","Make the final frame return to the source image",{type:"boolean",defaultValue:!1})]},{id:"video.animate",modality:"video",operation:"animate",displayName:"Animate image from video",description:"Apply the motion and camera movement from a source video to a reference image.",flags:[flag("video","Motion source asset id or absolute URL",{required:!0}),flag("image","Subject reference asset id or absolute URL",{required:!0}),flag("prompt","Optional instruction for the animation"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]},{id:"video.replace",modality:"video",operation:"replace",displayName:"Replace subjects in video",description:"Replace people in a source video with one to three reference identities while preserving motion.",flags:[flag("video","Source video asset id or absolute URL",{required:!0}),flag("images","Identity reference asset id or URL; repeatable up to three times",{required:!0,isArray:!0}),flag("prompt","Optional placement instruction"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]}],GenerationTaskEstimateDTOSchema=z52.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z52.number(),credits:z52.number().optional(),billingMode:z52.enum(["fimo-credits","provider-account"]).optional(),confidence:z52.enum(["exact","estimated","metered"]),basis:z52.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z53}from"zod";var GenerateRequestBaseSchema,GenerateRequestDTOSchema,GenerateRequestDTO,GenerateResponseDataSchema,GenerateResponseDTO,GenerateResponseSchema,GenerateErrorSchema,init_generation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation.dto.js"(){"use strict";init_create_dto();init_response();init_asset_dto();init_generation_task_dto();GenerateRequestBaseSchema=z53.object({options:z53.record(z53.string(),z53.unknown()),name:z53.string().optional(),parentId:z53.string().nullable().optional(),altText:z53.string().optional(),caption:z53.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z53.string().min(1).optional(),model:z53.string().min(1).optional()}).superRefine((value,context)=>{!!value.task==!!value.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model",path:["task"]})}),GenerateRequestDTO=createDTO(GenerateRequestDTOSchema),GenerateResponseDataSchema=z53.object({jobId:z53.string(),status:z53.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z53.string().nullable().optional(),credits:z53.number().optional(),costUsd:z53.number().optional(),billingMode:z53.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z53.object({error:z53.string(),code:z53.enum(["unknown-task","unknown-model","options-invalid","source-invalid","task-routing-failed","generation-failed","provider-error","cost-limit-exceeded","cost-estimate-unavailable","unsupported-modality"]),availableTasks:z53.array(GenerationTaskIdSchema).optional(),availableModels:z53.array(z53.string()).optional(),issues:z53.array(z53.unknown()).optional()})}});import{z as z54}from"zod";var FlagTypeSchema,FlagSpecSchema,AssetModelPriceSchema,AssetModelDTOSchema,AssetModelDTO,AssetModelEstimateDTOSchema,AssetModelEstimateDTO,init_asset_model_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset-model.dto.js"(){"use strict";init_create_dto();FlagTypeSchema=z54.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z54.object({name:z54.string(),key:z54.string(),description:z54.string(),type:FlagTypeSchema,required:z54.boolean(),defaultValue:z54.unknown().optional(),enumValues:z54.array(z54.string()).optional(),isArray:z54.boolean()}),AssetModelPriceSchema=z54.object({unitPrice:z54.number(),unit:z54.string(),confidence:z54.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z54.object({id:z54.string(),shortName:z54.string(),provider:z54.string(),source:z54.string(),modality:z54.enum(["image","video","audio"]),tags:z54.array(z54.string()),displayName:z54.string(),description:z54.string(),flags:z54.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z54.object({model:z54.string(),costUsd:z54.number(),credits:z54.number(),billingMode:z54.enum(["fimo-credits","provider-account"]),confidence:z54.enum(["exact","estimated","metered"]),basis:z54.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z55}from"zod";var UserTourDTOSchema,UserTourDTO,UserTourResponseSchema,UserTourListResponseSchema,init_tour_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/tour.dto.js"(){"use strict";init_create_dto();init_response();UserTourDTOSchema=z55.object({tourId:z55.string(),version:z55.string(),status:z55.string(),completedAt:z55.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z55.array(UserTourDTOSchema))}});import{z as z56}from"zod";var SUPPORT_REPORT_CATEGORIES,SupportReportCategorySchema,SUPPORT_REPORT_STATUSES,SupportReportStatusSchema,SupportReportSourceSchema,SupportReportDeliveryStatusSchema,SUPPORT_REPORT_LINK_KINDS,SupportReportLinkKindSchema,SupportReportEventKindSchema,SupportReportActorKindSchema,SupportReportTagSchema,SupportReportHttpUrlSchema,SupportReportContextInputSchema,CreateSupportReportInputSchema,SupportReportListQuerySchema,UpdateSupportReportInputSchema,CreateSupportReportMessageInputSchema,CreateSupportReportLinkInputSchema,SupportReportActorDTOSchema,SupportReportLinkDTOSchema,SupportReportLinkDTO,SupportReportEventDTOSchema,SupportReportEventDTO,SupportReportSummaryDTOSchema,SupportReportSummaryDTO,SupportReportDetailDTOSchema,SupportReportDetailDTO,SupportReportListDTOSchema,SupportReportListDTO,CreateSupportReportResultDTOSchema,CreateSupportReportResultDTO,init_support_report_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/support-report.dto.js"(){"use strict";init_create_dto();SUPPORT_REPORT_CATEGORIES=[{value:"account_billing",label:"Account & billing"},{value:"project_issues",label:"Project issues"},{value:"ai_prompt_output_quality",label:"AI prompt & output quality"},{value:"roles_access_collaboration",label:"Roles, access & collaboration"},{value:"code_technical_questions",label:"Code & technical questions"},{value:"others",label:"Other"}],SupportReportCategorySchema=z56.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z56.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z56.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z56.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z56.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z56.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z56.enum(["user","agent","system"]),SupportReportTagSchema=z56.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z56.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z56.object({organization:z56.object({id:z56.string().trim().min(1).max(255),name:z56.string().trim().max(240).optional()}),project:z56.object({id:z56.uuid(),name:z56.string().trim().max(240).optional(),createdAt:z56.coerce.date().optional()}).optional(),environment:z56.string().trim().max(255).optional(),clientVersion:z56.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z56.object({message:z56.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z56.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z56.string().trim().max(200).optional(),limit:z56.coerce.number().int().min(1).max(100).default(50),offset:z56.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z56.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z56.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z56.uuid().nullable().optional(),note:z56.string().trim().min(1).max(2e4).optional()}).refine(input=>Object.values(input).some(value=>value!==void 0),{message:"At least one report change is required"}),CreateSupportReportMessageInputSchema=z56.object({message:z56.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z56.object({kind:SupportReportLinkKindSchema,label:z56.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z56.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z56.object({kind:SupportReportActorKindSchema,id:z56.string().nullable(),name:z56.string().nullable()}),SupportReportLinkDTOSchema=z56.object({id:z56.uuid(),kind:SupportReportLinkKindSchema,label:z56.string(),url:SupportReportHttpUrlSchema,externalId:z56.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z56.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z56.object({id:z56.uuid(),kind:SupportReportEventKindSchema,body:z56.string().nullable(),metadata:z56.record(z56.string(),z56.unknown()),actor:SupportReportActorDTOSchema,createdAt:z56.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z56.object({id:z56.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z56.array(z56.string()),source:SupportReportSourceSchema,message:z56.string(),reporter:z56.object({id:z56.string().nullable(),name:z56.string().nullable(),email:z56.string().nullable()}),organization:z56.object({id:z56.string().nullable(),name:z56.string()}),project:z56.object({id:z56.uuid().nullable(),name:z56.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z56.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z56.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z56.string().nullable(),deliveredAt:z56.coerce.date().nullable()}).nullable(),duplicateOfReportId:z56.uuid().nullable(),resolvedAt:z56.coerce.date().nullable(),createdAt:z56.coerce.date(),updatedAt:z56.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z56.string().nullable(),clientVersion:z56.string().nullable(),links:z56.array(SupportReportLinkDTOSchema),events:z56.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z56.object({reports:z56.array(SupportReportSummaryDTOSchema),total:z56.number().int().nonnegative(),statusCounts:z56.object({new:z56.number().int().nonnegative(),in_progress:z56.number().int().nonnegative(),waiting:z56.number().int().nonnegative(),resolved:z56.number().int().nonnegative(),duplicate:z56.number().int().nonnegative(),irrelevant:z56.number().int().nonnegative(),ignored:z56.number().int().nonnegative()}),limit:z56.number().int().positive(),offset:z56.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z56.object({id:z56.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z56.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z57}from"zod";var OPS_RECENT_CHAT_MAX_WINDOW_MS,OpsChatTimestampInputSchema,OpsRecentChatInputSchema,OpsRecentChatMessageSchema,OpsRecentChatResponseSchema,OpsRecentChatResponseDTO,init_ops_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-chat.dto.js"(){"use strict";init_ops();init_create_dto();OPS_RECENT_CHAT_MAX_WINDOW_MS=10080*60*1e3,OpsChatTimestampInputSchema=z57.iso.datetime({offset:!0}).pipe(z57.coerce.date()),OpsRecentChatInputSchema=z57.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z57.string().trim().min(1).max(255).optional(),limit:z57.coerce.number().int().min(1).max(200).default(100),cursor:z57.string().trim().min(1).max(2e3).optional(),slim:z57.boolean().default(!0),reason:z57.string().trim().min(1).max(1e3)}).refine(input=>input.from<=(input.to??new Date),{message:"from must be before or equal to to",path:["from"]}).refine(input=>(input.to??new Date).getTime()-input.from.getTime()<=OPS_RECENT_CHAT_MAX_WINDOW_MS,{message:"recent chat window cannot exceed 7 days",path:["from"]}).refine(input=>!input.cursor||!!input.to,{message:"to is required when continuing with a cursor",path:["to"]}),OpsRecentChatMessageSchema=z57.object({id:z57.string(),messageId:z57.string(),env:z57.string(),versionId:z57.string().nullable(),userId:z57.string().nullable(),role:z57.string(),parts:z57.array(z57.record(z57.string(),z57.unknown())),metadata:z57.object({status:z57.string().optional(),traceUrl:z57.string().optional(),externalFileChanges:z57.array(z57.unknown()).optional()}),stats:z57.object({toolCount:z57.number().int().nonnegative(),failedToolCount:z57.number().int().nonnegative()}),createdAt:z57.iso.datetime({offset:!0}),project:z57.object({id:z57.string(),name:z57.string(),displayName:z57.string().nullable(),organizationId:z57.string().nullable()})}),OpsRecentChatResponseSchema=z57.object({target:z57.object({backendProfile:OpsBackendProfileSchema,projectEnv:z57.string().nullable()}),window:z57.object({from:z57.iso.datetime({offset:!0}),to:z57.iso.datetime({offset:!0})}),messages:z57.object({items:z57.array(OpsRecentChatMessageSchema),nextCursor:z57.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z58}from"zod";function createAgentRunWebhookEventDataSchema(status){return z58.object({run:z58.object({id:z58.string(),agentName:z58.string(),trigger:z58.string(),status:z58.literal(status),startedAt:z58.string().nullable(),finishedAt:z58.string().nullable(),reason:z58.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEntryBatchWindowSecondsSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AgentReviewRequestedWebhookEventDataSchema,AgentReviewResolvedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,MediaGeneratedWebhookEventDataSchema,MediaProcessingFailedWebhookEventDataSchema,DomainCreatedWebhookEventDataSchema,DomainDeletedWebhookEventDataSchema,LabelChangedWebhookEventDataSchema,LocaleCreatedWebhookEventDataSchema,LocaleDefaultChangedWebhookEventDataSchema,LocaleDeletedWebhookEventDataSchema,EnvironmentCreatedWebhookEventDataSchema,EnvironmentDeletedWebhookEventDataSchema,EnvironmentMergedWebhookEventDataSchema,EnvironmentRestoredWebhookEventDataSchema,WEBHOOK_EVENT_DATA_SCHEMAS,WebhookEventFamilySchema,WebhookDestinationKindSchema,WebhookHeaderValueInputSchema,WebhookHeaderInputSchema,WebhookHeaderDTOSchema,WebhookFilterSchema,JsonValueSchema,CreateProjectWebhookRequestSchema,UpdateProjectWebhookRequestSchema,TestProjectWebhookRequestSchema,WebhookDeliveryStatusSchema,ProjectWebhookDTOSchema,ProjectWebhookDTO,WebhookDeliveryDTOSchema,WebhookDeliveryDTO,WebhookDeliveriesPageSchema,WebhookDeliveryAttemptDTOSchema,WebhookDeliveryAttemptDTO,ProjectWebhookResponseSchema,ProjectWebhooksListResponseSchema,WebhookDeliveriesListResponseSchema,WebhookDeliveryAttemptsListResponseSchema,init_webhook_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/webhook.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();init_env_status_dto();init_project_domain_dto();WEBHOOK_EVENT_TYPES=["entry.changed","form.submitted","publish.started","publish.succeeded","publish.failed","publish.unpublished","agent.run.started","agent.run.completed","agent.run.failed","agent.run.cancelled","agent.review.requested","agent.review.resolved","analytics.report_ready","media.uploaded","media.updated","media.deleted","media.generated","media.processing_failed","domain.created","domain.deleted","label.changed","locale.created","locale.default_changed","locale.deleted","environment.created","environment.deleted","environment.merged","environment.restored"],WebhookEventTypeSchema=z58.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z58.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z58.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z58.enum(["main","all"]),WebhookEntryBatchWindowSecondsSchema=z58.union([z58.literal(0),z58.literal(5),z58.literal(30),z58.literal(60)]),EntryChangedWebhookEventDataSchema=z58.object({reason:WebhookEntryChangeReasonSchema,operationId:z58.string().optional(),batch:z58.object({index:z58.number().int().positive(),total:z58.number().int().positive()}).optional(),changes:z58.array(z58.object({action:WebhookEntryChangeActionSchema,contentType:z58.string(),id:z58.string(),documentId:z58.string(),locale:z58.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z58.object({form:z58.object({id:z58.string(),label:z58.string()}),submission:z58.object({id:z58.string(),data:z58.record(z58.string(),z58.unknown()),submittedAt:z58.string()})}),PublishStartedWebhookEventDataSchema=z58.object({publication:z58.object({status:z58.literal("publishing"),startedAt:z58.string()})}),PublishSucceededWebhookEventDataSchema=z58.object({publication:z58.object({status:z58.literal("published"),url:z58.string(),publishedAt:z58.string(),firstPublish:z58.boolean()})}),PublishFailedWebhookEventDataSchema=z58.object({publication:z58.object({status:z58.literal("failed"),reason:z58.string()})}),PublishUnpublishedWebhookEventDataSchema=z58.object({publication:z58.object({previousUrl:z58.string(),unpublishedAt:z58.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z58.object({review:z58.object({id:z58.string(),runId:z58.string(),agentName:z58.string(),classification:z58.string(),summary:z58.string(),reasons:z58.array(z58.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z58.object({review:z58.object({id:z58.string(),runId:z58.string(),agentName:z58.string(),resolution:z58.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z58.object({report:z58.object({weekStart:z58.string(),weekEnd:z58.string(),pageviews:z58.number(),visitors:z58.number(),previousPageviews:z58.number(),previousVisitors:z58.number()})}),MediaAssetWebhookEventDataSchema=z58.object({id:z58.string().nullable(),name:z58.string().nullable(),type:z58.string(),mimeType:z58.string().nullable(),fileSize:z58.number().nullable()}),MediaUploadedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.enum(["updated","moved","analysis"]),analysis:z58.object({category:z58.string(),status:z58.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.literal("generated"),generation:z58.object({model:z58.string(),mode:z58.string()})}),MediaProcessingFailedWebhookEventDataSchema=z58.object({asset:MediaAssetWebhookEventDataSchema,operation:z58.enum(["analysis","generation"]),failure:z58.object({code:z58.string()})}),DomainCreatedWebhookEventDataSchema=z58.object({domain:z58.object({id:z58.string(),hostname:z58.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z58.object({domain:z58.object({id:z58.string(),hostname:z58.string()})}),LabelChangedWebhookEventDataSchema=z58.object({changes:z58.array(z58.object({action:z58.enum(["created","updated","deleted"]),key:z58.string(),locale:z58.string(),value:z58.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z58.object({locale:z58.object({code:z58.string(),isDefault:z58.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z58.object({locale:z58.object({code:z58.string(),previousCode:z58.string()})}),LocaleDeletedWebhookEventDataSchema=z58.object({locale:z58.object({code:z58.string(),entriesDeleted:z58.number().int().nonnegative(),labelsDeleted:z58.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z58.object({environment:z58.object({name:EnvSchema,parent:EnvSchema})}),EnvironmentDeletedWebhookEventDataSchema=z58.object({environment:z58.object({name:EnvSchema})}),EnvironmentMergedWebhookEventDataSchema=z58.object({merge:z58.object({id:z58.string(),from:EnvSchema,to:EnvSchema,applied:z58.array(z58.object({surface:SurfaceNameSchema,count:z58.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z58.object({environment:z58.object({name:EnvSchema}),version:z58.object({id:z58.string(),name:z58.string()})}),WEBHOOK_EVENT_DATA_SCHEMAS={"entry.changed":EntryChangedWebhookEventDataSchema,"form.submitted":FormSubmittedWebhookEventDataSchema,"publish.started":PublishStartedWebhookEventDataSchema,"publish.succeeded":PublishSucceededWebhookEventDataSchema,"publish.failed":PublishFailedWebhookEventDataSchema,"publish.unpublished":PublishUnpublishedWebhookEventDataSchema,"agent.run.started":createAgentRunWebhookEventDataSchema("running"),"agent.run.completed":createAgentRunWebhookEventDataSchema("completed"),"agent.run.failed":createAgentRunWebhookEventDataSchema("failed"),"agent.run.cancelled":createAgentRunWebhookEventDataSchema("cancelled"),"agent.review.requested":AgentReviewRequestedWebhookEventDataSchema,"agent.review.resolved":AgentReviewResolvedWebhookEventDataSchema,"analytics.report_ready":AnalyticsReportReadyWebhookEventDataSchema,"media.uploaded":MediaUploadedWebhookEventDataSchema,"media.updated":MediaUpdatedWebhookEventDataSchema,"media.deleted":MediaDeletedWebhookEventDataSchema,"media.generated":MediaGeneratedWebhookEventDataSchema,"media.processing_failed":MediaProcessingFailedWebhookEventDataSchema,"domain.created":DomainCreatedWebhookEventDataSchema,"domain.deleted":DomainDeletedWebhookEventDataSchema,"label.changed":LabelChangedWebhookEventDataSchema,"locale.created":LocaleCreatedWebhookEventDataSchema,"locale.default_changed":LocaleDefaultChangedWebhookEventDataSchema,"locale.deleted":LocaleDeletedWebhookEventDataSchema,"environment.created":EnvironmentCreatedWebhookEventDataSchema,"environment.deleted":EnvironmentDeletedWebhookEventDataSchema,"environment.merged":EnvironmentMergedWebhookEventDataSchema,"environment.restored":EnvironmentRestoredWebhookEventDataSchema},WebhookEventFamilySchema=z58.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z58.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z58.discriminatedUnion("source",[z58.object({source:z58.literal("literal"),value:z58.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z58.object({source:z58.literal("secret"),key:z58.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z58.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z58.object({name:z58.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z58.object({name:z58.string(),source:z58.enum(["literal","secret"]),secretKey:z58.string().nullable(),secretPrefix:z58.string().nullable(),configured:z58.literal(!0)}),WebhookFilterSchema=z58.object({environment:WebhookEnvironmentScopeSchema.optional(),formId:z58.string().min(1).max(255).optional(),agentName:z58.string().min(1).max(120).optional(),mediaType:z58.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z58.string().min(1).max(255).optional(),locale:z58.string().min(1).max(120).optional()}),JsonValueSchema=z58.lazy(()=>z58.union([z58.string(),z58.number(),z58.boolean(),z58.null(),z58.array(JsonValueSchema),z58.record(z58.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z58.object({name:z58.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z58.url(),enabled:z58.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z58.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z58.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z58.object({name:z58.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z58.url().optional(),enabled:z58.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z58.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z58.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z58.object({eventType:WebhookEventTypeSchema.optional(),data:z58.record(z58.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z58.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z58.uuid(),name:z58.string(),eventType:WebhookEventTypeSchema,enabled:z58.boolean(),destination:z58.object({host:z58.string(),maskedUrl:z58.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z58.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z58.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z58.coerce.date().nullable(),deliveryStats24h:z58.object({succeeded:z58.number().int().nonnegative(),failed:z58.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z58.uuid(),projectId:z58.uuid(),env:EnvSchema,eventId:z58.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z58.number().int().positive(),test:z58.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z58.number().int().nonnegative(),responseStatus:z58.number().int().nullable(),lastErrorCode:z58.string().nullable(),lastErrorMessage:z58.string().nullable(),payloadAvailable:z58.boolean(),destination:z58.object({host:z58.string(),maskedUrl:z58.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z58.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z58.string().nullable(),qstashMessageId:z58.string().nullable(),deliveredAt:z58.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z58.object({items:z58.array(WebhookDeliveryDTOSchema),pagination:z58.object({page:z58.number().int().positive(),limit:z58.number().int().positive(),total:z58.number().int().nonnegative(),totalPages:z58.number().int().positive(),hasMore:z58.boolean()}),stats:z58.object({total:z58.number().int().nonnegative(),succeeded:z58.number().int().nonnegative(),failed:z58.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z58.object({id:z58.uuid(),deliveryId:z58.uuid(),attempt:z58.number().int().positive(),status:z58.enum(["delivering","succeeded","failed"]),responseStatus:z58.number().int().nullable(),durationMs:z58.number().int().nonnegative(),responseExcerpt:z58.string().nullable(),errorCode:z58.string().nullable(),errorMessage:z58.string().nullable(),createdAt:z58.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z58.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z58.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z59}from"zod";var SubscriptionStatusSchema,CreditBalanceBreakdownDTOSchema,CreditBalanceBreakdownDTO,SubscriptionPlanDTOSchema,SubscriptionPlanDTO,SubscriptionPaymentMethodDTOSchema,SubscriptionPaymentMethodDTO,SubscriptionPricingDTOSchema,SubscriptionPricingDTO,SubscriptionDetailsDTOSchema,SubscriptionDetailsDTO,CreditAlertDTOSchema,CreditAlertDTO,PlanAllocationDTOSchema,PlanAllocationDTO,LatestCancellationDTOSchema,LatestCancellationDTO,OrganizationSubscriptionDTOSchema,OrganizationSubscriptionDTO,BaseCreditTopupRequestSchema,FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema,CreditTopupRequestDTOSchema,CreditTopupRequestDTO,CreditTopupResponseDTOSchema,CreditTopupResponseDTO,init_subscription_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/subscription.dto.js"(){"use strict";init_common();init_create_dto();init_billing_dto();SubscriptionStatusSchema=z59.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z59.object({total:z59.number(),base:z59.number(),purchases:z59.number(),awards:z59.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z59.object({id:z59.string(),name:z59.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z59.object({type:z59.string(),brand:z59.string().nullable(),last4:z59.string().nullable(),expirationDate:z59.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z59.object({currency:z59.string(),nextPaymentAmount:z59.number().nullable(),nextPaymentAt:z59.string().nullable(),billingInterval:z59.string().nullable(),totalAmount:z59.number().nullable(),discountAmount:z59.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z59.object({id:z59.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z59.string().nullable(),currentPeriodEndsAt:z59.string().nullable(),renewsAt:z59.string().nullable(),cancelAt:z59.string().nullable(),renewAutomatically:z59.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z59.object({type:z59.enum(["low_balance","critical_balance","approaching_limit"]),message:z59.string(),estimatedPromptsRemaining:z59.number().nullable(),avgCostPerPrompt:z59.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z59.object({monthlyCredits:z59.number().nullable(),usedThisPeriod:z59.number(),remainingThisPeriod:z59.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z59.object({organizationId:z59.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z59.string().nullable(),tenureDays:z59.number().int().nonnegative(),capturedAt:z59.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z59.object({hasSubscription:z59.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z59.number().nullable(),alerts:z59.array(CreditAlertDTOSchema),portalUrl:z59.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z59.object({creditCount:z59.number().int().positive(),expiresAt:z59.string().datetime().nullable().optional(),message:z59.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z59.literal("free"),amountCents:z59.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z59.literal("purchase"),amountCents:z59.number().int().positive()}),CreditTopupRequestDTOSchema=z59.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z59.object({success:z59.boolean(),transactionId:z59.string().nullable(),newBalance:z59.number(),creditCount:z59.number(),type:z59.enum(["free","purchase"]),invoiceId:z59.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z60}from"zod";var UsageSummaryDTOSchema,UsageSummaryDTO,UsageByProjectDTOSchema,UsageByProjectDTO,UsageByUserDTOSchema,UsageByUserDTO,UsageTimelineItemDTOSchema,UsageTimelineItemDTO,UsageByUserForProjectDTOSchema,UsageByUserForProjectDTO,ProjectUsageDetailDTOSchema,ProjectUsageDetailDTO,OrganizationUsageDTOSchema,OrganizationUsageDTO,init_usage_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage.dto.js"(){"use strict";init_create_dto();UsageSummaryDTOSchema=z60.object({totalCredits:z60.number(),totalCostUsd:z60.number(),totalMessages:z60.number(),avgCostPerMessage:z60.number(),periodStart:z60.string().nullable(),periodEnd:z60.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z60.object({projectId:z60.string(),projectName:z60.string(),projectDisplayName:z60.string().nullable(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z60.object({userId:z60.string(),userName:z60.string().nullable(),userEmail:z60.string().email().nullable(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z60.object({date:z60.string(),credits:z60.number(),costUsd:z60.number(),messages:z60.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z60.object({userId:z60.string(),userName:z60.string().nullable(),userEmail:z60.string().email().nullable(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z60.object({projectId:z60.string(),projectName:z60.string(),projectDisplayName:z60.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z60.array(UsageByUserForProjectDTOSchema),timeline:z60.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z60.object({summary:UsageSummaryDTOSchema,byProject:z60.array(UsageByProjectDTOSchema),byUser:z60.array(UsageByUserDTOSchema),timeline:z60.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z61}from"zod";var TimeRangePresetSchema,SortOrderSchema,UsageAnalyticsQuerySchema,UsageOverviewSummaryDTOSchema,UsageOverviewSummaryDTO,UsageTimelinePointDTOSchema,UsageTimelinePointDTO,OrganizationUsageRowDTOSchema,OrganizationUsageRowDTO,UserUsageRowDTOSchema,UserUsageRowDTO,ProjectUsageRowDTOSchema,ProjectUsageRowDTO,UsageDistributionItemDTOSchema,UsageDistributionItemDTO,UsageHeatmapPointDTOSchema,UsageHeatmapPointDTO,UsageOverviewResponseDTOSchema,UsageOverviewResponseDTO,UsagePaginationDTOSchema,UsagePaginationDTO,UsageByOrganizationResponseDTOSchema,UsageByOrganizationResponseDTO,ExtendedUserUsageRowDTOSchema,ExtendedUserUsageRowDTO,UsageByUserResponseDTOSchema,UsageByUserResponseDTO,ExtendedProjectUsageRowDTOSchema,ExtendedProjectUsageRowDTO,UsageByProjectResponseDTOSchema,UsageByProjectResponseDTO,ExportFormatSchema,UsageExportQuerySchema,PeekUsageMetricsDTOSchema,PeekUsageMetricsDTO,OrganizationPeekDTOSchema,OrganizationPeekDTO,UserPeekDTOSchema,UserPeekDTO,ProjectPeekDTOSchema,ProjectPeekDTO,init_usage_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage-analytics.dto.js"(){"use strict";init_create_dto();TimeRangePresetSchema=z61.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z61.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z61.object({startDate:z61.string().optional(),endDate:z61.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z61.coerce.number().int().positive().default(1),limit:z61.coerce.number().int().positive().max(100).default(20),sortBy:z61.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z61.string().optional()}),UsageOverviewSummaryDTOSchema=z61.object({totalCredits:z61.number(),totalCostUsd:z61.number(),totalMessages:z61.number(),avgCostPerMessage:z61.number(),avgCreditsPerMessage:z61.number(),periodStart:z61.string(),periodEnd:z61.string(),creditsChange:z61.number().nullable(),costChange:z61.number().nullable(),messagesChange:z61.number().nullable()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z61.object({date:z61.string(),credits:z61.number(),costUsd:z61.number(),messages:z61.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z61.object({organizationId:z61.string(),organizationName:z61.string(),credits:z61.number(),costUsd:z61.number(),messages:z61.number(),percentage:z61.number(),userCount:z61.number(),projectCount:z61.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z61.object({userId:z61.string(),userName:z61.string().nullable(),userEmail:z61.string().nullable(),userImage:z61.string().nullable(),organizationId:z61.string().nullable(),organizationName:z61.string().nullable(),credits:z61.number(),costUsd:z61.number(),messages:z61.number(),percentage:z61.number(),projectCount:z61.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z61.object({projectId:z61.string(),projectName:z61.string(),projectDisplayName:z61.string().nullable(),organizationId:z61.string(),organizationName:z61.string(),credits:z61.number(),costUsd:z61.number(),messages:z61.number(),percentage:z61.number(),userCount:z61.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z61.object({id:z61.string(),name:z61.string(),value:z61.number(),percentage:z61.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z61.object({day:z61.number(),hour:z61.number(),value:z61.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z61.object({summary:UsageOverviewSummaryDTOSchema,timeline:z61.array(UsageTimelinePointDTOSchema),topOrganizations:z61.array(OrganizationUsageRowDTOSchema),topUsers:z61.array(UserUsageRowDTOSchema),topProjects:z61.array(ProjectUsageRowDTOSchema),creditDistribution:z61.array(UsageDistributionItemDTOSchema),heatmap:z61.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z61.object({page:z61.number(),limit:z61.number(),totalItems:z61.number(),totalPages:z61.number(),hasMore:z61.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z61.object({organizations:z61.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z61.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z61.object({users:z61.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z61.string(),ownerName:z61.string().nullable(),ownerEmail:z61.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z61.object({projects:z61.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z61.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z61.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z61.object({credits:z61.number(),costUsd:z61.number(),messages:z61.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z61.object({id:z61.string(),name:z61.string(),createdAt:z61.string(),memberCount:z61.number(),projectCount:z61.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z61.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z61.object({id:z61.string(),name:z61.string().nullable(),email:z61.string(),image:z61.string().nullable(),createdAt:z61.string(),organizationCount:z61.number(),projectCount:z61.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z61.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z61.object({id:z61.string(),name:z61.string(),displayName:z61.string().nullable(),createdAt:z61.string(),organizationId:z61.string(),organizationName:z61.string(),ownerId:z61.string(),ownerName:z61.string().nullable(),ownerEmail:z61.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z61.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z62}from"zod";var SandboxProcessStatusSchema,PresetSandboxCommandSchema,ExecuteSandboxCommandRequestDTOSchema,ExecuteSandboxCommandRequestDTO,SandboxProcessInfoDTOSchema,SandboxProcessInfoDTO,SandboxProcessInfoResponseSchema,SandboxProcessListDTOSchema,SandboxProcessListDTO,SandboxProcessListResponseSchema,ExecuteSandboxCommandResponseDTOSchema,ExecuteSandboxCommandResponseDTO,PresetCommandResponseDTOSchema,PresetCommandResponseDTO,PresetCommandResponseSchema,init_sandbox_command_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/sandbox-command.dto.js"(){"use strict";init_env();init_create_dto();init_response();SandboxProcessStatusSchema=z62.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z62.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z62.object({command:z62.string().min(1).max(1e4),cwd:z62.string().optional(),projectEnv:EnvSchema.optional(),env:z62.record(z62.string(),z62.string()).optional(),name:z62.string().optional(),waitForCompletion:z62.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z62.object({identifier:z62.string(),status:SandboxProcessStatusSchema,command:z62.string().optional(),startedAt:z62.string().optional(),exitCode:z62.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z62.object({processes:z62.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z62.object({processId:z62.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z62.object({success:z62.boolean(),message:z62.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z63}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common();init_attachments();init_env();init_realtime();init_references();init_content_fields();init_audit_log();init_ops();init_project_dto();init_project_env_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_activation_dto();init_agent_list_item_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_audit_log_dto();init_env_status_dto();init_env_diff_summary_dto();init_project_analytics_dto();init_project_access_dto();init_project_invite_dto();init_publication_dto();init_sandbox_dto();init_organization_dto();init_billing_dto();init_payment_method_dto();init_user_dto();init_content_dto();init_unique_conflict_dto();init_schema_transition_rejected_dto();init_cms_display_defaults_dto();init_asset_dto();init_translation_dto();init_document_dto();init_chat_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_webhook_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto()}});import{execFile as execFile2}from"node:child_process";import{promisify as promisify2}from"node:util";async function runGit(args,cwd){let{stdout}=await execFileAsync2("git",args,{cwd});return stdout.trim()}async function isGitRepo(cwd){try{return await runGit(["rev-parse","--is-inside-work-tree"],cwd),!0}catch{return!1}}async function hasUncommittedChanges(cwd){return(await runGit(["status","--porcelain"],cwd)).length>0}async function cloneRepo(args){await execFileAsync2("git",["clone","--branch",args.branch,"--single-branch",args.url,args.targetDir])}function isMissingRemoteBranch(error){let stderr=extractStderr(error).toLowerCase();return stderr.includes("remote branch")&&stderr.includes("not found")}async function remoteHasBranch(remoteUrl,branch){let{stdout}=await execFileAsync2("git",["ls-remote","--heads",remoteUrl,branch]);return stdout.trim().length>0}async function currentBranch(cwd){return runGit(["rev-parse","--abbrev-ref","HEAD"],cwd)}async function currentTagOrNull(cwd){try{return await runGit(["describe","--tags","--exact-match","HEAD"],cwd)||null}catch{return null}}function isReleaseTag(tag){return tag?/^release\/.+/.test(tag):!1}function classifyPushError(error){let stderr=extractStderr(error),lower=stderr.toLowerCase();return lower.includes("invalid or expired token")||lower.includes("expired token")||lower.includes("invalid token")||lower.includes("could not obtain git credentials")||lower.includes("not signed in")?{kind:"auth",stderr}:lower.includes("remote rejected")||lower.includes("protected")||lower.includes("no-push")||lower.includes("push declined")||lower.includes("not allowed to push")||lower.includes("permission to push")||lower.includes("forbidden")||lower.includes("403")?{kind:"protected",stderr}:lower.includes("non-fast-forward")||lower.includes("rejected")||lower.includes("fetch first")||lower.includes("updates were rejected")?{kind:"non-fast-forward",stderr}:lower.includes("authentication")||lower.includes("permission denied")?{kind:"auth",stderr}:lower.includes("could not resolve host")||lower.includes("timed out")||lower.includes("connection")?{kind:"network",stderr}:{kind:"unknown",stderr}}function extractStderr(error){if(error&&typeof error=="object"&&"stderr"in error){let value=error.stderr;if(typeof value=="string")return value;if(Buffer.isBuffer(value))return value.toString("utf8")}return error instanceof Error?error.message:String(error)}var execFileAsync2,init_git=__esm({"src/cli/utils/git.ts"(){execFileAsync2=promisify2(execFile2);__name(runGit,"runGit");__name(isGitRepo,"isGitRepo");__name(hasUncommittedChanges,"hasUncommittedChanges");__name(cloneRepo,"cloneRepo");__name(isMissingRemoteBranch,"isMissingRemoteBranch");__name(remoteHasBranch,"remoteHasBranch");__name(currentBranch,"currentBranch");__name(currentTagOrNull,"currentTagOrNull");__name(isReleaseTag,"isReleaseTag");__name(classifyPushError,"classifyPushError");__name(extractStderr,"extractStderr")}});function projectSettingsFromEnv(){let projectId=process.env.FIMO_PROJECT_ID?.trim();return projectId?{projectId,organizationId:process.env.FIMO_ORGANIZATION_ID?.trim()??"",name:process.env.FIMO_PROJECT_NAME?.trim()??projectId,apiUrl:process.env.FIMO_API_URL?.trim()??loadConfig().apiUrl}:null}async function resolveEnvFromGit(cwd){if(!await isGitRepo(cwd))return null;try{let tag=await currentTagOrNull(cwd);if(isReleaseTag(tag))return{env:"prod",source:"tag",readOnly:!0};let branch=await currentBranch(cwd);return!branch||branch==="HEAD"||!isValidEnv(branch)?null:{env:branch,source:"branch"}}catch{return null}}async function getProjectContext(opts={}){let cwd=resolveProjectCwd(opts.cwd),settings;try{settings=loadProjectSettings(cwd)}catch{let fromEnv=projectSettingsFromEnv();if(!fromEnv)throw new NotInProjectError;settings=fromEnv}let env,source,readOnly=!1;if(opts.envOverride!==void 0){if(!isValidEnv(opts.envOverride))throw new InvalidEnvOverrideError(opts.envOverride);env=opts.envOverride,source="flag"}else{let fromGit=await resolveEnvFromGit(cwd);if(fromGit)env=fromGit.env,source=fromGit.source,readOnly=fromGit.readOnly===!0;else{if(opts.requireBranch)throw await isGitRepo(cwd)?new GitBranchUndetectedError:new NotInProjectError;env=DEFAULT_ENV,source="fallback"}}if(opts.api&&env!=="prod")try{let names=(await opts.api.listEnvs(settings.projectId)).map(e=>e.env);if(!names.includes(env)&&source==="flag")throw new EnvNotFoundError(env,names)}catch(err){if(err instanceof EnvNotFoundError)throw err}return{projectId:settings.projectId,organizationId:settings.organizationId,name:settings.name,apiUrl:settings.apiUrl,env,source,readOnly:readOnly||void 0}}function envSourceBanner(ctx){let sourceHint=ctx.source==="flag"?"--env":ctx.source==="branch"?"git branch":ctx.source==="tag"?"git tag":"default",ro=ctx.readOnly?" \xB7 read-only":"";return`\u2192 env: ${ctx.env} (from ${sourceHint}${ro})`}function envOverrideFromCommand(cmd){let cur=cmd??void 0;for(;cur;){let env=cur.opts().env;if(typeof env=="string"&&env.length>0)return env;cur=cur.parent??null}}async function bootstrapProjectCommand(options={},cmd,bootstrapOpts={}){let envOverride2=envOverrideFromCommand(cmd),baseApi=new FimoApiClient(loadConfig()),ctx=await getProjectContext({cwd:options.cwd,envOverride:envOverride2,requireBranch:bootstrapOpts.requireBranch,api:baseApi});if(!bootstrapOpts.quiet){let{currentMode:currentMode2}=await Promise.resolve().then(()=>(init_dist(),dist_exports));currentMode2().format==="pretty"&&process.stderr.write(`${envSourceBanner(ctx)}
|
|
196
196
|
`)}if(bootstrapOpts.refuseReadOnly&&ctx.readOnly)throw new Error(`Refusing to run a mutating command against read-only env '${ctx.env}'. Switch off the release/* tag or pass --env <writable-env>.`);return{ctx,api:baseApi.withEnv(ctx.env)}}var NotInProjectError,InvalidEnvOverrideError,EnvNotFoundError,GitBranchUndetectedError,init_project_context=__esm({"src/cli/utils/project-context.ts"(){init_esm();init_api();init_config();init_git();init_project();NotInProjectError=class extends Error{static{__name(this,"NotInProjectError")}constructor(){super("You are not in a Fimo project. Run `fimo create` to start one, or cd into a linked project."),this.name="NotInProjectError"}};__name(projectSettingsFromEnv,"projectSettingsFromEnv");InvalidEnvOverrideError=class extends Error{static{__name(this,"InvalidEnvOverrideError")}value;constructor(value){super(`--env value '${value}' is invalid. Env names must match /^[a-zA-Z0-9._/-]+$/, not start with '-', and be \u2264255 chars.`),this.name="InvalidEnvOverrideError",this.value=value}},EnvNotFoundError=class extends Error{static{__name(this,"EnvNotFoundError")}env;knownEnvs;constructor(env,knownEnvs){super(`Env '${env}' not found on the server. Known envs: ${knownEnvs.length>0?knownEnvs.join(", "):"(none yet)"}.`),this.name="EnvNotFoundError",this.env=env,this.knownEnvs=knownEnvs}},GitBranchUndetectedError=class extends Error{static{__name(this,"GitBranchUndetectedError")}constructor(){super("In a git repository but no branch could be detected (detached HEAD or empty repo). Pass --env <name> to target an env explicitly."),this.name="GitBranchUndetectedError"}};__name(resolveEnvFromGit,"resolveEnvFromGit");__name(getProjectContext,"getProjectContext");__name(envSourceBanner,"envSourceBanner");__name(envOverrideFromCommand,"envOverrideFromCommand");__name(bootstrapProjectCommand,"bootstrapProjectCommand")}});var isAmbiguous,isFullWidth,isWide,init_utils=__esm({"../../node_modules/.pnpm/fast-string-truncated-width@1.2.1/node_modules/fast-string-truncated-width/dist/utils.js"(){isAmbiguous=__name(x=>x===161||x===164||x===167||x===168||x===170||x===173||x===174||x>=176&&x<=180||x>=182&&x<=186||x>=188&&x<=191||x===198||x===208||x===215||x===216||x>=222&&x<=225||x===230||x>=232&&x<=234||x===236||x===237||x===240||x===242||x===243||x>=247&&x<=250||x===252||x===254||x===257||x===273||x===275||x===283||x===294||x===295||x===299||x>=305&&x<=307||x===312||x>=319&&x<=322||x===324||x>=328&&x<=331||x===333||x===338||x===339||x===358||x===359||x===363||x===462||x===464||x===466||x===468||x===470||x===472||x===474||x===476||x===593||x===609||x===708||x===711||x>=713&&x<=715||x===717||x===720||x>=728&&x<=731||x===733||x===735||x>=768&&x<=879||x>=913&&x<=929||x>=931&&x<=937||x>=945&&x<=961||x>=963&&x<=969||x===1025||x>=1040&&x<=1103||x===1105||x===8208||x>=8211&&x<=8214||x===8216||x===8217||x===8220||x===8221||x>=8224&&x<=8226||x>=8228&&x<=8231||x===8240||x===8242||x===8243||x===8245||x===8251||x===8254||x===8308||x===8319||x>=8321&&x<=8324||x===8364||x===8451||x===8453||x===8457||x===8467||x===8470||x===8481||x===8482||x===8486||x===8491||x===8531||x===8532||x>=8539&&x<=8542||x>=8544&&x<=8555||x>=8560&&x<=8569||x===8585||x>=8592&&x<=8601||x===8632||x===8633||x===8658||x===8660||x===8679||x===8704||x===8706||x===8707||x===8711||x===8712||x===8715||x===8719||x===8721||x===8725||x===8730||x>=8733&&x<=8736||x===8739||x===8741||x>=8743&&x<=8748||x===8750||x>=8756&&x<=8759||x===8764||x===8765||x===8776||x===8780||x===8786||x===8800||x===8801||x>=8804&&x<=8807||x===8810||x===8811||x===8814||x===8815||x===8834||x===8835||x===8838||x===8839||x===8853||x===8857||x===8869||x===8895||x===8978||x>=9312&&x<=9449||x>=9451&&x<=9547||x>=9552&&x<=9587||x>=9600&&x<=9615||x>=9618&&x<=9621||x===9632||x===9633||x>=9635&&x<=9641||x===9650||x===9651||x===9654||x===9655||x===9660||x===9661||x===9664||x===9665||x>=9670&&x<=9672||x===9675||x>=9678&&x<=9681||x>=9698&&x<=9701||x===9711||x===9733||x===9734||x===9737||x===9742||x===9743||x===9756||x===9758||x===9792||x===9794||x===9824||x===9825||x>=9827&&x<=9829||x>=9831&&x<=9834||x===9836||x===9837||x===9839||x===9886||x===9887||x===9919||x>=9926&&x<=9933||x>=9935&&x<=9939||x>=9941&&x<=9953||x===9955||x===9960||x===9961||x>=9963&&x<=9969||x===9972||x>=9974&&x<=9977||x===9979||x===9980||x===9982||x===9983||x===10045||x>=10102&&x<=10111||x>=11094&&x<=11097||x>=12872&&x<=12879||x>=57344&&x<=63743||x>=65024&&x<=65039||x===65533||x>=127232&&x<=127242||x>=127248&&x<=127277||x>=127280&&x<=127337||x>=127344&&x<=127373||x===127375||x===127376||x>=127387&&x<=127404||x>=917760&&x<=917999||x>=983040&&x<=1048573||x>=1048576&&x<=1114109,"isAmbiguous"),isFullWidth=__name(x=>x===12288||x>=65281&&x<=65376||x>=65504&&x<=65510,"isFullWidth"),isWide=__name(x=>x>=4352&&x<=4447||x===8986||x===8987||x===9001||x===9002||x>=9193&&x<=9196||x===9200||x===9203||x===9725||x===9726||x===9748||x===9749||x>=9800&&x<=9811||x===9855||x===9875||x===9889||x===9898||x===9899||x===9917||x===9918||x===9924||x===9925||x===9934||x===9940||x===9962||x===9970||x===9971||x===9973||x===9978||x===9981||x===9989||x===9994||x===9995||x===10024||x===10060||x===10062||x>=10067&&x<=10069||x===10071||x>=10133&&x<=10135||x===10160||x===10175||x===11035||x===11036||x===11088||x===11093||x>=11904&&x<=11929||x>=11931&&x<=12019||x>=12032&&x<=12245||x>=12272&&x<=12287||x>=12289&&x<=12350||x>=12353&&x<=12438||x>=12441&&x<=12543||x>=12549&&x<=12591||x>=12593&&x<=12686||x>=12688&&x<=12771||x>=12783&&x<=12830||x>=12832&&x<=12871||x>=12880&&x<=19903||x>=19968&&x<=42124||x>=42128&&x<=42182||x>=43360&&x<=43388||x>=44032&&x<=55203||x>=63744&&x<=64255||x>=65040&&x<=65049||x>=65072&&x<=65106||x>=65108&&x<=65126||x>=65128&&x<=65131||x>=94176&&x<=94180||x===94192||x===94193||x>=94208&&x<=100343||x>=100352&&x<=101589||x>=101632&&x<=101640||x>=110576&&x<=110579||x>=110581&&x<=110587||x===110589||x===110590||x>=110592&&x<=110882||x===110898||x>=110928&&x<=110930||x===110933||x>=110948&&x<=110951||x>=110960&&x<=111355||x===126980||x===127183||x===127374||x>=127377&&x<=127386||x>=127488&&x<=127490||x>=127504&&x<=127547||x>=127552&&x<=127560||x===127568||x===127569||x>=127584&&x<=127589||x>=127744&&x<=127776||x>=127789&&x<=127797||x>=127799&&x<=127868||x>=127870&&x<=127891||x>=127904&&x<=127946||x>=127951&&x<=127955||x>=127968&&x<=127984||x===127988||x>=127992&&x<=128062||x===128064||x>=128066&&x<=128252||x>=128255&&x<=128317||x>=128331&&x<=128334||x>=128336&&x<=128359||x===128378||x===128405||x===128406||x===128420||x>=128507&&x<=128591||x>=128640&&x<=128709||x===128716||x>=128720&&x<=128722||x>=128725&&x<=128727||x>=128732&&x<=128735||x===128747||x===128748||x>=128756&&x<=128764||x>=128992&&x<=129003||x===129008||x>=129292&&x<=129338||x>=129340&&x<=129349||x>=129351&&x<=129535||x>=129648&&x<=129660||x>=129664&&x<=129672||x>=129680&&x<=129725||x>=129727&&x<=129733||x>=129742&&x<=129755||x>=129760&&x<=129768||x>=129776&&x<=129784||x>=131072&&x<=196605||x>=196608&&x<=262141,"isWide")}});var ANSI_RE,CONTROL_RE,TAB_RE,EMOJI_RE,LATIN_RE,MODIFIER_RE,NO_TRUNCATION,getStringTruncatedWidth,dist_default,init_dist2=__esm({"../../node_modules/.pnpm/fast-string-truncated-width@1.2.1/node_modules/fast-string-truncated-width/dist/index.js"(){init_utils();ANSI_RE=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,CONTROL_RE=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,TAB_RE=/\t{1,1000}/y,EMOJI_RE=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),LATIN_RE=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,MODIFIER_RE=new RegExp("\\p{M}+","gu"),NO_TRUNCATION={limit:1/0,ellipsis:""},getStringTruncatedWidth=__name((input,truncationOptions={},widthOptions={})=>{let LIMIT=truncationOptions.limit??1/0,ELLIPSIS=truncationOptions.ellipsis??"",ELLIPSIS_WIDTH=truncationOptions?.ellipsisWidth??(ELLIPSIS?getStringTruncatedWidth(ELLIPSIS,NO_TRUNCATION,widthOptions).width:0),ANSI_WIDTH=widthOptions.ansiWidth??0,CONTROL_WIDTH=widthOptions.controlWidth??0,TAB_WIDTH=widthOptions.tabWidth??8,AMBIGUOUS_WIDTH=widthOptions.ambiguousWidth??1,EMOJI_WIDTH=widthOptions.emojiWidth??2,FULL_WIDTH_WIDTH=widthOptions.fullWidthWidth??2,REGULAR_WIDTH=widthOptions.regularWidth??1,WIDE_WIDTH=widthOptions.wideWidth??2,indexPrev=0,index2=0,length=input.length,lengthExtra=0,truncationEnabled=!1,truncationIndex=length,truncationLimit=Math.max(0,LIMIT-ELLIPSIS_WIDTH),unmatchedStart=0,unmatchedEnd=0,width=0,widthExtra=0;outer:for(;;){if(unmatchedEnd>unmatchedStart||index2>=length&&index2>indexPrev){let unmatched=input.slice(unmatchedStart,unmatchedEnd)||input.slice(indexPrev,index2);lengthExtra=0;for(let char of unmatched.replaceAll(MODIFIER_RE,"")){let codePoint=char.codePointAt(0)||0;if(isFullWidth(codePoint)?widthExtra=FULL_WIDTH_WIDTH:isWide(codePoint)?widthExtra=WIDE_WIDTH:AMBIGUOUS_WIDTH!==REGULAR_WIDTH&&isAmbiguous(codePoint)?widthExtra=AMBIGUOUS_WIDTH:widthExtra=REGULAR_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,Math.max(unmatchedStart,indexPrev)+lengthExtra)),width+widthExtra>LIMIT){truncationEnabled=!0;break outer}lengthExtra+=char.length,width+=widthExtra}unmatchedStart=unmatchedEnd=0}if(index2>=length)break;if(LATIN_RE.lastIndex=index2,LATIN_RE.test(input)){if(lengthExtra=LATIN_RE.lastIndex-index2,widthExtra=lengthExtra*REGULAR_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index2+Math.floor((truncationLimit-width)/REGULAR_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index2,index2=indexPrev=LATIN_RE.lastIndex;continue}if(ANSI_RE.lastIndex=index2,ANSI_RE.test(input)){if(width+ANSI_WIDTH>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index2)),width+ANSI_WIDTH>LIMIT){truncationEnabled=!0;break}width+=ANSI_WIDTH,unmatchedStart=indexPrev,unmatchedEnd=index2,index2=indexPrev=ANSI_RE.lastIndex;continue}if(CONTROL_RE.lastIndex=index2,CONTROL_RE.test(input)){if(lengthExtra=CONTROL_RE.lastIndex-index2,widthExtra=lengthExtra*CONTROL_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index2+Math.floor((truncationLimit-width)/CONTROL_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index2,index2=indexPrev=CONTROL_RE.lastIndex;continue}if(TAB_RE.lastIndex=index2,TAB_RE.test(input)){if(lengthExtra=TAB_RE.lastIndex-index2,widthExtra=lengthExtra*TAB_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index2+Math.floor((truncationLimit-width)/TAB_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index2,index2=indexPrev=TAB_RE.lastIndex;continue}if(EMOJI_RE.lastIndex=index2,EMOJI_RE.test(input)){if(width+EMOJI_WIDTH>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index2)),width+EMOJI_WIDTH>LIMIT){truncationEnabled=!0;break}width+=EMOJI_WIDTH,unmatchedStart=indexPrev,unmatchedEnd=index2,index2=indexPrev=EMOJI_RE.lastIndex;continue}index2+=1}return{width:truncationEnabled?truncationLimit:width,index:truncationEnabled?truncationIndex:length,truncated:truncationEnabled,ellipsed:truncationEnabled&&LIMIT>=ELLIPSIS_WIDTH}},"getStringTruncatedWidth"),dist_default=getStringTruncatedWidth}});var NO_TRUNCATION2,fastStringWidth,dist_default2,init_dist3=__esm({"../../node_modules/.pnpm/fast-string-width@1.1.0/node_modules/fast-string-width/dist/index.js"(){init_dist2();NO_TRUNCATION2={limit:1/0,ellipsis:"",ellipsisWidth:0},fastStringWidth=__name((input,options={})=>dist_default(input,NO_TRUNCATION2,options).width,"fastStringWidth"),dist_default2=fastStringWidth}});function wrapAnsi(string,columns,options){return String(string).normalize().split(CRLF_OR_LF).map(line=>exec(line,columns,options)).join(`
|
|
197
197
|
`)}var ESC,CSI,END_CODE,ANSI_ESCAPE_BELL,ANSI_CSI,ANSI_OSC,ANSI_SGR_TERMINATOR,ANSI_ESCAPE_LINK,GROUP_REGEX,getClosingCode,wrapAnsiCode,wrapAnsiHyperlink,wrapWord,stringVisibleTrimSpacesRight,exec,CRLF_OR_LF,init_main=__esm({"../../node_modules/.pnpm/fast-wrap-ansi@0.1.6/node_modules/fast-wrap-ansi/lib/main.js"(){init_dist3();ESC="\x1B",CSI="\x9B",END_CODE=39,ANSI_ESCAPE_BELL="\x07",ANSI_CSI="[",ANSI_OSC="]",ANSI_SGR_TERMINATOR="m",ANSI_ESCAPE_LINK=`${ANSI_OSC}8;;`,GROUP_REGEX=new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`,"y"),getClosingCode=__name(openingCode=>{if(openingCode>=30&&openingCode<=37||openingCode>=90&&openingCode<=97)return 39;if(openingCode>=40&&openingCode<=47||openingCode>=100&&openingCode<=107)return 49;if(openingCode===1||openingCode===2)return 22;if(openingCode===3)return 23;if(openingCode===4)return 24;if(openingCode===7)return 27;if(openingCode===8)return 28;if(openingCode===9)return 29;if(openingCode===0)return 0},"getClosingCode"),wrapAnsiCode=__name(code2=>`${ESC}${ANSI_CSI}${code2}${ANSI_SGR_TERMINATOR}`,"wrapAnsiCode"),wrapAnsiHyperlink=__name(url=>`${ESC}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`,"wrapAnsiHyperlink"),wrapWord=__name((rows,word,columns)=>{let characters=word[Symbol.iterator](),isInsideEscape=!1,isInsideLinkEscape=!1,lastRow=rows.at(-1),visible=lastRow===void 0?0:dist_default2(lastRow),currentCharacter=characters.next(),nextCharacter=characters.next(),rawCharacterIndex=0;for(;!currentCharacter.done;){let character=currentCharacter.value,characterLength=dist_default2(character);visible+characterLength<=columns?rows[rows.length-1]+=character:(rows.push(character),visible=0),(character===ESC||character===CSI)&&(isInsideEscape=!0,isInsideLinkEscape=word.startsWith(ANSI_ESCAPE_LINK,rawCharacterIndex+1)),isInsideEscape?isInsideLinkEscape?character===ANSI_ESCAPE_BELL&&(isInsideEscape=!1,isInsideLinkEscape=!1):character===ANSI_SGR_TERMINATOR&&(isInsideEscape=!1):(visible+=characterLength,visible===columns&&!nextCharacter.done&&(rows.push(""),visible=0)),currentCharacter=nextCharacter,nextCharacter=characters.next(),rawCharacterIndex+=character.length}lastRow=rows.at(-1),!visible&&lastRow!==void 0&&lastRow.length&&rows.length>1&&(rows[rows.length-2]+=rows.pop())},"wrapWord"),stringVisibleTrimSpacesRight=__name(string=>{let words=string.split(" "),last2=words.length;for(;last2&&!dist_default2(words[last2-1]);)last2--;return last2===words.length?string:words.slice(0,last2).join(" ")+words.slice(last2).join("")},"stringVisibleTrimSpacesRight"),exec=__name((string,columns,options={})=>{if(options.trim!==!1&&string.trim()==="")return"";let returnValue="",escapeCode,escapeUrl,words=string.split(" "),rows=[""],rowLength=0;for(let index2=0;index2<words.length;index2++){let word=words[index2];if(options.trim!==!1){let row2=rows.at(-1)??"",trimmed=row2.trimStart();row2.length!==trimmed.length&&(rows[rows.length-1]=trimmed,rowLength=dist_default2(trimmed))}index2!==0&&(rowLength>=columns&&(options.wordWrap===!1||options.trim===!1)&&(rows.push(""),rowLength=0),(rowLength||options.trim===!1)&&(rows[rows.length-1]+=" ",rowLength++));let wordLength=dist_default2(word);if(options.hard&&wordLength>columns){let remainingColumns=columns-rowLength,breaksStartingThisLine=1+Math.floor((wordLength-remainingColumns-1)/columns);Math.floor((wordLength-1)/columns)<breaksStartingThisLine&&rows.push(""),wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}if(rowLength+wordLength>columns&&rowLength&&wordLength){if(options.wordWrap===!1&&rowLength<columns){wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}rows.push(""),rowLength=0}if(rowLength+wordLength>columns&&options.wordWrap===!1){wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}rows[rows.length-1]+=word,rowLength+=wordLength}options.trim!==!1&&(rows=rows.map(row2=>stringVisibleTrimSpacesRight(row2)));let preString=rows.join(`
|
|
198
198
|
`),inSurrogate=!1;for(let i=0;i<preString.length;i++){let character=preString[i];if(returnValue+=character,!inSurrogate)inSurrogate=character>="\uD800"&&character<="\uDBFF";else continue;if(character===ESC||character===CSI){GROUP_REGEX.lastIndex=i+1;let groups=GROUP_REGEX.exec(preString)?.groups;if(groups?.code!==void 0){let code2=Number.parseFloat(groups.code);escapeCode=code2===END_CODE?void 0:code2}else groups?.uri!==void 0&&(escapeUrl=groups.uri.length===0?void 0:groups.uri)}if(preString[i+1]===`
|
|
199
199
|
`){escapeUrl&&(returnValue+=wrapAnsiHyperlink(""));let closingCode=escapeCode?getClosingCode(escapeCode):void 0;escapeCode&&closingCode&&(returnValue+=wrapAnsiCode(closingCode))}else character===`
|
|
200
200
|
`&&(escapeCode&&getClosingCode(escapeCode)&&(returnValue+=wrapAnsiCode(escapeCode)),escapeUrl&&(returnValue+=wrapAnsiHyperlink(escapeUrl)))}return returnValue},"exec"),CRLF_OR_LF=/\r?\n/;__name(wrapAnsi,"wrapAnsi")}});var require_src=__commonJS({"../../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js"(exports2,module2){"use strict";var cursor={to(x,y2){return y2?`\x1B[${y2+1};${x+1}H`:`\x1B[${x+1}G`},move(x,y2){let ret="";return x<0?ret+=`\x1B[${-x}D`:x>0&&(ret+=`\x1B[${x}C`),y2<0?ret+=`\x1B[${-y2}A`:y2>0&&(ret+=`\x1B[${y2}B`),ret},up:__name((count=1)=>`\x1B[${count}A`,"up"),down:__name((count=1)=>`\x1B[${count}B`,"down"),forward:__name((count=1)=>`\x1B[${count}C`,"forward"),backward:__name((count=1)=>`\x1B[${count}D`,"backward"),nextLine:__name((count=1)=>"\x1B[E".repeat(count),"nextLine"),prevLine:__name((count=1)=>"\x1B[F".repeat(count),"prevLine"),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},scroll={up:__name((count=1)=>"\x1B[S".repeat(count),"up"),down:__name((count=1)=>"\x1B[T".repeat(count),"down")},erase={screen:"\x1B[2J",up:__name((count=1)=>"\x1B[1J".repeat(count),"up"),down:__name((count=1)=>"\x1B[J".repeat(count),"down"),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(count){let clear="";for(let i=0;i<count;i++)clear+=this.line+(i<count-1?cursor.up():"");return count&&(clear+=cursor.left),clear}};module2.exports={cursor,scroll,erase,beep:"\x07"}}});import{styleText as y}from"node:util";import{stdout as S,stdin as $}from"node:process";import*as _ from"node:readline";import P from"node:readline";import{ReadStream as D}from"node:tty";function d(r,t2,e){if(!e.some(o=>!o.disabled))return r;let s=r+t2,i=Math.max(e.length-1,0),n=s<0?i:s>i?0:s;return e[n].disabled?d(n,t2<0?-1:1,e):n}function V(r,t2){if(typeof r=="string")return u.aliases.get(r)===t2;for(let e of r)if(e!==void 0&&V(e,t2))return!0;return!1}function j(r,t2){if(r===t2)return;let e=r.split(`
|
|
201
201
|
`),s=t2.split(`
|
|
202
|
-
`),i=Math.max(e.length,s.length),n=[];for(let o=0;o<i;o++)e[o]!==s[o]&&n.push(o);return{lines:n,numLinesBefore:e.length,numLinesAfter:s.length,numLines:i}}function q(r){return r===C}function w(r,t2){let e=r;e.isTTY&&e.setRawMode(t2)}function
|
|
202
|
+
`),i=Math.max(e.length,s.length),n=[];for(let o=0;o<i;o++)e[o]!==s[o]&&n.push(o);return{lines:n,numLinesBefore:e.length,numLinesAfter:s.length,numLines:i}}function q(r){return r===C}function w(r,t2){let e=r;e.isTTY&&e.setRawMode(t2)}function z64({input:r=$,output:t2=S,overwrite:e=!0,hideCursor:s=!0}={}){let i=_.createInterface({input:r,output:t2,prompt:"",tabSize:1});_.emitKeypressEvents(r,i),r instanceof D&&r.isTTY&&r.setRawMode(!0);let n=__name((o,{name:a,sequence:h})=>{let l=String(o);if(V([l,a,h],"cancel")){s&&t2.write(import_sisteransi.cursor.show),process.exit(0);return}if(!e)return;_.moveCursor(t2,a==="return"?0:-1,a==="return"?-1:0,()=>{_.clearLine(t2,1,()=>{r.once("keypress",n)})})},"n");return s&&t2.write(import_sisteransi.cursor.hide),r.once("keypress",n),()=>{r.off("keypress",n),s&&t2.write(import_sisteransi.cursor.show),r instanceof D&&r.isTTY&&!Y&&r.setRawMode(!1),i.terminal=!1,i.close()}}function R(r,t2,e,s=e){let i=O(r??S);return wrapAnsi(t2,i-e.length,{hard:!0,trim:!1}).split(`
|
|
203
203
|
`).map((n,o)=>`${o===0?s:e}${n}`).join(`
|
|
204
|
-
`)}var import_sisteransi,E,G,u,Y,C,O,A,p,Q,it,rt,nt,at,init_dist4=__esm({"../../node_modules/.pnpm/@clack+core@1.2.0/node_modules/@clack/core/dist/index.mjs"(){init_main();import_sisteransi=__toESM(require_src(),1);__name(d,"d");E=["up","down","left","right","space","enter","cancel"],G=["January","February","March","April","May","June","July","August","September","October","November","December"],u={actions:new Set(E),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...G],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:__name((r,t2)=>`There are only ${r} days in ${t2}`,"invalidDay"),afterMin:__name(r=>`Date must be on or after ${r.toISOString().slice(0,10)}`,"afterMin"),beforeMax:__name(r=>`Date must be on or before ${r.toISOString().slice(0,10)}`,"beforeMax")}}};__name(V,"V");__name(j,"j");Y=globalThis.process.platform.startsWith("win"),C=Symbol("clack:cancel");__name(q,"q");__name(w,"w");__name(
|
|
204
|
+
`)}var import_sisteransi,E,G,u,Y,C,O,A,p,Q,it,rt,nt,at,init_dist4=__esm({"../../node_modules/.pnpm/@clack+core@1.2.0/node_modules/@clack/core/dist/index.mjs"(){init_main();import_sisteransi=__toESM(require_src(),1);__name(d,"d");E=["up","down","left","right","space","enter","cancel"],G=["January","February","March","April","May","June","July","August","September","October","November","December"],u={actions:new Set(E),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,date:{monthNames:[...G],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:__name((r,t2)=>`There are only ${r} days in ${t2}`,"invalidDay"),afterMin:__name(r=>`Date must be on or after ${r.toISOString().slice(0,10)}`,"afterMin"),beforeMax:__name(r=>`Date must be on or before ${r.toISOString().slice(0,10)}`,"beforeMax")}}};__name(V,"V");__name(j,"j");Y=globalThis.process.platform.startsWith("win"),C=Symbol("clack:cancel");__name(q,"q");__name(w,"w");__name(z64,"z");O=__name(r=>"columns"in r&&typeof r.columns=="number"?r.columns:80,"O"),A=__name(r=>"rows"in r&&typeof r.rows=="number"?r.rows:20,"A");__name(R,"R");p=class{static{__name(this,"p")}input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(t2,e=!0){let{input:s=$,output:i=S,render:n,signal:o,...a}=t2;this.opts=a,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=n.bind(this),this._track=e,this._abortSignal=o,this.input=s,this.output=i}unsubscribe(){this._subscribers.clear()}setSubscriber(t2,e){let s=this._subscribers.get(t2)??[];s.push(e),this._subscribers.set(t2,s)}on(t2,e){this.setSubscriber(t2,{cb:e})}once(t2,e){this.setSubscriber(t2,{cb:e,once:!0})}emit(t2,...e){let s=this._subscribers.get(t2)??[],i=[];for(let n of s)n.cb(...e),n.once&&i.push(()=>s.splice(s.indexOf(n),1));for(let n of i)n()}prompt(){return new Promise(t2=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t2(C);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=P.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),w(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(import_sisteransi.cursor.show),this.output.off("resize",this.render),w(this.input,!1),t2(this.value)}),this.once("cancel",()=>{this.output.write(import_sisteransi.cursor.show),this.output.off("resize",this.render),w(this.input,!1),t2(C)})})}_isActionKey(t2,e){return t2===" "}_setValue(t2){this.value=t2,this.emit("value",this.value)}_setUserInput(t2,e){this.userInput=t2??"",this.emit("userInput",this.userInput),e&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(t2,e){if(this._track&&e.name!=="return"&&(e.name&&this._isActionKey(t2,e)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),e?.name&&(!this._track&&u.aliases.has(e.name)&&this.emit("cursor",u.aliases.get(e.name)),u.actions.has(e.name)&&this.emit("cursor",e.name)),t2&&(t2.toLowerCase()==="y"||t2.toLowerCase()==="n")&&this.emit("confirm",t2.toLowerCase()==="y"),this.emit("key",t2?.toLowerCase(),e),e?.name==="return"){if(this.opts.validate){let s=this.opts.validate(this.value);s&&(this.error=s instanceof Error?s.message:s,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}V([t2,e?.name,e?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
205
205
|
`),w(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let t2=wrapAnsi(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
206
206
|
`).length-1;this.output.write(import_sisteransi.cursor.move(-999,t2*-1))}render(){let t2=wrapAnsi(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t2!==this._prevFrame){if(this.state==="initial")this.output.write(import_sisteransi.cursor.hide);else{let e=j(this._prevFrame,t2),s=A(this.output);if(this.restoreCursor(),e){let i=Math.max(0,e.numLinesAfter-s),n=Math.max(0,e.numLinesBefore-s),o=e.lines.find(a=>a>=i);if(o===void 0){this._prevFrame=t2;return}if(e.lines.length===1){this.output.write(import_sisteransi.cursor.move(0,o-n)),this.output.write(import_sisteransi.erase.lines(1));let a=t2.split(`
|
|
207
207
|
`);this.output.write(a[o]),this._prevFrame=t2,this.output.write(import_sisteransi.cursor.move(0,a.length-o-1));return}else if(e.lines.length>1){if(i<n)o=i;else{let h=o-n;h>0&&this.output.write(import_sisteransi.cursor.move(0,h))}this.output.write(import_sisteransi.erase.down());let a=t2.split(`
|
|
208
208
|
`).slice(o);this.output.write(a.join(`
|
|
209
|
-
`)),this._prevFrame=t2;return}}this.output.write(import_sisteransi.erase.down())}this.output.write(t2),this.state==="initial"&&(this.state="active"),this._prevFrame=t2}}},Q=class extends p{static{__name(this,"Q")}get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t2){super(t2,!1),this.value=!!t2.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",e=>{this.output.write(import_sisteransi.cursor.move(0,-1)),this.value=e,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}},it=class extends p{static{__name(this,"it")}options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter(t2=>t2.disabled!==!0)}toggleAll(){let t2=this._enabledOptions,e=this.value!==void 0&&this.value.length===t2.length;this.value=e?[]:t2.map(s=>s.value)}toggleInvert(){let t2=this.value;if(!t2)return;let e=this._enabledOptions.filter(s=>!t2.includes(s.value));this.value=e.map(s=>s.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t2=this.value.includes(this._value);this.value=t2?this.value.filter(e=>e!==this._value):[...this.value,this._value]}constructor(t2){super(t2,!1),this.options=t2.options,this.value=[...t2.initialValues??[]];let e=Math.max(this.options.findIndex(({value:s})=>s===t2.cursorAt),0);this.cursor=this.options[e].disabled?d(e,1,this.options):e,this.on("key",s=>{s==="a"&&this.toggleAll(),s==="i"&&this.toggleInvert()}),this.on("cursor",s=>{switch(s){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},rt=class extends p{static{__name(this,"rt")}_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.masked}${y(["inverse","hidden"],"_")}`;let e=this.masked,s=e.slice(0,this.cursor),i=e.slice(this.cursor);return`${s}${y("inverse",i[0])}${i.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:t2,...e}){super(e),this._mask=t2??"\u2022",this.on("userInput",s=>{this._setValue(s)})}},nt=class extends p{static{__name(this,"nt")}options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(t2){super(t2,!1),this.options=t2.options;let e=this.options.findIndex(({value:i})=>i===t2.initialValue),s=e===-1?0:e;this.cursor=this.options[s].disabled?d(s,1,this.options):s,this.changeValue(),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break}this.changeValue()})}},at=class extends p{static{__name(this,"at")}get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.userInput}\u2588`;let e=t2.slice(0,this.cursor),[s,...i]=t2.slice(this.cursor);return`${e}${y("inverse",s)}${i.join("")}`}get cursor(){return this._cursor}constructor(t2){super({...t2,initialUserInput:t2.initialUserInput??t2.initialValue}),this.on("userInput",e=>{this._setValue(e)}),this.on("finalize",()=>{this.value||(this.value=t2.defaultValue),this.value===void 0&&(this.value="")})}}}});import{styleText as t,stripVTControlCharacters as ne}from"node:util";import P2 from"node:process";function Ze(){return P2.platform!=="win32"?P2.env.TERM!=="linux":!!P2.env.CI||!!P2.env.WT_SESSION||!!P2.env.TERMINUS_SUBLIME||P2.env.ConEmuTask==="{cmd::Cmder}"||P2.env.TERM_PROGRAM==="Terminus-Sublime"||P2.env.TERM_PROGRAM==="vscode"||P2.env.TERM==="xterm-256color"||P2.env.TERM==="alacritty"||P2.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var import_sisteransi2,ee,ae,w2,_e,oe,ue,F,le,d2,E2,Ie,Ee,
|
|
209
|
+
`)),this._prevFrame=t2;return}}this.output.write(import_sisteransi.erase.down())}this.output.write(t2),this.state==="initial"&&(this.state="active"),this._prevFrame=t2}}},Q=class extends p{static{__name(this,"Q")}get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t2){super(t2,!1),this.value=!!t2.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",e=>{this.output.write(import_sisteransi.cursor.move(0,-1)),this.value=e,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}},it=class extends p{static{__name(this,"it")}options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter(t2=>t2.disabled!==!0)}toggleAll(){let t2=this._enabledOptions,e=this.value!==void 0&&this.value.length===t2.length;this.value=e?[]:t2.map(s=>s.value)}toggleInvert(){let t2=this.value;if(!t2)return;let e=this._enabledOptions.filter(s=>!t2.includes(s.value));this.value=e.map(s=>s.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t2=this.value.includes(this._value);this.value=t2?this.value.filter(e=>e!==this._value):[...this.value,this._value]}constructor(t2){super(t2,!1),this.options=t2.options,this.value=[...t2.initialValues??[]];let e=Math.max(this.options.findIndex(({value:s})=>s===t2.cursorAt),0);this.cursor=this.options[e].disabled?d(e,1,this.options):e,this.on("key",s=>{s==="a"&&this.toggleAll(),s==="i"&&this.toggleInvert()}),this.on("cursor",s=>{switch(s){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},rt=class extends p{static{__name(this,"rt")}_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.masked}${y(["inverse","hidden"],"_")}`;let e=this.masked,s=e.slice(0,this.cursor),i=e.slice(this.cursor);return`${s}${y("inverse",i[0])}${i.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:t2,...e}){super(e),this._mask=t2??"\u2022",this.on("userInput",s=>{this._setValue(s)})}},nt=class extends p{static{__name(this,"nt")}options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(t2){super(t2,!1),this.options=t2.options;let e=this.options.findIndex(({value:i})=>i===t2.initialValue),s=e===-1?0:e;this.cursor=this.options[s].disabled?d(s,1,this.options):s,this.changeValue(),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break}this.changeValue()})}},at=class extends p{static{__name(this,"at")}get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.userInput}\u2588`;let e=t2.slice(0,this.cursor),[s,...i]=t2.slice(this.cursor);return`${e}${y("inverse",s)}${i.join("")}`}get cursor(){return this._cursor}constructor(t2){super({...t2,initialUserInput:t2.initialUserInput??t2.initialValue}),this.on("userInput",e=>{this._setValue(e)}),this.on("finalize",()=>{this.value||(this.value=t2.defaultValue),this.value===void 0&&(this.value="")})}}}});import{styleText as t,stripVTControlCharacters as ne}from"node:util";import P2 from"node:process";function Ze(){return P2.platform!=="win32"?P2.env.TERM!=="linux":!!P2.env.CI||!!P2.env.WT_SESSION||!!P2.env.TERMINUS_SUBLIME||P2.env.ConEmuTask==="{cmd::Cmder}"||P2.env.TERM_PROGRAM==="Terminus-Sublime"||P2.env.TERM_PROGRAM==="vscode"||P2.env.TERM==="xterm-256color"||P2.env.TERM==="alacritty"||P2.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var import_sisteransi2,ee,ae,w2,_e,oe,ue,F,le,d2,E2,Ie,Ee,z65,H2,te,U,J,xe,se,ce,Ge,$e,de,Oe,he,pe,me,ge,V2,ye,et2,Y2,ot2,O2,pt,mt,ft,vt,wt,bt,Ct,fe,Ve,re,_t,je,Ot,init_dist5=__esm({"../../node_modules/.pnpm/@clack+prompts@1.2.0/node_modules/@clack/prompts/dist/index.mjs"(){init_dist4();init_dist4();init_main();init_dist3();import_sisteransi2=__toESM(require_src(),1);__name(Ze,"Ze");ee=Ze(),ae=__name(()=>process.env.CI==="true","ae"),w2=__name((e,i)=>ee?e:i,"w"),_e=w2("\u25C6","*"),oe=w2("\u25A0","x"),ue=w2("\u25B2","x"),F=w2("\u25C7","o"),le=w2("\u250C","T"),d2=w2("\u2502","|"),E2=w2("\u2514","\u2014"),Ie=w2("\u2510","T"),Ee=w2("\u2518","\u2014"),z65=w2("\u25CF",">"),H2=w2("\u25CB"," "),te=w2("\u25FB","[\u2022]"),U=w2("\u25FC","[+]"),J=w2("\u25FB","[ ]"),xe=w2("\u25AA","\u2022"),se=w2("\u2500","-"),ce=w2("\u256E","+"),Ge=w2("\u251C","+"),$e=w2("\u256F","+"),de=w2("\u2570","+"),Oe=w2("\u256D","+"),he=w2("\u25CF","\u2022"),pe=w2("\u25C6","*"),me=w2("\u25B2","!"),ge=w2("\u25A0","x"),V2=__name(e=>{switch(e){case"initial":case"active":return t("cyan",_e);case"cancel":return t("red",oe);case"error":return t("yellow",ue);case"submit":return t("green",F)}},"V"),ye=__name(e=>{switch(e){case"initial":case"active":return t("cyan",d2);case"cancel":return t("red",d2);case"error":return t("yellow",d2);case"submit":return t("green",d2)}},"ye"),et2=__name((e,i,s,r,u2)=>{let n=i,o=0;for(let c2=s;c2<r;c2++){let a=e[c2];if(n=n-a.length,o++,n<=u2)break}return{lineCount:n,removals:o}},"et"),Y2=__name(({cursor:e,options:i,style:s,output:r=process.stdout,maxItems:u2=Number.POSITIVE_INFINITY,columnPadding:n=0,rowPadding:o=4})=>{let c2=O(r)-n,a=A(r),l=t("dim","..."),$2=Math.max(a-o,0),y2=Math.max(Math.min(u2,$2),5),p2=0;e>=y2-3&&(p2=Math.max(Math.min(e-y2+3,i.length-y2),0));let m=y2<i.length&&p2>0,g=y2<i.length&&p2+y2<i.length,S2=Math.min(p2+y2,i.length),h=[],f=0;m&&f++,g&&f++;let v=p2+(m?1:0),T=S2-(g?1:0);for(let b=v;b<T;b++){let x=wrapAnsi(s(i[b],b===e),c2,{hard:!0,trim:!1}).split(`
|
|
210
210
|
`);h.push(x),f+=x.length}if(f>$2){let b=0,x=0,G2=f,M2=e-v,R2=__name((j2,D2)=>et2(h,G2,j2,D2,$2),"R");m?({lineCount:G2,removals:b}=R2(0,M2),G2>$2&&({lineCount:G2,removals:x}=R2(M2+1,h.length))):({lineCount:G2,removals:x}=R2(M2+1,h.length),G2>$2&&({lineCount:G2,removals:b}=R2(0,M2))),b>0&&(m=!0,h.splice(0,b)),x>0&&(g=!0,h.splice(h.length-x,x))}let C2=[];m&&C2.push(l);for(let b of h)for(let x of b)C2.push(x);return g&&C2.push(l),C2},"Y"),ot2=__name(e=>{let i=e.active??"Yes",s=e.inactive??"No";return new Q({active:i,inactive:s,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??u.withGuide,u2=`${V2(this.state)} `,n=r?`${t("gray",d2)} `:"",o=R(e.output,e.message,n,u2),c2=`${r?`${t("gray",d2)}
|
|
211
211
|
`:""}${o}
|
|
212
212
|
`,a=this.value?i:s;switch(this.state){case"submit":{let l=r?`${t("gray",d2)} `:"";return`${c2}${l}${t("dim",a)}`}case"cancel":{let l=r?`${t("gray",d2)} `:"";return`${c2}${l}${t(["strikethrough","dim"],a)}${r?`
|
|
213
|
-
${t("gray",d2)}`:""}`}default:{let l=r?`${t("cyan",d2)} `:"",$2=r?t("cyan",E2):"";return`${c2}${l}${this.value?`${t("green",
|
|
213
|
+
${t("gray",d2)}`:""}`}default:{let l=r?`${t("cyan",d2)} `:"",$2=r?t("cyan",E2):"";return`${c2}${l}${this.value?`${t("green",z65)} ${i}`:`${t("dim",H2)} ${t("dim",i)}`}${e.vertical?r?`
|
|
214
214
|
${t("cyan",d2)} `:`
|
|
215
|
-
`:` ${t("dim","/")} `}${this.value?`${t("dim",H2)} ${t("dim",s)}`:`${t("green",
|
|
215
|
+
`:` ${t("dim","/")} `}${this.value?`${t("dim",H2)} ${t("dim",s)}`:`${t("green",z65)} ${s}`}
|
|
216
216
|
${$2}
|
|
217
217
|
`}}}}).prompt()},"ot"),O2={message:__name((e=[],{symbol:i=t("gray",d2),secondarySymbol:s=t("gray",d2),output:r=process.stdout,spacing:u2=1,withGuide:n}={})=>{let o=[],c2=n??u.withGuide,a=c2?s:"",l=c2?`${i} `:"",$2=c2?`${s} `:"";for(let p2=0;p2<u2;p2++)o.push(a);let y2=Array.isArray(e)?e:e.split(`
|
|
218
218
|
`);if(y2.length>0){let[p2,...m]=y2;p2.length>0?o.push(`${l}${p2}`):o.push(c2?i:"");for(let g of m)g.length>0?o.push(`${$2}${g}`):o.push(c2?s:"")}r.write(`${o.join(`
|
|
@@ -237,13 +237,13 @@ ${t("gray",d2)}`:""}`}default:{let n=i?`${t("cyan",d2)} `:"",o=i?t("cyan",E2):"
|
|
|
237
237
|
${o}
|
|
238
238
|
`}}}}).prompt(),"bt"),Ct=__name(e=>t("magenta",e),"Ct"),fe=__name(({indicator:e="dots",onCancel:i,output:s=process.stdout,cancelMessage:r,errorMessage:u2,frames:n=ee?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=ee?80:120,signal:c2,...a}={})=>{let l=ae(),$2,y2,p2=!1,m=!1,g="",S2,h=performance.now(),f=O(s),v=a?.styleFrame??Ct,T=__name(_2=>{let A2=_2>1?u2??u.messages.error:r??u.messages.cancel;m=_2===1,p2&&(W(A2,_2),m&&typeof i=="function"&&i())},"T"),C2=__name(()=>T(2),"C"),b=__name(()=>T(1),"b"),x=__name(()=>{process.on("uncaughtExceptionMonitor",C2),process.on("unhandledRejection",C2),process.on("SIGINT",b),process.on("SIGTERM",b),process.on("exit",T),c2&&c2.addEventListener("abort",b)},"x"),G2=__name(()=>{process.removeListener("uncaughtExceptionMonitor",C2),process.removeListener("unhandledRejection",C2),process.removeListener("SIGINT",b),process.removeListener("SIGTERM",b),process.removeListener("exit",T),c2&&c2.removeEventListener("abort",b)},"G"),M2=__name(()=>{if(S2===void 0)return;l&&s.write(`
|
|
239
239
|
`);let _2=wrapAnsi(S2,f,{hard:!0,trim:!1}).split(`
|
|
240
|
-
`);_2.length>1&&s.write(import_sisteransi2.cursor.up(_2.length-1)),s.write(import_sisteransi2.cursor.to(0)),s.write(import_sisteransi2.erase.down())},"M"),R2=__name(_2=>_2.replace(/\.+$/,""),"R"),j2=__name(_2=>{let A2=(performance.now()-_2)/1e3,k=Math.floor(A2/60),L=Math.floor(A2%60);return k>0?`[${k}m ${L}s]`:`[${L}s]`},"j"),D2=a.withGuide??u.withGuide,ie=__name((_2="")=>{p2=!0,$2=
|
|
240
|
+
`);_2.length>1&&s.write(import_sisteransi2.cursor.up(_2.length-1)),s.write(import_sisteransi2.cursor.to(0)),s.write(import_sisteransi2.erase.down())},"M"),R2=__name(_2=>_2.replace(/\.+$/,""),"R"),j2=__name(_2=>{let A2=(performance.now()-_2)/1e3,k=Math.floor(A2/60),L=Math.floor(A2%60);return k>0?`[${k}m ${L}s]`:`[${L}s]`},"j"),D2=a.withGuide??u.withGuide,ie=__name((_2="")=>{p2=!0,$2=z64({output:s}),g=R2(_2),h=performance.now(),D2&&s.write(`${t("gray",d2)}
|
|
241
241
|
`);let A2=0,k=0;x(),y2=setInterval(()=>{if(l&&g===S2)return;M2(),S2=g;let L=v(n[A2]),Z;if(l)Z=`${L} ${g}...`;else if(e==="timer")Z=`${L} ${g} ${j2(h)}`;else{let Be=".".repeat(Math.floor(k)).slice(0,3);Z=`${L} ${g}${Be}`}let Ne=wrapAnsi(Z,f,{hard:!0,trim:!1});s.write(Ne),A2=A2+1<n.length?A2+1:0,k=k<4?k+.125:0},o)},"ie"),W=__name((_2="",A2=0,k=!1)=>{if(!p2)return;p2=!1,clearInterval(y2),M2();let L=A2===0?t("green",F):A2===1?t("red",oe):t("red",ue);g=_2??g,k||(e==="timer"?s.write(`${L} ${g} ${j2(h)}
|
|
242
242
|
`):s.write(`${L} ${g}
|
|
243
243
|
`)),G2(),$2()},"W");return{start:ie,stop:__name((_2="")=>W(_2,0),"stop"),message:__name((_2="")=>{g=R2(_2??g)},"message"),cancel:__name((_2="")=>W(_2,1),"cancel"),error:__name((_2="")=>W(_2,2),"error"),clear:__name(()=>W("",0,!0),"clear"),get isCancelled(){return m}}},"fe"),Ve={light:w2("\u2500","-"),heavy:w2("\u2501","="),block:w2("\u2588","#")},re=__name((e,i)=>e.includes(`
|
|
244
244
|
`)?e.split(`
|
|
245
245
|
`).map(s=>i(s)).join(`
|
|
246
|
-
`):i(e),"re"),_t=__name(e=>{let i=__name((s,r)=>{let u2=s.label??String(s.value);switch(r){case"disabled":return`${t("gray",H2)} ${re(u2,n=>t("gray",n))}${s.hint?` ${t("dim",`(${s.hint??"disabled"})`)}`:""}`;case"selected":return`${re(u2,n=>t("dim",n))}`;case"active":return`${t("green",
|
|
246
|
+
`):i(e),"re"),_t=__name(e=>{let i=__name((s,r)=>{let u2=s.label??String(s.value);switch(r){case"disabled":return`${t("gray",H2)} ${re(u2,n=>t("gray",n))}${s.hint?` ${t("dim",`(${s.hint??"disabled"})`)}`:""}`;case"selected":return`${re(u2,n=>t("dim",n))}`;case"active":return`${t("green",z65)} ${u2}${s.hint?` ${t("dim",`(${s.hint})`)}`:""}`;case"cancelled":return`${re(u2,n=>t(["strikethrough","dim"],n))}`;default:return`${t("dim",H2)} ${re(u2,n=>t("dim",n))}`}},"i");return new nt({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let s=e.withGuide??u.withGuide,r=`${V2(this.state)} `,u2=`${ye(this.state)} `,n=R(e.output,e.message,u2,r),o=`${s?`${t("gray",d2)}
|
|
247
247
|
`:""}${n}
|
|
248
248
|
`;switch(this.state){case"submit":{let c2=s?`${t("gray",d2)} `:"",a=R(e.output,i(this.options[this.cursor],"selected"),c2);return`${o}${a}`}case"cancel":{let c2=s?`${t("gray",d2)} `:"",a=R(e.output,i(this.options[this.cursor],"cancelled"),c2);return`${o}${a}${s?`
|
|
249
249
|
${t("gray",d2)}`:""}`}default:{let c2=s?`${t("cyan",d2)} `:"",a=s?t("cyan",E2):"",l=o.split(`
|
|
@@ -303,10 +303,10 @@ return __eta.res;
|
|
|
303
303
|
`)}}return returnStr}function trimWS(str,config,wsLeft,wsRight){let leftTrim,rightTrim;return Array.isArray(config.autoTrim)?(leftTrim=config.autoTrim[1],rightTrim=config.autoTrim[0]):leftTrim=rightTrim=config.autoTrim,(wsLeft||wsLeft===!1)&&(leftTrim=wsLeft),(wsRight||wsRight===!1)&&(rightTrim=wsRight),!rightTrim&&!leftTrim?str:leftTrim==="slurp"&&rightTrim==="slurp"?str.trim():(leftTrim==="_"||leftTrim==="slurp"?str=str.trimStart():(leftTrim==="-"||leftTrim==="nl")&&(str=str.replace(/^(?:\r\n|\n|\r)/,"")),rightTrim==="_"||rightTrim==="slurp"?str=str.trimEnd():(rightTrim==="-"||rightTrim==="nl")&&(str=str.replace(/(?:\r\n|\n|\r)$/,"")),str)}function replaceChar(s){return escMap[s]}function XMLEscape(str){let newStr=String(str);return/[&<>"']/.test(newStr)?newStr.replace(/[&<>"']/g,replaceChar):newStr}function escapeRegExp(string){return string.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&")}function getLineNo(str,index2){return str.slice(0,index2).split(`
|
|
304
304
|
`).length}function parse4(str){let config=this.config,buffer=[],trimLeftOfNextStr=!1,lastIndex=0,parseOptions=config.parse;if(config.plugins)for(let i=0;i<config.plugins.length;i++){let plugin=config.plugins[i];plugin.processTemplate&&(str=plugin.processTemplate(str,config))}config.rmWhitespace&&(str=str.replace(/[\r\n]+/g,`
|
|
305
305
|
`).replace(/^\s+|\s+$/gm,"")),templateLitReg.lastIndex=0,singleQuoteReg.lastIndex=0,doubleQuoteReg.lastIndex=0;function pushString(strng,shouldTrimRightOfString){strng&&(strng=trimWS(strng,config,trimLeftOfNextStr,shouldTrimRightOfString),strng&&(strng=strng.replace(/\\|'/g,"\\$&").replace(/\r\n|\n|\r/g,"\\n"),buffer.push(strng)))}__name(pushString,"pushString");let prefixes=[parseOptions.exec,parseOptions.interpolate,parseOptions.raw].reduce(function(accumulator,prefix){return accumulator&&prefix?accumulator+"|"+escapeRegExp(prefix):prefix?escapeRegExp(prefix):accumulator},""),parseOpenReg=new RegExp(escapeRegExp(config.tags[0])+"(-|_)?\\s*("+prefixes+")?\\s*","g"),parseCloseReg=new RegExp("'|\"|`|\\/\\*|(\\s*(-|_)?"+escapeRegExp(config.tags[1])+")","g"),m;for(;m=parseOpenReg.exec(str);){let precedingString=str.slice(lastIndex,m.index);lastIndex=m[0].length+m.index;let wsLeft=m[1],prefix=m[2]||"";pushString(precedingString,wsLeft),parseCloseReg.lastIndex=lastIndex;let closeTag,currentObj=!1;for(;closeTag=parseCloseReg.exec(str);)if(closeTag[1]){let content2=str.slice(lastIndex,closeTag.index);parseOpenReg.lastIndex=lastIndex=parseCloseReg.lastIndex,trimLeftOfNextStr=closeTag[2],currentObj={t:prefix===parseOptions.exec?"e":prefix===parseOptions.raw?"r":prefix===parseOptions.interpolate?"i":"",val:content2};break}else{let char=closeTag[0];if(char==="/*"){let commentCloseInd=str.indexOf("*/",parseCloseReg.lastIndex);commentCloseInd===-1&&ParseErr("unclosed comment",str,closeTag.index),parseCloseReg.lastIndex=commentCloseInd}else char==="'"?(singleQuoteReg.lastIndex=closeTag.index,singleQuoteReg.exec(str)?parseCloseReg.lastIndex=singleQuoteReg.lastIndex:ParseErr("unclosed string",str,closeTag.index)):char==='"'?(doubleQuoteReg.lastIndex=closeTag.index,doubleQuoteReg.exec(str)?parseCloseReg.lastIndex=doubleQuoteReg.lastIndex:ParseErr("unclosed string",str,closeTag.index)):char==="`"&&(templateLitReg.lastIndex=closeTag.index,templateLitReg.exec(str)?parseCloseReg.lastIndex=templateLitReg.lastIndex:ParseErr("unclosed string",str,closeTag.index))}currentObj?(config.debug&&(currentObj.lineNo=getLineNo(str,m.index)),buffer.push(currentObj)):ParseErr("unclosed tag",str,m.index)}if(pushString(str.slice(lastIndex,str.length),!1),config.plugins)for(let i=0;i<config.plugins.length;i++){let plugin=config.plugins[i];plugin.processAST&&(buffer=plugin.processAST(buffer,config))}return buffer}function handleCache(template,options){let templateStore=options&&options.async?this.templatesAsync:this.templatesSync;if(this.resolvePath&&this.readFile&&!template.startsWith("@")){let templatePath2=options.filepath,cachedTemplate=templateStore.get(templatePath2);if(this.config.cache&&cachedTemplate)return cachedTemplate;{let templateString=this.readFile(templatePath2),templateFn=this.compile(templateString,options);return this.config.cache&&templateStore.define(templatePath2,templateFn),templateFn}}else{let cachedTemplate=templateStore.get(template);if(cachedTemplate)return cachedTemplate;throw new EtaNameResolutionError("Failed to get template '"+template+"'")}}function render(template,data2,meta){let templateFn,options={...meta,async:!1};return typeof template=="string"?(this.resolvePath&&this.readFile&&!template.startsWith("@")&&(options.filepath=this.resolvePath(template,options)),templateFn=handleCache.call(this,template,options)):templateFn=template,templateFn.call(this,data2,options)}function renderAsync(template,data2,meta){let templateFn,options={...meta,async:!0};typeof template=="string"?(this.resolvePath&&this.readFile&&!template.startsWith("@")&&(options.filepath=this.resolvePath(template,options)),templateFn=handleCache.call(this,template,options)):templateFn=template;let res=templateFn.call(this,data2,options);return Promise.resolve(res)}function renderString(template,data2){let templateFn=this.compile(template,{async:!1});return render.call(this,templateFn,data2)}function renderStringAsync(template,data2){let templateFn=this.compile(template,{async:!0});return renderAsync.call(this,templateFn,data2)}function readFile(path47){let res="";try{res=fs17.readFileSync(path47,"utf8")}catch(err){throw err?.code==="ENOENT"?new EtaFileResolutionError(`Could not find template: ${path47}`):err}return res}function resolvePath2(templatePath2,options){let resolvedFilePath="",views=this.config.views;if(!views)throw new EtaFileResolutionError("Views directory is not defined");let baseFilePath=options&&options.filepath,defaultExtension=this.config.defaultExtension===void 0?".eta":this.config.defaultExtension,cacheIndex=JSON.stringify({filename:baseFilePath,path:templatePath2,views:this.config.views});if(templatePath2+=path20.extname(templatePath2)?"":defaultExtension,baseFilePath){if(this.config.cacheFilepaths&&this.filepathCache[cacheIndex])return this.filepathCache[cacheIndex];let absolutePathTest=absolutePathRegExp.exec(templatePath2);if(absolutePathTest&&absolutePathTest.length){let formattedPath=templatePath2.replace(/^\/*|^\\*/,"");resolvedFilePath=path20.join(views,formattedPath)}else resolvedFilePath=path20.join(path20.dirname(baseFilePath),templatePath2)}else resolvedFilePath=path20.join(views,templatePath2);if(dirIsChild(views,resolvedFilePath))return baseFilePath&&this.config.cacheFilepaths&&(this.filepathCache[cacheIndex]=resolvedFilePath),resolvedFilePath;throw new EtaFileResolutionError(`Template '${templatePath2}' is not in the views directory`)}function dirIsChild(parent2,dir){let relative3=path20.relative(parent2,dir);return relative3&&!relative3.startsWith("..")&&!path20.isAbsolute(relative3)}var Cacher,EtaError,EtaParseError,EtaRuntimeError,EtaFileResolutionError,EtaNameResolutionError,AsyncFunction,escMap,defaultConfig2,templateLitReg,singleQuoteReg,doubleQuoteReg,Eta$1,absolutePathRegExp,Eta,init_eta_module=__esm({"../../node_modules/.pnpm/eta@3.5.0/node_modules/eta/dist/eta.module.mjs"(){Cacher=class{static{__name(this,"Cacher")}constructor(cache){this.cache=void 0,this.cache=cache}define(key,val2){this.cache[key]=val2}get(key){return this.cache[key]}remove(key){delete this.cache[key]}reset(){this.cache={}}load(cacheObj){this.cache={...this.cache,...cacheObj}}},EtaError=class extends Error{static{__name(this,"EtaError")}constructor(message){super(message),this.name="Eta Error"}},EtaParseError=class extends EtaError{static{__name(this,"EtaParseError")}constructor(message){super(message),this.name="EtaParser Error"}},EtaRuntimeError=class extends EtaError{static{__name(this,"EtaRuntimeError")}constructor(message){super(message),this.name="EtaRuntime Error"}},EtaFileResolutionError=class extends EtaError{static{__name(this,"EtaFileResolutionError")}constructor(message){super(message),this.name="EtaFileResolution Error"}},EtaNameResolutionError=class extends EtaError{static{__name(this,"EtaNameResolutionError")}constructor(message){super(message),this.name="EtaNameResolution Error"}};__name(ParseErr,"ParseErr");__name(RuntimeErr,"RuntimeErr");AsyncFunction=async function(){}.constructor;__name(compile,"compile");__name(compileToString,"compileToString");__name(compileBody,"compileBody");__name(trimWS,"trimWS");escMap={"&":"&","<":"<",">":">",'"':""","'":"'"};__name(replaceChar,"replaceChar");__name(XMLEscape,"XMLEscape");defaultConfig2={autoEscape:!0,autoFilter:!1,autoTrim:[!1,"nl"],cache:!1,cacheFilepaths:!0,debug:!1,escapeFunction:XMLEscape,filterFunction:__name(val2=>String(val2),"filterFunction"),functionHeader:"",parse:{exec:"",interpolate:"=",raw:"~"},plugins:[],rmWhitespace:!1,tags:["<%","%>"],useWith:!1,varName:"it",defaultExtension:".eta"},templateLitReg=/`(?:\\[\s\S]|\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})*}|(?!\${)[^\\`])*`/g,singleQuoteReg=/'(?:\\[\s\w"'\\`]|[^\n\r'\\])*?'/g,doubleQuoteReg=/"(?:\\[\s\w"'\\`]|[^\n\r"\\])*?"/g;__name(escapeRegExp,"escapeRegExp");__name(getLineNo,"getLineNo");__name(parse4,"parse");__name(handleCache,"handleCache");__name(render,"render");__name(renderAsync,"renderAsync");__name(renderString,"renderString");__name(renderStringAsync,"renderStringAsync");Eta$1=class{static{__name(this,"Eta$1")}constructor(customConfig){this.config=void 0,this.RuntimeErr=RuntimeErr,this.compile=compile,this.compileToString=compileToString,this.compileBody=compileBody,this.parse=parse4,this.render=render,this.renderAsync=renderAsync,this.renderString=renderString,this.renderStringAsync=renderStringAsync,this.filepathCache={},this.templatesSync=new Cacher({}),this.templatesAsync=new Cacher({}),this.resolvePath=null,this.readFile=null,customConfig?this.config={...defaultConfig2,...customConfig}:this.config={...defaultConfig2}}configure(customConfig){this.config={...this.config,...customConfig}}withConfig(customConfig){return{...this,config:{...this.config,...customConfig}}}loadTemplate(name,template,options){if(typeof template=="string")(options&&options.async?this.templatesAsync:this.templatesSync).define(name,this.compile(template,options));else{let templates=this.templatesSync;(template.constructor.name==="AsyncFunction"||options&&options.async)&&(templates=this.templatesAsync),templates.define(name,template)}}};__name(readFile,"readFile");__name(resolvePath2,"resolvePath");__name(dirIsChild,"dirIsChild");absolutePathRegExp=/^\\|^\//,Eta=class extends Eta$1{static{__name(this,"Eta")}constructor(...args){super(...args),this.readFile=readFile,this.resolvePath=resolvePath2}}}});import{existsSync as existsSync2}from"node:fs";import{dirname as dirname3,resolve as resolve2}from"node:path";import{fileURLToPath as fileURLToPath4}from"node:url";function assetPath(...segments){return resolve2(PACKAGE_ROOT2,"assets",...segments)}var HERE,IS_BUNDLED,PACKAGE_ROOT2,init_assets=__esm({"src/scripts/utils/assets.ts"(){HERE=dirname3(fileURLToPath4(import.meta.url)),IS_BUNDLED=existsSync2(resolve2(HERE,"bundle.json")),PACKAGE_ROOT2=IS_BUNDLED?resolve2(HERE,"..",".."):resolve2(HERE,"..","..","..");__name(assetPath,"assetPath")}});import{existsSync as existsSync3,mkdirSync as mkdirSync2,readFileSync as readFileSync4,readdirSync as readdirSync2,unlinkSync,writeFileSync as writeFileSync3}from"node:fs";import{dirname as dirname4,join as join5,resolve as resolve3}from"node:path";function getFormFiles(formsDir){return existsSync3(formsDir)?readdirSync2(formsDir).filter(f=>f.endsWith(".json")).map(f=>join5(formsDir,f)):[]}function readForm(path47){try{return JSON.parse(readFileSync4(path47,"utf-8"))}catch{return null}}function generateIndexContent(forms3){let lines=["// AUTO-GENERATED \u26A0\uFE0F \u2014 do not edit by hand",""];for(let form of forms3){let pascal=pascalCase(form.name),varName=pascal.charAt(0).toLowerCase()+pascal.slice(1);lines.push(`export { ${pascal}Schema, submit${pascal}, FORM_ID as ${varName}FormId } from "./${form.name}";`),lines.push(`export type { ${pascal}Data } from "./${form.name}";`)}return lines.push(""),lines.join(`
|
|
306
|
-
`)}function syncForms(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),formsDir=resolve3(cwd,FORMS_REL),templatePath2=assetPath("content-templates","form-template.eta"),templateSource=readFileSync4(templatePath2,"utf-8"),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),formFiles=getFormFiles(formsDir),expectedTsFiles=new Set,allForms=[],created=0,updated=0,deleted=0;for(let jsonPath of formFiles){let form=readForm(jsonPath);if(!form){console.error(`Failed to parse form: ${jsonPath}`);continue}form.name||(form.name=jsonPath.split("/").pop().replace(/\.json$/,"")),allForms.push(form);let tsPath=join5(formsDir,`${form.name}.ts`);expectedTsFiles.add(tsPath);try{let content2=eta.renderString(templateSource,{form:{...form,pascal:pascalCase(form.name)}}),dir=dirname4(tsPath);if(existsSync3(dir)||mkdirSync2(dir,{recursive:!0}),!existsSync3(tsPath)){writeFileSync3(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync4(tsPath,"utf-8")!==content2&&(writeFileSync3(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}catch(error){console.error(`Failed to generate ${tsPath}:`,error)}}if(allForms.length>0){let indexPath=join5(formsDir,"index.ts");expectedTsFiles.add(indexPath);let indexContent=generateIndexContent(allForms);(!existsSync3(indexPath)||readFileSync4(indexPath,"utf-8")!==indexContent)&&(writeFileSync3(indexPath,indexContent,"utf-8"),log(`Updated: ${indexPath}`))}if(existsSync3(formsDir)){let allTsFiles=readdirSync2(formsDir).filter(f=>f.endsWith(".ts")).map(f=>join5(formsDir,f));for(let tsFile of allTsFiles)if(!expectedTsFiles.has(tsFile))try{unlinkSync(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}}return(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync forms: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var FORMS_REL,init_sync_forms=__esm({"src/scripts/sync-forms.ts"(){init_dist6();init_eta_module();init_assets();FORMS_REL="src/forms";__name(getFormFiles,"getFormFiles");__name(readForm,"readForm");__name(generateIndexContent,"generateIndexContent");__name(syncForms,"syncForms")}});import{existsSync as existsSync4,mkdirSync as mkdirSync3,readFileSync as readFileSync5,readdirSync as readdirSync3,unlinkSync as unlinkSync2,writeFileSync as writeFileSync4}from"node:fs";import{basename,dirname as dirname5,join as join6,resolve as resolve4}from"node:path";import{z as
|
|
306
|
+
`)}function syncForms(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),formsDir=resolve3(cwd,FORMS_REL),templatePath2=assetPath("content-templates","form-template.eta"),templateSource=readFileSync4(templatePath2,"utf-8"),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),formFiles=getFormFiles(formsDir),expectedTsFiles=new Set,allForms=[],created=0,updated=0,deleted=0;for(let jsonPath of formFiles){let form=readForm(jsonPath);if(!form){console.error(`Failed to parse form: ${jsonPath}`);continue}form.name||(form.name=jsonPath.split("/").pop().replace(/\.json$/,"")),allForms.push(form);let tsPath=join5(formsDir,`${form.name}.ts`);expectedTsFiles.add(tsPath);try{let content2=eta.renderString(templateSource,{form:{...form,pascal:pascalCase(form.name)}}),dir=dirname4(tsPath);if(existsSync3(dir)||mkdirSync2(dir,{recursive:!0}),!existsSync3(tsPath)){writeFileSync3(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync4(tsPath,"utf-8")!==content2&&(writeFileSync3(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}catch(error){console.error(`Failed to generate ${tsPath}:`,error)}}if(allForms.length>0){let indexPath=join5(formsDir,"index.ts");expectedTsFiles.add(indexPath);let indexContent=generateIndexContent(allForms);(!existsSync3(indexPath)||readFileSync4(indexPath,"utf-8")!==indexContent)&&(writeFileSync3(indexPath,indexContent,"utf-8"),log(`Updated: ${indexPath}`))}if(existsSync3(formsDir)){let allTsFiles=readdirSync2(formsDir).filter(f=>f.endsWith(".ts")).map(f=>join5(formsDir,f));for(let tsFile of allTsFiles)if(!expectedTsFiles.has(tsFile))try{unlinkSync(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}}return(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync forms: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var FORMS_REL,init_sync_forms=__esm({"src/scripts/sync-forms.ts"(){init_dist6();init_eta_module();init_assets();FORMS_REL="src/forms";__name(getFormFiles,"getFormFiles");__name(readForm,"readForm");__name(generateIndexContent,"generateIndexContent");__name(syncForms,"syncForms")}});import{existsSync as existsSync4,mkdirSync as mkdirSync3,readFileSync as readFileSync5,readdirSync as readdirSync3,unlinkSync as unlinkSync2,writeFileSync as writeFileSync4}from"node:fs";import{basename,dirname as dirname5,join as join6,resolve as resolve4}from"node:path";import{z as z66}from"zod";function getSchemaFiles(schemasDir){return existsSync4(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".json")).map(f=>join6(schemasDir,f)):[]}function getGeneratedFiles(schemasDir){return existsSync4(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".ts")&&f!=="index.ts").map(f=>join6(schemasDir,f)):[]}function parseVersion(version){let match=/^(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?(?:\+.*)?$/.exec(version);return match?{parts:[Number(match[1]),Number(match[2]),Number(match[3])],prerelease:match[4]!==void 0}:null}function isVersionAtLeast(version,minimum){let parsed=parseVersion(version),parsedMinimum=parseVersion(minimum);if(!parsed||!parsedMinimum)return!1;for(let index2=0;index2<parsed.parts.length;index2++)if(parsed.parts[index2]!==parsedMinimum.parts[index2])return parsed.parts[index2]>parsedMinimum.parts[index2];return!parsed.prerelease||parsedMinimum.prerelease}function resolveProjectRuntime(cwd){let packagePath=join6(cwd,"node_modules","fimo","package.json");if(!existsSync4(packagePath))throw new Error(`Cannot generate schema clients because the project-local fimo package could not be resolved from ${cwd}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);let version;try{version=JSON.parse(readFileSync5(packagePath,"utf-8")).version}catch{version=null}if(typeof version!="string"||!parseVersion(version))throw new Error(`Cannot generate schema clients with project-local fimo@${typeof version=="string"?version:"unknown"}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return{packageRoot:dirname5(packagePath),version}}function templatePath(runtime,fileName){return runtime&&!isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)?join6(runtime.packageRoot,"assets","content-templates",fileName):assetPath("content-templates",fileName)}function loadSchemas(schemaFiles){let errors=[],schemas3=[],outputOwners=new Map;for(let path47 of schemaFiles){let fileUid=basename(path47,".json"),pascal=pascalCase(fileUid),existingOwner=outputOwners.get(pascal);existingOwner&&existingOwner!==fileUid?errors.push(`${basename(path47)} and ${existingOwner}.json both generate ${pascal}.ts. Rename one schema to keep generated module names unique.`):outputOwners.set(pascal,fileUid);let parsed;try{parsed=JSON.parse(readFileSync5(path47,"utf-8"))}catch(error){errors.push(`${basename(path47)} is invalid JSON: ${error instanceof Error?error.message:String(error)}`);continue}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){errors.push(`${basename(path47)} must contain a JSON object.`);continue}let candidate=parsed;if(typeof candidate.uid!="string"||candidate.uid.length===0){errors.push(`${basename(path47)} is missing "uid". Set it to "${fileUid}".`);continue}if(candidate.uid!==fileUid){errors.push(`${basename(path47)} declares uid "${candidate.uid}". It must match the file name "${fileUid}".`);continue}let validation=SCHEMA_DEFINITION_SCHEMA.safeParse(candidate);if(!validation.success){let details=validation.error.issues.map(issue=>`${issue.path.join(".")||"schema"}: ${issue.message}`).join("; ");errors.push(`${basename(path47)} has an invalid schema shape: ${details}`);continue}schemas3.push({pascal,schema:validation.data})}if(errors.length>0)throw new Error(`Cannot generate schema clients:
|
|
307
307
|
- ${errors.join(`
|
|
308
308
|
- `)}
|
|
309
|
-
No generated files were changed.`);return schemas3}function normalizeFields(fields){return Object.fromEntries(Object.entries(fields).map(([key,value])=>{if(!value||typeof value!="object"||Array.isArray(value))return[key,{type:void 0}];let field=value,target=typeof field.target=="string"?field.target:void 0,targets=Array.isArray(field.targets)?field.targets.filter(candidate=>typeof candidate=="string"):void 0;return[key,{...field,type:typeof field.type=="string"?field.type:void 0,target,targetPascal:target?pascalCase(target):void 0,targets:targets&&targets.length>0?targets:void 0,targetRefs:targets&&targets.length>0?targets.map(candidate=>({uid:candidate,pascal:pascalCase(candidate)})):void 0,many:typeof field.many=="boolean"?field.many:void 0,multiple:typeof field.multiple=="boolean"?field.multiple:void 0}]}))}function referenceImportsFor(schema,fields){let imports=new Map;for(let field of Object.values(fields)){if(field.type!=="reference")continue;let targets=field.targets??(field.target?[field.target]:[]);for(let target of targets)target!==schema.uid&&imports.set(target,{uid:target,pascal:pascalCase(target)})}return[...imports.values()].sort((a,b)=>a.pascal.localeCompare(b.pascal))}function schemaToModel(schema,localizedByUid){let fields=normalizeFields(schema.fields??{});return{uid:schema.uid,pascal:pascalCase(schema.uid),isSingleton:schema.isSingleton??!1,localized:schema.i18n?.enabled!==!1,localizedReferenceFields:Object.entries(fields).filter(([,field])=>field.type!=="reference"?!1:(field.targets??(field.target?[field.target]:[])).some(target=>localizedByUid.get(target)!==!1)).map(([fieldName])=>fieldName),fields,referenceImports:referenceImportsFor(schema,fields)}}function syncSchemas(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),schemasDir=resolve4(cwd,SCHEMAS_REL),schemaFiles=getSchemaFiles(schemasDir),schemas3=loadSchemas(schemaFiles),generatedFilesOnDisk=getGeneratedFiles(schemasDir),runtime=schemas3.length>0||generatedFilesOnDisk.length>0?resolveProjectRuntime(cwd):null,templates=[{suffix:".types.ts",path:templatePath(runtime,"types-template.eta")},{suffix:".ts",path:templatePath(runtime,"hooks-template.eta")}].map(template=>({...template,source:readFileSync5(template.path,"utf-8")})),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),localizedByUid=new Map(schemas3.map(({schema})=>[schema.uid,schema.i18n?.enabled!==!1])),expectedTsFiles=new Set,generatedFiles=new Map,created=0,updated=0,deleted=0;for(let{pascal,schema}of schemas3){let model=schemaToModel(schema,localizedByUid);for(let template of templates){let tsPath=join6(schemasDir,`${pascal}${template.suffix}`);expectedTsFiles.add(tsPath),generatedFiles.set(tsPath,eta.renderString(template.source,{model}))}}for(let[tsPath,content2]of generatedFiles){let dir=dirname5(tsPath);if(existsSync4(dir)||mkdirSync3(dir,{recursive:!0}),!existsSync4(tsPath)){writeFileSync4(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync5(tsPath,"utf-8")!==content2&&(writeFileSync4(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}for(let tsFile of generatedFilesOnDisk)if(!expectedTsFiles.has(tsFile))try{unlinkSync2(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}return(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync schemas: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var SCHEMAS_REL,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION,CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND,SCHEMA_DEFINITION_SCHEMA,init_sync_schemas=__esm({"src/scripts/sync-schemas.ts"(){init_dist6();init_eta_module();init_assets();SCHEMAS_REL="src/schemas",MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION="0.7.0",CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND="npm install fimo@latest",SCHEMA_DEFINITION_SCHEMA=
|
|
309
|
+
No generated files were changed.`);return schemas3}function normalizeFields(fields){return Object.fromEntries(Object.entries(fields).map(([key,value])=>{if(!value||typeof value!="object"||Array.isArray(value))return[key,{type:void 0}];let field=value,target=typeof field.target=="string"?field.target:void 0,targets=Array.isArray(field.targets)?field.targets.filter(candidate=>typeof candidate=="string"):void 0;return[key,{...field,type:typeof field.type=="string"?field.type:void 0,target,targetPascal:target?pascalCase(target):void 0,targets:targets&&targets.length>0?targets:void 0,targetRefs:targets&&targets.length>0?targets.map(candidate=>({uid:candidate,pascal:pascalCase(candidate)})):void 0,many:typeof field.many=="boolean"?field.many:void 0,multiple:typeof field.multiple=="boolean"?field.multiple:void 0}]}))}function referenceImportsFor(schema,fields){let imports=new Map;for(let field of Object.values(fields)){if(field.type!=="reference")continue;let targets=field.targets??(field.target?[field.target]:[]);for(let target of targets)target!==schema.uid&&imports.set(target,{uid:target,pascal:pascalCase(target)})}return[...imports.values()].sort((a,b)=>a.pascal.localeCompare(b.pascal))}function schemaToModel(schema,localizedByUid){let fields=normalizeFields(schema.fields??{});return{uid:schema.uid,pascal:pascalCase(schema.uid),isSingleton:schema.isSingleton??!1,localized:schema.i18n?.enabled!==!1,localizedReferenceFields:Object.entries(fields).filter(([,field])=>field.type!=="reference"?!1:(field.targets??(field.target?[field.target]:[])).some(target=>localizedByUid.get(target)!==!1)).map(([fieldName])=>fieldName),fields,referenceImports:referenceImportsFor(schema,fields)}}function syncSchemas(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),schemasDir=resolve4(cwd,SCHEMAS_REL),schemaFiles=getSchemaFiles(schemasDir),schemas3=loadSchemas(schemaFiles),generatedFilesOnDisk=getGeneratedFiles(schemasDir),runtime=schemas3.length>0||generatedFilesOnDisk.length>0?resolveProjectRuntime(cwd):null,templates=[{suffix:".types.ts",path:templatePath(runtime,"types-template.eta")},{suffix:".ts",path:templatePath(runtime,"hooks-template.eta")}].map(template=>({...template,source:readFileSync5(template.path,"utf-8")})),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),localizedByUid=new Map(schemas3.map(({schema})=>[schema.uid,schema.i18n?.enabled!==!1])),expectedTsFiles=new Set,generatedFiles=new Map,created=0,updated=0,deleted=0;for(let{pascal,schema}of schemas3){let model=schemaToModel(schema,localizedByUid);for(let template of templates){let tsPath=join6(schemasDir,`${pascal}${template.suffix}`);expectedTsFiles.add(tsPath),generatedFiles.set(tsPath,eta.renderString(template.source,{model}))}}for(let[tsPath,content2]of generatedFiles){let dir=dirname5(tsPath);if(existsSync4(dir)||mkdirSync3(dir,{recursive:!0}),!existsSync4(tsPath)){writeFileSync4(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync5(tsPath,"utf-8")!==content2&&(writeFileSync4(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}for(let tsFile of generatedFilesOnDisk)if(!expectedTsFiles.has(tsFile))try{unlinkSync2(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}return(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync schemas: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var SCHEMAS_REL,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION,CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND,SCHEMA_DEFINITION_SCHEMA,init_sync_schemas=__esm({"src/scripts/sync-schemas.ts"(){init_dist6();init_eta_module();init_assets();SCHEMAS_REL="src/schemas",MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION="0.7.0",CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND="npm install fimo@latest",SCHEMA_DEFINITION_SCHEMA=z66.object({uid:z66.string().min(1),isSingleton:z66.boolean().optional(),i18n:z66.object({enabled:z66.boolean().optional()}).optional(),fields:z66.record(z66.string(),z66.unknown()).optional()});__name(getSchemaFiles,"getSchemaFiles");__name(getGeneratedFiles,"getGeneratedFiles");__name(parseVersion,"parseVersion");__name(isVersionAtLeast,"isVersionAtLeast");__name(resolveProjectRuntime,"resolveProjectRuntime");__name(templatePath,"templatePath");__name(loadSchemas,"loadSchemas");__name(normalizeFields,"normalizeFields");__name(referenceImportsFor,"referenceImportsFor");__name(schemaToModel,"schemaToModel");__name(syncSchemas,"syncSchemas")}});function renderCrossSurface(findings,p2,opts={}){let lines=[];lines.push(p2.bold("CROSS-SURFACE INTEGRITY")),lines.push(p2.dim(" references that span surfaces"));let errorGlyph=opts.ascii?"!!":"\u203C",arrow=opts.ascii?"->":"\u2192",sep2=opts.ascii?"|":"\xB7";for(let f of findings){let glyph=f.severity==="error"?p2.red("!"):p2.yellow(errorGlyph);lines.push(` ${glyph} ${f.description}`);let trail=`${f.source.surface}:${f.source.key} ${arrow} ${f.target.surface}:${f.target.key}`;lines.push(p2.dim(` ${trail}`)),f.actions.length>0&&lines.push(p2.dim(` actions: ${f.actions.join(` ${sep2} `)}`))}return lines.join(`
|
|
310
310
|
`)}var init_cross_surface=__esm({"src/cli/utils/format/cross-surface.ts"(){__name(renderCrossSurface,"renderCrossSurface")}});function getTerminalWidth(){let w3=process.stdout.columns;return typeof w3=="number"&&w3>0?w3:100}function layoutKeyDetail(args){let{indent,key,keyLength,detail,detailLength=0,width}=args;if(!detail)return`${indent}${key}`;let minGap=args.minGap??2,used=indent.length+keyLength+minGap+detailLength;if(width<80||used>=width)return`${indent}${key}${" ".repeat(minGap)}${detail}`;let padding=width-indent.length-keyLength-detailLength;return`${indent}${key}${" ".repeat(padding)}${detail}`}var init_columns=__esm({"src/cli/utils/format/columns.ts"(){__name(getTerminalWidth,"getTerminalWidth");__name(layoutKeyDetail,"layoutKeyDetail")}});var activations,init_activations=__esm({"src/cli/utils/format/surface-presenters/activations.ts"(){activations={label:"AGENTS",hint:"declared \xB7 active",emptyCopy:" (no agents activated)",groupBy:__name(item=>item.detail??"(no agent)","groupBy"),keyFormatter:__name(item=>{let idx=item.key.indexOf(":");return idx>0?`trigger ${item.key.slice(idx+1)}`:item.key},"keyFormatter"),detailFormatter:__name(()=>{},"detailFormatter")}}});function shortId(id){return id.length>12?`${id.slice(0,8)}\u2026`:id}var assets,init_assets2=__esm({"src/cli/utils/format/surface-presenters/assets.ts"(){assets={label:"ASSETS",hint:"media library",emptyCopy:" (no asset changes)",keyFormatter:__name(item=>item.detail??item.key,"keyFormatter"),detailFormatter:__name(item=>{if(item.detail&&item.key!==item.detail)return shortId(item.key)},"detailFormatter")};__name(shortId,"shortId")}});var code,init_code=__esm({"src/cli/utils/format/surface-presenters/code.ts"(){code={label:"CODE",hint:"git workspace vs HEAD",emptyCopy:" (clean)"}}});var content,init_content=__esm({"src/cli/utils/format/surface-presenters/content.ts"(){content={label:"CONTENT",hint:"entries per collection",emptyCopy:" (no content changes)",groupBy:__name(item=>item.detail??"(unknown)","groupBy"),keyFormatter:__name(item=>{let idx=item.key.indexOf(":");return idx>0?item.key.slice(idx+1):item.key},"keyFormatter"),detailFormatter:__name(()=>{},"detailFormatter")}}});var forms,init_forms=__esm({"src/cli/utils/format/surface-presenters/forms.ts"(){forms={label:"FORMS",hint:"schema changes",emptyCopy:" (no form changes)"}}});var schemas,init_schemas=__esm({"src/cli/utils/format/surface-presenters/schemas.ts"(){schemas={label:"SCHEMAS",hint:"content types",emptyCopy:" (no schema changes)",groupBy:__name(item=>{let idx=item.key.indexOf(".");return idx>0?item.key.slice(0,idx):""},"groupBy"),keyFormatter:__name(item=>{let idx=item.key.indexOf(".");return idx>0?item.key.slice(idx+1):item.key},"keyFormatter")}}});var translations,init_translations=__esm({"src/cli/utils/format/surface-presenters/translations.ts"(){translations={label:"TRANSLATIONS",hint:"per locale",emptyCopy:" (no translation changes)",groupBy:__name(item=>item.detail??"(no locale)","groupBy"),keyFormatter:__name(item=>{let idx=item.key.indexOf(":");return idx>0?item.key.slice(idx+1):item.key},"keyFormatter"),detailFormatter:__name(()=>{},"detailFormatter")}}});var SURFACE_PRESENTERS,init_surface_presenters=__esm({"src/cli/utils/format/surface-presenters/index.ts"(){init_activations();init_assets2();init_code();init_content();init_forms();init_schemas();init_translations();SURFACE_PRESENTERS={code,schemas,content,translations,assets,forms,activations}}});function renderItem(item,p2,opts={}){let glyph=VERB_GLYPHS[item.verb]??"?",colored=item.verb==="added"?p2.green(glyph):item.verb==="removed"?p2.red(glyph):item.verb==="conflict"?p2.yellow(glyph):p2.blue(glyph),indent=opts.indent??" ",displayKey=opts.presenter?.keyFormatter?opts.presenter.keyFormatter(item):item.key,displayDetail=opts.presenter?.detailFormatter?opts.presenter.detailFormatter(item):item.detail,width=opts.width;if(item.origin===void 0)return layoutCore({indent,marker:"",markerLen:0,colored,displayKey,displayDetail,width,p:p2});let marker=item.origin==="local-uncommitted"?p2.yellow("*"):" ";return layoutCore({indent,marker,markerLen:1,colored,displayKey,displayDetail,width,p:p2})}function layoutCore(args){let{indent,marker,markerLen,colored,displayKey,displayDetail,width,p:p2}=args,prefix=`${marker}${colored} ${displayKey}`,prefixLen=markerLen+1+1+displayKey.length;return displayDetail?width===void 0?`${indent}${prefix}${p2.dim(` ${displayDetail}`)}`:layoutKeyDetail({indent,key:prefix,keyLength:prefixLen,detail:p2.dim(displayDetail),detailLength:displayDetail.length,width}):`${indent}${prefix}`}function renderSurface(delta,p2,opts={}){let display=SURFACE_DISPLAY[delta.surface],presenter=SURFACE_PRESENTERS[delta.surface],lines=[],includeHeader=opts.includeHeader??!0,maxItems=opts.maxItems??50,width=opts.width??getTerminalWidth();if(includeHeader&&(lines.push(p2.bold(display.label)),lines.push(p2.dim(` ${display.hint}`))),delta.status==="timed_out")return lines.push(p2.yellow(" (surface check timed out)")),lines.join(`
|
|
311
311
|
`);if(delta.status==="failed")return lines.push(p2.red(` (surface check failed: ${delta.error??"unknown"})`)),lines.join(`
|
|
312
312
|
`);if(delta.status==="unchanged"||delta.changedCount===0&&delta.conflictCount===0)return lines.push(p2.dim(display.emptyCopy)),lines.join(`
|
|
@@ -1125,7 +1125,7 @@ Fix: add the route to src/routes.ts. Example: route('${route.path.replace(/^\//,
|
|
|
1125
1125
|
Fix: create the file at src/${file}.`);continue}if(route.paramNames.length>0)if(!route.params)errors.push(`Dynamic route "${route.id}" (${route.path}) needs \`params\` metadata to generate prerender URLs.
|
|
1126
1126
|
Fix: add to the route in fimo-config.json: \`"params": { "${route.paramNames[0]||"param"}": { "schema": "SchemaName", "queryField": "${route.paramNames[0]||"slug"}", "displayField": "title" } }\``);else for(let paramName of route.paramNames){let paramInfo=route.params[paramName];!paramInfo||typeof paramInfo!="object"?errors.push(`Dynamic route "${route.id}" (${route.path}): param "${paramName}" must be an object with "schema" and "queryField".
|
|
1127
1127
|
Fix: \`"params": { "${paramName}": { "schema": "SchemaName", "queryField": "${paramName}" } }\``):(!paramInfo.schema||!paramInfo.queryField)&&errors.push(`Dynamic route "${route.id}" (${route.path}): param "${paramName}" is missing ${paramInfo.schema?'"queryField"':'"schema"'}.
|
|
1128
|
-
Fix: \`"${paramName}": { "schema": "SchemaName", "queryField": "${paramName}" }\``)}if(route.seo){let GLOBAL_VARIABLES=new Set(["siteName","label"]),seoFields=[{name:"title",value:route.seo.title},{name:"description",value:route.seo.description}];for(let field of seoFields){if(typeof field.value!="string")continue;let templatePattern=/\{\{([^}]+)\}\}/g,match;for(;(match=templatePattern.exec(field.value))!==null;){let variable=match[1].trim();if(!GLOBAL_VARIABLES.has(variable))if(variable.includes(".")){let paramKey=variable.split(".")[0];if(!route.params||!route.params[paramKey]){let availableParams=route.params?Object.keys(route.params).join(", "):"none";errors.push(`Route "${route.id}" (${route.path}): SEO ${field.name} references "{{${variable}}}" but "${paramKey}" is not a declared param. Available params: ${availableParams}.`)}}else{let availableParams=route.params?Object.keys(route.params).join(", "):"none";errors.push(`Route "${route.id}" (${route.path}): SEO ${field.name} references "{{${variable}}}" which is not a global variable (siteName, label) and not a dotted param reference (e.g., "{{param.field}}"). Available params: ${availableParams}.`)}}}}}return{errors,routesChecked:configRoutes.length}}__name(validateRouteMetadata,"validateRouteMetadata");function validateI18nConfig(config){let rawI18n=isRecord(config.i18n)?config.i18n:{},errors=[],rawDefaultLocale=typeof rawI18n.defaultLocale=="string"?rawI18n.defaultLocale:"en",defaultLocale=normalizeFimoLocale(rawDefaultLocale);defaultLocale||errors.push(`Invalid i18n.defaultLocale "${rawDefaultLocale}". Use a structurally valid locale tag, for example "en", "es", or "pt-BR".`);let rawLocales=Array.isArray(rawI18n.locales)?rawI18n.locales:defaultLocale?[defaultLocale]:[];rawI18n.locales!==void 0&&!Array.isArray(rawI18n.locales)&&errors.push("i18n.locales must be an array of locale strings.");let locales=[],seenLocales=new Set;for(let rawLocale of rawLocales){if(typeof rawLocale!="string"){errors.push(`Invalid i18n.locales entry ${JSON.stringify(rawLocale)}. Locale entries must be strings.`);continue}let locale=normalizeFimoLocale(rawLocale);if(!locale){errors.push(`Invalid i18n.locales entry "${rawLocale}". Use a structurally valid locale tag, for example "en", "es", or "pt-BR".`);continue}seenLocales.has(locale)||(seenLocales.add(locale),locales.push(locale))}let effectiveDefaultLocale=defaultLocale??"en";seenLocales.has(effectiveDefaultLocale)||(errors.push(`i18n.locales must include i18n.defaultLocale "${effectiveDefaultLocale}".`),locales.unshift(effectiveDefaultLocale));let rawRouting=isRecord(rawI18n.routing)?rawI18n.routing:{},routingStrategy=typeof rawRouting.strategy=="string"?rawRouting.strategy:"path-prefix";return routingStrategy!=="path-prefix"&&errors.push(`Unsupported i18n.routing.strategy "${routingStrategy}". Supported now: "path-prefix".`),{defaultLocale:effectiveDefaultLocale,locales,routingStrategy,prefixDefaultLocale:rawRouting.prefixDefaultLocale===!0,errors}}__name(validateI18nConfig,"validateI18nConfig");function validateLocaleRouteCollisions(args){let errors=[],reservedPrefixes=new Set(args.i18n.locales.map(locale=>locale.toLowerCase()));for(let route of args.configRoutes){let first2=firstPathSegment(route.path);first2&&reservedPrefixes.has(first2.toLowerCase())&&errors.push(`Route "${route.id}" (${route.path}) uses reserved locale prefix "${first2}". Keep fimo-config.json routes canonical and unlocalized, for example "/pricing"; let fimoRoutes() or custom locale routing produce "/${first2}/...".`)}if(!args.routesSourceUsesFimoRoutes)for(let route of args.fileRoutes){if(!route.path||route.isLayout)continue;let first2=firstPathSegment(route.path);(first2?.startsWith(":")||first2==="*")&&errors.push(`Route "${route.path}" is a top-level dynamic route in a multi-locale path-prefix project. It can capture locale URLs like "/${args.i18n.locales[0]}". Use fimoRoutes(routes) from "fimo/react-router/routes" or implement explicit custom locale routing.`)}return errors}__name(validateLocaleRouteCollisions,"validateLocaleRouteCollisions");function sourceUsesFimoRoutes(fileRoutes,routesFilePath){return fileRoutes.length===0||!fs18.existsSync(routesFilePath)?!1:fs18.readFileSync(routesFilePath,"utf-8").includes("fimoRoutes(")}__name(sourceUsesFimoRoutes,"sourceUsesFimoRoutes");function firstPathSegment(routePath){return routePath.split("/").filter(Boolean)[0]??null}__name(firstPathSegment,"firstPathSegment");function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");function normalizeFimoLocale(locale){let trimmed=locale?.trim();if(!trimmed)return null;let candidate=trimmed.replace(/_/g,"-");try{return Intl.getCanonicalLocales(candidate)[0]??null}catch{return null}}__name(normalizeFimoLocale,"normalizeFimoLocale");init_esm();import{existsSync as existsSync5,readFileSync as readFileSync6,readdirSync as readdirSync4}from"node:fs";import{basename as basename2,join as join7,resolve as resolve5}from"node:path";var SCHEMAS_REL2="src/schemas",FIELD_TYPES=new Set(FieldTypeSchema.options),RESERVED_FIELD_NAMES=new Set(RESERVED_CONTENT_FIELD_NAMES);function validateSchemas(options={}){let cwd=resolve5(options.cwd??process.cwd()),schemasDir=join7(cwd,SCHEMAS_REL2);if(!existsSync5(schemasDir))return{errors:[],schemasChecked:0};let files=readdirSync4(schemasDir).filter(f=>f.endsWith(".json")).sort(),errors=[],schemaUids=new Set;for(let fileName of files){let schema=readSchemaObject(join7(schemasDir,fileName));schema&&typeof schema.uid=="string"&&schemaUids.add(schema.uid)}for(let fileName of files){let file=join7(SCHEMAS_REL2,fileName);errors.push(...validateSchemaFile(join7(schemasDir,fileName),file,schemaUids))}return{errors,schemasChecked:files.length}}__name(validateSchemas,"validateSchemas");function readSchemaObject(absolutePath){let schema;try{schema=JSON.parse(readFileSync6(absolutePath,"utf-8"))}catch{return null}return typeof schema=="object"&&schema!==null&&!Array.isArray(schema)?schema:null}__name(readSchemaObject,"readSchemaObject");function validateSchemaFile(absolutePath,file,schemaUids=new Set){let schema;try{schema=JSON.parse(readFileSync6(absolutePath,"utf-8"))}catch(error){return[{rule:"schemas/parse",message:`Invalid JSON: ${error instanceof Error?error.message:String(error)}`,file}]}if(typeof schema!="object"||schema===null||Array.isArray(schema))return[{rule:"schemas/shape",message:"Schema must be a JSON object.",file}];let errors=[],{uid,name,fields,i18n,isSingleton}=schema,expectedUid=basename2(file,".json");if(typeof uid!="string"||uid.length===0?errors.push({rule:"schemas/uid",message:`Missing "uid". Set it to the file name: "${expectedUid}".`,file}):uid!==expectedUid?errors.push({rule:"schemas/uid",message:`"uid" is "${uid}" but the file is ${expectedUid}.json \u2014 they must match.`,file}):CONTENT_TYPE_NAME_PATTERN.test(uid)||errors.push({rule:"schemas/type-name",message:`"uid" must use ${CONTENT_TYPE_NAME_PATTERN_DESCRIPTION}.`,file}),(typeof name!="string"||name.length===0)&&errors.push({rule:"schemas/name",message:'Missing "name" (the human-readable label).',file}),isSingleton!==void 0&&typeof isSingleton!="boolean"&&errors.push({rule:"schemas/singleton",message:'"isSingleton" must be a boolean when provided.',file}),i18n!==void 0)if(typeof i18n!="object"||i18n===null||Array.isArray(i18n))errors.push({rule:"schemas/i18n",message:'"i18n" must be an object like { "enabled": false }.',file});else{let keys=Object.keys(i18n);(keys.length!==1||keys[0]!=="enabled"||typeof i18n.enabled!="boolean")&&errors.push({rule:"schemas/i18n",message:'"i18n" only supports one boolean option: { "enabled": true | false }.',file})}if(typeof fields!="object"||fields===null||Array.isArray(fields))return errors.push({rule:"schemas/fields",message:'Missing "fields" object.',file}),errors;for(let[fieldName,definition]of Object.entries(fields)){if(!CONTENT_FIELD_NAME_PATTERN.test(fieldName)){errors.push({rule:"schemas/field-name",message:`Field "${fieldName}" must use ${CONTENT_FIELD_NAME_PATTERN_DESCRIPTION}.`,file});continue}if(RESERVED_FIELD_NAMES.has(fieldName)){errors.push({rule:"schemas/reserved-field",message:`Field "${fieldName}" is reserved entry metadata \u2014 the platform manages it automatically. Remove it from the schema${fieldName==="slug"?" (set slug inside entry data on create instead)":""}.`,file});continue}if(typeof definition!="object"||definition===null||Array.isArray(definition)){errors.push({rule:"schemas/field-shape",message:`Field "${fieldName}" must be an object like { "type": "string" }.`,file});continue}let{type}=definition;if((typeof type!="string"||!FIELD_TYPES.has(type))&&errors.push({rule:"schemas/field-type",message:`Field "${fieldName}" has unsupported type "${String(type)}". Allowed: ${[...FIELD_TYPES].join(", ")}.`,file}),"i18n"in definition||"localized"in definition){let key="i18n"in definition?"i18n":"localized";errors.push({rule:"schemas/field-i18n",message:`Field "${fieldName}": field-level locale settings ("${key}") are not supported.`,file})}if(type==="blocks"){let parsed=ContentFieldDefinitionSchema.safeParse(definition);if(!parsed.success){for(let issue of parsed.error.issues)errors.push({rule:"schemas/structured-content-shape",message:`Field "${fieldName}"${issue.path.length>0?` at ${issue.path.join(".")}`:""}: ${issue.message}`,file});continue}walkContentFields({[fieldName]:parsed.data},({field,path:path47,structuredDepth,insideStructuredContent})=>{if(field.type==="blocks"&&structuredDepth>=MAX_STRUCTURED_CONTENT_DEPTH&&errors.push({rule:"schemas/structured-content-depth",message:`Field "${path47.join(".")}" exceeds the ${MAX_STRUCTURED_CONTENT_DEPTH}-level blocks limit.`,file}),!(!insideStructuredContent||field.type!=="reference")){if(field.targets){errors.push({rule:"schemas/structured-content-reference",message:`Reference field "${path47.join(".")}" must use one fixed "target" inside blocks.`,file});return}field.target&&schemaUids.size>0&&!schemaUids.has(field.target)&&errors.push({rule:"schemas/reference-target",message:`Reference field "${path47.join(".")}" targets unknown schema "${field.target}".`,file})}});continue}if(type==="reference"){let{target,targets,many}=definition;if(targets!==void 0&&target!==void 0)errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" declares both "target" and "targets" \u2014 a field is fixed or polymorphic, never both.`,file});else if(targets!==void 0){let targetList=Array.isArray(targets)?targets:null;if(!targetList||targetList.length===0||new Set(targetList).size!==targetList.length)errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" must declare "targets" as a non-empty array of unique content types.`,file});else for(let candidate of targetList)typeof candidate!="string"||!CONTENT_TYPE_NAME_PATTERN.test(candidate)?errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" has an invalid entry in "targets".`,file}):schemaUids.size>0&&!schemaUids.has(candidate)&&errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" targets unknown schema "${candidate}".`,file})}else typeof target!="string"||!CONTENT_TYPE_NAME_PATTERN.test(target)?errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" must declare a valid "target" content type (or "targets" for a polymorphic field).`,file}):schemaUids.size>0&&!schemaUids.has(target)&&errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" targets unknown schema "${target}".`,file});many!==void 0&&typeof many!="boolean"&&errors.push({rule:"schemas/reference-many",message:`Reference field "${fieldName}" must use a boolean "many" value.`,file})}else for(let referenceOnlyKey of["target","targets","many"])referenceOnlyKey in definition&&errors.push({rule:"schemas/reference-shape",message:`Field "${fieldName}": "${referenceOnlyKey}" is only supported on reference fields.`,file})}return errors}__name(validateSchemaFile,"validateSchemaFile");init_api();init_config();init_auth_errors();import fs19 from"node:fs";import path22 from"node:path";var MIN_DB_LABELS_FIMO_VERSION="0.2.5",MIN_DB_LABELS_TEMPLATE_VERSION=4;function getDbLabelsRuntimeWarning(cwd){if(readExplicitConfigVersion(cwd)<MIN_DB_LABELS_TEMPLATE_VERSION)return null;let projectPackage=readPackageJson(path22.join(cwd,"package.json")),fimoSpec=findFimoSpec(projectPackage);if(!fimoSpec)return buildWarning("package.json has no fimo dependency");let source=findRuntimeVersion(cwd,fimoSpec);return!source||!isVersionOlder(source.version,MIN_DB_LABELS_FIMO_VERSION)?null:buildWarning(`${source.label} is fimo@${source.version}`)}__name(getDbLabelsRuntimeWarning,"getDbLabelsRuntimeWarning");function readExplicitConfigVersion(cwd){try{let raw=JSON.parse(fs19.readFileSync(path22.join(cwd,"fimo-config.json"),"utf8")),parsed=Number.parseInt(String(raw.version),10);return Number.isFinite(parsed)&&parsed>0?parsed:0}catch{return 0}}__name(readExplicitConfigVersion,"readExplicitConfigVersion");function buildWarning(subject){return[`CRITICAL: ${subject}, but DB-owned labels require fimo >= ${MIN_DB_LABELS_FIMO_VERSION}.`,"Labels changed with `fimo labels` or Fimo Studio may not render in this project until the app runtime is upgraded.","Run `npm install fimo@latest` (or your package manager equivalent), then run `fimo validate` again."].join(" ")}__name(buildWarning,"buildWarning");function findRuntimeVersion(cwd,fimoSpec){let installed=readPackageJson(path22.join(cwd,"node_modules","fimo","package.json"));if(typeof installed?.version=="string")return{label:"installed node_modules/fimo",version:installed.version};let packageLockVersion=readPackageLockVersion(cwd);if(packageLockVersion)return{label:"package-lock.json",version:packageLockVersion};let exactSpecVersion=parseVersion2(fimoSpec);if(exactSpecVersion)return{label:"package.json dependency",version:exactSpecVersion.normalized};if(fimoSpec.startsWith("file:")){let fileVersion=readFileDependencyVersion(cwd,fimoSpec);if(fileVersion)return{label:"package.json file dependency target",version:fileVersion}}return null}__name(findRuntimeVersion,"findRuntimeVersion");function findFimoSpec(pkg){let dependenciesSpec=pkg?.dependencies?.fimo;if(typeof dependenciesSpec=="string"&&dependenciesSpec.trim())return dependenciesSpec.trim();let devDependenciesSpec=pkg?.devDependencies?.fimo;return typeof devDependenciesSpec=="string"&&devDependenciesSpec.trim()?devDependenciesSpec.trim():null}__name(findFimoSpec,"findFimoSpec");function readFileDependencyVersion(cwd,spec){let rawPath=spec.slice(5),packageRoot=path22.isAbsolute(rawPath)?rawPath:path22.resolve(cwd,rawPath),pkg=readPackageJson(path22.join(packageRoot,"package.json"));return typeof pkg?.version=="string"?pkg.version:null}__name(readFileDependencyVersion,"readFileDependencyVersion");function readPackageLockVersion(cwd){try{let lock=JSON.parse(fs19.readFileSync(path22.join(cwd,"package-lock.json"),"utf8")),packagesVersion=lock.packages?.["node_modules/fimo"]?.version;if(typeof packagesVersion=="string")return packagesVersion;let dependencyVersion=lock.dependencies?.fimo?.version;return typeof dependencyVersion=="string"?dependencyVersion:null}catch{return null}}__name(readPackageLockVersion,"readPackageLockVersion");function readPackageJson(filePath){try{return JSON.parse(fs19.readFileSync(filePath,"utf8"))}catch{return null}}__name(readPackageJson,"readPackageJson");function isVersionOlder(version,minimum){let parsed=parseVersion2(version),parsedMinimum=parseVersion2(minimum);if(!parsed||!parsedMinimum)return!1;for(let key of["major","minor","patch"]){if(parsed[key]<parsedMinimum[key])return!0;if(parsed[key]>parsedMinimum[key])return!1}return!1}__name(isVersionOlder,"isVersionOlder");function parseVersion2(version){let match=version.trim().match(/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return match?{major:Number(match[1]),minor:Number(match[2]),patch:Number(match[3]),normalized:`${Number(match[1])}.${Number(match[2])}.${Number(match[3])}`}:null}__name(parseVersion2,"parseVersion");init_project_context();init_project();init_dist();import{existsSync as existsSync7,readFileSync as readFileSync8,readdirSync as readdirSync6,statSync as statSync3}from"node:fs";import{join as join9,resolve as resolve6}from"node:path";import fs20 from"node:fs/promises";import path23 from"node:path";async function pathExists(targetPath){try{return await fs20.access(targetPath),!0}catch{return!1}}__name(pathExists,"pathExists");async function removeDataFiles(dir){let entries2=await fs20.readdir(dir,{withFileTypes:!0});for(let entry of entries2){let fullPath=path23.join(dir,entry.name);entry.isDirectory()?await removeDataFiles(fullPath):entry.name.endsWith(".data")&&await fs20.rm(fullPath)}}__name(removeDataFiles,"removeDataFiles");async function exportStatic(options={}){let cwd=options.cwd??process.cwd(),clientDir=path23.resolve(cwd,"dist/client"),serverDir=path23.resolve(cwd,"dist/server");if(!await pathExists(clientDir))throw new Error("Missing dist/client output. Run `react-router build` first.");await pathExists(serverDir)&&await fs20.rm(serverDir,{recursive:!0,force:!0}),await removeDataFiles(clientDir),console.log("Static export complete.")}__name(exportStatic,"exportStatic");import{existsSync as existsSync6,readFileSync as readFileSync7,readdirSync as readdirSync5,statSync as statSync2}from"fs";import{join as join8}from"path";import{parseSync as parseSync2}from"oxc-parser";var SRC_DIR="src";function getLineAndColumn(code2,offset){let lines=code2.slice(0,offset).split(`
|
|
1128
|
+
Fix: \`"${paramName}": { "schema": "SchemaName", "queryField": "${paramName}" }\``)}if(route.seo){let GLOBAL_VARIABLES=new Set(["siteName","label"]),seoFields=[{name:"title",value:route.seo.title},{name:"description",value:route.seo.description}];for(let field of seoFields){if(typeof field.value!="string")continue;let templatePattern=/\{\{([^}]+)\}\}/g,match;for(;(match=templatePattern.exec(field.value))!==null;){let variable=match[1].trim();if(!GLOBAL_VARIABLES.has(variable))if(variable.includes(".")){let paramKey=variable.split(".")[0];if(!route.params||!route.params[paramKey]){let availableParams=route.params?Object.keys(route.params).join(", "):"none";errors.push(`Route "${route.id}" (${route.path}): SEO ${field.name} references "{{${variable}}}" but "${paramKey}" is not a declared param. Available params: ${availableParams}.`)}}else{let availableParams=route.params?Object.keys(route.params).join(", "):"none";errors.push(`Route "${route.id}" (${route.path}): SEO ${field.name} references "{{${variable}}}" which is not a global variable (siteName, label) and not a dotted param reference (e.g., "{{param.field}}"). Available params: ${availableParams}.`)}}}}}return{errors,routesChecked:configRoutes.length}}__name(validateRouteMetadata,"validateRouteMetadata");function validateI18nConfig(config){let rawI18n=isRecord(config.i18n)?config.i18n:{},errors=[],rawDefaultLocale=typeof rawI18n.defaultLocale=="string"?rawI18n.defaultLocale:"en",defaultLocale=normalizeFimoLocale(rawDefaultLocale);defaultLocale||errors.push(`Invalid i18n.defaultLocale "${rawDefaultLocale}". Use a structurally valid locale tag, for example "en", "es", or "pt-BR".`);let rawLocales=Array.isArray(rawI18n.locales)?rawI18n.locales:defaultLocale?[defaultLocale]:[];rawI18n.locales!==void 0&&!Array.isArray(rawI18n.locales)&&errors.push("i18n.locales must be an array of locale strings.");let locales=[],seenLocales=new Set;for(let rawLocale of rawLocales){if(typeof rawLocale!="string"){errors.push(`Invalid i18n.locales entry ${JSON.stringify(rawLocale)}. Locale entries must be strings.`);continue}let locale=normalizeFimoLocale(rawLocale);if(!locale){errors.push(`Invalid i18n.locales entry "${rawLocale}". Use a structurally valid locale tag, for example "en", "es", or "pt-BR".`);continue}seenLocales.has(locale)||(seenLocales.add(locale),locales.push(locale))}let effectiveDefaultLocale=defaultLocale??"en";seenLocales.has(effectiveDefaultLocale)||(errors.push(`i18n.locales must include i18n.defaultLocale "${effectiveDefaultLocale}".`),locales.unshift(effectiveDefaultLocale));let rawRouting=isRecord(rawI18n.routing)?rawI18n.routing:{},routingStrategy=typeof rawRouting.strategy=="string"?rawRouting.strategy:"path-prefix";return routingStrategy!=="path-prefix"&&errors.push(`Unsupported i18n.routing.strategy "${routingStrategy}". Supported now: "path-prefix".`),{defaultLocale:effectiveDefaultLocale,locales,routingStrategy,prefixDefaultLocale:rawRouting.prefixDefaultLocale===!0,errors}}__name(validateI18nConfig,"validateI18nConfig");function validateLocaleRouteCollisions(args){let errors=[],reservedPrefixes=new Set(args.i18n.locales.map(locale=>locale.toLowerCase()));for(let route of args.configRoutes){let first2=firstPathSegment(route.path);first2&&reservedPrefixes.has(first2.toLowerCase())&&errors.push(`Route "${route.id}" (${route.path}) uses reserved locale prefix "${first2}". Keep fimo-config.json routes canonical and unlocalized, for example "/pricing"; let fimoRoutes() or custom locale routing produce "/${first2}/...".`)}if(!args.routesSourceUsesFimoRoutes)for(let route of args.fileRoutes){if(!route.path||route.isLayout)continue;let first2=firstPathSegment(route.path);(first2?.startsWith(":")||first2==="*")&&errors.push(`Route "${route.path}" is a top-level dynamic route in a multi-locale path-prefix project. It can capture locale URLs like "/${args.i18n.locales[0]}". Use fimoRoutes(routes) from "fimo/react-router/routes" or implement explicit custom locale routing.`)}return errors}__name(validateLocaleRouteCollisions,"validateLocaleRouteCollisions");function sourceUsesFimoRoutes(fileRoutes,routesFilePath){return fileRoutes.length===0||!fs18.existsSync(routesFilePath)?!1:fs18.readFileSync(routesFilePath,"utf-8").includes("fimoRoutes(")}__name(sourceUsesFimoRoutes,"sourceUsesFimoRoutes");function firstPathSegment(routePath){return routePath.split("/").filter(Boolean)[0]??null}__name(firstPathSegment,"firstPathSegment");function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");function normalizeFimoLocale(locale){let trimmed=locale?.trim();if(!trimmed)return null;let candidate=trimmed.replace(/_/g,"-");try{return Intl.getCanonicalLocales(candidate)[0]??null}catch{return null}}__name(normalizeFimoLocale,"normalizeFimoLocale");init_esm();import{existsSync as existsSync5,readFileSync as readFileSync6,readdirSync as readdirSync4}from"node:fs";import{basename as basename2,join as join7,resolve as resolve5}from"node:path";var SCHEMAS_REL2="src/schemas",FIELD_TYPES=new Set(FieldTypeSchema.options),RESERVED_FIELD_NAMES=new Set(RESERVED_CONTENT_FIELD_NAMES);function validateSchemas(options={}){let cwd=resolve5(options.cwd??process.cwd()),schemasDir=join7(cwd,SCHEMAS_REL2);if(!existsSync5(schemasDir))return{errors:[],schemasChecked:0};let files=readdirSync4(schemasDir).filter(f=>f.endsWith(".json")).sort(),errors=[],schemaUids=new Set;for(let fileName of files){let schema=readSchemaObject(join7(schemasDir,fileName));schema&&typeof schema.uid=="string"&&schemaUids.add(schema.uid)}for(let fileName of files){let file=join7(SCHEMAS_REL2,fileName);errors.push(...validateSchemaFile(join7(schemasDir,fileName),file,schemaUids))}return{errors,schemasChecked:files.length}}__name(validateSchemas,"validateSchemas");function readSchemaObject(absolutePath){let schema;try{schema=JSON.parse(readFileSync6(absolutePath,"utf-8"))}catch{return null}return typeof schema=="object"&&schema!==null&&!Array.isArray(schema)?schema:null}__name(readSchemaObject,"readSchemaObject");function validateSchemaFile(absolutePath,file,schemaUids=new Set){let schema;try{schema=JSON.parse(readFileSync6(absolutePath,"utf-8"))}catch(error){return[{rule:"schemas/parse",message:`Invalid JSON: ${error instanceof Error?error.message:String(error)}`,file}]}if(typeof schema!="object"||schema===null||Array.isArray(schema))return[{rule:"schemas/shape",message:"Schema must be a JSON object.",file}];let errors=[],{uid,name,fields,i18n,isSingleton}=schema,expectedUid=basename2(file,".json");if(typeof uid!="string"||uid.length===0?errors.push({rule:"schemas/uid",message:`Missing "uid". Set it to the file name: "${expectedUid}".`,file}):uid!==expectedUid?errors.push({rule:"schemas/uid",message:`"uid" is "${uid}" but the file is ${expectedUid}.json \u2014 they must match.`,file}):CONTENT_TYPE_NAME_PATTERN.test(uid)||errors.push({rule:"schemas/type-name",message:`"uid" must use ${CONTENT_TYPE_NAME_PATTERN_DESCRIPTION}.`,file}),(typeof name!="string"||name.length===0)&&errors.push({rule:"schemas/name",message:'Missing "name" (the human-readable label).',file}),isSingleton!==void 0&&typeof isSingleton!="boolean"&&errors.push({rule:"schemas/singleton",message:'"isSingleton" must be a boolean when provided.',file}),i18n!==void 0)if(typeof i18n!="object"||i18n===null||Array.isArray(i18n))errors.push({rule:"schemas/i18n",message:'"i18n" must be an object like { "enabled": false }.',file});else{let keys=Object.keys(i18n);(keys.length!==1||keys[0]!=="enabled"||typeof i18n.enabled!="boolean")&&errors.push({rule:"schemas/i18n",message:'"i18n" only supports one boolean option: { "enabled": true | false }.',file})}if(typeof fields!="object"||fields===null||Array.isArray(fields))return errors.push({rule:"schemas/fields",message:'Missing "fields" object.',file}),errors;let parsedFields={};for(let[fieldName,definition]of Object.entries(fields)){if(!CONTENT_FIELD_NAME_PATTERN.test(fieldName)){errors.push({rule:"schemas/field-name",message:`Field "${fieldName}" must use ${CONTENT_FIELD_NAME_PATTERN_DESCRIPTION}.`,file});continue}if(RESERVED_FIELD_NAMES.has(fieldName)){errors.push({rule:"schemas/reserved-field",message:`Field "${fieldName}" is reserved entry metadata \u2014 the platform manages it automatically. Remove it from the schema${fieldName==="slug"?" (set slug inside entry data on create instead)":""}.`,file});continue}if(typeof definition!="object"||definition===null||Array.isArray(definition)){errors.push({rule:"schemas/field-shape",message:`Field "${fieldName}" must be an object like { "type": "string" }.`,file});continue}let{type}=definition;if((typeof type!="string"||!FIELD_TYPES.has(type))&&errors.push({rule:"schemas/field-type",message:`Field "${fieldName}" has unsupported type "${String(type)}". Allowed: ${[...FIELD_TYPES].join(", ")}.`,file}),"localized"in definition&&errors.push({rule:"schemas/field-i18n",message:`Field "${fieldName}": "localized" is not supported. Use "i18n": false to share one value across locales.`,file}),"i18n"in definition&&(typeof definition.i18n!="boolean"?errors.push({rule:"schemas/field-i18n",message:`Field "${fieldName}": "i18n" must be true or false.`,file}):type==="blocks"&&errors.push({rule:"schemas/field-i18n",message:`Field "${fieldName}": "i18n" is not supported on blocks fields.`,file})),type==="blocks"){let parsed2=ContentFieldDefinitionSchema.safeParse(definition);if(!parsed2.success){for(let issue of parsed2.error.issues)errors.push({rule:"schemas/structured-content-shape",message:`Field "${fieldName}"${issue.path.length>0?` at ${issue.path.join(".")}`:""}: ${issue.message}`,file});continue}parsedFields[fieldName]=parsed2.data,walkContentFields({[fieldName]:parsed2.data},({field,path:path47,structuredDepth,insideStructuredContent})=>{if(field.type==="blocks"&&structuredDepth>=MAX_STRUCTURED_CONTENT_DEPTH&&errors.push({rule:"schemas/structured-content-depth",message:`Field "${path47.join(".")}" exceeds the ${MAX_STRUCTURED_CONTENT_DEPTH}-level blocks limit.`,file}),!(!insideStructuredContent||field.type!=="reference")){if(field.targets){errors.push({rule:"schemas/structured-content-reference",message:`Reference field "${path47.join(".")}" must use one fixed "target" inside blocks.`,file});return}field.target&&schemaUids.size>0&&!schemaUids.has(field.target)&&errors.push({rule:"schemas/reference-target",message:`Reference field "${path47.join(".")}" targets unknown schema "${field.target}".`,file})}});continue}let parsed=ContentFieldDefinitionSchema.safeParse(definition);if(parsed.success&&(parsedFields[fieldName]=parsed.data),type==="reference"){let{target,targets,many}=definition;if(targets!==void 0&&target!==void 0)errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" declares both "target" and "targets" \u2014 a field is fixed or polymorphic, never both.`,file});else if(targets!==void 0){let targetList=Array.isArray(targets)?targets:null;if(!targetList||targetList.length===0||new Set(targetList).size!==targetList.length)errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" must declare "targets" as a non-empty array of unique content types.`,file});else for(let candidate of targetList)typeof candidate!="string"||!CONTENT_TYPE_NAME_PATTERN.test(candidate)?errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" has an invalid entry in "targets".`,file}):schemaUids.size>0&&!schemaUids.has(candidate)&&errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" targets unknown schema "${candidate}".`,file})}else typeof target!="string"||!CONTENT_TYPE_NAME_PATTERN.test(target)?errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" must declare a valid "target" content type (or "targets" for a polymorphic field).`,file}):schemaUids.size>0&&!schemaUids.has(target)&&errors.push({rule:"schemas/reference-target",message:`Reference field "${fieldName}" targets unknown schema "${target}".`,file});many!==void 0&&typeof many!="boolean"&&errors.push({rule:"schemas/reference-many",message:`Reference field "${fieldName}" must use a boolean "many" value.`,file})}else for(let referenceOnlyKey of["target","targets","many"])referenceOnlyKey in definition&&errors.push({rule:"schemas/reference-shape",message:`Field "${fieldName}": "${referenceOnlyKey}" is only supported on reference fields.`,file})}for(let problem of collectConditionProblems(parsedFields))errors.push({rule:"schemas/conditions",message:problem.message,file});return errors}__name(validateSchemaFile,"validateSchemaFile");init_api();init_config();init_auth_errors();import fs19 from"node:fs";import path22 from"node:path";var MIN_DB_LABELS_FIMO_VERSION="0.2.5",MIN_DB_LABELS_TEMPLATE_VERSION=4;function getDbLabelsRuntimeWarning(cwd){if(readExplicitConfigVersion(cwd)<MIN_DB_LABELS_TEMPLATE_VERSION)return null;let projectPackage=readPackageJson(path22.join(cwd,"package.json")),fimoSpec=findFimoSpec(projectPackage);if(!fimoSpec)return buildWarning("package.json has no fimo dependency");let source=findRuntimeVersion(cwd,fimoSpec);return!source||!isVersionOlder(source.version,MIN_DB_LABELS_FIMO_VERSION)?null:buildWarning(`${source.label} is fimo@${source.version}`)}__name(getDbLabelsRuntimeWarning,"getDbLabelsRuntimeWarning");function readExplicitConfigVersion(cwd){try{let raw=JSON.parse(fs19.readFileSync(path22.join(cwd,"fimo-config.json"),"utf8")),parsed=Number.parseInt(String(raw.version),10);return Number.isFinite(parsed)&&parsed>0?parsed:0}catch{return 0}}__name(readExplicitConfigVersion,"readExplicitConfigVersion");function buildWarning(subject){return[`CRITICAL: ${subject}, but DB-owned labels require fimo >= ${MIN_DB_LABELS_FIMO_VERSION}.`,"Labels changed with `fimo labels` or Fimo Studio may not render in this project until the app runtime is upgraded.","Run `npm install fimo@latest` (or your package manager equivalent), then run `fimo validate` again."].join(" ")}__name(buildWarning,"buildWarning");function findRuntimeVersion(cwd,fimoSpec){let installed=readPackageJson(path22.join(cwd,"node_modules","fimo","package.json"));if(typeof installed?.version=="string")return{label:"installed node_modules/fimo",version:installed.version};let packageLockVersion=readPackageLockVersion(cwd);if(packageLockVersion)return{label:"package-lock.json",version:packageLockVersion};let exactSpecVersion=parseVersion2(fimoSpec);if(exactSpecVersion)return{label:"package.json dependency",version:exactSpecVersion.normalized};if(fimoSpec.startsWith("file:")){let fileVersion=readFileDependencyVersion(cwd,fimoSpec);if(fileVersion)return{label:"package.json file dependency target",version:fileVersion}}return null}__name(findRuntimeVersion,"findRuntimeVersion");function findFimoSpec(pkg){let dependenciesSpec=pkg?.dependencies?.fimo;if(typeof dependenciesSpec=="string"&&dependenciesSpec.trim())return dependenciesSpec.trim();let devDependenciesSpec=pkg?.devDependencies?.fimo;return typeof devDependenciesSpec=="string"&&devDependenciesSpec.trim()?devDependenciesSpec.trim():null}__name(findFimoSpec,"findFimoSpec");function readFileDependencyVersion(cwd,spec){let rawPath=spec.slice(5),packageRoot=path22.isAbsolute(rawPath)?rawPath:path22.resolve(cwd,rawPath),pkg=readPackageJson(path22.join(packageRoot,"package.json"));return typeof pkg?.version=="string"?pkg.version:null}__name(readFileDependencyVersion,"readFileDependencyVersion");function readPackageLockVersion(cwd){try{let lock=JSON.parse(fs19.readFileSync(path22.join(cwd,"package-lock.json"),"utf8")),packagesVersion=lock.packages?.["node_modules/fimo"]?.version;if(typeof packagesVersion=="string")return packagesVersion;let dependencyVersion=lock.dependencies?.fimo?.version;return typeof dependencyVersion=="string"?dependencyVersion:null}catch{return null}}__name(readPackageLockVersion,"readPackageLockVersion");function readPackageJson(filePath){try{return JSON.parse(fs19.readFileSync(filePath,"utf8"))}catch{return null}}__name(readPackageJson,"readPackageJson");function isVersionOlder(version,minimum){let parsed=parseVersion2(version),parsedMinimum=parseVersion2(minimum);if(!parsed||!parsedMinimum)return!1;for(let key of["major","minor","patch"]){if(parsed[key]<parsedMinimum[key])return!0;if(parsed[key]>parsedMinimum[key])return!1}return!1}__name(isVersionOlder,"isVersionOlder");function parseVersion2(version){let match=version.trim().match(/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return match?{major:Number(match[1]),minor:Number(match[2]),patch:Number(match[3]),normalized:`${Number(match[1])}.${Number(match[2])}.${Number(match[3])}`}:null}__name(parseVersion2,"parseVersion");init_project_context();init_project();init_dist();import{existsSync as existsSync7,readFileSync as readFileSync8,readdirSync as readdirSync6,statSync as statSync3}from"node:fs";import{join as join9,resolve as resolve6}from"node:path";import fs20 from"node:fs/promises";import path23 from"node:path";async function pathExists(targetPath){try{return await fs20.access(targetPath),!0}catch{return!1}}__name(pathExists,"pathExists");async function removeDataFiles(dir){let entries2=await fs20.readdir(dir,{withFileTypes:!0});for(let entry of entries2){let fullPath=path23.join(dir,entry.name);entry.isDirectory()?await removeDataFiles(fullPath):entry.name.endsWith(".data")&&await fs20.rm(fullPath)}}__name(removeDataFiles,"removeDataFiles");async function exportStatic(options={}){let cwd=options.cwd??process.cwd(),clientDir=path23.resolve(cwd,"dist/client"),serverDir=path23.resolve(cwd,"dist/server");if(!await pathExists(clientDir))throw new Error("Missing dist/client output. Run `react-router build` first.");await pathExists(serverDir)&&await fs20.rm(serverDir,{recursive:!0,force:!0}),await removeDataFiles(clientDir),console.log("Static export complete.")}__name(exportStatic,"exportStatic");import{existsSync as existsSync6,readFileSync as readFileSync7,readdirSync as readdirSync5,statSync as statSync2}from"fs";import{join as join8}from"path";import{parseSync as parseSync2}from"oxc-parser";var SRC_DIR="src";function getLineAndColumn(code2,offset){let lines=code2.slice(0,offset).split(`
|
|
1129
1129
|
`);return{line:lines.length,column:lines[lines.length-1].length+1}}__name(getLineAndColumn,"getLineAndColumn");function isStringLiteral(node){return node?node.type==="Literal"&&typeof node.value=="string"||node.type==="TemplateLiteral"&&(!node.expressions||node.expressions.length===0):!1}__name(isStringLiteral,"isStringLiteral");var DYNAMIC_KEY_MESSAGE=`Dynamic translation key detected. The first argument to t() must be a string literal, not a variable or expression.
|
|
1130
1130
|
|
|
1131
1131
|
This breaks source tracking for inline editing. Translation keys must be statically analyzable.
|
|
@@ -1268,8 +1268,8 @@ Examples:
|
|
|
1268
1268
|
fimo schedules delete nightly-publish
|
|
1269
1269
|
|
|
1270
1270
|
Run \`fimo schedules <command> --help\` for command-specific help.
|
|
1271
|
-
`);schedules.command("create <name>").description("Create a scheduled command").requiredOption("--cron <expr>",'Cron expression, e.g. "0 2 * * *"').requiredOption("--do <command>","Command to run inside the env sandbox").option("--env <env>","Target env (defaults to the current git branch)").option("--project <id>","Project id (defaults to .fimo.settings.json projectId)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>createCommand2(name,opts)),schedules.command("list").description("List schedules for an env").option("--env <env>","Target env (defaults to the current git branch)").option("--project <id>","Project id").option("-C, --cwd <dir>","Project directory").action(opts=>listCommand3(opts)),schedules.command("run <name>").description("Run a schedule now, without waiting for its cron").option("--env <env>","Target env (defaults to the current git branch)").option("--project <id>","Project id").option("-C, --cwd <dir>","Project directory").action((name,opts)=>runCommand2(name,opts)),schedules.command("delete <name>").description("Delete a schedule").option("--env <env>","Target env (defaults to the current git branch)").option("--project <id>","Project id").option("-C, --cwd <dir>","Project directory").action((name,opts)=>deleteCommand(name,opts))}__name(registerSchedulesCommands,"registerSchedulesCommands");async function resolveScope(opts){let baseApi=new FimoApiClient(loadConfig()),env=opts.env;if(!env)try{env=(await getProjectContext({cwd:opts.cwd})).env}catch(err){if(!opts.project)throw err;env=DEFAULT_ENV}if(opts.project)return{projectId:opts.project,api:baseApi.withEnv(env)};let cwd=resolveProjectCwd(opts.cwd);return{projectId:loadProjectSettings(cwd).projectId,api:baseApi.withEnv(env)}}__name(resolveScope,"resolveScope");async function createCommand2(name,opts){let{projectId,api}=await resolveScope(opts),schedule=await api.createSchedule(projectId,{name,cron:opts.cron,command:opts.do});ui.ok({command:"schedules create",headline:`Created schedule ${schedule.name}`,details:{id:schedule.id,env:schedule.env,cron:schedule.cron,command:schedule.command}})}__name(createCommand2,"createCommand");async function listCommand3(opts){let{projectId,api}=await resolveScope(opts),schedules=await api.listSchedules(projectId);ui.table({command:"schedules list",columns:[{key:"name",label:"NAME"},{key:"cron",label:"CRON"},{key:"command",label:"COMMAND"},{key:"status",label:"LAST STATUS"}],rows:schedules.map(schedule=>({name:schedule.name,cron:schedule.cron,command:schedule.command,status:schedule.lastStatus??""}))})}__name(listCommand3,"listCommand");async function runCommand2(name,opts){let{projectId,api}=await resolveScope(opts),result=await api.runSchedule(projectId,name);if(result.status==="failed"){ui.error({command:"schedules run",code:"SCHEDULE_RUN_FAILED",message:`Schedule ${name} failed: ${result.error??"unknown error"}`}),process.exitCode=1;return}ui.ok({command:"schedules run",headline:`Ran schedule ${name}: ${result.status}`,details:{status:result.status,...result.error?{error:result.error}:{}}})}__name(runCommand2,"runCommand");async function deleteCommand(name,opts){let{projectId,api}=await resolveScope(opts);await api.deleteSchedule(projectId,name),ui.ok({command:"schedules delete",headline:`Deleted schedule ${name}`,details:{name}})}__name(deleteCommand,"deleteCommand");init_dist();init_sync_schemas();import fs41 from"node:fs";import path44 from"node:path";init_project_context();init_project();var SchemaCommandError=class extends Error{static{__name(this,"SchemaCommandError")}code;constructor(code2,message){super(message),this.name="SchemaCommandError",this.code=code2}};function renameOperation(contentType,value){let separator=value.indexOf("="),from=value.slice(0,separator).trim(),to=value.slice(separator+1).trim();if(separator<=0||!from||!to||to.includes("="))throw new SchemaCommandError("SCHEMA_RENAME_INVALID",`Invalid --rename "${value}". Use --rename old.path=new.path.`);return{type:"renameField",contentType,from,to}}__name(renameOperation,"renameOperation");function toApiShape(schema){return{name:schema.uid,label:schema.name,isSingleton:schema.isSingleton??!1,i18n:schema.i18n??{enabled:!0},fields:schema.fields}}__name(toApiShape,"toApiShape");function renderPrettyJson8(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson8,"renderPrettyJson");async function schemaListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.schema.list",{projectId:ctx.projectId,env:ctx.env});let result=await api.listSchemas(ctx.projectId);ui.result({command:"schemas list",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}__name(schemaListCommand,"schemaListCommand");async function schemaGetCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.schema.get",{projectId:ctx.projectId,env:ctx.env});let result=await api.getSchema(ctx.projectId,typeName);ui.result({command:"schemas get",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}__name(schemaGetCommand,"schemaGetCommand");async function schemaPushCommand(typeName,options,cmd){if((options.rename?.length??0)>0&&!typeName)throw new SchemaCommandError("SCHEMA_RENAME_REQUIRES_TYPE","--rename requires one schema name: fimo schemas push <typeName> --rename old.path=new.path.");let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.schema.push",{projectId:ctx.projectId,env:ctx.env});let cwd=resolveProjectCwd(options.cwd),schemasDir=path44.join(cwd,"src/schemas"),allSchemaFiles=fs41.readdirSync(schemasDir).filter(file=>file.endsWith(".json")),files=typeName?[`${typeName}.json`]:allSchemaFiles,schemaUids=new Set(allSchemaFiles.flatMap(file=>{try{let schema=JSON.parse(fs41.readFileSync(path44.join(schemasDir,file),"utf-8"));return typeof schema.uid=="string"?[schema.uid]:[]}catch{return[]}})),schemas3=files.map(file=>{let filePath=path44.join(schemasDir,file);if(!fs41.existsSync(filePath))throw new Error(`Schema file not found: ${filePath}`);let issues=validateSchemaFile(filePath,path44.join("src/schemas",file),schemaUids);if(issues.length>0)throw new Error(issues.map(issue=>`${issue.file}: ${issue.message}`).join(`
|
|
1272
|
-
`));return JSON.parse(fs41.readFileSync(filePath,"utf-8"))});syncSchemas({cwd,verbose:!1});let operations=schemas3.length===1?(options.rename??[]).map(value=>renameOperation(schemas3[0].uid,value)):[],results=await api.upsertSchemas(ctx.projectId,schemas3.map(schema=>toApiShape(schema)),operations),payload=results.length===1?results[0]:results;ui.result({command:"schemas push",data:payload,render:__name(()=>renderPrettyJson8(payload),"render")})}__name(schemaPushCommand,"schemaPushCommand");async function schemaDeleteCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.schema.delete",{projectId:ctx.projectId,env:ctx.env});let result=await api.deleteSchema(ctx.projectId,typeName);ui.result({command:"schemas delete",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}__name(schemaDeleteCommand,"schemaDeleteCommand");init_skills();init_status();init_dist5();init_dist();init_api();init_config();init_auth_errors();init_interactive();init_project_context();init_version();import{readFileSync as readFileSync11}from"node:fs";import path45 from"node:path";var MAX_SUPPORT_MESSAGE_LENGTH=2e4;function registerSupportCommands(program2){program2.command("support").description("Contact Fimo support").command("report").description("Report a Fimo problem or high-impact feature request with project and environment context").argument("[message...]","What happened or capability is missing; use --message-file for longer or agent-written reports").option("--message-file <path>","Read the report from a UTF-8 text file").option("-C, --cwd <dir>","Project directory").option("--preview","Print the exact support payload without sending it").option("-y, --yes","Send without prompting").addHelpText("after",`
|
|
1271
|
+
`);schedules.command("create <name>").description("Create a scheduled command").requiredOption("--cron <expr>",'Cron expression, e.g. "0 2 * * *"').requiredOption("--do <command>","Command to run inside the env sandbox").option("--env <env>","Target env (defaults to the current git branch)").option("--project <id>","Project id (defaults to .fimo.settings.json projectId)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>createCommand2(name,opts)),schedules.command("list").description("List schedules for an env").option("--env <env>","Target env (defaults to the current git branch)").option("--project <id>","Project id").option("-C, --cwd <dir>","Project directory").action(opts=>listCommand3(opts)),schedules.command("run <name>").description("Run a schedule now, without waiting for its cron").option("--env <env>","Target env (defaults to the current git branch)").option("--project <id>","Project id").option("-C, --cwd <dir>","Project directory").action((name,opts)=>runCommand2(name,opts)),schedules.command("delete <name>").description("Delete a schedule").option("--env <env>","Target env (defaults to the current git branch)").option("--project <id>","Project id").option("-C, --cwd <dir>","Project directory").action((name,opts)=>deleteCommand(name,opts))}__name(registerSchedulesCommands,"registerSchedulesCommands");async function resolveScope(opts){let baseApi=new FimoApiClient(loadConfig()),env=opts.env;if(!env)try{env=(await getProjectContext({cwd:opts.cwd})).env}catch(err){if(!opts.project)throw err;env=DEFAULT_ENV}if(opts.project)return{projectId:opts.project,api:baseApi.withEnv(env)};let cwd=resolveProjectCwd(opts.cwd);return{projectId:loadProjectSettings(cwd).projectId,api:baseApi.withEnv(env)}}__name(resolveScope,"resolveScope");async function createCommand2(name,opts){let{projectId,api}=await resolveScope(opts),schedule=await api.createSchedule(projectId,{name,cron:opts.cron,command:opts.do});ui.ok({command:"schedules create",headline:`Created schedule ${schedule.name}`,details:{id:schedule.id,env:schedule.env,cron:schedule.cron,command:schedule.command}})}__name(createCommand2,"createCommand");async function listCommand3(opts){let{projectId,api}=await resolveScope(opts),schedules=await api.listSchedules(projectId);ui.table({command:"schedules list",columns:[{key:"name",label:"NAME"},{key:"cron",label:"CRON"},{key:"command",label:"COMMAND"},{key:"status",label:"LAST STATUS"}],rows:schedules.map(schedule=>({name:schedule.name,cron:schedule.cron,command:schedule.command,status:schedule.lastStatus??""}))})}__name(listCommand3,"listCommand");async function runCommand2(name,opts){let{projectId,api}=await resolveScope(opts),result=await api.runSchedule(projectId,name);if(result.status==="failed"){ui.error({command:"schedules run",code:"SCHEDULE_RUN_FAILED",message:`Schedule ${name} failed: ${result.error??"unknown error"}`}),process.exitCode=1;return}ui.ok({command:"schedules run",headline:`Ran schedule ${name}: ${result.status}`,details:{status:result.status,...result.error?{error:result.error}:{}}})}__name(runCommand2,"runCommand");async function deleteCommand(name,opts){let{projectId,api}=await resolveScope(opts);await api.deleteSchedule(projectId,name),ui.ok({command:"schedules delete",headline:`Deleted schedule ${name}`,details:{name}})}__name(deleteCommand,"deleteCommand");init_dist();init_sync_schemas();import fs41 from"node:fs";import path44 from"node:path";init_api();init_project_context();init_project();var SchemaCommandError=class extends Error{static{__name(this,"SchemaCommandError")}code;constructor(code2,message){super(message),this.name="SchemaCommandError",this.code=code2}};function renameOperation(contentType,value){let separator=value.indexOf("="),from=value.slice(0,separator).trim(),to=value.slice(separator+1).trim();if(separator<=0||!from||!to||to.includes("="))throw new SchemaCommandError("SCHEMA_RENAME_INVALID",`Invalid --rename "${value}". Use --rename old.path=new.path.`);return{type:"renameField",contentType,from,to}}__name(renameOperation,"renameOperation");function toApiShape(schema){return{name:schema.uid,label:schema.name,isSingleton:schema.isSingleton??!1,i18n:schema.i18n??{enabled:!0},fields:schema.fields}}__name(toApiShape,"toApiShape");function renderPrettyJson8(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson8,"renderPrettyJson");function isUniqueConflictIssue(issue){if(!issue||typeof issue!="object"||Array.isArray(issue))return!1;let candidate=issue;return candidate.kind==="unique_conflict"&&typeof candidate.contentType=="string"&&typeof candidate.field=="string"&&typeof candidate.value=="string"&&typeof candidate.documentCount=="number"&&Array.isArray(candidate.documentIds)&&candidate.documentIds.every(id=>typeof id=="string")&&(candidate.documentIdsTruncated===void 0||typeof candidate.documentIdsTruncated=="boolean")}__name(isUniqueConflictIssue,"isUniqueConflictIssue");function getUniqueConflictIssues(body){if(!body||typeof body!="object"||Array.isArray(body))return null;let issues=body.issues;return Array.isArray(issues)?issues.filter(isUniqueConflictIssue):null}__name(getUniqueConflictIssues,"getUniqueConflictIssues");function renderSchemaTransitionRejected(body,issues){currentMode().format==="json"?ui.result({command:"schemas push",data:body,render:__name(()=>"","render")}):ui.table({command:"schemas push",headline:"Schema push rejected. Nothing was written.",columns:[{key:"content_type",label:"CONTENT TYPE"},{key:"field",label:"FIELD"},{key:"value",label:"VALUE"},{key:"documents",label:"DOCUMENTS"},{key:"document_ids",label:"DOCUMENT IDS"}],rows:issues.map(issue=>{let remaining=Math.max(issue.documentCount-issue.documentIds.length,0),truncationNote=remaining>0?`... and ${remaining} more`:"... and more";return{content_type:issue.contentType,field:issue.field,value:issue.value,documents:issue.documentCount,document_ids:issue.documentIdsTruncated?[...issue.documentIds,truncationNote].join(", "):issue.documentIds.join(", ")}})}),process.exitCode=1}__name(renderSchemaTransitionRejected,"renderSchemaTransitionRejected");async function schemaListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.schema.list",{projectId:ctx.projectId,env:ctx.env});let result=await api.listSchemas(ctx.projectId);ui.result({command:"schemas list",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}__name(schemaListCommand,"schemaListCommand");async function schemaGetCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.schema.get",{projectId:ctx.projectId,env:ctx.env});let result=await api.getSchema(ctx.projectId,typeName);ui.result({command:"schemas get",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}__name(schemaGetCommand,"schemaGetCommand");async function schemaPushCommand(typeName,options,cmd){if((options.rename?.length??0)>0&&!typeName)throw new SchemaCommandError("SCHEMA_RENAME_REQUIRES_TYPE","--rename requires one schema name: fimo schemas push <typeName> --rename old.path=new.path.");let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.schema.push",{projectId:ctx.projectId,env:ctx.env});let cwd=resolveProjectCwd(options.cwd),schemasDir=path44.join(cwd,"src/schemas"),allSchemaFiles=fs41.readdirSync(schemasDir).filter(file=>file.endsWith(".json")),files=typeName?[`${typeName}.json`]:allSchemaFiles,schemaUids=new Set(allSchemaFiles.flatMap(file=>{try{let schema=JSON.parse(fs41.readFileSync(path44.join(schemasDir,file),"utf-8"));return typeof schema.uid=="string"?[schema.uid]:[]}catch{return[]}})),schemas3=files.map(file=>{let filePath=path44.join(schemasDir,file);if(!fs41.existsSync(filePath))throw new Error(`Schema file not found: ${filePath}`);let issues=validateSchemaFile(filePath,path44.join("src/schemas",file),schemaUids);if(issues.length>0)throw new Error(issues.map(issue=>`${issue.file}: ${issue.message}`).join(`
|
|
1272
|
+
`));return JSON.parse(fs41.readFileSync(filePath,"utf-8"))});syncSchemas({cwd,verbose:!1});let operations=schemas3.length===1?(options.rename??[]).map(value=>renameOperation(schemas3[0].uid,value)):[],results;try{results=await api.upsertSchemas(ctx.projectId,schemas3.map(schema=>toApiShape(schema)),operations)}catch(error){if(error instanceof ApiRequestError&&error.code==="schema_transition_rejected"){let issues=getUniqueConflictIssues(error.body);if(issues){renderSchemaTransitionRejected(error.body,issues);return}}throw error}let payload=results.length===1?results[0]:results;ui.result({command:"schemas push",data:payload,render:__name(()=>renderPrettyJson8(payload),"render")})}__name(schemaPushCommand,"schemaPushCommand");async function schemaDeleteCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.schema.delete",{projectId:ctx.projectId,env:ctx.env});let result=await api.deleteSchema(ctx.projectId,typeName);ui.result({command:"schemas delete",data:result,render:__name(()=>renderPrettyJson8(result),"render")})}__name(schemaDeleteCommand,"schemaDeleteCommand");init_skills();init_status();init_dist5();init_dist();init_api();init_config();init_auth_errors();init_interactive();init_project_context();init_version();import{readFileSync as readFileSync11}from"node:fs";import path45 from"node:path";var MAX_SUPPORT_MESSAGE_LENGTH=2e4;function registerSupportCommands(program2){program2.command("support").description("Contact Fimo support").command("report").description("Report a Fimo problem or high-impact feature request with project and environment context").argument("[message...]","What happened or capability is missing; use --message-file for longer or agent-written reports").option("--message-file <path>","Read the report from a UTF-8 text file").option("-C, --cwd <dir>","Project directory").option("--preview","Print the exact support payload without sending it").option("-y, --yes","Send without prompting").addHelpText("after",`
|
|
1273
1273
|
Examples:
|
|
1274
1274
|
fimo support report "Preview deployment fails after validation"
|
|
1275
1275
|
fimo support report --message-file /tmp/fimo-support-report.md --preview --json
|