fimo 0.15.0 → 0.16.0-staging.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/content-templates/forms/react.eta +3 -3
- package/assets/skills/fimo-cli/SKILL.md +8 -8
- package/assets/skills/fimo-cli/references/account.md +1 -1
- package/assets/skills/fimo-cli/references/agents.md +9 -9
- package/assets/skills/fimo-cli/references/branches.md +38 -37
- package/assets/skills/fimo-cli/references/credits.md +1 -1
- package/assets/skills/fimo-cli/references/deploy.md +7 -7
- package/assets/skills/fimo-cli/references/history.md +13 -6
- package/assets/skills/fimo-cli/references/init.md +6 -2
- package/assets/skills/fimo-cli/references/locales.md +1 -1
- package/assets/skills/fimo-cli/references/mcp.md +8 -8
- package/assets/skills/fimo-cli/references/preview.md +8 -5
- package/assets/skills/fimo-cli/references/project-vars-and-secrets.md +1 -1
- package/assets/skills/fimo-cli/references/projects.md +3 -3
- package/assets/skills/fimo-cli/references/schedules.md +8 -5
- package/assets/skills/fimo-cli/references/support.md +1 -1
- package/assets/skills/fimo-cli/references/webhooks.md +8 -4
- package/assets/skills/fimo-code/SKILL.md +1 -0
- package/assets/skills/fimo-code/references/frameworks/compatibility.md +13 -8
- package/assets/skills/fimo-code/references/frameworks/hosting.md +23 -18
- package/assets/skills/fimo-studio/references/webhooks.md +2 -2
- package/dist/cli/bundle.json +1 -1
- package/dist/cli/index.js +43 -30
- package/dist/runtime/sveltekit/runtime.js +4 -1
- package/package.json +1 -1
- package/release.json +2 -2
- package/templates/astro/AGENTS.md +1 -0
- package/templates/nextjs/AGENTS.md +1 -0
- package/templates/react-router/AGENTS.md +1 -0
- package/templates/react-router/package.json +1 -1
- package/templates/sveltekit/AGENTS.md +1 -0
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 process9.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()}`,process9.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=path49.basename(filename,path49.extname(filename)),this}executableDir(path50){return path50===void 0?this._executableDir:(this._executableDir=path50,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(process9.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(process9.env.NO_COLOR||process9.env.FORCE_COLOR==="0"||process9.env.FORCE_COLOR==="false")return!1;if(process9.env.FORCE_COLOR||process9.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{z}from"zod";function filterUnknownProperties(data2,schema){if(data2==null)return data2;if(schema instanceof z.ZodOptional||schema instanceof z.ZodNullable||schema instanceof z.ZodDefault)return filterUnknownProperties(data2,schema.unwrap());if(schema instanceof z.ZodArray){if(!Array.isArray(data2))return data2;let itemSchema=schema.unwrap();return data2.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z.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 z.ZodLiteral?discriminatorField.def.values.includes(discriminatorValue):!1});return matchingSchema?filterUnknownProperties(data2,matchingSchema):data2}if(schema instanceof z.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 z.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 z.ZodObject)return createObjectDTO(schema);if(schema instanceof z.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 z2}from"zod";function createCursorPageDataSchema(dataSchema){return z2.object({items:z2.array(dataSchema),nextCursor:z2.string().nullable()})}function createCursorPaginatedResponseSchema(dataSchema){return z2.object({data:createCursorPageDataSchema(dataSchema)})}var createResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema=__name(dataSchema=>z2.object({data:dataSchema}),"createResponseSchema");__name(createCursorPageDataSchema,"createCursorPageDataSchema");__name(createCursorPaginatedResponseSchema,"createCursorPaginatedResponseSchema")}});import{z as z3}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z3.object({page:z3.coerce.number().int().positive().default(1),limit:z3.coerce.number().int().positive().max(100).default(20)})}});import{z as z4}from"zod";var CommonSchemas,BaseEntitySchema,ProjectRoleKeySchema,ProjectRoleKeyWithSystemSchema,ProjectPrincipalTypeSchema,ProjectStatusSchema,ProjectInviteStatusSchema,PublicationStatusSchema,OrganizationRoleSchema,AssetTypeSchema,TemplateCodeSchema,FieldTypeSchema,CONTENT_INTERNAL_FIELD_NAMES,contentInternalFieldNames,RESERVED_CONTENT_FIELD_NAMES,contentReviewHiddenFieldNames,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:z4.coerce.date(),positiveInt:z4.number().int().positive(),nonNegativeInt:z4.number().int().nonnegative()},BaseEntitySchema=z4.object({id:z4.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z4.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z4.enum(["full","edit","comment","view","agent","schedule"]),ProjectPrincipalTypeSchema=z4.enum(["user","org","orgRole","public","email"]),ProjectStatusSchema=z4.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z4.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z4.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z4.enum(["owner","admin","member"]),AssetTypeSchema=z4.enum(["file","folder"]),TemplateCodeSchema=z4.enum(["Free","Premium"]),FieldTypeSchema=z4.enum(["string","text","richtext","media","number","boolean","date","json","reference","blocks"]),CONTENT_INTERNAL_FIELD_NAMES=["id","entryId","documentId","locale","__fimo"],contentInternalFieldNames=new Set(CONTENT_INTERNAL_FIELD_NAMES),RESERVED_CONTENT_FIELD_NAMES=[...CONTENT_INTERNAL_FIELD_NAMES,"slug","createdAt","updatedAt"],contentReviewHiddenFieldNames=new Set(RESERVED_CONTENT_FIELD_NAMES),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_AUDIO_MIME_TYPES,ATTACHMENT_VIDEO_MIME_TYPES,ATTACHMENT_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,EXTENSION_MIME_TYPES,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image",maxSizeBytes:20971520},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image",maxSizeBytes:20971520},{mime:"image/webp",extensions:[".webp"],category:"image",maxSizeBytes:20971520},{mime:"image/avif",extensions:[".avif"],category:"image",maxSizeBytes:20971520},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:5242880},{mime:"application/msword",extensions:[".doc"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",extensions:[".docx"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.ms-excel",extensions:[".xls"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",extensions:[".xlsx"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.ms-powerpoint",extensions:[".ppt"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation",extensions:[".pptx"],category:"document",maxSizeBytes:5242880},{mime:"application/epub+zip",extensions:[".epub"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.oasis.opendocument.text",extensions:[".odt"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.oasis.opendocument.spreadsheet",extensions:[".ods"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.oasis.opendocument.presentation",extensions:[".odp"],category:"document",maxSizeBytes:5242880},{mime:"text/rtf",extensions:[],category:"document",maxSizeBytes:5242880},{mime:"application/rtf",extensions:[".rtf"],category:"document",maxSizeBytes:5242880},{mime:"text/html",extensions:[".html",".htm"],category:"document",maxSizeBytes:5242880},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:5242880},{mime:"text/markdown",extensions:[".md",".markdown"],category:"document",maxSizeBytes:5242880},{mime:"application/json",extensions:[".json"],category:"document",maxSizeBytes:5242880},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:5242880},{mime:"audio/mpeg",extensions:[".mp3"],category:"audio",maxSizeBytes:10485760},{mime:"audio/wav",extensions:[".wav"],category:"audio",maxSizeBytes:10485760},{mime:"audio/aiff",extensions:[".aiff",".aif"],category:"audio",maxSizeBytes:10485760},{mime:"audio/aac",extensions:[".aac"],category:"audio",maxSizeBytes:10485760},{mime:"audio/ogg",extensions:[".ogg"],category:"audio",maxSizeBytes:10485760},{mime:"audio/flac",extensions:[".flac"],category:"audio",maxSizeBytes:10485760},{mime:"video/mp4",extensions:[".mp4"],category:"video",maxSizeBytes:20971520},{mime:"video/mpeg",extensions:[".mpeg",".mpg"],category:"video",maxSizeBytes:20971520},{mime:"video/mpg",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/quicktime",extensions:[".mov"],category:"video",maxSizeBytes:20971520},{mime:"video/mov",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/avi",extensions:[".avi"],category:"video",maxSizeBytes:20971520},{mime:"video/vnd.avi",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/x-msvideo",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/x-flv",extensions:[".flv"],category:"video",maxSizeBytes:20971520},{mime:"video/webm",extensions:[".webm"],category:"video",maxSizeBytes:20971520},{mime:"video/wmv",extensions:[".wmv"],category:"video",maxSizeBytes:20971520},{mime:"video/x-ms-wmv",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/x-ms-asf",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/3gpp",extensions:[".3gp"],category:"video",maxSizeBytes:20971520}],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_AUDIO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="audio").map(t2=>t2.mime),ATTACHMENT_VIDEO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="video").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])),EXTENSION_MIME_TYPES=Object.fromEntries(ATTACHMENT_TYPES.flatMap(t2=>t2.extensions.map(extension=>[extension,t2.mime])))}});import{z as z5}from"zod";function isValidEnv(env){return typeof env!="string"||env.length===0||env.length>MAX_ENV_LENGTH||env.startsWith("-")||env.startsWith(".")||env.includes("//")||env.includes("--")||env.split("/").some(segment=>segment==="..")?!1:ENV_ID_REGEX.test(env)}function encodeEnvPathSegment(env){return env.replace(/\//g,"--")}function isProductionEnv(env){return env===PRODUCTION_ENV}function fnv1a8(s){let h=2166136261;for(let i=0;i<s.length;i++)h^=s.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}function envResourceKey(env){let base=env.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a8(env);return base?`${base}-${hash}`:hash}function buildTenantApiUrl(projectId,env,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${envResourceKey(env)}.${url.hostname}`,url.toString().replace(/\/$/,"")}var FIMO_CONTENT_API_ENV_KEYS,FIMO_PREVIEW_SCRIPT_ENV_KEYS,FIMO_MANAGED_PROJECT_ENV_KEYS,ENV_ID_REGEX,MAX_ENV_LENGTH,EnvSchema,DEFAULT_ENV,PRODUCTION_ENV,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";FIMO_CONTENT_API_ENV_KEYS=["FIMO_CONTENT_API_URL","VITE_API_URL","NEXT_PUBLIC_FIMO_API_URL","NUXT_PUBLIC_FIMO_API_URL","PUBLIC_FIMO_API_URL"],FIMO_PREVIEW_SCRIPT_ENV_KEYS=["VITE_PREVIEW_SCRIPT_URL","VITE_FIMO_PREVIEW_SCRIPT_URL","NEXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","NUXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","PUBLIC_FIMO_PREVIEW_SCRIPT_URL","FIMO_PREVIEW_SCRIPT_URL"],FIMO_MANAGED_PROJECT_ENV_KEYS=["FIMO_API_URL","FIMO_API_TOKEN","FIMO_PROJECT_ID","FIMO_ENV","NEXT_PUBLIC_FIMO_ENV","FIMO_AGENT_SESSION","FIMO_DATA_SOURCES",...FIMO_CONTENT_API_ENV_KEYS,...FIMO_PREVIEW_SCRIPT_ENV_KEYS,"VITE_ENABLE_ANALYTICS","VITE_FIMO_BRANCH","VITE_FIMO_IMAGE_HOSTS"],ENV_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_ENV_LENGTH=255;__name(isValidEnv,"isValidEnv");__name(encodeEnvPathSegment,"encodeEnvPathSegment");EnvSchema=z5.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");__name(fnv1a8,"fnv1a8");__name(envResourceKey,"envResourceKey");__name(buildTenantApiUrl,"buildTenantApiUrl")}});var init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict"}});import{z as z6}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=z6.preprocess(referenceValuePreprocess,z6.object({documentId:z6.uuid()})),ReferenceInputValueSchema=z6.preprocess(referenceValuePreprocess,z6.union([z6.object({documentId:z6.uuid()}),z6.object({slug:z6.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=z6.preprocess(polymorphicReferenceValuePreprocess,z6.object({contentType:z6.string().min(1),documentId:z6.uuid()})),PolymorphicReferenceInputValueSchema=z6.preprocess(polymorphicReferenceValuePreprocess,z6.union([z6.object({contentType:z6.string().min(1),documentId:z6.uuid()}),z6.object({contentType:z6.string().min(1),slug:z6.string().min(1)})]))}});import{z as z7}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,path49){let conditionPath=[...path49,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,path49)=>{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,path49));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path49,fieldName,variant.uid]);else walk(field.schema.fields,[...path49,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path49,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path49,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=7,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],showIfClauseSchema=z7.union([z7.object({field:z7.string().min(1),equals:z7.union([z7.string(),z7.number(),z7.boolean()])}).strict(),z7.object({field:z7.string().min(1),in:z7.array(z7.union([z7.string(),z7.number(),z7.boolean()])).min(1)}).strict()]),commonFieldShape={label:z7.string().min(1).optional(),description:z7.string().optional(),editable:z7.boolean().optional(),required:z7.boolean().optional(),default:z7.unknown().optional(),showIf:z7.union([showIfClauseSchema,z7.array(showIfClauseSchema).min(1)]).optional(),showIfAny:z7.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=z7.object({...commonFieldShape,type:z7.enum(["string","text","richtext","media","number","boolean","date","json"]),min:z7.number().optional(),max:z7.number().optional(),minLength:z7.number().int().nonnegative().optional(),maxLength:z7.number().int().nonnegative().optional(),regex:z7.string().optional(),multiple:z7.boolean().optional(),allowedMimeTypes:z7.array(z7.string()).optional(),options:z7.array(z7.string().min(1)).min(1).optional(),unique:z7.boolean().optional(),i18n:z7.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=z7.object({...commonFieldShape,type:z7.literal("reference"),target:z7.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z7.array(z7.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z7.boolean().optional(),i18n:z7.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=z7.lazy(()=>contentFieldDefinitionSchema);__name(getConditionDefinition,"getConditionDefinition");__name(getConditionValues,"getConditionValues");__name(collectClauseProblems,"collectClauseProblems");__name(collectConditionProblems,"collectConditionProblems");blockFieldsSchema=z7.record(z7.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=z7.object({uid:z7.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z7.string().min(1),description:z7.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z7.object({fields:blockFieldsSchema}).strict(),blocksSchema=z7.object({oneOf:z7.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=z7.object({...commonFieldShape,type:z7.literal("blocks"),min:z7.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z7.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z7.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=z7.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z8}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","schedule_notification_change","cutover_step","agent_delegate","version_restore","ops_access_change","ops_service_token_change","ops_project_search","ops_project_inspect","ops_project_chat_read","ops_recent_chat_read","ops_sentry_issue_change","ops_sentry_read","ops_logs_read","ops_trace_read","ops_project_snapshot","ops_support_thread_read","ops_support_report_read","ops_support_report_change","ops_billing_read","ops_billing_cache_invalidate","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send","ops_project_operation","admin_resource_read","merge_force"],AuditActionSchema=z8.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z8.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z8.enum(AUDIT_ACTOR_KINDS)}});import{z as z9}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,OpsSentryIssueIdSchema,OpsSentryResolveInputSchema,OpsTraceIdSchema,OpsTraceReadInputSchema,OpsBillingCacheInvalidateInputSchema,OPS_PROJECT_OPERATIONS,OpsProjectOperationKindSchema,ExactVersionSchema,OpsProjectOperationPlanInputSchema,OPS_MIGRATIONS,OpsMigrationIdSchema,OPS_MIGRATION_PLAN_STATUSES,OpsMigrationPlanStatusSchema,OPS_MIGRATION_CHANGE_ACTIONS,OpsMigrationChangeActionSchema,OpsMigrationDryRunInputSchema,OpsProjectOperationApplyInputSchema,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z9.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing: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=z9.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","ops:billing:read","ops:billing:write","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:project:operate","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing: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=z9.object({permissions:z9.array(OpsPermissionSchema).min(1),backendProfiles:z9.array(OpsBackendProfileSchema).min(1),enabled:z9.boolean().default(!0)}),OpsServiceTokenInputSchema=z9.object({name:z9.string().trim().min(1).max(120),permissions:z9.array(OpsPermissionSchema).min(1),backendProfiles:z9.array(OpsBackendProfileSchema).min(1),expiresAt:z9.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=z9.object({importanceReason:z9.string().trim().min(1).max(1e3),ownerUserId:z9.string().trim().min(1).nullable().optional(),framework:z9.string().trim().max(120).nullable().optional(),packageManager:z9.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z9.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z9.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z9.object({projectId:z9.uuid(),title:z9.string().trim().min(1).max(240),userReport:z9.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z9.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z9.string().trim().max(1e4).nullable().optional(),outcome:z9.string().trim().max(1e4).nullable().optional(),evidence:z9.array(z9.record(z9.string(),z9.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=z9.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z9.object({fingerprint:z9.string().trim().min(1).max(240),title:z9.string().trim().min(1).max(240),description:z9.string().trim().min(1).max(1e4),affectedVersions:z9.array(z9.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z9.array(z9.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z9.string().trim().min(1).max(64).nullable().optional(),workaround:z9.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z9.array(z9.string().trim().min(1).max(120)).max(100),detectionQueries:z9.array(z9.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=z9.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z9.object({changeReference:z9.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z9.string().trim().min(1).max(1e4),evidence:z9.array(z9.record(z9.string(),z9.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z9.object({recipientEmail:z9.email().optional(),subject:z9.string().trim().min(1).max(200).default("An update from Fimo"),message:z9.string().trim().min(1).max(5e3),locale:z9.string().trim().min(2).max(20),reason:z9.string().trim().min(1).max(1e3),acknowledgePolicy:z9.literal(!0)}),OpsSentryIssueIdSchema=z9.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsSentryResolveInputSchema=z9.object({reason:z9.string().trim().min(1).max(1e3)}),OpsTraceIdSchema=z9.string().trim().regex(/^[a-fA-F0-9]{32}$/).transform(value=>value.toLowerCase()),OpsTraceReadInputSchema=z9.object({projectId:z9.uuid(),from:z9.coerce.date(),to:z9.coerce.date(),reason:z9.string().trim().min(1).max(1e3)}).refine(input=>input.from<=input.to,{path:["from"],message:"from must be before or equal to to"}).refine(input=>input.to.getTime()-input.from.getTime()<=10080*60*1e3,{path:["from"],message:"trace windows cannot exceed 7 days"}),OpsBillingCacheInvalidateInputSchema=z9.object({reason:z9.string().trim().min(1).max(1e3)}),OPS_PROJECT_OPERATIONS=["runtime.bump","preview.restart"],OpsProjectOperationKindSchema=z9.enum(OPS_PROJECT_OPERATIONS),ExactVersionSchema=z9.string().trim().regex(/^\d+\.\d+\.\d+$/,"Expected an exact version such as 0.11.0"),OpsProjectOperationPlanInputSchema=z9.discriminatedUnion("kind",[z9.object({kind:z9.literal("runtime.bump"),targetVersion:ExactVersionSchema}),z9.object({kind:z9.literal("preview.restart")})]),OPS_MIGRATIONS=["project.v3-to-v4"],OpsMigrationIdSchema=z9.enum(OPS_MIGRATIONS),OPS_MIGRATION_PLAN_STATUSES=["applicable","not_applicable","unknown"],OpsMigrationPlanStatusSchema=z9.enum(OPS_MIGRATION_PLAN_STATUSES),OPS_MIGRATION_CHANGE_ACTIONS=["create","rewrite","delete"],OpsMigrationChangeActionSchema=z9.enum(OPS_MIGRATION_CHANGE_ACTIONS),OpsMigrationDryRunInputSchema=z9.object({migrationId:OpsMigrationIdSchema,projectEnv:z9.string().trim().min(1).max(255).default("main"),reason:z9.string().trim().min(1).max(1e3)}),OpsProjectOperationApplyInputSchema=z9.intersection(OpsProjectOperationPlanInputSchema,z9.object({planHash:z9.string().trim().length(64),reason:z9.string().trim().min(1).max(1e3),consentReference:z9.string().trim().min(1).max(200).optional()}))}});import{z as z10}from"zod";function getChatFormOptionLabels(body){switch(body.type){case"choices":return body.actions.map(action=>action.label);case"cards":return body.items.map(item=>item.title);case"table":return body.rows.map(row2=>row2.cells[0]??"");case"assets":return body.items.map(item=>item.label??item.alt)}}var BlockSayActionSchema,BlockActionSchema,BlockAppActionSchema,BlockBaseSchema,ChoicesBlockSchema,TableRowTargetSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,ChatDisplayBlockSchema,ChatFormBodySchema,ChatFormStepSchema,FormBlockSchema,ChatBlockSchema,ChatBlockToolInputSchema,ChatFormAnswerItemSchema,ChatFormAnswerMetadataSchema,ChatFormResponseSchema,init_chat_block=__esm({"../../packages/api-contracts/dist/esm/types/chat-block.js"(){"use strict";BlockSayActionSchema=z10.object({kind:z10.literal("say"),label:z10.string().trim().min(1).max(40,"Button labels must be 40 characters or fewer."),description:z10.string().min(1).max(240).optional(),message:z10.string().trim().min(1,"Every say button needs the sentence the user is saying by clicking.").max(2e3),style:z10.enum(["primary","default","ghost"]).optional()}),BlockActionSchema=BlockSayActionSchema,BlockAppActionSchema=z10.object({kind:z10.literal("app"),command:z10.literal("publish")}).strict(),BlockBaseSchema=z10.object({fallback:z10.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z10.string().min(1).max(80).optional()}),ChoicesBlockSchema=BlockBaseSchema.extend({type:z10.literal("choices"),text:z10.string().max(500).optional(),actions:z10.array(BlockActionSchema).min(2,"A choices block needs 2 to 4 buttons.").max(4,"A choices block needs 2 to 4 buttons.")}),TableRowTargetSchema=z10.discriminatedUnion("kind",[z10.object({kind:z10.literal("entry"),collection:z10.string().min(1).max(80),entryId:z10.string().min(1).max(120)}),z10.object({kind:z10.literal("asset"),assetId:z10.string().min(1).max(120)}),z10.object({kind:z10.literal("url"),url:z10.url({protocol:/^https$/}).max(2e3)})]),TableBlockSchema=BlockBaseSchema.extend({type:z10.literal("table"),columns:z10.array(z10.object({label:z10.string().min(1).max(24)})).min(2).max(4),rows:z10.array(z10.object({cells:z10.array(z10.string().max(80)).min(2).max(4),target:TableRowTargetSchema.optional()})).min(1).max(8)}).superRefine((table,ctx)=>{table.rows.forEach((row2,index2)=>{row2.cells.length!==table.columns.length&&ctx.addIssue({code:"custom",path:["rows",index2,"cells"],message:`Every table row needs exactly ${table.columns.length} cells, one for each column.`})})}),CardsBlockSchema=BlockBaseSchema.extend({type:z10.literal("cards"),layout:z10.enum(["rail","stack"]).optional(),items:z10.array(z10.object({title:z10.string().min(1).max(60),subtitle:z10.string().min(1).max(120).optional(),imageUrl:z10.url({protocol:/^https$/}).max(2e3).optional(),action:BlockSayActionSchema.optional()})).min(2).max(6)}),EntryBlockSchema=BlockBaseSchema.extend({type:z10.literal("entry"),label:z10.string().min(1).max(80),collection:z10.string().min(1).max(80),entryId:z10.string().min(1).max(120),path:z10.string().min(1).max(120).optional()}),AssetsBlockSchema=BlockBaseSchema.extend({type:z10.literal("assets"),items:z10.array(z10.object({url:z10.url({protocol:/^https$/}).max(2e3),alt:z10.string().min(1).max(120),label:z10.string().min(1).max(60).optional()})).min(1).max(6)}),CalloutBlockSchema=BlockBaseSchema.extend({type:z10.literal("callout"),title:z10.string().min(1).max(80),text:z10.string().min(1).max(240),action:BlockAppActionSchema}).strict(),StatBlockSchema=BlockBaseSchema.extend({type:z10.literal("stat"),items:z10.array(z10.object({label:z10.string().min(1).max(24),value:z10.string().min(1).max(16),delta:z10.string().min(1).max(12).optional(),tone:z10.enum(["up","down","flat"]).optional()})).min(1).max(4)}),ChartBlockSchema=BlockBaseSchema.extend({type:z10.literal("chart"),unit:z10.string().min(1).max(12).optional(),points:z10.array(z10.object({label:z10.string().min(1).max(12),value:z10.number().finite().min(0).max(1e9)})).min(2).max(12)}),ChatDisplayBlockSchema=z10.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema]),ChatFormBodySchema=z10.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,AssetsBlockSchema]);__name(getChatFormOptionLabels,"getChatFormOptionLabels");ChatFormStepSchema=z10.object({question:z10.string().min(1).max(500),header:z10.string().min(1).max(25),body:ChatFormBodySchema,multiSelect:z10.boolean(),recommended:z10.string().min(1).max(80).optional()}).superRefine((step,ctx)=>{let labels2=getChatFormOptionLabels(step.body);labels2.some(label=>!label.trim())&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a visible label."}),new Set(labels2).size!==labels2.length&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a unique label."}),step.recommended&&!labels2.includes(step.recommended)&&ctx.addIssue({code:"custom",path:["recommended"],message:"The recommended option must match a visible option label."})}),FormBlockSchema=BlockBaseSchema.extend({type:z10.literal("form"),steps:z10.array(ChatFormStepSchema).min(1).max(4)}),ChatBlockSchema=z10.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,FormBlockSchema]),ChatBlockToolInputSchema=z10.object({block:ChatBlockSchema}),ChatFormAnswerItemSchema=z10.object({header:z10.string().min(1).max(25),question:z10.string().min(1).max(500),answer:z10.string().min(1).max(3e3),selectedLabels:z10.array(z10.string().min(1).max(120)).max(8),freeText:z10.string().max(2e3),skipped:z10.boolean()}),ChatFormAnswerMetadataSchema=z10.object({toolCallId:z10.string().max(255).optional(),shortTitle:z10.string().max(80).optional(),questions:z10.array(ChatFormAnswerItemSchema).max(4)}),ChatFormResponseSchema=ChatFormAnswerMetadataSchema.extend({toolCallId:z10.string().min(1).max(255)})}});import{z as z11}from"zod";var FIMO_CONFIG_PATH,LEGACY_FIMO_CONFIG_PATHS,ALL_FIMO_CONFIG_PATHS,FimoFrameworkSchema,FimoRuntimeCommandsSchema,FimoRuntimeConfigSchema,FimoHostingRewriteSchema,FimoHostingConfigSchema,FimoAppConfigSchema,init_fimo_config=__esm({"../../packages/api-contracts/dist/esm/types/fimo-config.js"(){"use strict";FIMO_CONFIG_PATH=".fimo/config.json",LEGACY_FIMO_CONFIG_PATHS=["fimo-config.json","fimo.config.json"],ALL_FIMO_CONFIG_PATHS=[FIMO_CONFIG_PATH,...LEGACY_FIMO_CONFIG_PATHS],FimoFrameworkSchema=z11.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z11.object({dev:z11.string().trim().min(1).optional(),build:z11.string().trim().min(1).optional(),install:z11.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z11.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z11.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingRewriteSchema=z11.object({source:z11.string().min(1),destination:z11.string().min(1)}),FimoHostingConfigSchema=z11.object({rewrites:z11.array(FimoHostingRewriteSchema).optional()}).strict(),FimoAppConfigSchema=z11.object({runtime:FimoRuntimeConfigSchema.optional(),hosting:FimoHostingConfigSchema.optional()}).passthrough().superRefine((config,context)=>{Object.hasOwn(config,"framework")&&context.addIssue({code:"custom",path:["framework"],message:"Use runtime.framework instead of the top-level framework field."})})}});import{z as z12}from"zod";var PROJECT_CHAT_MANUAL_MODEL_IDS,ProjectChatManualModelIdSchema,ProjectDTOSchema,ProjectDTO,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectHistoryUsageDTOSchema,ProjectVersionPageDTOSchema,ProjectVersionPageDTO,ProjectHistorySummaryDTOSchema,ProjectHistorySummaryDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionResponseSchema,ProjectVersionPageResponseSchema,ProjectHistorySummaryResponseSchema,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_chat_block();init_common();init_create_dto();init_response();PROJECT_CHAT_MANUAL_MODEL_IDS=["anthropic/claude-opus-5","anthropic/claude-sonnet-5","anthropic/claude-fable-5","openai/gpt-5.6-luna","openai/gpt-5.6-terra","openai/gpt-5.6-sol","xai/grok-4.6","google/gemini-3.1-pro-preview","google/gemini-3.7-flash","google/gemini-3.6-flash","google/gemini-3.5-flash-lite","zai/glm-5.2","deepseek/deepseek-v4-pro","minimax/minimax-m3","moonshotai/kimi-k3"],ProjectChatManualModelIdSchema=z12.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z12.string(),displayName:z12.string().nullable(),subdomain:z12.string().nullable().optional(),subdomainUpdatedAt:z12.date().nullable().optional(),organizationId:z12.string().nullable(),createdBy:z12.string().nullable(),previewEnabled:z12.boolean().default(!0),enabledChatModels:z12.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z12.string(),thumbnailUrl:z12.string().nullable(),publishedThumbnailUrl:z12.string().nullable(),category:z12.string().nullable(),appUrl:z12.string().nullable(),lastPublishedAt:z12.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z12.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z12.object({id:z12.uuid(),name:z12.string(),displayName:z12.string().nullable(),thumbnailUrl:z12.string().nullable(),category:z12.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z12.object({id:z12.string(),name:z12.string(),avatar:z12.string().nullable(),color:z12.object({bg:z12.string(),text:z12.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z12.object({path:z12.string(),content:z12.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z12.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z12.object({id:z12.string(),messageId:z12.string(),versionId:z12.string().nullable(),role:ProjectChatMessageRole,parts:z12.array(z12.any()),createdAt:z12.coerce.date()}),MessageUserMetadataSchema=z12.object({id:z12.string(),name:z12.string().nullable().optional(),image:z12.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z12.number(),metadata:z12.object({user:MessageUserMetadataSchema,changeManifest:z12.array(z12.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z12.object({versionId:z12.uuid(),commitHash:z12.string(),name:z12.string(),description:z12.string().nullable(),kind:z12.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z12.object({versionCount:z12.number().int().nonnegative(),snapshotBytes:z12.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z12.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z12.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z12.object({content:z12.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z12.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z12.object({success:z12.boolean(),message:z12.string().optional(),warning:z12.string().optional(),durationMs:z12.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z12.object({isPublished:z12.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z12.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublicationMutationDTOSchema=z12.object({success:z12.boolean(),message:z12.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z12.boolean()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z13}from"zod";var ProjectEnvStatusSchema,ProjectEnvKindSchema,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=z13.enum(["provisioning","active","deleted"]),ProjectEnvKindSchema=z13.enum(["user","agent-session"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z13.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,kind:ProjectEnvKindSchema,previewUrl:z13.string().nullable(),parentEnv:EnvSchema.nullable(),createdBy:z13.string().nullable(),deletedAt:z13.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),CreateProjectEnvRequestSchema=z13.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z13.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z13.array(ProjectEnvDTOSchema)),EnvSurfaceDiffSchema=z13.object({surface:z13.enum(["code","schemas","content","translations","assets","forms"]),status:z13.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z13.number().int().nonnegative(),conflictCount:z13.number().int().nonnegative()}),EnvDiffResultSchema=z13.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z13.coerce.date(),surfaces:z13.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z14}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=z14.object({success:z14.literal(!0),downloadUrl:z14.string(),expiresAt:z14.string(),fileSize:z14.number(),duration:z14.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z14.object({success:z14.literal(!0),projectId:z14.string(),projectName:z14.string(),displayName:z14.string(),projectUrl:z14.string(),duration:z14.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z14.object({contentTypes:z14.number(),entries:z14.number(),assets:z14.number(),translations:z14.number(),forms:z14.number(),codeFiles:z14.number(),assetFiles:z14.number()}),ImportPreviewSurfaceDTOSchema=z14.object({name:z14.string(),included:z14.boolean(),count:z14.number().optional(),note:z14.string().optional()}),ImportPreviewDTOSchema=z14.object({projectName:z14.string(),displayName:z14.string().nullable(),category:z14.string().nullable(),exportedAt:z14.string(),version:z14.string(),envScope:z14.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z14.array(ImportPreviewSurfaceDTOSchema),fileSize:z14.number(),fileName:z14.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z14.object({success:z14.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z15}from"zod";var TriggerKindSchema,ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema,TriggerSchema,init_agent_trigger_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-trigger.dto.js"(){"use strict";TriggerKindSchema=z15.enum(["manual","schedule","webhook"]),ManualTriggerSchema=z15.object({type:z15.literal("manual")}),ScheduleTriggerSchema=z15.object({type:z15.literal("schedule"),cron:z15.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:z15.string().optional()}),WebhookTriggerSchema=z15.object({type:z15.literal("webhook"),path:z15.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z15.discriminatedUnion("type",[ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema])}});import{z as z16}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=z16.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z16.object({token:z16.string().min(1),risk:CapabilityRiskTierSchema,description:z16.string()}),AgentSubAgentSummarySchema=z16.object({name:z16.string().min(1),grant:z16.enum(["inherit","explicit"]),effectiveCaps:z16.array(z16.string().min(1))}),AgentInstallSummaryDTOSchema=z16.object({agentName:z16.string().min(1),env:z16.string().min(1),declaredCapabilities:z16.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z16.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z16.array(CapabilitySummaryEntrySchema),criticalCapabilities:z16.array(CapabilitySummaryEntrySchema),subAgents:z16.array(AgentSubAgentSummarySchema),declaresDelegate:z16.boolean(),cycle:z16.array(z16.string()).nullable(),missingSubAgents:z16.array(z16.string()),warnings:z16.array(z16.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z17}from"zod";var AgentListItemTriggerSchema,AgentListItemTriggerStateSchema,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=z17.object({kind:TriggerKindSchema,summary:z17.string()}),AgentListItemTriggerStateSchema=z17.object({triggerIndex:z17.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z17.boolean(),wired:z17.boolean(),syncError:z17.string().nullable()}),AgentListItemDTOSchema=z17.object({name:z17.string().min(1),description:z17.string().nullable(),goalFirstLine:z17.string().nullable(),declaredCapabilities:z17.array(CapabilitySummaryEntrySchema),triggers:z17.array(AgentListItemTriggerSchema),triggerStates:z17.array(AgentListItemTriggerStateSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z17.array(AgentListItemDTOSchema))}});import{z as z18}from"zod";var ManualRunRequestSchema,DispatchSkippedSchema,DispatchAcceptedSchema,ManualRunResponseSchema,init_agent_run_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-run.dto.js"(){"use strict";init_response();ManualRunRequestSchema=z18.object({args:z18.unknown().optional(),requestId:z18.string().min(1).max(128).optional()}),DispatchSkippedSchema=z18.object({skipped:z18.enum(["no-manual-trigger","trigger-not-wired","run-in-progress","task-env-budget"])}),DispatchAcceptedSchema=z18.object({sessionId:z18.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z18.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z19}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,CONFLICT_KINDS,ConflictKindSchema,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=z19.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z19.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z19.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z19.object({verb:SurfaceDeltaVerbSchema,key:z19.string(),detail:z19.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z19.record(z19.string(),z19.unknown()).optional()}),PerSurfaceDeltaSchema=z19.object({surface:SurfaceNameSchema,status:z19.enum(["ok","timed_out","failed","unchanged"]),durationMs:z19.number().int().nonnegative().optional(),changedCount:z19.number().int().nonnegative(),conflictCount:z19.number().int().nonnegative(),items:z19.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z19.boolean().optional(),error:z19.string().optional()}),CrossSurfaceFindingSchema=z19.object({id:z19.string(),kind:z19.string(),description:z19.string(),severity:z19.enum(["warning","error"]),source:z19.object({surface:SurfaceNameSchema,key:z19.string()}),target:z19.object({surface:SurfaceNameSchema,key:z19.string()}),actions:z19.array(z19.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z19.object({env:EnvSchema,vs:EnvSchema,syncState:z19.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z19.coerce.date(),surfaces:z19.array(PerSurfaceDeltaSchema),agents:z19.array(z19.object({id:z19.string(),name:z19.string(),status:z19.enum(["active","paused","failed"]),lastRunAt:z19.coerce.date().nullable()})).optional(),crossSurface:z19.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z19.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z19.coerce.date(),surfaces:z19.array(PerSurfaceDeltaSchema),crossSurface:z19.array(CrossSurfaceFindingSchema).optional(),fingerprint:z19.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z19.object({path:z19.string(),state:z19.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z19.string(),additions:z19.number().int().nonnegative(),deletions:z19.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z19.object({oid:z19.string().optional(),content:z19.string().optional(),truncated:z19.boolean(),binary:z19.boolean()}),CodeConflictDetailSchema=z19.object({path:z19.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z19.string(),targetTipSha:z19.string(),mergeBaseSha:z19.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z19.object({id:z19.string(),slug:z19.string(),contentType:z19.string(),data:z19.record(z19.string(),z19.unknown()),updatedAt:z19.coerce.date()}),ContentRowDiffSchema=z19.object({collection:z19.string(),rowId:z19.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z19.object({name:z19.string(),label:z19.string(),isSingleton:z19.boolean(),fields:z19.record(z19.string(),z19.unknown())}),SchemaTypeDiffSchema=z19.object({typeName:z19.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z19.object({id:z19.string(),name:z19.string(),type:z19.enum(["file","folder"]),mimeType:z19.string().nullable(),storageKey:z19.string().nullable(),url:z19.string().nullable(),fileSize:z19.number().nullable(),width:z19.number().nullable(),height:z19.number().nullable(),altText:z19.string().nullable(),caption:z19.string().nullable(),createdAt:z19.coerce.date(),updatedAt:z19.coerce.date()}),AssetDiffSchema=z19.object({assetId:z19.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z19.object({locale:z19.string(),key:z19.string(),parent:z19.string().nullable(),child:z19.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z19.object({formName:z19.string(),label:z19.string().nullable(),schemaFingerprint:z19.string(),fields:z19.record(z19.string(),z19.unknown()),settings:z19.record(z19.string(),z19.unknown()).optional()}),FormSchemaDiffSchema=z19.object({formName:z19.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z19.enum(CONFLICT_KINDS),ConflictSchema=z19.object({surface:SurfaceNameSchema,key:z19.string(),kind:ConflictKindSchema.optional(),description:z19.string(),parentValue:z19.unknown().optional(),childValue:z19.unknown().optional(),conflictingFields:z19.array(z19.string()).optional(),code:z19.object({path:z19.string(),unresolvable:z19.boolean().optional(),reason:z19.string().optional()}).optional()}),FieldPickSchema=z19.object({field:z19.string(),choice:z19.enum(["parent","child","pick","ai-pick"]),pickedValue:z19.unknown().optional(),aiSessionId:z19.string().optional()}),ConflictResolutionSchema=z19.object({surface:SurfaceNameSchema,key:z19.string(),choice:z19.enum(["parent","child","pick"]),pickedValue:z19.unknown().optional(),fieldPicks:z19.array(FieldPickSchema).optional()}),MergeResultSchema=z19.object({ok:z19.boolean(),mergeId:z19.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z19.array(z19.object({surface:SurfaceNameSchema,count:z19.number().int().nonnegative()})),conflicts:z19.array(ConflictSchema).optional(),summary:z19.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z19.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z19.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z19.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z19.boolean().optional()}),ResolvedStrategySchema=z19.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z19.boolean()}),MergeRequestSchema=z19.object({from:EnvSchema,allowDirectMerge:z19.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z19.object({mergeId:z19.string().uuid(),streamUrl:z19.string(),strategy:ResolvedStrategySchema,acceptedAt:z19.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z19.object({mergeId:z19.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z19.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z19.array(ConflictSchema),draftResolutions:z19.array(ConflictResolutionSchema),lastEditedBy:z19.string().nullable(),lastEditedAt:z19.coerce.date().nullable(),initiator:z19.object({userId:z19.string().nullable(),role:z19.string().nullable(),agentName:z19.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z19.object({resolutions:z19.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z19.object({mergeId:z19.string().uuid(),draftResolutions:z19.array(ConflictResolutionSchema),lastEditedAt:z19.coerce.date(),lastEditedBy:z19.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z19.object({mergeId:z19.string().uuid(),resolutions:z19.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z19.object({mergeId:z19.string().uuid()}),PublishReleaseRequestSchema=z19.object({version:z19.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z19.string().max(2e4).optional()}),PublishReleaseResultSchema=z19.object({releaseTag:z19.string(),sha:z19.string(),publishedAt:z19.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z20}from"zod";var AgentSessionStatusSchema,SessionMetricsSchema,AgentSessionReviewPublicationSchema,AgentSessionReviewSummarySchema,AgentSessionReviewSummaryDTO,AgentSessionReviewPayloadSchema,AgentSessionReviewPayloadDTO,AgentSessionReviewPayloadResponseSchema,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();init_env_status_dto();AgentSessionStatusSchema=z20.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z20.object({cpuMs:z20.number().nonnegative().default(0),netBytes:z20.number().nonnegative().default(0),walltimeMs:z20.number().nonnegative().default(0),llmTokensIn:z20.number().nonnegative().optional(),llmTokensOut:z20.number().nonnegative().optional(),stepCount:z20.number().int().nonnegative().optional(),toolCallCounts:z20.record(z20.string().min(1).max(120),z20.number().int().nonnegative()).optional()}),AgentSessionReviewPublicationSchema=z20.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z20.object({capturedAt:z20.coerce.date(),fingerprint:z20.string().min(1).max(256),counts:z20.object({code:z20.number().int().nonnegative(),content:z20.number().int().nonnegative(),schemas:z20.number().int().nonnegative(),labels:z20.number().int().nonnegative()}),publication:AgentSessionReviewPublicationSchema,mergeId:z20.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z20.object({diff:DiffReportSchema,code:z20.array(CodeFileDiffSchema.extend({raw:z20.string().max(24576)})).max(200),schemas:z20.array(SchemaTypeDiffSchema).max(200),content:z20.array(z20.object({key:z20.string().min(1).max(512),collection:z20.string().min(1).max(256),slug:z20.string().max(512).optional(),verb:z20.enum(["added","modified","deleted"]),fields:z20.array(z20.object({name:z20.string().min(1).max(256),before:z20.unknown().optional(),after:z20.unknown().optional()})).max(20)})).max(200),labels:z20.array(z20.object({key:z20.string().min(1).max(512),locale:z20.string().min(1).max(64).optional(),before:z20.unknown().nullable(),after:z20.unknown().nullable()})).max(200)}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),AgentSessionDTOSchema=z20.object({id:z20.uuid(),projectId:z20.uuid(),env:EnvSchema,agentName:z20.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z20.unknown().optional(),capabilities:z20.array(z20.string()).optional(),dataSources:z20.array(z20.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z20.string().nullable(),startedAt:z20.coerce.date().nullable(),finishedAt:z20.coerce.date().nullable(),cancelledAt:z20.coerce.date().nullable(),costUsd:z20.number().nonnegative(),costCeilingUsd:z20.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z20.boolean(),lastCheckpointId:z20.uuid().nullable(),branchEnvId:z20.uuid().nullable(),parentSessionId:z20.uuid().nullable(),terminalReason:z20.string().nullable(),errorMessage:z20.string().nullable(),report:z20.string().nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z20.string().nullable(),createdAt:z20.coerce.date(),updatedAt:z20.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z20.object({id:z20.uuid(),sessionId:z20.uuid(),checkpointIdx:z20.number().int().nonnegative(),payloadRef:z20.string(),payloadSizeBytes:z20.number().int().nonnegative(),checksum:z20.string().length(64),createdAt:z20.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z20.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z20.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z20.object({session:AgentSessionDTOSchema,checkpoints:z20.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z20.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","too_many_agent_envs","env_provisioning_failed","agent_run_in_progress"]),CancelSessionRequestSchema=z20.object({reason:z20.string().min(1).max(120).optional()})}});import{z as z21}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=z21.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z21.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z21.object({id:z21.uuid(),envId:z21.uuid(),sessionId:z21.uuid().nullable(),skillName:z21.string().min(1),classification:AgentBranchClassificationSchema,rationale:z21.string().nullable(),summary:z21.string().nullable(),surfaceDeltas:z21.record(z21.string(),z21.unknown()),createdAt:z21.coerce.date(),decidedAt:z21.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z21.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z21.object({path:z21.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z21.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z21.object({code:z21.literal("merge_conflict"),message:z21.string(),conflicts:z21.record(z21.string(),z21.number().int().nonnegative())})}});import{z as z22}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,IntegrationToolEffectSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,SetProjectIntegrationCredentialRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,ConnectOrganizationIntegrationRequestSchema,ProjectIntegrationReturnPathSchema,ConnectProjectIntegrationRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,ProjectIntegrationConnectResponseSchema,BindProjectChannelRequestSchema,ListProjectChannelsQuerySchema,SearchProjectChannelsQuerySchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,ProjectChannelCandidateAvailabilitySchema,ProjectChannelCandidateDTOSchema,ProjectChannelCandidateDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,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,ProjectIntegrationConnectionsResponseSchema,ProjectIntegrationConnectResponseResponseSchema,ProjectChannelBindingResponseSchema,ProjectChannelBindingsResponseSchema,ProjectChannelCandidatesResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z22.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z22.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z22.enum(["secret_text"]),IntegrationCredentialUsageSchema=z22.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z22.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z22.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z22.object({mode:IntegrationAuthModeSchema,label:z22.string().min(1),description:z22.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z22.object({id:z22.string().min(1),label:z22.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z22.boolean()}),IntegrationToolDefinitionDTOSchema=z22.object({key:z22.string().min(1),name:z22.string().min(1),description:z22.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z22.object({title:z22.string().min(1),description:z22.string().min(1),command:z22.string().min(1).optional()}),IntegrationInfoDTOSchema=z22.object({key:z22.string().min(1),name:z22.string().min(1),summary:z22.string().min(1),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z22.array(IntegrationAuthModeDTOSchema),credentials:z22.array(IntegrationCredentialDefinitionDTOSchema),tools:z22.array(IntegrationToolDefinitionDTOSchema),recipes:z22.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z22.object({projectId:z22.uuid(),integrationKey:z22.string().min(1),name:z22.string().min(1),summary:z22.string().min(1),installed:z22.boolean(),enabled:z22.boolean(),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z22.string().nullable(),connectionId:z22.uuid().nullable().optional(),connectionAlias:z22.string().min(1).nullable().optional(),connectionStatus:z22.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z22.array(z22.string()),installedAt:z22.coerce.date().nullable(),updatedAt:z22.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z22.object({id:z22.uuid(),projectId:z22.uuid(),integrationKey:z22.string().min(1),enabled:z22.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z22.string(),connectionId:z22.uuid().nullable().optional(),connectionAlias:z22.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z22.array(z22.string()),createdAt:z22.coerce.date(),updatedAt:z22.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z22.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z22.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z22.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z22.object({value:z22.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z22.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z22.object({id:z22.uuid(),organizationId:z22.string().min(1),integrationKey:z22.string().min(1),alias:z22.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z22.string().min(1),externalAccountName:z22.string().nullable(),externalBotUserId:z22.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z22.array(z22.string()),connectedAt:z22.coerce.date(),updatedAt:z22.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ConnectOrganizationIntegrationRequestSchema=z22.object({alias:z22.string().min(1).max(120).optional(),token:z22.string().min(1).optional()}),ProjectIntegrationReturnPathSchema=z22.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),ConnectProjectIntegrationRequestSchema=z22.discriminatedUnion("mode",[z22.object({mode:z22.literal("personal"),alias:z22.string().min(1).max(120),token:z22.string().min(1)}),z22.object({mode:z22.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional()})]),StartProjectIntegrationConnectResponseSchema=z22.object({integrationKey:z22.string().min(1),connectUrl:z22.string().url(),expiresAt:z22.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z22.discriminatedUnion("mode",[z22.object({mode:z22.literal("personal"),integrationKey:z22.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z22.object({mode:z22.literal("oauth"),integrationKey:z22.string().min(1),connectUrl:z22.string().url(),expiresAt:z22.coerce.date()})]),BindProjectChannelRequestSchema=z22.object({ref:z22.string().min(1),connectionAlias:z22.string().min(1).optional(),agentName:z22.string().min(1).max(160).nullable().optional(),force:z22.boolean().optional()}),ListProjectChannelsQuerySchema=z22.object({integrationKey:z22.string().min(1)}),SearchProjectChannelsQuerySchema=z22.object({integrationKey:z22.string().min(1),connectionAlias:z22.string().min(1),query:z22.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z22.object({id:z22.uuid(),projectId:z22.uuid(),integrationKey:z22.string().min(1),connectionId:z22.uuid(),externalWorkspaceId:z22.string().min(1),externalChannelId:z22.string().min(1),externalChannelName:z22.string().nullable(),agentName:z22.string().nullable(),enabled:z22.boolean(),createdAt:z22.coerce.date(),updatedAt:z22.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z22.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z22.object({id:z22.string().min(1),name:z22.string().min(1),visibility:z22.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z22.string().min(1).nullable(),canMove:z22.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z22.object({markdown:z22.boolean().optional(),summary:z22.boolean().optional(),links:z22.boolean().optional(),images:z22.boolean().optional(),html:z22.union([z22.literal("cleaned"),z22.literal("raw"),z22.boolean()]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z22.object({url:z22.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z22.boolean().optional(),timeoutMs:z22.number().int().positive().max(12e4).optional(),waitForMs:z22.number().int().min(0).max(3e4).optional()}),FirecrawlSearchToolInputSchema=z22.object({query:z22.string().min(1),maxResults:z22.number().int().positive().max(20).optional(),sources:z22.array(z22.enum(["web","news","images"])).min(1).max(3).optional(),categories:z22.array(z22.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z22.array(z22.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z22.array(z22.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z22.enum(["hour","day","week","month","year"]).optional(),location:z22.string().min(1).max(160).optional(),country:z22.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z22.boolean().optional(),timeoutMs:z22.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlMapToolInputSchema=z22.object({url:z22.string().url(),search:z22.string().min(1).optional(),limit:z22.number().int().positive().max(200).optional(),includeSubdomains:z22.boolean().optional(),timeoutMs:z22.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z22.object({url:z22.string().url(),limit:z22.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z22.boolean().optional(),timeoutMs:z22.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z22.object({text:z22.string().min(1).max(200).optional(),cron:z22.string().min(1).max(120).optional(),timezone:z22.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorTargetInputSchema=z22.object({type:z22.enum(["scrape","crawl"]).default("scrape"),urls:z22.array(z22.string().url()).min(1).max(50),scrapeOptions:z22.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z22.boolean().optional(),timeoutMs:z22.number().int().positive().max(12e4).optional(),waitForMs:z22.number().int().min(0).max(3e4).optional()}).optional()}),FirecrawlMonitorCreateToolInputSchema=z22.object({name:z22.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z22.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z22.string().min(1).max(2e3).optional(),judgeEnabled:z22.boolean().optional(),retentionDays:z22.number().int().min(1).max(365).optional(),notification:z22.object({email:z22.object({enabled:z22.boolean().default(!0),recipients:z22.array(z22.string().email()).min(1).max(20),includeDiffs:z22.boolean().optional()}).optional()}).optional()}),FirecrawlMonitorIdToolInputSchema=z22.object({monitorId:z22.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z22.string().uuid()}),RunProjectIntegrationToolRequestSchema=z22.object({tool:z22.string().min(1),input:z22.record(z22.string(),z22.unknown()),connectionAlias:z22.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z22.object({provider:z22.string().min(1),providerCredits:z22.number().nonnegative().optional(),providerCostUsd:z22.number().nonnegative().optional(),requests:z22.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z22.object({credits:z22.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z22.object({url:z22.string(),provider:z22.literal("firecrawl"),title:z22.string().optional(),statusCode:z22.number().optional(),markdown:z22.string().optional(),summary:z22.string().optional(),links:z22.array(z22.string()).optional(),images:z22.array(z22.string()).optional(),html:z22.string().optional(),warning:z22.string().optional()}),FirecrawlSearchToolOutputSchema=z22.object({query:z22.string(),provider:z22.literal("firecrawl"),warning:z22.string().optional(),results:z22.array(z22.object({title:z22.string(),url:z22.string(),snippet:z22.string().optional(),content:z22.string().optional(),score:z22.number().optional(),publishedAt:z22.string().optional()}))}),FirecrawlMapToolOutputSchema=z22.object({url:z22.string(),provider:z22.literal("firecrawl"),count:z22.number(),links:z22.array(z22.object({url:z22.string(),title:z22.string().optional(),description:z22.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z22.object({url:z22.string(),provider:z22.literal("firecrawl"),total:z22.number(),pages:z22.array(z22.object({url:z22.string(),title:z22.string().optional(),statusCode:z22.number().optional(),markdown:z22.string().optional(),summary:z22.string().optional(),links:z22.array(z22.string()).optional(),images:z22.array(z22.string()).optional(),html:z22.string().optional(),warning:z22.string().optional()})),warning:z22.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z22.object({cron:z22.string().optional(),text:z22.string().optional(),timezone:z22.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z22.object({id:z22.string().optional(),urls:z22.array(z22.string()).optional(),scrapeOptions:z22.record(z22.string(),z22.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z22.object({id:z22.string(),name:z22.string(),status:z22.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z22.string().nullable().optional(),lastRunAt:z22.string().nullable().optional(),currentCheckId:z22.string().nullable().optional(),targets:z22.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z22.string().nullable().optional(),judgeEnabled:z22.boolean().optional(),estimatedCreditsPerMonth:z22.number().optional(),createdAt:z22.string().optional(),updatedAt:z22.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z22.object({id:z22.string(),monitorId:z22.string(),scheduledFor:z22.string().nullable().optional(),startedAt:z22.string().nullable().optional(),finishedAt:z22.string().nullable().optional(),estimatedCredits:z22.number().optional(),reservedCredits:z22.number().optional(),actualCredits:z22.number().optional(),billingStatus:z22.string().nullable().optional(),summary:z22.object({totalPages:z22.number().optional(),same:z22.number().optional(),changed:z22.number().optional(),new:z22.number().optional(),removed:z22.number().optional(),error:z22.number().optional()}).passthrough().optional(),error:z22.string().nullable().optional(),createdAt:z22.string().optional(),updatedAt:z22.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z22.object({provider:z22.literal("firecrawl"),monitors:z22.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z22.object({provider:z22.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z22.object({provider:z22.literal("firecrawl"),monitorId:z22.string(),deleted:z22.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z22.object({provider:z22.literal("firecrawl"),monitorId:z22.string(),checks:z22.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z22.object({provider:z22.literal("firecrawl"),monitorId:z22.string(),check:FirecrawlMonitorCheckOutputSchema,next:z22.string().optional()}),FirecrawlToolKeySchema=z22.enum(["search","scrape","map","crawl","monitor.create","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z22.union([FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z22.object({projectId:z22.uuid(),integrationKey:z22.string().min(1),tool:z22.string().min(1),connectionAlias:z22.string().min(1).nullable().optional(),output:z22.record(z22.string(),z22.unknown()),executedAt:z22.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z22.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z22.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z22.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z22.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z22.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z22.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z22.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z22.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z22.array(OrganizationIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z22.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z22.array(ProjectChannelCandidateDTOSchema))}});import{z as z23}from"zod";var SCHEDULE_NOTIFICATION_TOPICS,ScheduleNotificationTopicSchema,USER_MANAGED_NOTIFICATION_TOPICS,UserManagedNotificationTopicSchema,MAX_SCHEDULE_SUBSCRIBERS,ScheduleSubscriberDeliveryStateSchema,ScheduleSubscriberCandidateSchema,ScheduleNotificationSettingsSchema,ScheduleNotificationSettingsResponseSchema,UpdateScheduleSubscribersRequestSchema,UserNotificationPreferenceSchema,UserNotificationPreferencesSchema,UserNotificationPreferencesResponseSchema,UpdateUserNotificationPreferenceRequestSchema,SCHEDULE_OPT_OUT_LINK_ACTIONS,ScheduleOptOutLinkActionSchema,SCHEDULE_OPT_OUT_ACTIONS,ScheduleOptOutActionSchema,ScheduleOptOutStateSchema,ScheduleOptOutResponseSchema,FollowedScheduleSchema,FollowedSchedulesSchema,FollowedSchedulesResponseSchema,init_schedule_notifications_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule-notifications.dto.js"(){"use strict";init_response();SCHEDULE_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],ScheduleNotificationTopicSchema=z23.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],UserManagedNotificationTopicSchema=z23.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z23.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z23.object({userId:z23.string().min(1),name:z23.string(),email:z23.string().min(1),subscribed:z23.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z23.object({maxSubscribers:z23.number().int().positive(),subscriberCount:z23.number().int().nonnegative(),effectiveRecipientCount:z23.number().int().nonnegative(),currentUserSubscribed:z23.boolean(),candidates:z23.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z23.object({userIds:z23.array(z23.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z23.object({topic:UserManagedNotificationTopicSchema,enabled:z23.boolean(),source:z23.enum(["default","explicit"])}),UserNotificationPreferencesSchema=z23.object({topics:z23.array(UserNotificationPreferenceSchema)}),UserNotificationPreferencesResponseSchema=createResponseSchema(UserNotificationPreferencesSchema),UpdateUserNotificationPreferenceRequestSchema=z23.object({enabled:z23.boolean()}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z23.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z23.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z23.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z23.string().nullable(),maskedEmail:z23.string().min(1),applied:z23.boolean(),expiresAt:z23.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z23.object({scheduleId:z23.string().min(1),scheduleName:z23.string(),projectId:z23.string().min(1),projectName:z23.string(),env:z23.string().min(1)}),FollowedSchedulesSchema=z23.object({schedules:z23.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z24}from"zod";var PROJECT_SECRET_KEY_PATTERN,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN,RESERVED_PROJECT_SECRET_KEYS,ProjectSecretKeySchema,ProjectScheduleStatusSchema,ProjectScheduleDTOSchema,ProjectScheduleDTO,CreateProjectScheduleRequestSchema,UpdateProjectScheduleRequestSchema,ProjectScheduleRunStatusSchema,ProjectScheduleRunTriggerSchema,ProjectScheduleRunSecretSnapshotStateSchema,ProjectScheduleRunSecretResolutionSchema,ProjectSchedulePolicySchema,SchedulePolicyStateSchema,ProjectSchedulePlanSnapshotSchema,ProjectScheduleUsageSchema,ProjectScheduleRunDTOSchema,ProjectScheduleRunDTO,ProjectScheduleRunSecretSnapshotSchema,ProjectScheduleRunDetailDTOSchema,ProjectScheduleRunDetailDTO,RunProjectScheduleRequestSchema,ProjectScheduleRunsQuerySchema,ProjectScheduleResponseSchema,ProjectSchedulesListDataSchema,ProjectSchedulesListResponseSchema,ProjectSchedulesOverviewResponseSchema,ProjectScheduleDetailDataSchema,ProjectScheduleDetailResponseSchema,ProjectScheduleRunsPageSchema,ProjectScheduleRunsResponseSchema,ProjectScheduleRunResponseSchema,ProjectScheduleRunDetailResponseSchema,init_schedule_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();init_schedule_notifications_dto();PROJECT_SECRET_KEY_PATTERN=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN=/^(PUBLIC_|VITE_|NEXT_PUBLIC_|NUXT_PUBLIC_)/,RESERVED_PROJECT_SECRET_KEYS=new Set([...FIMO_MANAGED_PROJECT_ENV_KEYS,"FIMO_SCHEDULE_ID","FIMO_SCHEDULE_RUN_ID","FIMO_SCHEDULE_NAME"]),ProjectSecretKeySchema=z24.string().min(1).max(255).superRefine((key,context)=>{PROJECT_SECRET_KEY_PATTERN.test(key)?RESERVED_PROJECT_SECRET_KEYS.has(key)?context.addIssue({code:"custom",message:`Secret key '${key}' is managed by Fimo and cannot be stored in project secrets.`}):PUBLIC_PROJECT_SECRET_PREFIX_PATTERN.test(key)&&context.addIssue({code:"custom",message:`Secret key '${key}' uses a public variable prefix. Store public values with fimo vars instead.`}):context.addIssue({code:"custom",message:`Secret key '${key}' must be UPPER_SNAKE_CASE.`})}),ProjectScheduleStatusSchema=z24.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z24.uuid(),env:z24.string().min(1),name:z24.string().min(1),cron:z24.string().min(1),command:z24.string().min(1),secretKeys:z24.array(z24.string().min(1)),enabled:z24.boolean(),lastRunAt:z24.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z24.string().nullable(),overPolicyReasons:z24.array(z24.string()).optional()}),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),secretKeys:z24.array(ProjectSecretKeySchema).default([]),enabled:z24.boolean().optional()}),UpdateProjectScheduleRequestSchema=z24.object({name:z24.string().min(1).max(120).optional(),cron:z24.string().min(1).max(120).optional(),command:z24.string().min(1).max(500).optional(),secretKeys:z24.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z24.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z24.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z24.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z24.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z24.object({maxRuns:z24.number().int().positive(),retentionDays:z24.number().int().positive().nullable(),outputRetentionDays:z24.number().int().positive(),maxOutputBytes:z24.number().int().positive()}),SchedulePolicyStateSchema=z24.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z24.object({code:z24.enum(["Free","Premium"]),source:z24.enum(["cached_subscription","free_fallback"]),activeSchedules:z24.object({used:z24.number().int().nonnegative(),limit:z24.number().int().positive()}),minCadenceMinutes:z24.number().int().positive(),maxRunMs:z24.number().int().positive(),concurrency:z24.object({used:z24.number().int().nonnegative(),limit:z24.number().int().positive()}),compute:z24.object({settledMs:z24.number().int().nonnegative(),reservedMs:z24.number().int().nonnegative(),includedMs:z24.number().int().positive(),remainingMs:z24.number().int().nonnegative(),resetsAt:z24.coerce.date()}),upgrade:z24.object({code:z24.literal("Premium"),activeSchedulesLimit:z24.number().int().positive(),minCadenceMinutes:z24.number().int().positive(),maxRunMs:z24.number().int().positive(),maxConcurrentRuns:z24.number().int().positive(),computeIncludedMs:z24.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z24.array(z24.string())}),ProjectScheduleUsageSchema=z24.object({runCount:z24.number().int().nonnegative(),runsWithOutput:z24.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z24.object({id:z24.uuid(),scheduleId:z24.uuid(),projectId:z24.uuid(),env:z24.string().min(1),scheduleName:z24.string().min(1),command:z24.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z24.object({id:z24.string().min(1),name:z24.string().min(1)}).nullable(),queuedAt:z24.coerce.date(),startedAt:z24.coerce.date().nullable(),finishedAt:z24.coerce.date().nullable(),exitCode:z24.number().int().nullable(),errorCode:z24.string().nullable(),error:z24.string().nullable(),outputBytes:z24.number().int().nonnegative(),outputTruncated:z24.boolean(),outputExpiresAt:z24.coerce.date().nullable(),metadataExpiresAt:z24.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z24.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z24.coerce.date().nullable(),items:z24.array(z24.object({key:z24.string().min(1),updatedAt:z24.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z24.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z24.object({trigger:z24.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z24.object({limit:z24.coerce.number().int().min(1).max(100).default(25),cursor:z24.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z24.object({items:z24.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z24.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z24.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z24.object({items:z24.array(ProjectScheduleRunDTOSchema),nextCursor:z24.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});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 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=z26.object({surface:SurfaceNameSchema,key:z26.string(),label:z26.string()}),InlineSchema=z26.object({text:z26.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z26.discriminatedUnion("type",[z26.object({type:z26.literal("paragraph"),content:z26.array(InlineSchema).max(24)}),z26.object({type:z26.literal("preview"),ref:DiffRefSchema,caption:z26.string().optional()}),z26.object({type:z26.literal("code"),code:z26.string(),lang:z26.string().optional(),caption:z26.string().optional()}),z26.object({type:z26.literal("risk"),level:z26.enum(["warning","error"]),content:z26.array(InlineSchema).max(24)}),z26.object({type:z26.literal("list"),items:z26.array(z26.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z26.object({headline:z26.string(),blocks:z26.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z26.object({summary:EnvDiffSummarySchema,fingerprint:z26.string(),generatedAt:z26.coerce.date(),cached:z26.boolean().optional(),credits:z26.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z27}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=z27.object({date:z27.string(),visitors:z27.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z27.object({key:z27.string(),visitors:z27.number().int().nonnegative(),pageviews:z27.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z27.object({path:z27.string(),pageName:z27.string().nullable().optional(),visitors:z27.number().int().nonnegative(),pageviews:z27.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z27.object({preset:z27.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z27.string(),requestedTo:z27.string(),effectiveFrom:z27.string(),effectiveTo:z27.string(),isRetentionLimited:z27.boolean(),groupBy:z27.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z27.object({date:z27.string(),content:z27.string(),updatedAt:z27.string(),updatedByUserId:z27.string()}),ProjectPageviewAnalyticsDTOSchema=z27.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z27.number().int().nonnegative(),pageviews:z27.number().int().nonnegative(),bounceRate:z27.number().min(0).max(100),viewsPerVisit:z27.number().nonnegative(),averageVisitDurationSeconds:z27.number().nonnegative(),visitorsSeries:z27.array(ProjectDailyVisitorsDTOSchema),topPages:z27.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z27.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z27.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z27.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z27.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z27.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z28}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=z28.object({id:z28.string(),email:z28.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z28.coerce.date(),createdAt:z28.coerce.date(),inviterUserId:z28.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z28.object({id:z28.string(),token:z28.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z28.object({success:z28.boolean(),projectId:z28.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z29}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=z29.object({id:z29.string(),name:z29.string(),image:z29.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z29.object({count:z29.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z29.object({counts:z29.object({signed_up:z29.int(),activated:z29.int()}),credits:z29.object({total:z29.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z29.email(),emailVerified:z29.boolean(),createdAt:z29.coerce.date(),updatedAt:z29.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z30}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,PROJECT_PERMISSION_KEYS,ProjectPermissionKeySchema,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=z30.object({id:z30.string(),principalType:ProjectPrincipalTypeSchema,principalId:z30.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z30.coerce.date(),expiresAt:z30.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),PROJECT_PERMISSION_KEYS=["project:read","project:manage","project:publish","project:unpublish","project:duplicate","project:export","project:import","project:transfer","project:delete","acl:read","acl:grant","member:read","member:change-role","invite:read","invite:send","invite:revoke","asset:read","asset:upload","asset:manage","asset:delete","code:view","code:edit","content:view","content:edit","chat:read","chat:prompt","history:view","history:manage","comment:read","comment:create","comment:delete","integration:run","sync:github","webhook:read","webhook:manage","schedule:read","schedule:manage","preview:view","realtime:connect","analytics:view","logs:view","domain:manage","agent:run"],ProjectPermissionKeySchema=z30.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z30.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z30.record(z30.string(),z30.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z30.object({access:z30.array(ProjectAccessItemDTOSchema),invites:z30.array(ProjectInviteDTOSchema),organization:z30.object({name:z30.string().nullable(),logo:z30.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z30.object({success:z30.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z30.object({success:z30.boolean(),projectId:z30.uuid()}))}});import{z as z31}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=z31.object({publicationStatus:PublicationStatusSchema,appUrl:z31.string().nullable(),lastPublishedAt:z31.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z32}from"zod";var SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();SandboxSessionDTOSchema=z32.object({url:z32.url(),expiresAt:z32.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema)}});import{z as z33}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:z33.string(),slug:z33.string().nullable(),logo:z33.string().nullable(),metadata:z33.record(z33.string(),z33.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z33.object({id:z33.string(),name:z33.string(),email:z33.email(),image:z33.string().nullable()}),OrganizationMemberDTOSchema=z33.object({id:z33.string(),userId:z33.string(),organizationId:z33.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z33.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z34}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,AutoRefillConfigDTOSchema,AutoRefillConfigDTO,UpdateAutoRefillDTOSchema,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,AutoRefillConfigResponseSchema,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=z34.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z34.object({reason:CancellationReasonCodeSchema,details:z34.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z34.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),AiCreditsEntitlementSchema=z34.object({included:z34.number().optional(),unitPrice:z34.number().optional(),dailyCap:z34.number().nullable().optional()}),EntitlementsDTOSchema=z34.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z34.object({retentionDays:z34.number().int().positive(),canUseExtendedDateRanges:z34.boolean()}).optional(),history:z34.object({retentionDays:z34.number().int().positive()}).optional(),members:z34.object({canInvite:z34.boolean(),maxMembers:z34.number().int().positive().nullable()}).optional(),domains:z34.object({canUseCustomDomains:z34.boolean(),maxDomains:z34.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z34.object({id:z34.string(),external_id:z34.string(),customerId:z34.string(),planId:z34.string(),planCode:TemplateCodeSchema,currentPeriod:z34.object({start:z34.string(),end:z34.string().nullable()}),cancelAt:z34.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z34.string(),nextPaymentAt:z34.string().nullable(),baseAmount:z34.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z34.object({totalCap:z34.number(),dailyCap:z34.number(),usedTotal:z34.number()}),CreditBalanceDTOSchema=z34.object({total:z34.number(),base:z34.number(),dailyBase:z34.number(),purchases:z34.number(),awards:z34.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z34.object({total:z34.number(),nearLimit:z34.boolean(),canChat:z34.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z34.object({dailyFreeAvailable:z34.number(),monthlyAvailable:z34.number(),purchasedAvailable:z34.number(),awardedAvailable:z34.number()}),ProjectDailyCreditAllowanceDTOSchema=z34.object({periodCap:z34.number(),dailyGrant:z34.number(),usedThisPeriod:z34.number(),remainingThisPeriod:z34.number()}),ProjectCreditBalanceDTOSchema=z34.object({projectId:z34.uuid(),organizationId:z34.string(),balance:z34.object({totalAvailable:z34.number(),nearLimit:z34.boolean(),canUseAi:z34.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z34.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AutoRefillConfigDTOSchema=z34.discriminatedUnion("enabled",[z34.object({enabled:z34.literal(!0),thresholdUsd:z34.number().nonnegative(),refillAmountUsd:z34.number().nonnegative()}),z34.object({enabled:z34.literal(!1),thresholdUsd:z34.number().nonnegative().nullable(),refillAmountUsd:z34.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z34.discriminatedUnion("enabled",[z34.object({enabled:z34.literal(!0),thresholdUsd:z34.number().min(.01).multipleOf(.01),refillAmountUsd:z34.number().min(.01).multipleOf(.01)}).strict(),z34.object({enabled:z34.literal(!1),thresholdUsd:z34.number().min(.01).multipleOf(.01)}).strict()]),SuccessfulPurchaseDTOSchema=z34.object({invoiceId:z34.string(),newBalance:z34.int(),creditCount:z34.int(),amountUsd:z34.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z34.object({url:z34.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),AutoRefillConfigResponseSchema=createResponseSchema(AutoRefillConfigDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema)}});import{z as z35}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=z35.object({brand:z35.string(),last4:z35.string(),exp:z35.string(),isDefault:z35.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z36}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=z36.string().superRefine((path49,ctx)=>{let segments=path49.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=z36.object({type:z36.literal("renameField"),contentType:z36.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z36.object({enabled:z36.boolean()}).strict(),ContentTypeDTOSchema=z36.object({id:z36.string(),name:z36.string(),label:z36.string(),isSingleton:z36.boolean(),i18n:ContentTypeI18nSchema,fields:z36.record(z36.string(),FieldDefinitionSchema),createdAt:z36.string(),updatedAt:z36.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z36.object({contentTypes:z36.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z36.object({id:z36.string(),entryId:z36.string(),documentId:z36.string(),slug:z36.string(),locale:z36.string().optional(),createdAt:z36.string(),updatedAt:z36.string(),__fimo:z36.object({contentType:z36.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z36.object({data:z36.array(EntryDTOSchema),meta:z36.object({limit:z36.number(),offset:z36.number(),total:z36.number(),hasMore:z36.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z36.object({contentType:z36.string(),count:z36.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z36.object({counts:z36.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z36.object({count:z36.number().int().nonnegative(),sourceLocale:z36.string(),targetLocale:z36.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z36.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z36.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z36.union([z36.string(),z36.number(),z36.boolean(),z36.null()]),entryWhereOperatorSchema=z36.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z36.array(entryWhereScalarSchema).optional(),$nin:z36.array(entryWhereScalarSchema).optional(),$contains:z36.string().optional(),$startsWith:z36.string().optional(),$null:z36.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z36.record(z36.string(),z36.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z36.record(z36.string(),z36.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z36.object({data:z36.record(z36.string(),z36.unknown()),locale:z36.string().min(1).optional(),documentId:z36.uuid().optional()}),entryIdsSchema=z36.array(z36.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z36.object({sql:z36.string().min(1)}),BulkCreateEntriesRequestSchema=z36.object({entries:z36.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z36.union([z36.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z36.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z36.object({updates:z36.array(z36.object({id:z36.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z36.union([z36.object({ids:entryIdsSchema,locale:z36.string().min(1).optional()}),z36.object({where:EntryWhereSchema,locale:z36.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z36.object({data:z36.array(z36.record(z36.string(),z36.unknown())),meta:z36.object({rowCount:z36.number().int().nonnegative(),truncated:z36.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z36.object({data:z36.array(EntryDTOSchema),meta:z36.object({created:z36.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z36.object({data:z36.array(EntryDTOSchema),meta:z36.object({updated:z36.number().int().nonnegative(),missing:z36.array(z36.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z36.object({data:z36.array(EntryDTOSchema),meta:z36.object({deleted:z36.number().int().nonnegative(),missing:z36.array(z36.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z37}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z37.object({index:z37.number().int().nonnegative(),contentType:z37.string(),field:z37.string(),value:z37.string(),against:z37.enum(["stored","batch"]),ownerDocumentId:z37.uuid().optional(),ownerIndex:z37.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z37.object({code:z37.literal("unique_conflict"),message:z37.string(),conflicts:z37.array(UniqueConflictSchema),truncated:z37.boolean().optional()})}});import{z as z38}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=z38.object({kind:z38.literal("unique_conflict"),contentType:z38.string(),field:z38.string(),value:z38.string(),documentCount:z38.number().int().positive(),documentIds:z38.array(z38.uuid()),documentIdsTruncated:z38.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z38.object({code:z38.literal("schema_transition_rejected"),message:z38.string(),issues:z38.array(SchemaTransitionIssueSchema),truncated:z38.boolean().optional()})}});import{z as z39}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=z39.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z39.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z39.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z39.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z39.object({field:CmsFieldNameSchema,direction:z39.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z39.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z39.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z39.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z39.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z39.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z40}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=z40.object({id:z40.string(),name:z40.string()}),AssetDTOSchema=z40.object({id:z40.string(),name:z40.string(),type:AssetTypeSchema,originalFileName:z40.string().nullable(),parentId:z40.string().nullable(),mimeType:z40.string().nullable(),fileSize:z40.number().nullable(),url:z40.string().nullable(),storageKey:z40.string().nullable(),createdAt:z40.string(),updatedAt:z40.string(),altText:z40.string().nullable().optional(),caption:z40.string().nullable().optional(),aiCaption:z40.string().nullable().optional(),aiAltText:z40.string().nullable().optional(),aiTags:z40.array(z40.string()).nullable().optional(),aiPrimaryColor:z40.string().nullable().optional(),aiProcessingStatus:z40.string().nullable().optional(),width:z40.number().nullable().optional(),height:z40.number().nullable().optional(),path:z40.array(AssetPathItemSchema).optional(),hasChildren:z40.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z40.lazy(()=>z40.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z40.array(AssetDTOSchema))}});import{z as z41}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z41.object({key:z41.string(),value:z41.string().optional(),defaultValue:z41.string(),locale:z41.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z42}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=z42.object({id:z42.string(),name:z42.string(),type:z42.enum(["file","folder"]),path:z42.string(),children:z42.lazy(()=>z42.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z42.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z42.object({path:z42.string(),exists:z42.boolean(),type:z42.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z43}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatLiveTurnStateDTOSchema,ChatLiveTurnStateDTO,ChatThreadMessageDTOSchema,ChatAttentionDTOSchema,ChatThreadMessagesPageDTOSchema,ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema,ChatNonStreamingOutcomeDTOSchema,ChatDeletionDTOSchema,ChatDeletionDTO,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,ChatDeletionResponseSchema,ChatClearErrorDTOSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_create_dto();init_response();init_project_dto();ChatMessageListDTOSchema=z43.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z43.object({items:z43.array(ProjectMessagePublicDTOSchema),nextCursor:z43.string().nullable()}),ChatLiveTurnDTOSchema=z43.object({invocationId:z43.string(),step:z43.enum(["preparing","working","compacting","merging"]),startedAt:z43.string()}),ChatLiveTurnStateDTOSchema=z43.object({threadId:z43.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z43.object({id:z43.string(),role:z43.enum(["user","assistant"]),parts:z43.array(z43.unknown()),metadata:z43.record(z43.string(),z43.unknown()).nullable(),versionId:z43.string().nullable().optional(),createdAt:z43.date().transform(value=>value.toISOString()),providerMessageId:z43.string().nullable().optional(),invocationId:z43.string().nullable().optional(),invocationStatus:z43.string().nullable().optional(),invocationTerminalReason:z43.string().nullable().optional()}),ChatAttentionDTOSchema=z43.object({type:z43.literal("merge_conflict"),merge:z43.object({mergeId:z43.string().uuid(),projectId:z43.string(),fromEnv:z43.string(),toEnv:z43.string()}),publishAfterMerge:z43.boolean()}),ChatThreadMessagesPageDTOSchema=z43.object({threadId:z43.string().nullable(),title:z43.string().nullable(),messages:z43.array(ChatThreadMessageDTOSchema),nextCursor:z43.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z43.object({kind:z43.literal("replay"),threadId:z43.string(),userMessageId:z43.string()}),ChatQueuedOutcomeDTOSchema=z43.object({kind:z43.literal("queued"),threadId:z43.string(),userMessageId:z43.string(),blockingRootId:z43.string()}),ChatBusyOutcomeDTOSchema=z43.object({kind:z43.literal("busy"),threadId:z43.string(),userMessageId:z43.string(),blockingRootId:z43.string().optional()}),ChatRefusedOutcomeDTOSchema=z43.object({kind:z43.literal("refused"),threadId:z43.string(),userMessageId:z43.string(),refusedInvocationId:z43.string(),terminalReason:z43.string()}),ChatNonStreamingOutcomeDTOSchema=z43.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z43.object({success:z43.boolean(),deletedCount:z43.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z43.object({code:z43.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z43.string()})}});import{z as z44}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=z44.object({url:z44.string().url(),key:z44.string(),size:z44.number(),contentType:z44.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z45}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=z45.object({canAccess:z45.boolean(),permissions:z45.record(z45.string(),z45.boolean()),role:z45.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z46}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:z46.string().trim().default(""),sort:z46.enum(["recent","name","relevance"]).default("recent"),category:z46.string().optional()})}});import{z as z47}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=z47.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z47.enum(["fimo","external"]),PaymentStatusSchema=z47.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z47.object({id:z47.string().uuid(),domain:z47.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z47.boolean(),price:z47.number().int().nullable(),renewalPrice:z47.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z47.string().nullable(),failureReason:z47.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z47.object({domain:z47.string(),available:z47.boolean(),premium:z47.boolean(),price:z47.number().nullable(),renewalPrice:z47.number().nullable(),purchaseType:z47.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z47.object({domain:z47.string(),price:z47.number().nullable(),renewalPrice:z47.number().nullable(),premium:z47.boolean(),allowedYears:z47.array(z47.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z47.object({firstName:z47.string().max(100),lastName:z47.string().max(100),companyName:z47.string().max(100).optional(),address1:z47.string().max(255),address2:z47.string().max(255).optional(),city:z47.string().max(100),state:z47.string().max(100),zip:z47.string().max(20),country:z47.string().max(2),phone:z47.string().max(30),email:z47.union([z47.string().email().max(255),z47.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z47.object({firstName:z47.string().min(1).max(100),lastName:z47.string().min(1).max(100),companyName:z47.string().max(100).optional(),address1:z47.string().min(1).max(255),address2:z47.string().max(255).optional(),city:z47.string().min(1).max(100),state:z47.string().min(1).max(100),zip:z47.string().min(1).max(20),country:z47.string().min(1).max(2),phone:z47.string().min(1).max(30),email:z47.string().email().max(255)}),SearchDomainsRequestSchema=z47.object({keyword:z47.string().min(1).max(100),tldFilter:z47.array(z47.string()).optional()}),CheckAvailabilityRequestSchema=z47.object({domains:z47.array(z47.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=z47.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z47.object({domain:DomainNameSchema,years:z47.number().int().min(1).max(10).optional().default(3),autoRenew:z47.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z47.object({autoRenew:z47.boolean().optional()}),RenewDomainRequestSchema=z47.object({years:z47.number().int().min(1).max(10).optional().default(1),autoRenew:z47.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z47.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z47.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z47.object({verified:z47.boolean(),email:z47.string().nullable(),verifyBy:z47.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z48}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=z48.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=z48.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=z48.object({txtName:z48.string().nullable().optional(),txtValue:z48.string().nullable().optional(),httpUrl:z48.string().nullable().optional(),httpBody:z48.string().nullable().optional(),cname:z48.string().nullable().optional(),cnameTarget:z48.string().nullable().optional()}),SSLValidationErrorSchema=z48.object({message:z48.string()}),OwnershipVerificationSchema=z48.object({type:z48.string(),name:z48.string(),value:z48.string()}),ProjectDomainSSLDTOSchema=z48.object({status:z48.string(),method:z48.string().nullable(),type:z48.string().nullable(),validationRecords:z48.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z48.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z48.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z48.enum(["subdomain","apex"]),RedirectConfigSchema=z48.object({type:z48.literal("apex_to_www"),linkedDomainId:z48.string()}).nullable().optional(),ProjectDomainDTOSchema=z48.object({id:z48.string(),hostname:z48.string(),status:z48.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z48.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z48.string(),scdCnameTarget:z48.string().optional(),apexTargets:z48.array(z48.string()),dnsAutoConfigured:z48.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z48.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z48.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z48.object({hostname:z48.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:z48.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z48.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z48.object({available:z48.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z48.object({success:z48.boolean(),hostname:z48.string()}))}});import{z as z49}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=z49.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z49.object({available:z49.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z49.object({slug:z49.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z49.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z49.object({subdomain:z49.string(),subdomainUpdatedAt:z49.coerce.date()})),SubdomainSuggestionsQuerySchema=z49.object({base:z49.string().max(100).optional(),max:z49.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z49.object({suggestions:z49.array(z49.string())}))}});import{z as z50}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=z50.object({translated:z50.number().int().nonnegative(),total:z50.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z50.object({locale:z50.string(),isDefault:z50.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z50.object({defaultLocale:z50.string(),routing:z50.object({strategy:z50.literal("path-prefix"),prefixDefaultLocale:z50.boolean()}),locales:z50.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z50.object({locale:z50.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z50.object({locale:z50.string().min(1).max(40)}),ProjectLocaleMutationSchema=z50.object({locale:z50.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z50.object({locale:z50.string(),entriesDeleted:z50.number().int().nonnegative(),labelsDeleted:z50.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z51}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=z51.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z51.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=z51.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z51.number(),credits:z51.number().optional(),billingMode:z51.enum(["fimo-credits","provider-account"]).optional(),confidence:z51.enum(["exact","estimated","metered"]),basis:z51.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z52}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=z52.object({options:z52.record(z52.string(),z52.unknown()),name:z52.string().optional(),parentId:z52.string().nullable().optional(),altText:z52.string().optional(),caption:z52.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z52.string().min(1).optional(),model:z52.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=z52.object({jobId:z52.string(),status:z52.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z52.string().nullable().optional(),credits:z52.number().optional(),costUsd:z52.number().optional(),billingMode:z52.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z52.object({error:z52.string(),code:z52.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:z52.array(GenerationTaskIdSchema).optional(),availableModels:z52.array(z52.string()).optional(),issues:z52.array(z52.unknown()).optional()})}});import{z as z53}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=z53.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z53.object({name:z53.string(),key:z53.string(),description:z53.string(),type:FlagTypeSchema,required:z53.boolean(),defaultValue:z53.unknown().optional(),enumValues:z53.array(z53.string()).optional(),isArray:z53.boolean()}),AssetModelPriceSchema=z53.object({unitPrice:z53.number(),unit:z53.string(),confidence:z53.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z53.object({id:z53.string(),shortName:z53.string(),provider:z53.string(),source:z53.string(),modality:z53.enum(["image","video","audio"]),tags:z53.array(z53.string()),displayName:z53.string(),description:z53.string(),flags:z53.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z53.object({model:z53.string(),costUsd:z53.number(),credits:z53.number(),billingMode:z53.enum(["fimo-credits","provider-account"]),confidence:z53.enum(["exact","estimated","metered"]),basis:z53.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z54}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=z54.object({tourId:z54.string(),version:z54.string(),status:z54.string(),completedAt:z54.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z54.array(UserTourDTOSchema))}});import{z as z55}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=z55.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z55.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z55.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z55.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z55.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z55.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z55.enum(["user","agent","system"]),SupportReportTagSchema=z55.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z55.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z55.object({organization:z55.object({id:z55.string().trim().min(1).max(255),name:z55.string().trim().max(240).optional()}),project:z55.object({id:z55.uuid(),name:z55.string().trim().max(240).optional(),createdAt:z55.coerce.date().optional()}).optional(),environment:z55.string().trim().max(255).optional(),clientVersion:z55.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z55.object({message:z55.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z55.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z55.string().trim().max(200).optional(),limit:z55.coerce.number().int().min(1).max(100).default(50),offset:z55.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z55.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z55.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z55.uuid().nullable().optional(),note:z55.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=z55.object({message:z55.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z55.object({kind:SupportReportLinkKindSchema,label:z55.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z55.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z55.object({kind:SupportReportActorKindSchema,id:z55.string().nullable(),name:z55.string().nullable()}),SupportReportLinkDTOSchema=z55.object({id:z55.uuid(),kind:SupportReportLinkKindSchema,label:z55.string(),url:SupportReportHttpUrlSchema,externalId:z55.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z55.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z55.object({id:z55.uuid(),kind:SupportReportEventKindSchema,body:z55.string().nullable(),metadata:z55.record(z55.string(),z55.unknown()),actor:SupportReportActorDTOSchema,createdAt:z55.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z55.object({id:z55.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z55.array(z55.string()),source:SupportReportSourceSchema,message:z55.string(),reporter:z55.object({id:z55.string().nullable(),name:z55.string().nullable(),email:z55.string().nullable()}),organization:z55.object({id:z55.string().nullable(),name:z55.string()}),project:z55.object({id:z55.uuid().nullable(),name:z55.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z55.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z55.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z55.string().nullable(),deliveredAt:z55.coerce.date().nullable()}).nullable(),duplicateOfReportId:z55.uuid().nullable(),resolvedAt:z55.coerce.date().nullable(),createdAt:z55.coerce.date(),updatedAt:z55.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z55.string().nullable(),clientVersion:z55.string().nullable(),links:z55.array(SupportReportLinkDTOSchema),events:z55.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z55.object({reports:z55.array(SupportReportSummaryDTOSchema),total:z55.number().int().nonnegative(),statusCounts:z55.object({new:z55.number().int().nonnegative(),in_progress:z55.number().int().nonnegative(),waiting:z55.number().int().nonnegative(),resolved:z55.number().int().nonnegative(),duplicate:z55.number().int().nonnegative(),irrelevant:z55.number().int().nonnegative(),ignored:z55.number().int().nonnegative()}),limit:z55.number().int().positive(),offset:z55.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z55.object({id:z55.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z55.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z56}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=z56.iso.datetime({offset:!0}).pipe(z56.coerce.date()),OpsRecentChatInputSchema=z56.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z56.string().trim().min(1).max(255).optional(),limit:z56.coerce.number().int().min(1).max(200).default(100),cursor:z56.string().trim().min(1).max(2e3).optional(),slim:z56.boolean().default(!0),reason:z56.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=z56.object({id:z56.string(),threadId:z56.string(),providerMessageId:z56.string().nullable(),invocationId:z56.string().nullable(),env:z56.string().nullable(),role:z56.string(),parts:z56.array(z56.record(z56.string(),z56.unknown())),metadata:z56.object({status:z56.string().optional(),traceUrl:z56.string().optional(),externalFileChanges:z56.array(z56.unknown()).optional()}),stats:z56.object({toolCount:z56.number().int().nonnegative(),failedToolCount:z56.number().int().nonnegative()}),createdAt:z56.iso.datetime({offset:!0}),project:z56.object({id:z56.string(),name:z56.string(),displayName:z56.string().nullable(),organizationId:z56.string().nullable()})}),OpsRecentChatResponseSchema=z56.object({target:z56.object({backendProfile:OpsBackendProfileSchema,projectEnv:z56.string().nullable()}),window:z56.object({from:z56.iso.datetime({offset:!0}),to:z56.iso.datetime({offset:!0})}),messages:z56.object({items:z56.array(OpsRecentChatMessageSchema),nextCursor:z56.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z57}from"zod";var OpsSentryIssueResolutionResponseSchema,OpsSentryIssueResolutionResponseDTO,OpsSentryIssueResolutionErrorResponseSchema,OpsSentryIssueResolutionErrorResponseDTO,init_ops_sentry_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-sentry.dto.js"(){"use strict";init_ops();init_create_dto();OpsSentryIssueResolutionResponseSchema=z57.object({backendProfile:OpsBackendProfileSchema,provider:z57.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z57.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z57.object({backendProfile:OpsBackendProfileSchema,provider:z57.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z57.literal(!1),reason:z57.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});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({versionId:z58.uuid(),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 PREVIEW_FEATURE_REGISTRY,previewFeatureKeys,PreviewFeatureDTOSchema,PreviewFeatureDTO,PreviewFeatureResponseSchema,PreviewFeatureListResponseSchema,init_preview_feature_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/preview-feature.dto.js"(){"use strict";init_create_dto();init_response();PREVIEW_FEATURE_REGISTRY={"fimo-2":{key:"fimo-2",defaultEnabled:!1}},previewFeatureKeys=Object.keys(PREVIEW_FEATURE_REGISTRY),PreviewFeatureDTOSchema=z59.object({key:z59.enum(previewFeatureKeys),enabled:z59.boolean(),dismissed:z59.boolean().default(!1),interacted:z59.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema),PreviewFeatureResponseSchema=createResponseSchema(PreviewFeatureDTOSchema),PreviewFeatureListResponseSchema=createResponseSchema(z59.array(PreviewFeatureDTOSchema))}});import{z as z60}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=z60.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z60.object({total:z60.number(),base:z60.number(),purchases:z60.number(),awards:z60.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z60.object({id:z60.string(),name:z60.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z60.object({type:z60.string(),brand:z60.string().nullable(),last4:z60.string().nullable(),expirationDate:z60.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z60.object({currency:z60.string(),nextPaymentAmount:z60.number().nullable(),nextPaymentAt:z60.string().nullable(),billingInterval:z60.string().nullable(),totalAmount:z60.number().nullable(),discountAmount:z60.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z60.object({id:z60.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z60.string().nullable(),currentPeriodEndsAt:z60.string().nullable(),renewsAt:z60.string().nullable(),cancelAt:z60.string().nullable(),renewAutomatically:z60.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z60.object({type:z60.enum(["low_balance","critical_balance","approaching_limit"]),message:z60.string(),estimatedPromptsRemaining:z60.number().nullable(),avgCostPerPrompt:z60.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z60.object({monthlyCredits:z60.number().nullable(),usedThisPeriod:z60.number(),remainingThisPeriod:z60.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z60.object({organizationId:z60.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z60.string().nullable(),tenureDays:z60.number().int().nonnegative(),capturedAt:z60.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z60.object({hasSubscription:z60.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z60.number().nullable(),alerts:z60.array(CreditAlertDTOSchema),portalUrl:z60.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z60.object({creditCount:z60.number().int().positive(),expiresAt:z60.string().datetime().nullable().optional(),message:z60.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z60.literal("free"),amountCents:z60.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z60.literal("purchase"),amountCents:z60.number().int().positive()}),CreditTopupRequestDTOSchema=z60.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z60.object({success:z60.boolean(),transactionId:z60.string().nullable(),newBalance:z60.number(),creditCount:z60.number(),type:z60.enum(["free","purchase"]),invoiceId:z60.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z61}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=z61.object({totalCredits:z61.number(),totalCostUsd:z61.number(),totalMessages:z61.number(),avgCostPerMessage:z61.number(),periodStart:z61.string().nullable(),periodEnd:z61.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z61.object({projectId:z61.string(),projectName:z61.string(),projectDisplayName:z61.string().nullable(),credits:z61.number(),costUsd:z61.number(),messages:z61.number(),percentage:z61.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z61.object({userId:z61.string(),userName:z61.string().nullable(),userEmail:z61.string().email().nullable(),credits:z61.number(),costUsd:z61.number(),messages:z61.number(),percentage:z61.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z61.object({date:z61.string(),credits:z61.number(),costUsd:z61.number(),messages:z61.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z61.object({userId:z61.string(),userName:z61.string().nullable(),userEmail:z61.string().email().nullable(),credits:z61.number(),costUsd:z61.number(),messages:z61.number(),percentage:z61.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z61.object({projectId:z61.string(),projectName:z61.string(),projectDisplayName:z61.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z61.array(UsageByUserForProjectDTOSchema),timeline:z61.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z61.object({summary:UsageSummaryDTOSchema,byProject:z61.array(UsageByProjectDTOSchema),byUser:z61.array(UsageByUserDTOSchema),timeline:z61.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z62}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=z62.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z62.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z62.object({startDate:z62.string().optional(),endDate:z62.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z62.coerce.number().int().positive().default(1),limit:z62.coerce.number().int().positive().max(100).default(20),sortBy:z62.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z62.string().optional(),activeOnly:z62.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z62.object({totalCredits:z62.number(),totalCostUsd:z62.number(),totalMessages:z62.number(),avgCostPerMessage:z62.number(),avgCreditsPerMessage:z62.number(),periodStart:z62.string(),periodEnd:z62.string(),creditsChange:z62.number().nullable(),costChange:z62.number().nullable(),messagesChange:z62.number().nullable(),unattributedCredits:z62.number(),unattributedCostUsd:z62.number(),unattributedMessages:z62.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z62.object({date:z62.string(),credits:z62.number(),costUsd:z62.number(),messages:z62.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z62.object({organizationId:z62.string(),organizationName:z62.string(),credits:z62.number(),costUsd:z62.number(),messages:z62.number(),percentage:z62.number(),userCount:z62.number(),projectCount:z62.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z62.object({userId:z62.string(),userName:z62.string().nullable(),userEmail:z62.string().nullable(),userImage:z62.string().nullable(),organizationId:z62.string().nullable(),organizationName:z62.string().nullable(),credits:z62.number(),costUsd:z62.number(),messages:z62.number(),percentage:z62.number(),projectCount:z62.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z62.object({projectId:z62.string(),projectName:z62.string(),projectDisplayName:z62.string().nullable(),organizationId:z62.string(),organizationName:z62.string(),credits:z62.number(),costUsd:z62.number(),messages:z62.number(),percentage:z62.number(),userCount:z62.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z62.object({id:z62.string(),name:z62.string(),value:z62.number(),percentage:z62.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z62.object({day:z62.number(),hour:z62.number(),value:z62.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z62.object({summary:UsageOverviewSummaryDTOSchema,timeline:z62.array(UsageTimelinePointDTOSchema),topOrganizations:z62.array(OrganizationUsageRowDTOSchema),topUsers:z62.array(UserUsageRowDTOSchema),topProjects:z62.array(ProjectUsageRowDTOSchema),creditDistribution:z62.array(UsageDistributionItemDTOSchema),userDistribution:z62.array(UsageDistributionItemDTOSchema),heatmap:z62.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z62.object({page:z62.number(),limit:z62.number(),totalItems:z62.number(),totalPages:z62.number(),hasMore:z62.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z62.object({organizations:z62.array(OrganizationUsageRowDTOSchema),top:z62.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z62.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z62.object({users:z62.array(ExtendedUserUsageRowDTOSchema),top:z62.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z62.string(),ownerName:z62.string().nullable(),ownerEmail:z62.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z62.object({projects:z62.array(ExtendedProjectUsageRowDTOSchema),top:z62.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z62.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z62.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z62.object({credits:z62.number(),costUsd:z62.number(),messages:z62.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z62.object({id:z62.string(),name:z62.string(),createdAt:z62.string(),memberCount:z62.number(),projectCount:z62.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z62.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z62.object({id:z62.string(),name:z62.string().nullable(),email:z62.string(),image:z62.string().nullable(),createdAt:z62.string(),organizationCount:z62.number(),projectCount:z62.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z62.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z62.object({id:z62.string(),name:z62.string(),displayName:z62.string().nullable(),createdAt:z62.string(),organizationId:z62.string(),organizationName:z62.string(),ownerId:z62.string(),ownerName:z62.string().nullable(),ownerEmail:z62.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z62.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z63}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=z63.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z63.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z63.object({command:z63.string().min(1).max(1e4),cwd:z63.string().optional(),projectEnv:EnvSchema.optional(),env:z63.record(z63.string(),z63.string()).optional(),name:z63.string().optional(),waitForCompletion:z63.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z63.object({identifier:z63.string(),status:SandboxProcessStatusSchema,command:z63.string().optional(),startedAt:z63.string().optional(),exitCode:z63.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z63.object({processes:z63.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z63.object({processId:z63.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z63.object({success:z63.boolean(),message:z63.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z64}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_chat_block();init_fimo_config();init_project_dto();init_project_env_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_list_item_dto();init_agent_run_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_schedule_notifications_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_ops_sentry_dto();init_webhook_dto();init_preview_feature_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto()}});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 buildSkipsVersionCheck(cliRoot=CLI_ROOT,readFile6=defaultReadFile){try{return JSON.parse(readFile6(path2.join(cliRoot,"release.json"))).skipVersionCheck===!0}catch{return!1}}function defaultReadFile(file){return fs3.readFileSync(file,"utf8")}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||buildSkipsVersionCheck(cliRoot))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(buildSkipsVersionCheck,"buildSkipsVersionCheck");__name(defaultReadFile,"defaultReadFile");__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:path49,message}=issue;return`${Array.isArray(path49)&&path49.length>0?`${path49.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}function recoverTenantApiBaseUrl(tenantApiUrl,projectId,env){try{let normalized=tenantApiUrl.replace(/\/$/,""),url=new URL(normalized),prefix=`${projectId}-${envResourceKey(env)}.`;if(!url.hostname.startsWith(prefix))return;url.hostname=url.hostname.slice(prefix.length);let base=url.toString().replace(/\/$/,"");return buildTenantApiUrl(projectId,env,base)===normalized?base:void 0}catch{return}}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_esm();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,path49,status,detail,code2,body){super(`API ${method} ${path49} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path49,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");__name(recoverTenantApiBaseUrl,"recoverTenantApiBaseUrl");FimoApiClient=class _FimoApiClient{constructor(cfg=loadConfig()){this.cfg=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(path49,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}${path49}`,{...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",path49,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async fetchRaw(path49,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);return 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),fimoFetch(`${this.cfg.apiUrl}${path49}`,{...init,headers})}async rawRequest(path49,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}${path49}`,{...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"} ${path49} 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/${encodeEnvPathSegment(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/${encodeEnvPathSegment(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 listProjectVersions(projectId,options){let params=new URLSearchParams({limit:String(options.limit)});return options.cursor&¶ms.set("cursor",options.cursor),(await this.request(`${this.projectEnvManagementPath(projectId,"/versions")}?${params.toString()}`)).data}async getProjectHistorySummary(projectId){return(await this.request(this.projectEnvManagementPath(projectId,"/versions/summary"))).data}async getProjectVersion(projectId,versionId){return(await this.request(this.projectEnvManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}`))).data}async createProjectVersion(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/versions"),{method:"POST",body:JSON.stringify(input)})).data}async restoreProjectVersion(projectId,versionId){return(await this.request(this.projectEnvManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}/restore`),{method:"POST"})).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 getSchedulesOverview(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules/overview`)).data}async getSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`)).data}async updateSchedule(projectId,scheduleId,request){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"PATCH",body:JSON.stringify(request)})).data}async setScheduleEnabled(projectId,scheduleId,enabled){let action=enabled?"resume":"pause";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/${action}`,{method:"POST"})).data}async runSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/run`,{method:"POST",body:JSON.stringify({trigger:"cli"})})).data}async listScheduleRuns(projectId,scheduleId,query={}){let params=new URLSearchParams;query.limit!==void 0&¶ms.set("limit",String(query.limit)),query.cursor&¶ms.set("cursor",query.cursor),query.status&¶ms.set("status",query.status);let suffix=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/runs${suffix}`)).data}async getScheduleRun(projectId,runId){return(await this.request(`/api/management/projects/${projectId}/schedules/runs/${encodeURIComponent(runId)}`)).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,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"DELETE"})).data}async listEnvs(projectId,opts={}){let params=new URLSearchParams;opts.includeDeleted&¶ms.set("includeDeleted","true"),opts.includeAgentEnvs&¶ms.set("includeAgentEnvs","true");let qs=params.size>0?`?${params.toString()}`:"";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,path49,opts={}){let qs=lazyFetchQs(opts.against,{path:path49});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),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async getSchemaTypeDiff(projectId,env,typeName,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async getAssetDiff(projectId,env,assetId,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async getTranslationRowDiff(projectId,env,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async getFormSchemaDiff(projectId,env,formName,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).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 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){let remote=(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-remote`,{},{allow403:!0})).data;if(!remote.tenantApiBaseUrl){let recovered=recoverTenantApiBaseUrl(remote.tenantApiUrl,projectId,env);if(recovered)return{...remote,tenantApiBaseUrl:recovered}}return remote}async getProjectLocaleStats(projectId){return(await this.request(this.projectEnvManagementPath(projectId,"/locales/stats"))).data}async addProjectLocale(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/locales"),{method:"POST",body:JSON.stringify(input)})).data}async setProjectDefaultLocale(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/locales/default"),{method:"PUT",body:JSON.stringify(input)})).data}async removeProjectLocale(projectId,locale){return(await this.request(this.projectEnvManagementPath(projectId,`/locales/${encodeURIComponent(locale)}`),{method:"DELETE"})).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/${encodeEnvPathSegment(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(process9.env.NO_COLOR||process9.env.FORCE_COLOR==="0"||process9.env.FORCE_COLOR==="false")return!1;if(process9.env.FORCE_COLOR||process9.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{z}from"zod";function filterUnknownProperties(data2,schema){if(data2==null)return data2;if(schema instanceof z.ZodOptional||schema instanceof z.ZodNullable||schema instanceof z.ZodDefault)return filterUnknownProperties(data2,schema.unwrap());if(schema instanceof z.ZodArray){if(!Array.isArray(data2))return data2;let itemSchema=schema.unwrap();return data2.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z.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 z.ZodLiteral?discriminatorField.def.values.includes(discriminatorValue):!1});return matchingSchema?filterUnknownProperties(data2,matchingSchema):data2}if(schema instanceof z.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 z.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 z.ZodObject)return createObjectDTO(schema);if(schema instanceof z.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 z2}from"zod";function createCursorPageDataSchema(dataSchema){return z2.object({items:z2.array(dataSchema),nextCursor:z2.string().nullable()})}function createCursorPaginatedResponseSchema(dataSchema){return z2.object({data:createCursorPageDataSchema(dataSchema)})}var createResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema=__name(dataSchema=>z2.object({data:dataSchema}),"createResponseSchema");__name(createCursorPageDataSchema,"createCursorPageDataSchema");__name(createCursorPaginatedResponseSchema,"createCursorPaginatedResponseSchema")}});import{z as z3}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z3.object({page:z3.coerce.number().int().positive().default(1),limit:z3.coerce.number().int().positive().max(100).default(20)})}});import{z as z4}from"zod";var CommonSchemas,BaseEntitySchema,ProjectRoleKeySchema,ProjectRoleKeyWithSystemSchema,ProjectPrincipalTypeSchema,ProjectStatusSchema,ProjectInviteStatusSchema,PublicationStatusSchema,OrganizationRoleSchema,AssetTypeSchema,TemplateCodeSchema,FieldTypeSchema,CONTENT_INTERNAL_FIELD_NAMES,contentInternalFieldNames,RESERVED_CONTENT_FIELD_NAMES,contentReviewHiddenFieldNames,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:z4.coerce.date(),positiveInt:z4.number().int().positive(),nonNegativeInt:z4.number().int().nonnegative()},BaseEntitySchema=z4.object({id:z4.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z4.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z4.enum(["full","edit","comment","view","agent","schedule"]),ProjectPrincipalTypeSchema=z4.enum(["user","org","orgRole","public","email"]),ProjectStatusSchema=z4.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z4.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z4.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z4.enum(["owner","admin","member"]),AssetTypeSchema=z4.enum(["file","folder"]),TemplateCodeSchema=z4.enum(["Free","Premium"]),FieldTypeSchema=z4.enum(["string","text","richtext","media","number","boolean","date","json","reference","blocks"]),CONTENT_INTERNAL_FIELD_NAMES=["id","entryId","documentId","locale","__fimo"],contentInternalFieldNames=new Set(CONTENT_INTERNAL_FIELD_NAMES),RESERVED_CONTENT_FIELD_NAMES=[...CONTENT_INTERNAL_FIELD_NAMES,"slug","createdAt","updatedAt"],contentReviewHiddenFieldNames=new Set(RESERVED_CONTENT_FIELD_NAMES),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_AUDIO_MIME_TYPES,ATTACHMENT_VIDEO_MIME_TYPES,ATTACHMENT_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,EXTENSION_MIME_TYPES,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image",maxSizeBytes:20971520},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image",maxSizeBytes:20971520},{mime:"image/webp",extensions:[".webp"],category:"image",maxSizeBytes:20971520},{mime:"image/avif",extensions:[".avif"],category:"image",maxSizeBytes:20971520},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:5242880},{mime:"application/msword",extensions:[".doc"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",extensions:[".docx"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.ms-excel",extensions:[".xls"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",extensions:[".xlsx"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.ms-powerpoint",extensions:[".ppt"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation",extensions:[".pptx"],category:"document",maxSizeBytes:5242880},{mime:"application/epub+zip",extensions:[".epub"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.oasis.opendocument.text",extensions:[".odt"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.oasis.opendocument.spreadsheet",extensions:[".ods"],category:"document",maxSizeBytes:5242880},{mime:"application/vnd.oasis.opendocument.presentation",extensions:[".odp"],category:"document",maxSizeBytes:5242880},{mime:"text/rtf",extensions:[],category:"document",maxSizeBytes:5242880},{mime:"application/rtf",extensions:[".rtf"],category:"document",maxSizeBytes:5242880},{mime:"text/html",extensions:[".html",".htm"],category:"document",maxSizeBytes:5242880},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:5242880},{mime:"text/markdown",extensions:[".md",".markdown"],category:"document",maxSizeBytes:5242880},{mime:"application/json",extensions:[".json"],category:"document",maxSizeBytes:5242880},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:5242880},{mime:"audio/mpeg",extensions:[".mp3"],category:"audio",maxSizeBytes:10485760},{mime:"audio/wav",extensions:[".wav"],category:"audio",maxSizeBytes:10485760},{mime:"audio/aiff",extensions:[".aiff",".aif"],category:"audio",maxSizeBytes:10485760},{mime:"audio/aac",extensions:[".aac"],category:"audio",maxSizeBytes:10485760},{mime:"audio/ogg",extensions:[".ogg"],category:"audio",maxSizeBytes:10485760},{mime:"audio/flac",extensions:[".flac"],category:"audio",maxSizeBytes:10485760},{mime:"video/mp4",extensions:[".mp4"],category:"video",maxSizeBytes:20971520},{mime:"video/mpeg",extensions:[".mpeg",".mpg"],category:"video",maxSizeBytes:20971520},{mime:"video/mpg",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/quicktime",extensions:[".mov"],category:"video",maxSizeBytes:20971520},{mime:"video/mov",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/avi",extensions:[".avi"],category:"video",maxSizeBytes:20971520},{mime:"video/vnd.avi",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/x-msvideo",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/x-flv",extensions:[".flv"],category:"video",maxSizeBytes:20971520},{mime:"video/webm",extensions:[".webm"],category:"video",maxSizeBytes:20971520},{mime:"video/wmv",extensions:[".wmv"],category:"video",maxSizeBytes:20971520},{mime:"video/x-ms-wmv",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/x-ms-asf",extensions:[],category:"video",maxSizeBytes:20971520},{mime:"video/3gpp",extensions:[".3gp"],category:"video",maxSizeBytes:20971520}],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_AUDIO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="audio").map(t2=>t2.mime),ATTACHMENT_VIDEO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="video").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])),EXTENSION_MIME_TYPES=Object.fromEntries(ATTACHMENT_TYPES.flatMap(t2=>t2.extensions.map(extension=>[extension,t2.mime])))}});import{z as z5}from"zod";function isValidEnv(env){return typeof env!="string"||env.length===0||env.length>MAX_ENV_LENGTH||env.startsWith("-")||env.startsWith(".")||env.includes("//")||env.includes("--")||env.split("/").some(segment=>segment==="..")?!1:ENV_ID_REGEX.test(env)}function encodeEnvPathSegment(env){return env.replace(/\//g,"--")}function isProductionEnv(env){return env===PRODUCTION_ENV}function fnv1a8(s){let h=2166136261;for(let i=0;i<s.length;i++)h^=s.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}function envResourceKey(env){let base=env.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a8(env);return base?`${base}-${hash}`:hash}function buildTenantApiUrl(projectId,env,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${envResourceKey(env)}.${url.hostname}`,url.toString().replace(/\/$/,"")}var FIMO_CONTENT_API_ENV_KEYS,FIMO_PREVIEW_SCRIPT_ENV_KEYS,FIMO_MANAGED_PROJECT_ENV_KEYS,ENV_ID_REGEX,MAX_ENV_LENGTH,EnvSchema,DEFAULT_ENV,PRODUCTION_ENV,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";FIMO_CONTENT_API_ENV_KEYS=["FIMO_CONTENT_API_URL","VITE_API_URL","NEXT_PUBLIC_FIMO_API_URL","NUXT_PUBLIC_FIMO_API_URL","PUBLIC_FIMO_API_URL"],FIMO_PREVIEW_SCRIPT_ENV_KEYS=["VITE_PREVIEW_SCRIPT_URL","VITE_FIMO_PREVIEW_SCRIPT_URL","NEXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","NUXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","PUBLIC_FIMO_PREVIEW_SCRIPT_URL","FIMO_PREVIEW_SCRIPT_URL"],FIMO_MANAGED_PROJECT_ENV_KEYS=["FIMO_API_URL","FIMO_API_TOKEN","FIMO_PROJECT_ID","FIMO_ENV","NEXT_PUBLIC_FIMO_ENV","FIMO_AGENT_SESSION","FIMO_DATA_SOURCES",...FIMO_CONTENT_API_ENV_KEYS,...FIMO_PREVIEW_SCRIPT_ENV_KEYS,"VITE_ENABLE_ANALYTICS","VITE_FIMO_BRANCH","VITE_FIMO_IMAGE_HOSTS"],ENV_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_ENV_LENGTH=255;__name(isValidEnv,"isValidEnv");__name(encodeEnvPathSegment,"encodeEnvPathSegment");EnvSchema=z5.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");__name(fnv1a8,"fnv1a8");__name(envResourceKey,"envResourceKey");__name(buildTenantApiUrl,"buildTenantApiUrl")}});import{z as z6}from"zod";var PRODUCTION_ENVIRONMENT_KEY,PREVIEW_ENVIRONMENT_KEY,EnvironmentKeySchema,CustomEnvironmentSchema,ResolvedEnvironmentSchema,init_environment=__esm({"../../packages/api-contracts/dist/esm/types/environment.js"(){"use strict";init_env();PRODUCTION_ENVIRONMENT_KEY="production",PREVIEW_ENVIRONMENT_KEY="preview",EnvironmentKeySchema=z6.union([z6.literal(PRODUCTION_ENVIRONMENT_KEY),z6.literal(PREVIEW_ENVIRONMENT_KEY),z6.uuid()]),CustomEnvironmentSchema=z6.object({id:z6.uuid(),projectId:z6.uuid(),name:z6.string().trim().min(1).max(64),branchPatterns:z6.array(z6.string().min(1).max(255)).min(1),description:z6.string().max(255).nullable()}),ResolvedEnvironmentSchema=z6.object({branch:EnvSchema,environment:EnvironmentKeySchema})}});var init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict";init_env()}});import{z as z7}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=z7.preprocess(referenceValuePreprocess,z7.object({documentId:z7.uuid()})),ReferenceInputValueSchema=z7.preprocess(referenceValuePreprocess,z7.union([z7.object({documentId:z7.uuid()}),z7.object({slug:z7.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=z7.preprocess(polymorphicReferenceValuePreprocess,z7.object({contentType:z7.string().min(1),documentId:z7.uuid()})),PolymorphicReferenceInputValueSchema=z7.preprocess(polymorphicReferenceValuePreprocess,z7.union([z7.object({contentType:z7.string().min(1),documentId:z7.uuid()}),z7.object({contentType:z7.string().min(1),slug:z7.string().min(1)})]))}});import{z as z8}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,path49){let conditionPath=[...path49,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,path49)=>{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,path49));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path49,fieldName,variant.uid]);else walk(field.schema.fields,[...path49,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path49,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path49,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=7,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],showIfClauseSchema=z8.union([z8.object({field:z8.string().min(1),equals:z8.union([z8.string(),z8.number(),z8.boolean()])}).strict(),z8.object({field:z8.string().min(1),in:z8.array(z8.union([z8.string(),z8.number(),z8.boolean()])).min(1)}).strict()]),commonFieldShape={label:z8.string().min(1).optional(),description:z8.string().optional(),editable:z8.boolean().optional(),required:z8.boolean().optional(),default:z8.unknown().optional(),showIf:z8.union([showIfClauseSchema,z8.array(showIfClauseSchema).min(1)]).optional(),showIfAny:z8.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=z8.object({...commonFieldShape,type:z8.enum(["string","text","richtext","media","number","boolean","date","json"]),min:z8.number().optional(),max:z8.number().optional(),minLength:z8.number().int().nonnegative().optional(),maxLength:z8.number().int().nonnegative().optional(),regex:z8.string().optional(),multiple:z8.boolean().optional(),allowedMimeTypes:z8.array(z8.string()).optional(),options:z8.array(z8.string().min(1)).min(1).optional(),unique:z8.boolean().optional(),i18n:z8.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=z8.object({...commonFieldShape,type:z8.literal("reference"),target:z8.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z8.array(z8.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z8.boolean().optional(),i18n:z8.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=z8.lazy(()=>contentFieldDefinitionSchema);__name(getConditionDefinition,"getConditionDefinition");__name(getConditionValues,"getConditionValues");__name(collectClauseProblems,"collectClauseProblems");__name(collectConditionProblems,"collectConditionProblems");blockFieldsSchema=z8.record(z8.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=z8.object({uid:z8.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z8.string().min(1),description:z8.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z8.object({fields:blockFieldsSchema}).strict(),blocksSchema=z8.object({oneOf:z8.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=z8.object({...commonFieldShape,type:z8.literal("blocks"),min:z8.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z8.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z8.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=z8.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z9}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","schedule_notification_change","cutover_step","agent_delegate","version_restore","ops_access_change","ops_service_token_change","ops_project_search","ops_project_inspect","ops_project_chat_read","ops_recent_chat_read","ops_sentry_issue_change","ops_sentry_read","ops_logs_read","ops_trace_read","ops_project_snapshot","ops_support_thread_read","ops_support_report_read","ops_support_report_change","ops_billing_read","ops_billing_cache_invalidate","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send","ops_project_operation","ops_project_publish","admin_resource_read","merge_force"],AuditActionSchema=z9.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z9.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z9.enum(AUDIT_ACTOR_KINDS)}});import{z as z10}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,OpsSentryIssueIdSchema,OpsSentryResolveInputSchema,OpsTraceIdSchema,OpsTraceReadInputSchema,OpsBillingCacheInvalidateInputSchema,OPS_PROJECT_OPERATIONS,OpsProjectOperationKindSchema,ExactVersionSchema,OpsProjectOperationPlanInputSchema,OPS_MIGRATIONS,OpsMigrationIdSchema,OPS_MIGRATION_PLAN_STATUSES,OpsMigrationPlanStatusSchema,OPS_MIGRATION_CHANGE_ACTIONS,OpsMigrationChangeActionSchema,OpsMigrationDryRunInputSchema,OpsProjectOperationApplyInputSchema,OpsProjectPublishApplyInputSchema,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z10.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:project:publish","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing: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=z10.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","ops:billing:read","ops:billing:write","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:project:operate","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing: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=z10.object({permissions:z10.array(OpsPermissionSchema).min(1),backendProfiles:z10.array(OpsBackendProfileSchema).min(1),enabled:z10.boolean().default(!0)}),OpsServiceTokenInputSchema=z10.object({name:z10.string().trim().min(1).max(120),permissions:z10.array(OpsPermissionSchema).min(1),backendProfiles:z10.array(OpsBackendProfileSchema).min(1),expiresAt:z10.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=z10.object({importanceReason:z10.string().trim().min(1).max(1e3),ownerUserId:z10.string().trim().min(1).nullable().optional(),framework:z10.string().trim().max(120).nullable().optional(),packageManager:z10.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z10.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z10.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z10.object({projectId:z10.uuid(),title:z10.string().trim().min(1).max(240),userReport:z10.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z10.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z10.string().trim().max(1e4).nullable().optional(),outcome:z10.string().trim().max(1e4).nullable().optional(),evidence:z10.array(z10.record(z10.string(),z10.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=z10.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z10.object({fingerprint:z10.string().trim().min(1).max(240),title:z10.string().trim().min(1).max(240),description:z10.string().trim().min(1).max(1e4),affectedVersions:z10.array(z10.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z10.array(z10.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z10.string().trim().min(1).max(64).nullable().optional(),workaround:z10.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z10.array(z10.string().trim().min(1).max(120)).max(100),detectionQueries:z10.array(z10.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=z10.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z10.object({changeReference:z10.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z10.string().trim().min(1).max(1e4),evidence:z10.array(z10.record(z10.string(),z10.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z10.object({recipientEmail:z10.email().optional(),subject:z10.string().trim().min(1).max(200).default("An update from Fimo"),message:z10.string().trim().min(1).max(5e3),locale:z10.string().trim().min(2).max(20),reason:z10.string().trim().min(1).max(1e3),acknowledgePolicy:z10.literal(!0)}),OpsSentryIssueIdSchema=z10.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsSentryResolveInputSchema=z10.object({reason:z10.string().trim().min(1).max(1e3)}),OpsTraceIdSchema=z10.string().trim().regex(/^[a-fA-F0-9]{32}$/).transform(value=>value.toLowerCase()),OpsTraceReadInputSchema=z10.object({projectId:z10.uuid(),from:z10.coerce.date(),to:z10.coerce.date(),reason:z10.string().trim().min(1).max(1e3)}).refine(input=>input.from<=input.to,{path:["from"],message:"from must be before or equal to to"}).refine(input=>input.to.getTime()-input.from.getTime()<=10080*60*1e3,{path:["from"],message:"trace windows cannot exceed 7 days"}),OpsBillingCacheInvalidateInputSchema=z10.object({reason:z10.string().trim().min(1).max(1e3)}),OPS_PROJECT_OPERATIONS=["runtime.bump","preview.restart","production.publish"],OpsProjectOperationKindSchema=z10.enum(OPS_PROJECT_OPERATIONS),ExactVersionSchema=z10.string().trim().regex(/^\d+\.\d+\.\d+$/,"Expected an exact version such as 0.11.0"),OpsProjectOperationPlanInputSchema=z10.discriminatedUnion("kind",[z10.object({kind:z10.literal("runtime.bump"),targetVersion:ExactVersionSchema}),z10.object({kind:z10.literal("preview.restart")})]),OPS_MIGRATIONS=["project.v3-to-v4"],OpsMigrationIdSchema=z10.enum(OPS_MIGRATIONS),OPS_MIGRATION_PLAN_STATUSES=["applicable","not_applicable","unknown"],OpsMigrationPlanStatusSchema=z10.enum(OPS_MIGRATION_PLAN_STATUSES),OPS_MIGRATION_CHANGE_ACTIONS=["create","rewrite","delete"],OpsMigrationChangeActionSchema=z10.enum(OPS_MIGRATION_CHANGE_ACTIONS),OpsMigrationDryRunInputSchema=z10.object({migrationId:OpsMigrationIdSchema,projectEnv:z10.string().trim().min(1).max(255).default("main"),reason:z10.string().trim().min(1).max(1e3)}),OpsProjectOperationApplyInputSchema=z10.intersection(OpsProjectOperationPlanInputSchema,z10.object({planHash:z10.string().trim().length(64),reason:z10.string().trim().min(1).max(1e3),consentReference:z10.string().trim().min(1).max(200).optional()})),OpsProjectPublishApplyInputSchema=z10.object({planHash:z10.string().trim().length(64),reason:z10.string().trim().min(1).max(1e3),consentReference:z10.string({error:"Publishing on a customer's behalf requires a recorded consent reference"}).trim().min(1).max(200)})}});import{z as z11}from"zod";function getChatFormOptionLabels(body){switch(body.type){case"choices":return body.actions.map(action=>action.label);case"cards":return body.items.map(item=>item.title);case"table":return body.rows.map(row2=>row2.cells[0]??"");case"assets":return body.items.map(item=>item.label??item.alt)}}var BlockSayActionSchema,BlockActionSchema,BlockAppActionSchema,BlockBaseSchema,ChoicesBlockSchema,TableRowTargetSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,ChatDisplayBlockSchema,ChatFormBodySchema,ChatFormStepSchema,FormBlockSchema,ChatBlockSchema,ChatBlockToolInputSchema,ChatFormAnswerItemSchema,ChatFormAnswerMetadataSchema,ChatFormResponseSchema,init_chat_block=__esm({"../../packages/api-contracts/dist/esm/types/chat-block.js"(){"use strict";BlockSayActionSchema=z11.object({kind:z11.literal("say"),label:z11.string().trim().min(1).max(40,"Button labels must be 40 characters or fewer."),description:z11.string().min(1).max(240).optional(),message:z11.string().trim().min(1,"Every say button needs the sentence the user is saying by clicking.").max(2e3),style:z11.enum(["primary","default","ghost"]).optional()}),BlockActionSchema=BlockSayActionSchema,BlockAppActionSchema=z11.object({kind:z11.literal("app"),command:z11.literal("publish")}).strict(),BlockBaseSchema=z11.object({fallback:z11.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z11.string().min(1).max(80).optional()}),ChoicesBlockSchema=BlockBaseSchema.extend({type:z11.literal("choices"),text:z11.string().max(500).optional(),actions:z11.array(BlockActionSchema).min(2,"A choices block needs 2 to 4 buttons.").max(4,"A choices block needs 2 to 4 buttons.")}),TableRowTargetSchema=z11.discriminatedUnion("kind",[z11.object({kind:z11.literal("entry"),collection:z11.string().min(1).max(80),entryId:z11.string().min(1).max(120)}),z11.object({kind:z11.literal("asset"),assetId:z11.string().min(1).max(120)}),z11.object({kind:z11.literal("url"),url:z11.url({protocol:/^https$/}).max(2e3)})]),TableBlockSchema=BlockBaseSchema.extend({type:z11.literal("table"),columns:z11.array(z11.object({label:z11.string().min(1).max(24)})).min(2).max(4),rows:z11.array(z11.object({cells:z11.array(z11.string().max(80)).min(2).max(4),target:TableRowTargetSchema.optional()})).min(1).max(8)}).superRefine((table,ctx)=>{table.rows.forEach((row2,index2)=>{row2.cells.length!==table.columns.length&&ctx.addIssue({code:"custom",path:["rows",index2,"cells"],message:`Every table row needs exactly ${table.columns.length} cells, one for each column.`})})}),CardsBlockSchema=BlockBaseSchema.extend({type:z11.literal("cards"),layout:z11.enum(["rail","stack"]).optional(),items:z11.array(z11.object({title:z11.string().min(1).max(60),subtitle:z11.string().min(1).max(120).optional(),imageUrl:z11.url({protocol:/^https$/}).max(2e3).optional(),action:BlockSayActionSchema.optional()})).min(2).max(6)}),EntryBlockSchema=BlockBaseSchema.extend({type:z11.literal("entry"),label:z11.string().min(1).max(80),collection:z11.string().min(1).max(80),entryId:z11.string().min(1).max(120),path:z11.string().min(1).max(120).optional()}),AssetsBlockSchema=BlockBaseSchema.extend({type:z11.literal("assets"),items:z11.array(z11.object({url:z11.url({protocol:/^https$/}).max(2e3),alt:z11.string().min(1).max(120),label:z11.string().min(1).max(60).optional()})).min(1).max(6)}),CalloutBlockSchema=BlockBaseSchema.extend({type:z11.literal("callout"),title:z11.string().min(1).max(80),text:z11.string().min(1).max(240),action:BlockAppActionSchema}).strict(),StatBlockSchema=BlockBaseSchema.extend({type:z11.literal("stat"),items:z11.array(z11.object({label:z11.string().min(1).max(24),value:z11.string().min(1).max(16),delta:z11.string().min(1).max(12).optional(),tone:z11.enum(["up","down","flat"]).optional()})).min(1).max(4)}),ChartBlockSchema=BlockBaseSchema.extend({type:z11.literal("chart"),unit:z11.string().min(1).max(12).optional(),points:z11.array(z11.object({label:z11.string().min(1).max(12),value:z11.number().finite().min(0).max(1e9)})).min(2).max(12)}),ChatDisplayBlockSchema=z11.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema]),ChatFormBodySchema=z11.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,AssetsBlockSchema]);__name(getChatFormOptionLabels,"getChatFormOptionLabels");ChatFormStepSchema=z11.object({question:z11.string().min(1).max(500),header:z11.string().min(1).max(25),body:ChatFormBodySchema,multiSelect:z11.boolean(),recommended:z11.string().min(1).max(80).optional()}).superRefine((step,ctx)=>{let labels2=getChatFormOptionLabels(step.body);labels2.some(label=>!label.trim())&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a visible label."}),new Set(labels2).size!==labels2.length&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a unique label."}),step.recommended&&!labels2.includes(step.recommended)&&ctx.addIssue({code:"custom",path:["recommended"],message:"The recommended option must match a visible option label."})}),FormBlockSchema=BlockBaseSchema.extend({type:z11.literal("form"),steps:z11.array(ChatFormStepSchema).min(1).max(4)}),ChatBlockSchema=z11.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,FormBlockSchema]),ChatBlockToolInputSchema=z11.object({block:ChatBlockSchema}),ChatFormAnswerItemSchema=z11.object({header:z11.string().min(1).max(25),question:z11.string().min(1).max(500),answer:z11.string().min(1).max(3e3),selectedLabels:z11.array(z11.string().min(1).max(120)).max(8),freeText:z11.string().max(2e3),skipped:z11.boolean()}),ChatFormAnswerMetadataSchema=z11.object({toolCallId:z11.string().max(255).optional(),shortTitle:z11.string().max(80).optional(),questions:z11.array(ChatFormAnswerItemSchema).max(4)}),ChatFormResponseSchema=ChatFormAnswerMetadataSchema.extend({toolCallId:z11.string().min(1).max(255)})}});import{z as z12}from"zod";var FIMO_CONFIG_PATH,LEGACY_FIMO_CONFIG_PATHS,ALL_FIMO_CONFIG_PATHS,FimoFrameworkSchema,FimoRuntimeCommandsSchema,FimoRuntimeConfigSchema,FimoHostingRewriteSchema,FimoHostingConfigSchema,FimoAppConfigSchema,init_fimo_config=__esm({"../../packages/api-contracts/dist/esm/types/fimo-config.js"(){"use strict";FIMO_CONFIG_PATH=".fimo/config.json",LEGACY_FIMO_CONFIG_PATHS=["fimo-config.json","fimo.config.json"],ALL_FIMO_CONFIG_PATHS=[FIMO_CONFIG_PATH,...LEGACY_FIMO_CONFIG_PATHS],FimoFrameworkSchema=z12.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z12.object({dev:z12.string().trim().min(1).optional(),build:z12.string().trim().min(1).optional(),install:z12.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z12.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z12.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingRewriteSchema=z12.object({source:z12.string().min(1),destination:z12.string().min(1)}),FimoHostingConfigSchema=z12.object({rewrites:z12.array(FimoHostingRewriteSchema).optional()}).strict(),FimoAppConfigSchema=z12.object({runtime:FimoRuntimeConfigSchema.optional(),hosting:FimoHostingConfigSchema.optional()}).passthrough().superRefine((config,context)=>{Object.hasOwn(config,"framework")&&context.addIssue({code:"custom",path:["framework"],message:"Use runtime.framework instead of the top-level framework field."})})}});import{z as z13}from"zod";var PROJECT_CHAT_MANUAL_MODEL_IDS,ProjectChatManualModelIdSchema,ProjectDTOSchema,ProjectDTO,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectHistoryUsageDTOSchema,ProjectVersionPageDTOSchema,ProjectVersionPageDTO,ProjectHistorySummaryDTOSchema,ProjectHistorySummaryDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionResponseSchema,ProjectVersionPageResponseSchema,ProjectHistorySummaryResponseSchema,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_chat_block();init_common();init_create_dto();init_response();PROJECT_CHAT_MANUAL_MODEL_IDS=["anthropic/claude-opus-5","anthropic/claude-sonnet-5","anthropic/claude-fable-5","openai/gpt-5.6-luna","openai/gpt-5.6-terra","openai/gpt-5.6-sol","xai/grok-4.6","google/gemini-3.1-pro-preview","google/gemini-3.7-flash","google/gemini-3.6-flash","google/gemini-3.5-flash-lite","zai/glm-5.2","deepseek/deepseek-v4-pro","minimax/minimax-m3","moonshotai/kimi-k3"],ProjectChatManualModelIdSchema=z13.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z13.string(),displayName:z13.string().nullable(),subdomain:z13.string().nullable().optional(),subdomainUpdatedAt:z13.date().nullable().optional(),organizationId:z13.string().nullable(),createdBy:z13.string().nullable(),previewEnabled:z13.boolean().default(!0),enabledChatModels:z13.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z13.string(),thumbnailUrl:z13.string().nullable(),publishedThumbnailUrl:z13.string().nullable(),category:z13.string().nullable(),appUrl:z13.string().nullable(),lastPublishedAt:z13.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z13.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z13.object({id:z13.uuid(),name:z13.string(),displayName:z13.string().nullable(),thumbnailUrl:z13.string().nullable(),category:z13.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z13.object({id:z13.string(),name:z13.string(),avatar:z13.string().nullable(),color:z13.object({bg:z13.string(),text:z13.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z13.object({path:z13.string(),content:z13.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z13.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z13.object({id:z13.string(),messageId:z13.string(),versionId:z13.string().nullable(),role:ProjectChatMessageRole,parts:z13.array(z13.any()),createdAt:z13.coerce.date()}),MessageUserMetadataSchema=z13.object({id:z13.string(),name:z13.string().nullable().optional(),image:z13.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z13.number(),metadata:z13.object({user:MessageUserMetadataSchema,changeManifest:z13.array(z13.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z13.object({versionId:z13.uuid(),commitHash:z13.string(),name:z13.string(),description:z13.string().nullable(),kind:z13.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z13.object({versionCount:z13.number().int().nonnegative(),snapshotBytes:z13.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z13.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z13.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z13.object({content:z13.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z13.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z13.object({success:z13.boolean(),message:z13.string().optional(),warning:z13.string().optional(),durationMs:z13.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z13.object({isPublished:z13.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z13.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublicationMutationDTOSchema=z13.object({success:z13.boolean(),message:z13.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z13.boolean()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z14}from"zod";var ProjectEnvStatusSchema,ProjectEnvKindSchema,ProjectEnvDTOSchema,ProjectEnvDTO,ResolvedBranchEnvironmentDTOSchema,ProjectEnvListItemDTOSchema,ProjectEnvListItemDTO,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_environment();init_create_dto();init_response();ProjectEnvStatusSchema=z14.enum(["provisioning","active","deleted"]),ProjectEnvKindSchema=z14.enum(["user","agent-session"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z14.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,kind:ProjectEnvKindSchema,previewUrl:z14.string().nullable(),parentEnv:EnvSchema.nullable(),createdBy:z14.string().nullable(),deletedAt:z14.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),ResolvedBranchEnvironmentDTOSchema=z14.object({id:z14.union([z14.literal(PREVIEW_ENVIRONMENT_KEY),z14.uuid()]),name:z14.string()}),ProjectEnvListItemDTOSchema=ProjectEnvDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable()}),ProjectEnvListItemDTO=createDTO(ProjectEnvListItemDTOSchema),CreateProjectEnvRequestSchema=z14.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z14.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z14.array(ProjectEnvListItemDTOSchema)),EnvSurfaceDiffSchema=z14.object({surface:z14.enum(["code","schemas","content","translations","assets","forms"]),status:z14.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z14.number().int().nonnegative(),conflictCount:z14.number().int().nonnegative()}),EnvDiffResultSchema=z14.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z14.coerce.date(),surfaces:z14.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z15}from"zod";var ProjectEnvironmentBaseSchema,ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema,ProjectEnvironmentDTOSchema,ProjectEnvironmentDTO,CreateProjectEnvironmentRequestSchema,ProjectEnvironmentsListResponseSchema,ProjectEnvironmentResponseSchema,DeleteProjectEnvironmentResultSchema,DeleteProjectEnvironmentResponseSchema,init_project_environment_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-environment.dto.js"(){"use strict";init_env();init_environment();init_create_dto();init_response();ProjectEnvironmentBaseSchema=z15.object({projectId:z15.uuid(),name:z15.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z15.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z15.literal("production"),sourceBranch:EnvSchema,isPublished:z15.boolean(),url:z15.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z15.literal(PREVIEW_ENVIRONMENT_KEY),kind:z15.literal("preview"),matchedBranchCount:z15.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z15.literal("custom"),matchedBranchCount:z15.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z15.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z15.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema(z15.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z15.object({deletedId:z15.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema(DeleteProjectEnvironmentResultSchema)}});import{z as z16}from"zod";var ProjectSecretsListQuerySchema,ProjectSecretWriteRequestSchema,CreateProjectSecretRequestSchema,DeleteProjectSecretQuerySchema,ProjectSecretMetadataDTOSchema,ProjectSecretMetadataDTO,ProjectSecretsListResponseSchema,ProjectSecretResponseSchema,init_project_secret_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-secret.dto.js"(){"use strict";init_environment();init_create_dto();init_response();ProjectSecretsListQuerySchema=z16.object({kind:z16.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z16.object({kind:z16.enum(["variable","secret"]),value:z16.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z16.string().min(1).max(255)}),DeleteProjectSecretQuerySchema=z16.object({kind:z16.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z16.object({id:z16.uuid(),projectId:z16.uuid(),key:z16.string(),kind:z16.literal("secret"),exposure:z16.literal("private"),environment:EnvironmentKeySchema,maskedValue:z16.string().optional(),createdAt:z16.date().transform(value=>value.toISOString()),updatedAt:z16.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema(z16.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema(ProjectSecretMetadataDTOSchema)}});import{z as z17}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=z17.object({success:z17.literal(!0),downloadUrl:z17.string(),expiresAt:z17.string(),fileSize:z17.number(),duration:z17.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z17.object({success:z17.literal(!0),projectId:z17.string(),projectName:z17.string(),displayName:z17.string(),projectUrl:z17.string(),duration:z17.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z17.object({contentTypes:z17.number(),entries:z17.number(),assets:z17.number(),translations:z17.number(),forms:z17.number(),codeFiles:z17.number(),assetFiles:z17.number()}),ImportPreviewSurfaceDTOSchema=z17.object({name:z17.string(),included:z17.boolean(),count:z17.number().optional(),note:z17.string().optional()}),ImportPreviewDTOSchema=z17.object({projectName:z17.string(),displayName:z17.string().nullable(),category:z17.string().nullable(),exportedAt:z17.string(),version:z17.string(),envScope:z17.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z17.array(ImportPreviewSurfaceDTOSchema),fileSize:z17.number(),fileName:z17.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z17.object({success:z17.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z18}from"zod";var TriggerKindSchema,ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema,TriggerSchema,init_agent_trigger_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-trigger.dto.js"(){"use strict";TriggerKindSchema=z18.enum(["manual","schedule","webhook"]),ManualTriggerSchema=z18.object({type:z18.literal("manual")}),ScheduleTriggerSchema=z18.object({type:z18.literal("schedule"),cron:z18.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:z18.string().optional()}),WebhookTriggerSchema=z18.object({type:z18.literal("webhook"),path:z18.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z18.discriminatedUnion("type",[ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema])}});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,AgentListItemTriggerStateSchema,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()}),AgentListItemTriggerStateSchema=z20.object({triggerIndex:z20.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z20.boolean(),wired:z20.boolean(),syncError:z20.string().nullable()}),AgentListItemDTOSchema=z20.object({name:z20.string().min(1),description:z20.string().nullable(),goalFirstLine:z20.string().nullable(),declaredCapabilities:z20.array(CapabilitySummaryEntrySchema),triggers:z20.array(AgentListItemTriggerSchema),triggerStates:z20.array(AgentListItemTriggerStateSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z20.array(AgentListItemDTOSchema))}});import{z as z21}from"zod";var ManualRunRequestSchema,DispatchSkippedSchema,DispatchAcceptedSchema,ManualRunResponseSchema,init_agent_run_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-run.dto.js"(){"use strict";init_response();ManualRunRequestSchema=z21.object({args:z21.unknown().optional(),requestId:z21.string().min(1).max(128).optional()}),DispatchSkippedSchema=z21.object({skipped:z21.enum(["no-manual-trigger","trigger-not-wired","run-in-progress","task-env-budget"])}),DispatchAcceptedSchema=z21.object({sessionId:z21.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z21.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z22}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,CONFLICT_KINDS,ConflictKindSchema,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=z22.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z22.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z22.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z22.object({verb:SurfaceDeltaVerbSchema,key:z22.string(),detail:z22.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z22.record(z22.string(),z22.unknown()).optional()}),PerSurfaceDeltaSchema=z22.object({surface:SurfaceNameSchema,status:z22.enum(["ok","timed_out","failed","unchanged"]),durationMs:z22.number().int().nonnegative().optional(),changedCount:z22.number().int().nonnegative(),conflictCount:z22.number().int().nonnegative(),items:z22.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z22.boolean().optional(),error:z22.string().optional()}),CrossSurfaceFindingSchema=z22.object({id:z22.string(),kind:z22.string(),description:z22.string(),severity:z22.enum(["warning","error"]),source:z22.object({surface:SurfaceNameSchema,key:z22.string()}),target:z22.object({surface:SurfaceNameSchema,key:z22.string()}),actions:z22.array(z22.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z22.object({env:EnvSchema,vs:EnvSchema,syncState:z22.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z22.coerce.date(),surfaces:z22.array(PerSurfaceDeltaSchema),agents:z22.array(z22.object({id:z22.string(),name:z22.string(),status:z22.enum(["active","paused","failed"]),lastRunAt:z22.coerce.date().nullable()})).optional(),crossSurface:z22.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z22.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z22.coerce.date(),surfaces:z22.array(PerSurfaceDeltaSchema),crossSurface:z22.array(CrossSurfaceFindingSchema).optional(),fingerprint:z22.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z22.object({path:z22.string(),state:z22.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z22.string(),additions:z22.number().int().nonnegative(),deletions:z22.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z22.object({oid:z22.string().optional(),content:z22.string().optional(),truncated:z22.boolean(),binary:z22.boolean()}),CodeConflictDetailSchema=z22.object({path:z22.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z22.string(),targetTipSha:z22.string(),mergeBaseSha:z22.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z22.object({id:z22.string(),slug:z22.string(),contentType:z22.string(),data:z22.record(z22.string(),z22.unknown()),updatedAt:z22.coerce.date()}),ContentRowDiffSchema=z22.object({collection:z22.string(),rowId:z22.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z22.object({name:z22.string(),label:z22.string(),isSingleton:z22.boolean(),fields:z22.record(z22.string(),z22.unknown())}),SchemaTypeDiffSchema=z22.object({typeName:z22.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z22.object({id:z22.string(),name:z22.string(),type:z22.enum(["file","folder"]),mimeType:z22.string().nullable(),storageKey:z22.string().nullable(),url:z22.string().nullable(),fileSize:z22.number().nullable(),width:z22.number().nullable(),height:z22.number().nullable(),altText:z22.string().nullable(),caption:z22.string().nullable(),createdAt:z22.coerce.date(),updatedAt:z22.coerce.date()}),AssetDiffSchema=z22.object({assetId:z22.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z22.object({locale:z22.string(),key:z22.string(),parent:z22.string().nullable(),child:z22.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z22.object({formName:z22.string(),label:z22.string().nullable(),schemaFingerprint:z22.string(),fields:z22.record(z22.string(),z22.unknown()),settings:z22.record(z22.string(),z22.unknown()).optional()}),FormSchemaDiffSchema=z22.object({formName:z22.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z22.enum(CONFLICT_KINDS),ConflictSchema=z22.object({surface:SurfaceNameSchema,key:z22.string(),kind:ConflictKindSchema.optional(),description:z22.string(),parentValue:z22.unknown().optional(),childValue:z22.unknown().optional(),conflictingFields:z22.array(z22.string()).optional(),code:z22.object({path:z22.string(),unresolvable:z22.boolean().optional(),reason:z22.string().optional()}).optional()}),FieldPickSchema=z22.object({field:z22.string(),choice:z22.enum(["parent","child","pick","ai-pick"]),pickedValue:z22.unknown().optional(),aiSessionId:z22.string().optional()}),ConflictResolutionSchema=z22.object({surface:SurfaceNameSchema,key:z22.string(),choice:z22.enum(["parent","child","pick"]),pickedValue:z22.unknown().optional(),fieldPicks:z22.array(FieldPickSchema).optional()}),MergeResultSchema=z22.object({ok:z22.boolean(),mergeId:z22.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z22.array(z22.object({surface:SurfaceNameSchema,count:z22.number().int().nonnegative()})),conflicts:z22.array(ConflictSchema).optional(),summary:z22.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z22.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z22.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z22.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z22.boolean().optional()}),ResolvedStrategySchema=z22.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z22.boolean()}),MergeRequestSchema=z22.object({from:EnvSchema,allowDirectMerge:z22.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z22.object({mergeId:z22.string().uuid(),streamUrl:z22.string(),strategy:ResolvedStrategySchema,acceptedAt:z22.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z22.object({mergeId:z22.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z22.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z22.array(ConflictSchema),draftResolutions:z22.array(ConflictResolutionSchema),lastEditedBy:z22.string().nullable(),lastEditedAt:z22.coerce.date().nullable(),initiator:z22.object({userId:z22.string().nullable(),role:z22.string().nullable(),agentName:z22.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z22.object({resolutions:z22.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z22.object({mergeId:z22.string().uuid(),draftResolutions:z22.array(ConflictResolutionSchema),lastEditedAt:z22.coerce.date(),lastEditedBy:z22.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z22.object({mergeId:z22.string().uuid(),resolutions:z22.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z22.object({mergeId:z22.string().uuid()}),PublishReleaseRequestSchema=z22.object({version:z22.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z22.string().max(2e4).optional()}),PublishReleaseResultSchema=z22.object({releaseTag:z22.string(),sha:z22.string(),publishedAt:z22.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z23}from"zod";var AgentSessionStatusSchema,SessionMetricsSchema,AgentSessionReviewPublicationSchema,AgentSessionReviewSummarySchema,AgentSessionReviewSummaryDTO,AgentSessionReviewPayloadSchema,AgentSessionReviewPayloadDTO,AgentSessionReviewPayloadResponseSchema,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();init_env_status_dto();AgentSessionStatusSchema=z23.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z23.object({cpuMs:z23.number().nonnegative().default(0),netBytes:z23.number().nonnegative().default(0),walltimeMs:z23.number().nonnegative().default(0),llmTokensIn:z23.number().nonnegative().optional(),llmTokensOut:z23.number().nonnegative().optional(),stepCount:z23.number().int().nonnegative().optional(),toolCallCounts:z23.record(z23.string().min(1).max(120),z23.number().int().nonnegative()).optional()}),AgentSessionReviewPublicationSchema=z23.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z23.object({capturedAt:z23.coerce.date(),fingerprint:z23.string().min(1).max(256),counts:z23.object({code:z23.number().int().nonnegative(),content:z23.number().int().nonnegative(),schemas:z23.number().int().nonnegative(),labels:z23.number().int().nonnegative()}),publication:AgentSessionReviewPublicationSchema,mergeId:z23.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z23.object({diff:DiffReportSchema,code:z23.array(CodeFileDiffSchema.extend({raw:z23.string().max(24576)})).max(200),schemas:z23.array(SchemaTypeDiffSchema).max(200),content:z23.array(z23.object({key:z23.string().min(1).max(512),collection:z23.string().min(1).max(256),slug:z23.string().max(512).optional(),verb:z23.enum(["added","modified","deleted"]),fields:z23.array(z23.object({name:z23.string().min(1).max(256),before:z23.unknown().optional(),after:z23.unknown().optional()})).max(20)})).max(200),labels:z23.array(z23.object({key:z23.string().min(1).max(512),locale:z23.string().min(1).max(64).optional(),before:z23.unknown().nullable(),after:z23.unknown().nullable()})).max(200)}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),AgentSessionDTOSchema=z23.object({id:z23.uuid(),projectId:z23.uuid(),env:EnvSchema,agentName:z23.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z23.unknown().optional(),capabilities:z23.array(z23.string()).optional(),dataSources:z23.array(z23.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z23.string().nullable(),startedAt:z23.coerce.date().nullable(),finishedAt:z23.coerce.date().nullable(),cancelledAt:z23.coerce.date().nullable(),costUsd:z23.number().nonnegative(),costCeilingUsd:z23.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z23.boolean(),lastCheckpointId:z23.uuid().nullable(),branchEnvId:z23.uuid().nullable(),parentSessionId:z23.uuid().nullable(),terminalReason:z23.string().nullable(),errorMessage:z23.string().nullable(),report:z23.string().nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z23.string().nullable(),createdAt:z23.coerce.date(),updatedAt:z23.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z23.object({id:z23.uuid(),sessionId:z23.uuid(),checkpointIdx:z23.number().int().nonnegative(),payloadRef:z23.string(),payloadSizeBytes:z23.number().int().nonnegative(),checksum:z23.string().length(64),createdAt:z23.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z23.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z23.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z23.object({session:AgentSessionDTOSchema,checkpoints:z23.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z23.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","too_many_agent_envs","env_provisioning_failed","agent_run_in_progress"]),CancelSessionRequestSchema=z23.object({reason:z23.string().min(1).max(120).optional()})}});import{z as z24}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=z24.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z24.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z24.object({id:z24.uuid(),envId:z24.uuid(),sessionId:z24.uuid().nullable(),skillName:z24.string().min(1),classification:AgentBranchClassificationSchema,rationale:z24.string().nullable(),summary:z24.string().nullable(),surfaceDeltas:z24.record(z24.string(),z24.unknown()),createdAt:z24.coerce.date(),decidedAt:z24.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z24.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z24.object({path:z24.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z24.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z24.object({code:z24.literal("merge_conflict"),message:z24.string(),conflicts:z24.record(z24.string(),z24.number().int().nonnegative())})}});import{z as z25}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,IntegrationToolEffectSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,SetProjectIntegrationCredentialRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,ConnectOrganizationIntegrationRequestSchema,ProjectIntegrationReturnPathSchema,ConnectProjectIntegrationRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,ProjectIntegrationConnectResponseSchema,BindProjectChannelRequestSchema,ListProjectChannelsQuerySchema,SearchProjectChannelsQuerySchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,ProjectChannelCandidateAvailabilitySchema,ProjectChannelCandidateDTOSchema,ProjectChannelCandidateDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,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,ProjectIntegrationConnectionsResponseSchema,ProjectIntegrationConnectResponseResponseSchema,ProjectChannelBindingResponseSchema,ProjectChannelBindingsResponseSchema,ProjectChannelCandidatesResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z25.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z25.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z25.enum(["secret_text"]),IntegrationCredentialUsageSchema=z25.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z25.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z25.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z25.object({mode:IntegrationAuthModeSchema,label:z25.string().min(1),description:z25.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z25.object({id:z25.string().min(1),label:z25.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z25.boolean()}),IntegrationToolDefinitionDTOSchema=z25.object({key:z25.string().min(1),name:z25.string().min(1),description:z25.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z25.object({title:z25.string().min(1),description:z25.string().min(1),command:z25.string().min(1).optional()}),IntegrationInfoDTOSchema=z25.object({key:z25.string().min(1),name:z25.string().min(1),summary:z25.string().min(1),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z25.array(IntegrationAuthModeDTOSchema),credentials:z25.array(IntegrationCredentialDefinitionDTOSchema),tools:z25.array(IntegrationToolDefinitionDTOSchema),recipes:z25.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z25.object({projectId:z25.uuid(),integrationKey:z25.string().min(1),name:z25.string().min(1),summary:z25.string().min(1),installed:z25.boolean(),enabled:z25.boolean(),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z25.string().nullable(),connectionId:z25.uuid().nullable().optional(),connectionAlias:z25.string().min(1).nullable().optional(),connectionStatus:z25.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z25.array(z25.string()),installedAt:z25.coerce.date().nullable(),updatedAt:z25.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z25.object({id:z25.uuid(),projectId:z25.uuid(),integrationKey:z25.string().min(1),enabled:z25.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z25.string(),connectionId:z25.uuid().nullable().optional(),connectionAlias:z25.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z25.array(z25.string()),createdAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z25.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z25.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z25.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z25.object({value:z25.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z25.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z25.object({id:z25.uuid(),organizationId:z25.string().min(1),integrationKey:z25.string().min(1),alias:z25.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z25.string().min(1),externalAccountName:z25.string().nullable(),externalBotUserId:z25.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z25.array(z25.string()),connectedAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ConnectOrganizationIntegrationRequestSchema=z25.object({alias:z25.string().min(1).max(120).optional(),token:z25.string().min(1).optional()}),ProjectIntegrationReturnPathSchema=z25.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),ConnectProjectIntegrationRequestSchema=z25.discriminatedUnion("mode",[z25.object({mode:z25.literal("personal"),alias:z25.string().min(1).max(120),token:z25.string().min(1)}),z25.object({mode:z25.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional()})]),StartProjectIntegrationConnectResponseSchema=z25.object({integrationKey:z25.string().min(1),connectUrl:z25.string().url(),expiresAt:z25.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z25.discriminatedUnion("mode",[z25.object({mode:z25.literal("personal"),integrationKey:z25.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z25.object({mode:z25.literal("oauth"),integrationKey:z25.string().min(1),connectUrl:z25.string().url(),expiresAt:z25.coerce.date()})]),BindProjectChannelRequestSchema=z25.object({ref:z25.string().min(1),connectionAlias:z25.string().min(1).optional(),agentName:z25.string().min(1).max(160).nullable().optional(),force:z25.boolean().optional()}),ListProjectChannelsQuerySchema=z25.object({integrationKey:z25.string().min(1)}),SearchProjectChannelsQuerySchema=z25.object({integrationKey:z25.string().min(1),connectionAlias:z25.string().min(1),query:z25.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z25.object({id:z25.uuid(),projectId:z25.uuid(),integrationKey:z25.string().min(1),connectionId:z25.uuid(),externalWorkspaceId:z25.string().min(1),externalChannelId:z25.string().min(1),externalChannelName:z25.string().nullable(),agentName:z25.string().nullable(),enabled:z25.boolean(),createdAt:z25.coerce.date(),updatedAt:z25.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z25.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z25.object({id:z25.string().min(1),name:z25.string().min(1),visibility:z25.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z25.string().min(1).nullable(),canMove:z25.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z25.object({markdown:z25.boolean().optional(),summary:z25.boolean().optional(),links:z25.boolean().optional(),images:z25.boolean().optional(),html:z25.union([z25.literal("cleaned"),z25.literal("raw"),z25.boolean()]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z25.object({url:z25.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional(),waitForMs:z25.number().int().min(0).max(3e4).optional()}),FirecrawlSearchToolInputSchema=z25.object({query:z25.string().min(1),maxResults:z25.number().int().positive().max(20).optional(),sources:z25.array(z25.enum(["web","news","images"])).min(1).max(3).optional(),categories:z25.array(z25.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z25.array(z25.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z25.array(z25.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z25.enum(["hour","day","week","month","year"]).optional(),location:z25.string().min(1).max(160).optional(),country:z25.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlMapToolInputSchema=z25.object({url:z25.string().url(),search:z25.string().min(1).optional(),limit:z25.number().int().positive().max(200).optional(),includeSubdomains:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z25.object({url:z25.string().url(),limit:z25.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z25.object({text:z25.string().min(1).max(200).optional(),cron:z25.string().min(1).max(120).optional(),timezone:z25.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorTargetInputSchema=z25.object({type:z25.enum(["scrape","crawl"]).default("scrape"),urls:z25.array(z25.string().url()).min(1).max(50),scrapeOptions:z25.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z25.boolean().optional(),timeoutMs:z25.number().int().positive().max(12e4).optional(),waitForMs:z25.number().int().min(0).max(3e4).optional()}).optional()}),FirecrawlMonitorCreateToolInputSchema=z25.object({name:z25.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z25.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z25.string().min(1).max(2e3).optional(),judgeEnabled:z25.boolean().optional(),retentionDays:z25.number().int().min(1).max(365).optional(),notification:z25.object({email:z25.object({enabled:z25.boolean().default(!0),recipients:z25.array(z25.string().email()).min(1).max(20),includeDiffs:z25.boolean().optional()}).optional()}).optional()}),FirecrawlMonitorIdToolInputSchema=z25.object({monitorId:z25.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z25.string().uuid()}),RunProjectIntegrationToolRequestSchema=z25.object({tool:z25.string().min(1),input:z25.record(z25.string(),z25.unknown()),connectionAlias:z25.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z25.object({provider:z25.string().min(1),providerCredits:z25.number().nonnegative().optional(),providerCostUsd:z25.number().nonnegative().optional(),requests:z25.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z25.object({credits:z25.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z25.object({url:z25.string(),provider:z25.literal("firecrawl"),title:z25.string().optional(),statusCode:z25.number().optional(),markdown:z25.string().optional(),summary:z25.string().optional(),links:z25.array(z25.string()).optional(),images:z25.array(z25.string()).optional(),html:z25.string().optional(),warning:z25.string().optional()}),FirecrawlSearchToolOutputSchema=z25.object({query:z25.string(),provider:z25.literal("firecrawl"),warning:z25.string().optional(),results:z25.array(z25.object({title:z25.string(),url:z25.string(),snippet:z25.string().optional(),content:z25.string().optional(),score:z25.number().optional(),publishedAt:z25.string().optional()}))}),FirecrawlMapToolOutputSchema=z25.object({url:z25.string(),provider:z25.literal("firecrawl"),count:z25.number(),links:z25.array(z25.object({url:z25.string(),title:z25.string().optional(),description:z25.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z25.object({url:z25.string(),provider:z25.literal("firecrawl"),total:z25.number(),pages:z25.array(z25.object({url:z25.string(),title:z25.string().optional(),statusCode:z25.number().optional(),markdown:z25.string().optional(),summary:z25.string().optional(),links:z25.array(z25.string()).optional(),images:z25.array(z25.string()).optional(),html:z25.string().optional(),warning:z25.string().optional()})),warning:z25.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z25.object({cron:z25.string().optional(),text:z25.string().optional(),timezone:z25.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z25.object({id:z25.string().optional(),urls:z25.array(z25.string()).optional(),scrapeOptions:z25.record(z25.string(),z25.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z25.object({id:z25.string(),name:z25.string(),status:z25.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z25.string().nullable().optional(),lastRunAt:z25.string().nullable().optional(),currentCheckId:z25.string().nullable().optional(),targets:z25.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z25.string().nullable().optional(),judgeEnabled:z25.boolean().optional(),estimatedCreditsPerMonth:z25.number().optional(),createdAt:z25.string().optional(),updatedAt:z25.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z25.object({id:z25.string(),monitorId:z25.string(),scheduledFor:z25.string().nullable().optional(),startedAt:z25.string().nullable().optional(),finishedAt:z25.string().nullable().optional(),estimatedCredits:z25.number().optional(),reservedCredits:z25.number().optional(),actualCredits:z25.number().optional(),billingStatus:z25.string().nullable().optional(),summary:z25.object({totalPages:z25.number().optional(),same:z25.number().optional(),changed:z25.number().optional(),new:z25.number().optional(),removed:z25.number().optional(),error:z25.number().optional()}).passthrough().optional(),error:z25.string().nullable().optional(),createdAt:z25.string().optional(),updatedAt:z25.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitors:z25.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitorId:z25.string(),deleted:z25.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitorId:z25.string(),checks:z25.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z25.object({provider:z25.literal("firecrawl"),monitorId:z25.string(),check:FirecrawlMonitorCheckOutputSchema,next:z25.string().optional()}),FirecrawlToolKeySchema=z25.enum(["search","scrape","map","crawl","monitor.create","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z25.union([FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z25.object({projectId:z25.uuid(),integrationKey:z25.string().min(1),tool:z25.string().min(1),connectionAlias:z25.string().min(1).nullable().optional(),output:z25.record(z25.string(),z25.unknown()),executedAt:z25.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z25.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z25.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z25.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z25.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z25.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z25.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z25.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z25.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z25.array(OrganizationIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z25.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z25.array(ProjectChannelCandidateDTOSchema))}});import{z as z26}from"zod";var SCHEDULE_NOTIFICATION_TOPICS,ScheduleNotificationTopicSchema,USER_MANAGED_NOTIFICATION_TOPICS,UserManagedNotificationTopicSchema,MAX_SCHEDULE_SUBSCRIBERS,ScheduleSubscriberDeliveryStateSchema,ScheduleSubscriberCandidateSchema,ScheduleNotificationSettingsSchema,ScheduleNotificationSettingsResponseSchema,UpdateScheduleSubscribersRequestSchema,UserNotificationPreferenceSchema,UserNotificationPreferencesSchema,UserNotificationPreferencesResponseSchema,UpdateUserNotificationPreferenceRequestSchema,SCHEDULE_OPT_OUT_LINK_ACTIONS,ScheduleOptOutLinkActionSchema,SCHEDULE_OPT_OUT_ACTIONS,ScheduleOptOutActionSchema,ScheduleOptOutStateSchema,ScheduleOptOutResponseSchema,FollowedScheduleSchema,FollowedSchedulesSchema,FollowedSchedulesResponseSchema,init_schedule_notifications_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule-notifications.dto.js"(){"use strict";init_response();SCHEDULE_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],ScheduleNotificationTopicSchema=z26.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],UserManagedNotificationTopicSchema=z26.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z26.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z26.object({userId:z26.string().min(1),name:z26.string(),email:z26.string().min(1),subscribed:z26.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z26.object({maxSubscribers:z26.number().int().positive(),subscriberCount:z26.number().int().nonnegative(),effectiveRecipientCount:z26.number().int().nonnegative(),currentUserSubscribed:z26.boolean(),candidates:z26.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z26.object({userIds:z26.array(z26.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z26.object({topic:UserManagedNotificationTopicSchema,enabled:z26.boolean(),source:z26.enum(["default","explicit"])}),UserNotificationPreferencesSchema=z26.object({topics:z26.array(UserNotificationPreferenceSchema)}),UserNotificationPreferencesResponseSchema=createResponseSchema(UserNotificationPreferencesSchema),UpdateUserNotificationPreferenceRequestSchema=z26.object({enabled:z26.boolean()}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z26.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z26.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z26.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z26.string().nullable(),maskedEmail:z26.string().min(1),applied:z26.boolean(),expiresAt:z26.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z26.object({scheduleId:z26.string().min(1),scheduleName:z26.string(),projectId:z26.string().min(1),projectName:z26.string(),env:z26.string().min(1)}),FollowedSchedulesSchema=z26.object({schedules:z26.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z27}from"zod";var PROJECT_SECRET_KEY_PATTERN,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN,RESERVED_PROJECT_SECRET_KEYS,ProjectSecretKeySchema,ProjectScheduleStatusSchema,ProjectScheduleDTOSchema,ProjectScheduleDTO,CreateProjectScheduleRequestSchema,UpdateProjectScheduleRequestSchema,ProjectScheduleRunStatusSchema,ProjectScheduleRunTriggerSchema,ProjectScheduleRunSecretSnapshotStateSchema,ProjectScheduleRunSecretResolutionSchema,ProjectSchedulePolicySchema,SchedulePolicyStateSchema,ProjectSchedulePlanSnapshotSchema,ProjectScheduleUsageSchema,ProjectScheduleRunDTOSchema,ProjectScheduleRunDTO,ProjectScheduleRunSecretSnapshotSchema,ProjectScheduleRunDetailDTOSchema,ProjectScheduleRunDetailDTO,RunProjectScheduleRequestSchema,ProjectScheduleRunsQuerySchema,ProjectScheduleResponseSchema,ProjectSchedulesListDataSchema,ProjectSchedulesListResponseSchema,ProjectSchedulesOverviewResponseSchema,ProjectScheduleDetailDataSchema,ProjectScheduleDetailResponseSchema,ProjectScheduleRunsPageSchema,ProjectScheduleRunsResponseSchema,ProjectScheduleRunResponseSchema,ProjectScheduleRunDetailResponseSchema,init_schedule_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();init_schedule_notifications_dto();PROJECT_SECRET_KEY_PATTERN=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN=/^(PUBLIC_|VITE_|NEXT_PUBLIC_|NUXT_PUBLIC_)/,RESERVED_PROJECT_SECRET_KEYS=new Set([...FIMO_MANAGED_PROJECT_ENV_KEYS,"FIMO_SCHEDULE_ID","FIMO_SCHEDULE_RUN_ID","FIMO_SCHEDULE_NAME"]),ProjectSecretKeySchema=z27.string().min(1).max(255).superRefine((key,context)=>{PROJECT_SECRET_KEY_PATTERN.test(key)?RESERVED_PROJECT_SECRET_KEYS.has(key)?context.addIssue({code:"custom",message:`Secret key '${key}' is managed by Fimo and cannot be stored in project secrets.`}):PUBLIC_PROJECT_SECRET_PREFIX_PATTERN.test(key)&&context.addIssue({code:"custom",message:`Secret key '${key}' uses a public variable prefix. Store public values with fimo vars instead.`}):context.addIssue({code:"custom",message:`Secret key '${key}' must be UPPER_SNAKE_CASE.`})}),ProjectScheduleStatusSchema=z27.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z27.uuid(),env:z27.string().min(1),name:z27.string().min(1),cron:z27.string().min(1),command:z27.string().min(1),secretKeys:z27.array(z27.string().min(1)),enabled:z27.boolean(),lastRunAt:z27.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z27.string().nullable(),overPolicyReasons:z27.array(z27.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z27.object({name:z27.string().min(1).max(120),cron:z27.string().min(1).max(120),command:z27.string().min(1).max(500),secretKeys:z27.array(ProjectSecretKeySchema).default([]),enabled:z27.boolean().optional()}),UpdateProjectScheduleRequestSchema=z27.object({name:z27.string().min(1).max(120).optional(),cron:z27.string().min(1).max(120).optional(),command:z27.string().min(1).max(500).optional(),secretKeys:z27.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z27.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z27.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z27.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z27.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z27.object({maxRuns:z27.number().int().positive(),retentionDays:z27.number().int().positive().nullable(),outputRetentionDays:z27.number().int().positive(),maxOutputBytes:z27.number().int().positive()}),SchedulePolicyStateSchema=z27.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z27.object({code:z27.enum(["Free","Premium"]),source:z27.enum(["cached_subscription","free_fallback"]),activeSchedules:z27.object({used:z27.number().int().nonnegative(),limit:z27.number().int().positive()}),minCadenceMinutes:z27.number().int().positive(),maxRunMs:z27.number().int().positive(),concurrency:z27.object({used:z27.number().int().nonnegative(),limit:z27.number().int().positive()}),compute:z27.object({settledMs:z27.number().int().nonnegative(),reservedMs:z27.number().int().nonnegative(),includedMs:z27.number().int().positive(),remainingMs:z27.number().int().nonnegative(),resetsAt:z27.coerce.date()}),upgrade:z27.object({code:z27.literal("Premium"),activeSchedulesLimit:z27.number().int().positive(),minCadenceMinutes:z27.number().int().positive(),maxRunMs:z27.number().int().positive(),maxConcurrentRuns:z27.number().int().positive(),computeIncludedMs:z27.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z27.array(z27.string())}),ProjectScheduleUsageSchema=z27.object({runCount:z27.number().int().nonnegative(),runsWithOutput:z27.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z27.object({id:z27.uuid(),scheduleId:z27.uuid(),projectId:z27.uuid(),env:z27.string().min(1),scheduleName:z27.string().min(1),command:z27.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z27.object({id:z27.string().min(1),name:z27.string().min(1)}).nullable(),queuedAt:z27.coerce.date(),startedAt:z27.coerce.date().nullable(),finishedAt:z27.coerce.date().nullable(),exitCode:z27.number().int().nullable(),errorCode:z27.string().nullable(),error:z27.string().nullable(),outputBytes:z27.number().int().nonnegative(),outputTruncated:z27.boolean(),outputExpiresAt:z27.coerce.date().nullable(),metadataExpiresAt:z27.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z27.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z27.coerce.date().nullable(),items:z27.array(z27.object({key:z27.string().min(1),updatedAt:z27.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z27.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z27.object({trigger:z27.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z27.object({limit:z27.coerce.number().int().min(1).max(100).default(25),cursor:z27.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z27.object({items:z27.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z27.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z27.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z27.object({items:z27.array(ProjectScheduleRunDTOSchema),nextCursor:z27.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z28}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=z28.object({id:z28.uuid(),occurredAt:z28.coerce.date(),projectId:z28.uuid().nullable(),env:z28.string().nullable(),actor:z28.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z28.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z28.unknown().optional(),ipAddress:z28.string().nullable().optional(),userAgent:z28.string().nullable().optional(),error:z28.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z28.object({rows:z28.array(AuditLogRowDTOSchema),nextCursor:z28.string().nullable()})),AuditLogQuerySchema=z28.object({env:z28.string().optional(),action:AuditActionSchema.optional(),actor:z28.string().optional(),from:z28.coerce.date().optional(),to:z28.coerce.date().optional(),limit:z28.coerce.number().int().min(1).max(200).optional(),cursor:z28.string().optional()})}});import{z as z29}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=z29.object({surface:SurfaceNameSchema,key:z29.string(),label:z29.string()}),InlineSchema=z29.object({text:z29.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z29.discriminatedUnion("type",[z29.object({type:z29.literal("paragraph"),content:z29.array(InlineSchema).max(24)}),z29.object({type:z29.literal("preview"),ref:DiffRefSchema,caption:z29.string().optional()}),z29.object({type:z29.literal("code"),code:z29.string(),lang:z29.string().optional(),caption:z29.string().optional()}),z29.object({type:z29.literal("risk"),level:z29.enum(["warning","error"]),content:z29.array(InlineSchema).max(24)}),z29.object({type:z29.literal("list"),items:z29.array(z29.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z29.object({headline:z29.string(),blocks:z29.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z29.object({summary:EnvDiffSummarySchema,fingerprint:z29.string(),generatedAt:z29.coerce.date(),cached:z29.boolean().optional(),credits:z29.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z30}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=z30.object({date:z30.string(),visitors:z30.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z30.object({key:z30.string(),visitors:z30.number().int().nonnegative(),pageviews:z30.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z30.object({path:z30.string(),pageName:z30.string().nullable().optional(),visitors:z30.number().int().nonnegative(),pageviews:z30.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z30.object({preset:z30.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z30.string(),requestedTo:z30.string(),effectiveFrom:z30.string(),effectiveTo:z30.string(),isRetentionLimited:z30.boolean(),groupBy:z30.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z30.object({date:z30.string(),content:z30.string(),updatedAt:z30.string(),updatedByUserId:z30.string()}),ProjectPageviewAnalyticsDTOSchema=z30.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z30.number().int().nonnegative(),pageviews:z30.number().int().nonnegative(),bounceRate:z30.number().min(0).max(100),viewsPerVisit:z30.number().nonnegative(),averageVisitDurationSeconds:z30.number().nonnegative(),visitorsSeries:z30.array(ProjectDailyVisitorsDTOSchema),topPages:z30.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z30.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z30.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z31}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=z31.object({id:z31.string(),email:z31.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z31.coerce.date(),createdAt:z31.coerce.date(),inviterUserId:z31.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z31.object({id:z31.string(),token:z31.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z31.object({success:z31.boolean(),projectId:z31.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z32}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=z32.object({id:z32.string(),name:z32.string(),image:z32.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z32.object({count:z32.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z32.object({counts:z32.object({signed_up:z32.int(),activated:z32.int()}),credits:z32.object({total:z32.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z32.email(),emailVerified:z32.boolean(),createdAt:z32.coerce.date(),updatedAt:z32.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z33}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,PROJECT_PERMISSION_KEYS,ProjectPermissionKeySchema,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=z33.object({id:z33.string(),principalType:ProjectPrincipalTypeSchema,principalId:z33.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z33.coerce.date(),expiresAt:z33.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),PROJECT_PERMISSION_KEYS=["project:read","project:manage","project:publish","project:unpublish","project:duplicate","project:export","project:import","project:transfer","project:delete","acl:read","acl:grant","member:read","member:change-role","invite:read","invite:send","invite:revoke","asset:read","asset:upload","asset:manage","asset:delete","code:view","code:edit","content:view","content:edit","chat:read","chat:prompt","history:view","history:manage","comment:read","comment:create","comment:delete","integration:run","sync:github","webhook:read","webhook:manage","schedule:read","schedule:manage","preview:view","realtime:connect","analytics:view","logs:view","domain:manage","agent:run"],ProjectPermissionKeySchema=z33.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z33.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z33.record(z33.string(),z33.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z33.object({access:z33.array(ProjectAccessItemDTOSchema),invites:z33.array(ProjectInviteDTOSchema),organization:z33.object({name:z33.string().nullable(),logo:z33.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z33.object({success:z33.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z33.object({success:z33.boolean(),projectId:z33.uuid()}))}});import{z as z34}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=z34.object({publicationStatus:PublicationStatusSchema,appUrl:z34.string().nullable(),lastPublishedAt:z34.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z35}from"zod";var SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();SandboxSessionDTOSchema=z35.object({url:z35.url(),expiresAt:z35.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema)}});import{z as z36}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:z36.string(),slug:z36.string().nullable(),logo:z36.string().nullable(),metadata:z36.record(z36.string(),z36.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z36.object({id:z36.string(),name:z36.string(),email:z36.email(),image:z36.string().nullable()}),OrganizationMemberDTOSchema=z36.object({id:z36.string(),userId:z36.string(),organizationId:z36.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z36.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z37}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,AutoRefillConfigDTOSchema,AutoRefillConfigDTO,UpdateAutoRefillDTOSchema,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,AutoRefillConfigResponseSchema,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=z37.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z37.object({reason:CancellationReasonCodeSchema,details:z37.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z37.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),AiCreditsEntitlementSchema=z37.object({included:z37.number().optional(),unitPrice:z37.number().optional(),dailyCap:z37.number().nullable().optional()}),EntitlementsDTOSchema=z37.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z37.object({retentionDays:z37.number().int().positive(),canUseExtendedDateRanges:z37.boolean()}).optional(),history:z37.object({retentionDays:z37.number().int().positive()}).optional(),members:z37.object({canInvite:z37.boolean(),maxMembers:z37.number().int().positive().nullable()}).optional(),domains:z37.object({canUseCustomDomains:z37.boolean(),maxDomains:z37.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z37.object({id:z37.string(),external_id:z37.string(),customerId:z37.string(),planId:z37.string(),planCode:TemplateCodeSchema,currentPeriod:z37.object({start:z37.string(),end:z37.string().nullable()}),cancelAt:z37.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z37.string(),nextPaymentAt:z37.string().nullable(),baseAmount:z37.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z37.object({totalCap:z37.number(),dailyCap:z37.number(),usedTotal:z37.number()}),CreditBalanceDTOSchema=z37.object({total:z37.number(),base:z37.number(),dailyBase:z37.number(),purchases:z37.number(),awards:z37.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z37.object({total:z37.number(),nearLimit:z37.boolean(),canChat:z37.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z37.object({dailyFreeAvailable:z37.number(),monthlyAvailable:z37.number(),purchasedAvailable:z37.number(),awardedAvailable:z37.number()}),ProjectDailyCreditAllowanceDTOSchema=z37.object({periodCap:z37.number(),dailyGrant:z37.number(),usedThisPeriod:z37.number(),remainingThisPeriod:z37.number()}),ProjectCreditBalanceDTOSchema=z37.object({projectId:z37.uuid(),organizationId:z37.string(),balance:z37.object({totalAvailable:z37.number(),nearLimit:z37.boolean(),canUseAi:z37.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z37.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AutoRefillConfigDTOSchema=z37.discriminatedUnion("enabled",[z37.object({enabled:z37.literal(!0),thresholdUsd:z37.number().nonnegative(),refillAmountUsd:z37.number().nonnegative()}),z37.object({enabled:z37.literal(!1),thresholdUsd:z37.number().nonnegative().nullable(),refillAmountUsd:z37.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z37.discriminatedUnion("enabled",[z37.object({enabled:z37.literal(!0),thresholdUsd:z37.number().min(.01).multipleOf(.01),refillAmountUsd:z37.number().min(.01).multipleOf(.01)}).strict(),z37.object({enabled:z37.literal(!1),thresholdUsd:z37.number().min(.01).multipleOf(.01)}).strict()]),SuccessfulPurchaseDTOSchema=z37.object({invoiceId:z37.string(),newBalance:z37.int(),creditCount:z37.int(),amountUsd:z37.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z37.object({url:z37.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),AutoRefillConfigResponseSchema=createResponseSchema(AutoRefillConfigDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema)}});import{z as z38}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=z38.object({brand:z38.string(),last4:z38.string(),exp:z38.string(),isDefault:z38.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z39}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=z39.string().superRefine((path49,ctx)=>{let segments=path49.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=z39.object({type:z39.literal("renameField"),contentType:z39.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z39.object({enabled:z39.boolean()}).strict(),ContentTypeDTOSchema=z39.object({id:z39.string(),name:z39.string(),label:z39.string(),isSingleton:z39.boolean(),i18n:ContentTypeI18nSchema,fields:z39.record(z39.string(),FieldDefinitionSchema),createdAt:z39.string(),updatedAt:z39.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z39.object({contentTypes:z39.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z39.object({id:z39.string(),entryId:z39.string(),documentId:z39.string(),slug:z39.string(),locale:z39.string().optional(),createdAt:z39.string(),updatedAt:z39.string(),__fimo:z39.object({contentType:z39.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({limit:z39.number(),offset:z39.number(),total:z39.number(),hasMore:z39.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z39.object({contentType:z39.string(),count:z39.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z39.object({counts:z39.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z39.object({count:z39.number().int().nonnegative(),sourceLocale:z39.string(),targetLocale:z39.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z39.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z39.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z39.union([z39.string(),z39.number(),z39.boolean(),z39.null()]),entryWhereOperatorSchema=z39.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z39.array(entryWhereScalarSchema).optional(),$nin:z39.array(entryWhereScalarSchema).optional(),$contains:z39.string().optional(),$startsWith:z39.string().optional(),$null:z39.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z39.record(z39.string(),z39.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z39.record(z39.string(),z39.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z39.object({data:z39.record(z39.string(),z39.unknown()),locale:z39.string().min(1).optional(),documentId:z39.uuid().optional()}),entryIdsSchema=z39.array(z39.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z39.object({sql:z39.string().min(1)}),BulkCreateEntriesRequestSchema=z39.object({entries:z39.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z39.union([z39.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z39.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z39.object({updates:z39.array(z39.object({id:z39.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z39.union([z39.object({ids:entryIdsSchema,locale:z39.string().min(1).optional()}),z39.object({where:EntryWhereSchema,locale:z39.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z39.object({data:z39.array(z39.record(z39.string(),z39.unknown())),meta:z39.object({rowCount:z39.number().int().nonnegative(),truncated:z39.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({created:z39.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({updated:z39.number().int().nonnegative(),missing:z39.array(z39.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z39.object({data:z39.array(EntryDTOSchema),meta:z39.object({deleted:z39.number().int().nonnegative(),missing:z39.array(z39.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z40}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z40.object({index:z40.number().int().nonnegative(),contentType:z40.string(),field:z40.string(),value:z40.string(),against:z40.enum(["stored","batch"]),ownerDocumentId:z40.uuid().optional(),ownerIndex:z40.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z40.object({code:z40.literal("unique_conflict"),message:z40.string(),conflicts:z40.array(UniqueConflictSchema),truncated:z40.boolean().optional()})}});import{z as z41}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=z41.object({kind:z41.literal("unique_conflict"),contentType:z41.string(),field:z41.string(),value:z41.string(),documentCount:z41.number().int().positive(),documentIds:z41.array(z41.uuid()),documentIdsTruncated:z41.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z41.object({code:z41.literal("schema_transition_rejected"),message:z41.string(),issues:z41.array(SchemaTransitionIssueSchema),truncated:z41.boolean().optional()})}});import{z as z42}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=z42.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z42.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z42.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z42.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z42.object({field:CmsFieldNameSchema,direction:z42.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z42.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z42.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z42.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z42.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z42.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z43}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=z43.object({id:z43.string(),name:z43.string()}),AssetDTOSchema=z43.object({id:z43.string(),name:z43.string(),type:AssetTypeSchema,originalFileName:z43.string().nullable(),parentId:z43.string().nullable(),mimeType:z43.string().nullable(),fileSize:z43.number().nullable(),url:z43.string().nullable(),storageKey:z43.string().nullable(),createdAt:z43.string(),updatedAt:z43.string(),altText:z43.string().nullable().optional(),caption:z43.string().nullable().optional(),aiCaption:z43.string().nullable().optional(),aiAltText:z43.string().nullable().optional(),aiTags:z43.array(z43.string()).nullable().optional(),aiPrimaryColor:z43.string().nullable().optional(),aiProcessingStatus:z43.string().nullable().optional(),width:z43.number().nullable().optional(),height:z43.number().nullable().optional(),path:z43.array(AssetPathItemSchema).optional(),hasChildren:z43.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z43.lazy(()=>z43.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z43.array(AssetDTOSchema))}});import{z as z44}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z44.object({key:z44.string(),value:z44.string().optional(),defaultValue:z44.string(),locale:z44.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z45}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=z45.object({id:z45.string(),name:z45.string(),type:z45.enum(["file","folder"]),path:z45.string(),children:z45.lazy(()=>z45.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z45.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z45.object({path:z45.string(),exists:z45.boolean(),type:z45.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z46}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatLiveTurnStateDTOSchema,ChatLiveTurnStateDTO,ChatThreadMessageDTOSchema,ChatAttentionDTOSchema,ChatThreadMessagesPageDTOSchema,ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema,ChatNonStreamingOutcomeDTOSchema,ChatDeletionDTOSchema,ChatDeletionDTO,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,ChatDeletionResponseSchema,ChatClearErrorDTOSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_create_dto();init_response();init_project_dto();ChatMessageListDTOSchema=z46.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z46.object({items:z46.array(ProjectMessagePublicDTOSchema),nextCursor:z46.string().nullable()}),ChatLiveTurnDTOSchema=z46.object({invocationId:z46.string(),step:z46.enum(["preparing","working","compacting","merging"]),startedAt:z46.string()}),ChatLiveTurnStateDTOSchema=z46.object({threadId:z46.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z46.object({id:z46.string(),role:z46.enum(["user","assistant"]),parts:z46.array(z46.unknown()),metadata:z46.record(z46.string(),z46.unknown()).nullable(),versionId:z46.string().nullable().optional(),createdAt:z46.date().transform(value=>value.toISOString()),providerMessageId:z46.string().nullable().optional(),invocationId:z46.string().nullable().optional(),invocationStatus:z46.string().nullable().optional(),invocationTerminalReason:z46.string().nullable().optional()}),ChatAttentionDTOSchema=z46.object({type:z46.literal("merge_conflict"),merge:z46.object({mergeId:z46.string().uuid(),projectId:z46.string(),fromEnv:z46.string(),toEnv:z46.string()}),publishAfterMerge:z46.boolean()}),ChatThreadMessagesPageDTOSchema=z46.object({threadId:z46.string().nullable(),title:z46.string().nullable(),messages:z46.array(ChatThreadMessageDTOSchema),nextCursor:z46.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z46.object({kind:z46.literal("replay"),threadId:z46.string(),userMessageId:z46.string()}),ChatQueuedOutcomeDTOSchema=z46.object({kind:z46.literal("queued"),threadId:z46.string(),userMessageId:z46.string(),blockingRootId:z46.string()}),ChatBusyOutcomeDTOSchema=z46.object({kind:z46.literal("busy"),threadId:z46.string(),userMessageId:z46.string(),blockingRootId:z46.string().optional()}),ChatRefusedOutcomeDTOSchema=z46.object({kind:z46.literal("refused"),threadId:z46.string(),userMessageId:z46.string(),refusedInvocationId:z46.string(),terminalReason:z46.string()}),ChatNonStreamingOutcomeDTOSchema=z46.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z46.object({success:z46.boolean(),deletedCount:z46.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z46.object({code:z46.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z46.string()})}});import{z as z47}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=z47.object({url:z47.string().url(),key:z47.string(),size:z47.number(),contentType:z47.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z48}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=z48.object({canAccess:z48.boolean(),permissions:z48.record(z48.string(),z48.boolean()),role:z48.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z49}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:z49.string().trim().default(""),sort:z49.enum(["recent","name","relevance"]).default("recent"),category:z49.string().optional()})}});import{z as z50}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=z50.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z50.enum(["fimo","external"]),PaymentStatusSchema=z50.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z50.object({id:z50.string().uuid(),domain:z50.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z50.boolean(),price:z50.number().int().nullable(),renewalPrice:z50.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z50.string().nullable(),failureReason:z50.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z50.object({domain:z50.string(),available:z50.boolean(),premium:z50.boolean(),price:z50.number().nullable(),renewalPrice:z50.number().nullable(),purchaseType:z50.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z50.object({domain:z50.string(),price:z50.number().nullable(),renewalPrice:z50.number().nullable(),premium:z50.boolean(),allowedYears:z50.array(z50.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z50.object({firstName:z50.string().max(100),lastName:z50.string().max(100),companyName:z50.string().max(100).optional(),address1:z50.string().max(255),address2:z50.string().max(255).optional(),city:z50.string().max(100),state:z50.string().max(100),zip:z50.string().max(20),country:z50.string().max(2),phone:z50.string().max(30),email:z50.union([z50.string().email().max(255),z50.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z50.object({firstName:z50.string().min(1).max(100),lastName:z50.string().min(1).max(100),companyName:z50.string().max(100).optional(),address1:z50.string().min(1).max(255),address2:z50.string().max(255).optional(),city:z50.string().min(1).max(100),state:z50.string().min(1).max(100),zip:z50.string().min(1).max(20),country:z50.string().min(1).max(2),phone:z50.string().min(1).max(30),email:z50.string().email().max(255)}),SearchDomainsRequestSchema=z50.object({keyword:z50.string().min(1).max(100),tldFilter:z50.array(z50.string()).optional()}),CheckAvailabilityRequestSchema=z50.object({domains:z50.array(z50.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=z50.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z50.object({domain:DomainNameSchema,years:z50.number().int().min(1).max(10).optional().default(3),autoRenew:z50.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z50.object({autoRenew:z50.boolean().optional()}),RenewDomainRequestSchema=z50.object({years:z50.number().int().min(1).max(10).optional().default(1),autoRenew:z50.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z50.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z50.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z50.object({verified:z50.boolean(),email:z50.string().nullable(),verifyBy:z50.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z51}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=z51.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=z51.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=z51.object({txtName:z51.string().nullable().optional(),txtValue:z51.string().nullable().optional(),httpUrl:z51.string().nullable().optional(),httpBody:z51.string().nullable().optional(),cname:z51.string().nullable().optional(),cnameTarget:z51.string().nullable().optional()}),SSLValidationErrorSchema=z51.object({message:z51.string()}),OwnershipVerificationSchema=z51.object({type:z51.string(),name:z51.string(),value:z51.string()}),ProjectDomainSSLDTOSchema=z51.object({status:z51.string(),method:z51.string().nullable(),type:z51.string().nullable(),validationRecords:z51.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z51.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z51.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z51.enum(["subdomain","apex"]),RedirectConfigSchema=z51.object({type:z51.literal("apex_to_www"),linkedDomainId:z51.string()}).nullable().optional(),ProjectDomainDTOSchema=z51.object({id:z51.string(),hostname:z51.string(),status:z51.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z51.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z51.string(),scdCnameTarget:z51.string().optional(),apexTargets:z51.array(z51.string()),dnsAutoConfigured:z51.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z51.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z51.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z51.object({hostname:z51.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:z51.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z51.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z51.object({available:z51.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z51.object({success:z51.boolean(),hostname:z51.string()}))}});import{z as z52}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=z52.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z52.object({available:z52.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z52.object({slug:z52.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z52.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z52.object({subdomain:z52.string(),subdomainUpdatedAt:z52.coerce.date()})),SubdomainSuggestionsQuerySchema=z52.object({base:z52.string().max(100).optional(),max:z52.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z52.object({suggestions:z52.array(z52.string())}))}});import{z as z53}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=z53.object({translated:z53.number().int().nonnegative(),total:z53.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z53.object({locale:z53.string(),isDefault:z53.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z53.object({defaultLocale:z53.string(),routing:z53.object({strategy:z53.literal("path-prefix"),prefixDefaultLocale:z53.boolean()}),locales:z53.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z53.object({locale:z53.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z53.object({locale:z53.string().min(1).max(40)}),ProjectLocaleMutationSchema=z53.object({locale:z53.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z53.object({locale:z53.string(),entriesDeleted:z53.number().int().nonnegative(),labelsDeleted:z53.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z54}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=z54.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z54.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=z54.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z54.number(),credits:z54.number().optional(),billingMode:z54.enum(["fimo-credits","provider-account"]).optional(),confidence:z54.enum(["exact","estimated","metered"]),basis:z54.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z55}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=z55.object({options:z55.record(z55.string(),z55.unknown()),name:z55.string().optional(),parentId:z55.string().nullable().optional(),altText:z55.string().optional(),caption:z55.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z55.string().min(1).optional(),model:z55.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=z55.object({jobId:z55.string(),status:z55.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z55.string().nullable().optional(),credits:z55.number().optional(),costUsd:z55.number().optional(),billingMode:z55.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z55.object({error:z55.string(),code:z55.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:z55.array(GenerationTaskIdSchema).optional(),availableModels:z55.array(z55.string()).optional(),issues:z55.array(z55.unknown()).optional()})}});import{z as z56}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=z56.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z56.object({name:z56.string(),key:z56.string(),description:z56.string(),type:FlagTypeSchema,required:z56.boolean(),defaultValue:z56.unknown().optional(),enumValues:z56.array(z56.string()).optional(),isArray:z56.boolean()}),AssetModelPriceSchema=z56.object({unitPrice:z56.number(),unit:z56.string(),confidence:z56.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z56.object({id:z56.string(),shortName:z56.string(),provider:z56.string(),source:z56.string(),modality:z56.enum(["image","video","audio"]),tags:z56.array(z56.string()),displayName:z56.string(),description:z56.string(),flags:z56.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z56.object({model:z56.string(),costUsd:z56.number(),credits:z56.number(),billingMode:z56.enum(["fimo-credits","provider-account"]),confidence:z56.enum(["exact","estimated","metered"]),basis:z56.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z57}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=z57.object({tourId:z57.string(),version:z57.string(),status:z57.string(),completedAt:z57.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z57.array(UserTourDTOSchema))}});import{z as z58}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=z58.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z58.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z58.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z58.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z58.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z58.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z58.enum(["user","agent","system"]),SupportReportTagSchema=z58.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z58.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z58.object({organization:z58.object({id:z58.string().trim().min(1).max(255),name:z58.string().trim().max(240).optional()}),project:z58.object({id:z58.uuid(),name:z58.string().trim().max(240).optional(),createdAt:z58.coerce.date().optional()}).optional(),environment:z58.string().trim().max(255).optional(),clientVersion:z58.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z58.object({message:z58.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z58.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z58.string().trim().max(200).optional(),limit:z58.coerce.number().int().min(1).max(100).default(50),offset:z58.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z58.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z58.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z58.uuid().nullable().optional(),note:z58.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=z58.object({message:z58.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z58.object({kind:SupportReportLinkKindSchema,label:z58.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z58.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z58.object({kind:SupportReportActorKindSchema,id:z58.string().nullable(),name:z58.string().nullable()}),SupportReportLinkDTOSchema=z58.object({id:z58.uuid(),kind:SupportReportLinkKindSchema,label:z58.string(),url:SupportReportHttpUrlSchema,externalId:z58.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z58.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z58.object({id:z58.uuid(),kind:SupportReportEventKindSchema,body:z58.string().nullable(),metadata:z58.record(z58.string(),z58.unknown()),actor:SupportReportActorDTOSchema,createdAt:z58.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z58.object({id:z58.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z58.array(z58.string()),source:SupportReportSourceSchema,message:z58.string(),reporter:z58.object({id:z58.string().nullable(),name:z58.string().nullable(),email:z58.string().nullable()}),organization:z58.object({id:z58.string().nullable(),name:z58.string()}),project:z58.object({id:z58.uuid().nullable(),name:z58.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z58.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z58.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z58.string().nullable(),deliveredAt:z58.coerce.date().nullable()}).nullable(),duplicateOfReportId:z58.uuid().nullable(),resolvedAt:z58.coerce.date().nullable(),createdAt:z58.coerce.date(),updatedAt:z58.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z58.string().nullable(),clientVersion:z58.string().nullable(),links:z58.array(SupportReportLinkDTOSchema),events:z58.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z58.object({reports:z58.array(SupportReportSummaryDTOSchema),total:z58.number().int().nonnegative(),statusCounts:z58.object({new:z58.number().int().nonnegative(),in_progress:z58.number().int().nonnegative(),waiting:z58.number().int().nonnegative(),resolved:z58.number().int().nonnegative(),duplicate:z58.number().int().nonnegative(),irrelevant:z58.number().int().nonnegative(),ignored:z58.number().int().nonnegative()}),limit:z58.number().int().positive(),offset:z58.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z58.object({id:z58.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z58.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z59}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=z59.iso.datetime({offset:!0}).pipe(z59.coerce.date()),OpsRecentChatInputSchema=z59.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z59.string().trim().min(1).max(255).optional(),limit:z59.coerce.number().int().min(1).max(200).default(100),cursor:z59.string().trim().min(1).max(2e3).optional(),slim:z59.boolean().default(!0),reason:z59.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=z59.object({id:z59.string(),threadId:z59.string(),providerMessageId:z59.string().nullable(),invocationId:z59.string().nullable(),env:z59.string().nullable(),role:z59.string(),parts:z59.array(z59.record(z59.string(),z59.unknown())),metadata:z59.object({status:z59.string().optional(),traceUrl:z59.string().optional(),externalFileChanges:z59.array(z59.unknown()).optional()}),stats:z59.object({toolCount:z59.number().int().nonnegative(),failedToolCount:z59.number().int().nonnegative()}),createdAt:z59.iso.datetime({offset:!0}),project:z59.object({id:z59.string(),name:z59.string(),displayName:z59.string().nullable(),organizationId:z59.string().nullable()})}),OpsRecentChatResponseSchema=z59.object({target:z59.object({backendProfile:OpsBackendProfileSchema,projectEnv:z59.string().nullable()}),window:z59.object({from:z59.iso.datetime({offset:!0}),to:z59.iso.datetime({offset:!0})}),messages:z59.object({items:z59.array(OpsRecentChatMessageSchema),nextCursor:z59.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z60}from"zod";var OpsSentryIssueResolutionResponseSchema,OpsSentryIssueResolutionResponseDTO,OpsSentryIssueResolutionErrorResponseSchema,OpsSentryIssueResolutionErrorResponseDTO,init_ops_sentry_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-sentry.dto.js"(){"use strict";init_ops();init_create_dto();OpsSentryIssueResolutionResponseSchema=z60.object({backendProfile:OpsBackendProfileSchema,provider:z60.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z60.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z60.object({backendProfile:OpsBackendProfileSchema,provider:z60.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z60.literal(!1),reason:z60.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z61}from"zod";function createAgentRunWebhookEventDataSchema(status){return z61.object({run:z61.object({id:z61.string(),agentName:z61.string(),trigger:z61.string(),status:z61.literal(status),startedAt:z61.string().nullable(),finishedAt:z61.string().nullable(),reason:z61.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEnvironmentSelectorSchema,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_environment();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=z61.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z61.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z61.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z61.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z61.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),WebhookEntryBatchWindowSecondsSchema=z61.union([z61.literal(0),z61.literal(5),z61.literal(30),z61.literal(60)]),EntryChangedWebhookEventDataSchema=z61.object({reason:WebhookEntryChangeReasonSchema,operationId:z61.string().optional(),batch:z61.object({index:z61.number().int().positive(),total:z61.number().int().positive()}).optional(),changes:z61.array(z61.object({action:WebhookEntryChangeActionSchema,contentType:z61.string(),id:z61.string(),documentId:z61.string(),locale:z61.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z61.object({form:z61.object({id:z61.string(),label:z61.string()}),submission:z61.object({id:z61.string(),data:z61.record(z61.string(),z61.unknown()),submittedAt:z61.string()})}),PublishStartedWebhookEventDataSchema=z61.object({publication:z61.object({status:z61.literal("publishing"),startedAt:z61.string()})}),PublishSucceededWebhookEventDataSchema=z61.object({publication:z61.object({status:z61.literal("published"),url:z61.string(),publishedAt:z61.string(),firstPublish:z61.boolean()})}),PublishFailedWebhookEventDataSchema=z61.object({publication:z61.object({status:z61.literal("failed"),reason:z61.string()})}),PublishUnpublishedWebhookEventDataSchema=z61.object({publication:z61.object({previousUrl:z61.string(),unpublishedAt:z61.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z61.object({review:z61.object({id:z61.string(),runId:z61.string(),agentName:z61.string(),classification:z61.string(),summary:z61.string(),reasons:z61.array(z61.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z61.object({review:z61.object({id:z61.string(),runId:z61.string(),agentName:z61.string(),resolution:z61.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z61.object({report:z61.object({weekStart:z61.string(),weekEnd:z61.string(),pageviews:z61.number(),visitors:z61.number(),previousPageviews:z61.number(),previousVisitors:z61.number()})}),MediaAssetWebhookEventDataSchema=z61.object({id:z61.string().nullable(),name:z61.string().nullable(),type:z61.string(),mimeType:z61.string().nullable(),fileSize:z61.number().nullable()}),MediaUploadedWebhookEventDataSchema=z61.object({asset:MediaAssetWebhookEventDataSchema,operation:z61.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z61.object({asset:MediaAssetWebhookEventDataSchema,operation:z61.enum(["updated","moved","analysis"]),analysis:z61.object({category:z61.string(),status:z61.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z61.object({asset:MediaAssetWebhookEventDataSchema,operation:z61.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z61.object({asset:MediaAssetWebhookEventDataSchema,operation:z61.literal("generated"),generation:z61.object({model:z61.string(),mode:z61.string()})}),MediaProcessingFailedWebhookEventDataSchema=z61.object({asset:MediaAssetWebhookEventDataSchema,operation:z61.enum(["analysis","generation"]),failure:z61.object({code:z61.string()})}),DomainCreatedWebhookEventDataSchema=z61.object({domain:z61.object({id:z61.string(),hostname:z61.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z61.object({domain:z61.object({id:z61.string(),hostname:z61.string()})}),LabelChangedWebhookEventDataSchema=z61.object({changes:z61.array(z61.object({action:z61.enum(["created","updated","deleted"]),key:z61.string(),locale:z61.string(),value:z61.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z61.object({locale:z61.object({code:z61.string(),isDefault:z61.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z61.object({locale:z61.object({code:z61.string(),previousCode:z61.string()})}),LocaleDeletedWebhookEventDataSchema=z61.object({locale:z61.object({code:z61.string(),entriesDeleted:z61.number().int().nonnegative(),labelsDeleted:z61.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z61.object({environment:z61.object({name:EnvSchema,parent:EnvSchema})}),EnvironmentDeletedWebhookEventDataSchema=z61.object({environment:z61.object({name:EnvSchema})}),EnvironmentMergedWebhookEventDataSchema=z61.object({merge:z61.object({id:z61.string(),from:EnvSchema,to:EnvSchema,applied:z61.array(z61.object({surface:SurfaceNameSchema,count:z61.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z61.object({environment:z61.object({name:EnvSchema}),version:z61.object({versionId:z61.uuid(),name:z61.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=z61.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z61.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z61.discriminatedUnion("source",[z61.object({source:z61.literal("literal"),value:z61.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z61.object({source:z61.literal("secret"),key:z61.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z61.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z61.object({name:z61.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z61.object({name:z61.string(),source:z61.enum(["literal","secret"]),secretKey:z61.string().nullable(),secretPrefix:z61.string().nullable(),configured:z61.literal(!0)}),WebhookFilterSchema=z61.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z61.string().min(1).max(255).optional(),agentName:z61.string().min(1).max(120).optional(),mediaType:z61.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z61.string().min(1).max(255).optional(),locale:z61.string().min(1).max(120).optional()}),JsonValueSchema=z61.lazy(()=>z61.union([z61.string(),z61.number(),z61.boolean(),z61.null(),z61.array(JsonValueSchema),z61.record(z61.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z61.object({name:z61.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z61.url(),enabled:z61.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z61.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z61.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z61.object({name:z61.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z61.url().optional(),enabled:z61.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z61.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z61.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z61.object({eventType:WebhookEventTypeSchema.optional(),data:z61.record(z61.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z61.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z61.uuid(),name:z61.string(),eventType:WebhookEventTypeSchema,enabled:z61.boolean(),destination:z61.object({host:z61.string(),maskedUrl:z61.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z61.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z61.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z61.coerce.date().nullable(),deliveryStats24h:z61.object({succeeded:z61.number().int().nonnegative(),failed:z61.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z61.uuid(),projectId:z61.uuid(),env:EnvSchema,environment:EnvironmentKeySchema,branch:EnvSchema,eventId:z61.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z61.number().int().positive(),test:z61.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z61.number().int().nonnegative(),responseStatus:z61.number().int().nullable(),lastErrorCode:z61.string().nullable(),lastErrorMessage:z61.string().nullable(),payloadAvailable:z61.boolean(),destination:z61.object({host:z61.string(),maskedUrl:z61.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z61.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z61.string().nullable(),qstashMessageId:z61.string().nullable(),deliveredAt:z61.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z61.object({items:z61.array(WebhookDeliveryDTOSchema),pagination:z61.object({page:z61.number().int().positive(),limit:z61.number().int().positive(),total:z61.number().int().nonnegative(),totalPages:z61.number().int().positive(),hasMore:z61.boolean()}),stats:z61.object({total:z61.number().int().nonnegative(),succeeded:z61.number().int().nonnegative(),failed:z61.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z61.object({id:z61.uuid(),deliveryId:z61.uuid(),attempt:z61.number().int().positive(),status:z61.enum(["delivering","succeeded","failed"]),responseStatus:z61.number().int().nullable(),durationMs:z61.number().int().nonnegative(),responseExcerpt:z61.string().nullable(),errorCode:z61.string().nullable(),errorMessage:z61.string().nullable(),createdAt:z61.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z61.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z61.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z62}from"zod";var PreviewFeatureDTOSchema,PreviewFeatureDTO,init_preview_feature_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/preview-feature.dto.js"(){"use strict";init_create_dto();PreviewFeatureDTOSchema=z62.object({key:z62.literal("fimo-2"),enabled:z62.boolean(),dismissed:z62.boolean().default(!1),interacted:z62.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z63}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=z63.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z63.object({total:z63.number(),base:z63.number(),purchases:z63.number(),awards:z63.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z63.object({id:z63.string(),name:z63.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z63.object({type:z63.string(),brand:z63.string().nullable(),last4:z63.string().nullable(),expirationDate:z63.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z63.object({currency:z63.string(),nextPaymentAmount:z63.number().nullable(),nextPaymentAt:z63.string().nullable(),billingInterval:z63.string().nullable(),totalAmount:z63.number().nullable(),discountAmount:z63.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z63.object({id:z63.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z63.string().nullable(),currentPeriodEndsAt:z63.string().nullable(),renewsAt:z63.string().nullable(),cancelAt:z63.string().nullable(),renewAutomatically:z63.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z63.object({type:z63.enum(["low_balance","critical_balance","approaching_limit"]),message:z63.string(),estimatedPromptsRemaining:z63.number().nullable(),avgCostPerPrompt:z63.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z63.object({monthlyCredits:z63.number().nullable(),usedThisPeriod:z63.number(),remainingThisPeriod:z63.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z63.object({organizationId:z63.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z63.string().nullable(),tenureDays:z63.number().int().nonnegative(),capturedAt:z63.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z63.object({hasSubscription:z63.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z63.number().nullable(),alerts:z63.array(CreditAlertDTOSchema),portalUrl:z63.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z63.object({creditCount:z63.number().int().positive(),expiresAt:z63.string().datetime().nullable().optional(),message:z63.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z63.literal("free"),amountCents:z63.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z63.literal("purchase"),amountCents:z63.number().int().positive()}),CreditTopupRequestDTOSchema=z63.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z63.object({success:z63.boolean(),transactionId:z63.string().nullable(),newBalance:z63.number(),creditCount:z63.number(),type:z63.enum(["free","purchase"]),invoiceId:z63.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z64}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=z64.object({totalCredits:z64.number(),totalCostUsd:z64.number(),totalMessages:z64.number(),avgCostPerMessage:z64.number(),periodStart:z64.string().nullable(),periodEnd:z64.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z64.object({projectId:z64.string(),projectName:z64.string(),projectDisplayName:z64.string().nullable(),credits:z64.number(),costUsd:z64.number(),messages:z64.number(),percentage:z64.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z64.object({userId:z64.string(),userName:z64.string().nullable(),userEmail:z64.string().email().nullable(),credits:z64.number(),costUsd:z64.number(),messages:z64.number(),percentage:z64.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z64.object({date:z64.string(),credits:z64.number(),costUsd:z64.number(),messages:z64.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z64.object({userId:z64.string(),userName:z64.string().nullable(),userEmail:z64.string().email().nullable(),credits:z64.number(),costUsd:z64.number(),messages:z64.number(),percentage:z64.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z64.object({projectId:z64.string(),projectName:z64.string(),projectDisplayName:z64.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z64.array(UsageByUserForProjectDTOSchema),timeline:z64.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z64.object({summary:UsageSummaryDTOSchema,byProject:z64.array(UsageByProjectDTOSchema),byUser:z64.array(UsageByUserDTOSchema),timeline:z64.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z65}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=z65.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z65.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z65.object({startDate:z65.string().optional(),endDate:z65.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z65.coerce.number().int().positive().default(1),limit:z65.coerce.number().int().positive().max(100).default(20),sortBy:z65.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z65.string().optional(),activeOnly:z65.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z65.object({totalCredits:z65.number(),totalCostUsd:z65.number(),totalMessages:z65.number(),avgCostPerMessage:z65.number(),avgCreditsPerMessage:z65.number(),periodStart:z65.string(),periodEnd:z65.string(),creditsChange:z65.number().nullable(),costChange:z65.number().nullable(),messagesChange:z65.number().nullable(),unattributedCredits:z65.number(),unattributedCostUsd:z65.number(),unattributedMessages:z65.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z65.object({date:z65.string(),credits:z65.number(),costUsd:z65.number(),messages:z65.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z65.object({organizationId:z65.string(),organizationName:z65.string(),credits:z65.number(),costUsd:z65.number(),messages:z65.number(),percentage:z65.number(),userCount:z65.number(),projectCount:z65.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z65.object({userId:z65.string(),userName:z65.string().nullable(),userEmail:z65.string().nullable(),userImage:z65.string().nullable(),organizationId:z65.string().nullable(),organizationName:z65.string().nullable(),credits:z65.number(),costUsd:z65.number(),messages:z65.number(),percentage:z65.number(),projectCount:z65.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z65.object({projectId:z65.string(),projectName:z65.string(),projectDisplayName:z65.string().nullable(),organizationId:z65.string(),organizationName:z65.string(),credits:z65.number(),costUsd:z65.number(),messages:z65.number(),percentage:z65.number(),userCount:z65.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z65.object({id:z65.string(),name:z65.string(),value:z65.number(),percentage:z65.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z65.object({day:z65.number(),hour:z65.number(),value:z65.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z65.object({summary:UsageOverviewSummaryDTOSchema,timeline:z65.array(UsageTimelinePointDTOSchema),topOrganizations:z65.array(OrganizationUsageRowDTOSchema),topUsers:z65.array(UserUsageRowDTOSchema),topProjects:z65.array(ProjectUsageRowDTOSchema),creditDistribution:z65.array(UsageDistributionItemDTOSchema),userDistribution:z65.array(UsageDistributionItemDTOSchema),heatmap:z65.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z65.object({page:z65.number(),limit:z65.number(),totalItems:z65.number(),totalPages:z65.number(),hasMore:z65.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z65.object({organizations:z65.array(OrganizationUsageRowDTOSchema),top:z65.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z65.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z65.object({users:z65.array(ExtendedUserUsageRowDTOSchema),top:z65.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z65.string(),ownerName:z65.string().nullable(),ownerEmail:z65.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z65.object({projects:z65.array(ExtendedProjectUsageRowDTOSchema),top:z65.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z65.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z65.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z65.object({credits:z65.number(),costUsd:z65.number(),messages:z65.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z65.object({id:z65.string(),name:z65.string(),createdAt:z65.string(),memberCount:z65.number(),projectCount:z65.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z65.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z65.object({id:z65.string(),name:z65.string().nullable(),email:z65.string(),image:z65.string().nullable(),createdAt:z65.string(),organizationCount:z65.number(),projectCount:z65.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z65.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z65.object({id:z65.string(),name:z65.string(),displayName:z65.string().nullable(),createdAt:z65.string(),organizationId:z65.string(),organizationName:z65.string(),ownerId:z65.string(),ownerName:z65.string().nullable(),ownerEmail:z65.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z65.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z66}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=z66.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z66.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z66.object({command:z66.string().min(1).max(1e4),cwd:z66.string().optional(),projectEnv:EnvSchema.optional(),env:z66.record(z66.string(),z66.string()).optional(),name:z66.string().optional(),waitForCompletion:z66.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z66.object({identifier:z66.string(),status:SandboxProcessStatusSchema,command:z66.string().optional(),startedAt:z66.string().optional(),exitCode:z66.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z66.object({processes:z66.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z66.object({processId:z66.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z66.object({success:z66.boolean(),message:z66.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z67}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_environment();init_realtime();init_references();init_content_fields();init_audit_log();init_ops();init_chat_block();init_fimo_config();init_project_dto();init_project_env_dto();init_project_environment_dto();init_project_secret_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_list_item_dto();init_agent_run_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_schedule_notifications_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_ops_sentry_dto();init_webhook_dto();init_preview_feature_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto()}});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 buildSkipsVersionCheck(cliRoot=CLI_ROOT,readFile6=defaultReadFile){try{return JSON.parse(readFile6(path2.join(cliRoot,"release.json"))).skipVersionCheck===!0}catch{return!1}}function defaultReadFile(file){return fs3.readFileSync(file,"utf8")}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||buildSkipsVersionCheck(cliRoot))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(buildSkipsVersionCheck,"buildSkipsVersionCheck");__name(defaultReadFile,"defaultReadFile");__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:path49,message}=issue;return`${Array.isArray(path49)&&path49.length>0?`${path49.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}function recoverTenantApiBaseUrl(tenantApiUrl,projectId,env){try{let normalized=tenantApiUrl.replace(/\/$/,""),url=new URL(normalized),prefix=`${projectId}-${envResourceKey(env)}.`;if(!url.hostname.startsWith(prefix))return;url.hostname=url.hostname.slice(prefix.length);let base=url.toString().replace(/\/$/,"");return buildTenantApiUrl(projectId,env,base)===normalized?base:void 0}catch{return}}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_esm();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,path49,status,detail,code2,body){super(`API ${method} ${path49} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path49,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");__name(recoverTenantApiBaseUrl,"recoverTenantApiBaseUrl");FimoApiClient=class _FimoApiClient{constructor(cfg=loadConfig()){this.cfg=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(path49,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}${path49}`,{...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",path49,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async fetchRaw(path49,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);return 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),fimoFetch(`${this.cfg.apiUrl}${path49}`,{...init,headers})}async rawRequest(path49,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}${path49}`,{...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"} ${path49} 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/${encodeEnvPathSegment(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/${encodeEnvPathSegment(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 listProjectVersions(projectId,options){let params=new URLSearchParams({limit:String(options.limit)});return options.cursor&¶ms.set("cursor",options.cursor),(await this.request(`${this.projectEnvManagementPath(projectId,"/versions")}?${params.toString()}`)).data}async getProjectHistorySummary(projectId){return(await this.request(this.projectEnvManagementPath(projectId,"/versions/summary"))).data}async getProjectVersion(projectId,versionId){return(await this.request(this.projectEnvManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}`))).data}async createProjectVersion(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/versions"),{method:"POST",body:JSON.stringify(input)})).data}async restoreProjectVersion(projectId,versionId){return(await this.request(this.projectEnvManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}/restore`),{method:"POST"})).data}async listProjectSecretEntries(projectId,opts){let query=new URLSearchParams({environment:opts.environment});return opts.kind&&query.set("kind",opts.kind),(await this.request(`/api/management/projects/${projectId}/secrets?${query.toString()}`)).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,environment:input.environment})})).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,environment:input.environment})})).data}async deleteProjectSecretEntry(projectId,key,kind,environment){let qs=new URLSearchParams({kind,environment});await this.request(`/api/management/projects/${projectId}/secrets/${encodeURIComponent(key)}?${qs.toString()}`,{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 getSchedulesOverview(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules/overview`)).data}async getSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`)).data}async updateSchedule(projectId,scheduleId,request){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"PATCH",body:JSON.stringify(request)})).data}async setScheduleEnabled(projectId,scheduleId,enabled){let action=enabled?"resume":"pause";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/${action}`,{method:"POST"})).data}async runSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/run`,{method:"POST",body:JSON.stringify({trigger:"cli"})})).data}async listScheduleRuns(projectId,scheduleId,query={}){let params=new URLSearchParams;query.limit!==void 0&¶ms.set("limit",String(query.limit)),query.cursor&¶ms.set("cursor",query.cursor),query.status&¶ms.set("status",query.status);let suffix=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/runs${suffix}`)).data}async getScheduleRun(projectId,runId){return(await this.request(`/api/management/projects/${projectId}/schedules/runs/${encodeURIComponent(runId)}`)).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 listProjectEnvironments(projectId){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments`)).data}async createProjectEnvironment(projectId,input){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments`,{method:"POST",body:JSON.stringify(input)},{allow403:!0})).data}async updateProjectEnvironment(projectId,environmentId,input){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(environmentId)}`,{method:"PATCH",body:JSON.stringify(input)},{allow403:!0})).data}async deleteProjectEnvironment(projectId,environmentId){return(await this.request(`/api/management/projects/${encodeURIComponent(projectId)}/environments/${encodeURIComponent(environmentId)}`,{method:"DELETE"},{allow403:!0})).data}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,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"DELETE"})).data}async listEnvs(projectId,opts={}){let params=new URLSearchParams;opts.includeDeleted&¶ms.set("includeDeleted","true"),opts.includeAgentEnvs&¶ms.set("includeAgentEnvs","true");let qs=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/envs${qs}`)).data}async resolveProjectEnvironmentKey(projectId,branch){if(branch==="prod")return PRODUCTION_ENVIRONMENT_KEY;let branches=await this.listEnvs(projectId,{includeAgentEnvs:!0}),current=branches.find(candidate=>candidate.env===branch),visited=new Set;for(;current&&!visited.has(current.env);){if(visited.add(current.env),current.resolvedEnvironment)return current.resolvedEnvironment.id;current=current.parentEnv?branches.find(candidate=>candidate.env===current?.parentEnv):void 0}return PREVIEW_ENVIRONMENT_KEY}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,path49,opts={}){let qs=lazyFetchQs(opts.against,{path:path49});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),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async getSchemaTypeDiff(projectId,env,typeName,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async getAssetDiff(projectId,env,assetId,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async getTranslationRowDiff(projectId,env,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).data}async getFormSchemaDiff(projectId,env,formName,opts={}){let qs=lazyFetchQs(opts.against),path49=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path49}?${qs}`:path49)).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 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){let remote=(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-remote`,{},{allow403:!0})).data;if(!remote.tenantApiBaseUrl){let recovered=recoverTenantApiBaseUrl(remote.tenantApiUrl,projectId,env);if(recovered)return{...remote,tenantApiBaseUrl:recovered}}return remote}async getProjectLocaleStats(projectId){return(await this.request(this.projectEnvManagementPath(projectId,"/locales/stats"))).data}async addProjectLocale(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/locales"),{method:"POST",body:JSON.stringify(input)})).data}async setProjectDefaultLocale(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/locales/default"),{method:"PUT",body:JSON.stringify(input)})).data}async removeProjectLocale(projectId,locale){return(await this.request(this.projectEnvManagementPath(projectId,`/locales/${encodeURIComponent(locale)}`),{method:"DELETE"})).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/${encodeEnvPathSegment(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,7 +192,7 @@ alwaysApply: true
|
|
|
192
192
|
|
|
193
193
|
${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=path6.join(targetDir,"AGENTS.md");if(!fs6.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=fs6.readFileSync(agentsMdPath,"utf8");return writePerAgentVariants(targetDir,agents,agentsMdContent)}function detectAgentsInProject(cwd){let detected=[];return fs6.existsSync(path6.join(cwd,"CLAUDE.md"))&&detected.push("claude-code"),fs6.existsSync(path6.join(cwd,".cursor","rules","fimo.mdc"))&&detected.push("cursor"),fs6.existsSync(path6.join(cwd,".windsurfrules"))&&detected.push("windsurf"),fs6.existsSync(path6.join(cwd,"GEMINI.md"))&&detected.push("gemini-cli"),detected}var AGENT_TEMPLATES_ROOT,EXCLUDED_DIRS,TemplateFrameworkError,init_scaffold=__esm({"src/cli/utils/scaffold.ts"(){init_templates();init_config();init_templates();AGENT_TEMPLATES_ROOT=path6.resolve(CLI_ROOT,"assets","agent-templates"),EXCLUDED_DIRS=new Set(["node_modules","dist","build",".turbo",".git"]),TemplateFrameworkError=class extends Error{static{__name(this,"TemplateFrameworkError")}constructor(message){super(message),this.name="TemplateFrameworkError"}};__name(resolveTemplateFramework,"resolveTemplateFramework");__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")}});function colorEnabled(opts={}){if(opts.forceDisable)return!1;let env=opts.env??process.env;return env.NO_COLOR&&env.NO_COLOR.length>0?!1:env.FORCE_COLOR&&env.FORCE_COLOR!=="0"&&env.FORCE_COLOR!=="false"?!0:(opts.isTTY??process.stdout.isTTY??!1)===!0}function makeColorPalette(opts={}){let on=colorEnabled(opts),wrap2=__name(style=>s=>on?`${ANSI[style]}${s}${ANSI.reset}`:s,"wrap");return{enabled:on,bold:wrap2("bold"),dim:wrap2("dim"),red:wrap2("red"),green:wrap2("green"),yellow:wrap2("yellow"),blue:wrap2("blue"),magenta:wrap2("magenta"),cyan:wrap2("cyan"),gray:wrap2("gray")}}var ANSI,palette,init_color=__esm({"src/cli/utils/format/color.ts"(){ANSI={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m"};__name(colorEnabled,"colorEnabled");__name(makeColorPalette,"makeColorPalette");palette=makeColorPalette()}});function isCliAuthError(err){return err instanceof NotAuthenticatedError||err instanceof UnauthorizedError||err instanceof PermissionDeniedError}function rethrowCliAuthError(err,beforeThrow){if(isCliAuthError(err))throw beforeThrow?.(err),err}function retryCommand(args=process.argv.slice(2)){return["fimo",...args].map(formatShellArg).join(" ")}function formatCliAuthError(err,opts={}){let p2=opts.palette??palette,command=retryCommand(opts.args);if(err instanceof PermissionDeniedError)return[`${p2.red("\u2717")} You don't have permission to run this command.`,"",err.required.length?` Missing permission: ${p2.bold(err.required.join(", "))}`:" Your role on this project does not allow this action."," Ask a project admin for access, or use an account with a higher role.","",p2.dim(` Backend: ${err.apiUrl}`)].join(`
|
|
194
194
|
`);let expired=err instanceof UnauthorizedError,intro=expired?"Your Fimo session is expired or invalid.":"You're not signed in to Fimo.",loginVerb=expired?"refresh your session":"sign in";return[`${p2.red("\u2717")} ${intro}`,"",` Run this to ${loginVerb}:`,` ${p2.bold("fimo login")}`,""," Then retry:",` ${p2.bold(command)}`,"",p2.dim(` Backend: ${err.apiUrl}`)].join(`
|
|
195
|
-
`)}function renderCliAuthError(err,opts={}){console.error(formatCliAuthError(err,opts))}function formatShellArg(arg){return/^[A-Za-z0-9_/:=.,@%+-]+$/.test(arg)?arg:`'${arg.replace(/'/g,"'\\''")}'`}var init_auth_errors=__esm({"src/cli/utils/auth-errors.ts"(){init_api();init_auth();init_color();__name(isCliAuthError,"isCliAuthError");__name(rethrowCliAuthError,"rethrowCliAuthError");__name(retryCommand,"retryCommand");__name(formatCliAuthError,"formatCliAuthError");__name(renderCliAuthError,"renderCliAuthError");__name(formatShellArg,"formatShellArg")}});function detectProjectLayout(paths){let hasCurrentProject=!1,hasLegacyProject=!1,hasCurrentMarker=!1,hasLegacyMarker=!1;for(let input of paths){let file=input.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/$/,"");hasCurrentProject||=file===CURRENT_PROJECT_LAYOUT.project,hasLegacyProject||=file===LEGACY_PROJECT_LAYOUT.project,hasCurrentMarker||=file===CURRENT_PROJECT_LAYOUT.config||file===CURRENT_PROJECT_LAYOUT.agents||file.startsWith(`${CURRENT_PROJECT_LAYOUT.agents}/`),hasLegacyMarker||=file===LEGACY_PROJECT_LAYOUT.config||file===LEGACY_AGENT_POLICY_PATH}return hasCurrentProject?"current":hasLegacyProject?"legacy":hasCurrentMarker?"current":hasLegacyMarker?"legacy":null}function getProjectLayoutPaths(layout){return layout==="current"?CURRENT_PROJECT_LAYOUT:LEGACY_PROJECT_LAYOUT}function selectProjectConfigPath(paths,layout){let files=new Set(Array.from(paths,file=>file.replace(/\\/g,"/").replace(/^\.\//,"")));return(layout??detectProjectLayout(files)??"current")==="current"?CURRENT_PROJECT_LAYOUT.config:files.has(LEGACY_AGENT_POLICY_PATH)&&!files.has(LEGACY_PROJECT_LAYOUT.config)?LEGACY_AGENT_POLICY_PATH:LEGACY_PROJECT_LAYOUT.config}function selectProjectPolicyPath(paths,layout){let files=new Set(Array.from(paths,file=>file.replace(/\\/g,"/").replace(/^\.\//,"")));return(layout??detectProjectLayout(files)??"current")==="current"?CURRENT_PROJECT_LAYOUT.config:files.has(LEGACY_AGENT_POLICY_PATH)?LEGACY_AGENT_POLICY_PATH:LEGACY_PROJECT_LAYOUT.config}var CURRENT_PROJECT_LAYOUT,LEGACY_PROJECT_LAYOUT,LEGACY_AGENT_POLICY_PATH,init_project_layout=__esm({"src/runtime/project-layout.ts"(){CURRENT_PROJECT_LAYOUT={project:".fimo/project.json",config:".fimo/config.json",agents:".fimo/agents"},LEGACY_PROJECT_LAYOUT={project:".fimo.settings.json",config:"fimo-config.json",agents:"agents"},LEGACY_AGENT_POLICY_PATH="fimo.config.json";__name(detectProjectLayout,"detectProjectLayout");__name(getProjectLayoutPaths,"getProjectLayoutPaths");__name(selectProjectConfigPath,"selectProjectConfigPath");__name(selectProjectPolicyPath,"selectProjectPolicyPath")}});import fs7 from"node:fs";import path7 from"node:path";function existingLayoutPaths(cwd){return[CURRENT_PROJECT_LAYOUT.project,CURRENT_PROJECT_LAYOUT.config,CURRENT_PROJECT_LAYOUT.agents,LEGACY_PROJECT_LAYOUT.project,LEGACY_PROJECT_LAYOUT.config,LEGACY_AGENT_POLICY_PATH].filter(file=>fs7.existsSync(path7.join(cwd,file)))}function detectProjectLayoutAtRoot(cwd){return detectProjectLayout(existingLayoutPaths(cwd))}function resolveProjectLayoutPaths(cwd,fallback="current"){return getProjectLayoutPaths(detectProjectLayoutAtRoot(cwd)??fallback)}function resolveProjectSettingsPath(cwd){return path7.join(cwd,resolveProjectLayoutPaths(cwd).project)}function resolveProjectConfigPath(cwd){let files=existingLayoutPaths(cwd);return path7.join(cwd,selectProjectConfigPath(files,detectProjectLayout(files)))}function resolveProjectPolicyPath(cwd){let files=existingLayoutPaths(cwd);return path7.join(cwd,selectProjectPolicyPath(files,detectProjectLayout(files)))}function resolveProjectAgentsDir(cwd){return path7.join(cwd,resolveProjectLayoutPaths(cwd).agents)}function loadProjectSettings(cwd){let settingsPath=resolveProjectSettingsPath(cwd);if(!fs7.existsSync(settingsPath))throw new Error("You are not in a Fimo project. Run `fimo create` to start one, or cd into a linked project.");return JSON.parse(fs7.readFileSync(settingsPath,"utf-8"))}function findProjectRoot(start){let dir=path7.resolve(start);for(;;){if(fs7.existsSync(path7.join(dir,CURRENT_PROJECT_LAYOUT.project))||fs7.existsSync(path7.join(dir,LEGACY_PROJECT_LAYOUT.project)))return dir;let parent2=path7.dirname(dir);if(parent2===dir)return null;dir=parent2}}function resolveProjectCwd(cwdOption){let start=path7.resolve(cwdOption??process.cwd());return findProjectRoot(start)??start}var init_project=__esm({"src/cli/utils/project.ts"(){init_project_layout();__name(existingLayoutPaths,"existingLayoutPaths");__name(detectProjectLayoutAtRoot,"detectProjectLayoutAtRoot");__name(resolveProjectLayoutPaths,"resolveProjectLayoutPaths");__name(resolveProjectSettingsPath,"resolveProjectSettingsPath");__name(resolveProjectConfigPath,"resolveProjectConfigPath");__name(resolveProjectPolicyPath,"resolveProjectPolicyPath");__name(resolveProjectAgentsDir,"resolveProjectAgentsDir");__name(loadProjectSettings,"loadProjectSettings");__name(findProjectRoot,"findProjectRoot");__name(resolveProjectCwd,"resolveProjectCwd")}});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,{includeAgentEnvs:!0})).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
|
+
`)}function renderCliAuthError(err,opts={}){console.error(formatCliAuthError(err,opts))}function formatShellArg(arg){return/^[A-Za-z0-9_/:=.,@%+-]+$/.test(arg)?arg:`'${arg.replace(/'/g,"'\\''")}'`}var init_auth_errors=__esm({"src/cli/utils/auth-errors.ts"(){init_api();init_auth();init_color();__name(isCliAuthError,"isCliAuthError");__name(rethrowCliAuthError,"rethrowCliAuthError");__name(retryCommand,"retryCommand");__name(formatCliAuthError,"formatCliAuthError");__name(renderCliAuthError,"renderCliAuthError");__name(formatShellArg,"formatShellArg")}});function detectProjectLayout(paths){let hasCurrentProject=!1,hasLegacyProject=!1,hasCurrentMarker=!1,hasLegacyMarker=!1;for(let input of paths){let file=input.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/$/,"");hasCurrentProject||=file===CURRENT_PROJECT_LAYOUT.project,hasLegacyProject||=file===LEGACY_PROJECT_LAYOUT.project,hasCurrentMarker||=file===CURRENT_PROJECT_LAYOUT.config||file===CURRENT_PROJECT_LAYOUT.agents||file.startsWith(`${CURRENT_PROJECT_LAYOUT.agents}/`),hasLegacyMarker||=file===LEGACY_PROJECT_LAYOUT.config||file===LEGACY_AGENT_POLICY_PATH}return hasCurrentProject?"current":hasLegacyProject?"legacy":hasCurrentMarker?"current":hasLegacyMarker?"legacy":null}function getProjectLayoutPaths(layout){return layout==="current"?CURRENT_PROJECT_LAYOUT:LEGACY_PROJECT_LAYOUT}function selectProjectConfigPath(paths,layout){let files=new Set(Array.from(paths,file=>file.replace(/\\/g,"/").replace(/^\.\//,"")));return(layout??detectProjectLayout(files)??"current")==="current"?CURRENT_PROJECT_LAYOUT.config:files.has(LEGACY_AGENT_POLICY_PATH)&&!files.has(LEGACY_PROJECT_LAYOUT.config)?LEGACY_AGENT_POLICY_PATH:LEGACY_PROJECT_LAYOUT.config}function selectProjectPolicyPath(paths,layout){let files=new Set(Array.from(paths,file=>file.replace(/\\/g,"/").replace(/^\.\//,"")));return(layout??detectProjectLayout(files)??"current")==="current"?CURRENT_PROJECT_LAYOUT.config:files.has(LEGACY_AGENT_POLICY_PATH)?LEGACY_AGENT_POLICY_PATH:LEGACY_PROJECT_LAYOUT.config}var CURRENT_PROJECT_LAYOUT,LEGACY_PROJECT_LAYOUT,LEGACY_AGENT_POLICY_PATH,init_project_layout=__esm({"src/runtime/project-layout.ts"(){CURRENT_PROJECT_LAYOUT={project:".fimo/project.json",config:".fimo/config.json",agents:".fimo/agents"},LEGACY_PROJECT_LAYOUT={project:".fimo.settings.json",config:"fimo-config.json",agents:"agents"},LEGACY_AGENT_POLICY_PATH="fimo.config.json";__name(detectProjectLayout,"detectProjectLayout");__name(getProjectLayoutPaths,"getProjectLayoutPaths");__name(selectProjectConfigPath,"selectProjectConfigPath");__name(selectProjectPolicyPath,"selectProjectPolicyPath")}});import fs7 from"node:fs";import path7 from"node:path";function existingLayoutPaths(cwd){return[CURRENT_PROJECT_LAYOUT.project,CURRENT_PROJECT_LAYOUT.config,CURRENT_PROJECT_LAYOUT.agents,LEGACY_PROJECT_LAYOUT.project,LEGACY_PROJECT_LAYOUT.config,LEGACY_AGENT_POLICY_PATH].filter(file=>fs7.existsSync(path7.join(cwd,file)))}function detectProjectLayoutAtRoot(cwd){return detectProjectLayout(existingLayoutPaths(cwd))}function resolveProjectLayoutPaths(cwd,fallback="current"){return getProjectLayoutPaths(detectProjectLayoutAtRoot(cwd)??fallback)}function resolveProjectSettingsPath(cwd){return path7.join(cwd,resolveProjectLayoutPaths(cwd).project)}function resolveProjectConfigPath(cwd){let files=existingLayoutPaths(cwd);return path7.join(cwd,selectProjectConfigPath(files,detectProjectLayout(files)))}function resolveProjectPolicyPath(cwd){let files=existingLayoutPaths(cwd);return path7.join(cwd,selectProjectPolicyPath(files,detectProjectLayout(files)))}function resolveProjectAgentsDir(cwd){return path7.join(cwd,resolveProjectLayoutPaths(cwd).agents)}function loadProjectSettings(cwd){let settingsPath=resolveProjectSettingsPath(cwd);if(!fs7.existsSync(settingsPath))throw new Error("You are not in a Fimo project. Run `fimo create` to start one, or cd into a linked project.");return JSON.parse(fs7.readFileSync(settingsPath,"utf-8"))}function findProjectRoot(start){let dir=path7.resolve(start);for(;;){if(fs7.existsSync(path7.join(dir,CURRENT_PROJECT_LAYOUT.project))||fs7.existsSync(path7.join(dir,LEGACY_PROJECT_LAYOUT.project)))return dir;let parent2=path7.dirname(dir);if(parent2===dir)return null;dir=parent2}}function resolveProjectCwd(cwdOption){let start=path7.resolve(cwdOption??process.cwd());return findProjectRoot(start)??start}var init_project=__esm({"src/cli/utils/project.ts"(){init_project_layout();__name(existingLayoutPaths,"existingLayoutPaths");__name(detectProjectLayoutAtRoot,"detectProjectLayoutAtRoot");__name(resolveProjectLayoutPaths,"resolveProjectLayoutPaths");__name(resolveProjectSettingsPath,"resolveProjectSettingsPath");__name(resolveProjectConfigPath,"resolveProjectConfigPath");__name(resolveProjectPolicyPath,"resolveProjectPolicyPath");__name(resolveProjectAgentsDir,"resolveProjectAgentsDir");__name(loadProjectSettings,"loadProjectSettings");__name(findProjectRoot,"findProjectRoot");__name(resolveProjectCwd,"resolveProjectCwd")}});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,{includeAgentEnvs:!0})).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"?"--branch":ctx.source==="branch"?"git branch":ctx.source==="tag"?"git tag":"default",ro=ctx.readOnly?" \xB7 read-only":"";return`\u2192 Branch: ${ctx.env} (from ${sourceHint}${ro})`}function envOverrideFromCommand(cmd){let cur=cmd??void 0;for(;cur;){let options=cur.opts(),branch=options.branch;if(typeof branch=="string"&&branch.length>0)return branch;let env=options.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(string2,columns,options){return String(string2).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(string2=>{let words=string2.split(" "),last2=words.length;for(;last2&&!dist_default2(words[last2-1]);)last2--;return last2===words.length?string2:words.slice(0,last2).join(" ")+words.slice(last2).join("")},"stringVisibleTrimSpacesRight"),exec=__name((string2,columns,options={})=>{if(options.trim!==!1&&string2.trim()==="")return"";let returnValue="",escapeCode,escapeUrl,words=string2.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]===`
|
|
@@ -206,13 +206,13 @@ ${agentsMdContent}`;writeIfMissing(".cursor/rules/fimo.mdc",cursorContent)}retur
|
|
|
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,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,w2,_e,oe,ue,F,le,d2,E2,Ie,Ee,z73,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,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(),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"),z73=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,D)=>et2(h,G2,j2,D,$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",z73)} ${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",z73)} ${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(`
|
|
@@ -238,7 +238,7 @@ ${o}
|
|
|
238
238
|
`}}}}).prompt(),"bt"),Ve={light:w2("\u2500","-"),heavy:w2("\u2501","="),block:w2("\u2588","#")},re=__name((e,i)=>e.includes(`
|
|
239
239
|
`)?e.split(`
|
|
240
240
|
`).map(s=>i(s)).join(`
|
|
241
|
-
`):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",
|
|
241
|
+
`):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",z73)} ${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)}
|
|
242
242
|
`:""}${n}
|
|
243
243
|
`;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?`
|
|
244
244
|
${t("gray",d2)}`:""}`}default:{let c2=s?`${t("cyan",d2)} `:"",a=s?t("cyan",E2):"",l=o.split(`
|
|
@@ -354,7 +354,7 @@ return __eta.res;
|
|
|
354
354
|
`)}}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(string2){return string2.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&")}function getLineNo(str,index2){return str.slice(0,index2).split(`
|
|
355
355
|
`).length}function parse5(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,`
|
|
356
356
|
`).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 readFile2(path49){let res="";try{res=fs17.readFileSync(path49,"utf8")}catch(err){throw err?.code==="ENOENT"?new EtaFileResolutionError(`Could not find template: ${path49}`):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(parse5,"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=parse5,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(readFile2,"readFile");__name(resolvePath2,"resolvePath");__name(dirIsChild,"dirIsChild");absolutePathRegExp=/^\\|^\//,Eta=class extends Eta$1{static{__name(this,"Eta")}constructor(...args){super(...args),this.readFile=readFile2,this.resolvePath=resolvePath2}}}});import{existsSync as existsSync3}from"node:fs";import{dirname as dirname3,resolve as resolve3}from"node:path";import{fileURLToPath as fileURLToPath4}from"node:url";function assetPath(...segments){return resolve3(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=existsSync3(resolve3(HERE,"bundle.json")),PACKAGE_ROOT2=IS_BUNDLED?resolve3(HERE,"..",".."):resolve3(HERE,"..","..","..");__name(assetPath,"assetPath")}});import{existsSync as existsSync4,mkdirSync as mkdirSync2,readFileSync as readFileSync4,readdirSync as readdirSync2,unlinkSync,writeFileSync as writeFileSync2}from"node:fs";import{dirname as dirname4,join as join5,resolve as resolve4}from"node:path";function getFormFiles(formsDir){return existsSync4(formsDir)?readdirSync2(formsDir).filter(f=>f.endsWith(".json")).map(f=>join5(formsDir,f)):[]}function readForm(path49){try{return JSON.parse(readFileSync4(path49,"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, parse${pascal}FormData, submit${pascal}, FORM_ID as ${varName}FormId } from "./${form.name}";`),lines.push(`export type { ${pascal}Data } from "./${form.name}";`)}return lines.push(""),lines.join(`
|
|
357
|
-
`)}function frameworkFormsTarget(framework){return framework==="nextjs"?"next":framework==="astro"?"astro":framework==="sveltekit"||framework==="sveltekit-1"?"sveltekit":null}function hasPackageExport(cwd,subpath){let packagePath=join5(cwd,"node_modules","fimo","package.json");if(!existsSync4(packagePath))return!1;try{let packageJson=JSON.parse(readFileSync4(packagePath,"utf-8"));return!!(packageJson.exports&&Object.prototype.hasOwnProperty.call(packageJson.exports,subpath))}catch{return!1}}function assertFrameworkRuntime(cwd,target){let missing=(target==="next"?["./forms","./next","./next/client"]:["./forms",`./${target}`]).filter(subpath=>!hasPackageExport(cwd,subpath));if(missing.length!==0)throw new Error(`Cannot generate ${target} form clients because the project-local fimo package is missing ${missing.join(", ")}. Install the current fimo package, then run \`fimo validate\` again. No generated files were changed.`)}function generatedFormFiles(target){return target==="next"?[{suffix:".ts",runtimeImport:"fimo/next"},{suffix:".client.ts",runtimeImport:"fimo/next/client",clientDirective:"'use client';"}]:target==="astro"?[{suffix:".ts",runtimeImport:"fimo/astro"}]:target==="sveltekit"?[{suffix:".ts",runtimeImport:"fimo/sveltekit"}]:[]}function syncForms(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),formsDir=resolve4(cwd,FORMS_REL),formFiles=getFormFiles(formsDir),target=frameworkFormsTarget(options.framework);target&&formFiles.length>0&&assertFrameworkRuntime(cwd,target);let legacyTemplateSource=readFileSync4(assetPath("content-templates","forms","react.eta"),"utf-8"),frameworkTemplateSource=target?readFileSync4(assetPath("content-templates","forms","framework.eta"),"utf-8"):null,outputFiles=generatedFormFiles(target),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),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 formModel={...form,pascal:pascalCase(form.name)},files=target?outputFiles:[{suffix:".ts",runtimeImport:"",clientDirective:""}];for(let output of files){let tsPath=join5(formsDir,`${form.name}${output.suffix}`);expectedTsFiles.add(tsPath);try{let content2=eta.renderString(target?frameworkTemplateSource:legacyTemplateSource,{form:{...formModel,...output}}),dir=dirname4(tsPath);if(existsSync4(dir)||mkdirSync2(dir,{recursive:!0}),!existsSync4(tsPath)){writeFileSync2(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync4(tsPath,"utf-8")!==content2&&(writeFileSync2(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);(!existsSync4(indexPath)||readFileSync4(indexPath,"utf-8")!==indexContent)&&(writeFileSync2(indexPath,indexContent,"utf-8"),log(`Updated: ${indexPath}`))}if(existsSync4(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_dist8();init_eta_module();init_assets();FORMS_REL="src/forms";__name(getFormFiles,"getFormFiles");__name(readForm,"readForm");__name(generateIndexContent,"generateIndexContent");__name(frameworkFormsTarget,"frameworkFormsTarget");__name(hasPackageExport,"hasPackageExport");__name(assertFrameworkRuntime,"assertFrameworkRuntime");__name(generatedFormFiles,"generatedFormFiles");__name(syncForms,"syncForms")}});import{existsSync as existsSync5,mkdirSync as mkdirSync3,readFileSync as readFileSync5,readdirSync as readdirSync3,unlinkSync as unlinkSync2,writeFileSync as writeFileSync3}from"node:fs";import{basename,dirname as dirname5,join as join6,resolve as resolve5}from"node:path";import{z as z71}from"zod";function getSchemaFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".json")).sort().map(f=>join6(schemasDir,f)):[]}function getGeneratedFiles(schemasDir){return existsSync5(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 packageExportsSubpath(packageJson,subpath){if(!packageJson||typeof packageJson!="object"||Array.isArray(packageJson))return!1;let exports2=packageJson.exports;return!!(exports2&&typeof exports2=="object"&&!Array.isArray(exports2)&&Object.prototype.hasOwnProperty.call(exports2,subpath))}function resolveProjectRuntime(cwd){let packagePath=join6(cwd,"node_modules","fimo","package.json");if(!existsSync5(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 packageJson;try{packageJson=JSON.parse(readFileSync5(packagePath,"utf-8"))}catch{packageJson=null}let version=packageJson&&typeof packageJson=="object"&&!Array.isArray(packageJson)?packageJson.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,providesNextRuntime:packageExportsSubpath(packageJson,"./next")&&packageExportsSubpath(packageJson,"./next/client"),providesAstroRuntime:packageExportsSubpath(packageJson,"./astro"),providesSvelteKitRuntime:packageExportsSubpath(packageJson,"./sveltekit")}}function contentRuntimeImportFor(framework){return framework==="nextjs"?"fimo/next":framework==="astro"?"fimo/astro":framework==="sveltekit"||framework==="sveltekit-1"?"fimo/sveltekit":"fimo/ui"}function templatePath(runtime,templateName){let template=CONTENT_TEMPLATE_PATHS[templateName];if(runtime&&!isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)){let legacyPath="legacy"in template?template.legacy:template.current;return join6(runtime.packageRoot,"assets","content-templates",legacyPath)}return assetPath("content-templates",template.current)}function resolveSchemaGenerationTarget(runtimeImport,runtime){if(runtimeImport==="fimo/ui")return"react";if(runtimeImport==="fimo/next"&&!runtime.providesNextRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the fimo/next and fimo/next/client exports required by this Next.js project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo/astro"&&!runtime.providesAstroRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the fimo/astro export required by this Astro project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo/sveltekit"&&!runtime.providesSvelteKitRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the fimo/sveltekit export required by this SvelteKit project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return runtimeImport==="fimo/next"?"next":runtimeImport==="fimo/astro"?"astro":"sveltekit"}function templatesForTarget(target,runtime,runtimeImport){return target==="next"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo/next"},{suffix:".ts",path:templatePath(runtime,"nextServer"),runtimeImport:"fimo/next"},{suffix:".client.ts",path:templatePath(runtime,"nextClient"),runtimeImport:"fimo/next/client"}]:target==="astro"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo/astro"},{suffix:".ts",path:templatePath(runtime,"sharedServer"),runtimeImport:"fimo/astro"}]:target==="sveltekit"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo/sveltekit"},{suffix:".ts",path:templatePath(runtime,"svelteKitContent"),runtimeImport:"fimo/sveltekit"}]:[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport},{suffix:".ts",path:templatePath(runtime,"reactClient"),runtimeImport}]}function loadSchemas(schemaFiles){let errors=[],schemas3=[],outputOwners=new Map,registryOwners=new Map;for(let path49 of schemaFiles){let fileUid=basename(path49,".json"),pascal=pascalCase(fileUid),existingOwner=outputOwners.get(pascal);existingOwner&&existingOwner!==fileUid?errors.push(`${basename(path49)} 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(path49,"utf-8"))}catch(error){errors.push(`${basename(path49)} is invalid JSON: ${error instanceof Error?error.message:String(error)}`);continue}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){errors.push(`${basename(path49)} must contain a JSON object.`);continue}let candidate=parsed;if(typeof candidate.uid!="string"||candidate.uid.length===0){errors.push(`${basename(path49)} is missing "uid". Set it to "${fileUid}".`);continue}if(candidate.uid!==fileUid){errors.push(`${basename(path49)} 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(path49)} has an invalid schema shape: ${details}`);continue}let registryKey=camelCase(validation.data.name??validation.data.uid),existingRegistryOwner=registryOwners.get(registryKey);if(existingRegistryOwner&&existingRegistryOwner!==fileUid){errors.push(`${basename(path49)} and ${existingRegistryOwner}.json both generate the content registry key "${registryKey}". Rename one schema display name to keep generated registry keys unique.`);continue}registryOwners.set(registryKey,fileUid),schemas3.push({pascal,registryKey,schema:validation.data})}if(errors.length>0)throw new Error(`Cannot generate schema clients:
|
|
357
|
+
`)}function frameworkFormsTarget(framework){return framework==="nextjs"?"next":framework==="astro"?"astro":framework==="sveltekit"||framework==="sveltekit-1"?"sveltekit":null}function hasPackageExport(cwd,subpath){let packagePath=join5(cwd,"node_modules","fimo","package.json");if(!existsSync4(packagePath))return!1;try{let packageJson=JSON.parse(readFileSync4(packagePath,"utf-8"));return!!(packageJson.exports&&Object.prototype.hasOwnProperty.call(packageJson.exports,subpath))}catch{return!1}}function assertFrameworkRuntime(cwd,target){let missing=(target==="next"?["./forms","./next","./next/client"]:["./forms",`./${target}`]).filter(subpath=>!hasPackageExport(cwd,subpath));if(missing.length!==0)throw new Error(`Cannot generate ${target} form clients because the project-local fimo package is missing ${missing.join(", ")}. Install the current fimo package, then run \`fimo validate\` again. No generated files were changed.`)}function generatedFormFiles(target){return target==="next"?[{suffix:".ts",runtimeImport:"fimo/next"},{suffix:".client.ts",runtimeImport:"fimo/next/client",clientDirective:"'use client';"}]:target==="astro"?[{suffix:".ts",runtimeImport:"fimo/astro"}]:target==="sveltekit"?[{suffix:".ts",runtimeImport:"fimo/sveltekit"}]:[]}function syncForms(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),formsDir=resolve4(cwd,FORMS_REL),formFiles=getFormFiles(formsDir),target=frameworkFormsTarget(options.framework);target&&formFiles.length>0&&assertFrameworkRuntime(cwd,target);let legacyTemplateSource=readFileSync4(assetPath("content-templates","forms","react.eta"),"utf-8"),frameworkTemplateSource=target?readFileSync4(assetPath("content-templates","forms","framework.eta"),"utf-8"):null,outputFiles=generatedFormFiles(target),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),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 formModel={...form,pascal:pascalCase(form.name)},files=target?outputFiles:[{suffix:".ts",runtimeImport:"",clientDirective:""}];for(let output of files){let tsPath=join5(formsDir,`${form.name}${output.suffix}`);expectedTsFiles.add(tsPath);try{let content2=eta.renderString(target?frameworkTemplateSource:legacyTemplateSource,{form:{...formModel,...output}}),dir=dirname4(tsPath);if(existsSync4(dir)||mkdirSync2(dir,{recursive:!0}),!existsSync4(tsPath)){writeFileSync2(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync4(tsPath,"utf-8")!==content2&&(writeFileSync2(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);(!existsSync4(indexPath)||readFileSync4(indexPath,"utf-8")!==indexContent)&&(writeFileSync2(indexPath,indexContent,"utf-8"),log(`Updated: ${indexPath}`))}if(existsSync4(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_dist8();init_eta_module();init_assets();FORMS_REL="src/forms";__name(getFormFiles,"getFormFiles");__name(readForm,"readForm");__name(generateIndexContent,"generateIndexContent");__name(frameworkFormsTarget,"frameworkFormsTarget");__name(hasPackageExport,"hasPackageExport");__name(assertFrameworkRuntime,"assertFrameworkRuntime");__name(generatedFormFiles,"generatedFormFiles");__name(syncForms,"syncForms")}});import{existsSync as existsSync5,mkdirSync as mkdirSync3,readFileSync as readFileSync5,readdirSync as readdirSync3,unlinkSync as unlinkSync2,writeFileSync as writeFileSync3}from"node:fs";import{basename,dirname as dirname5,join as join6,resolve as resolve5}from"node:path";import{z as z74}from"zod";function getSchemaFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".json")).sort().map(f=>join6(schemasDir,f)):[]}function getGeneratedFiles(schemasDir){return existsSync5(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 packageExportsSubpath(packageJson,subpath){if(!packageJson||typeof packageJson!="object"||Array.isArray(packageJson))return!1;let exports2=packageJson.exports;return!!(exports2&&typeof exports2=="object"&&!Array.isArray(exports2)&&Object.prototype.hasOwnProperty.call(exports2,subpath))}function resolveProjectRuntime(cwd){let packagePath=join6(cwd,"node_modules","fimo","package.json");if(!existsSync5(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 packageJson;try{packageJson=JSON.parse(readFileSync5(packagePath,"utf-8"))}catch{packageJson=null}let version=packageJson&&typeof packageJson=="object"&&!Array.isArray(packageJson)?packageJson.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,providesNextRuntime:packageExportsSubpath(packageJson,"./next")&&packageExportsSubpath(packageJson,"./next/client"),providesAstroRuntime:packageExportsSubpath(packageJson,"./astro"),providesSvelteKitRuntime:packageExportsSubpath(packageJson,"./sveltekit")}}function contentRuntimeImportFor(framework){return framework==="nextjs"?"fimo/next":framework==="astro"?"fimo/astro":framework==="sveltekit"||framework==="sveltekit-1"?"fimo/sveltekit":"fimo/ui"}function templatePath(runtime,templateName){let template=CONTENT_TEMPLATE_PATHS[templateName];if(runtime&&!isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)){let legacyPath="legacy"in template?template.legacy:template.current;return join6(runtime.packageRoot,"assets","content-templates",legacyPath)}return assetPath("content-templates",template.current)}function resolveSchemaGenerationTarget(runtimeImport,runtime){if(runtimeImport==="fimo/ui")return"react";if(runtimeImport==="fimo/next"&&!runtime.providesNextRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the fimo/next and fimo/next/client exports required by this Next.js project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo/astro"&&!runtime.providesAstroRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the fimo/astro export required by this Astro project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo/sveltekit"&&!runtime.providesSvelteKitRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the fimo/sveltekit export required by this SvelteKit project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return runtimeImport==="fimo/next"?"next":runtimeImport==="fimo/astro"?"astro":"sveltekit"}function templatesForTarget(target,runtime,runtimeImport){return target==="next"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo/next"},{suffix:".ts",path:templatePath(runtime,"nextServer"),runtimeImport:"fimo/next"},{suffix:".client.ts",path:templatePath(runtime,"nextClient"),runtimeImport:"fimo/next/client"}]:target==="astro"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo/astro"},{suffix:".ts",path:templatePath(runtime,"sharedServer"),runtimeImport:"fimo/astro"}]:target==="sveltekit"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo/sveltekit"},{suffix:".ts",path:templatePath(runtime,"svelteKitContent"),runtimeImport:"fimo/sveltekit"}]:[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport},{suffix:".ts",path:templatePath(runtime,"reactClient"),runtimeImport}]}function loadSchemas(schemaFiles){let errors=[],schemas3=[],outputOwners=new Map,registryOwners=new Map;for(let path49 of schemaFiles){let fileUid=basename(path49,".json"),pascal=pascalCase(fileUid),existingOwner=outputOwners.get(pascal);existingOwner&&existingOwner!==fileUid?errors.push(`${basename(path49)} 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(path49,"utf-8"))}catch(error){errors.push(`${basename(path49)} is invalid JSON: ${error instanceof Error?error.message:String(error)}`);continue}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){errors.push(`${basename(path49)} must contain a JSON object.`);continue}let candidate=parsed;if(typeof candidate.uid!="string"||candidate.uid.length===0){errors.push(`${basename(path49)} is missing "uid". Set it to "${fileUid}".`);continue}if(candidate.uid!==fileUid){errors.push(`${basename(path49)} 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(path49)} has an invalid schema shape: ${details}`);continue}let registryKey=camelCase(validation.data.name??validation.data.uid),existingRegistryOwner=registryOwners.get(registryKey);if(existingRegistryOwner&&existingRegistryOwner!==fileUid){errors.push(`${basename(path49)} and ${existingRegistryOwner}.json both generate the content registry key "${registryKey}". Rename one schema display name to keep generated registry keys unique.`);continue}registryOwners.set(registryKey,fileUid),schemas3.push({pascal,registryKey,schema:validation.data})}if(errors.length>0)throw new Error(`Cannot generate schema clients:
|
|
358
358
|
- ${errors.join(`
|
|
359
359
|
- `)}
|
|
360
360
|
No generated files were changed.`);return schemas3}function renderContentRegistry(schemas3){let imports=schemas3.map(({pascal})=>`import * as ${pascal} from "./${pascal}";`).join(`
|
|
@@ -367,7 +367,7 @@ ${imports}
|
|
|
367
367
|
export const content = {
|
|
368
368
|
${entries2}
|
|
369
369
|
} as const;
|
|
370
|
-
`}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=resolve5(cwd,SCHEMAS_REL),registryPath=join6(schemasDir,"index.ts"),schemaFiles=getSchemaFiles(schemasDir),schemas3=loadSchemas(schemaFiles),generatedFilesOnDisk=getGeneratedFiles(schemasDir),runtime=schemas3.length>0||generatedFilesOnDisk.length>0?resolveProjectRuntime(cwd):null,runtimeImport=contentRuntimeImportFor(options.framework),generationTarget=runtime?resolveSchemaGenerationTarget(runtimeImport,runtime):null,needsContentRegistry=(generationTarget==="next"||generationTarget==="sveltekit")&&schemas3.length>0,ownsExistingRegistry=existsSync5(registryPath)&&readFileSync5(registryPath,"utf-8").startsWith(GENERATED_REGISTRY_MARKER),shouldGenerateRegistry=needsContentRegistry&&(!existsSync5(registryPath)||ownsExistingRegistry);needsContentRegistry&&!shouldGenerateRegistry&&log(`Kept project-owned schema barrel: ${registryPath}`);let loadedTemplates=(generationTarget&&runtime?templatesForTarget(generationTarget,runtime,runtimeImport):[]).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 loadedTemplates){let tsPath=join6(schemasDir,`${pascal}${template.suffix}`);expectedTsFiles.add(tsPath),generatedFiles.set(tsPath,eta.renderString(template.source,{model,runtimeImport:template.runtimeImport}))}}shouldGenerateRegistry&&(expectedTsFiles.add(registryPath),generatedFiles.set(registryPath,renderContentRegistry(schemas3)));for(let[tsPath,content2]of generatedFiles){let dir=dirname5(tsPath);if(existsSync5(dir)||mkdirSync3(dir,{recursive:!0}),!existsSync5(tsPath)){writeFileSync3(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync5(tsPath,"utf-8")!==content2&&(writeFileSync3(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!shouldGenerateRegistry&&existsSync5(registryPath)&&readFileSync5(registryPath,"utf-8").startsWith(GENERATED_REGISTRY_MARKER)&&(unlinkSync2(registryPath),deleted++,log(`Deleted orphaned: ${registryPath}`)),(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync schemas: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var SCHEMAS_REL,GENERATED_REGISTRY_MARKER,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION,CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND,SCHEMA_DEFINITION_SCHEMA,CONTENT_TEMPLATE_PATHS,init_sync_schemas=__esm({"src/scripts/sync-schemas.ts"(){init_dist8();init_eta_module();init_assets();SCHEMAS_REL="src/schemas",GENERATED_REGISTRY_MARKER="// AUTO-GENERATED by `fimo` from src/schemas/*.json - DO NOT EDIT.",MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION="0.7.0",CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND="npm install fimo@latest",SCHEMA_DEFINITION_SCHEMA=
|
|
370
|
+
`}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=resolve5(cwd,SCHEMAS_REL),registryPath=join6(schemasDir,"index.ts"),schemaFiles=getSchemaFiles(schemasDir),schemas3=loadSchemas(schemaFiles),generatedFilesOnDisk=getGeneratedFiles(schemasDir),runtime=schemas3.length>0||generatedFilesOnDisk.length>0?resolveProjectRuntime(cwd):null,runtimeImport=contentRuntimeImportFor(options.framework),generationTarget=runtime?resolveSchemaGenerationTarget(runtimeImport,runtime):null,needsContentRegistry=(generationTarget==="next"||generationTarget==="sveltekit")&&schemas3.length>0,ownsExistingRegistry=existsSync5(registryPath)&&readFileSync5(registryPath,"utf-8").startsWith(GENERATED_REGISTRY_MARKER),shouldGenerateRegistry=needsContentRegistry&&(!existsSync5(registryPath)||ownsExistingRegistry);needsContentRegistry&&!shouldGenerateRegistry&&log(`Kept project-owned schema barrel: ${registryPath}`);let loadedTemplates=(generationTarget&&runtime?templatesForTarget(generationTarget,runtime,runtimeImport):[]).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 loadedTemplates){let tsPath=join6(schemasDir,`${pascal}${template.suffix}`);expectedTsFiles.add(tsPath),generatedFiles.set(tsPath,eta.renderString(template.source,{model,runtimeImport:template.runtimeImport}))}}shouldGenerateRegistry&&(expectedTsFiles.add(registryPath),generatedFiles.set(registryPath,renderContentRegistry(schemas3)));for(let[tsPath,content2]of generatedFiles){let dir=dirname5(tsPath);if(existsSync5(dir)||mkdirSync3(dir,{recursive:!0}),!existsSync5(tsPath)){writeFileSync3(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync5(tsPath,"utf-8")!==content2&&(writeFileSync3(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!shouldGenerateRegistry&&existsSync5(registryPath)&&readFileSync5(registryPath,"utf-8").startsWith(GENERATED_REGISTRY_MARKER)&&(unlinkSync2(registryPath),deleted++,log(`Deleted orphaned: ${registryPath}`)),(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync schemas: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var SCHEMAS_REL,GENERATED_REGISTRY_MARKER,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION,CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND,SCHEMA_DEFINITION_SCHEMA,CONTENT_TEMPLATE_PATHS,init_sync_schemas=__esm({"src/scripts/sync-schemas.ts"(){init_dist8();init_eta_module();init_assets();SCHEMAS_REL="src/schemas",GENERATED_REGISTRY_MARKER="// AUTO-GENERATED by `fimo` from src/schemas/*.json - DO NOT EDIT.",MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION="0.7.0",CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND="npm install fimo@latest",SCHEMA_DEFINITION_SCHEMA=z74.object({uid:z74.string().min(1),name:z74.string().min(1).optional(),isSingleton:z74.boolean().optional(),i18n:z74.object({enabled:z74.boolean().optional()}).optional(),fields:z74.record(z74.string(),z74.unknown()).optional()}),CONTENT_TEMPLATE_PATHS={types:{current:"shared/types.eta",legacy:"types-template.eta"},sharedServer:{current:"shared/server.eta"},reactClient:{current:"react/client.eta",legacy:"hooks-template.eta"},nextServer:{current:"next/server.eta"},nextClient:{current:"next/client.eta"},svelteKitContent:{current:"sveltekit/content.eta"}};__name(getSchemaFiles,"getSchemaFiles");__name(getGeneratedFiles,"getGeneratedFiles");__name(parseVersion,"parseVersion");__name(isVersionAtLeast,"isVersionAtLeast");__name(packageExportsSubpath,"packageExportsSubpath");__name(resolveProjectRuntime,"resolveProjectRuntime");__name(contentRuntimeImportFor,"contentRuntimeImportFor");__name(templatePath,"templatePath");__name(resolveSchemaGenerationTarget,"resolveSchemaGenerationTarget");__name(templatesForTarget,"templatesForTarget");__name(loadSchemas,"loadSchemas");__name(renderContentRegistry,"renderContentRegistry");__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(`
|
|
371
371
|
`)}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")}});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_assets2();init_code();init_content();init_forms();init_schemas();init_translations();SURFACE_PRESENTERS={code,schemas,content,translations,assets,forms}}});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(`
|
|
372
372
|
`);if(delta.status==="failed")return lines.push(p2.red(` (surface check failed: ${delta.error??"unknown"})`)),lines.join(`
|
|
373
373
|
`);if(delta.status==="unchanged"||delta.changedCount===0&&delta.conflictCount===0)return lines.push(p2.dim(display.emptyCopy)),lines.join(`
|
|
@@ -1178,7 +1178,7 @@ ${html3}`.toLowerCase();return haystack.includes("webflow")||haystack.includes("
|
|
|
1178
1178
|
${target}: Fimo branch not created yet`}}function pickSurfaces(opts){let selected=[["code","code"],["content","content"],["i18n","translations"],["assets","assets"],["forms","forms"]].filter(([flag2])=>opts[flag2]===!0).map(([,surface])=>surface);return selected.length>0?selected:void 0}function withSoftTimeout(p2,ms){return new Promise(resolve10=>{let t2=setTimeout(()=>resolve10({kind:"timeout"}),ms);p2.then(value=>{clearTimeout(t2),resolve10({kind:"ok",value})},error=>{clearTimeout(t2),resolve10({kind:"error",error})})})}async function localCodeSurface(cwd){if(!await isGitRepo(cwd))return{surface:"code",status:"unchanged",changedCount:0,conflictCount:0,items:[]};try{let items=(await runGit(["status","--porcelain"],cwd)).split(`
|
|
1179
1179
|
`).filter(Boolean).map(line=>{let code2=line.slice(0,2),path49=line.slice(3).trim();return{verb:code2.startsWith("A")||code2.startsWith("?")?"added":code2.startsWith("D")?"removed":"changed",key:path49,origin:"local-uncommitted"}});return{surface:"code",status:items.length===0?"unchanged":"ok",changedCount:items.length,conflictCount:0,items}}catch{return{surface:"code",status:"unchanged",changedCount:0,conflictCount:0,items:[]}}}function mergeCodeSurfaces(serverCode,local){if(!serverCode)return local;if(serverCode.status==="failed"||serverCode.status==="timed_out")return{...serverCode,items:[...serverCode.items??[],...local.items??[]],changedCount:serverCode.changedCount+local.changedCount};let items=[...serverCode.items??[],...local.items??[]],changedCount=serverCode.changedCount+local.changedCount,conflictCount=serverCode.conflictCount+local.conflictCount;return{surface:"code",status:changedCount>0||conflictCount>0?"ok":"unchanged",durationMs:serverCode.durationMs,changedCount,conflictCount,items}}async function statusCommand2(arg1,maybeCmd){let cmd=maybeCmd??arg1,options=maybeCmd?arg1:cmd.opts(),program2=cmd.parent??cmd,envOverride2=envOverrideFromCommand(program2),ctx=await getProjectContext({cwd:options.cwd,envOverride:envOverride2}),api=new FimoApiClient().withEnv(ctx.env),cwd=resolveProjectCwd(options.cwd),surfaces=pickSurfaces(options),codePromise=localCodeSurface(cwd),checkoutPromise=localCheckoutStatus(api,ctx.projectId,ctx.env,cwd),serverPromise=withSoftTimeout(api.getEnvStatus(ctx.projectId,ctx.env,{against:options.vs,surfaces}),SOFT_TIMEOUT_MS*15),[local,checkout,serverResult]=await Promise.all([codePromise,checkoutPromise,serverPromise]);if(serverResult.kind==="timeout"){ui.error({command:"status",code:"STATUS_TIMEOUT",message:`Server did not respond within ${SOFT_TIMEOUT_MS*15/1e3}s. Try again, or run \`fimo diff\` to drill in.`});return}if(serverResult.kind==="error"){let err=serverResult.error,message=err instanceof Error?err.message:String(err);ui.error({command:"status",code:"STATUS_REQUEST_FAILED",message:`Failed to fetch status: ${message}`});return}let server=serverResult.value,serverCode=server.surfaces.find(s=>s.surface==="code"),code2=mergeCodeSurfaces(serverCode,local),merged={...server,checkout,surfaces:[code2,...server.surfaces.filter(s=>s.surface!=="code")]};ui.result({command:"status",data:merged,render:__name(rctx=>{let p2=rctx.color?palette:makeColorPalette({forceDisable:!0}),environmentStatus=renderStatus2(merged,p2,{short:options.short,surface:surfaces?.length===1?surfaces[0]:void 0,all:options.all,ascii:rctx.ascii});return`${renderLocalCheckoutStatus(checkout)}
|
|
1180
1180
|
|
|
1181
|
-
${environmentStatus}`},"render")})}var SOFT_TIMEOUT_MS,init_status=__esm({"src/cli/commands/status.ts"(){init_dist();init_api();init_environment_checkout();init_color();init_render_status();init_git_credential_setup();init_git();init_project_context();init_project();SOFT_TIMEOUT_MS=2e3;__name(withCheckoutRecovery,"withCheckoutRecovery");__name(localCheckoutStatus,"localCheckoutStatus");__name(renderLocalCheckoutStatus,"renderLocalCheckoutStatus");__name(pickSurfaces,"pickSurfaces");__name(withSoftTimeout,"withSoftTimeout");__name(localCodeSurface,"localCodeSurface");__name(mergeCodeSurfaces,"mergeCodeSurfaces");__name(statusCommand2,"statusCommand")}});init_dist();import fs46 from"node:fs";import path48 from"node:path";var import_index=__toESM(require_commander(),1),{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import_index.default;init_api();import fs9 from"node:fs";import path9 from"node:path";var import_yaml=__toESM(require_dist(),1);import{createHash as createHash2}from"node:crypto";import{promises}from"node:fs";import path4 from"node:path";import{z as z65}from"zod";var CapabilityTokenSchema=z65.string().min(1).regex(/^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?$/,{error:"capability tokens must match verb:noun or verb:noun:qualifier (lowercase + digits + underscores; must start with a letter)"}),CapabilitiesFileSchema=z65.array(CapabilityTokenSchema);import{z as z66}from"zod";var CronTriggerSchema=z66.object({type:z66.literal("schedule"),cron:z66.string().min(1,"cron expression required"),tz:z66.string().optional()}),ManualTriggerSchema2=z66.object({type:z66.literal("manual")}),WebhookTriggerSchema2=z66.object({type:z66.literal("webhook"),path:z66.string().min(1).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z66.discriminatedUnion("type",[ManualTriggerSchema2,CronTriggerSchema,WebhookTriggerSchema2]),SubAgentRefSchema=z66.object({name:z66.string().min(1),capability_grant:z66.enum(["inherit","explicit"]).optional(),explicit_grants:z66.array(z66.string()).optional()}).refine(v=>v.capability_grant!=="explicit"||Array.isArray(v.explicit_grants)&&v.explicit_grants.length>0,{message:"`explicit_grants` is required when `capability_grant: explicit`",path:["explicit_grants"]}),CompositionConfigSchema=z66.object({"sub-agents":z66.array(SubAgentRefSchema)}),RuntimeConfigSchema=z66.object({cloud:z66.boolean().optional(),dev:z66.boolean().optional(),long_running:z66.boolean().optional()}),DataSourceSchema=z66.enum(["main","prod"]),ConfigValueKeySchema=z66.string().min(1).max(255).regex(/^[A-Z_][A-Z0-9_]*$/,"secret keys must be UPPER_SNAKE_CASE and start with a letter or underscore"),PUBLIC_CONFIG_PREFIX=/^(PUBLIC_|VITE_|NEXT_PUBLIC_)/,AgentSecretRequestSchema=z66.preprocess(value=>typeof value=="string"?{key:value}:value,z66.object({key:ConfigValueKeySchema.refine(key=>!PUBLIC_CONFIG_PREFIX.test(key),{message:"agent secrets cannot use public variable prefixes (PUBLIC_, VITE_, NEXT_PUBLIC_)"}),required:z66.boolean().default(!0),delivery:z66.literal("process_env").default("process_env")})),IntegrationKeySchema=z66.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*$/,"integration keys must be lowercase alphanumeric with optional _ or -"),IntegrationToolKeySchema=z66.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)*$/,"integration tool keys must be lowercase dot-separated identifiers with optional _ or -"),IntegrationPolicyEntrySchema=z66.preprocess(value=>typeof value=="boolean"?{enabled:value}:value,z66.object({enabled:z66.boolean().default(!0),tools:z66.record(IntegrationToolKeySchema,z66.boolean()).optional()})),IntegrationPolicySchema=z66.record(IntegrationKeySchema,IntegrationPolicyEntrySchema),AgentConfigSchema=z66.object({version:z66.literal(1),description:z66.string().min(1).max(280).optional(),runtime:RuntimeConfigSchema.optional(),triggers:z66.array(TriggerSchema2).optional(),composition:CompositionConfigSchema.optional(),data_sources:z66.array(DataSourceSchema).optional(),secrets:z66.array(AgentSecretRequestSchema).optional(),integrations:IntegrationPolicySchema.optional(),integration_policy:IntegrationPolicySchema.optional()}).refine(config=>!(config.integrations&&config.integration_policy),{message:"use either `integrations` or legacy `integration_policy`, not both",path:["integrations"]});function _define_property(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property,"_define_property");var BundleParseError=class extends Error{static{__name(this,"BundleParseError")}constructor(bundlePath,file,message,cause){super(`[${file}] ${message}`),_define_property(this,"bundlePath",void 0),_define_property(this,"file",void 0),_define_property(this,"cause",void 0),this.name="BundleParseError",this.bundlePath=bundlePath,this.file=file,this.cause=cause}};async function fileExists(file){try{return(await promises.stat(file)).isFile()}catch{return!1}}__name(fileExists,"fileExists");async function readFileOrNull(file){try{return await promises.readFile(file,"utf8")}catch(err){if(err.code==="ENOENT")return null;throw err}}__name(readFileOrNull,"readFileOrNull");async function listDir(dir){try{return(await promises.readdir(dir,{withFileTypes:!0,recursive:!0})).filter(e=>e.isFile()).map(e=>{let parentPath=e.parentPath??e.path??dir;return path4.relative(dir,path4.join(parentPath,e.name))}).sort()}catch(err){if(err.code==="ENOENT")return[];throw err}}__name(listDir,"listDir");function parseYamlStrict(text3,file,bundlePath){try{return(0,import_yaml.parse)(text3)}catch(err){throw new BundleParseError(bundlePath,file,`invalid YAML: ${err.message}`,err)}}__name(parseYamlStrict,"parseYamlStrict");function formatZodIssue(issue){return`${issue.path.length===0?"(root)":issue.path.join(".")}: ${issue.message}`}__name(formatZodIssue,"formatZodIssue");async function parseBundle(bundlePath,opts={}){let name=path4.basename(bundlePath),goalPath=path4.join(bundlePath,"GOAL.md"),goal=await readFileOrNull(goalPath);if(goal===null)throw new BundleParseError(bundlePath,"GOAL.md","GOAL.md is required but missing");if(goal.trim().length===0)throw new BundleParseError(bundlePath,"GOAL.md","GOAL.md is empty");let configPath=path4.join(bundlePath,"config.yaml"),configRaw=await readFileOrNull(configPath),config;if(configRaw===null){if(!opts.defaultConfig)throw new BundleParseError(bundlePath,"config.yaml","config.yaml is required but missing");config={version:1}}else{let yamlData=parseYamlStrict(configRaw,"config.yaml",bundlePath),parsed=AgentConfigSchema.safeParse(yamlData);if(!parsed.success){let issues=parsed.error.issues.map(formatZodIssue).join("; ");throw new BundleParseError(bundlePath,"config.yaml",`schema validation failed: ${issues}`)}config=parsed.data}let soul=await readFileOrNull(path4.join(bundlePath,"SOUL.md")),capsPath=path4.join(bundlePath,"capabilities.yaml"),capsRaw=await readFileOrNull(capsPath),capabilities=[];if(capsRaw!==null){let candidate=parseYamlStrict(capsRaw,"capabilities.yaml",bundlePath)??[],parsed=CapabilitiesFileSchema.safeParse(candidate);if(!parsed.success){let issues=parsed.error.issues.map(formatZodIssue).join("; ");throw new BundleParseError(bundlePath,"capabilities.yaml",`schema validation failed: ${issues} \u2014 file must be a bare YAML list of capability tokens`)}capabilities=parsed.data}let[scripts2,references,assets3]=await Promise.all([listDir(path4.join(bundlePath,"scripts")),listDir(path4.join(bundlePath,"references")),listDir(path4.join(bundlePath,"assets"))]),warnings=[],pluginsDir=path4.join(bundlePath,"plugins");try{(await promises.stat(pluginsDir)).isDirectory()&&warnings.push({pointer:"plugins/",message:"`plugins/` is reserved for v1.x and will be ignored at runtime."})}catch{}let checksum=await computeBundleChecksum(bundlePath,{goal,soul,configRaw,capsRaw,scripts:scripts2,references,assets:assets3});return{name,path:bundlePath,goal,soul,config,capabilities,scripts:scripts2,references,assets:assets3,checksum,warnings}}__name(parseBundle,"parseBundle");async function computeBundleChecksum(bundlePath,parts){let hash=createHash2("sha256");hash.update("GOAL.md\0"),hash.update(parts.goal),hash.update("\0config.yaml\0"),hash.update(parts.configRaw??""),parts.capsRaw!==null&&(hash.update("\0capabilities.yaml\0"),hash.update(parts.capsRaw)),parts.soul!==null&&(hash.update("\0SOUL.md\0"),hash.update(parts.soul));let dirs=[["scripts",parts.scripts],["references",parts.references],["assets",parts.assets]];for(let[dirName,files]of dirs)for(let rel of files){let filePath=path4.join(bundlePath,dirName,rel);try{let buf=await promises.readFile(filePath);hash.update(`\0${dirName}/${rel}\0`),hash.update(buf)}catch{}}return hash.digest("hex")}__name(computeBundleChecksum,"computeBundleChecksum");async function listBundles(agentsDir){let entries2=[];try{entries2=await promises.readdir(agentsDir,{withFileTypes:!0})}catch(err){if(err.code==="ENOENT")return[];throw err}let bundles=[];for(let entry of entries2){if(!entry.isDirectory())continue;let bundlePath=path4.join(agentsDir,entry.name);if(await fileExists(path4.join(bundlePath,"GOAL.md")))try{bundles.push(await parseBundle(bundlePath))}catch{}}return bundles.sort((a,b)=>a.name.localeCompare(b.name))}__name(listBundles,"listBundles");var ENTRIES=[{token:"files:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read project files"},{token:"files:write",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Write or delete project files"},{token:"cms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS content"},{token:"cms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Create, update, or delete CMS entries"},{token:"cms:schema:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS schemas"},{token:"cms:schema:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Modify CMS schemas (destructive \u2014 alters all entries of the type)"},{token:"assets:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read uploaded media"},{token:"assets:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Upload, replace, or delete media"},{token:"i18n:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read translation catalogs"},{token:"i18n:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify translation catalogs via the fimo i18n CLI"},{token:"forms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read form schemas and submissions"},{token:"forms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify form schemas or clear submissions"},{token:"webhooks:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read webhook configurations and delivery history"},{token:"webhooks:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger webhooks that send project data to external URLs"},{token:"schedules:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read schedule configurations and run history"},{token:"schedules:write",risk:"critical",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger scheduled commands that run with publish and code-edit rights"},{token:"git:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read git state"},{token:"git:branch",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Create agent-proposed branches off main"},{token:"git:commit",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Commit changes to an agent branch"},{token:"git:push",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Push to the project remote (main push is intercepted)"},{token:"git:tag",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Used by runtime for prod release tags; agents cannot call directly"},{token:"fimo:deploy",risk:"critical",declarable:!0,enforcedBy:"api",description:"Trigger a production deploy"},{token:"fimo:logs:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read production logs"},{token:"fimo:analytics:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read analytics data"},{token:"fimo:domains:manage",risk:"high",declarable:!0,enforcedBy:"api",description:"Read and manage project domains"},{token:"fimo:agents:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run project agents"},{token:"fimo:preview:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read a current preview URL for an env (no commit, no deploy)"},{token:"fimo:history:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project restore points"},{token:"net:fetch",risk:"medium",declarable:!0,enforcedBy:"runtime",description:"Make outbound HTTP requests"},{token:"integrations:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run enabled project integration tools allowed by the agent policy"},{token:"shell:exec",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Run arbitrary shell commands inside the sandbox"},{token:"agent:delegate",risk:"medium",declarable:!0,enforcedBy:"engine",description:"Invoke declared sub-agents"},{token:"runtime:long_running",risk:"high",declarable:!0,enforcedBy:"runtime",description:"Run autonomously past the default 30 min limit (up to 4h walltime / 12h ceiling)"},{token:"runtime:auto_merge",risk:"critical",declarable:!0,enforcedBy:"runtime",description:"Auto-merge trivial proposed branches to main without per-change human review"}],BY_TOKEN=new Map(ENTRIES.map(entry=>[entry.token,entry])),CAPABILITY_VOCABULARY=ENTRIES;function getCapability(token){return BY_TOKEN.get(token)??null}__name(getCapability,"getCapability");function isKnownCapability(token){return BY_TOKEN.has(token)}__name(isKnownCapability,"isKnownCapability");function isDeclarableCapability(token){return getCapability(token)?.declarable===!0}__name(isDeclarableCapability,"isDeclarableCapability");function validateBundle(bundle,opts={}){let issues=[],available=new Map((opts.availableAgents??[]).map(b=>[b.name,b]));for(let i=0;i<bundle.capabilities.length;i++){let token=bundle.capabilities[i];if(token!==void 0){if(!isKnownCapability(token)){issues.push({pointer:`capabilities.yaml:[${i}]`,message:`unknown capability token: ${token}`,severity:"error"});continue}isDeclarableCapability(token)||issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is platform-internal; project-authored agents cannot declare it`,severity:"error"}),getCapability(token)?.risk==="critical"&&issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is critical-risk; requires project policy + install-time confirmation`,severity:"warning"})}}let subAgents=bundle.config.composition?.["sub-agents"]??[];subAgents.length>0&&!bundle.capabilities.includes("agent:delegate")&&issues.push({pointer:"capabilities.yaml",message:"`composition.sub-agents` is declared but `agent:delegate` capability is missing",severity:"error"});for(let i=0;i<subAgents.length;i++){let sub=subAgents[i];sub&&opts.availableAgents&&!available.has(sub.name)&&issues.push({pointer:`config.yaml:composition.sub-agents[${i}].name`,message:`sub-agent '${sub.name}' is not present in the project's agents directory`,severity:"error"})}if(opts.availableAgents&&subAgents.length>0){let cycle=detectCycle(bundle,available);cycle&&issues.push({pointer:"config.yaml:composition",message:`composition cycle detected: ${cycle.join(" \u2192 ")}`,severity:"error"})}let webhookPaths=new Set,triggers=bundle.config.triggers??[];for(let i=0;i<triggers.length;i++){let t2=triggers[i];t2&&t2.type==="webhook"&&(webhookPaths.has(t2.path)&&issues.push({pointer:`config.yaml:triggers[${i}].path`,message:`duplicate webhook path '${t2.path}' within bundle`,severity:"error"}),webhookPaths.add(t2.path))}return bundle.config.data_sources&&bundle.config.data_sources.length===0&&issues.push({pointer:"config.yaml:data_sources",message:'data_sources is empty; omit the field to default to ["main"]',severity:"warning"}),issues}__name(validateBundle,"validateBundle");function detectCycle(start,available){let color=new Map,parent2=new Map;function visit2(name){color.set(name,1);let children2=available.get(name)?.config.composition?.["sub-agents"]??[];for(let child of children2){if(!child)continue;let c2=color.get(child.name)??0;if(c2===1){let cycle=[child.name],curr=name;for(;curr&&curr!==child.name;)cycle.unshift(curr),curr=parent2.get(curr)??null;return cycle.unshift(child.name),cycle}if(c2===0&&available.has(child.name)){parent2.set(child.name,name);let found=visit2(child.name);if(found)return found}}return color.set(name,2),null}return __name(visit2,"visit"),visit2(start.name)}__name(detectCycle,"detectCycle");function agentIntegrationPolicy(config){return config.integrations??config.integration_policy??{}}__name(agentIntegrationPolicy,"agentIntegrationPolicy");function agentAllowsIntegrationTool(policy,integrationKey,toolKey){let entry=policy[integrationKey];return entry?.enabled?entry.tools===void 0||entry.tools[toolKey]===!0:!1}__name(agentAllowsIntegrationTool,"agentAllowsIntegrationTool");function enabledAgentIntegrationTools(entry,availableTools=[]){return entry?.enabled?entry.tools===void 0?[...availableTools].sort((a,b)=>a.localeCompare(b)):Object.entries(entry.tools??{}).filter(([,enabled])=>enabled).map(([tool])=>tool).sort((a,b)=>a.localeCompare(b)):[]}__name(enabledAgentIntegrationTools,"enabledAgentIntegrationTools");function _define_property2(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property2,"_define_property");var CapabilityDeniedError=class extends Error{static{__name(this,"CapabilityDeniedError")}constructor(required,granted){let def=getCapability(required),what=def?.description?` (${def.description})`:"";super(`capability '${required}'${what} denied \u2014 granted: [${granted.join(", ")}]`),_define_property2(this,"required",void 0),_define_property2(this,"granted",void 0),this.name="CapabilityDeniedError",this.required=required,this.granted=granted}};function assertCapability(required,granted){if(!granted.includes(required))throw new CapabilityDeniedError(required,granted)}__name(assertCapability,"assertCapability");function resolveSubCallCapabilities(parentGranted,subDeclared,ref){if((ref.capability_grant??"inherit")==="explicit"){let explicit=ref.explicit_grants??[];return subDeclared.filter(t2=>explicit.includes(t2))}return[...subDeclared]}__name(resolveSubCallCapabilities,"resolveSubCallCapabilities");function _define_property3(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property3,"_define_property");var BundleError=class extends Error{static{__name(this,"BundleError")}constructor(message,remediation,bundlePath){super(message),_define_property3(this,"remediation",void 0),_define_property3(this,"bundlePath",void 0),this.name=this.constructor.name,this.remediation=remediation,this.bundlePath=bundlePath}},BundleValidationError=class extends BundleError{static{__name(this,"BundleValidationError")}constructor(message,options={}){super(message,options.remediation??"Fix the file in the bundle and re-run `fimo agents validate`.",options.bundlePath),_define_property3(this,"code","bundle.validation"),_define_property3(this,"file",void 0),_define_property3(this,"cause",void 0),this.file=options.file,this.cause=options.cause}};var BundleInvalidCapabilityError=class extends BundleError{static{__name(this,"BundleInvalidCapabilityError")}constructor(token,reason,options={}){let remediation=reason==="runtime_only"?`'${token}' is reserved for the runtime \u2014 drop it from capabilities.yaml.`:options.suggestion?`Unknown capability '${token}'. Did you mean '${options.suggestion}'?`:`Unknown capability '${token}'. Run \`fimo agents list-capabilities\` to see the vocabulary.`;super(reason==="runtime_only"?`Capability '${token}' is runtime-orchestration-only and cannot be declared.`:`Capability '${token}' is not in the closed vocabulary.`,remediation,options.bundlePath),_define_property3(this,"code","bundle.invalid_capability"),_define_property3(this,"token",void 0),_define_property3(this,"reason",void 0),this.token=token,this.reason=reason}},BundleCompositionCycleError=class extends BundleError{static{__name(this,"BundleCompositionCycleError")}constructor(cycle,options={}){super(`Composition cycle detected: ${cycle.join(" \u2192 ")}`,"Break the cycle by removing one of the sub-agent references in the chain.",options.bundlePath),_define_property3(this,"code","bundle.composition_cycle"),_define_property3(this,"cycle",void 0),this.cycle=[...cycle]}},BundleTemplateNotFoundError=class extends BundleError{static{__name(this,"BundleTemplateNotFoundError")}constructor(templateName,available){super(`Template '${templateName}' not found.`,available.length>0?`Available templates: ${available.join(", ")}. Use \`fimo agents list-templates\` to see all options.`:"No templates are bundled with this CLI. Use the empty default by omitting --template."),_define_property3(this,"code","bundle.template_not_found"),_define_property3(this,"templateName",void 0),_define_property3(this,"available",void 0),this.templateName=templateName,this.available=[...available]}};function isBundleError(err){return err instanceof BundleError}__name(isBundleError,"isBundleError");function detectCompositionCycle(input){let{root:root2,agentMap}=input,WHITE=0,GRAY=1,BLACK=2,color=new Map,parent2=new Map,visit2=__name(name=>{color.set(name,GRAY);let children2=agentMap.get(name)?.config.composition?.["sub-agents"]??[];for(let child of children2){if(!child)continue;let c2=color.get(child.name)??WHITE;if(c2===GRAY){let cycle=[child.name],curr=name;for(;curr&&curr!==child.name;)cycle.unshift(curr),curr=parent2.get(curr)??null;return cycle.unshift(child.name),cycle}if(c2===WHITE&&agentMap.has(child.name)){parent2.set(child.name,name);let found=visit2(child.name);if(found)return found}}return color.set(name,BLACK),null},"visit");return visit2(root2.name)}__name(detectCompositionCycle,"detectCompositionCycle");function validateAgainstVocabulary(tokens,vocab=CAPABILITY_VOCABULARY){let byToken=new Map(vocab.map(v=>[v.token,v])),unknown2=[],nonDeclarable=[],highRisk=[];for(let token of tokens){let def=byToken.get(token);if(!def){unknown2.push(token);continue}def.declarable||nonDeclarable.push(token),(def.risk==="high"||def.risk==="critical")&&highRisk.push(token)}return{ok:unknown2.length===0&&nonDeclarable.length===0,unknown:unknown2,nonDeclarable,highRisk}}__name(validateAgainstVocabulary,"validateAgainstVocabulary");function suggestCapability(token,vocab=CAPABILITY_VOCABULARY){let best=null,bestDistance=1/0;for(let def of vocab){let d3=levenshtein(token,def.token);d3<bestDistance&&(bestDistance=d3,best=def.token)}return bestDistance<=2?best:null}__name(suggestCapability,"suggestCapability");function levenshtein(a,b){if(a===b)return 0;let al=a.length,bl=b.length;if(al===0)return bl;if(bl===0)return al;let prev2=Array.from({length:bl+1},(_,i)=>i);for(let i=1;i<=al;i++){let curr=new Array(bl+1);curr[0]=i;for(let j2=1;j2<=bl;j2++){let cost=a[i-1]===b[j2-1]?0:1;curr[j2]=Math.min((prev2[j2]??0)+1,(curr[j2-1]??0)+1,(prev2[j2-1]??0)+cost)}prev2=curr}return prev2[bl]??0}__name(levenshtein,"levenshtein");import{z as z67}from"zod";var SurfaceGuardPolicySchema=z67.enum(["block","warn","allow"]),ClassificationSchema=z67.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z67.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z67.object({enabled:z67.boolean(),allowed_skills:z67.array(z67.string().min(1)).default([]),allowed_classifications:z67.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z67.enum(["off","daily","weekly"]),NotificationFormatSchema=z67.object({markdown:z67.boolean().default(!0),html:z67.boolean().default(!1)}),NotificationsPolicySchema=z67.object({email_recipients:z67.array(z67.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z67.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z67.object({agents:FimoAgentsConfigSchema.optional()}).passthrough();function parseFimoConfig(jsonOrText,opts={}){let raw;if(typeof jsonOrText=="string")try{raw=JSON.parse(jsonOrText)}catch(err){throw new BundleValidationError(`${opts.path??".fimo/config.json"} is not valid JSON: ${err.message}`,{remediation:"Run the file through `jq .` or your editor JSON validator and fix the syntax.",file:opts.path??".fimo/config.json",cause:err})}else raw=jsonOrText;let parsed=FimoConfigSchema.safeParse(raw);if(!parsed.success){let issues=parsed.error.issues.map(i=>`${i.path.join(".")||"(root)"}: ${i.message}`).join("; ");throw new BundleValidationError(`${opts.path??".fimo/config.json"} schema validation failed: ${issues}`,{remediation:"See `.fimo/config.json` in the lifecycle docs (`fimo agents docs lifecycle` or visit lifecycle.html#config).",file:opts.path??".fimo/config.json"})}let data2=parsed.data;if(data2.agents?.auto_merge?.enabled===!0&&(data2.agents.auto_merge.allowed_classifications??[]).length===0)throw new BundleValidationError("`agents.auto_merge.enabled: true` but `allowed_classifications` is empty \u2014 nothing would ever auto-merge.",{remediation:'Either set `allowed_classifications: ["trivial"]` (or any subset) or set `enabled: false`.',file:opts.path??".fimo/config.json"});return data2}__name(parseFimoConfig,"parseFimoConfig");import{z as z68}from"zod";function toSpec(def){return{token:def.token,riskTier:def.risk,description:def.description}}__name(toSpec,"toSpec");var VOCABULARY=Object.freeze(Object.fromEntries(CAPABILITY_VOCABULARY.filter(definition=>definition.declarable).map(definition=>[definition.token,toSpec(definition)]))),CapabilityToken=z68.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z68.array(CapabilityToken);function isCapability(token){return Object.prototype.hasOwnProperty.call(VOCABULARY,token)}__name(isCapability,"isCapability");var RUNTIME_BASELINE_OPERATION_CAPABILITIES=["files:read","files:write"];function isRuntimeBaselineOperationCapability(capability){return RUNTIME_BASELINE_OPERATION_CAPABILITIES.includes(capability)}__name(isRuntimeBaselineOperationCapability,"isRuntimeBaselineOperationCapability");var OPERATION_CAP={"cms.list":"cms:read","cms.get":"cms:read","cms.query":"cms:read","cms.create":"cms:write","cms.update":"cms:write","cms.delete":"cms:write","cms.bulk_create":"cms:write","cms.bulk_update":"cms:write","cms.bulk_delete":"cms:write","cms.schema.list":"cms:schema:read","cms.schema.get":"cms:schema:read","cms.schema.push":"cms:schema:write","cms.schema.delete":"cms:schema:write","assets.list":"assets:read","assets.get":"assets:read","assets.upload":"assets:write","assets.generate":"assets:write","assets.create_folder":"assets:write","assets.move":"assets:write","assets.delete":"assets:write","i18n.list":"i18n:read","i18n.get":"i18n:read","i18n.create":"i18n:write","i18n.update":"i18n:write","i18n.delete":"i18n:write","forms.list":"forms:read","forms.get":"forms:read","forms.push":"forms:write","forms.delete":"forms:write","webhooks.events":"webhooks:read","webhooks.list":"webhooks:read","webhooks.get":"webhooks:read","webhooks.deliveries.list":"webhooks:read","webhooks.deliveries.get":"webhooks:read","webhooks.create":"webhooks:write","webhooks.update":"webhooks:write","webhooks.delete":"webhooks:write","webhooks.test":"webhooks:write","webhooks.deliveries.retry":"webhooks:write","webhooks.rotate_secret":"webhooks:write","schedules.list":"schedules:read","schedules.get":"schedules:read","schedules.runs.list":"schedules:read","schedules.runs.get":"schedules:read","schedules.create":"schedules:write","schedules.update":"schedules:write","schedules.delete":"schedules:write","schedules.pause":"schedules:write","schedules.resume":"schedules:write","schedules.run":"schedules:write","files.read":"files:read","files.write":"files:write","fimo.deploy":"fimo:deploy","fimo.logs.read":"fimo:logs:read","fimo.analytics.read":"fimo:analytics:read","fimo.preview.url":"fimo:preview:read","fimo.history.list":"fimo:history:read","fimo.history.get":"fimo:history:read","net.fetch":"net:fetch","agent.delegate":"agent:delegate","runtime.long_running":"runtime:long_running","runtime.auto_merge":"runtime:auto_merge"};function capabilityFor(op){return OPERATION_CAP[op]}__name(capabilityFor,"capabilityFor");function hasOperation(op){return Object.prototype.hasOwnProperty.call(OPERATION_CAP,op)}__name(hasOperation,"hasOperation");var import_yaml2=__toESM(require_dist(),1);function _define_property4(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property4,"_define_property");var CapabilityDenied=class extends Error{static{__name(this,"CapabilityDenied")}constructor(detail){let def=getCapability(detail.cap),description=def?.description?` (${def.description})`:"";super(`capability denied: ${detail.cap}${description} \u2014 reason: ${detail.reason}`),_define_property4(this,"cap",void 0),_define_property4(this,"reason",void 0),_define_property4(this,"granted",void 0),_define_property4(this,"sessionId",void 0),_define_property4(this,"fixHint",void 0),this.name="CapabilityDenied",this.cap=detail.cap,this.reason=detail.reason,this.granted=detail.granted??[],this.sessionId=detail.sessionId,this.fixHint=fixHintFor(detail)}};function fixHintFor(detail){switch(detail.reason){case"not-declared":return`Add '${detail.cap}' to the agent's capabilities.yaml and re-activate.`;case"session-not-found":return`Session '${detail.sessionId??"<unknown>"}' does not exist or has expired.`;case"snapshot-stale":return"Session capability snapshot is corrupted. Restart the agent session.";case"runtime-only":return`'${detail.cap}' is reserved for the platform \u2014 drop it from capabilities.yaml.`;case"auto-merge-blocked":return"runtime:auto_merge is declared but blocked by project policy (.fimo/config.json \u2192 agents.auto_merge)."}}__name(fixHintFor,"fixHintFor");var configured=null;async function auditCapabilityDecision(event){if(!configured)return;let row2={...event,ts:new Date().toISOString()};if(event.decision==="deny"){try{await configured.transport.write(row2)}catch(err){throw configured.breadcrumb?.({category:"audit",level:"error",message:"audit deny row write failed",data:{cap:event.cap,error:err.message}}),err}configured.breadcrumb?.({category:"audit",level:"warning",message:`capability denied: ${event.cap}`,data:{sessionId:event.sessionId,cap:event.cap,reason:event.reason}});return}configured.transport.write(row2).catch(err=>{configured?.breadcrumb?.({category:"audit",level:"warning",message:"audit allow row write failed (best-effort)",data:{cap:event.cap,error:err.message}})})}__name(auditCapabilityDecision,"auditCapabilityDecision");var composition_exports={};__export(composition_exports,{CompositionError:()=>CompositionError,InvalidExplicitGrantsError:()=>InvalidExplicitGrantsError,MAX_DELEGATION_DEPTH:()=>MAX_DELEGATION_DEPTH,MaxDelegationDepthError:()=>MaxDelegationDepthError,SubAgentInvocationError:()=>SubAgentInvocationError,SubAgentNotInProjectError:()=>SubAgentNotInProjectError,UnknownSubAgentError:()=>UnknownSubAgentError,createDelegateTool:()=>createDelegateTool,delegate:()=>delegate,detectCompositionCycle:()=>detectCompositionCycle,detectCycle:()=>detectCycle2,isCompositionError:()=>isCompositionError,resolveSubCallCapabilities:()=>resolveSubCallCapabilities2,resolveSubCallCapabilitiesLenient:()=>resolveSubCallCapabilities,resolveTransitiveCapabilities:()=>resolveTransitiveCapabilities,validateComposition:()=>validateComposition});function resolveTransitiveCapabilities(bundle,allBundles){let union2=new Set,missing=[],visited=new Set,visit2=__name(b=>{if(visited.has(b.name))return;visited.add(b.name);for(let token of b.capabilities)isCapability(token)&&union2.add(token);let subAgents=b.config.composition?.["sub-agents"]??[];for(let ref of subAgents){let sub=allBundles.get(ref.name);if(!sub){missing.includes(ref.name)||missing.push(ref.name);continue}visit2(sub)}},"visit");return visit2(bundle),{union:Array.from(union2).sort(),missing}}__name(resolveTransitiveCapabilities,"resolveTransitiveCapabilities");function detectCycle2(rootKey,nodes){if(!new Map(nodes.map(n=>[n.key,n])).get(rootKey))return null;let bundleMap=new Map;for(let node of nodes)bundleMap.set(node.key,{name:node.key,capabilities:[],config:{version:1,composition:{"sub-agents":node.subAgentKeys.map(k=>({name:k}))}}});let root2=bundleMap.get(rootKey);return detectCompositionCycle({root:root2,agentMap:bundleMap})}__name(detectCycle2,"detectCycle");function validateComposition(root2,allBundles){let cycle=detectCompositionCycle({root:root2,agentMap:allBundles}),missing=[],invalidGrants=[],capUnion=new Set,visited=new Set,visit2=__name(bundle=>{if(visited.has(bundle.name))return;visited.add(bundle.name);for(let token of bundle.capabilities)isCapability(token)&&capUnion.add(token);let subAgents=bundle.config.composition?.["sub-agents"]??[];for(let ref of subAgents){let sub=allBundles.get(ref.name);if(!sub){missing.includes(ref.name)||missing.push(ref.name);continue}if(ref.capability_grant==="explicit"){let declaredSet=new Set(sub.capabilities),invalid=(ref.explicit_grants??[]).filter(t2=>!declaredSet.has(t2));invalid.length>0&&invalidGrants.push({subAgentName:ref.name,invalid,declared:[...sub.capabilities]})}visit2(sub)}},"visit");if(!cycle)visit2(root2);else for(let token of root2.capabilities)isCapability(token)&&capUnion.add(token);let declaredDelegate=root2.capabilities.includes("agent:delegate");return{cycle,missing,transitiveCapabilities:Array.from(capUnion).sort(),declaredDelegate,invalidGrants}}__name(validateComposition,"validateComposition");function _define_property5(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property5,"_define_property");var CompositionError=class extends Error{static{__name(this,"CompositionError")}},InvalidExplicitGrantsError=class extends CompositionError{static{__name(this,"InvalidExplicitGrantsError")}constructor(subAgentName,invalid,declared){super(`composition.sub-agents[name=${subAgentName}].explicit_grants references capabilities the sub-agent never declared: [${invalid.join(", ")}]. Declared by sub-agent: [${declared.join(", ")}]`),_define_property5(this,"code","composition.invalid_explicit_grants"),_define_property5(this,"subAgentName",void 0),_define_property5(this,"invalid",void 0),_define_property5(this,"declared",void 0),this.name="InvalidExplicitGrantsError",this.subAgentName=subAgentName,this.invalid=invalid,this.declared=declared}},SubAgentInvocationError=class extends CompositionError{static{__name(this,"SubAgentInvocationError")}constructor(subAgentName,cause){super(`sub-agent '${subAgentName}' threw during invocation: ${cause?.message??String(cause)}`),_define_property5(this,"code","composition.sub_agent_invocation_failed"),_define_property5(this,"subAgentName",void 0),this.name="SubAgentInvocationError",this.subAgentName=subAgentName,this.cause=cause}};function isCompositionError(err){return err instanceof CompositionError?!0:err instanceof Error?err.name==="MaxDelegationDepthError"||err.name==="UnknownSubAgentError"||err.name==="SubAgentNotInProjectError":!1}__name(isCompositionError,"isCompositionError");function resolveSubCallCapabilities2(input){let{parentCapabilities,subAgentDeclared,ref}=input;if((ref.capability_grant??"inherit")==="explicit"){let explicitGrants=ref.explicit_grants??[],declaredSet=new Set(subAgentDeclared),invalid=explicitGrants.filter(t2=>!declaredSet.has(t2));if(invalid.length>0)throw new InvalidExplicitGrantsError(ref.name,invalid,subAgentDeclared)}return resolveSubCallCapabilities(parentCapabilities,subAgentDeclared,ref)}__name(resolveSubCallCapabilities2,"resolveSubCallCapabilities");function _define_property6(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property6,"_define_property");var MAX_DELEGATION_DEPTH=5,MaxDelegationDepthError=class extends Error{static{__name(this,"MaxDelegationDepthError")}constructor(depth){super(`max delegation depth ${depth} reached (limit ${MAX_DELEGATION_DEPTH})`),_define_property6(this,"depth",void 0),this.name="MaxDelegationDepthError",this.depth=depth}},UnknownSubAgentError=class extends Error{static{__name(this,"UnknownSubAgentError")}constructor(name){super(`sub-agent '${name}' is not declared in composition.sub-agents`),_define_property6(this,"name_",void 0),this.name="UnknownSubAgentError",this.name_=name}},SubAgentNotInProjectError=class extends Error{static{__name(this,"SubAgentNotInProjectError")}constructor(name){super(`sub-agent '${name}' is declared but not present in agents/ directory`),_define_property6(this,"name_",void 0),this.name="SubAgentNotInProjectError",this.name_=name}};async function delegate(input,ctx,runSubAgent){if(assertCapability("agent:delegate",ctx.parentCapabilities),ctx.depth>=MAX_DELEGATION_DEPTH)throw new MaxDelegationDepthError(ctx.depth);let ref=(ctx.parentBundle.config.composition?.["sub-agents"]??[]).find(r=>r.name===input.name);if(!ref)throw new UnknownSubAgentError(input.name);let sub=ctx.projectBundles.find(b=>b.name===ref.name);if(!sub)throw new SubAgentNotInProjectError(ref.name);let subCallCapabilities=resolveSubCallCapabilities(ctx.parentCapabilities,sub.capabilities,ref);return{result:await runSubAgent(sub,subCallCapabilities,input.args),subCallCapabilities}}__name(delegate,"delegate");function createDelegateTool(opts){return __name(async function(input){let{session,runSubAgent,audit}=opts,started=Date.now(),parentCaps=session.capabilityStack[session.capabilityStack.length-1]??session.parentBundle.capabilities,ctx={parentBundle:session.parentBundle,parentCapabilities:parentCaps,depth:session.depth,projectBundles:session.projectBundles};try{let grantMode=(session.parentBundle.config.composition?.["sub-agents"]??[]).find(r=>r.name===input.name)?.capability_grant??"inherit";session.depth+=1;let result=await delegate(input,ctx,__name(async(sub,capabilities,args)=>{session.capabilityStack.push([...capabilities]);try{return await runSubAgent(sub,capabilities,args)}finally{session.capabilityStack.pop()}},"wrappedRunSubAgent"));return await audit?.emit({subAgentName:input.name,grantMode,resolvedCapabilities:result.subCallCapabilities,args:input.args,durationMs:Date.now()-started,depth:ctx.depth}),result}catch(err){let wrapped=err instanceof SubAgentInvocationError?err:new SubAgentInvocationError(input.name,err);throw await audit?.emit({subAgentName:input.name,grantMode:"inherit",resolvedCapabilities:[],args:input.args,durationMs:Date.now()-started,depth:ctx.depth,error:{name:err.name??"Error",message:err.message??String(err)}}),wrapped}finally{session.depth-=1}},"delegateFn")}__name(createDelegateTool,"createDelegateTool");init_dist();init_scaffold();import fs8 from"node:fs";import path8 from"node:path";init_dist();init_auth_errors();init_project();var NAME_RE=/^[a-z][a-z0-9-]*$/;function isValidAgentName(name){return name.length===0||name.length>64?!1:NAME_RE.test(name)}__name(isValidAgentName,"isValidAgentName");var InvalidAgentNameError=class extends Error{static{__name(this,"InvalidAgentNameError")}name="InvalidAgentNameError";attempted;constructor(attempted){super(`'${attempted}' is not a valid agent name. Names must be lowercase, start with a letter, and contain only letters/digits/hyphens.`),this.attempted=attempted}};function resolveProjectRoot(cwd=process.cwd()){let dir=path8.resolve(cwd);for(let i=0;i<8;i++){if(fs8.existsSync(resolveProjectConfigPath(dir))||fs8.existsSync(path8.join(dir,"package.json")))return dir;let parent2=path8.dirname(dir);if(parent2===dir)break;dir=parent2}throw new Error(`Could not find a project root (no Fimo config or package.json) under ${cwd}. Run \`fimo agents *\` from inside a project.`)}__name(resolveProjectRoot,"resolveProjectRoot");function resolveFimoProject(cwd=process.cwd()){let projectRoot=findProjectRoot(cwd);if(!projectRoot)return null;try{return{projectRoot,settings:loadProjectSettings(projectRoot)}}catch{return null}}__name(resolveFimoProject,"resolveFimoProject");function resolveAgentBundlesDir(projectRoot){return resolveProjectAgentsDir(projectRoot)}__name(resolveAgentBundlesDir,"resolveAgentBundlesDir");function printBundleError(command,err){if(rethrowCliAuthError(err),isBundleError(err)){let e=err,hintParts=[];e.remediation&&hintParts.push(`fix: ${e.remediation}`),e.bundlePath&&hintParts.push(`at: ${e.bundlePath}`),ui.error({command,code:"AGENT_BUNDLE_ERROR",message:e.message,hint:hintParts.length>0?hintParts.join(" \xB7 "):void 0})}else ui.error({command,code:"AGENT_BUNDLE_ERROR",message:err.message??String(err)})}__name(printBundleError,"printBundleError");async function createAgent(opts){if(!isValidAgentName(opts.name))throw new InvalidAgentNameError(opts.name);let cwd=opts.cwd??process.cwd(),projectRoot;if(opts.requireFimoProject){let resolved=resolveFimoProject(cwd);if(!resolved)return{ok:!1,error:"Not inside a linked Fimo project. Run from inside a Fimo project, or pass -C <dir>."};projectRoot=resolved.projectRoot}else projectRoot=resolveProjectRoot(cwd);let targetDir=path9.join(resolveAgentBundlesDir(projectRoot),opts.name);if(fs9.existsSync(targetDir))return{ok:!1,error:`${path9.relative(projectRoot,targetDir)}/ already exists. Pick a different name or remove the existing directory first.`};let templateName=opts.template??"_default",templateRoot;try{templateRoot=resolveAgentTemplate(templateName)}catch{let available=listAgentTemplates().map(t2=>t2.name);throw new BundleTemplateNotFoundError(templateName,available)}return await copyAgentTemplate(templateRoot,targetDir),opts.description!==void 0&&writeDescriptionToConfig(path9.join(targetDir,"config.yaml"),opts.description),{ok:!0,agentDir:targetDir}}__name(createAgent,"createAgent");function writeDescriptionToConfig(configPath,description){let content2=fs9.readFileSync(configPath,"utf8"),line=`description: ${JSON.stringify(description)}`,next2;/^description:.*$/m.test(content2)?next2=content2.replace(/^description:.*$/m,line):/^version:\s*\d+.*$/m.test(content2)?next2=content2.replace(/^(version:\s*\d+.*)$/m,`$1
|
|
1181
|
+
${environmentStatus}`},"render")})}var SOFT_TIMEOUT_MS,init_status=__esm({"src/cli/commands/status.ts"(){init_dist();init_api();init_environment_checkout();init_color();init_render_status();init_git_credential_setup();init_git();init_project_context();init_project();SOFT_TIMEOUT_MS=2e3;__name(withCheckoutRecovery,"withCheckoutRecovery");__name(localCheckoutStatus,"localCheckoutStatus");__name(renderLocalCheckoutStatus,"renderLocalCheckoutStatus");__name(pickSurfaces,"pickSurfaces");__name(withSoftTimeout,"withSoftTimeout");__name(localCodeSurface,"localCodeSurface");__name(mergeCodeSurfaces,"mergeCodeSurfaces");__name(statusCommand2,"statusCommand")}});init_dist();import fs46 from"node:fs";import path48 from"node:path";var import_index=__toESM(require_commander(),1),{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import_index.default;init_api();import fs9 from"node:fs";import path9 from"node:path";var import_yaml=__toESM(require_dist(),1);import{createHash as createHash2}from"node:crypto";import{promises}from"node:fs";import path4 from"node:path";import{z as z68}from"zod";var CapabilityTokenSchema=z68.string().min(1).regex(/^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?$/,{error:"capability tokens must match verb:noun or verb:noun:qualifier (lowercase + digits + underscores; must start with a letter)"}),CapabilitiesFileSchema=z68.array(CapabilityTokenSchema);import{z as z69}from"zod";var CronTriggerSchema=z69.object({type:z69.literal("schedule"),cron:z69.string().min(1,"cron expression required"),tz:z69.string().optional()}),ManualTriggerSchema2=z69.object({type:z69.literal("manual")}),WebhookTriggerSchema2=z69.object({type:z69.literal("webhook"),path:z69.string().min(1).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z69.discriminatedUnion("type",[ManualTriggerSchema2,CronTriggerSchema,WebhookTriggerSchema2]),SubAgentRefSchema=z69.object({name:z69.string().min(1),capability_grant:z69.enum(["inherit","explicit"]).optional(),explicit_grants:z69.array(z69.string()).optional()}).refine(v=>v.capability_grant!=="explicit"||Array.isArray(v.explicit_grants)&&v.explicit_grants.length>0,{message:"`explicit_grants` is required when `capability_grant: explicit`",path:["explicit_grants"]}),CompositionConfigSchema=z69.object({"sub-agents":z69.array(SubAgentRefSchema)}),RuntimeConfigSchema=z69.object({cloud:z69.boolean().optional(),dev:z69.boolean().optional(),long_running:z69.boolean().optional()}),DataSourceSchema=z69.enum(["main","prod"]),ConfigValueKeySchema=z69.string().min(1).max(255).regex(/^[A-Z_][A-Z0-9_]*$/,"secret keys must be UPPER_SNAKE_CASE and start with a letter or underscore"),PUBLIC_CONFIG_PREFIX=/^(PUBLIC_|VITE_|NEXT_PUBLIC_)/,AgentSecretRequestSchema=z69.preprocess(value=>typeof value=="string"?{key:value}:value,z69.object({key:ConfigValueKeySchema.refine(key=>!PUBLIC_CONFIG_PREFIX.test(key),{message:"agent secrets cannot use public variable prefixes (PUBLIC_, VITE_, NEXT_PUBLIC_)"}),required:z69.boolean().default(!0),delivery:z69.literal("process_env").default("process_env")})),IntegrationKeySchema=z69.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*$/,"integration keys must be lowercase alphanumeric with optional _ or -"),IntegrationToolKeySchema=z69.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)*$/,"integration tool keys must be lowercase dot-separated identifiers with optional _ or -"),IntegrationPolicyEntrySchema=z69.preprocess(value=>typeof value=="boolean"?{enabled:value}:value,z69.object({enabled:z69.boolean().default(!0),tools:z69.record(IntegrationToolKeySchema,z69.boolean()).optional()})),IntegrationPolicySchema=z69.record(IntegrationKeySchema,IntegrationPolicyEntrySchema),AgentConfigSchema=z69.object({version:z69.literal(1),description:z69.string().min(1).max(280).optional(),runtime:RuntimeConfigSchema.optional(),triggers:z69.array(TriggerSchema2).optional(),composition:CompositionConfigSchema.optional(),data_sources:z69.array(DataSourceSchema).optional(),secrets:z69.array(AgentSecretRequestSchema).optional(),integrations:IntegrationPolicySchema.optional(),integration_policy:IntegrationPolicySchema.optional()}).refine(config=>!(config.integrations&&config.integration_policy),{message:"use either `integrations` or legacy `integration_policy`, not both",path:["integrations"]});function _define_property(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property,"_define_property");var BundleParseError=class extends Error{static{__name(this,"BundleParseError")}constructor(bundlePath,file,message,cause){super(`[${file}] ${message}`),_define_property(this,"bundlePath",void 0),_define_property(this,"file",void 0),_define_property(this,"cause",void 0),this.name="BundleParseError",this.bundlePath=bundlePath,this.file=file,this.cause=cause}};async function fileExists(file){try{return(await promises.stat(file)).isFile()}catch{return!1}}__name(fileExists,"fileExists");async function readFileOrNull(file){try{return await promises.readFile(file,"utf8")}catch(err){if(err.code==="ENOENT")return null;throw err}}__name(readFileOrNull,"readFileOrNull");async function listDir(dir){try{return(await promises.readdir(dir,{withFileTypes:!0,recursive:!0})).filter(e=>e.isFile()).map(e=>{let parentPath=e.parentPath??e.path??dir;return path4.relative(dir,path4.join(parentPath,e.name))}).sort()}catch(err){if(err.code==="ENOENT")return[];throw err}}__name(listDir,"listDir");function parseYamlStrict(text3,file,bundlePath){try{return(0,import_yaml.parse)(text3)}catch(err){throw new BundleParseError(bundlePath,file,`invalid YAML: ${err.message}`,err)}}__name(parseYamlStrict,"parseYamlStrict");function formatZodIssue(issue){return`${issue.path.length===0?"(root)":issue.path.join(".")}: ${issue.message}`}__name(formatZodIssue,"formatZodIssue");async function parseBundle(bundlePath,opts={}){let name=path4.basename(bundlePath),goalPath=path4.join(bundlePath,"GOAL.md"),goal=await readFileOrNull(goalPath);if(goal===null)throw new BundleParseError(bundlePath,"GOAL.md","GOAL.md is required but missing");if(goal.trim().length===0)throw new BundleParseError(bundlePath,"GOAL.md","GOAL.md is empty");let configPath=path4.join(bundlePath,"config.yaml"),configRaw=await readFileOrNull(configPath),config;if(configRaw===null){if(!opts.defaultConfig)throw new BundleParseError(bundlePath,"config.yaml","config.yaml is required but missing");config={version:1}}else{let yamlData=parseYamlStrict(configRaw,"config.yaml",bundlePath),parsed=AgentConfigSchema.safeParse(yamlData);if(!parsed.success){let issues=parsed.error.issues.map(formatZodIssue).join("; ");throw new BundleParseError(bundlePath,"config.yaml",`schema validation failed: ${issues}`)}config=parsed.data}let soul=await readFileOrNull(path4.join(bundlePath,"SOUL.md")),capsPath=path4.join(bundlePath,"capabilities.yaml"),capsRaw=await readFileOrNull(capsPath),capabilities=[];if(capsRaw!==null){let candidate=parseYamlStrict(capsRaw,"capabilities.yaml",bundlePath)??[],parsed=CapabilitiesFileSchema.safeParse(candidate);if(!parsed.success){let issues=parsed.error.issues.map(formatZodIssue).join("; ");throw new BundleParseError(bundlePath,"capabilities.yaml",`schema validation failed: ${issues} \u2014 file must be a bare YAML list of capability tokens`)}capabilities=parsed.data}let[scripts2,references,assets3]=await Promise.all([listDir(path4.join(bundlePath,"scripts")),listDir(path4.join(bundlePath,"references")),listDir(path4.join(bundlePath,"assets"))]),warnings=[],pluginsDir=path4.join(bundlePath,"plugins");try{(await promises.stat(pluginsDir)).isDirectory()&&warnings.push({pointer:"plugins/",message:"`plugins/` is reserved for v1.x and will be ignored at runtime."})}catch{}let checksum=await computeBundleChecksum(bundlePath,{goal,soul,configRaw,capsRaw,scripts:scripts2,references,assets:assets3});return{name,path:bundlePath,goal,soul,config,capabilities,scripts:scripts2,references,assets:assets3,checksum,warnings}}__name(parseBundle,"parseBundle");async function computeBundleChecksum(bundlePath,parts){let hash=createHash2("sha256");hash.update("GOAL.md\0"),hash.update(parts.goal),hash.update("\0config.yaml\0"),hash.update(parts.configRaw??""),parts.capsRaw!==null&&(hash.update("\0capabilities.yaml\0"),hash.update(parts.capsRaw)),parts.soul!==null&&(hash.update("\0SOUL.md\0"),hash.update(parts.soul));let dirs=[["scripts",parts.scripts],["references",parts.references],["assets",parts.assets]];for(let[dirName,files]of dirs)for(let rel of files){let filePath=path4.join(bundlePath,dirName,rel);try{let buf=await promises.readFile(filePath);hash.update(`\0${dirName}/${rel}\0`),hash.update(buf)}catch{}}return hash.digest("hex")}__name(computeBundleChecksum,"computeBundleChecksum");async function listBundles(agentsDir){let entries2=[];try{entries2=await promises.readdir(agentsDir,{withFileTypes:!0})}catch(err){if(err.code==="ENOENT")return[];throw err}let bundles=[];for(let entry of entries2){if(!entry.isDirectory())continue;let bundlePath=path4.join(agentsDir,entry.name);if(await fileExists(path4.join(bundlePath,"GOAL.md")))try{bundles.push(await parseBundle(bundlePath))}catch{}}return bundles.sort((a,b)=>a.name.localeCompare(b.name))}__name(listBundles,"listBundles");var ENTRIES=[{token:"files:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read project files"},{token:"files:write",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Write or delete project files"},{token:"cms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS content"},{token:"cms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Create, update, or delete CMS entries"},{token:"cms:schema:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS schemas"},{token:"cms:schema:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Modify CMS schemas (destructive \u2014 alters all entries of the type)"},{token:"assets:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read uploaded media"},{token:"assets:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Upload, replace, or delete media"},{token:"i18n:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read translation catalogs"},{token:"i18n:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify translation catalogs via the fimo i18n CLI"},{token:"forms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read form schemas and submissions"},{token:"forms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify form schemas or clear submissions"},{token:"webhooks:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read webhook configurations and delivery history"},{token:"webhooks:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger webhooks that send project data to external URLs"},{token:"schedules:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read schedule configurations and run history"},{token:"schedules:write",risk:"critical",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger scheduled commands that run with publish and code-edit rights"},{token:"git:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read git state"},{token:"git:branch",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Create agent-proposed branches off main"},{token:"git:commit",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Commit changes to an agent branch"},{token:"git:push",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Push to the project remote (main push is intercepted)"},{token:"git:tag",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Used by runtime for prod release tags; agents cannot call directly"},{token:"fimo:deploy",risk:"critical",declarable:!0,enforcedBy:"api",description:"Trigger a production deploy"},{token:"fimo:logs:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read production logs"},{token:"fimo:analytics:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read analytics data"},{token:"fimo:domains:manage",risk:"high",declarable:!0,enforcedBy:"api",description:"Read and manage project domains"},{token:"fimo:agents:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run project agents"},{token:"fimo:preview:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read a current preview URL for an env (no commit, no deploy)"},{token:"fimo:history:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project restore points"},{token:"net:fetch",risk:"medium",declarable:!0,enforcedBy:"runtime",description:"Make outbound HTTP requests"},{token:"integrations:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run enabled project integration tools allowed by the agent policy"},{token:"shell:exec",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Run arbitrary shell commands inside the sandbox"},{token:"agent:delegate",risk:"medium",declarable:!0,enforcedBy:"engine",description:"Invoke declared sub-agents"},{token:"runtime:long_running",risk:"high",declarable:!0,enforcedBy:"runtime",description:"Run autonomously past the default 30 min limit (up to 4h walltime / 12h ceiling)"},{token:"runtime:auto_merge",risk:"critical",declarable:!0,enforcedBy:"runtime",description:"Auto-merge trivial proposed branches to main without per-change human review"}],BY_TOKEN=new Map(ENTRIES.map(entry=>[entry.token,entry])),CAPABILITY_VOCABULARY=ENTRIES;function getCapability(token){return BY_TOKEN.get(token)??null}__name(getCapability,"getCapability");function isKnownCapability(token){return BY_TOKEN.has(token)}__name(isKnownCapability,"isKnownCapability");function isDeclarableCapability(token){return getCapability(token)?.declarable===!0}__name(isDeclarableCapability,"isDeclarableCapability");function validateBundle(bundle,opts={}){let issues=[],available=new Map((opts.availableAgents??[]).map(b=>[b.name,b]));for(let i=0;i<bundle.capabilities.length;i++){let token=bundle.capabilities[i];if(token!==void 0){if(!isKnownCapability(token)){issues.push({pointer:`capabilities.yaml:[${i}]`,message:`unknown capability token: ${token}`,severity:"error"});continue}isDeclarableCapability(token)||issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is platform-internal; project-authored agents cannot declare it`,severity:"error"}),getCapability(token)?.risk==="critical"&&issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is critical-risk; requires project policy + install-time confirmation`,severity:"warning"})}}let subAgents=bundle.config.composition?.["sub-agents"]??[];subAgents.length>0&&!bundle.capabilities.includes("agent:delegate")&&issues.push({pointer:"capabilities.yaml",message:"`composition.sub-agents` is declared but `agent:delegate` capability is missing",severity:"error"});for(let i=0;i<subAgents.length;i++){let sub=subAgents[i];sub&&opts.availableAgents&&!available.has(sub.name)&&issues.push({pointer:`config.yaml:composition.sub-agents[${i}].name`,message:`sub-agent '${sub.name}' is not present in the project's agents directory`,severity:"error"})}if(opts.availableAgents&&subAgents.length>0){let cycle=detectCycle(bundle,available);cycle&&issues.push({pointer:"config.yaml:composition",message:`composition cycle detected: ${cycle.join(" \u2192 ")}`,severity:"error"})}let webhookPaths=new Set,triggers=bundle.config.triggers??[];for(let i=0;i<triggers.length;i++){let t2=triggers[i];t2&&t2.type==="webhook"&&(webhookPaths.has(t2.path)&&issues.push({pointer:`config.yaml:triggers[${i}].path`,message:`duplicate webhook path '${t2.path}' within bundle`,severity:"error"}),webhookPaths.add(t2.path))}return bundle.config.data_sources&&bundle.config.data_sources.length===0&&issues.push({pointer:"config.yaml:data_sources",message:'data_sources is empty; omit the field to default to ["main"]',severity:"warning"}),issues}__name(validateBundle,"validateBundle");function detectCycle(start,available){let color=new Map,parent2=new Map;function visit2(name){color.set(name,1);let children2=available.get(name)?.config.composition?.["sub-agents"]??[];for(let child of children2){if(!child)continue;let c2=color.get(child.name)??0;if(c2===1){let cycle=[child.name],curr=name;for(;curr&&curr!==child.name;)cycle.unshift(curr),curr=parent2.get(curr)??null;return cycle.unshift(child.name),cycle}if(c2===0&&available.has(child.name)){parent2.set(child.name,name);let found=visit2(child.name);if(found)return found}}return color.set(name,2),null}return __name(visit2,"visit"),visit2(start.name)}__name(detectCycle,"detectCycle");function agentIntegrationPolicy(config){return config.integrations??config.integration_policy??{}}__name(agentIntegrationPolicy,"agentIntegrationPolicy");function agentAllowsIntegrationTool(policy,integrationKey,toolKey){let entry=policy[integrationKey];return entry?.enabled?entry.tools===void 0||entry.tools[toolKey]===!0:!1}__name(agentAllowsIntegrationTool,"agentAllowsIntegrationTool");function enabledAgentIntegrationTools(entry,availableTools=[]){return entry?.enabled?entry.tools===void 0?[...availableTools].sort((a,b)=>a.localeCompare(b)):Object.entries(entry.tools??{}).filter(([,enabled])=>enabled).map(([tool])=>tool).sort((a,b)=>a.localeCompare(b)):[]}__name(enabledAgentIntegrationTools,"enabledAgentIntegrationTools");function _define_property2(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property2,"_define_property");var CapabilityDeniedError=class extends Error{static{__name(this,"CapabilityDeniedError")}constructor(required,granted){let def=getCapability(required),what=def?.description?` (${def.description})`:"";super(`capability '${required}'${what} denied \u2014 granted: [${granted.join(", ")}]`),_define_property2(this,"required",void 0),_define_property2(this,"granted",void 0),this.name="CapabilityDeniedError",this.required=required,this.granted=granted}};function assertCapability(required,granted){if(!granted.includes(required))throw new CapabilityDeniedError(required,granted)}__name(assertCapability,"assertCapability");function resolveSubCallCapabilities(parentGranted,subDeclared,ref){if((ref.capability_grant??"inherit")==="explicit"){let explicit=ref.explicit_grants??[];return subDeclared.filter(t2=>explicit.includes(t2))}return[...subDeclared]}__name(resolveSubCallCapabilities,"resolveSubCallCapabilities");function _define_property3(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property3,"_define_property");var BundleError=class extends Error{static{__name(this,"BundleError")}constructor(message,remediation,bundlePath){super(message),_define_property3(this,"remediation",void 0),_define_property3(this,"bundlePath",void 0),this.name=this.constructor.name,this.remediation=remediation,this.bundlePath=bundlePath}},BundleValidationError=class extends BundleError{static{__name(this,"BundleValidationError")}constructor(message,options={}){super(message,options.remediation??"Fix the file in the bundle and re-run `fimo agents validate`.",options.bundlePath),_define_property3(this,"code","bundle.validation"),_define_property3(this,"file",void 0),_define_property3(this,"cause",void 0),this.file=options.file,this.cause=options.cause}};var BundleInvalidCapabilityError=class extends BundleError{static{__name(this,"BundleInvalidCapabilityError")}constructor(token,reason,options={}){let remediation=reason==="runtime_only"?`'${token}' is reserved for the runtime \u2014 drop it from capabilities.yaml.`:options.suggestion?`Unknown capability '${token}'. Did you mean '${options.suggestion}'?`:`Unknown capability '${token}'. Run \`fimo agents list-capabilities\` to see the vocabulary.`;super(reason==="runtime_only"?`Capability '${token}' is runtime-orchestration-only and cannot be declared.`:`Capability '${token}' is not in the closed vocabulary.`,remediation,options.bundlePath),_define_property3(this,"code","bundle.invalid_capability"),_define_property3(this,"token",void 0),_define_property3(this,"reason",void 0),this.token=token,this.reason=reason}},BundleCompositionCycleError=class extends BundleError{static{__name(this,"BundleCompositionCycleError")}constructor(cycle,options={}){super(`Composition cycle detected: ${cycle.join(" \u2192 ")}`,"Break the cycle by removing one of the sub-agent references in the chain.",options.bundlePath),_define_property3(this,"code","bundle.composition_cycle"),_define_property3(this,"cycle",void 0),this.cycle=[...cycle]}},BundleTemplateNotFoundError=class extends BundleError{static{__name(this,"BundleTemplateNotFoundError")}constructor(templateName,available){super(`Template '${templateName}' not found.`,available.length>0?`Available templates: ${available.join(", ")}. Use \`fimo agents list-templates\` to see all options.`:"No templates are bundled with this CLI. Use the empty default by omitting --template."),_define_property3(this,"code","bundle.template_not_found"),_define_property3(this,"templateName",void 0),_define_property3(this,"available",void 0),this.templateName=templateName,this.available=[...available]}};function isBundleError(err){return err instanceof BundleError}__name(isBundleError,"isBundleError");function detectCompositionCycle(input){let{root:root2,agentMap}=input,WHITE=0,GRAY=1,BLACK=2,color=new Map,parent2=new Map,visit2=__name(name=>{color.set(name,GRAY);let children2=agentMap.get(name)?.config.composition?.["sub-agents"]??[];for(let child of children2){if(!child)continue;let c2=color.get(child.name)??WHITE;if(c2===GRAY){let cycle=[child.name],curr=name;for(;curr&&curr!==child.name;)cycle.unshift(curr),curr=parent2.get(curr)??null;return cycle.unshift(child.name),cycle}if(c2===WHITE&&agentMap.has(child.name)){parent2.set(child.name,name);let found=visit2(child.name);if(found)return found}}return color.set(name,BLACK),null},"visit");return visit2(root2.name)}__name(detectCompositionCycle,"detectCompositionCycle");function validateAgainstVocabulary(tokens,vocab=CAPABILITY_VOCABULARY){let byToken=new Map(vocab.map(v=>[v.token,v])),unknown2=[],nonDeclarable=[],highRisk=[];for(let token of tokens){let def=byToken.get(token);if(!def){unknown2.push(token);continue}def.declarable||nonDeclarable.push(token),(def.risk==="high"||def.risk==="critical")&&highRisk.push(token)}return{ok:unknown2.length===0&&nonDeclarable.length===0,unknown:unknown2,nonDeclarable,highRisk}}__name(validateAgainstVocabulary,"validateAgainstVocabulary");function suggestCapability(token,vocab=CAPABILITY_VOCABULARY){let best=null,bestDistance=1/0;for(let def of vocab){let d3=levenshtein(token,def.token);d3<bestDistance&&(bestDistance=d3,best=def.token)}return bestDistance<=2?best:null}__name(suggestCapability,"suggestCapability");function levenshtein(a,b){if(a===b)return 0;let al=a.length,bl=b.length;if(al===0)return bl;if(bl===0)return al;let prev2=Array.from({length:bl+1},(_,i)=>i);for(let i=1;i<=al;i++){let curr=new Array(bl+1);curr[0]=i;for(let j2=1;j2<=bl;j2++){let cost=a[i-1]===b[j2-1]?0:1;curr[j2]=Math.min((prev2[j2]??0)+1,(curr[j2-1]??0)+1,(prev2[j2-1]??0)+cost)}prev2=curr}return prev2[bl]??0}__name(levenshtein,"levenshtein");import{z as z70}from"zod";var SurfaceGuardPolicySchema=z70.enum(["block","warn","allow"]),ClassificationSchema=z70.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z70.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z70.object({enabled:z70.boolean(),allowed_skills:z70.array(z70.string().min(1)).default([]),allowed_classifications:z70.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z70.enum(["off","daily","weekly"]),NotificationFormatSchema=z70.object({markdown:z70.boolean().default(!0),html:z70.boolean().default(!1)}),NotificationsPolicySchema=z70.object({email_recipients:z70.array(z70.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z70.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z70.object({agents:FimoAgentsConfigSchema.optional()}).passthrough();function parseFimoConfig(jsonOrText,opts={}){let raw;if(typeof jsonOrText=="string")try{raw=JSON.parse(jsonOrText)}catch(err){throw new BundleValidationError(`${opts.path??".fimo/config.json"} is not valid JSON: ${err.message}`,{remediation:"Run the file through `jq .` or your editor JSON validator and fix the syntax.",file:opts.path??".fimo/config.json",cause:err})}else raw=jsonOrText;let parsed=FimoConfigSchema.safeParse(raw);if(!parsed.success){let issues=parsed.error.issues.map(i=>`${i.path.join(".")||"(root)"}: ${i.message}`).join("; ");throw new BundleValidationError(`${opts.path??".fimo/config.json"} schema validation failed: ${issues}`,{remediation:"See `.fimo/config.json` in the lifecycle docs (`fimo agents docs lifecycle` or visit lifecycle.html#config).",file:opts.path??".fimo/config.json"})}let data2=parsed.data;if(data2.agents?.auto_merge?.enabled===!0&&(data2.agents.auto_merge.allowed_classifications??[]).length===0)throw new BundleValidationError("`agents.auto_merge.enabled: true` but `allowed_classifications` is empty \u2014 nothing would ever auto-merge.",{remediation:'Either set `allowed_classifications: ["trivial"]` (or any subset) or set `enabled: false`.',file:opts.path??".fimo/config.json"});return data2}__name(parseFimoConfig,"parseFimoConfig");import{z as z71}from"zod";function toSpec(def){return{token:def.token,riskTier:def.risk,description:def.description}}__name(toSpec,"toSpec");var VOCABULARY=Object.freeze(Object.fromEntries(CAPABILITY_VOCABULARY.filter(definition=>definition.declarable).map(definition=>[definition.token,toSpec(definition)]))),CapabilityToken=z71.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z71.array(CapabilityToken);function isCapability(token){return Object.prototype.hasOwnProperty.call(VOCABULARY,token)}__name(isCapability,"isCapability");var RUNTIME_BASELINE_OPERATION_CAPABILITIES=["files:read","files:write"];function isRuntimeBaselineOperationCapability(capability){return RUNTIME_BASELINE_OPERATION_CAPABILITIES.includes(capability)}__name(isRuntimeBaselineOperationCapability,"isRuntimeBaselineOperationCapability");var OPERATION_CAP={"cms.list":"cms:read","cms.get":"cms:read","cms.query":"cms:read","cms.create":"cms:write","cms.update":"cms:write","cms.delete":"cms:write","cms.bulk_create":"cms:write","cms.bulk_update":"cms:write","cms.bulk_delete":"cms:write","cms.schema.list":"cms:schema:read","cms.schema.get":"cms:schema:read","cms.schema.push":"cms:schema:write","cms.schema.delete":"cms:schema:write","assets.list":"assets:read","assets.get":"assets:read","assets.upload":"assets:write","assets.generate":"assets:write","assets.create_folder":"assets:write","assets.move":"assets:write","assets.delete":"assets:write","i18n.list":"i18n:read","i18n.get":"i18n:read","i18n.create":"i18n:write","i18n.update":"i18n:write","i18n.delete":"i18n:write","forms.list":"forms:read","forms.get":"forms:read","forms.push":"forms:write","forms.delete":"forms:write","webhooks.events":"webhooks:read","webhooks.list":"webhooks:read","webhooks.get":"webhooks:read","webhooks.deliveries.list":"webhooks:read","webhooks.deliveries.get":"webhooks:read","webhooks.create":"webhooks:write","webhooks.update":"webhooks:write","webhooks.delete":"webhooks:write","webhooks.test":"webhooks:write","webhooks.deliveries.retry":"webhooks:write","webhooks.rotate_secret":"webhooks:write","schedules.list":"schedules:read","schedules.get":"schedules:read","schedules.runs.list":"schedules:read","schedules.runs.get":"schedules:read","schedules.create":"schedules:write","schedules.update":"schedules:write","schedules.delete":"schedules:write","schedules.pause":"schedules:write","schedules.resume":"schedules:write","schedules.run":"schedules:write","files.read":"files:read","files.write":"files:write","fimo.deploy":"fimo:deploy","fimo.logs.read":"fimo:logs:read","fimo.analytics.read":"fimo:analytics:read","fimo.preview.url":"fimo:preview:read","fimo.history.list":"fimo:history:read","fimo.history.get":"fimo:history:read","net.fetch":"net:fetch","agent.delegate":"agent:delegate","runtime.long_running":"runtime:long_running","runtime.auto_merge":"runtime:auto_merge"};function capabilityFor(op){return OPERATION_CAP[op]}__name(capabilityFor,"capabilityFor");function hasOperation(op){return Object.prototype.hasOwnProperty.call(OPERATION_CAP,op)}__name(hasOperation,"hasOperation");var import_yaml2=__toESM(require_dist(),1);function _define_property4(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property4,"_define_property");var CapabilityDenied=class extends Error{static{__name(this,"CapabilityDenied")}constructor(detail){let def=getCapability(detail.cap),description=def?.description?` (${def.description})`:"";super(`capability denied: ${detail.cap}${description} \u2014 reason: ${detail.reason}`),_define_property4(this,"cap",void 0),_define_property4(this,"reason",void 0),_define_property4(this,"granted",void 0),_define_property4(this,"sessionId",void 0),_define_property4(this,"fixHint",void 0),this.name="CapabilityDenied",this.cap=detail.cap,this.reason=detail.reason,this.granted=detail.granted??[],this.sessionId=detail.sessionId,this.fixHint=fixHintFor(detail)}};function fixHintFor(detail){switch(detail.reason){case"not-declared":return`Add '${detail.cap}' to the agent's capabilities.yaml and re-activate.`;case"session-not-found":return`Session '${detail.sessionId??"<unknown>"}' does not exist or has expired.`;case"snapshot-stale":return"Session capability snapshot is corrupted. Restart the agent session.";case"runtime-only":return`'${detail.cap}' is reserved for the platform \u2014 drop it from capabilities.yaml.`;case"auto-merge-blocked":return"runtime:auto_merge is declared but blocked by project policy (.fimo/config.json \u2192 agents.auto_merge)."}}__name(fixHintFor,"fixHintFor");var configured=null;async function auditCapabilityDecision(event){if(!configured)return;let row2={...event,ts:new Date().toISOString()};if(event.decision==="deny"){try{await configured.transport.write(row2)}catch(err){throw configured.breadcrumb?.({category:"audit",level:"error",message:"audit deny row write failed",data:{cap:event.cap,error:err.message}}),err}configured.breadcrumb?.({category:"audit",level:"warning",message:`capability denied: ${event.cap}`,data:{sessionId:event.sessionId,cap:event.cap,reason:event.reason}});return}configured.transport.write(row2).catch(err=>{configured?.breadcrumb?.({category:"audit",level:"warning",message:"audit allow row write failed (best-effort)",data:{cap:event.cap,error:err.message}})})}__name(auditCapabilityDecision,"auditCapabilityDecision");var composition_exports={};__export(composition_exports,{CompositionError:()=>CompositionError,InvalidExplicitGrantsError:()=>InvalidExplicitGrantsError,MAX_DELEGATION_DEPTH:()=>MAX_DELEGATION_DEPTH,MaxDelegationDepthError:()=>MaxDelegationDepthError,SubAgentInvocationError:()=>SubAgentInvocationError,SubAgentNotInProjectError:()=>SubAgentNotInProjectError,UnknownSubAgentError:()=>UnknownSubAgentError,createDelegateTool:()=>createDelegateTool,delegate:()=>delegate,detectCompositionCycle:()=>detectCompositionCycle,detectCycle:()=>detectCycle2,isCompositionError:()=>isCompositionError,resolveSubCallCapabilities:()=>resolveSubCallCapabilities2,resolveSubCallCapabilitiesLenient:()=>resolveSubCallCapabilities,resolveTransitiveCapabilities:()=>resolveTransitiveCapabilities,validateComposition:()=>validateComposition});function resolveTransitiveCapabilities(bundle,allBundles){let union2=new Set,missing=[],visited=new Set,visit2=__name(b=>{if(visited.has(b.name))return;visited.add(b.name);for(let token of b.capabilities)isCapability(token)&&union2.add(token);let subAgents=b.config.composition?.["sub-agents"]??[];for(let ref of subAgents){let sub=allBundles.get(ref.name);if(!sub){missing.includes(ref.name)||missing.push(ref.name);continue}visit2(sub)}},"visit");return visit2(bundle),{union:Array.from(union2).sort(),missing}}__name(resolveTransitiveCapabilities,"resolveTransitiveCapabilities");function detectCycle2(rootKey,nodes){if(!new Map(nodes.map(n=>[n.key,n])).get(rootKey))return null;let bundleMap=new Map;for(let node of nodes)bundleMap.set(node.key,{name:node.key,capabilities:[],config:{version:1,composition:{"sub-agents":node.subAgentKeys.map(k=>({name:k}))}}});let root2=bundleMap.get(rootKey);return detectCompositionCycle({root:root2,agentMap:bundleMap})}__name(detectCycle2,"detectCycle");function validateComposition(root2,allBundles){let cycle=detectCompositionCycle({root:root2,agentMap:allBundles}),missing=[],invalidGrants=[],capUnion=new Set,visited=new Set,visit2=__name(bundle=>{if(visited.has(bundle.name))return;visited.add(bundle.name);for(let token of bundle.capabilities)isCapability(token)&&capUnion.add(token);let subAgents=bundle.config.composition?.["sub-agents"]??[];for(let ref of subAgents){let sub=allBundles.get(ref.name);if(!sub){missing.includes(ref.name)||missing.push(ref.name);continue}if(ref.capability_grant==="explicit"){let declaredSet=new Set(sub.capabilities),invalid=(ref.explicit_grants??[]).filter(t2=>!declaredSet.has(t2));invalid.length>0&&invalidGrants.push({subAgentName:ref.name,invalid,declared:[...sub.capabilities]})}visit2(sub)}},"visit");if(!cycle)visit2(root2);else for(let token of root2.capabilities)isCapability(token)&&capUnion.add(token);let declaredDelegate=root2.capabilities.includes("agent:delegate");return{cycle,missing,transitiveCapabilities:Array.from(capUnion).sort(),declaredDelegate,invalidGrants}}__name(validateComposition,"validateComposition");function _define_property5(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property5,"_define_property");var CompositionError=class extends Error{static{__name(this,"CompositionError")}},InvalidExplicitGrantsError=class extends CompositionError{static{__name(this,"InvalidExplicitGrantsError")}constructor(subAgentName,invalid,declared){super(`composition.sub-agents[name=${subAgentName}].explicit_grants references capabilities the sub-agent never declared: [${invalid.join(", ")}]. Declared by sub-agent: [${declared.join(", ")}]`),_define_property5(this,"code","composition.invalid_explicit_grants"),_define_property5(this,"subAgentName",void 0),_define_property5(this,"invalid",void 0),_define_property5(this,"declared",void 0),this.name="InvalidExplicitGrantsError",this.subAgentName=subAgentName,this.invalid=invalid,this.declared=declared}},SubAgentInvocationError=class extends CompositionError{static{__name(this,"SubAgentInvocationError")}constructor(subAgentName,cause){super(`sub-agent '${subAgentName}' threw during invocation: ${cause?.message??String(cause)}`),_define_property5(this,"code","composition.sub_agent_invocation_failed"),_define_property5(this,"subAgentName",void 0),this.name="SubAgentInvocationError",this.subAgentName=subAgentName,this.cause=cause}};function isCompositionError(err){return err instanceof CompositionError?!0:err instanceof Error?err.name==="MaxDelegationDepthError"||err.name==="UnknownSubAgentError"||err.name==="SubAgentNotInProjectError":!1}__name(isCompositionError,"isCompositionError");function resolveSubCallCapabilities2(input){let{parentCapabilities,subAgentDeclared,ref}=input;if((ref.capability_grant??"inherit")==="explicit"){let explicitGrants=ref.explicit_grants??[],declaredSet=new Set(subAgentDeclared),invalid=explicitGrants.filter(t2=>!declaredSet.has(t2));if(invalid.length>0)throw new InvalidExplicitGrantsError(ref.name,invalid,subAgentDeclared)}return resolveSubCallCapabilities(parentCapabilities,subAgentDeclared,ref)}__name(resolveSubCallCapabilities2,"resolveSubCallCapabilities");function _define_property6(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property6,"_define_property");var MAX_DELEGATION_DEPTH=5,MaxDelegationDepthError=class extends Error{static{__name(this,"MaxDelegationDepthError")}constructor(depth){super(`max delegation depth ${depth} reached (limit ${MAX_DELEGATION_DEPTH})`),_define_property6(this,"depth",void 0),this.name="MaxDelegationDepthError",this.depth=depth}},UnknownSubAgentError=class extends Error{static{__name(this,"UnknownSubAgentError")}constructor(name){super(`sub-agent '${name}' is not declared in composition.sub-agents`),_define_property6(this,"name_",void 0),this.name="UnknownSubAgentError",this.name_=name}},SubAgentNotInProjectError=class extends Error{static{__name(this,"SubAgentNotInProjectError")}constructor(name){super(`sub-agent '${name}' is declared but not present in agents/ directory`),_define_property6(this,"name_",void 0),this.name="SubAgentNotInProjectError",this.name_=name}};async function delegate(input,ctx,runSubAgent){if(assertCapability("agent:delegate",ctx.parentCapabilities),ctx.depth>=MAX_DELEGATION_DEPTH)throw new MaxDelegationDepthError(ctx.depth);let ref=(ctx.parentBundle.config.composition?.["sub-agents"]??[]).find(r=>r.name===input.name);if(!ref)throw new UnknownSubAgentError(input.name);let sub=ctx.projectBundles.find(b=>b.name===ref.name);if(!sub)throw new SubAgentNotInProjectError(ref.name);let subCallCapabilities=resolveSubCallCapabilities(ctx.parentCapabilities,sub.capabilities,ref);return{result:await runSubAgent(sub,subCallCapabilities,input.args),subCallCapabilities}}__name(delegate,"delegate");function createDelegateTool(opts){return __name(async function(input){let{session,runSubAgent,audit}=opts,started=Date.now(),parentCaps=session.capabilityStack[session.capabilityStack.length-1]??session.parentBundle.capabilities,ctx={parentBundle:session.parentBundle,parentCapabilities:parentCaps,depth:session.depth,projectBundles:session.projectBundles};try{let grantMode=(session.parentBundle.config.composition?.["sub-agents"]??[]).find(r=>r.name===input.name)?.capability_grant??"inherit";session.depth+=1;let result=await delegate(input,ctx,__name(async(sub,capabilities,args)=>{session.capabilityStack.push([...capabilities]);try{return await runSubAgent(sub,capabilities,args)}finally{session.capabilityStack.pop()}},"wrappedRunSubAgent"));return await audit?.emit({subAgentName:input.name,grantMode,resolvedCapabilities:result.subCallCapabilities,args:input.args,durationMs:Date.now()-started,depth:ctx.depth}),result}catch(err){let wrapped=err instanceof SubAgentInvocationError?err:new SubAgentInvocationError(input.name,err);throw await audit?.emit({subAgentName:input.name,grantMode:"inherit",resolvedCapabilities:[],args:input.args,durationMs:Date.now()-started,depth:ctx.depth,error:{name:err.name??"Error",message:err.message??String(err)}}),wrapped}finally{session.depth-=1}},"delegateFn")}__name(createDelegateTool,"createDelegateTool");init_dist();init_scaffold();import fs8 from"node:fs";import path8 from"node:path";init_dist();init_auth_errors();init_project();var NAME_RE=/^[a-z][a-z0-9-]*$/;function isValidAgentName(name){return name.length===0||name.length>64?!1:NAME_RE.test(name)}__name(isValidAgentName,"isValidAgentName");var InvalidAgentNameError=class extends Error{static{__name(this,"InvalidAgentNameError")}name="InvalidAgentNameError";attempted;constructor(attempted){super(`'${attempted}' is not a valid agent name. Names must be lowercase, start with a letter, and contain only letters/digits/hyphens.`),this.attempted=attempted}};function resolveProjectRoot(cwd=process.cwd()){let dir=path8.resolve(cwd);for(let i=0;i<8;i++){if(fs8.existsSync(resolveProjectConfigPath(dir))||fs8.existsSync(path8.join(dir,"package.json")))return dir;let parent2=path8.dirname(dir);if(parent2===dir)break;dir=parent2}throw new Error(`Could not find a project root (no Fimo config or package.json) under ${cwd}. Run \`fimo agents *\` from inside a project.`)}__name(resolveProjectRoot,"resolveProjectRoot");function resolveFimoProject(cwd=process.cwd()){let projectRoot=findProjectRoot(cwd);if(!projectRoot)return null;try{return{projectRoot,settings:loadProjectSettings(projectRoot)}}catch{return null}}__name(resolveFimoProject,"resolveFimoProject");function resolveAgentBundlesDir(projectRoot){return resolveProjectAgentsDir(projectRoot)}__name(resolveAgentBundlesDir,"resolveAgentBundlesDir");function printBundleError(command,err){if(rethrowCliAuthError(err),isBundleError(err)){let e=err,hintParts=[];e.remediation&&hintParts.push(`fix: ${e.remediation}`),e.bundlePath&&hintParts.push(`at: ${e.bundlePath}`),ui.error({command,code:"AGENT_BUNDLE_ERROR",message:e.message,hint:hintParts.length>0?hintParts.join(" \xB7 "):void 0})}else ui.error({command,code:"AGENT_BUNDLE_ERROR",message:err.message??String(err)})}__name(printBundleError,"printBundleError");async function createAgent(opts){if(!isValidAgentName(opts.name))throw new InvalidAgentNameError(opts.name);let cwd=opts.cwd??process.cwd(),projectRoot;if(opts.requireFimoProject){let resolved=resolveFimoProject(cwd);if(!resolved)return{ok:!1,error:"Not inside a linked Fimo project. Run from inside a Fimo project, or pass -C <dir>."};projectRoot=resolved.projectRoot}else projectRoot=resolveProjectRoot(cwd);let targetDir=path9.join(resolveAgentBundlesDir(projectRoot),opts.name);if(fs9.existsSync(targetDir))return{ok:!1,error:`${path9.relative(projectRoot,targetDir)}/ already exists. Pick a different name or remove the existing directory first.`};let templateName=opts.template??"_default",templateRoot;try{templateRoot=resolveAgentTemplate(templateName)}catch{let available=listAgentTemplates().map(t2=>t2.name);throw new BundleTemplateNotFoundError(templateName,available)}return await copyAgentTemplate(templateRoot,targetDir),opts.description!==void 0&&writeDescriptionToConfig(path9.join(targetDir,"config.yaml"),opts.description),{ok:!0,agentDir:targetDir}}__name(createAgent,"createAgent");function writeDescriptionToConfig(configPath,description){let content2=fs9.readFileSync(configPath,"utf8"),line=`description: ${JSON.stringify(description)}`,next2;/^description:.*$/m.test(content2)?next2=content2.replace(/^description:.*$/m,line):/^version:\s*\d+.*$/m.test(content2)?next2=content2.replace(/^(version:\s*\d+.*)$/m,`$1
|
|
1182
1182
|
${line}`):next2=(content2.endsWith(`
|
|
1183
1183
|
`)?content2:content2+`
|
|
1184
1184
|
`)+line+`
|
|
@@ -1189,9 +1189,9 @@ ${line}`):next2=(content2.endsWith(`
|
|
|
1189
1189
|
${report}`,"render")})}catch(err){printBundleError("agents report",err)}}__name(agentReportCommand,"agentReportCommand");function readProjectId(projectRoot){try{return loadProjectSettings(projectRoot).projectId}catch{return}}__name(readProjectId,"readProjectId");init_dist();init_api();init_config();import{execFile}from"node:child_process";import path11 from"node:path";import{promisify}from"node:util";var execFileAsync=promisify(execFile);async function detectBundleDrift(projectRoot,agentName){let porcelain;try{let{stdout}=await execFileAsync("git",["status","--porcelain"],{cwd:projectRoot});porcelain=stdout}catch{return[]}if(porcelain.length===0)return[];let prefix=`${path11.relative(projectRoot,resolveAgentBundlesDir(projectRoot)).replace(/\\/g,"/")}/${agentName}/`;return porcelain.split(`
|
|
1190
1190
|
`).map(line=>line.replace(/\r$/,"")).filter(line=>{if(line.length===0)return!1;let pathPart=line.slice(3),[from,to]=pathPart.split(" -> ");return(from?.startsWith(prefix)??!1)||(to?.startsWith(prefix)??!1)})}__name(detectBundleDrift,"detectBundleDrift");async function runAgent(opts){let cwd=opts.cwd??process.cwd(),fimoProject=resolveFimoProject(cwd),projectRoot=fimoProject?.projectRoot??resolveProjectRoot(cwd);if(!opts.skipDriftCheck){let driftLines=await detectBundleDrift(projectRoot,opts.name);if(driftLines.length>0)return{exitCode:1,driftLines}}let env=opts.env??"main",projectId=opts.projectId??fimoProject?.settings.projectId;if(!projectId)throw new Error("Could not determine project id. Pass --project <id>, or run from inside a linked Fimo project.");let cfg=loadConfig(),api=new FimoApiClient(cfg);try{let result=await api.runAgent(projectId,env,opts.name,{});return{exitCode:0,sessionId:result.sessionId,skipped:result.skipped}}catch(err){throw err instanceof ApiRequestError?new Error(`Failed to run '${opts.name}' (HTTP ${err.status}): ${err.detail}`):err}}__name(runAgent,"runAgent");async function runAgentCommand(name,options){try{let result=await runAgent({name,cwd:options.cwd,env:options.env,projectId:options.project,skipDriftCheck:options.skipDriftCheck});if(result.driftLines&&result.driftLines.length>0){ui.error({command:"agents run",code:"BUNDLE_DRIFT",message:`Bundle '${name}' has local changes that haven't been deployed:
|
|
1191
1191
|
${result.driftLines.map(l=>` ${l}`).join(`
|
|
1192
|
-
`)}`,hint:"Run `fimo deploy` to push them first, or `fimo agents run --skip-drift-check` to dispatch the deployed version anyway."});return}if(result.skipped){ui.info({command:"agents run",message:`Dispatch was skipped: ${result.skipped}`});return}if(result.sessionId){ui.ok({command:"agents run",headline:`Triggered ${name} (session ${result.sessionId})`,details:{agent:name,session_id:result.sessionId},hint:`Watch progress: fimo agents runs ${name}`});return}ui.error({command:"agents run",code:"UNEXPECTED_RUN_RESPONSE",message:"Unexpected response from server (no sessionId, no skipped)."})}catch(err){printBundleError("agents run",err)}}__name(runAgentCommand,"runAgentCommand");init_dist();init_api();init_config();init_project();async function agentRunsCommand(name,options){try{let projectRoot=resolveProjectRoot(options.cwd??process.cwd()),projectId=options.project??readProjectId2(projectRoot);if(!projectId){ui.error({command:"agents runs",code:"NO_PROJECT_ID",message:"Could not determine project id.",hint:"Pass --project, or run from a linked Fimo project directory."});return}let limit=options.limit??20,cfg=loadConfig(),api=new FimoApiClient(cfg),sessions;try{sessions=await api.listAgentSessions(projectId,{agentName:name,env:options.env,limit})}catch(err){if(err instanceof ApiRequestError){ui.error({command:"agents runs",code:"AGENT_SESSIONS_FETCH_FAILED",message:`Failed to fetch sessions (HTTP ${err.status}): ${err.detail}`});return}throw err}if(sessions.length===0){ui.info({command:"agents runs",message:`(no recent sessions for '${name}'${options.env?` on env '${options.env}'`:""})`});return}let rows=sessions.map(session=>({id:session.id.slice(0,8),started:formatStartedAt(session.startedAt),duration:formatDuration(session.startedAt,session.finishedAt??session.cancelledAt),status:session.status,trigger:session.triggerKind,env:session.env,cost:`$${session.costUsd.toFixed(4)}`}));ui.table({command:"agents runs",columns:[{key:"id",label:"ID"},{key:"started",label:"STARTED"},{key:"duration",label:"DURATION"},{key:"status",label:"STATUS"},{key:"trigger",label:"TRIGGER"},{key:"env",label:"
|
|
1193
|
-
`)},"render")})}__name(listTemplatesCommand,"listTemplatesCommand");import fs11 from"node:fs";import path13 from"node:path";init_dist();init_api();init_auth();init_config();init_project();async function runValidateAgents(opts){let projectRoot=resolveProjectRoot(opts.cwd??process.cwd()),agentsDir=resolveAgentBundlesDir(projectRoot),configPath=resolveProjectPolicyPath(projectRoot),policy=validatePolicy(configPath,projectRoot),bundleList=[];if(opts.name){if(!isValidAgentName(opts.name))return{ok:!1,policy,bundles:[{name:opts.name,ok:!1,phases:{parse:{ok:!1,issues:[{pointer:"name",message:`Invalid agent name '${opts.name}'.`}]},capabilities:{ok:!0,issues:[]},composition:{ok:!0,issues:[]},semantics:{ok:!0,issues:[]}},warnings:[]}]};let bundle=await safeParse(path13.join(agentsDir,opts.name));if(!bundle.ok)return{ok:!1,policy,bundles:[{name:opts.name,ok:!1,phases:{parse:{ok:!1,issues:[bundle.issue]},capabilities:{ok:!0,issues:[]},composition:{ok:!0,issues:[]},semantics:{ok:!0,issues:[]}},warnings:[]}]};bundleList=[bundle.bundle]}else bundleList=await listBundles(agentsDir);let reports=[],cloudNotifications=hasCloudNotificationRecipients(configPath);for(let bundle of bundleList){let report=validateOneBundle(bundle,bundleList);!cloudNotifications&&(bundle.config.triggers??[]).some(t2=>t2.type!=="manual")&&report.warnings.push({pointer:`${path13.basename(configPath)}:agents.notifications.email_recipients`,message:"Cloud triggers stay unwired until `agents.notifications.email_recipients` is non-empty (ADR-0009)."}),reports.push(report)}return{ok:(policy?.ok??!0)&&reports.every(r=>r.ok),policy,bundles:reports}}__name(runValidateAgents,"runValidateAgents");function hasCloudNotificationRecipients(policyPath){if(!fs11.existsSync(policyPath))return!1;try{return(parseFimoConfig(fs11.readFileSync(policyPath,"utf8"),{path:path13.basename(policyPath)}).agents?.notifications?.email_recipients??[]).length>0}catch{return!1}}__name(hasCloudNotificationRecipients,"hasCloudNotificationRecipients");function validatePolicy(policyPath,projectRoot){if(!fs11.existsSync(policyPath))return null;try{let text3=fs11.readFileSync(policyPath,"utf8");return parseFimoConfig(text3,{path:path13.relative(projectRoot,policyPath)}),{ok:!0,issues:[]}}catch(err){return{ok:!1,issues:[{pointer:path13.relative(projectRoot,policyPath),message:err.message,remediation:err.remediation}]}}}__name(validatePolicy,"validatePolicy");async function safeParse(bundlePath){try{return{ok:!0,bundle:await parseBundle(bundlePath)}}catch(err){return{ok:!1,issue:{pointer:path13.basename(bundlePath),message:err.message,remediation:err.remediation}}}}__name(safeParse,"safeParse");function validateOneBundle(bundle,allBundles){let phases={parse:{ok:!0,issues:[]},capabilities:{ok:!0,issues:[]},composition:{ok:!0,issues:[]},semantics:{ok:!0,issues:[]}},vocab=validateAgainstVocabulary(bundle.capabilities,CAPABILITY_VOCABULARY);for(let token of vocab.unknown){let suggestion=suggestCapability(token),err=new BundleInvalidCapabilityError(token,"unknown",{suggestion:suggestion??void 0});phases.capabilities.ok=!1,phases.capabilities.issues.push({pointer:`capabilities.yaml: ${token}`,message:err.message,remediation:err.remediation})}for(let token of vocab.nonDeclarable){let err=new BundleInvalidCapabilityError(token,"runtime_only");phases.capabilities.ok=!1,phases.capabilities.issues.push({pointer:`capabilities.yaml: ${token}`,message:err.message,remediation:err.remediation})}let agentMap=new Map(allBundles.map(b=>[b.name,b])),compositionResult=composition_exports.validateComposition(bundle,agentMap);if(compositionResult.cycle){let err=new BundleCompositionCycleError(compositionResult.cycle);phases.composition.ok=!1,phases.composition.issues.push({pointer:"config.yaml:composition",message:err.message,remediation:err.remediation})}for(let missingName of compositionResult.missing)phases.composition.ok=!1,phases.composition.issues.push({pointer:`config.yaml:composition.sub-agents[name=${missingName}]`,message:`Sub-agent '${missingName}' is referenced but not present in the project's agent-bundle directory.`,remediation:`Run \`fimo agents create ${missingName}\` or remove the reference from composition.sub-agents.`});for(let invalid of compositionResult.invalidGrants)phases.composition.ok=!1,phases.composition.issues.push({pointer:`config.yaml:composition.sub-agents[name=${invalid.subAgentName}].explicit_grants`,message:`explicit_grants references capabilities the sub-agent never declared: [${invalid.invalid.join(", ")}]. Declared: [${invalid.declared.join(", ")}].`,remediation:"Remove the undeclared tokens from explicit_grants, or add them to the sub-agent's capabilities.yaml."});if(!compositionResult.cycle){let cycle=detectCompositionCycle({root:bundle,agentMap});if(cycle){let err=new BundleCompositionCycleError(cycle);phases.composition.ok=!1,phases.composition.issues.push({pointer:"config.yaml:composition",message:err.message,remediation:err.remediation})}}let issues=validateBundle(bundle,{availableAgents:allBundles}),warnings=[...bundle.warnings];for(let issue of issues){if(issue.severity==="warning"){warnings.push({pointer:issue.pointer,message:issue.message});continue}issue.pointer.startsWith("capabilities.yaml")||issue.pointer.startsWith("config.yaml:composition")||(phases.semantics.ok=!1,phases.semantics.issues.push({pointer:issue.pointer,message:issue.message}))}let ok=phases.parse.ok&&phases.capabilities.ok&&phases.composition.ok&&phases.semantics.ok;return{name:bundle.name,ok,phases,warnings}}__name(validateOneBundle,"validateOneBundle");async function runAvailabilityChecks(cwd){let projectRoot=resolveProjectRoot(cwd),projectId;try{projectId=loadProjectSettings(projectRoot).projectId}catch{if(projectId=process.env.FIMO_PROJECT_ID?.trim()??"",!projectId)return{ok:!0,skippedReason:"not-linked",issues:[]}}if(!process.env.FIMO_API_TOKEN?.trim()&&!readCredentials())return{ok:!0,skippedReason:"not-signed-in",issues:[]};let api=new FimoApiClient(loadConfig()),agentsDir=resolveAgentBundlesDir(projectRoot),bundles=await listBundles(agentsDir),issues=[],configPath=__name(agentName=>path13.relative(projectRoot,path13.join(agentsDir,agentName,"config.yaml")).replaceAll("\\","/"),"configPath"),integrationsByAgent=bundles.map(bundle=>({name:bundle.name,integrations:Object.entries(agentIntegrationPolicy(bundle.config)).map(([integrationKey,entry])=>({integrationKey,enabled:entry.enabled,tools:enabledAgentIntegrationTools(entry),allTools:entry.tools===void 0,toolsConfigured:entry.tools!==void 0})).filter(entry=>entry.enabled)})).filter(entry=>entry.integrations.length>0);if(integrationsByAgent.length>0){let statuses=await api.listProjectIntegrations(projectId),statusByKey=new Map(statuses.map(status=>[status.integrationKey,status])),infoByKey=new Map;for(let agent of integrationsByAgent)for(let integration of agent.integrations){let file=configPath(agent.name),status=statusByKey.get(integration.integrationKey);if(!status){issues.push({pointer:file,message:`${agent.name} allows unsupported integration ${integration.integrationKey}.`});continue}integration.toolsConfigured&&integration.tools.length===0&&issues.push({pointer:file,message:`${agent.name} enables ${integration.integrationKey}, but its tools map allows none. Remove the tools map to allow all available tools, or set at least one integrations.${integration.integrationKey}.tools.<tool>: true entry.`}),status.enabled||issues.push({pointer:file,message:`${agent.name} allows ${integration.integrationKey}, but the project integration is not enabled. Run: fimo integrations enable ${integration.integrationKey}`});let info=infoByKey.get(integration.integrationKey)??await api.getProjectIntegrationInfo(projectId,integration.integrationKey);infoByKey.set(integration.integrationKey,info);let knownTools=new Set(info.tools.map(tool=>tool.key)),effectiveTools=integration.allTools?[...knownTools]:integration.tools;for(let tool of effectiveTools)knownTools.has(tool)||issues.push({pointer:file,message:`${agent.name} allows unknown ${integration.integrationKey}.${tool} tool. Supported tools: ${[...knownTools].sort().join(", ")}`})}}let secretsByAgent=bundles.map(bundle=>({name:bundle.name,keys:(bundle.config.secrets??[]).filter(secret=>secret.required!==!1).map(secret=>secret.key)})).filter(entry=>entry.keys.length>0);if(secretsByAgent.length>0){let defined=new Set((await api.listProjectSecretEntries(projectId,{kind:"secret"})).map(secret=>secret.key));for(let entry of secretsByAgent)for(let key of entry.keys)defined.has(key)||issues.push({pointer:configPath(entry.name),message:`${entry.name} requires project secret ${key}, but it is not set. Run: fimo secrets add ${key} --stdin`})}return{ok:issues.length===0,skippedReason:null,issues}}__name(runAvailabilityChecks,"runAvailabilityChecks");async function validateAgentsCommand(opts){let report;try{report=await runValidateAgents(opts)}catch(err){throw printBundleError("agents validate",err),opts.noExit||(process.exitCode=1),err}return report.bundles.length===0&&!report.policy?(ui.info({command:"agents validate",message:"No bundles or Fimo project config found."}),report):(report.availability=await runAvailabilityChecks(opts.cwd??process.cwd()),report.availability.ok||(report.ok=!1),ui.result({command:"agents validate",data:report,render:__name(()=>renderReportHuman(report),"render")}),!report.ok&&!opts.noExit&&(process.exitCode=1),report)}__name(validateAgentsCommand,"validateAgentsCommand");function renderReportHuman(report){let lines=[];if(report.policy)if(report.policy.ok)lines.push(" \u2713 Fimo config policy ok");else{lines.push(" \u2717 Fimo config");for(let issue of report.policy.issues)lines.push(` \u2717 ${issue.message}`),issue.remediation&&lines.push(` fix: ${issue.remediation}`)}for(let bundle of report.bundles)if(bundle.ok){lines.push(` \u2713 ${bundle.name} all phases ok`);for(let w3 of bundle.warnings)lines.push(` ! ${w3.pointer}: ${w3.message}`)}else{lines.push(` \u2717 ${bundle.name}`);for(let phase of["parse","capabilities","composition","semantics"])for(let issue of bundle.phases[phase].issues)lines.push(` \u2717 [${phase}] ${issue.message}`),issue.remediation&&lines.push(` fix: ${issue.remediation}`)}if(report.availability)if(report.availability.skippedReason){let why=report.availability.skippedReason==="not-signed-in"?"not signed in \u2014 run `fimo login`":"no linked project";lines.push(` \u21B7 integrations & secrets \u2014 skipped (${why})`)}else if(report.availability.ok)lines.push(" \u2713 integrations & secrets available");else{lines.push(" \u2717 integrations & secrets");for(let issue of report.availability.issues)lines.push(` \u2717 ${issue.message}`)}return lines.join(`
|
|
1194
|
-
`)}__name(renderReportHuman,"renderReportHuman");function registerAgentsCommands(program2){let agents=program2.command("agents").description("AI agent bundle management (M13)");agents.command("create <name>").description("Scaffold .fimo/agents/<name>/ from a template").option("--template <name>","Template to copy from (default: _default)").option("--description <text>","Short tagline written to config.yaml (one line, up to 280 chars)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>createAgentCommand(name,opts)),agents.command("list").description("List agents declared under the project agents directory").option("-C, --cwd <dir>","Project directory").option("--project <id>","Project id (accepted for parity with cloud-scoped subcommands)").action(opts=>listAgentsCommand(opts)),agents.command("list-templates").alias("templates").description("List the bundled starter-catalog templates").action(()=>listTemplatesCommand()),agents.command("validate [name]").description("Validate one or every bundle (parse, capabilities, composition, policy)").option("--json","Emit structured ValidationReport (for CI)").option("-C, --cwd <dir>","Project directory").action(async(name,opts)=>{await validateAgentsCommand({name,json:opts.json,cwd:opts.cwd})}),agents.command("integrations <name>").description("Preview local integration access policy for an agent").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentIntegrationsCommand(name,opts)),agents.command("run <name>").description("Trigger a manual run on the server (returns sessionId)").option("--env <env>","Target env (default: main)").option("--project <id>","Project id (defaults to .fimo/project.json or legacy .fimo.settings.json projectId)").option("-C, --cwd <dir>","Project directory").option("--skip-drift-check","Dispatch even when the bundle has uncommitted local changes").action((name,opts)=>runAgentCommand(name,opts)),agents.command("logs <name>").description("Stream the most recent session log").option("--session <id>","Specific session id to target").option("-C, --cwd <dir>","Project directory").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").action((name,opts)=>agentLogsCommand(name,opts)),agents.command("runs <name>").description("Paginated session list").option("--limit <n>","Max sessions to show (default: 20)",v=>Number.parseInt(v,10)).option("--env <env>","Filter sessions to a specific env").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentRunsCommand(name,opts)),agents.command("report <name>").description("Print a run's report (the agent's final message); latest run unless --session is given").option("--session <id>","Target a specific session id").option("--env <env>","Pick the latest run on a specific env").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentReportCommand(name,opts));let secrets=agents.command("secrets").description("Edit the secrets requested in an agent config.yaml");secrets.command("list <name>").description("List secret keys requested by an agent config").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentSecretsListCommand(name,opts)),secrets.command("add <name> <key>").description("Add a secret key request to an agent config").option("-C, --cwd <dir>","Project directory").option("--optional","Mark the secret as optional").action((name,key,opts)=>agentSecretsAddCommand(name,key,opts)),secrets.command("remove <name> <key>").alias("rm").description("Remove a secret key request from an agent config").option("-C, --cwd <dir>","Project directory").action((name,key,opts)=>agentSecretsRemoveCommand(name,key,opts))}__name(registerAgentsCommands,"registerAgentsCommands");init_dist();init_project_context();function parseRangeOptions(options){let params={};if(options.preset&&(params.preset=options.preset),options.groupBy&&(params.groupBy=options.groupBy),options.from&&(params.from=options.from),options.to&&(params.to=options.to),options.days!==void 0){let n=Number(options.days);if(!Number.isFinite(n))throw new Error(`Invalid --days value: ${options.days}`);params.days=n}return params}__name(parseRangeOptions,"parseRangeOptions");function renderPrettyJson(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson,"renderPrettyJson");async function analyticsPageviewsCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params);ui.result({command:"analytics pageviews",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsPageviewsCommand,"analyticsPageviewsCommand");var TOP_DIMENSIONS=["pages","browsers","devices","countries","sources"];function dimensionField(dimension){return`top${dimension.charAt(0).toUpperCase()}${dimension.slice(1)}`}__name(dimensionField,"dimensionField");async function analyticsTopCommand(dimension,options,cmd){if(!TOP_DIMENSIONS.includes(dimension))throw new Error(`Unknown dimension: ${dimension}. Expected one of: ${TOP_DIMENSIONS.join(", ")}`);let{ctx,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params),field=dimensionField(dimension),items=Array.isArray(result[field])?result[field]:[],limit;if(options.limit!==void 0){let n=Number(options.limit);if(!Number.isFinite(n)||n<1)throw new Error(`Invalid --limit value: ${options.limit}`);limit=n}let trimmed=limit!==void 0?items.slice(0,limit):items;ui.result({command:"analytics top",data:{dimension,items:trimmed},render:__name(()=>renderPrettyJson(trimmed),"render")})}__name(analyticsTopCommand,"analyticsTopCommand");async function analyticsAnnotationsListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params),annotations2=Array.isArray(result.annotations)?result.annotations:[];ui.result({command:"analytics annotations list",data:{annotations:annotations2},render:__name(()=>renderPrettyJson(annotations2),"render")})}__name(analyticsAnnotationsListCommand,"analyticsAnnotationsListCommand");async function analyticsAnnotationsSetCommand(date,content2,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd),result=await api.setAnalyticsAnnotation(ctx.projectId,date,content2);ui.result({command:"analytics annotations set",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsAnnotationsSetCommand,"analyticsAnnotationsSetCommand");async function analyticsAnnotationsDeleteCommand(date,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await api.deleteAnalyticsAnnotation(ctx.projectId,date),ui.ok({command:"analytics annotations delete",headline:`Deleted annotation for ${date}.`,details:{date}})}__name(analyticsAnnotationsDeleteCommand,"analyticsAnnotationsDeleteCommand");init_dist();import{spawn}from"node:child_process";import{mkdirSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{dirname,extname,isAbsolute,join as join2,resolve as resolvePath}from"node:path";var ENV_SESSION="FIMO_AGENT_SESSION",ENV_CAPS_FALLBACK="FIMO_AGENT_CAPABILITIES";function currentAgentSession(){let id=process.env[ENV_SESSION];return id&&id.length>0?id:void 0}__name(currentAgentSession,"currentAgentSession");async function defaultFetchSessionCapabilities(_sessionId){let raw=process.env[ENV_CAPS_FALLBACK];return raw?raw.split(",").map(s=>s.trim()).filter(s=>s.length>0):[]}__name(defaultFetchSessionCapabilities,"defaultFetchSessionCapabilities");async function requireCapability(cap,ctx={}){let sessionId=currentAgentSession();if(!sessionId)return{ok:!0,bypassed:!0};let granted=await(ctx.fetchSessionCapabilities??defaultFetchSessionCapabilities)(sessionId);if(!granted.includes(cap)){try{await auditCapabilityDecision({sessionId,cap,decision:"deny",reason:granted.length===0?"session-not-found":"not-declared",projectId:ctx.projectId,env:ctx.env})}catch{}throw new CapabilityDenied({cap,reason:granted.length===0?"session-not-found":"not-declared",granted,sessionId})}return auditCapabilityDecision({sessionId,cap,decision:"allow",projectId:ctx.projectId,env:ctx.env}),{ok:!0,bypassed:!1}}__name(requireCapability,"requireCapability");async function requireOperation(op,ctx={}){if(!hasOperation(op))throw new Error(`requireOperation: unknown operation id '${op}' \u2014 register it in @fimo/agents capabilities/operation-map.ts`);let cap=capabilityFor(op);return isRuntimeBaselineOperationCapability(cap)?{ok:!0,bypassed:currentAgentSession()===void 0}:requireCapability(cap,ctx)}__name(requireOperation,"requireOperation");init_project_context();init_project();function extensionFor(asset){let fromName=extname(asset.name);if(fromName&&fromName.length<=6)return fromName;let mime=asset.mimeType??"";return mime.startsWith("image/")?"."+(mime.split("/")[1]??"bin"):mime.startsWith("video/")?"."+(mime.split("/")[1]??"mp4"):mime.startsWith("audio/")?"."+(mime.split("/")[1]??"mp3"):""}__name(extensionFor,"extensionFor");function defaultDownloadPath(asset){let ext=extensionFor(asset);return join2(tmpdir(),"fimo-assets",`${asset.id}${ext}`)}__name(defaultDownloadPath,"defaultDownloadPath");async function downloadToPath(url,dest){let response=await fetch(url);if(!response.ok)throw new Error(`Failed to download asset: HTTP ${response.status} ${response.statusText}`);let arrayBuffer=await response.arrayBuffer();mkdirSync(dirname(dest),{recursive:!0}),writeFileSync(dest,new Uint8Array(arrayBuffer))}__name(downloadToPath,"downloadToPath");function spawnBrowser(url){let command=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(process.platform==="win32"?spawn("cmd",["/c","start","",url],{detached:!0,stdio:"ignore"}):spawn(command,[url],{detached:!0,stdio:"ignore"})).unref()}__name(spawnBrowser,"spawnBrowser");function renderPrettyJson2(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson2,"renderPrettyJson");async function assetsOpenCommand(id,options,cmd){if(options.download&&options.browser)throw new Error("--download and --browser are mutually exclusive \u2014 pick one");let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.get",{projectId:ctx.projectId,env:ctx.env});let cwd=resolveProjectCwd(options.cwd),{data:asset}=await api.getAsset(ctx.projectId,id);if(asset.type==="folder")throw new Error(`Asset ${id} is a folder; can only open files`);if(!asset.url)throw new Error(`Asset ${id} has no public URL \u2014 it may not have finished uploading`);if(options.browser){spawnBrowser(asset.url);let payload2={opened:asset.url};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}if(options.download){let dest=options.path?isAbsolute(options.path)?options.path:resolvePath(cwd,options.path):defaultDownloadPath(asset);await downloadToPath(asset.url,dest);let payload2={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,path:dest,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,aiAltText:asset.aiAltText??null};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}let payload={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,caption:asset.caption??null,aiAltText:asset.aiAltText??null,aiCaption:asset.aiCaption??null,aiTags:asset.aiTags??null};ui.result({command:"assets open",data:payload,render:__name(()=>renderPrettyJson2(payload),"render")})}__name(assetsOpenCommand,"assetsOpenCommand");init_dist();import fs12 from"node:fs";import path14 from"node:path";init_project_context();init_project();function renderPrettyJson3(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson3,"renderPrettyJson");async function assetsListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.list",{projectId:ctx.projectId,env:ctx.env});let mimePrefix=options.mimePrefix;mimePrefix||(options.image?mimePrefix="image/":options.video?mimePrefix="video/":options.audio&&(mimePrefix="audio/"));let params={};options.parentId&&(params.parentId=options.parentId),options.search&&(params.search=options.search),options.type&&(params.type=options.type),mimePrefix&&(params.mimePrefix=mimePrefix),options.sortBy&&(params.sortBy=options.sortBy),options.limit&&(params.limit=options.limit),options.offset&&(params.offset=options.offset);let result=await api.listAssets(ctx.projectId,Object.keys(params).length>0?params:void 0);ui.result({command:"assets list",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsListCommand,"assetsListCommand");async function assetsUploadCommand(file,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.upload",{projectId:ctx.projectId,env:ctx.env});let cwd=resolveProjectCwd(options.cwd);if(options.parentId&&options.folderPath)throw new Error("Use either --parent-id or --folder-path, not both");let filePath=path14.resolve(cwd,file);if(!fs12.existsSync(filePath))throw new Error(`File not found: ${filePath}`);let fileBuffer=fs12.readFileSync(filePath),fileName=options.name??path14.basename(filePath),formData=new FormData;formData.append("file",new Blob([fileBuffer]),fileName),options.name&&formData.append("name",options.name),options.parentId&&formData.append("parentId",options.parentId),options.folderPath&&formData.append("folderPath",options.folderPath);let result=await api.uploadAsset(ctx.projectId,formData);ui.result({command:"assets upload",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsUploadCommand,"assetsUploadCommand");async function assetsCreateFolderCommand(name,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.create_folder",{projectId:ctx.projectId,env:ctx.env});let result=await api.createFolder(ctx.projectId,name,options.parentId);ui.result({command:"assets create-folder",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsCreateFolderCommand,"assetsCreateFolderCommand");async function assetsMoveCommand(id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.move",{projectId:ctx.projectId,env:ctx.env});let result=await api.moveAsset(ctx.projectId,id,options.parentId);ui.result({command:"assets move",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsMoveCommand,"assetsMoveCommand");async function assetsDeleteCommand(id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.delete",{projectId:ctx.projectId,env:ctx.env});let result=await api.deleteAsset(ctx.projectId,id);ui.result({command:"assets delete",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsDeleteCommand,"assetsDeleteCommand");init_esm();init_dist();init_project_layout();import{execFileSync}from"node:child_process";import fs13 from"node:fs";import path15 from"node:path";var DEFAULT_ENV2="main";var ENV_ID_REGEX2=/^[a-zA-Z0-9._/-]+$/;function isValidEnv2(env){return typeof env!="string"||env.length===0||env.length>255||env.startsWith("-")||env.startsWith(".")||env.includes("//")||env.includes("--")||env.split("/").some(segment=>segment==="..")?!1:ENV_ID_REGEX2.test(env)}__name(isValidEnv2,"isValidEnv");function fnv1a82(s){let h=2166136261;for(let i=0;i<s.length;i++)h^=s.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}__name(fnv1a82,"fnv1a8");function envResourceKey2(env){let base=env.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a82(env);return base?`${base}-${hash}`:hash}__name(envResourceKey2,"envResourceKey");function buildTenantApiUrl2(projectId,env,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${envResourceKey2(env)}.${url.hostname}`,url.toString().replace(/\/$/,"")}__name(buildTenantApiUrl2,"buildTenantApiUrl");var LOCAL_CONTENT_API_ENV_KEYS=["FIMO_CONTENT_API_URL","VITE_API_URL","NEXT_PUBLIC_FIMO_API_URL","PUBLIC_FIMO_API_URL"],LOCAL_ENV_SELECTOR_KEYS=["FIMO_ENV","NEXT_PUBLIC_FIMO_ENV"];function buildLocalRuntimeEnv(options){return{...Object.fromEntries(LOCAL_CONTENT_API_ENV_KEYS.map(key=>[key,options.tenantApiUrl])),...Object.fromEntries(LOCAL_ENV_SELECTOR_KEYS.map(key=>[key,options.env]))}}__name(buildLocalRuntimeEnv,"buildLocalRuntimeEnv");function resolveLocalRuntimeEnv(options){let root2=findProjectRoot2(options.cwd),link=root2?readProjectLink(root2):null;if(!root2||!link)return null;let branch=currentBranch2(root2),env=branch??DEFAULT_ENV2,tenantApiUrl=buildTenantApiUrl2(link.projectId,env,link.tenantApiBaseUrl);return{env,tenantApiUrl,source:branch?"branch":"fallback",values:buildLocalRuntimeEnv({tenantApiUrl,env}),link}}__name(resolveLocalRuntimeEnv,"resolveLocalRuntimeEnv");function findStaleFimoOverride(explicit,derived){for(let key of LOCAL_CONTENT_API_ENV_KEYS){let value=explicit[key];if(value&&value!==derived.tenantApiUrl&&isFimoMintedTenantUrl(value,derived.link))return{key,explicit:value,derived:derived.tenantApiUrl}}return null}__name(findStaleFimoOverride,"findStaleFimoOverride");function staleOverrideMessage(stale){return`[fimo] An env file pins the app to ${stale.explicit} (seeded by an older CLI), so it will NOT follow the git branch (${stale.derived}). Run \`fimo link\` to remove that line, or delete it yourself.`}__name(staleOverrideMessage,"staleOverrideMessage");function isFimoMintedTenantUrl(value,link){try{let candidate=new URL(value),base=new URL(link.tenantApiBaseUrl);return candidate.protocol===base.protocol&&candidate.port===base.port&&candidate.hostname.startsWith(`${link.projectId}-`)&&candidate.hostname.endsWith(`.${base.hostname}`)}catch{return!1}}__name(isFimoMintedTenantUrl,"isFimoMintedTenantUrl");function readLocalEnvFiles(cwd){let root2=findProjectRoot2(cwd)??cwd,values={};for(let file of[".env",".env.local"]){let filePath=path15.join(root2,file);if(fs13.existsSync(filePath))for(let line of fs13.readFileSync(filePath,"utf-8").split(/\r?\n/)){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;let eq2=trimmed.indexOf("=");eq2<=0||(values[trimmed.slice(0,eq2).trim()]=trimmed.slice(eq2+1).trim().replace(/^['"]|['"]$/g,""))}}return values}__name(readLocalEnvFiles,"readLocalEnvFiles");function currentBranch2(root2){try{let branch=execFileSync("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:root2,stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim();return branch&&branch!=="HEAD"&&isValidEnv2(branch)?branch:null}catch{return null}}__name(currentBranch2,"currentBranch");function findProjectRoot2(start){let dir=path15.resolve(start);for(;;){if(fs13.existsSync(path15.join(dir,CURRENT_PROJECT_LAYOUT.project))||fs13.existsSync(path15.join(dir,LEGACY_PROJECT_LAYOUT.project)))return dir;let parent2=path15.dirname(dir);if(parent2===dir)return null;dir=parent2}}__name(findProjectRoot2,"findProjectRoot");function readProjectLink(root2){for(let layout of[CURRENT_PROJECT_LAYOUT,LEGACY_PROJECT_LAYOUT]){let file=path15.join(root2,layout.project);if(fs13.existsSync(file))try{let parsed=JSON.parse(fs13.readFileSync(file,"utf-8"));if(typeof parsed.projectId=="string"&&parsed.projectId.length>0&&typeof parsed.tenantApiBaseUrl=="string"&&parsed.tenantApiBaseUrl.length>0)return{projectId:parsed.projectId,tenantApiBaseUrl:parsed.tenantApiBaseUrl}}catch{return null}}return null}__name(readProjectLink,"readProjectLink");init_api();init_git();init_project_context();init_project();function envOverride(program2){return envOverrideFromCommand(program2)}__name(envOverride,"envOverride");async function branchListCommand(cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({envOverride:envOverride(program2)}),envs=await new FimoApiClient().withEnv(ctx.env).listEnvs(ctx.projectId,{includeDeleted:opts.verbose,includeAgentEnvs:opts.all});if(envs.length===0){ui.info({command:"branch",message:"(no envs yet)",hint:"Run `fimo branch <name>` to create one."});return}ui.table({command:"branch",columns:opts.verbose?[{key:"env",label:"ENV"},{key:"status",label:"STATUS"},{key:"parent",label:"PARENT"},{key:"preview",label:"PREVIEW"}]:[{key:"env",label:"ENV"},{key:"status",label:"STATUS"},{key:"parent",label:"PARENT"}],rows:envs.map(e=>({env:e.env,status:e.status,parent:e.parentEnv??"\u2014",preview:opts.verbose?e.previewUrl??"":void 0})),isActive:__name(row2=>row2.env===ctx.env,"isActive")})}__name(branchListCommand,"branchListCommand");async function branchCreateCommand(name,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env),parentEnv=opts.from??ctx.env;if(isProductionEnv(name)||isProductionEnv(parentEnv)){ui.error({command:"branch",code:"PROTECTED_ENV",message:`The '${PRODUCTION_ENV}' env is protected \u2014 it cannot be created or forked from.`});return}let parentValidation=await validateParentEnv(api,ctx.projectId,parentEnv,ctx,opts.from);if(!parentValidation.ok){ui.error({command:"branch",code:"ENV_NOT_FOUND",message:parentValidation.message});return}let created=await api.createEnv(ctx.projectId,{env:name,parentEnv});ui.ok({command:"branch",headline:`Created env '${created.env}' (status: ${created.status})`,details:{env:created.env,parent_env:parentEnv,status:created.status,preview_url:created.previewUrl??null}})}__name(branchCreateCommand,"branchCreateCommand");async function branchDeleteCommand(name,cmd){let program2=cmd.parent??cmd,ctx=await getProjectContext({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env);if(name===DEFAULT_ENV){ui.error({command:"branch",code:"PROTECTED_ENV",message:`Refusing to delete the default env '${DEFAULT_ENV}'.`});return}if(isProductionEnv(name)){ui.error({command:"branch",code:"PROTECTED_ENV",message:`The '${PRODUCTION_ENV}' env is protected and cannot be deleted.`});return}await api.deleteEnv(ctx.projectId,name),ui.ok({command:"branch",headline:`Deleted env '${name}'`,details:{env:name}})}__name(branchDeleteCommand,"branchDeleteCommand");async function checkoutCommand(name,_options,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env),cwd=resolveProjectCwd();if(isProductionEnv(name)){ui.error({command:"checkout",code:"PROTECTED_ENV",message:`The '${PRODUCTION_ENV}' env is protected and cannot be checked out.`});return}let created=!1;if(opts.create){let parentEnv=opts.from??ctx.env,parentValidation=await validateParentEnv(api,ctx.projectId,parentEnv,ctx,opts.from);if(!parentValidation.ok){ui.error({command:"checkout",code:"ENV_NOT_FOUND",message:parentValidation.message});return}await api.createEnv(ctx.projectId,{env:name,parentEnv}),created=!0}else await api.getEnv(ctx.projectId,name);let gitSwitched=!1;if(await isGitRepo(cwd))try{await runGit(["checkout",name],cwd),gitSwitched=!0}catch(err){let stderr=err instanceof Error&&"stderr"in err?String(err.stderr):"";if(/did not match any file|pathspec/i.test(stderr))await runGit(["checkout","-b",name],cwd),gitSwitched=!0;else throw err}let runtime=resolveLocalRuntimeEnv({cwd});ui.ok({command:"checkout",headline:`Now on env '${name}'`,details:{env:name,created,git_switched:gitSwitched,parent_env:opts.from??null,tenant_api_url:runtime?.tenantApiUrl??null},warnings:describeRuntimeWarnings(cwd,runtime)})}__name(checkoutCommand,"checkoutCommand");function describeRuntimeWarnings(cwd,runtime){if(!runtime)return["This checkout cannot derive its tenant API URL \u2014 the project link predates that. Run `fimo link` once to record it; until then the app keeps whatever env values it already has."];let stale=findStaleFimoOverride({...readLocalEnvFiles(cwd),...process.env},runtime);return stale?[staleOverrideMessage(stale)]:void 0}__name(describeRuntimeWarnings,"describeRuntimeWarnings");async function pullCommand(_options,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env),{env,conflicts}=await api.syncEnv(ctx.projectId,ctx.env,{from:opts.from}),warnings=conflicts>0?[`Resolved ${conflicts} conflict(s) (parent-wins for now \u2014 M12 conflict UI will add per-row picks)`]:void 0;ui.ok({command:"pull",headline:`Env '${env.env}' synced`,details:{env:env.env,from:opts.from??null,conflicts},warnings})}__name(pullCommand,"pullCommand");async function validateParentEnv(api,projectId,parentEnv,ctx,fromFlag){try{return await api.getEnv(projectId,parentEnv),{ok:!0}}catch(err){if(!(err instanceof ApiRequestError)||err.status!==404)throw err;let origin=fromFlag?`the \`--from ${fromFlag}\` flag`:ctx.source==="branch"?`your active env (\`${ctx.env}\`)`:ctx.source==="flag"?`the \`--env ${ctx.env}\` flag`:ctx.source==="tag"?`the release tag \`${ctx.env}\``:`the project default (\`${ctx.env}\`)`,fixes=[];return fromFlag?fixes.push(`pass an existing env via \`--from <env>\` (try \`--from ${DEFAULT_ENV}\`)`):ctx.source==="branch"?(fixes.push(`switch envs first: \`fimo checkout ${DEFAULT_ENV}\``),fixes.push(`or pass \`--from ${DEFAULT_ENV}\` to override for this command`)):ctx.source==="flag"?fixes.push(`use a different \`--env <existing>\` (try \`--env ${DEFAULT_ENV}\`)`):fixes.push(`pass \`--from ${DEFAULT_ENV}\` to fork from main`),{ok:!1,message:`Cannot create env: parent env '${parentEnv}' doesn't exist on this project. The CLI resolved the parent from ${origin}. Fix: ${fixes.join(", or ")}.`}}}__name(validateParentEnv,"validateParentEnv");init_dist();init_api();init_config();init_project();function registerChannelsCommands(program2){program2.command("channels").description("Manage project channel bindings").addHelpText("after",`
|
|
1192
|
+
`)}`,hint:"Run `fimo deploy` to push them first, or `fimo agents run --skip-drift-check` to dispatch the deployed version anyway."});return}if(result.skipped){ui.info({command:"agents run",message:`Dispatch was skipped: ${result.skipped}`});return}if(result.sessionId){ui.ok({command:"agents run",headline:`Triggered ${name} (session ${result.sessionId})`,details:{agent:name,session_id:result.sessionId},hint:`Watch progress: fimo agents runs ${name}`});return}ui.error({command:"agents run",code:"UNEXPECTED_RUN_RESPONSE",message:"Unexpected response from server (no sessionId, no skipped)."})}catch(err){printBundleError("agents run",err)}}__name(runAgentCommand,"runAgentCommand");init_dist();init_api();init_config();init_project();async function agentRunsCommand(name,options){try{let projectRoot=resolveProjectRoot(options.cwd??process.cwd()),projectId=options.project??readProjectId2(projectRoot);if(!projectId){ui.error({command:"agents runs",code:"NO_PROJECT_ID",message:"Could not determine project id.",hint:"Pass --project, or run from a linked Fimo project directory."});return}let limit=options.limit??20,cfg=loadConfig(),api=new FimoApiClient(cfg),sessions;try{sessions=await api.listAgentSessions(projectId,{agentName:name,env:options.env,limit})}catch(err){if(err instanceof ApiRequestError){ui.error({command:"agents runs",code:"AGENT_SESSIONS_FETCH_FAILED",message:`Failed to fetch sessions (HTTP ${err.status}): ${err.detail}`});return}throw err}if(sessions.length===0){ui.info({command:"agents runs",message:`(no recent sessions for '${name}'${options.env?` on env '${options.env}'`:""})`});return}let rows=sessions.map(session=>({id:session.id.slice(0,8),started:formatStartedAt(session.startedAt),duration:formatDuration(session.startedAt,session.finishedAt??session.cancelledAt),status:session.status,trigger:session.triggerKind,env:session.env,cost:`$${session.costUsd.toFixed(4)}`}));ui.table({command:"agents runs",columns:[{key:"id",label:"ID"},{key:"started",label:"STARTED"},{key:"duration",label:"DURATION"},{key:"status",label:"STATUS"},{key:"trigger",label:"TRIGGER"},{key:"env",label:"BRANCH"},{key:"cost",label:"COST"}],rows,cellStyle:__name((row2,column)=>{if(column==="status")return statusRole(row2.status);if(column==="cost")return"dim"},"cellStyle")})}catch(err){printBundleError("agents runs",err)}}__name(agentRunsCommand,"agentRunsCommand");function readProjectId2(projectRoot){try{return loadProjectSettings(projectRoot).projectId}catch{return}}__name(readProjectId2,"readProjectId");function statusRole(status){switch(status){case"finished":return"success";case"errored":return"error";case"cancelled":return"warn";case"running":return"accent";default:return}}__name(statusRole,"statusRole");function formatStartedAt(startedAt){if(!startedAt)return"\u2014";let date=startedAt instanceof Date?startedAt:new Date(startedAt);return Number.isNaN(date.getTime())?"\u2014":date.toISOString().slice(0,16).replace("T"," ")}__name(formatStartedAt,"formatStartedAt");function formatDuration(startedAt,endedAt){if(!startedAt||!endedAt)return"\u2014";let start=startedAt instanceof Date?startedAt:new Date(startedAt),ms=(endedAt instanceof Date?endedAt:new Date(endedAt)).getTime()-start.getTime();if(Number.isNaN(ms)||ms<0)return"\u2014";if(ms<1e3)return`${ms}ms`;let secs=Math.floor(ms/1e3);if(secs<60)return`${secs}s`;let mins=Math.floor(secs/60),remainingSecs=secs%60;return`${mins}m${remainingSecs.toString().padStart(2,"0")}s`}__name(formatDuration,"formatDuration");init_dist();var import_yaml3=__toESM(require_dist(),1);import fs10 from"node:fs";import path12 from"node:path";var SECRET_KEY_RE=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_CONFIG_PREFIX2=/^(PUBLIC_|VITE_|NEXT_PUBLIC_)/;async function agentSecretsListCommand(name,opts){try{let config=readAgentConfig(name,opts.cwd),secrets=normalizeSecrets(config.secrets);if(secrets.length===0){ui.info({command:"agents secrets list",message:`No secrets requested by agent '${name}'.`});return}ui.table({command:"agents secrets list",columns:[{key:"key",label:"KEY"},{key:"requirement",label:"REQUIREMENT"},{key:"delivery",label:"DELIVERY"}],rows:secrets.map(secret=>({key:secret.key,requirement:secret.required===!1?"optional":"required",delivery:secret.delivery??"process_env"}))})}catch(err){printBundleError("agents secrets list",err)}}__name(agentSecretsListCommand,"agentSecretsListCommand");async function agentSecretsAddCommand(name,key,opts){try{validateSecretKey(key);let{filePath,config}=readAgentConfigWithPath(name,opts.cwd),secrets=normalizeSecrets(config.secrets);secrets.some(secret=>secret.key===key)||(secrets.push({key,required:!opts.optional,delivery:"process_env"}),config.secrets=secrets,fs10.writeFileSync(filePath,(0,import_yaml3.stringify)(config))),ui.ok({command:"agents secrets add",headline:`Agent '${name}' now requests secret ${key}`,details:{agent:name,key,optional:opts.optional===!0}})}catch(err){printBundleError("agents secrets add",err)}}__name(agentSecretsAddCommand,"agentSecretsAddCommand");async function agentSecretsRemoveCommand(name,key,opts){try{let{filePath,config}=readAgentConfigWithPath(name,opts.cwd),after2=normalizeSecrets(config.secrets).filter(secret=>secret.key!==key);config.secrets=after2,fs10.writeFileSync(filePath,(0,import_yaml3.stringify)(config)),ui.ok({command:"agents secrets remove",headline:`Agent '${name}' no longer requests secret ${key}`,details:{agent:name,key}})}catch(err){printBundleError("agents secrets remove",err)}}__name(agentSecretsRemoveCommand,"agentSecretsRemoveCommand");function normalizeSecrets(raw){if(!Array.isArray(raw))return[];let out=[];for(let item of raw){if(typeof item=="string"){out.push({key:item,required:!0,delivery:"process_env"});continue}if(item&&typeof item=="object"&&typeof item.key=="string"){let entry=item;out.push({key:entry.key,required:typeof entry.required=="boolean"?entry.required:!0,delivery:(entry.delivery==="process_env","process_env")})}}return out}__name(normalizeSecrets,"normalizeSecrets");function validateSecretKey(key){if(!SECRET_KEY_RE.test(key))throw new Error(`Secret key '${key}' must be UPPER_SNAKE_CASE.`);if(PUBLIC_CONFIG_PREFIX2.test(key))throw new Error(`Secret key '${key}' uses a public variable prefix. Use project variables for public values.`)}__name(validateSecretKey,"validateSecretKey");function readAgentConfig(name,cwd){return readAgentConfigWithPath(name,cwd).config}__name(readAgentConfig,"readAgentConfig");function readAgentConfigWithPath(name,cwd){let projectRoot=resolveProjectRoot(cwd??process.cwd()),filePath=path12.join(resolveAgentBundlesDir(projectRoot),name,"config.yaml");if(!fs10.existsSync(filePath))throw new Error(`Agent '${name}' does not have a config.yaml at ${filePath}.`);let parsed=(0,import_yaml3.parse)(fs10.readFileSync(filePath,"utf8")),config=parsed&&typeof parsed=="object"&&!Array.isArray(parsed)?parsed:{};return{filePath,config}}__name(readAgentConfigWithPath,"readAgentConfigWithPath");init_dist();init_scaffold();async function listTemplatesCommand(){let templates=listAgentTemplates();if(templates.length===0){ui.info({command:"agents list-templates",message:"No agent templates bundled with this CLI."});return}ui.result({command:"agents list-templates",data:{templates},render:__name(()=>{let lines=["Available templates:"],longest=templates.reduce((acc,t2)=>Math.max(acc,t2.name.length),0);for(let t2 of templates){let padded=t2.name.padEnd(longest);lines.push(` ${padded} ${t2.goalFirstLine??"(no GOAL.md)"}`)}return lines.push(""),lines.push(" Use `fimo agents create <name> --template <template>` to scaffold."),lines.join(`
|
|
1193
|
+
`)},"render")})}__name(listTemplatesCommand,"listTemplatesCommand");import fs11 from"node:fs";import path13 from"node:path";init_dist();init_api();init_auth();init_config();init_project_context();init_project();async function runValidateAgents(opts){let projectRoot=resolveProjectRoot(opts.cwd??process.cwd()),agentsDir=resolveAgentBundlesDir(projectRoot),configPath=resolveProjectPolicyPath(projectRoot),policy=validatePolicy(configPath,projectRoot),bundleList=[];if(opts.name){if(!isValidAgentName(opts.name))return{ok:!1,policy,bundles:[{name:opts.name,ok:!1,phases:{parse:{ok:!1,issues:[{pointer:"name",message:`Invalid agent name '${opts.name}'.`}]},capabilities:{ok:!0,issues:[]},composition:{ok:!0,issues:[]},semantics:{ok:!0,issues:[]}},warnings:[]}]};let bundle=await safeParse(path13.join(agentsDir,opts.name));if(!bundle.ok)return{ok:!1,policy,bundles:[{name:opts.name,ok:!1,phases:{parse:{ok:!1,issues:[bundle.issue]},capabilities:{ok:!0,issues:[]},composition:{ok:!0,issues:[]},semantics:{ok:!0,issues:[]}},warnings:[]}]};bundleList=[bundle.bundle]}else bundleList=await listBundles(agentsDir);let reports=[],cloudNotifications=hasCloudNotificationRecipients(configPath);for(let bundle of bundleList){let report=validateOneBundle(bundle,bundleList);!cloudNotifications&&(bundle.config.triggers??[]).some(t2=>t2.type!=="manual")&&report.warnings.push({pointer:`${path13.basename(configPath)}:agents.notifications.email_recipients`,message:"Cloud triggers stay unwired until `agents.notifications.email_recipients` is non-empty (ADR-0009)."}),reports.push(report)}return{ok:(policy?.ok??!0)&&reports.every(r=>r.ok),policy,bundles:reports}}__name(runValidateAgents,"runValidateAgents");function hasCloudNotificationRecipients(policyPath){if(!fs11.existsSync(policyPath))return!1;try{return(parseFimoConfig(fs11.readFileSync(policyPath,"utf8"),{path:path13.basename(policyPath)}).agents?.notifications?.email_recipients??[]).length>0}catch{return!1}}__name(hasCloudNotificationRecipients,"hasCloudNotificationRecipients");function validatePolicy(policyPath,projectRoot){if(!fs11.existsSync(policyPath))return null;try{let text3=fs11.readFileSync(policyPath,"utf8");return parseFimoConfig(text3,{path:path13.relative(projectRoot,policyPath)}),{ok:!0,issues:[]}}catch(err){return{ok:!1,issues:[{pointer:path13.relative(projectRoot,policyPath),message:err.message,remediation:err.remediation}]}}}__name(validatePolicy,"validatePolicy");async function safeParse(bundlePath){try{return{ok:!0,bundle:await parseBundle(bundlePath)}}catch(err){return{ok:!1,issue:{pointer:path13.basename(bundlePath),message:err.message,remediation:err.remediation}}}}__name(safeParse,"safeParse");function validateOneBundle(bundle,allBundles){let phases={parse:{ok:!0,issues:[]},capabilities:{ok:!0,issues:[]},composition:{ok:!0,issues:[]},semantics:{ok:!0,issues:[]}},vocab=validateAgainstVocabulary(bundle.capabilities,CAPABILITY_VOCABULARY);for(let token of vocab.unknown){let suggestion=suggestCapability(token),err=new BundleInvalidCapabilityError(token,"unknown",{suggestion:suggestion??void 0});phases.capabilities.ok=!1,phases.capabilities.issues.push({pointer:`capabilities.yaml: ${token}`,message:err.message,remediation:err.remediation})}for(let token of vocab.nonDeclarable){let err=new BundleInvalidCapabilityError(token,"runtime_only");phases.capabilities.ok=!1,phases.capabilities.issues.push({pointer:`capabilities.yaml: ${token}`,message:err.message,remediation:err.remediation})}let agentMap=new Map(allBundles.map(b=>[b.name,b])),compositionResult=composition_exports.validateComposition(bundle,agentMap);if(compositionResult.cycle){let err=new BundleCompositionCycleError(compositionResult.cycle);phases.composition.ok=!1,phases.composition.issues.push({pointer:"config.yaml:composition",message:err.message,remediation:err.remediation})}for(let missingName of compositionResult.missing)phases.composition.ok=!1,phases.composition.issues.push({pointer:`config.yaml:composition.sub-agents[name=${missingName}]`,message:`Sub-agent '${missingName}' is referenced but not present in the project's agent-bundle directory.`,remediation:`Run \`fimo agents create ${missingName}\` or remove the reference from composition.sub-agents.`});for(let invalid of compositionResult.invalidGrants)phases.composition.ok=!1,phases.composition.issues.push({pointer:`config.yaml:composition.sub-agents[name=${invalid.subAgentName}].explicit_grants`,message:`explicit_grants references capabilities the sub-agent never declared: [${invalid.invalid.join(", ")}]. Declared: [${invalid.declared.join(", ")}].`,remediation:"Remove the undeclared tokens from explicit_grants, or add them to the sub-agent's capabilities.yaml."});if(!compositionResult.cycle){let cycle=detectCompositionCycle({root:bundle,agentMap});if(cycle){let err=new BundleCompositionCycleError(cycle);phases.composition.ok=!1,phases.composition.issues.push({pointer:"config.yaml:composition",message:err.message,remediation:err.remediation})}}let issues=validateBundle(bundle,{availableAgents:allBundles}),warnings=[...bundle.warnings];for(let issue of issues){if(issue.severity==="warning"){warnings.push({pointer:issue.pointer,message:issue.message});continue}issue.pointer.startsWith("capabilities.yaml")||issue.pointer.startsWith("config.yaml:composition")||(phases.semantics.ok=!1,phases.semantics.issues.push({pointer:issue.pointer,message:issue.message}))}let ok=phases.parse.ok&&phases.capabilities.ok&&phases.composition.ok&&phases.semantics.ok;return{name:bundle.name,ok,phases,warnings}}__name(validateOneBundle,"validateOneBundle");async function runAvailabilityChecks(cwd){let projectRoot=resolveProjectRoot(cwd),projectId;try{projectId=loadProjectSettings(projectRoot).projectId}catch{if(projectId=process.env.FIMO_PROJECT_ID?.trim()??"",!projectId)return{ok:!0,skippedReason:"not-linked",issues:[]}}if(!process.env.FIMO_API_TOKEN?.trim()&&!readCredentials())return{ok:!0,skippedReason:"not-signed-in",issues:[]};let api=new FimoApiClient(loadConfig()),context=await getProjectContext({cwd:projectRoot}),environment=await api.resolveProjectEnvironmentKey(projectId,context.env),agentsDir=resolveAgentBundlesDir(projectRoot),bundles=await listBundles(agentsDir),issues=[],configPath=__name(agentName=>path13.relative(projectRoot,path13.join(agentsDir,agentName,"config.yaml")).replaceAll("\\","/"),"configPath"),integrationsByAgent=bundles.map(bundle=>({name:bundle.name,integrations:Object.entries(agentIntegrationPolicy(bundle.config)).map(([integrationKey,entry])=>({integrationKey,enabled:entry.enabled,tools:enabledAgentIntegrationTools(entry),allTools:entry.tools===void 0,toolsConfigured:entry.tools!==void 0})).filter(entry=>entry.enabled)})).filter(entry=>entry.integrations.length>0);if(integrationsByAgent.length>0){let statuses=await api.listProjectIntegrations(projectId),statusByKey=new Map(statuses.map(status=>[status.integrationKey,status])),infoByKey=new Map;for(let agent of integrationsByAgent)for(let integration of agent.integrations){let file=configPath(agent.name),status=statusByKey.get(integration.integrationKey);if(!status){issues.push({pointer:file,message:`${agent.name} allows unsupported integration ${integration.integrationKey}.`});continue}integration.toolsConfigured&&integration.tools.length===0&&issues.push({pointer:file,message:`${agent.name} enables ${integration.integrationKey}, but its tools map allows none. Remove the tools map to allow all available tools, or set at least one integrations.${integration.integrationKey}.tools.<tool>: true entry.`}),status.enabled||issues.push({pointer:file,message:`${agent.name} allows ${integration.integrationKey}, but the project integration is not enabled. Run: fimo integrations enable ${integration.integrationKey}`});let info=infoByKey.get(integration.integrationKey)??await api.getProjectIntegrationInfo(projectId,integration.integrationKey);infoByKey.set(integration.integrationKey,info);let knownTools=new Set(info.tools.map(tool=>tool.key)),effectiveTools=integration.allTools?[...knownTools]:integration.tools;for(let tool of effectiveTools)knownTools.has(tool)||issues.push({pointer:file,message:`${agent.name} allows unknown ${integration.integrationKey}.${tool} tool. Supported tools: ${[...knownTools].sort().join(", ")}`})}}let secretsByAgent=bundles.map(bundle=>({name:bundle.name,keys:(bundle.config.secrets??[]).filter(secret=>secret.required!==!1).map(secret=>secret.key)})).filter(entry=>entry.keys.length>0);if(secretsByAgent.length>0){let defined=new Set((await api.listProjectSecretEntries(projectId,{kind:"secret",environment})).map(secret=>secret.key));for(let entry of secretsByAgent)for(let key of entry.keys)defined.has(key)||issues.push({pointer:configPath(entry.name),message:`${entry.name} requires project secret ${key}, but it is not set. Run: fimo secrets add ${key} --stdin`})}return{ok:issues.length===0,skippedReason:null,issues}}__name(runAvailabilityChecks,"runAvailabilityChecks");async function validateAgentsCommand(opts){let report;try{report=await runValidateAgents(opts)}catch(err){throw printBundleError("agents validate",err),opts.noExit||(process.exitCode=1),err}return report.bundles.length===0&&!report.policy?(ui.info({command:"agents validate",message:"No bundles or Fimo project config found."}),report):(report.availability=await runAvailabilityChecks(opts.cwd??process.cwd()),report.availability.ok||(report.ok=!1),ui.result({command:"agents validate",data:report,render:__name(()=>renderReportHuman(report),"render")}),!report.ok&&!opts.noExit&&(process.exitCode=1),report)}__name(validateAgentsCommand,"validateAgentsCommand");function renderReportHuman(report){let lines=[];if(report.policy)if(report.policy.ok)lines.push(" \u2713 Fimo config policy ok");else{lines.push(" \u2717 Fimo config");for(let issue of report.policy.issues)lines.push(` \u2717 ${issue.message}`),issue.remediation&&lines.push(` fix: ${issue.remediation}`)}for(let bundle of report.bundles)if(bundle.ok){lines.push(` \u2713 ${bundle.name} all phases ok`);for(let w3 of bundle.warnings)lines.push(` ! ${w3.pointer}: ${w3.message}`)}else{lines.push(` \u2717 ${bundle.name}`);for(let phase of["parse","capabilities","composition","semantics"])for(let issue of bundle.phases[phase].issues)lines.push(` \u2717 [${phase}] ${issue.message}`),issue.remediation&&lines.push(` fix: ${issue.remediation}`)}if(report.availability)if(report.availability.skippedReason){let why=report.availability.skippedReason==="not-signed-in"?"not signed in \u2014 run `fimo login`":"no linked project";lines.push(` \u21B7 integrations & secrets \u2014 skipped (${why})`)}else if(report.availability.ok)lines.push(" \u2713 integrations & secrets available");else{lines.push(" \u2717 integrations & secrets");for(let issue of report.availability.issues)lines.push(` \u2717 ${issue.message}`)}return lines.join(`
|
|
1194
|
+
`)}__name(renderReportHuman,"renderReportHuman");function registerAgentsCommands(program2){let agents=program2.command("agents").description("AI agent bundle management (M13)");agents.command("create <name>").description("Scaffold .fimo/agents/<name>/ from a template").option("--template <name>","Template to copy from (default: _default)").option("--description <text>","Short tagline written to config.yaml (one line, up to 280 chars)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>createAgentCommand(name,opts)),agents.command("list").description("List agents declared under the project agents directory").option("-C, --cwd <dir>","Project directory").option("--project <id>","Project id (accepted for parity with cloud-scoped subcommands)").action(opts=>listAgentsCommand(opts)),agents.command("list-templates").alias("templates").description("List the bundled starter-catalog templates").action(()=>listTemplatesCommand()),agents.command("validate [name]").description("Validate one or every bundle (parse, capabilities, composition, policy)").option("--json","Emit structured ValidationReport (for CI)").option("-C, --cwd <dir>","Project directory").action(async(name,opts)=>{await validateAgentsCommand({name,json:opts.json,cwd:opts.cwd})}),agents.command("integrations <name>").description("Preview local integration access policy for an agent").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentIntegrationsCommand(name,opts)),agents.command("run <name>").description("Trigger a manual run on the server (returns sessionId)").option("--env <env>","Target env (default: main)").option("--project <id>","Project id (defaults to .fimo/project.json or legacy .fimo.settings.json projectId)").option("-C, --cwd <dir>","Project directory").option("--skip-drift-check","Dispatch even when the bundle has uncommitted local changes").action((name,opts)=>runAgentCommand(name,opts)),agents.command("logs <name>").description("Stream the most recent session log").option("--session <id>","Specific session id to target").option("-C, --cwd <dir>","Project directory").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").action((name,opts)=>agentLogsCommand(name,opts)),agents.command("runs <name>").description("Paginated session list").option("--limit <n>","Max sessions to show (default: 20)",v=>Number.parseInt(v,10)).option("--env <env>","Filter sessions to a specific env").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentRunsCommand(name,opts)),agents.command("report <name>").description("Print a run's report (the agent's final message); latest run unless --session is given").option("--session <id>","Target a specific session id").option("--env <env>","Pick the latest run on a specific env").option("--project <id>","Project id (defaults to the linked project in .fimo/project.json or legacy .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentReportCommand(name,opts));let secrets=agents.command("secrets").description("Edit the secrets requested in an agent config.yaml");secrets.command("list <name>").description("List secret keys requested by an agent config").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentSecretsListCommand(name,opts)),secrets.command("add <name> <key>").description("Add a secret key request to an agent config").option("-C, --cwd <dir>","Project directory").option("--optional","Mark the secret as optional").action((name,key,opts)=>agentSecretsAddCommand(name,key,opts)),secrets.command("remove <name> <key>").alias("rm").description("Remove a secret key request from an agent config").option("-C, --cwd <dir>","Project directory").action((name,key,opts)=>agentSecretsRemoveCommand(name,key,opts))}__name(registerAgentsCommands,"registerAgentsCommands");init_dist();init_project_context();function parseRangeOptions(options){let params={};if(options.preset&&(params.preset=options.preset),options.groupBy&&(params.groupBy=options.groupBy),options.from&&(params.from=options.from),options.to&&(params.to=options.to),options.days!==void 0){let n=Number(options.days);if(!Number.isFinite(n))throw new Error(`Invalid --days value: ${options.days}`);params.days=n}return params}__name(parseRangeOptions,"parseRangeOptions");function renderPrettyJson(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson,"renderPrettyJson");async function analyticsPageviewsCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params);ui.result({command:"analytics pageviews",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsPageviewsCommand,"analyticsPageviewsCommand");var TOP_DIMENSIONS=["pages","browsers","devices","countries","sources"];function dimensionField(dimension){return`top${dimension.charAt(0).toUpperCase()}${dimension.slice(1)}`}__name(dimensionField,"dimensionField");async function analyticsTopCommand(dimension,options,cmd){if(!TOP_DIMENSIONS.includes(dimension))throw new Error(`Unknown dimension: ${dimension}. Expected one of: ${TOP_DIMENSIONS.join(", ")}`);let{ctx,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params),field=dimensionField(dimension),items=Array.isArray(result[field])?result[field]:[],limit;if(options.limit!==void 0){let n=Number(options.limit);if(!Number.isFinite(n)||n<1)throw new Error(`Invalid --limit value: ${options.limit}`);limit=n}let trimmed=limit!==void 0?items.slice(0,limit):items;ui.result({command:"analytics top",data:{dimension,items:trimmed},render:__name(()=>renderPrettyJson(trimmed),"render")})}__name(analyticsTopCommand,"analyticsTopCommand");async function analyticsAnnotationsListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params),annotations2=Array.isArray(result.annotations)?result.annotations:[];ui.result({command:"analytics annotations list",data:{annotations:annotations2},render:__name(()=>renderPrettyJson(annotations2),"render")})}__name(analyticsAnnotationsListCommand,"analyticsAnnotationsListCommand");async function analyticsAnnotationsSetCommand(date,content2,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd),result=await api.setAnalyticsAnnotation(ctx.projectId,date,content2);ui.result({command:"analytics annotations set",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsAnnotationsSetCommand,"analyticsAnnotationsSetCommand");async function analyticsAnnotationsDeleteCommand(date,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await api.deleteAnalyticsAnnotation(ctx.projectId,date),ui.ok({command:"analytics annotations delete",headline:`Deleted annotation for ${date}.`,details:{date}})}__name(analyticsAnnotationsDeleteCommand,"analyticsAnnotationsDeleteCommand");init_dist();import{spawn}from"node:child_process";import{mkdirSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{dirname,extname,isAbsolute,join as join2,resolve as resolvePath}from"node:path";var ENV_SESSION="FIMO_AGENT_SESSION",ENV_CAPS_FALLBACK="FIMO_AGENT_CAPABILITIES";function currentAgentSession(){let id=process.env[ENV_SESSION];return id&&id.length>0?id:void 0}__name(currentAgentSession,"currentAgentSession");async function defaultFetchSessionCapabilities(_sessionId){let raw=process.env[ENV_CAPS_FALLBACK];return raw?raw.split(",").map(s=>s.trim()).filter(s=>s.length>0):[]}__name(defaultFetchSessionCapabilities,"defaultFetchSessionCapabilities");async function requireCapability(cap,ctx={}){let sessionId=currentAgentSession();if(!sessionId)return{ok:!0,bypassed:!0};let granted=await(ctx.fetchSessionCapabilities??defaultFetchSessionCapabilities)(sessionId);if(!granted.includes(cap)){try{await auditCapabilityDecision({sessionId,cap,decision:"deny",reason:granted.length===0?"session-not-found":"not-declared",projectId:ctx.projectId,env:ctx.env})}catch{}throw new CapabilityDenied({cap,reason:granted.length===0?"session-not-found":"not-declared",granted,sessionId})}return auditCapabilityDecision({sessionId,cap,decision:"allow",projectId:ctx.projectId,env:ctx.env}),{ok:!0,bypassed:!1}}__name(requireCapability,"requireCapability");async function requireOperation(op,ctx={}){if(!hasOperation(op))throw new Error(`requireOperation: unknown operation id '${op}' \u2014 register it in @fimo/agents capabilities/operation-map.ts`);let cap=capabilityFor(op);return isRuntimeBaselineOperationCapability(cap)?{ok:!0,bypassed:currentAgentSession()===void 0}:requireCapability(cap,ctx)}__name(requireOperation,"requireOperation");init_project_context();init_project();function extensionFor(asset){let fromName=extname(asset.name);if(fromName&&fromName.length<=6)return fromName;let mime=asset.mimeType??"";return mime.startsWith("image/")?"."+(mime.split("/")[1]??"bin"):mime.startsWith("video/")?"."+(mime.split("/")[1]??"mp4"):mime.startsWith("audio/")?"."+(mime.split("/")[1]??"mp3"):""}__name(extensionFor,"extensionFor");function defaultDownloadPath(asset){let ext=extensionFor(asset);return join2(tmpdir(),"fimo-assets",`${asset.id}${ext}`)}__name(defaultDownloadPath,"defaultDownloadPath");async function downloadToPath(url,dest){let response=await fetch(url);if(!response.ok)throw new Error(`Failed to download asset: HTTP ${response.status} ${response.statusText}`);let arrayBuffer=await response.arrayBuffer();mkdirSync(dirname(dest),{recursive:!0}),writeFileSync(dest,new Uint8Array(arrayBuffer))}__name(downloadToPath,"downloadToPath");function spawnBrowser(url){let command=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(process.platform==="win32"?spawn("cmd",["/c","start","",url],{detached:!0,stdio:"ignore"}):spawn(command,[url],{detached:!0,stdio:"ignore"})).unref()}__name(spawnBrowser,"spawnBrowser");function renderPrettyJson2(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson2,"renderPrettyJson");async function assetsOpenCommand(id,options,cmd){if(options.download&&options.browser)throw new Error("--download and --browser are mutually exclusive \u2014 pick one");let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.get",{projectId:ctx.projectId,env:ctx.env});let cwd=resolveProjectCwd(options.cwd),{data:asset}=await api.getAsset(ctx.projectId,id);if(asset.type==="folder")throw new Error(`Asset ${id} is a folder; can only open files`);if(!asset.url)throw new Error(`Asset ${id} has no public URL \u2014 it may not have finished uploading`);if(options.browser){spawnBrowser(asset.url);let payload2={opened:asset.url};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}if(options.download){let dest=options.path?isAbsolute(options.path)?options.path:resolvePath(cwd,options.path):defaultDownloadPath(asset);await downloadToPath(asset.url,dest);let payload2={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,path:dest,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,aiAltText:asset.aiAltText??null};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}let payload={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,caption:asset.caption??null,aiAltText:asset.aiAltText??null,aiCaption:asset.aiCaption??null,aiTags:asset.aiTags??null};ui.result({command:"assets open",data:payload,render:__name(()=>renderPrettyJson2(payload),"render")})}__name(assetsOpenCommand,"assetsOpenCommand");init_dist();import fs12 from"node:fs";import path14 from"node:path";init_project_context();init_project();function renderPrettyJson3(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson3,"renderPrettyJson");async function assetsListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.list",{projectId:ctx.projectId,env:ctx.env});let mimePrefix=options.mimePrefix;mimePrefix||(options.image?mimePrefix="image/":options.video?mimePrefix="video/":options.audio&&(mimePrefix="audio/"));let params={};options.parentId&&(params.parentId=options.parentId),options.search&&(params.search=options.search),options.type&&(params.type=options.type),mimePrefix&&(params.mimePrefix=mimePrefix),options.sortBy&&(params.sortBy=options.sortBy),options.limit&&(params.limit=options.limit),options.offset&&(params.offset=options.offset);let result=await api.listAssets(ctx.projectId,Object.keys(params).length>0?params:void 0);ui.result({command:"assets list",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsListCommand,"assetsListCommand");async function assetsUploadCommand(file,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.upload",{projectId:ctx.projectId,env:ctx.env});let cwd=resolveProjectCwd(options.cwd);if(options.parentId&&options.folderPath)throw new Error("Use either --parent-id or --folder-path, not both");let filePath=path14.resolve(cwd,file);if(!fs12.existsSync(filePath))throw new Error(`File not found: ${filePath}`);let fileBuffer=fs12.readFileSync(filePath),fileName=path14.basename(filePath),formData=new FormData;formData.append("file",new Blob([fileBuffer]),fileName),options.name&&formData.append("name",options.name),options.parentId&&formData.append("parentId",options.parentId),options.folderPath&&formData.append("folderPath",options.folderPath);let result=await api.uploadAsset(ctx.projectId,formData);ui.result({command:"assets upload",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsUploadCommand,"assetsUploadCommand");async function assetsCreateFolderCommand(name,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.create_folder",{projectId:ctx.projectId,env:ctx.env});let result=await api.createFolder(ctx.projectId,name,options.parentId);ui.result({command:"assets create-folder",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsCreateFolderCommand,"assetsCreateFolderCommand");async function assetsMoveCommand(id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.move",{projectId:ctx.projectId,env:ctx.env});let result=await api.moveAsset(ctx.projectId,id,options.parentId);ui.result({command:"assets move",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsMoveCommand,"assetsMoveCommand");async function assetsDeleteCommand(id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.delete",{projectId:ctx.projectId,env:ctx.env});let result=await api.deleteAsset(ctx.projectId,id);ui.result({command:"assets delete",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsDeleteCommand,"assetsDeleteCommand");init_esm();init_dist();init_project_layout();import{execFileSync}from"node:child_process";import fs13 from"node:fs";import path15 from"node:path";var DEFAULT_ENV2="main";var ENV_ID_REGEX2=/^[a-zA-Z0-9._/-]+$/;function isValidEnv2(env){return typeof env!="string"||env.length===0||env.length>255||env.startsWith("-")||env.startsWith(".")||env.includes("//")||env.includes("--")||env.split("/").some(segment=>segment==="..")?!1:ENV_ID_REGEX2.test(env)}__name(isValidEnv2,"isValidEnv");function fnv1a82(s){let h=2166136261;for(let i=0;i<s.length;i++)h^=s.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}__name(fnv1a82,"fnv1a8");function envResourceKey2(env){let base=env.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a82(env);return base?`${base}-${hash}`:hash}__name(envResourceKey2,"envResourceKey");function buildTenantApiUrl2(projectId,env,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${envResourceKey2(env)}.${url.hostname}`,url.toString().replace(/\/$/,"")}__name(buildTenantApiUrl2,"buildTenantApiUrl");var LOCAL_CONTENT_API_ENV_KEYS=["FIMO_CONTENT_API_URL","VITE_API_URL","NEXT_PUBLIC_FIMO_API_URL","PUBLIC_FIMO_API_URL"],LOCAL_ENV_SELECTOR_KEYS=["FIMO_ENV","NEXT_PUBLIC_FIMO_ENV"];function buildLocalRuntimeEnv(options){return{...Object.fromEntries(LOCAL_CONTENT_API_ENV_KEYS.map(key=>[key,options.tenantApiUrl])),...Object.fromEntries(LOCAL_ENV_SELECTOR_KEYS.map(key=>[key,options.env]))}}__name(buildLocalRuntimeEnv,"buildLocalRuntimeEnv");function resolveLocalRuntimeEnv(options){let root2=findProjectRoot2(options.cwd),link=root2?readProjectLink(root2):null;if(!root2||!link)return null;let branch=currentBranch2(root2),env=branch??DEFAULT_ENV2,tenantApiUrl=buildTenantApiUrl2(link.projectId,env,link.tenantApiBaseUrl);return{env,tenantApiUrl,source:branch?"branch":"fallback",values:buildLocalRuntimeEnv({tenantApiUrl,env}),link}}__name(resolveLocalRuntimeEnv,"resolveLocalRuntimeEnv");function findStaleFimoOverride(explicit,derived){for(let key of LOCAL_CONTENT_API_ENV_KEYS){let value=explicit[key];if(value&&value!==derived.tenantApiUrl&&isFimoMintedTenantUrl(value,derived.link))return{key,explicit:value,derived:derived.tenantApiUrl}}return null}__name(findStaleFimoOverride,"findStaleFimoOverride");function staleOverrideMessage(stale){return`[fimo] An env file pins the app to ${stale.explicit} (seeded by an older CLI), so it will NOT follow the git branch (${stale.derived}). Run \`fimo link\` to remove that line, or delete it yourself.`}__name(staleOverrideMessage,"staleOverrideMessage");function isFimoMintedTenantUrl(value,link){try{let candidate=new URL(value),base=new URL(link.tenantApiBaseUrl);return candidate.protocol===base.protocol&&candidate.port===base.port&&candidate.hostname.startsWith(`${link.projectId}-`)&&candidate.hostname.endsWith(`.${base.hostname}`)}catch{return!1}}__name(isFimoMintedTenantUrl,"isFimoMintedTenantUrl");function readLocalEnvFiles(cwd){let root2=findProjectRoot2(cwd)??cwd,values={};for(let file of[".env",".env.local"]){let filePath=path15.join(root2,file);if(fs13.existsSync(filePath))for(let line of fs13.readFileSync(filePath,"utf-8").split(/\r?\n/)){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;let eq2=trimmed.indexOf("=");eq2<=0||(values[trimmed.slice(0,eq2).trim()]=trimmed.slice(eq2+1).trim().replace(/^['"]|['"]$/g,""))}}return values}__name(readLocalEnvFiles,"readLocalEnvFiles");function currentBranch2(root2){try{let branch=execFileSync("git",["rev-parse","--abbrev-ref","HEAD"],{cwd:root2,stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim();return branch&&branch!=="HEAD"&&isValidEnv2(branch)?branch:null}catch{return null}}__name(currentBranch2,"currentBranch");function findProjectRoot2(start){let dir=path15.resolve(start);for(;;){if(fs13.existsSync(path15.join(dir,CURRENT_PROJECT_LAYOUT.project))||fs13.existsSync(path15.join(dir,LEGACY_PROJECT_LAYOUT.project)))return dir;let parent2=path15.dirname(dir);if(parent2===dir)return null;dir=parent2}}__name(findProjectRoot2,"findProjectRoot");function readProjectLink(root2){for(let layout of[CURRENT_PROJECT_LAYOUT,LEGACY_PROJECT_LAYOUT]){let file=path15.join(root2,layout.project);if(fs13.existsSync(file))try{let parsed=JSON.parse(fs13.readFileSync(file,"utf-8"));if(typeof parsed.projectId=="string"&&parsed.projectId.length>0&&typeof parsed.tenantApiBaseUrl=="string"&&parsed.tenantApiBaseUrl.length>0)return{projectId:parsed.projectId,tenantApiBaseUrl:parsed.tenantApiBaseUrl}}catch{return null}}return null}__name(readProjectLink,"readProjectLink");init_api();init_git();init_project_context();init_project();function envOverride(program2){return envOverrideFromCommand(program2)}__name(envOverride,"envOverride");async function branchListCommand(cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({envOverride:envOverride(program2)}),envs=await new FimoApiClient().withEnv(ctx.env).listEnvs(ctx.projectId,{includeDeleted:opts.verbose,includeAgentEnvs:opts.all});if(envs.length===0){ui.info({command:"branch",message:"(no envs yet)",hint:"Run `fimo branch <name>` to create one."});return}ui.table({command:"branch",columns:opts.verbose?[{key:"env",label:"ENV"},{key:"status",label:"STATUS"},{key:"parent",label:"PARENT"},{key:"preview",label:"PREVIEW"}]:[{key:"env",label:"ENV"},{key:"status",label:"STATUS"},{key:"parent",label:"PARENT"}],rows:envs.map(e=>({env:e.env,status:e.status,parent:e.parentEnv??"\u2014",preview:opts.verbose?e.previewUrl??"":void 0})),isActive:__name(row2=>row2.env===ctx.env,"isActive")})}__name(branchListCommand,"branchListCommand");async function branchCreateCommand(name,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env),parentEnv=opts.from??ctx.env;if(isProductionEnv(name)||isProductionEnv(parentEnv)){ui.error({command:"branch",code:"PROTECTED_ENV",message:`The '${PRODUCTION_ENV}' env is protected \u2014 it cannot be created or forked from.`});return}let parentValidation=await validateParentEnv(api,ctx.projectId,parentEnv,ctx,opts.from);if(!parentValidation.ok){ui.error({command:"branch",code:"ENV_NOT_FOUND",message:parentValidation.message});return}let created=await api.createEnv(ctx.projectId,{env:name,parentEnv});ui.ok({command:"branch",headline:`Created Branch '${created.env}' (status: ${created.status})`,details:{env:created.env,parent_env:parentEnv,status:created.status,preview_url:created.previewUrl??null}})}__name(branchCreateCommand,"branchCreateCommand");async function branchDeleteCommand(name,cmd){let program2=cmd.parent??cmd,ctx=await getProjectContext({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env);if(name===DEFAULT_ENV){ui.error({command:"branch",code:"PROTECTED_ENV",message:`Refusing to delete the default env '${DEFAULT_ENV}'.`});return}if(isProductionEnv(name)){ui.error({command:"branch",code:"PROTECTED_ENV",message:`The '${PRODUCTION_ENV}' env is protected and cannot be deleted.`});return}await api.deleteEnv(ctx.projectId,name),ui.ok({command:"branch",headline:`Deleted Branch '${name}'`,details:{env:name}})}__name(branchDeleteCommand,"branchDeleteCommand");async function checkoutCommand(name,_options,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env),cwd=resolveProjectCwd();if(isProductionEnv(name)){ui.error({command:"checkout",code:"PROTECTED_ENV",message:`The '${PRODUCTION_ENV}' env is protected and cannot be checked out.`});return}let created=!1;if(opts.create){let parentEnv=opts.from??ctx.env,parentValidation=await validateParentEnv(api,ctx.projectId,parentEnv,ctx,opts.from);if(!parentValidation.ok){ui.error({command:"checkout",code:"ENV_NOT_FOUND",message:parentValidation.message});return}await api.createEnv(ctx.projectId,{env:name,parentEnv}),created=!0}else await api.getEnv(ctx.projectId,name);let gitSwitched=!1;if(await isGitRepo(cwd))try{await runGit(["checkout",name],cwd),gitSwitched=!0}catch(err){let stderr=err instanceof Error&&"stderr"in err?String(err.stderr):"";if(/did not match any file|pathspec/i.test(stderr))await runGit(["checkout","-b",name],cwd),gitSwitched=!0;else throw err}let runtime=resolveLocalRuntimeEnv({cwd});ui.ok({command:"checkout",headline:`Now on Branch '${name}'`,details:{env:name,created,git_switched:gitSwitched,parent_env:opts.from??null,tenant_api_url:runtime?.tenantApiUrl??null},warnings:describeRuntimeWarnings(cwd,runtime)})}__name(checkoutCommand,"checkoutCommand");function describeRuntimeWarnings(cwd,runtime){if(!runtime)return["This checkout cannot derive its tenant API URL \u2014 the project link predates that. Run `fimo link` once to record it; until then the app keeps whatever env values it already has."];let stale=findStaleFimoOverride({...readLocalEnvFiles(cwd),...process.env},runtime);return stale?[staleOverrideMessage(stale)]:void 0}__name(describeRuntimeWarnings,"describeRuntimeWarnings");async function pullCommand(_options,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env),{env,conflicts}=await api.syncEnv(ctx.projectId,ctx.env,{from:opts.from}),warnings=conflicts>0?[`Resolved ${conflicts} conflict(s) (parent-wins for now \u2014 M12 conflict UI will add per-row picks)`]:void 0;ui.ok({command:"pull",headline:`Env '${env.env}' synced`,details:{env:env.env,from:opts.from??null,conflicts},warnings})}__name(pullCommand,"pullCommand");async function validateParentEnv(api,projectId,parentEnv,ctx,fromFlag){try{return await api.getEnv(projectId,parentEnv),{ok:!0}}catch(err){if(!(err instanceof ApiRequestError)||err.status!==404)throw err;let origin=fromFlag?`the \`--from ${fromFlag}\` flag`:ctx.source==="branch"?`your active env (\`${ctx.env}\`)`:ctx.source==="flag"?`the Branch override flag (\`${ctx.env}\`)`:ctx.source==="tag"?`the release tag \`${ctx.env}\``:`the project default (\`${ctx.env}\`)`,fixes=[];return fromFlag?fixes.push(`pass an existing env via \`--from <env>\` (try \`--from ${DEFAULT_ENV}\`)`):ctx.source==="branch"?(fixes.push(`switch envs first: \`fimo checkout ${DEFAULT_ENV}\``),fixes.push(`or pass \`--from ${DEFAULT_ENV}\` to override for this command`)):ctx.source==="flag"?fixes.push(`use a different \`--env <existing>\` (try \`--env ${DEFAULT_ENV}\`)`):fixes.push(`pass \`--from ${DEFAULT_ENV}\` to fork from main`),{ok:!1,message:`Cannot create env: parent env '${parentEnv}' doesn't exist on this project. The CLI resolved the parent from ${origin}. Fix: ${fixes.join(", or ")}.`}}}__name(validateParentEnv,"validateParentEnv");init_dist();init_api();init_config();init_project();function registerChannelsCommands(program2){program2.command("channels").description("Manage project channel bindings").addHelpText("after",`
|
|
1195
1195
|
Examples:
|
|
1196
1196
|
fimo integrations connect slack
|
|
1197
1197
|
fimo channels bind slack:#launch
|
|
@@ -1275,7 +1275,20 @@ ${failure.stderr}`});break}}__name(emitPushFailure,"emitPushFailure");function e
|
|
|
1275
1275
|
Purchase: ${formatPrice(pricing.price)} \xD7 ${effectiveYears} year${effectiveYears===1?"":"s"} = ${formatPrice(totalCents)}
|
|
1276
1276
|
Renewal: ${formatPrice(pricing.renewalPrice)}/year${autoRenew===!1?" (auto-renew off)":" (auto-renews)"}`);let confirmed=await ot2({message:`Create a checkout invoice for ${domain}?`,initialValue:!1});if(q(confirmed)||!confirmed){ui.info({command:"domains buy",message:"Cancelled."});return}}let purchased;try{purchased=await api.purchaseRegisteredDomain(organizationId,{domain,years:effectiveYears,autoRenew})}catch(err){rethrowCliAuthError(err);let featureMsg=featureDisabledMessage(err);if(featureMsg){ui.error({command:"domains buy",code:"DOMAIN_PURCHASE_DISABLED",message:featureMsg});return}if(err instanceof ApiRequestError){if(err.status===403){ui.error({command:"domains buy",code:"PURCHASE_FORBIDDEN",message:"You don't have permission to buy domains for this organization.",hint:"Org admins only."});return}ui.error({command:"domains buy",code:"PURCHASE_FAILED",message:`Purchase failed: ${err.detail}`});return}throw err}ui.result({command:"domains buy",data:purchased,render:__name(()=>{let lines=[];return lines.push(""),lines.push(`Invoice created for ${purchased.domain} (${formatPrice(purchased.price)}).`),lines.push("Pay to complete registration:"),lines.push(""),lines.push(` ${purchased.checkoutUrl??"(checkout URL pending \u2014 refresh in a moment)"}`),lines.push(""),lines.push("No money moves until you complete payment in the browser."),lines.push(`Once paid, ${purchased.domain} registers automatically and shows up in \`fimo domains owned\`.`),lines.join(`
|
|
1277
1277
|
`)},"render")}),options.open&&purchased.checkoutUrl&&await open_default(purchased.checkoutUrl).catch(()=>{});let{enabled:waitEnabled,timeoutMs}=parseWait(options,!1);waitEnabled&&await pollPurchasePayment(api,organizationId,purchased,timeoutMs)}__name(domainsBuyCommand,"domainsBuyCommand");async function pollPurchasePayment(api,organizationId,initial,timeoutMs){let start=Date.now(),sp=spinner(`Waiting for payment (status: ${initial.status})`),current=initial;for(;Date.now()-start<timeoutMs;){if(current.status==="owned")return sp.succeed(`Registered \u2014 ${current.domain} is now yours.`),current;if(current.status==="registration_failed"||current.status==="payment_failed")return sp.fail(`${current.status==="payment_failed"?"Payment":"Registration"} failed for ${current.domain}.`),current;await new Promise(resolve10=>setTimeout(resolve10,5e3));try{current=await api.refreshRegisteredDomainPayment(organizationId,current.id),sp.update(`Waiting (status: ${current.status})`)}catch(err){return rethrowCliAuthError(err,()=>sp.fail("Authentication required")),sp.fail(`Refresh failed: ${err instanceof Error?err.message:String(err)}`),current}}return sp.fail("Timed out. Run `fimo domains owned` later to check status."),current}__name(pollPurchasePayment,"pollPurchasePayment");async function domainsOwnedCommand(options){let cfg=loadConfig(),api=new FimoApiClient(cfg),organizationId=resolveOrgId(options),domains2;try{domains2=await api.listOwnedRegisteredDomains(organizationId)}catch(err){rethrowCliAuthError(err);let featureMsg=featureDisabledMessage(err);if(featureMsg){ui.error({command:"domains owned",code:"DOMAIN_PURCHASE_DISABLED",message:featureMsg});return}if(err instanceof ApiRequestError&&err.status===403){ui.error({command:"domains owned",code:"OWNED_DOMAINS_FORBIDDEN",message:"You don't have access to this organization's domains.",hint:"Org admins only."});return}throw err}let statusFilter=options.status?.split(",").map(s=>s.trim().toLowerCase()).filter(s=>s.length>0),limit=options.limit?parseInt(options.limit,10):null,filtered=domains2;if(statusFilter&&statusFilter.length>0&&(filtered=filtered.filter(d3=>statusFilter.includes(d3.status.toLowerCase()))),limit!==null&&Number.isFinite(limit)&&limit>0&&(filtered=filtered.slice(0,limit)),filtered.length===0){ui.info({command:"domains owned",message:"No domains registered through Fimo yet.",hint:"Try `fimo domains search <keyword>`."});return}ui.result({command:"domains owned",data:{domains:filtered,total:filtered.length},render:__name(()=>{let nameW=Math.max(8,...filtered.map(d3=>d3.domain.length)),statusW=Math.max(8,...filtered.map(d3=>d3.status.length)),lines=[];lines.push(` ${pad("DOMAIN",nameW)} ${pad("STATUS",statusW)} EXPIRES`);for(let d3 of filtered){let expires=d3.expirationDate?new Date(d3.expirationDate).toISOString().slice(0,10):"\u2014";lines.push(` ${pad(d3.domain,nameW)} ${pad(d3.status,statusW)} ${expires}`)}return lines.join(`
|
|
1278
|
-
`)},"render")})}__name(domainsOwnedCommand,"domainsOwnedCommand");init_dist();init_project_context();init_project();import fs30 from"node:fs";import path29 from"node:path";function selectedInputSources(options,inlineFlag){return[options.body!==void 0?inlineFlag:void 0,options.file?"--file":void 0,options.stdin?"--stdin":void 0].filter(source=>!!source)}__name(selectedInputSources,"selectedInputSources");async function readContentInputSource(options,createError,inlineFlag="--body"){if(selectedInputSources(options,inlineFlag).length!==1)throw createError(`Pass exactly one of ${inlineFlag}, --file, or --stdin.`);if(options.body!==void 0)return options.body;if(options.file){let filePath=path29.resolve(resolveProjectCwd(options.cwd),options.file);try{return fs30.readFileSync(filePath,"utf8")}catch(error){throw createError(error instanceof Error?error.message:`Could not read ${filePath}.`)}}if(process.stdin.isTTY)throw createError("Pipe input to the command when using --stdin.");let chunks=[];for await(let chunk of process.stdin)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));return Buffer.concat(chunks).toString("utf8")}__name(readContentInputSource,"readContentInputSource");function renderPrettyJson5(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson5,"renderPrettyJson");var EntriesInputError=class extends Error{static{__name(this,"EntriesInputError")}constructor(message){super(message),this.name="EntriesInputError"}};function parseJsonObject(value){let parsed=JSON.parse(value);if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new Error("Expected a JSON object");return parsed}__name(parseJsonObject,"parseJsonObject");function parseJsonArray(value){let parsed;try{parsed=JSON.parse(value)}catch(error){throw new EntriesInputError(error instanceof Error?`Invalid JSON: ${error.message}`:"Invalid JSON.")}if(!Array.isArray(parsed))throw new EntriesInputError("Expected a JSON array.");return parsed}__name(parseJsonArray,"parseJsonArray");function parseBulkJsonObject(value){try{return parseJsonObject(value)}catch(error){throw new EntriesInputError(error instanceof Error?error.message:"Expected a JSON object.")}}__name(parseBulkJsonObject,"parseBulkJsonObject");function parseIds(value){let ids=[...new Set(value.split(",").map(id=>id.trim()).filter(Boolean))];if(ids.length===0)throw new EntriesInputError("--ids must include at least one ID.");return ids}__name(parseIds,"parseIds");function missingIdWarnings(result,action){let{missing}=result.meta;if(missing.length===0)return[];let changed=action==="updated"?result.meta.updated:result.meta.deleted,ids=missing.join(", ");if(changed===0)return missing.length===1?[`No entries were ${action}; the requested ID was not found: ${ids}.`]:[`No entries were ${action}; all ${missing.length} requested IDs were not found: ${ids}.`];let subject=missing.length===1?"ID was":"IDs were";return[`${missing.length} requested ${subject} not found: ${ids}.`]}__name(missingIdWarnings,"missingIdWarnings");function addDefinedMetadata(body,metadata){for(let[key,value]of Object.entries(metadata))value!==void 0&&(body[key]=value);return body}__name(addDefinedMetadata,"addDefinedMetadata");async function entriesListCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.list",{projectId:ctx.projectId,env:ctx.env});let params={};options.limit&&(params.limit=options.limit),options.offset&&(params.offset=options.offset),options.search&&(params.search=options.search),options.sort&&(params.sort=options.sort),!options.sort&&options.sortBy&&(params.sortBy=options.sortBy),!options.sort&&options.sortDirection&&(params.sortDirection=options.sortDirection),options.where&&(JSON.parse(options.where),params.where=options.where),options.fields&&(params.fields=options.fields),options.populate&&(params.populate=options.populate),options.locale&&(params.locale=options.locale);let result=await api.listEntries(ctx.projectId,typeName,Object.keys(params).length>0?params:void 0);ui.result({command:"entries list",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesListCommand,"entriesListCommand");async function entriesGetCommand(typeName,id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.get",{projectId:ctx.projectId,env:ctx.env});let result=await api.getEntry(ctx.projectId,typeName,id,options.locale);ui.result({command:"entries get",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesGetCommand,"entriesGetCommand");async function entriesCreateCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.create",{projectId:ctx.projectId,env:ctx.env});let data2=addDefinedMetadata(parseJsonObject(options.body),{locale:options.locale,documentId:options.documentId}),result=await api.createEntry(ctx.projectId,typeName,data2);ui.result({command:"entries create",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesCreateCommand,"entriesCreateCommand");async function entriesUpdateCommand(typeName,id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.update",{projectId:ctx.projectId,env:ctx.env});let data2=parseJsonObject(options.body),result=await api.updateEntry(ctx.projectId,typeName,id,options.locale,data2);ui.result({command:"entries update",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesUpdateCommand,"entriesUpdateCommand");async function entriesDeleteCommand(typeName,id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.delete",{projectId:ctx.projectId,env:ctx.env});let result=await api.deleteEntry(ctx.projectId,typeName,id,options.locale);ui.result({command:"entries delete",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesDeleteCommand,"entriesDeleteCommand");async function entriesQueryCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.query",{projectId:ctx.projectId,env:ctx.env});let sql=await readContentInputSource({...options,body:options.sql},message=>new EntriesInputError(message),"--sql"),result=await api.queryEntries(ctx.projectId,sql);ui.result({command:"entries query",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesQueryCommand,"entriesQueryCommand");async function entriesBulkCreateCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.bulk_create",{projectId:ctx.projectId,env:ctx.env});let entries2=parseJsonArray(await readContentInputSource(options,message=>new EntriesInputError(message))),result=await api.bulkCreateEntries(ctx.projectId,typeName,entries2);ui.result({command:"entries bulk-create",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesBulkCreateCommand,"entriesBulkCreateCommand");async function entriesBulkUpdateCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.bulk_update",{projectId:ctx.projectId,env:ctx.env});let usesBatchInput=!!(options.file||options.stdin),payload;if(usesBatchInput){if(options.body!==void 0||options.ids||options.where)throw new EntriesInputError("Use --file or --stdin alone for per-entry updates.");payload={updates:parseJsonArray(await readContentInputSource(options,message=>new EntriesInputError(message)))}}else{if((options.ids?1:0)+(options.where?1:0)!=1||options.body===void 0)throw new EntriesInputError("Pass --body with exactly one of --ids or --where.");payload={...options.ids?{ids:parseIds(options.ids)}:{where:parseBulkJsonObject(options.where)},body:parseBulkJsonObject(options.body)}}let result=await api.bulkUpdateEntries(ctx.projectId,typeName,payload);ui.result({command:"entries bulk-update",data:result,warnings:missingIdWarnings(result,"updated"),render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesBulkUpdateCommand,"entriesBulkUpdateCommand");async function entriesBulkDeleteCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});if(await requireOperation("cms.bulk_delete",{projectId:ctx.projectId,env:ctx.env}),(options.ids?1:0)+(options.where?1:0)!=1)throw new EntriesInputError("Pass exactly one of --ids or --where.");let payload={...options.ids?{ids:parseIds(options.ids)}:{where:parseBulkJsonObject(options.where)},...options.locale?{locale:options.locale}:{}},result=await api.bulkDeleteEntries(ctx.projectId,typeName,payload);ui.result({command:"entries bulk-delete",data:result,warnings:missingIdWarnings(result,"deleted"),render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesBulkDeleteCommand,"entriesBulkDeleteCommand");init_dist();init_project_context();var UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function resolveFormId(api,projectId,formIdOrName){if(UUID_RE.test(formIdOrName))return formIdOrName;let forms3=await api.listForms(projectId),matches=(Array.isArray(forms3)?forms3:[]).filter(f=>f&&f.name===formIdOrName);if(matches.length===0)throw new Error(`No form named '${formIdOrName}'. Run \`fimo forms list\` to see options.`);if(matches.length>1)throw new Error(`Multiple forms named '${formIdOrName}' (${matches.length}). Pass the form ID instead.`);return matches[0].id}__name(resolveFormId,"resolveFormId");async function formsSubmissionsListCommand(formIdOrName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("forms.list",{projectId:ctx.projectId,env:ctx.env});let formId=await resolveFormId(api,ctx.projectId,formIdOrName),params={};if(options.limit!==void 0){let n=Number(options.limit);if(!Number.isFinite(n)||n<1)throw new Error(`Invalid --limit value: ${options.limit}`);params.limit=n}if(options.offset!==void 0){let n=Number(options.offset);if(!Number.isFinite(n)||n<0)throw new Error(`Invalid --offset value: ${options.offset}`);params.offset=n}if(options.search&&(params.searchQuery=options.search),options.sort){if(options.sort!=="asc"&&options.sort!=="desc")throw new Error(`Invalid --sort value: ${options.sort}. Expected 'asc' or 'desc'.`);params.sortDirection=options.sort}let result=await api.listFormSubmissions(ctx.projectId,formId,params);ui.result({command:"forms submissions list",data:result,render:__name(()=>JSON.stringify(result,null,2),"render")})}__name(formsSubmissionsListCommand,"formsSubmissionsListCommand");async function formsSubmissionsGetCommand(formIdOrName,submissionId,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("forms.get",{projectId:ctx.projectId,env:ctx.env});let formId=await resolveFormId(api,ctx.projectId,formIdOrName),result=await api.getFormSubmission(ctx.projectId,formId,submissionId);ui.result({command:"forms submissions get",data:result,render:__name(()=>JSON.stringify(result,null,2),"render")})}__name(formsSubmissionsGetCommand,"formsSubmissionsGetCommand");async function formsSubmissionsStatsCommand(formIdOrName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("forms.get",{projectId:ctx.projectId,env:ctx.env});let formId=await resolveFormId(api,ctx.projectId,formIdOrName),result=await api.getFormSubmissionStats(ctx.projectId,formId);ui.result({command:"forms submissions stats",data:result,render:__name(()=>JSON.stringify(result,null,2),"render")})}__name(formsSubmissionsStatsCommand,"formsSubmissionsStatsCommand");init_dist();import fs31 from"node:fs";import path30 from"node:path";init_project_context();init_project();function renderPrettyJson6(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson6,"renderPrettyJson");async function formsListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("forms.list",{projectId:ctx.projectId,env:ctx.env});let result=await api.listForms(ctx.projectId);ui.result({command:"forms list",data:result,render:__name(()=>renderPrettyJson6(result),"render")})}__name(formsListCommand,"formsListCommand");async function formsGetCommand(id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("forms.get",{projectId:ctx.projectId,env:ctx.env});let result=await api.getForm(ctx.projectId,id);ui.result({command:"forms get",data:result,render:__name(()=>renderPrettyJson6(result),"render")})}__name(formsGetCommand,"formsGetCommand");async function formsPushCommand(formName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("forms.push",{projectId:ctx.projectId,env:ctx.env});let cwd=resolveProjectCwd(options.cwd),formsDir=path30.join(cwd,"src/forms"),files=formName?[`${formName}.json`]:fs31.readdirSync(formsDir).filter(f=>f.endsWith(".json")),results=[];for(let file of files){let filePath=path30.join(formsDir,file);if(!fs31.existsSync(filePath))throw new Error(`Form file not found: ${filePath}`);let form=JSON.parse(fs31.readFileSync(filePath,"utf-8")),{id,...payload2}=form;if(id){let result=await api.updateForm(ctx.projectId,id,payload2);results.push(result)}else{let result=await api.createForm(ctx.projectId,payload2);form.id=result.id,fs31.writeFileSync(filePath,`${JSON.stringify(form,null,2)}
|
|
1278
|
+
`)},"render")})}__name(domainsOwnedCommand,"domainsOwnedCommand");init_dist();init_project_context();init_project();import fs30 from"node:fs";import path29 from"node:path";function selectedInputSources(options,inlineFlag){return[options.body!==void 0?inlineFlag:void 0,options.file?"--file":void 0,options.stdin?"--stdin":void 0].filter(source=>!!source)}__name(selectedInputSources,"selectedInputSources");async function readContentInputSource(options,createError,inlineFlag="--body"){if(selectedInputSources(options,inlineFlag).length!==1)throw createError(`Pass exactly one of ${inlineFlag}, --file, or --stdin.`);if(options.body!==void 0)return options.body;if(options.file){let filePath=path29.resolve(resolveProjectCwd(options.cwd),options.file);try{return fs30.readFileSync(filePath,"utf8")}catch(error){throw createError(error instanceof Error?error.message:`Could not read ${filePath}.`)}}if(process.stdin.isTTY)throw createError("Pipe input to the command when using --stdin.");let chunks=[];for await(let chunk of process.stdin)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));return Buffer.concat(chunks).toString("utf8")}__name(readContentInputSource,"readContentInputSource");function renderPrettyJson5(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson5,"renderPrettyJson");var EntriesInputError=class extends Error{static{__name(this,"EntriesInputError")}constructor(message){super(message),this.name="EntriesInputError"}};function parseJsonObject(value){let parsed=JSON.parse(value);if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new Error("Expected a JSON object");return parsed}__name(parseJsonObject,"parseJsonObject");function parseJsonArray(value){let parsed;try{parsed=JSON.parse(value)}catch(error){throw new EntriesInputError(error instanceof Error?`Invalid JSON: ${error.message}`:"Invalid JSON.")}if(!Array.isArray(parsed))throw new EntriesInputError("Expected a JSON array.");return parsed}__name(parseJsonArray,"parseJsonArray");function parseBulkJsonObject(value){try{return parseJsonObject(value)}catch(error){throw new EntriesInputError(error instanceof Error?error.message:"Expected a JSON object.")}}__name(parseBulkJsonObject,"parseBulkJsonObject");function parseIds(value){let ids=[...new Set(value.split(",").map(id=>id.trim()).filter(Boolean))];if(ids.length===0)throw new EntriesInputError("--ids must include at least one ID.");return ids}__name(parseIds,"parseIds");function missingIdWarnings(result,action){let{missing}=result.meta;if(missing.length===0)return[];let changed=action==="updated"?result.meta.updated:result.meta.deleted,ids=missing.join(", ");if(changed===0)return missing.length===1?[`No entries were ${action}; the requested ID was not found: ${ids}.`]:[`No entries were ${action}; all ${missing.length} requested IDs were not found: ${ids}.`];let subject=missing.length===1?"ID was":"IDs were";return[`${missing.length} requested ${subject} not found: ${ids}.`]}__name(missingIdWarnings,"missingIdWarnings");function addDefinedMetadata(body,metadata){for(let[key,value]of Object.entries(metadata))value!==void 0&&(body[key]=value);return body}__name(addDefinedMetadata,"addDefinedMetadata");async function entriesListCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.list",{projectId:ctx.projectId,env:ctx.env});let params={};options.limit&&(params.limit=options.limit),options.offset&&(params.offset=options.offset),options.search&&(params.search=options.search),options.sort&&(params.sort=options.sort),!options.sort&&options.sortBy&&(params.sortBy=options.sortBy),!options.sort&&options.sortDirection&&(params.sortDirection=options.sortDirection),options.where&&(JSON.parse(options.where),params.where=options.where),options.fields&&(params.fields=options.fields),options.populate&&(params.populate=options.populate),options.locale&&(params.locale=options.locale);let result=await api.listEntries(ctx.projectId,typeName,Object.keys(params).length>0?params:void 0);ui.result({command:"entries list",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesListCommand,"entriesListCommand");async function entriesGetCommand(typeName,id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.get",{projectId:ctx.projectId,env:ctx.env});let result=await api.getEntry(ctx.projectId,typeName,id,options.locale);ui.result({command:"entries get",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesGetCommand,"entriesGetCommand");async function entriesCreateCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.create",{projectId:ctx.projectId,env:ctx.env});let data2=addDefinedMetadata(parseJsonObject(options.body),{locale:options.locale,documentId:options.documentId}),result=await api.createEntry(ctx.projectId,typeName,data2);ui.result({command:"entries create",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesCreateCommand,"entriesCreateCommand");async function entriesUpdateCommand(typeName,id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.update",{projectId:ctx.projectId,env:ctx.env});let data2=parseJsonObject(options.body),result=await api.updateEntry(ctx.projectId,typeName,id,options.locale,data2);ui.result({command:"entries update",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesUpdateCommand,"entriesUpdateCommand");async function entriesDeleteCommand(typeName,id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.delete",{projectId:ctx.projectId,env:ctx.env});let result=await api.deleteEntry(ctx.projectId,typeName,id,options.locale);ui.result({command:"entries delete",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesDeleteCommand,"entriesDeleteCommand");async function entriesQueryCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.query",{projectId:ctx.projectId,env:ctx.env});let sql=await readContentInputSource({...options,body:options.sql},message=>new EntriesInputError(message),"--sql"),result=await api.queryEntries(ctx.projectId,sql);ui.result({command:"entries query",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesQueryCommand,"entriesQueryCommand");async function entriesBulkCreateCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.bulk_create",{projectId:ctx.projectId,env:ctx.env});let entries2=parseJsonArray(await readContentInputSource(options,message=>new EntriesInputError(message))),result=await api.bulkCreateEntries(ctx.projectId,typeName,entries2);ui.result({command:"entries bulk-create",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesBulkCreateCommand,"entriesBulkCreateCommand");async function entriesBulkUpdateCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.bulk_update",{projectId:ctx.projectId,env:ctx.env});let usesBatchInput=!!(options.file||options.stdin),payload;if(usesBatchInput){if(options.body!==void 0||options.ids||options.where)throw new EntriesInputError("Use --file or --stdin alone for per-entry updates.");payload={updates:parseJsonArray(await readContentInputSource(options,message=>new EntriesInputError(message)))}}else{if((options.ids?1:0)+(options.where?1:0)!=1||options.body===void 0)throw new EntriesInputError("Pass --body with exactly one of --ids or --where.");payload={...options.ids?{ids:parseIds(options.ids)}:{where:parseBulkJsonObject(options.where)},body:parseBulkJsonObject(options.body)}}let result=await api.bulkUpdateEntries(ctx.projectId,typeName,payload);ui.result({command:"entries bulk-update",data:result,warnings:missingIdWarnings(result,"updated"),render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesBulkUpdateCommand,"entriesBulkUpdateCommand");async function entriesBulkDeleteCommand(typeName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});if(await requireOperation("cms.bulk_delete",{projectId:ctx.projectId,env:ctx.env}),(options.ids?1:0)+(options.where?1:0)!=1)throw new EntriesInputError("Pass exactly one of --ids or --where.");let payload={...options.ids?{ids:parseIds(options.ids)}:{where:parseBulkJsonObject(options.where)},...options.locale?{locale:options.locale}:{}},result=await api.bulkDeleteEntries(ctx.projectId,typeName,payload);ui.result({command:"entries bulk-delete",data:result,warnings:missingIdWarnings(result,"deleted"),render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesBulkDeleteCommand,"entriesBulkDeleteCommand");init_dist();init_api();init_config();init_auth_errors();init_project();function collect(value,previous){return[...previous??[],value]}__name(collect,"collect");function addScopeOptions(command){return command.option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory")}__name(addScopeOptions,"addScopeOptions");function registerEnvironmentsCommands(program2){let environments=program2.command("environments").description("Group project Branches into deployment Environments").addHelpText("after",`
|
|
1279
|
+
Environments group Branches. Production is the deployed snapshot published from main.
|
|
1280
|
+
Automatic previews receives every unclaimed Branch, including main.
|
|
1281
|
+
|
|
1282
|
+
Examples:
|
|
1283
|
+
fimo environments list
|
|
1284
|
+
fimo environments create Staging --match "release/*" --match qa
|
|
1285
|
+
fimo environments update Staging --match "release/*" --description "Release verification"
|
|
1286
|
+
fimo environments delete Staging
|
|
1287
|
+
`);addScopeOptions(environments.command("list").description("List built-in and custom Environments")).action(options=>listCommand(options)),addScopeOptions(environments.command("create <name>").description("Create a custom Environment that claims matching Branches (Pro plan required)").requiredOption("--match <pattern>","Claim an exact or trailing-wildcard Branch pattern; repeat as needed",collect).option("--description <text>","Describe how this Environment is used")).action((name,options)=>createCommand2(name,options)),addScopeOptions(environments.command("update <name-or-id>").description("Replace the Branch patterns for a custom Environment").requiredOption("--match <pattern>","Claim an exact or trailing-wildcard Branch pattern; repeat as needed",collect).option("--description <text>","Replace the Environment description")).action((nameOrId,options)=>updateCommand(nameOrId,options)),addScopeOptions(environments.command("delete <name-or-id>").description("Delete a custom policy; matching Branches fall back to Automatic previews")).action((nameOrId,options)=>deleteCommand(nameOrId,options))}__name(registerEnvironmentsCommands,"registerEnvironmentsCommands");function resolveProjectId3(options){return options.project?options.project:loadProjectSettings(resolveProjectCwd(options.cwd)).projectId}__name(resolveProjectId3,"resolveProjectId");function renderPatterns(environment){return environment.kind==="production"?`${environment.sourceBranch} (published snapshot)`:environment.kind==="preview"?"every unclaimed Branch":environment.branchPatterns.join(", ")}__name(renderPatterns,"renderPatterns");function renderBranchCount(environment){return environment.kind==="production"?"n/a":String(environment.matchedBranchCount)}__name(renderBranchCount,"renderBranchCount");function renderEnvironment(environment){let lines=[environment.name,` ID: ${environment.id}`,` Branch patterns: ${renderPatterns(environment)}`];return environment.kind!=="production"&&lines.push(` Matched Branches: ${environment.matchedBranchCount}`),environment.kind==="custom"&&environment.description&&lines.push(` Description: ${environment.description}`),lines.join(`
|
|
1288
|
+
`)}__name(renderEnvironment,"renderEnvironment");async function listCommand(options){let environments=await new FimoApiClient(loadConfig()).listProjectEnvironments(resolveProjectId3(options));ui.result({command:"environments list",data:environments,render:__name(()=>{let rows=environments.map(environment=>({environment:environment.name,patterns:renderPatterns(environment),branches:renderBranchCount(environment),description:environment.kind==="custom"?environment.description??"":""})),widths={environment:Math.max(11,...rows.map(row2=>row2.environment.length)),patterns:Math.max(15,...rows.map(row2=>row2.patterns.length)),branches:Math.max(8,...rows.map(row2=>row2.branches.length))},pad2=__name((value,width)=>value.padEnd(width),"pad");return[`${pad2("ENVIRONMENT",widths.environment)} ${pad2("BRANCH PATTERNS",widths.patterns)} ${pad2("BRANCHES",widths.branches)} DESCRIPTION`,...rows.map(row2=>`${pad2(row2.environment,widths.environment)} ${pad2(row2.patterns,widths.patterns)} ${pad2(row2.branches,widths.branches)} ${row2.description}`)].join(`
|
|
1289
|
+
`)},"render"),hint:"Production is published from main. Automatic previews receives every unclaimed Branch, including main."})}__name(listCommand,"listCommand");async function createCommand2(name,options){let api=new FimoApiClient(loadConfig());try{let environment=await api.createProjectEnvironment(resolveProjectId3(options),{name,branchPatterns:options.match,description:options.description??null});ui.result({command:"environments create",data:environment,render:__name(()=>`Created custom Environment
|
|
1290
|
+
${renderEnvironment(environment)}`,"render")})}catch(error){renderApiError("environments create",error)}}__name(createCommand2,"createCommand");async function findEnvironment(api,projectId,nameOrId,command){let environment=(await api.listProjectEnvironments(projectId)).find(candidate=>candidate.id===nameOrId||candidate.name===nameOrId);return environment||(ui.error({command,code:"PROJECT_ENVIRONMENT_NOT_FOUND",message:`No Environment matching '${nameOrId}' was found in this project.`,hint:"Run `fimo environments list` to see available names and IDs."}),null)}__name(findEnvironment,"findEnvironment");async function updateCommand(nameOrId,options){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId3(options),current=await findEnvironment(api,projectId,nameOrId,"environments update");if(current)try{let environment=await api.updateProjectEnvironment(projectId,current.id,{name:current.name,branchPatterns:options.match,description:options.description??(current.kind==="custom"?current.description:null)});ui.result({command:"environments update",data:environment,render:__name(()=>`Updated custom Environment
|
|
1291
|
+
${renderEnvironment(environment)}`,"render")})}catch(error){renderApiError("environments update",error)}}__name(updateCommand,"updateCommand");async function deleteCommand(nameOrId,options){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId3(options),current=await findEnvironment(api,projectId,nameOrId,"environments delete");if(current)try{let result=await api.deleteProjectEnvironment(projectId,current.id),matchedBranches=current.kind==="production"?0:current.matchedBranchCount;ui.ok({command:"environments delete",headline:`Deleted custom Environment ${current.name}. ${matchedBranches} matching ${matchedBranches===1?"Branch now falls":"Branches now fall"} back to Automatic previews. Branches and sandboxes were not deleted.`,details:{deleted_id:result.deletedId,matched_branches:matchedBranches,fallback_environment:"preview"}})}catch(error){renderApiError("environments delete",error)}}__name(deleteCommand,"deleteCommand");function renderApiError(command,error){if(rethrowCliAuthError(error),!(error instanceof ApiRequestError))throw error;if(error.status===403&&error.code!=="custom_environments_requires_pro"){let required=error.body&&typeof error.body=="object"&&!Array.isArray(error.body)?error.body.required:void 0;throw new PermissionDeniedError(loadConfig().apiUrl,Array.isArray(required)?required:required?[required]:[],error.detail)}ui.error({command,code:error.code?.toUpperCase()??"ENVIRONMENT_REQUEST_FAILED",message:error.detail,...error.code==="custom_environments_requires_pro"?{hint:"Upgrade at https://fimo.ai/pricing to create custom Environments."}:{}})}__name(renderApiError,"renderApiError");init_dist();init_project_context();var UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function resolveFormId(api,projectId,formIdOrName){if(UUID_RE.test(formIdOrName))return formIdOrName;let forms3=await api.listForms(projectId),matches=(Array.isArray(forms3)?forms3:[]).filter(f=>f&&f.name===formIdOrName);if(matches.length===0)throw new Error(`No form named '${formIdOrName}'. Run \`fimo forms list\` to see options.`);if(matches.length>1)throw new Error(`Multiple forms named '${formIdOrName}' (${matches.length}). Pass the form ID instead.`);return matches[0].id}__name(resolveFormId,"resolveFormId");async function formsSubmissionsListCommand(formIdOrName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("forms.list",{projectId:ctx.projectId,env:ctx.env});let formId=await resolveFormId(api,ctx.projectId,formIdOrName),params={};if(options.limit!==void 0){let n=Number(options.limit);if(!Number.isFinite(n)||n<1)throw new Error(`Invalid --limit value: ${options.limit}`);params.limit=n}if(options.offset!==void 0){let n=Number(options.offset);if(!Number.isFinite(n)||n<0)throw new Error(`Invalid --offset value: ${options.offset}`);params.offset=n}if(options.search&&(params.searchQuery=options.search),options.sort){if(options.sort!=="asc"&&options.sort!=="desc")throw new Error(`Invalid --sort value: ${options.sort}. Expected 'asc' or 'desc'.`);params.sortDirection=options.sort}let result=await api.listFormSubmissions(ctx.projectId,formId,params);ui.result({command:"forms submissions list",data:result,render:__name(()=>JSON.stringify(result,null,2),"render")})}__name(formsSubmissionsListCommand,"formsSubmissionsListCommand");async function formsSubmissionsGetCommand(formIdOrName,submissionId,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("forms.get",{projectId:ctx.projectId,env:ctx.env});let formId=await resolveFormId(api,ctx.projectId,formIdOrName),result=await api.getFormSubmission(ctx.projectId,formId,submissionId);ui.result({command:"forms submissions get",data:result,render:__name(()=>JSON.stringify(result,null,2),"render")})}__name(formsSubmissionsGetCommand,"formsSubmissionsGetCommand");async function formsSubmissionsStatsCommand(formIdOrName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("forms.get",{projectId:ctx.projectId,env:ctx.env});let formId=await resolveFormId(api,ctx.projectId,formIdOrName),result=await api.getFormSubmissionStats(ctx.projectId,formId);ui.result({command:"forms submissions stats",data:result,render:__name(()=>JSON.stringify(result,null,2),"render")})}__name(formsSubmissionsStatsCommand,"formsSubmissionsStatsCommand");init_dist();import fs31 from"node:fs";import path30 from"node:path";init_project_context();init_project();function renderPrettyJson6(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson6,"renderPrettyJson");async function formsListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("forms.list",{projectId:ctx.projectId,env:ctx.env});let result=await api.listForms(ctx.projectId);ui.result({command:"forms list",data:result,render:__name(()=>renderPrettyJson6(result),"render")})}__name(formsListCommand,"formsListCommand");async function formsGetCommand(id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("forms.get",{projectId:ctx.projectId,env:ctx.env});let result=await api.getForm(ctx.projectId,id);ui.result({command:"forms get",data:result,render:__name(()=>renderPrettyJson6(result),"render")})}__name(formsGetCommand,"formsGetCommand");async function formsPushCommand(formName,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("forms.push",{projectId:ctx.projectId,env:ctx.env});let cwd=resolveProjectCwd(options.cwd),formsDir=path30.join(cwd,"src/forms"),files=formName?[`${formName}.json`]:fs31.readdirSync(formsDir).filter(f=>f.endsWith(".json")),results=[];for(let file of files){let filePath=path30.join(formsDir,file);if(!fs31.existsSync(filePath))throw new Error(`Form file not found: ${filePath}`);let form=JSON.parse(fs31.readFileSync(filePath,"utf-8")),{id,...payload2}=form;if(id){let result=await api.updateForm(ctx.projectId,id,payload2);results.push(result)}else{let result=await api.createForm(ctx.projectId,payload2);form.id=result.id,fs31.writeFileSync(filePath,`${JSON.stringify(form,null,2)}
|
|
1279
1292
|
`),results.push(result)}}let payload=results.length===1?results[0]:results;ui.result({command:"forms push",data:payload,render:__name(()=>renderPrettyJson6(payload),"render")})}__name(formsPushCommand,"formsPushCommand");async function formsDeleteCommand(id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("forms.delete",{projectId:ctx.projectId,env:ctx.env});let result=await api.deleteForm(ctx.projectId,id);ui.result({command:"forms delete",data:result,render:__name(()=>renderPrettyJson6(result),"render")})}__name(formsDeleteCommand,"formsDeleteCommand");init_dist();init_project_context();init_dist();function coerceScalar(type,raw){switch(type){case"number":return Number.parseFloat(raw);case"integer":return Number.parseInt(raw,10);case"boolean":return raw==="true"||raw==="1";case"unknown":try{return JSON.parse(raw)}catch{return raw}default:return raw}}__name(coerceScalar,"coerceScalar");function tokenizeFlags(tokens,knownNames,booleanNames,shortAliases={}){let values=new Map,bools=new Map,unknown2=[];for(let i=0;i<tokens.length;i++){let tok=tokens[i],name,inlineVal;if(tok.startsWith("--")){name=tok.slice(2);let eq2=name.indexOf("=");eq2!==-1&&(inlineVal=name.slice(eq2+1),name=name.slice(0,eq2))}else if(tok.length===2&&tok.startsWith("-")&&shortAliases[tok])name=shortAliases[tok];else continue;let negated=!1;if(name.startsWith("no-")&&(negated=!0,name=name.slice(3)),!knownNames.has(name)){unknown2.push(`--${name}`);continue}if(booleanNames.has(name)){bools.set(name,!negated);continue}let val2=inlineVal;if(val2===void 0){let next2=tokens[i+1];if(next2===void 0||next2.startsWith("-")){unknown2.push(`--${name} (missing value)`);continue}val2=next2,i++}let arr=values.get(name);arr?arr.push(val2):values.set(name,[val2])}return{values,bools,unknown:unknown2}}__name(tokenizeFlags,"tokenizeFlags");function buildOptions(flags,values,bools){let options={},missing=[];for(let flag2 of flags){if(flag2.type==="boolean"){bools.has(flag2.name)?options[flag2.key]=bools.get(flag2.name):flag2.required&&missing.push(`--${flag2.name}`);continue}let vals=values.get(flag2.name);if(!vals||vals.length===0){flag2.required&&missing.push(`--${flag2.name}`);continue}options[flag2.key]=flag2.isArray?vals.map(v=>coerceScalar(flag2.type,v)):coerceScalar(flag2.type,vals[vals.length-1])}return{options,missing}}__name(buildOptions,"buildOptions");init_auth_errors();var UNIVERSAL_NAMES=new Set(["name","parent","cwd","json","dry-run","help"]),UNIVERSAL_BOOLEANS=new Set(["json","dry-run","help"]),SHORT_ALIASES={"-C":"cwd","-h":"help"};function cwdFromTokens(tokens){for(let index2=0;index2<tokens.length;index2++){let token=tokens[index2];if(token.startsWith("--cwd="))return token.slice(6);if((token==="--cwd"||token==="-C")&&tokens[index2+1])return tokens[index2+1]}}__name(cwdFromTokens,"cwdFromTokens");function parseGenerationFlags({commandName:commandName2,subject,helpCommand,flags,tokens}){let knownNames=new Set([...flags.map(flag2=>flag2.name),...UNIVERSAL_NAMES]),booleanNames=new Set([...flags.filter(flag2=>flag2.type==="boolean").map(flag2=>flag2.name),...UNIVERSAL_BOOLEANS]),{values,bools,unknown:unknown2}=tokenizeFlags(tokens,knownNames,booleanNames,SHORT_ALIASES);unknown2.length>0&&(ui.error({command:commandName2,code:"UNKNOWN_FLAGS",message:`Unknown flag(s) for ${subject}: ${unknown2.join(", ")}`,hint:`Run \`${helpCommand}\` to see valid flags.`}),process.exit(78));let{options,missing}=buildOptions(flags,values,bools);return missing.length>0&&(ui.error({command:commandName2,code:"MISSING_REQUIRED_FLAGS",message:`Missing required flag(s) for ${subject}: ${missing.join(", ")}`,hint:`Run \`${helpCommand}\` to see required flags.`}),process.exit(78)),{values,bools,options}}__name(parseGenerationFlags,"parseGenerationFlags");function renderGenerationHelp({usage,description,flags,footer}){let lines=[usage,` ${description}`,""];for(let flag2 of flags){let type=flag2.enumValues?.length?flag2.enumValues.join("|"):flag2.type,value=flag2.type==="boolean"?"":` <${type}>`,metadata=[flag2.required?"required":"optional",flag2.isArray?"repeatable":""].filter(Boolean).join(", ");lines.push(` --${flag2.name}${value} (${metadata})`)}return lines.push(""),lines.push(" --name <string> (optional asset name)"),lines.push(" --parent <id> (optional media-library folder)"),lines.push(" --dry-run (validate and estimate without generating)"),footer&&(lines.push(""),lines.push(footer)),lines.join(`
|
|
1280
1293
|
`)}__name(renderGenerationHelp,"renderGenerationHelp");async function submitGeneration({commandName:commandName2,ctx,api,body}){await requireOperation("assets.generate",{projectId:ctx.projectId,env:ctx.env});try{let result=await api.generate(ctx.projectId,body),asset=result.asset;ui.result({command:commandName2,data:result,render:__name(()=>`\u2713 Generated ${asset?.name??"(no name)"} \u2014 ${asset?.id??result.jobId}`,"render")})}catch(error){rethrowCliAuthError(error),ui.error({command:commandName2,code:"GENERATION_FAILED",message:error instanceof Error?error.message:"Generation failed"}),process.exit(1)}}__name(submitGeneration,"submitGeneration");function parseGenerateArgv(argv=process.argv.slice(2)){let gi=argv.indexOf("generate");if(gi===-1)return{tokens:[]};let rest=argv.slice(gi+1),namespacedModelIndex=rest.findIndex(token=>/^[a-z][a-z0-9-]*\/\S+$/i.test(token)),mi=namespacedModelIndex>=0?namespacedModelIndex:rest[0]&&!rest[0].startsWith("-")?0:-1;return mi===-1?{tokens:rest}:{model:rest[mi],tokens:[...rest.slice(0,mi),...rest.slice(mi+1)]}}__name(parseGenerateArgv,"parseGenerateArgv");function renderModelHelp(model){return renderGenerationHelp({usage:`fimo generate ${model.id} [flags]`,description:`${model.description.split(". ")[0]}.`,flags:model.flags,footer:`Full detail + examples: fimo models show ${model.id}`})}__name(renderModelHelp,"renderModelHelp");async function runGenerate(command){let{model,tokens}=parseGenerateArgv();if(!model){ui.info({command:"generate",message:"Usage: fimo generate fal/<endpoint-id> [--flag value ...]",hint:"Enable the Fal integration, then run `fimo models list`."});return}model.startsWith("fal/")||(ui.error({command:"generate",code:"BUILT_IN_MODEL_HIDDEN",message:"Direct generation is available only for models from the enabled Fal integration.",hint:'For images, run `fimo image generate --prompt "\u2026" --quality premium --aspect-ratio 1:1`; enable Fal only for direct `fal/...` catalog IDs.'}),process.exit(78));let wantsHelp=tokens.includes("--help")||tokens.includes("-h"),isJson=currentMode().format==="json",{ctx,api}=await bootstrapProjectCommand({cwd:cwdFromTokens(tokens)},command,{quiet:isJson}),dto=await api.getModel(ctx.projectId,model);if(dto||(ui.error({command:"generate",code:"UNKNOWN_MODEL",message:`Unknown model: "${model}".`,hint:"Run `fimo models list` to see available models."}),process.exit(78)),wantsHelp){ui.result({command:"generate",data:{model:dto},render:__name(()=>renderModelHelp(dto),"render")});return}let{values,bools,options}=parseGenerationFlags({commandName:"generate",subject:dto.id,helpCommand:`fimo models show ${dto.id}`,flags:dto.flags,tokens}),universal={name:values.get("name")?.[0],parent:values.get("parent")?.[0]??null,cwd:values.get("cwd")?.[0],dryRun:bools.get("dry-run")??!1},body={model:dto.id,options,name:universal.name,parentId:universal.parent};if(universal.dryRun){let estimate=await api.estimateModel(ctx.projectId,dto.id,options);ui.result({command:"generate",data:{...body,estimate},render:__name(()=>JSON.stringify({...body,estimate},null,2),"render")});return}await submitGeneration({commandName:"generate",ctx,api,body})}__name(runGenerate,"runGenerate");function registerGenerate(program2){let command=new Command("generate").description("Generate media through an enabled Fal integration endpoint").argument("[model]","Namespaced endpoint id from `fimo models list`").allowUnknownOption(!0).allowExcessArguments(!0).helpOption(!1).addHelpText("after","\nEnable Fal, then run `fimo models list` or `fimo models show <model>`.").action(async(_model,_opts,command2)=>{await runGenerate(command2)});program2.addCommand(command,{hidden:!0})}__name(registerGenerate,"registerGenerate");init_api();init_project_context();function parseCredentialInput(raw){let out={};for(let line of raw.split(`
|
|
1281
1294
|
`)){if(line==="")break;let eq2=line.indexOf("=");eq2>0&&(out[line.slice(0,eq2)]=line.slice(eq2+1))}return out}__name(parseCredentialInput,"parseCredentialInput");function buildCredentialOutput(input,cred){if(input.protocol!=="https"||input.host!==cred.host||input.path&&input.path.replace(/^\//,"").replace(/\.git$/,"")!==cred.repo)return null;let out=`protocol=https
|
|
@@ -1284,14 +1297,14 @@ username=${cred.username}
|
|
|
1284
1297
|
password=${cred.token}
|
|
1285
1298
|
`;return cred.expiresAt&&(out+=`password_expiry_utc=${Math.floor(cred.expiresAt/1e3)}
|
|
1286
1299
|
`),out}__name(buildCredentialOutput,"buildCredentialOutput");async function readStdin(){if(process.stdin.isTTY)return"";let chunks=[];for await(let chunk of process.stdin)chunks.push(chunk);return Buffer.concat(chunks).toString("utf8")}__name(readStdin,"readStdin");async function gitCredentialCommand(operation){if(operation!=="get")return;let input=parseCredentialInput(await readStdin());if(input.protocol!=="https")return;let ctx;try{ctx=await getProjectContext()}catch{return}let cred;try{cred=await new FimoApiClient().getGitCredential(ctx.projectId,ctx.env)}catch(err){process.stderr.write(`fimo: could not obtain git credentials \u2014 ${err instanceof Error?err.message:String(err)}
|
|
1287
|
-
`);return}let out=buildCredentialOutput(input,cred);out&&process.stdout.write(out)}__name(gitCredentialCommand,"gitCredentialCommand");init_dist5();init_esm();init_dist();init_api();init_config();init_interactive();init_project_context();function
|
|
1300
|
+
`);return}let out=buildCredentialOutput(input,cred);out&&process.stdout.write(out)}__name(gitCredentialCommand,"gitCredentialCommand");init_dist5();init_esm();init_dist();init_api();init_config();init_interactive();init_project_context();function addScopeOptions2(command){return command.option("--project <id>","Project id (defaults to the linked project)").option("-C, --cwd <dir>","Project directory")}__name(addScopeOptions2,"addScopeOptions");function registerHistoryCommands(program2){let history=program2.command("history").description("Create, inspect, and restore project history").addHelpText("after",`
|
|
1288
1301
|
Examples:
|
|
1289
1302
|
fimo history list
|
|
1290
1303
|
fimo history list --limit 20 --cursor <cursor>
|
|
1291
1304
|
fimo history show <version-id>
|
|
1292
1305
|
fimo history create "Before content migration"
|
|
1293
1306
|
fimo history restore <version-id> --yes
|
|
1294
|
-
`);
|
|
1307
|
+
`);addScopeOptions2(history.command("list").description("List restore points for the current environment").option("--limit <count>","Maximum restore points to return (1-100)","20").option("--cursor <cursor>","Opaque cursor returned by the previous page")).action((options,command)=>historyListCommand(options,command)),addScopeOptions2(history.command("show <versionId>").description("Show one restore point")).action((versionId,options,command)=>historyShowCommand(versionId,options,command)),addScopeOptions2(history.command("create <name>").description("Save the current code and content as a restore point").option("--description <text>","Optional description")).action((name,options,command)=>historyCreateCommand(name,options,command)),addScopeOptions2(history.command("restore <versionId>").description("Restore code and content from a restore point").option("-y, --yes","Skip the confirmation prompt")).action((versionId,options,command)=>historyRestoreCommand(versionId,options,command))}__name(registerHistoryCommands,"registerHistoryCommands");async function resolveScope(options,command){let envOverride2=envOverrideFromCommand(command),baseApi=new FimoApiClient(loadConfig());if(options.project){let env=envOverride2??DEFAULT_ENV;if(!isValidEnv(env))throw new Error(`Invalid environment '${env}'.`);return{api:baseApi.withEnv(env),projectId:options.project,env}}let context=await getProjectContext({cwd:options.cwd,envOverride:envOverride2,api:baseApi});return{api:baseApi.withEnv(context.env),projectId:context.projectId,env:context.env}}__name(resolveScope,"resolveScope");function parseLimit(value){let limit=Number(value??20);if(!Number.isInteger(limit)||limit<1||limit>100)throw new Error("--limit must be an integer between 1 and 100.");return limit}__name(parseLimit,"parseLimit");async function runHistoryCommand(command,operation){try{await operation()}catch(error){if(error instanceof ApiRequestError){ui.error({command,code:error.code??"HISTORY_REQUEST_FAILED",message:error.detail,...error.code==="HISTORY_BUSY"?{hint:"Retry after the current history operation finishes."}:error.code==="RESTORE_INCOMPLETE"?{hint:"Retry the restore after checking that active editors have stopped writing."}:{}});return}throw error}}__name(runHistoryCommand,"runHistoryCommand");async function historyListCommand(options,command){await runHistoryCommand("history list",async()=>{let scope=await resolveScope(options,command);await requireOperation("fimo.history.list",{projectId:scope.projectId,env:scope.env});let limit=parseLimit(options.limit),[page,summary2]=await Promise.all([scope.api.listProjectVersions(scope.projectId,{limit,cursor:options.cursor}),scope.api.getProjectHistorySummary(scope.projectId)]),result={...page,...summary2},hint=page.nextCursor?buildHistoryListHint(page.nextCursor,scope.env,limit,options):void 0;ui.result({command:"history list",data:result,render:__name(()=>renderHistoryList(result,scope.env),"render"),...hint?{hint}:{}})})}__name(historyListCommand,"historyListCommand");function buildHistoryListHint(nextCursor,env,limit,options){let args=["fimo","history","list","--branch",env,"--limit",String(limit),"--cursor",nextCursor];return options.project&&args.push("--project",options.project),options.cwd&&args.push("--cwd",options.cwd),`More: ${args.map(formatCommandArgument).join(" ")}`}__name(buildHistoryListHint,"buildHistoryListHint");function formatCommandArgument(value){return/^[A-Za-z0-9_./:@+-]+$/.test(value)?value:`'${value.replaceAll("'",`'"'"'`)}'`}__name(formatCommandArgument,"formatCommandArgument");async function historyShowCommand(versionId,options,command){await runHistoryCommand("history show",async()=>{let scope=await resolveScope(options,command);await requireOperation("fimo.history.get",{projectId:scope.projectId,env:scope.env});let version=await scope.api.getProjectVersion(scope.projectId,versionId);ui.result({command:"history show",data:version,render:__name(()=>renderHistoryVersion(version,scope.env),"render")})})}__name(historyShowCommand,"historyShowCommand");async function historyCreateCommand(name,options,command){await runHistoryCommand("history create",async()=>{let scope=await resolveScope(options,command),version=await scope.api.createProjectVersion(scope.projectId,{name,description:options.description});ui.ok({command:"history create",headline:`Saved restore point "${version.name}".`,details:{version_id:version.versionId,env:scope.env,created_at:formatTimestamp(version.createdAt)}})})}__name(historyCreateCommand,"historyCreateCommand");async function historyRestoreCommand(versionId,options,command){await runHistoryCommand("history restore",async()=>{let scope=await resolveScope(options,command),version=await scope.api.getProjectVersion(scope.projectId,versionId);if(!options.yes){assertInteractive("Pass --yes to restore without a prompt.","history restore");let confirmed=await ot2({message:`Restore "${version.name}" on ${scope.env}? Current code and content will be saved as a safety point first.`,initialValue:!1});if(q(confirmed)||!confirmed){ui.info({command:"history restore",message:"Cancelled."});return}}let result=await scope.api.restoreProjectVersion(scope.projectId,versionId);ui.ok({command:"history restore",headline:`Restored "${version.name}" on ${scope.env}.`,details:{version_id:version.versionId,env:scope.env,duration_ms:result.durationMs??null},...result.warning?{warnings:[result.warning]}:{}})})}__name(historyRestoreCommand,"historyRestoreCommand");function renderHistoryList(result,env){let lines=[`History \xB7 ${env}`,""];if(result.items.length===0)lines.push("No restore points yet.");else{lines.push("ID CREATED KIND NAME");for(let version of result.items)lines.push(`${version.versionId.padEnd(36)} ${formatTimestamp(version.createdAt).padEnd(16)} ${version.kind.padEnd(15)} ${version.name}`)}return lines.push("",`Usage: ${result.usage.versionCount} restore points \xB7 ${formatBytes2(result.usage.snapshotBytes)} compressed`,`Retention: ${result.retentionDays} days`),lines.join(`
|
|
1295
1308
|
`)}__name(renderHistoryList,"renderHistoryList");function renderHistoryVersion(version,env){return[version.name,"",`Version ID: ${version.versionId}`,`Environment: ${env}`,`Kind: ${version.kind}`,`Created: ${formatTimestamp(version.createdAt)}`,`Commit: ${version.commitHash}`,`Description: ${version.description??"None"}`].join(`
|
|
1296
1309
|
`)}__name(renderHistoryVersion,"renderHistoryVersion");function formatTimestamp(value){let date=value instanceof Date?value:new Date(value);return Number.isNaN(date.getTime())?String(value):date.toISOString().slice(0,16).replace("T"," ")}__name(formatTimestamp,"formatTimestamp");function formatBytes2(bytes){return bytes<1024?`${bytes} B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)} KiB`:`${(bytes/(1024*1024)).toFixed(1)} MiB`}__name(formatBytes2,"formatBytes");init_init();init_dist5();import fs35 from"node:fs";import path35 from"node:path";init_dist();init_open();init_api();init_auth();init_config();init_interactive();init_project();function relativeAgentConfigPath(projectRoot,agentName){return path35.relative(projectRoot,path35.join(resolveProjectAgentsDir(projectRoot),agentName,"config.yaml")).replaceAll("\\","/")}__name(relativeAgentConfigPath,"relativeAgentConfigPath");function registerIntegrationsCommands(program2){let integrations=program2.command("integrations").description("Manage project integrations").addHelpText("after",`
|
|
1297
1310
|
Examples:
|
|
@@ -1313,7 +1326,7 @@ Examples:
|
|
|
1313
1326
|
fimo integrations run <provider> <tool> --input @request.json
|
|
1314
1327
|
|
|
1315
1328
|
Run \`fimo integrations <command> --help\` for command-specific help.
|
|
1316
|
-
`);integrations.command("list").description("List supported integrations and project setup status").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action(opts=>listCommand(opts)),integrations.command("info <integration>").description("Show integration tools, auth modes, and recipes").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((integration,opts)=>infoCommand(integration,opts)),integrations.command("status <integration>").description("Show project setup status for an integration").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((integration,opts)=>statusCommand(integration,opts)),integrations.command("connect <integration>").description("Connect an integration account, workspace, or API key to the active organization").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--org <organizationId>","Organization id (defaults to current project org or active organization)").option("--name <alias>","Connection name/alias").option("--token <value>","API token value (prefer --token-stdin in shells that record history)").option("--token-stdin","Read an API token from stdin").option("--no-open","Print the connect URL without opening a browser").action((integration,opts)=>connectCommand(integration,opts)),integrations.command("enable <integration>").description("Enable an integration for this project").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--auth <mode>","Override auth mode: fimo, api-key, or oauth").option("--connection <alias>","Enable with a named organization connection").action((integration,opts)=>enableCommand(integration,opts)),integrations.command("disable <integration>").description("Disable an integration for this project").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((integration,opts)=>disableCommand(integration,opts)),integrations.command("run <integration> <tool>").description("Run an enabled integration tool").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--connection <alias>","Use a named integration connection for this run only").option("--input <json|@file|->","Provider input as inline JSON, @file, or - for stdin").option("--url <url>","URL for Firecrawl scrape, map, or crawl").option("--query <query>","Query for Firecrawl search").option("--formats <formats>","Comma-separated output formats: markdown, summary, links, images, html, raw-html").option("--all-content","Allow Firecrawl to include non-main page content").option("--limit <count>","Maximum URLs/pages for Firecrawl map or crawl").option("--max-results <count>","Maximum search results for Firecrawl search").option("--sources <sources>","Comma-separated Firecrawl search sources: web, news, images").option("--categories <categories>","Comma-separated Firecrawl search categories: github, research, pdf").option("--include-domains <domains>","Only return Firecrawl search results from these comma-separated domains").option("--exclude-domains <domains>","Exclude these comma-separated domains from Firecrawl search results").option("--freshness <range>","Firecrawl search freshness: hour, day, week, month, or year").option("--location <location>","Firecrawl search location, such as Barcelona,Spain").option("--country <code>","Two-letter Firecrawl search country code").option("--no-highlights","Disable query-relevant Firecrawl search excerpts").option("--search <term>","Filter Firecrawl map results").option("--include-subdomains","Include subdomains in Firecrawl map results").option("--timeout-ms <ms>","Provider timeout in milliseconds").option("--wait-for-ms <ms>","Wait before scraping, in milliseconds").option("--name <name>","Name for Firecrawl monitor.create").option("--schedule <schedule>","Plain-language schedule for Firecrawl monitor.create, such as hourly").option("--timezone <timezone>","Timezone for Firecrawl monitor.create schedule").option("--goal <goal>","Plain-language goal for Firecrawl monitor.create").option("--emails <emails>","Comma-separated notification emails for Firecrawl monitor.create").option("--target <type>","Firecrawl monitor target type: scrape or crawl","scrape").option("--monitor-id <id>","Firecrawl monitor id for monitor lifecycle commands").option("--check-id <id>","Firecrawl monitor check id for monitor.check").option("--retention-days <days>","Retention days for Firecrawl monitor.create").option("--judge","Enable Firecrawl goal judging for monitor.create").action((integration,tool,opts)=>runCommand(integration,tool,opts)),integrations.command("auth").description("Choose the active auth mode for an enabled integration").command("use <integration> <mode>").description("Switch auth mode: fimo, api-key, or oauth").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((integration,mode2,opts)=>authUseCommand(integration,mode2,opts));let credentials=integrations.command("credentials").description("Manage hidden integration credentials");credentials.command("set <integration> [credential] [value]").description("Set a hidden credential for an integration").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--stdin","Read the credential value from stdin").option("--value <value>","Credential value (prefer --stdin in shells that record history)").action((integration,credential,value,opts)=>credentialsSetCommand(integration,credential,opts.value??value,opts)),credentials.command("clear <integration> [credential]").alias("unset").description("Clear a hidden credential for an integration").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((integration,credential,opts)=>credentialsClearCommand(integration,credential,opts))}__name(registerIntegrationsCommands,"registerIntegrationsCommands");async function listCommand(opts){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId3(opts);if(currentAgentSession()){await listAgentRuntimeCommand(api,projectId,opts);return}let rows=await api.listProjectIntegrations(projectId);ui.table({command:"integrations list",columns:[{key:"integration",label:"INTEGRATION"},{key:"status",label:"STATUS"},{key:"auth",label:"AUTH"},{key:"connection",label:"CONNECTION"},{key:"credentials",label:"CREDENTIALS"}],rows:rows.map(row2=>({integration:row2.integrationKey,status:row2.enabled?"enabled":row2.installed?"disabled":"available",auth:row2.authModeLabel??"",connection:row2.connectionAlias??"",credentials:credentialStatusLabel(row2.credentialStatus)}))})}__name(listCommand,"listCommand");async function listAgentRuntimeCommand(api,projectId,opts){let agentName=process.env.FIMO_AGENT_NAME?.trim();if(!agentName)throw new Error("Agent integration access cannot be listed because FIMO_AGENT_NAME is not set in this agent runtime.");let projectRoot=resolveProjectCwd(opts.cwd),bundle=await parseBundle(path35.join(resolveProjectAgentsDir(projectRoot),agentName)),policy=agentIntegrationPolicy(bundle.config),statuses=await api.listProjectIntegrations(projectId),statusByKey=new Map(statuses.map(status=>[status.integrationKey,status])),rows=[];for(let[integrationKey,entry]of Object.entries(policy).sort(([a],[b])=>a.localeCompare(b))){let status=statusByKey.get(integrationKey);if(!entry.enabled||!status?.enabled)continue;let info=await api.getProjectIntegrationInfo(projectId,integrationKey),knownTools=new Set(info.tools.map(tool=>tool.key)),availableTools=enabledAgentIntegrationTools(entry,[...knownTools]).filter(tool=>knownTools.has(tool));availableTools.length!==0&&rows.push({integration:integrationKey,project:"enabled",auth:status.authModeLabel??"",agent:"enabled",tools:availableTools.join(", ")})}let data2={agentName,configuredBy:relativeAgentConfigPath(projectRoot,agentName),rows};ui.result({command:"integrations list",data:data2,render:__name(()=>renderAgentRuntimeIntegrationList(data2),"render")})}__name(listAgentRuntimeCommand,"listAgentRuntimeCommand");async function infoCommand(integration,opts){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId3(opts),info=await api.getProjectIntegrationInfo(projectId,integration);ui.result({command:"integrations info",data:info,render:__name(()=>renderInfo(info),"render")})}__name(infoCommand,"infoCommand");async function statusCommand(integration,opts){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId3(opts),status=await api.getProjectIntegrationStatus(projectId,integration);ui.result({command:"integrations status",data:status,render:__name(()=>renderStatus(status),"render")})}__name(statusCommand,"statusCommand");async function enableCommand(integration,opts){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId3(opts),authMode=opts.auth?parseAuthMode(opts.auth):void 0,installation=await api.enableProjectIntegration({projectId,integrationKey:integration,authMode,connectionAlias:opts.connection});emitInstallationOk("integrations enable",`Enabled ${installation.integrationKey}`,installation)}__name(enableCommand,"enableCommand");async function connectCommand(integration,opts){let api=new FimoApiClient(loadConfig()),organizationId=resolveOrganizationId(opts);if(integration.toLowerCase()==="slack"){let connect=await api.startOrganizationIntegrationConnect({organizationId,integrationKey:integration});opts.open!==!1&&await open_default(connect.connectUrl),ui.ok({command:"integrations connect",headline:opts.open===!1?`Connect ${connect.integrationKey}`:`Opening ${connect.integrationKey} connect`,details:{organization_id:organizationId,integration:connect.integrationKey,connect_url:connect.connectUrl,expires_at:connect.expiresAt}});return}let token=await resolveConnectionToken(opts),connection=await api.connectOrganizationIntegrationWithToken({organizationId,integrationKey:integration,alias:opts.name,token});ui.ok({command:"integrations connect",headline:`Connected ${connection.integrationKey}`,details:{organization_id:organizationId,integration:connection.integrationKey,connection:connection.alias,auth:authKindCliLabel(connection.authKind),status:connection.status}})}__name(connectCommand,"connectCommand");async function disableCommand(integration,opts){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId3(opts);await api.disableProjectIntegration(projectId,integration),ui.ok({command:"integrations disable",headline:`Disabled ${integration}`,details:{project_id:projectId,integration}})}__name(disableCommand,"disableCommand");async function runCommand(integration,tool,opts){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId3(opts),request=await buildRunRequest(integration,tool,opts);await requireAgentIntegrationTool(integration,request.tool,opts);let run=await api.runProjectIntegrationTool({projectId,integrationKey:integration,request});ui.result({command:"integrations run",data:run,render:__name(()=>renderToolRun(run),"render")})}__name(runCommand,"runCommand");async function requireAgentIntegrationTool(integration,tool,opts){if(!currentAgentSession())return;let agentName=process.env.FIMO_AGENT_NAME?.trim();if(!agentName)throw new Error("Agent integration policy cannot be checked because FIMO_AGENT_NAME is not set in this agent runtime.");let projectRoot=resolveProjectCwd(opts.cwd),bundle=await parseBundle(path35.join(resolveProjectAgentsDir(projectRoot),agentName)),policy=agentIntegrationPolicy(bundle.config),integrationKey=integration.toLowerCase(),toolKey=tool.toLowerCase();if(!agentAllowsIntegrationTool(policy,integrationKey,toolKey))throw new Error(`Agent '${agentName}' is not allowed to run ${integrationKey}.${toolKey}. Set integrations.${integrationKey}.enabled: true in ${relativeAgentConfigPath(projectRoot,agentName)}, or add ${toolKey}: true under its tools map to use a narrower allowlist.`)}__name(requireAgentIntegrationTool,"requireAgentIntegrationTool");async function authUseCommand(integration,mode2,opts){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId3(opts),authMode=parseAuthMode(mode2),installation=await api.switchProjectIntegrationAuth({projectId,integrationKey:integration,authMode});emitInstallationOk("integrations auth use",`Using ${installation.authModeLabel} for ${installation.integrationKey}`,installation)}__name(authUseCommand,"authUseCommand");async function credentialsSetCommand(integration,credential,valueArg,opts){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId3(opts),credentialId=credential??"api_key",value=opts.stdin||valueArg===void 0?await readStdinValue():valueArg,installation=await api.setProjectIntegrationCredential({projectId,integrationKey:integration,credentialId,value});emitInstallationOk("integrations credentials set",`Stored credential ${credentialId} for ${installation.integrationKey}`,installation)}__name(credentialsSetCommand,"credentialsSetCommand");async function credentialsClearCommand(integration,credential,opts){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId3(opts),credentialId=credential??"api_key",installation=await api.clearProjectIntegrationCredential({projectId,integrationKey:integration,credentialId});emitInstallationOk("integrations credentials clear",`Cleared credential ${credentialId} for ${installation.integrationKey}`,installation)}__name(credentialsClearCommand,"credentialsClearCommand");function emitInstallationOk(command,headline,installation){ui.ok({command,headline,details:{project_id:installation.projectId,integration:installation.integrationKey,enabled:installation.enabled,auth_mode:installation.authMode,auth:installation.authModeLabel,connection:installation.connectionAlias,credential_status:installation.credentialStatus,configured_credentials:installation.configuredCredentials}})}__name(emitInstallationOk,"emitInstallationOk");function renderInfo(info){let lines=[];lines.push(`${info.name}`),lines.push(info.summary),lines.push(""),lines.push("Auth");for(let mode2 of info.authModes)lines.push(` ${mode2.mode.padEnd(8)} ${mode2.label} - ${mode2.description}`);if(info.credentials.length>0){lines.push(""),lines.push("Credentials");for(let credential of info.credentials)lines.push(` ${credential.id.padEnd(12)} ${credential.label}`)}if(info.tools.length>0){lines.push(""),lines.push("Tools");for(let tool of info.tools)lines.push(` ${tool.key.padEnd(18)} ${tool.effect.padEnd(9)} ${tool.description}`)}if(info.recipes.length>0){lines.push(""),lines.push("Recipes");for(let recipe of info.recipes)lines.push(` ${recipe.title}`),lines.push(` ${recipe.description}`),recipe.command&&lines.push(` ${recipe.command}`)}return lines.join(`
|
|
1329
|
+
`);integrations.command("list").description("List supported integrations and project setup status").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action(opts=>listCommand2(opts)),integrations.command("info <integration>").description("Show integration tools, auth modes, and recipes").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((integration,opts)=>infoCommand(integration,opts)),integrations.command("status <integration>").description("Show project setup status for an integration").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((integration,opts)=>statusCommand(integration,opts)),integrations.command("connect <integration>").description("Connect an integration account, workspace, or API key to the active organization").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--org <organizationId>","Organization id (defaults to current project org or active organization)").option("--name <alias>","Connection name/alias").option("--token <value>","API token value (prefer --token-stdin in shells that record history)").option("--token-stdin","Read an API token from stdin").option("--no-open","Print the connect URL without opening a browser").action((integration,opts)=>connectCommand(integration,opts)),integrations.command("enable <integration>").description("Enable an integration for this project").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--auth <mode>","Override auth mode: fimo, api-key, or oauth").option("--connection <alias>","Enable with a named organization connection").action((integration,opts)=>enableCommand(integration,opts)),integrations.command("disable <integration>").description("Disable an integration for this project").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((integration,opts)=>disableCommand(integration,opts)),integrations.command("run <integration> <tool>").description("Run an enabled integration tool").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--connection <alias>","Use a named integration connection for this run only").option("--input <json|@file|->","Provider input as inline JSON, @file, or - for stdin").option("--url <url>","URL for Firecrawl scrape, map, or crawl").option("--query <query>","Query for Firecrawl search").option("--formats <formats>","Comma-separated output formats: markdown, summary, links, images, html, raw-html").option("--all-content","Allow Firecrawl to include non-main page content").option("--limit <count>","Maximum URLs/pages for Firecrawl map or crawl").option("--max-results <count>","Maximum search results for Firecrawl search").option("--sources <sources>","Comma-separated Firecrawl search sources: web, news, images").option("--categories <categories>","Comma-separated Firecrawl search categories: github, research, pdf").option("--include-domains <domains>","Only return Firecrawl search results from these comma-separated domains").option("--exclude-domains <domains>","Exclude these comma-separated domains from Firecrawl search results").option("--freshness <range>","Firecrawl search freshness: hour, day, week, month, or year").option("--location <location>","Firecrawl search location, such as Barcelona,Spain").option("--country <code>","Two-letter Firecrawl search country code").option("--no-highlights","Disable query-relevant Firecrawl search excerpts").option("--search <term>","Filter Firecrawl map results").option("--include-subdomains","Include subdomains in Firecrawl map results").option("--timeout-ms <ms>","Provider timeout in milliseconds").option("--wait-for-ms <ms>","Wait before scraping, in milliseconds").option("--name <name>","Name for Firecrawl monitor.create").option("--schedule <schedule>","Plain-language schedule for Firecrawl monitor.create, such as hourly").option("--timezone <timezone>","Timezone for Firecrawl monitor.create schedule").option("--goal <goal>","Plain-language goal for Firecrawl monitor.create").option("--emails <emails>","Comma-separated notification emails for Firecrawl monitor.create").option("--target <type>","Firecrawl monitor target type: scrape or crawl","scrape").option("--monitor-id <id>","Firecrawl monitor id for monitor lifecycle commands").option("--check-id <id>","Firecrawl monitor check id for monitor.check").option("--retention-days <days>","Retention days for Firecrawl monitor.create").option("--judge","Enable Firecrawl goal judging for monitor.create").action((integration,tool,opts)=>runCommand(integration,tool,opts)),integrations.command("auth").description("Choose the active auth mode for an enabled integration").command("use <integration> <mode>").description("Switch auth mode: fimo, api-key, or oauth").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((integration,mode2,opts)=>authUseCommand(integration,mode2,opts));let credentials=integrations.command("credentials").description("Manage hidden integration credentials");credentials.command("set <integration> [credential] [value]").description("Set a hidden credential for an integration").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--stdin","Read the credential value from stdin").option("--value <value>","Credential value (prefer --stdin in shells that record history)").action((integration,credential,value,opts)=>credentialsSetCommand(integration,credential,opts.value??value,opts)),credentials.command("clear <integration> [credential]").alias("unset").description("Clear a hidden credential for an integration").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((integration,credential,opts)=>credentialsClearCommand(integration,credential,opts))}__name(registerIntegrationsCommands,"registerIntegrationsCommands");async function listCommand2(opts){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId4(opts);if(currentAgentSession()){await listAgentRuntimeCommand(api,projectId,opts);return}let rows=await api.listProjectIntegrations(projectId);ui.table({command:"integrations list",columns:[{key:"integration",label:"INTEGRATION"},{key:"status",label:"STATUS"},{key:"auth",label:"AUTH"},{key:"connection",label:"CONNECTION"},{key:"credentials",label:"CREDENTIALS"}],rows:rows.map(row2=>({integration:row2.integrationKey,status:row2.enabled?"enabled":row2.installed?"disabled":"available",auth:row2.authModeLabel??"",connection:row2.connectionAlias??"",credentials:credentialStatusLabel(row2.credentialStatus)}))})}__name(listCommand2,"listCommand");async function listAgentRuntimeCommand(api,projectId,opts){let agentName=process.env.FIMO_AGENT_NAME?.trim();if(!agentName)throw new Error("Agent integration access cannot be listed because FIMO_AGENT_NAME is not set in this agent runtime.");let projectRoot=resolveProjectCwd(opts.cwd),bundle=await parseBundle(path35.join(resolveProjectAgentsDir(projectRoot),agentName)),policy=agentIntegrationPolicy(bundle.config),statuses=await api.listProjectIntegrations(projectId),statusByKey=new Map(statuses.map(status=>[status.integrationKey,status])),rows=[];for(let[integrationKey,entry]of Object.entries(policy).sort(([a],[b])=>a.localeCompare(b))){let status=statusByKey.get(integrationKey);if(!entry.enabled||!status?.enabled)continue;let info=await api.getProjectIntegrationInfo(projectId,integrationKey),knownTools=new Set(info.tools.map(tool=>tool.key)),availableTools=enabledAgentIntegrationTools(entry,[...knownTools]).filter(tool=>knownTools.has(tool));availableTools.length!==0&&rows.push({integration:integrationKey,project:"enabled",auth:status.authModeLabel??"",agent:"enabled",tools:availableTools.join(", ")})}let data2={agentName,configuredBy:relativeAgentConfigPath(projectRoot,agentName),rows};ui.result({command:"integrations list",data:data2,render:__name(()=>renderAgentRuntimeIntegrationList(data2),"render")})}__name(listAgentRuntimeCommand,"listAgentRuntimeCommand");async function infoCommand(integration,opts){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId4(opts),info=await api.getProjectIntegrationInfo(projectId,integration);ui.result({command:"integrations info",data:info,render:__name(()=>renderInfo(info),"render")})}__name(infoCommand,"infoCommand");async function statusCommand(integration,opts){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId4(opts),status=await api.getProjectIntegrationStatus(projectId,integration);ui.result({command:"integrations status",data:status,render:__name(()=>renderStatus(status),"render")})}__name(statusCommand,"statusCommand");async function enableCommand(integration,opts){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId4(opts),authMode=opts.auth?parseAuthMode(opts.auth):void 0,installation=await api.enableProjectIntegration({projectId,integrationKey:integration,authMode,connectionAlias:opts.connection});emitInstallationOk("integrations enable",`Enabled ${installation.integrationKey}`,installation)}__name(enableCommand,"enableCommand");async function connectCommand(integration,opts){let api=new FimoApiClient(loadConfig()),organizationId=resolveOrganizationId(opts);if(integration.toLowerCase()==="slack"){let connect=await api.startOrganizationIntegrationConnect({organizationId,integrationKey:integration});opts.open!==!1&&await open_default(connect.connectUrl),ui.ok({command:"integrations connect",headline:opts.open===!1?`Connect ${connect.integrationKey}`:`Opening ${connect.integrationKey} connect`,details:{organization_id:organizationId,integration:connect.integrationKey,connect_url:connect.connectUrl,expires_at:connect.expiresAt}});return}let token=await resolveConnectionToken(opts),connection=await api.connectOrganizationIntegrationWithToken({organizationId,integrationKey:integration,alias:opts.name,token});ui.ok({command:"integrations connect",headline:`Connected ${connection.integrationKey}`,details:{organization_id:organizationId,integration:connection.integrationKey,connection:connection.alias,auth:authKindCliLabel(connection.authKind),status:connection.status}})}__name(connectCommand,"connectCommand");async function disableCommand(integration,opts){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId4(opts);await api.disableProjectIntegration(projectId,integration),ui.ok({command:"integrations disable",headline:`Disabled ${integration}`,details:{project_id:projectId,integration}})}__name(disableCommand,"disableCommand");async function runCommand(integration,tool,opts){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId4(opts),request=await buildRunRequest(integration,tool,opts);await requireAgentIntegrationTool(integration,request.tool,opts);let run=await api.runProjectIntegrationTool({projectId,integrationKey:integration,request});ui.result({command:"integrations run",data:run,render:__name(()=>renderToolRun(run),"render")})}__name(runCommand,"runCommand");async function requireAgentIntegrationTool(integration,tool,opts){if(!currentAgentSession())return;let agentName=process.env.FIMO_AGENT_NAME?.trim();if(!agentName)throw new Error("Agent integration policy cannot be checked because FIMO_AGENT_NAME is not set in this agent runtime.");let projectRoot=resolveProjectCwd(opts.cwd),bundle=await parseBundle(path35.join(resolveProjectAgentsDir(projectRoot),agentName)),policy=agentIntegrationPolicy(bundle.config),integrationKey=integration.toLowerCase(),toolKey=tool.toLowerCase();if(!agentAllowsIntegrationTool(policy,integrationKey,toolKey))throw new Error(`Agent '${agentName}' is not allowed to run ${integrationKey}.${toolKey}. Set integrations.${integrationKey}.enabled: true in ${relativeAgentConfigPath(projectRoot,agentName)}, or add ${toolKey}: true under its tools map to use a narrower allowlist.`)}__name(requireAgentIntegrationTool,"requireAgentIntegrationTool");async function authUseCommand(integration,mode2,opts){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId4(opts),authMode=parseAuthMode(mode2),installation=await api.switchProjectIntegrationAuth({projectId,integrationKey:integration,authMode});emitInstallationOk("integrations auth use",`Using ${installation.authModeLabel} for ${installation.integrationKey}`,installation)}__name(authUseCommand,"authUseCommand");async function credentialsSetCommand(integration,credential,valueArg,opts){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId4(opts),credentialId=credential??"api_key",value=opts.stdin||valueArg===void 0?await readStdinValue():valueArg,installation=await api.setProjectIntegrationCredential({projectId,integrationKey:integration,credentialId,value});emitInstallationOk("integrations credentials set",`Stored credential ${credentialId} for ${installation.integrationKey}`,installation)}__name(credentialsSetCommand,"credentialsSetCommand");async function credentialsClearCommand(integration,credential,opts){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId4(opts),credentialId=credential??"api_key",installation=await api.clearProjectIntegrationCredential({projectId,integrationKey:integration,credentialId});emitInstallationOk("integrations credentials clear",`Cleared credential ${credentialId} for ${installation.integrationKey}`,installation)}__name(credentialsClearCommand,"credentialsClearCommand");function emitInstallationOk(command,headline,installation){ui.ok({command,headline,details:{project_id:installation.projectId,integration:installation.integrationKey,enabled:installation.enabled,auth_mode:installation.authMode,auth:installation.authModeLabel,connection:installation.connectionAlias,credential_status:installation.credentialStatus,configured_credentials:installation.configuredCredentials}})}__name(emitInstallationOk,"emitInstallationOk");function renderInfo(info){let lines=[];lines.push(`${info.name}`),lines.push(info.summary),lines.push(""),lines.push("Auth");for(let mode2 of info.authModes)lines.push(` ${mode2.mode.padEnd(8)} ${mode2.label} - ${mode2.description}`);if(info.credentials.length>0){lines.push(""),lines.push("Credentials");for(let credential of info.credentials)lines.push(` ${credential.id.padEnd(12)} ${credential.label}`)}if(info.tools.length>0){lines.push(""),lines.push("Tools");for(let tool of info.tools)lines.push(` ${tool.key.padEnd(18)} ${tool.effect.padEnd(9)} ${tool.description}`)}if(info.recipes.length>0){lines.push(""),lines.push("Recipes");for(let recipe of info.recipes)lines.push(` ${recipe.title}`),lines.push(` ${recipe.description}`),recipe.command&&lines.push(` ${recipe.command}`)}return lines.join(`
|
|
1317
1330
|
`)}__name(renderInfo,"renderInfo");function renderStatus(status){return[status.integrationKey,`Status: ${status.enabled?"enabled":status.installed?"disabled":"not enabled"}`,`Auth: ${status.authModeLabel??"not selected"}`,`Connection: ${status.connectionAlias??"none"}`,`Credentials: ${credentialStatusLabel(status.credentialStatus)}`,status.configuredCredentials.length>0?`Configured credentials: ${status.configuredCredentials.join(", ")}`:"Configured credentials: none"].join(`
|
|
1318
1331
|
`)}__name(renderStatus,"renderStatus");function renderAgentRuntimeIntegrationList(data2){let lines=["Integrations available to this agent runtime.",`Configured by: ${data2.configuredBy}`,"Use `fimo integrations info <integration>` for details and `fimo integrations run <integration> <tool> ...` to run a tool.",""];return data2.rows.length===0?(lines.push("No integrations are available to this agent runtime."),lines.join(`
|
|
1319
1332
|
`)):(lines.push(formatPlainTable([["INTEGRATION","PROJECT","AUTH","AGENT","TOOLS"],...data2.rows.map(row2=>[row2.integration,row2.project,row2.auth,row2.agent,row2.tools])])),lines.join(`
|
|
@@ -1330,16 +1343,16 @@ Run \`fimo integrations <command> --help\` for command-specific help.
|
|
|
1330
1343
|
`)}let output=run.output;return pushMonitorSummary(lines,output.monitor),lines.join(`
|
|
1331
1344
|
`)}__name(renderMonitorToolRun,"renderMonitorToolRun");function pushMonitorSummary(lines,monitor){if(lines.push(""),lines.push(monitor.name),lines.push(`ID: ${monitor.id}`),monitor.status&&lines.push(`Status: ${monitor.status}`),monitor.schedule){let schedule=monitor.schedule.text??monitor.schedule.cron;schedule&&lines.push(`Schedule: ${schedule}${monitor.schedule.timezone?` (${monitor.schedule.timezone})`:""}`)}monitor.nextRunAt&&lines.push(`Next run: ${monitor.nextRunAt}`),typeof monitor.estimatedCreditsPerMonth=="number"&&lines.push(`Estimated Firecrawl credits/month: ${monitor.estimatedCreditsPerMonth}`)}__name(pushMonitorSummary,"pushMonitorSummary");function formatMonitorCheckSummary(summary2){return Object.entries(summary2).filter(([,value])=>typeof value=="number").map(([key,value])=>`${key}=${value}`).join(", ")}__name(formatMonitorCheckSummary,"formatMonitorCheckSummary");function baseRunLines(run){let lines=[`${run.integrationKey} ${run.tool}`];return pushRunMetadata(lines,run),lines}__name(baseRunLines,"baseRunLines");function pushRunMetadata(lines,run){if(run.connectionAlias&&lines.push(`Connection: ${run.connectionAlias}`),run.billing&&lines.push(`Fimo credits: ${run.billing.credits}`),run.usage){let usage=[typeof run.usage.providerCredits=="number"?`${run.usage.providerCredits} ${run.usage.provider} credits`:null,typeof run.usage.requests=="number"?`${run.usage.requests} request`:null].filter(value=>!!value);usage.length>0&&lines.push(`Provider usage: ${usage.join(", ")}`)}}__name(pushRunMetadata,"pushRunMetadata");function credentialStatusLabel(status){return status==="not_required"?"not required":status}__name(credentialStatusLabel,"credentialStatusLabel");function parseAuthMode(value){if(value==="api-key"||value==="token")return"personal";if(value==="fimo"||value==="personal"||value==="oauth")return value;throw new Error(`Unknown auth mode '${value}'. Use 'fimo', 'api-key', or 'oauth'.`)}__name(parseAuthMode,"parseAuthMode");function authKindCliLabel(kind){return kind.replace("_","-")}__name(authKindCliLabel,"authKindCliLabel");async function buildRunRequest(integration,tool,opts){if(opts.input!==void 0)return withRunConnection({tool,input:await readToolInput(opts.input,opts)},opts);if(integration.toLowerCase()!=="firecrawl")throw new Error(`Pass --input <json|@file|-> for ${integration}.${tool}. Provider-specific convenience flags are currently available for Firecrawl only.`);return buildFirecrawlRunRequest(tool,opts)}__name(buildRunRequest,"buildRunRequest");function buildFirecrawlRunRequest(tool,opts){let withConnection=__name(request=>withRunConnection(request,opts),"withConnection");switch(tool){case"search":if(!opts.query)throw new Error("Pass --query to search the web.");if(opts.includeDomains&&opts.excludeDomains)throw new Error("Choose --include-domains or --exclude-domains, not both.");return withConnection({tool:"search",input:{query:opts.query,maxResults:parseOptionalInt(opts.maxResults,"--max-results",1),sources:parseOptionalChoiceList(opts.sources,"--sources",["web","news","images"]),categories:parseOptionalChoiceList(opts.categories,"--categories",["github","research","pdf"]),includeDomains:opts.includeDomains?parseCsvList(opts.includeDomains):void 0,excludeDomains:opts.excludeDomains?parseCsvList(opts.excludeDomains):void 0,timeRange:parseFirecrawlFreshness(opts.freshness),location:opts.location,country:parseCountryCode(opts.country),highlights:opts.highlights,timeoutMs:parseOptionalInt(opts.timeoutMs,"--timeout-ms",1)}});case"scrape":if(!opts.url)throw new Error("Pass --url to scrape a page.");return withConnection({tool:"scrape",input:{url:opts.url,formats:parseFirecrawlFormats(opts.formats),onlyMainContent:opts.allContent?!1:void 0,timeoutMs:parseOptionalInt(opts.timeoutMs,"--timeout-ms",1),waitForMs:parseOptionalInt(opts.waitForMs,"--wait-for-ms",0)}});case"map":if(!opts.url)throw new Error("Pass --url to map a site.");return withConnection({tool:"map",input:{url:opts.url,search:opts.search,limit:parseOptionalInt(opts.limit,"--limit",1),includeSubdomains:opts.includeSubdomains,timeoutMs:parseOptionalInt(opts.timeoutMs,"--timeout-ms",1)}});case"crawl":if(!opts.url)throw new Error("Pass --url to crawl a site.");return withConnection({tool:"crawl",input:{url:opts.url,limit:parseOptionalInt(opts.limit,"--limit",1),formats:parseFirecrawlFormats(opts.formats),onlyMainContent:opts.allContent?!1:void 0,timeoutMs:parseOptionalInt(opts.timeoutMs,"--timeout-ms",1)}});case"monitor.create":{if(!opts.name)throw new Error("Pass --name to create a Firecrawl monitor.");if(!opts.url)throw new Error("Pass --url to create a Firecrawl monitor.");if(!opts.schedule)throw new Error("Pass --schedule to create a Firecrawl monitor.");let retentionDays=parseOptionalInt(opts.retentionDays,"--retention-days",1);if(retentionDays!==void 0&&retentionDays>365)throw new Error("--retention-days must be less than or equal to 365.");return withConnection({tool:"monitor.create",input:{name:opts.name,schedule:{text:opts.schedule,...opts.timezone?{timezone:opts.timezone}:{}},targets:[{type:parseFirecrawlMonitorTarget(opts.target),urls:parseCsvList(opts.url),scrapeOptions:{formats:parseFirecrawlFormats(opts.formats),onlyMainContent:opts.allContent?!1:void 0,timeoutMs:parseOptionalInt(opts.timeoutMs,"--timeout-ms",1),waitForMs:parseOptionalInt(opts.waitForMs,"--wait-for-ms",0)}}],...opts.goal?{goal:opts.goal}:{},...opts.judge?{judgeEnabled:!0}:{},...retentionDays!==void 0?{retentionDays}:{},...opts.emails?{notification:{email:{enabled:!0,recipients:parseCsvList(opts.emails),includeDiffs:!0}}}:{}}})}case"monitor.list":return withConnection({tool:"monitor.list",input:{}});case"monitor.get":case"monitor.pause":case"monitor.resume":case"monitor.delete":case"monitor.run":case"monitor.checks":{if(!opts.monitorId)throw new Error(`Pass --monitor-id to run ${tool}.`);return withConnection({tool,input:{monitorId:opts.monitorId}})}case"monitor.check":{if(!opts.monitorId)throw new Error("Pass --monitor-id to run monitor.check.");if(!opts.checkId)throw new Error("Pass --check-id to run monitor.check.");return withConnection({tool:"monitor.check",input:{monitorId:opts.monitorId,checkId:opts.checkId}})}default:throw new Error(`Unknown integration tool '${tool}'. Firecrawl supports search, scrape, map, crawl, and monitor.* tools.`)}}__name(buildFirecrawlRunRequest,"buildFirecrawlRunRequest");function withRunConnection(request,opts){let connectionAlias=opts.connection?.trim();return connectionAlias?{...request,connectionAlias}:request}__name(withRunConnection,"withRunConnection");async function readToolInput(value,opts){let raw=value;if(value==="-"){if(process.stdin.isTTY)throw new Error("Pipe JSON input to the command when using --input -.");raw=await readStdinValue()}else if(value.startsWith("@")){let file=value.slice(1);if(!file)throw new Error("Pass a file path after @ in --input @file.");let filePath=path35.resolve(resolveProjectCwd(opts.cwd),file);try{raw=fs35.readFileSync(filePath,"utf8")}catch(error){throw new Error(error instanceof Error?error.message:`Could not read ${filePath}.`)}}let parsed;try{parsed=JSON.parse(raw)}catch(error){throw new Error(`Integration tool input must be valid JSON: ${error instanceof Error?error.message:"parse failed"}`)}if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new Error("Integration tool input must be a JSON object.");return parsed}__name(readToolInput,"readToolInput");function parseFirecrawlMonitorTarget(value){if(value===void 0||value==="scrape")return"scrape";if(value==="crawl")return"crawl";throw new Error("--target must be 'scrape' or 'crawl'.")}__name(parseFirecrawlMonitorTarget,"parseFirecrawlMonitorTarget");function parseCsvList(value){let parts=value.split(",").map(part=>part.trim()).filter(part=>part.length>0);if(parts.length===0)throw new Error("Expected at least one comma-separated value.");return parts}__name(parseCsvList,"parseCsvList");function parseOptionalChoiceList(value,option,choices){if(value===void 0)return;let values=parseCsvList(value).map(item=>item.toLowerCase());for(let item of values)if(!choices.includes(item))throw new Error(`${option} must contain only: ${choices.join(", ")}.`);return values}__name(parseOptionalChoiceList,"parseOptionalChoiceList");function parseFirecrawlFreshness(value){if(value!==void 0){if(value==="hour"||value==="day"||value==="week"||value==="month"||value==="year")return value;throw new Error("--freshness must be hour, day, week, month, or year.")}}__name(parseFirecrawlFreshness,"parseFirecrawlFreshness");function parseCountryCode(value){if(value!==void 0){if(!/^[A-Za-z]{2}$/.test(value))throw new Error("--country must be a two-letter country code.");return value.toUpperCase()}}__name(parseCountryCode,"parseCountryCode");function parseFirecrawlFormats(value){let result={},parts=(value??"markdown").split(",").map(part=>part.trim().toLowerCase()).filter(part=>part.length>0);for(let part of parts)switch(part){case"markdown":result.markdown=!0;break;case"summary":result.summary=!0;break;case"links":result.links=!0;break;case"images":result.images=!0;break;case"html":result.html="cleaned";break;case"raw-html":case"rawhtml":result.html="raw";break;default:throw new Error(`Unknown Firecrawl scrape format '${part}'. Use markdown, summary, links, images, html, or raw-html.`)}if(!Object.values(result).some(enabled=>!!enabled))throw new Error("Choose at least one Firecrawl scrape format.");return result}__name(parseFirecrawlFormats,"parseFirecrawlFormats");function parseOptionalInt(value,option,min){if(value===void 0)return;let parsed=Number(value);if(!Number.isInteger(parsed)||parsed<min)throw new Error(`${option} must be an integer greater than or equal to ${min}.`);return parsed}__name(parseOptionalInt,"parseOptionalInt");function trimContent(content2,maxLength){return content2.length<=maxLength?content2:`${content2.slice(0,maxLength).trimEnd()}
|
|
1332
1345
|
...`}__name(trimContent,"trimContent");function trimSearchExcerpt(content2,maxLength=1200){if(content2.length<=maxLength)return content2;let candidate=content2.slice(0,maxLength+1),sentenceEnd=[...candidate.matchAll(/[.!?](?=\s|$)/g)].at(-1)?.index,cutoff=sentenceEnd!==void 0&&sentenceEnd>=maxLength*.6?sentenceEnd+1:maxLength;return`${candidate.slice(0,cutoff).trimEnd()}
|
|
1333
|
-
...`}__name(trimSearchExcerpt,"trimSearchExcerpt");function
|
|
1346
|
+
...`}__name(trimSearchExcerpt,"trimSearchExcerpt");function resolveProjectId4(opts){if(opts.project)return opts.project;let cwd=resolveProjectCwd(opts.cwd);return loadProjectSettings(cwd).projectId}__name(resolveProjectId4,"resolveProjectId");function resolveOrganizationId(opts){if(opts.org)return opts.org;try{let cwd=resolveProjectCwd(opts.cwd),settings=loadProjectSettings(cwd);if(settings.organizationId)return settings.organizationId}catch{}let active=readCredentials()?.activeOrganization?.id;if(active)return active;throw new Error("No organization found. Run inside a Fimo project, pass --org <id>, or run `fimo switch`.")}__name(resolveOrganizationId,"resolveOrganizationId");async function resolveConnectionToken(opts){if(opts.token)return opts.token;if(opts.tokenStdin)return readStdinValue();assertInteractive("Pass --token-stdin or --token <value>.","integrations connect");let value=await bt({message:"Integration API token",validate:__name(input=>input?.trim().length?void 0:"token required","validate")});if(q(value))throw new Error("Cancelled.");return String(value)}__name(resolveConnectionToken,"resolveConnectionToken");async function readStdinValue(){if(process.stdin.isTTY)throw new Error("Pass a value or pipe one with --stdin.");let chunks=[];for await(let chunk of process.stdin)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));return Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/,"")}__name(readStdinValue,"readStdinValue");init_dist5();init_dist();init_api();init_auth();init_config();init_auth_errors();init_project();var EMAIL_RE=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,ORGANIZATION_ROLE_OPTIONS=[{value:"member",label:"Member",hint:"Can create projects and view members"},{value:"admin",label:"Admin",hint:"Can manage members, settings, and projects"},{value:"owner",label:"Owner",hint:"Full control over the organization"}],PROJECT_ROLE_OPTIONS=[{value:"view",label:"Can view",hint:"Read-only access to the project"},{value:"comment",label:"Can comment",hint:"Can view and leave comments"},{value:"edit",label:"Can edit",hint:"Can edit code, content, assets, and use AI chat"},{value:"full",label:"Full access",hint:"Can manage settings, sharing, and publishing"}];async function inviteCommand(options){let cfg=loadConfig();requireCredentials(cfg);let isPretty2=currentMode().format==="pretty";isPretty2&&mt("Invite a user to Fimo");let api=new FimoApiClient(cfg),target=await resolveInviteTarget(options.target);if(!target)return;if(target==="project"&&options.resend){ui.error({command:"invite",code:"RESEND_PROJECT_UNSUPPORTED",message:"`--resend` is only supported for organization invites."});return}let email=await resolveSingleEmail(options.email);if(!email)return;if(target==="organization"){let organization=await resolveOrganization2(api,options.org);if(!organization)return;let role2=await resolveOrganizationRole(options.role);if(!role2||(isPretty2&&wt(["Target: organization",`Organization: ${organization.name} (${organization.id})`,`Email: ${email}`,`Role: ${role2}`,options.resend?"Resend existing invite: yes":null].filter(Boolean).join(`
|
|
1334
1347
|
`),"Review invite"),!await confirmInvite(options.yes)))return;let sp2=spinner(options.resend?"Resending invitation":"Sending invitation");try{await api.inviteOrganizationMember({organizationId:organization.id,email,role:role2,resend:options.resend}),sp2.succeed(options.resend?"Invitation resent":"Invitation sent")}catch(error){throw rethrowCliAuthError(error,()=>sp2.fail("Authentication required")),sp2.fail(options.resend?"Failed to resend invitation":"Failed to send invitation"),error}ui.ok({command:"invite",headline:`${options.resend?"Resent":"Sent"} organization invite to ${email} for ${organization.name} as ${role2}.`,details:{target:"organization",organization_id:organization.id,organization_name:organization.name,email,role:role2,resent:options.resend===!0}});return}let project=await resolveProject2(api,options);if(!project)return;let role=await resolveProjectRole(options.role);if(!role||(isPretty2&&wt(["Target: project",`Project: ${formatProjectLabel(project)} (${project.id})`,`Email: ${email}`,`Access: ${role}`].join(`
|
|
1335
1348
|
`),"Review invite"),!await confirmInvite(options.yes)))return;let sp=spinner("Sending invitation");try{await api.inviteProjectUser({projectId:project.id,email,roleKey:role}),sp.succeed("Invitation sent")}catch(error){throw rethrowCliAuthError(error,()=>sp.fail("Authentication required")),sp.fail("Failed to send invitation"),error}ui.ok({command:"invite",headline:`Sent project invite to ${email} for ${formatProjectLabel(project)} as ${role}.`,details:{target:"project",project_id:project.id,project_name:project.name,email,role}})}__name(inviteCommand,"inviteCommand");async function resolveInviteTarget(targetArg){if(targetArg){let normalized=normalizeTarget(targetArg);return normalized||(ui.error({command:"invite",code:"INVALID_TARGET",message:`Unsupported target "${targetArg}".`,hint:'Use "organization" or "project".'}),null)}let selected=await _t({message:"Where do you want to invite this user?",initialValue:"project",options:[{value:"project",label:"Project",hint:"Invite someone to collaborate on a single project"},{value:"organization",label:"Organization",hint:"Invite someone to join the organization"}]});return q(selected)?(ui.info({command:"invite",message:"Cancelled."}),null):normalizeTarget(String(selected))}__name(resolveInviteTarget,"resolveInviteTarget");async function resolveSingleEmail(emailArg){let initialValue=emailArg?.trim();if(initialValue){let normalized=normalizeEmail(initialValue);return normalized||(ui.error({command:"invite",code:"INVALID_EMAIL",message:"Enter a single valid email address."}),null)}let email=await Ot({message:"Who do you want to invite?",placeholder:"jane@acme.com",validate:__name(value=>validateEmailInput(String(value??"")),"validate")});return q(email)?(ui.info({command:"invite",message:"Cancelled."}),null):normalizeEmail(String(email))}__name(resolveSingleEmail,"resolveSingleEmail");async function resolveOrganization2(api,explicitOrganizationId){if(explicitOrganizationId){let organization=(await api.listOrganizations()).find(org=>org.id===explicitOrganizationId);return organization||(ui.error({command:"invite",code:"ORGANIZATION_NOT_FOUND",message:`Organization ${explicitOrganizationId} was not found in your account.`}),null)}let creds=readCredentials(loadConfig());if(creds?.activeOrganization)return creds.activeOrganization;let orgs2=await api.listOrganizations();if(orgs2.length===0)return ui.error({command:"invite",code:"NO_ORGANIZATIONS",message:"No organization found for this account."}),null;if(orgs2.length===1)return orgs2[0];let selected=await _t({message:"Select an organization",options:orgs2.map(org=>({value:org.id,label:org.name,hint:org.slug}))});return q(selected)?(ui.info({command:"invite",message:"Cancelled."}),null):orgs2.find(org=>org.id===selected)??null}__name(resolveOrganization2,"resolveOrganization");async function resolveOrganizationRole(roleArg){if(roleArg){let normalized=normalizeOrganizationRole(roleArg);return normalized||(ui.error({command:"invite",code:"INVALID_ROLE",message:`Unsupported organization role "${roleArg}".`,hint:"Use member, admin, or owner."}),null)}let selected=await _t({message:"Select the organization role",initialValue:"member",options:ORGANIZATION_ROLE_OPTIONS});return q(selected)?(ui.info({command:"invite",message:"Cancelled."}),null):normalizeOrganizationRole(String(selected))}__name(resolveOrganizationRole,"resolveOrganizationRole");async function resolveProjectRole(roleArg){if(roleArg){let normalized=normalizeProjectRole(roleArg);return normalized||(ui.error({command:"invite",code:"INVALID_ROLE",message:`Unsupported project access "${roleArg}".`,hint:"Use view, comment, edit, or full."}),null)}let selected=await _t({message:"Select the project access level",initialValue:"edit",options:PROJECT_ROLE_OPTIONS});return q(selected)?(ui.info({command:"invite",message:"Cancelled."}),null):normalizeProjectRole(String(selected))}__name(resolveProjectRole,"resolveProjectRole");async function resolveProject2(api,options){if(options.project)return api.getProject(options.project);if(!options.org){let local=tryLoadLocalProject(options.cwd);if(local?.projectId)return api.getProject(local.projectId)}let organization=await resolveOrganization2(api,options.org);if(!organization)return null;let projects2=await api.listProjects(organization.id);if(projects2.length===0)return ui.error({command:"invite",code:"NO_PROJECTS_IN_ORGANIZATION",message:`No projects found in ${organization.name}.`}),null;if(projects2.length===1)return projects2[0];let selected=await _t({message:"Select a project",options:projects2.map(project=>({value:project.id,label:formatProjectLabel(project),hint:project.id}))});return q(selected)?(ui.info({command:"invite",message:"Cancelled."}),null):projects2.find(project=>project.id===selected)??null}__name(resolveProject2,"resolveProject");async function confirmInvite(skipPrompt){if(skipPrompt)return!0;let confirmed=await ot2({message:"Send this invitation now?",initialValue:!0});return q(confirmed)||!confirmed?(ui.info({command:"invite",message:"Cancelled."}),!1):!0}__name(confirmInvite,"confirmInvite");function tryLoadLocalProject(cwdOption){let cwd=resolveProjectCwd(cwdOption);try{return loadProjectSettings(cwd)}catch{return null}}__name(tryLoadLocalProject,"tryLoadLocalProject");function normalizeTarget(value){let normalized=value.trim().toLowerCase();return normalized==="organization"||normalized==="org"?"organization":normalized==="project"?"project":null}__name(normalizeTarget,"normalizeTarget");function normalizeOrganizationRole(value){let normalized=value.trim().toLowerCase();return ORGANIZATION_ROLE_OPTIONS.find(option=>option.value===normalized)?.value??null}__name(normalizeOrganizationRole,"normalizeOrganizationRole");function normalizeProjectRole(value){let normalized=value.trim().toLowerCase();return PROJECT_ROLE_OPTIONS.find(option=>option.value===normalized)?.value??null}__name(normalizeProjectRole,"normalizeProjectRole");function validateEmailInput(value){if(!normalizeEmail(value))return"Enter a single valid email address"}__name(validateEmailInput,"validateEmailInput");function normalizeEmail(value){let tokens=value.trim().split(/[,\s]+/).filter(Boolean);if(tokens.length!==1)return null;let[email]=tokens,normalized=email.toLowerCase();return EMAIL_RE.test(normalized)?normalized:null}__name(normalizeEmail,"normalizeEmail");function formatProjectLabel(project){return project.displayName?.trim()||project.name}__name(formatProjectLabel,"formatProjectLabel");init_dist();import fs36 from"node:fs";import path36 from"node:path";init_project_context();init_project();function renderPrettyJson7(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson7,"renderPrettyJson");function dbLabelsRuntimeWarnings(cwd){let warning=getDbLabelsRuntimeWarning(resolveProjectCwd(cwd));return warning?[warning]:void 0}__name(dbLabelsRuntimeWarnings,"dbLabelsRuntimeWarnings");function defaultLocaleForProject(cwd){return getConfigServer(resolveProjectCwd(cwd)).i18n?.defaultLocale??"en"}__name(defaultLocaleForProject,"defaultLocaleForProject");async function labelsListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("i18n.list",{projectId:ctx.projectId,env:ctx.env});let result=await api.listLabels(ctx.projectId,options.locale);ui.result({command:"labels list",data:result,render:__name(()=>renderPrettyJson7(result),"render")})}__name(labelsListCommand,"labelsListCommand");async function labelsSetCommand(key,valueArg,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("i18n.update",{projectId:ctx.projectId,env:ctx.env});let value=options.stdin?await readStdinValue2():options.value??valueArg??await readStdinValue2(),locale=options.locale??defaultLocaleForProject(options.cwd),result=await api.setLabel(ctx.projectId,{key,value,locale});ui.result({command:"labels set",data:result,render:__name(()=>`Set ${key} (${locale})`,"render"),warnings:dbLabelsRuntimeWarnings(options.cwd)})}__name(labelsSetCommand,"labelsSetCommand");async function labelsSetManyCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("i18n.update",{projectId:ctx.projectId,env:ctx.env});let fallbackLocale=options.locale??defaultLocaleForProject(options.cwd),records=readLabelRecords(options).map(({key,value,locale})=>({key,value,locale:locale??fallbackLocale})),locales=[...new Set(records.map(record2=>record2.locale))],result=await api.setLabels(ctx.projectId,records);ui.result({command:"labels set-many",data:{...result,locale:fallbackLocale,locales,labels:records.length},render:__name(()=>`Set ${records.length} label${records.length===1?"":"s"} (${locales.join(", ")})`,"render"),warnings:dbLabelsRuntimeWarnings(options.cwd)})}__name(labelsSetManyCommand,"labelsSetManyCommand");async function labelsDeleteCommand(key,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("i18n.delete",{projectId:ctx.projectId,env:ctx.env});let locale=options.locale??defaultLocaleForProject(options.cwd),result=await api.deleteLabel(ctx.projectId,locale,key);ui.result({command:"labels delete",data:result,render:__name(()=>`Deleted ${key} (${locale})`,"render"),warnings:dbLabelsRuntimeWarnings(options.cwd)})}__name(labelsDeleteCommand,"labelsDeleteCommand");function readLabelRecords(options){if(options.file&&options.data)throw new Error("Pass either --file or --data, not both.");if(!options.file&&!options.data)throw new Error("Pass --file <path> or --data <json>.");let raw=options.data??readLabelFile(options),parsed=JSON.parse(raw);if(Array.isArray(parsed))return parsed.map(item=>{if(!item||typeof item!="object")throw new Error("Label arrays must contain objects with key and value fields.");let record2=item;if(typeof record2.key!="string")throw new Error("Each label record must include a string key.");let value=record2.value??record2.defaultValue;if(typeof value!="string")throw new Error(`Label ${record2.key} must include a string value.`);let locale;if(record2.locale!==void 0){if(typeof record2.locale!="string")throw new Error(`Label ${record2.key} has a non-string locale.`);locale=record2.locale}return{key:record2.key,value,locale}});if(!parsed||typeof parsed!="object")throw new Error("Labels JSON must be an object map or an array of { key, value } records.");return Object.entries(parsed).map(([key,value])=>{if(typeof value!="string")throw new Error(`Label ${key} must be a string.`);return{key,value}})}__name(readLabelRecords,"readLabelRecords");function readLabelFile(options){let projectRoot=resolveProjectCwd(options.cwd),filePath=path36.resolve(projectRoot,options.file);return fs36.readFileSync(filePath,"utf8")}__name(readLabelFile,"readLabelFile");async function readStdinValue2(){if(process.stdin.isTTY)throw new Error("Pass a label value or pipe one with --stdin.");let chunks=[];for await(let chunk of process.stdin)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));return Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/,"")}__name(readStdinValue2,"readStdinValue");init_esm();init_dist();import path38 from"node:path";init_api();init_auth();init_config();import fs37 from"node:fs";import path37 from"node:path";function removeSeededEnvResidue(targetDir,link){let removed=[],urlKeys=new Set(LOCAL_CONTENT_API_ENV_KEYS),selectorKeys=new Set(LOCAL_ENV_SELECTOR_KEYS);for(let file of[".env",".env.local"]){let filePath=path37.join(targetDir,file);if(!fs37.existsSync(filePath))continue;let original=fs37.readFileSync(filePath,"utf-8"),eol=original.includes(`\r
|
|
1336
1349
|
`)?`\r
|
|
1337
1350
|
`:`
|
|
1338
1351
|
`,kept=[],removedUrlHere=!1,lines=original.split(/\r?\n/),isSeededUrl=__name((key,value)=>urlKeys.has(key)&&isFimoMintedTenantUrl(value,link),"isSeededUrl");removedUrlHere=lines.some(line=>{let parsed=parseLine(line);return parsed!==null&&isSeededUrl(parsed.key,parsed.value)});for(let line of lines){let parsed=parseLine(line);if(parsed&&(isSeededUrl(parsed.key,parsed.value)||removedUrlHere&&selectorKeys.has(parsed.key))){removed.push({file,key:parsed.key,value:parsed.value});continue}kept.push(line)}if(kept.length!==lines.length){let content2=kept.join(eol);fs37.writeFileSync(filePath,content2)}}return removed}__name(removeSeededEnvResidue,"removeSeededEnvResidue");function parseLine(line){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))return null;let eq2=trimmed.indexOf("=");return eq2<=0?null:{key:trimmed.slice(0,eq2).trim(),value:trimmed.slice(eq2+1).trim().replace(/^['"]|['"]$/g,"")}}__name(parseLine,"parseLine");init_git_credential_setup();init_git();init_local_project_files();init_project();init_clone();async function linkCommand(projectIdArg,options={}){let cfg=loadConfig(),creds=requireCredentials(cfg),api=new FimoApiClient(cfg),targetDir=path38.resolve(options.cwd??process.cwd());if(!await isGitRepo(targetDir)){ui.error({command:"link",code:"NOT_A_GIT_REPO",message:`${targetDir} is not a git repository.`,hint:"Run `git init` and commit your application first \u2014 Fimo deploys from git."});return}let existingProjectId=findProjectRoot(targetDir)===targetDir?readLinkedProjectId(targetDir):null,projectId=projectIdArg??existingProjectId??await promptForProjectId(api,creds);if(!projectId)return;let env=await resolveLinkEnv(targetDir,options.env);if(!env)return;let remote,project;try{[remote,project]=await Promise.all([api.getGitRemote(projectId,env),api.getProject(projectId)])}catch(error){ui.error({command:"link",code:error instanceof ApiRequestError&&error.status===404?"PROJECT_NOT_FOUND":"LINK_FAILED",message:`Could not read project ${projectId} (env '${env}'): ${error instanceof Error?error.message:String(error)}`,hint:"Check the project id with `fimo projects list`, and that the env exists (`fimo branch`)."});return}await ensureFimoRemote(targetDir,remote.url),writeLocalProjectFiles({targetDir,project,apiUrl:cfg.apiUrl,tenantApiBaseUrl:remote.tenantApiBaseUrl});let removed=remote.tenantApiBaseUrl?removeSeededEnvResidue(targetDir,{projectId,tenantApiBaseUrl:remote.tenantApiBaseUrl}):[],runtime=resolveLocalRuntimeEnv({cwd:targetDir}),relinked=!!existingProjectId;ui.ok({command:"link",headline:relinked?`Repaired the link to '${project.displayName??project.name}' on env '${env}'`:`Linked ${path38.basename(targetDir)} to '${project.displayName??project.name}' on env '${env}'`,details:{project_id:projectId,env,relinked,git_remote:"fimo",tenant_api_url:runtime?.tenantApiUrl??null,removed_env_lines:removed.map(entry=>`${entry.file}: ${entry.key}`)},warnings:remote.tenantApiBaseUrl?void 0:["The server did not return a tenant API base URL, so this checkout cannot derive env URLs on its own. Upgrade the Fimo backend, or set VITE_API_URL / NEXT_PUBLIC_FIMO_API_URL yourself."]})}__name(linkCommand,"linkCommand");function readLinkedProjectId(targetDir){try{return loadProjectSettings(targetDir).projectId}catch{return null}}__name(readLinkedProjectId,"readLinkedProjectId");async function promptForProjectId(api,creds){let picked=await selectProjectId({api,activeOrganizationId:creds?.activeOrganization?.id,message:"Which Fimo project should this application link to?"});switch(picked.status){case"selected":return picked.projectId;case"cancelled":return ui.info({command:"link",message:"Cancelled."}),null;case"empty":return ui.error({command:"link",code:"NO_PROJECTS",message:picked.message,hint:"Create one with `fimo init`, then link this application to it."}),null;default:return ui.error({command:"link",code:picked.code,message:picked.message,hint:picked.hint}),null}}__name(promptForProjectId,"promptForProjectId");async function resolveLinkEnv(targetDir,override){if(override)return isValidEnv(override)?override:(ui.error({command:"link",code:"INVALID_ENV",message:`'${override}' is not a valid env name.`}),null);let branch=await currentBranch(targetDir).catch(()=>null);return branch&&branch!=="HEAD"&&isValidEnv(branch)?branch:DEFAULT_ENV}__name(resolveLinkEnv,"resolveLinkEnv");init_dist5();init_dist();init_api();init_auth_errors();init_environment_checkout();init_git_credential_setup();init_interactive();init_project_context();init_project();function coverage(value){return`${value.translated}/${value.total}`}__name(coverage,"coverage");function localeLines(stats){return stats.map(item=>`${item.isDefault?"* ":" "}${item.locale.padEnd(12)} entries ${coverage(item.entries).padEnd(9)} labels ${coverage(item.labels)}`)}__name(localeLines,"localeLines");function renderLocaleStats(env,stats){return[`Locales for ${env}`,"",...localeLines(stats.locales),"",`Routing: path prefix; default locale ${stats.routing.prefixDefaultLocale?"is":"is not"} prefixed`].join(`
|
|
1339
|
-
`)}__name(renderLocaleStats,"renderLocaleStats");async function localesListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("i18n.list",{projectId:ctx.projectId,env:ctx.env});let stats=await api.getProjectLocaleStats(ctx.projectId);ui.result({command:"locales list",data:{env:ctx.env,...stats},render:__name(()=>renderLocaleStats(ctx.env,stats),"render")})}__name(localesListCommand,"localesListCommand");function confirmationDetails(spec,locale,env,plan){let movement=plan.state.relation==="behind"?`Fimo will first fast-forward '${plan.state.localBranch}' by ${plan.state.behind} commit${plan.state.behind===1?"":"s"}, then commit this change to fimo/${plan.state.remoteBranch} and synchronize it back.`:`Fimo will commit this change to fimo/${plan.state.remoteBranch}, then fast-forward '${plan.state.localBranch}' to that commit.`;return[`${spec.verb} locale '${locale}' in
|
|
1352
|
+
`)}__name(renderLocaleStats,"renderLocaleStats");async function localesListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("i18n.list",{projectId:ctx.projectId,env:ctx.env});let stats=await api.getProjectLocaleStats(ctx.projectId);ui.result({command:"locales list",data:{env:ctx.env,...stats},render:__name(()=>renderLocaleStats(ctx.env,stats),"render")})}__name(localesListCommand,"localesListCommand");function confirmationDetails(spec,locale,env,plan){let movement=plan.state.relation==="behind"?`Fimo will first fast-forward '${plan.state.localBranch}' by ${plan.state.behind} commit${plan.state.behind===1?"":"s"}, then commit this change to fimo/${plan.state.remoteBranch} and synchronize it back.`:`Fimo will commit this change to fimo/${plan.state.remoteBranch}, then fast-forward '${plan.state.localBranch}' to that commit.`;return[`${spec.verb} locale '${locale}' in Branch '${env}'.`,movement,...spec.destructive?[`This permanently deletes stored entries and labels for '${locale}' from this Branch.`]:[]].join(`
|
|
1340
1353
|
`)}__name(confirmationDetails,"confirmationDetails");function rejectMissingConfirmation(spec,options){return options.yes||currentMode().format!=="json"&&isInteractive()?!1:(ui.error({command:`locales ${spec.operation}`,code:"CONFIRMATION_REQUIRED",message:"Locale lifecycle changes require confirmation.",hint:"Review the operation, then pass --yes to apply it non-interactively."}),!0)}__name(rejectMissingConfirmation,"rejectMissingConfirmation");async function confirmMutation(spec,locale,env,plan,options){if(options.yes)return!0;wt(confirmationDetails(spec,locale,env,plan),"What will happen");let confirmed=await ot2({message:"Continue?",initialValue:!1});return q(confirmed)||!confirmed?(ui.info({command:`locales ${spec.operation}`,message:"Cancelled."}),!1):!0}__name(confirmMutation,"confirmMutation");function emitPreflightError(command,error){return error instanceof EnvironmentCheckoutError?(ui.error({command,code:error.code,message:error.message,hint:error.hint}),!0):!1}__name(emitPreflightError,"emitPreflightError");function emitApiError(command,error){return rethrowCliAuthError(error),error instanceof ApiRequestError?(ui.error({command,code:error.code?.toUpperCase()??"LOCALE_MUTATION_FAILED",message:error.detail}),!0):!1}__name(emitApiError,"emitApiError");function renderMutationResult(spec,response,env,sync){if(sync.status==="required")return[`Locale '${response.locale}' was changed in '${env}', but this checkout could not be synchronized.`,"The remote change succeeded. Do not retry the locale command.","",sync.reason,"","Recover the checkout:",...sync.recovery.map(command=>` ${command}`)].join(`
|
|
1341
1354
|
`);let removal="entriesDeleted"in response?` Deleted ${response.entriesDeleted} entr${response.entriesDeleted===1?"y":"ies"} and ${response.labelsDeleted} label${response.labelsDeleted===1?"":"s"}.`:"";return`${spec.verb} locale '${response.locale}' in '${env}'.${removal}
|
|
1342
|
-
Remote config and local checkout are synchronized.`}__name(renderMutationResult,"renderMutationResult");async function runLocaleMutation(locale,options,cmd,spec){let command=`locales ${spec.operation}`;if(rejectMissingConfirmation(spec,options))return;let cwd=resolveProjectCwd(options.cwd),{ctx,api}=await bootstrapProjectCommand(options,cmd,{requireBranch:!0,refuseReadOnly:!0});await requireOperation(spec.capability,{projectId:ctx.projectId,env:ctx.env});let plan;try{let remote=await api.getGitRemote(ctx.projectId,ctx.env);await ensureFimoRemote(cwd,remote.url),plan=await planLocaleMutationCheckout({cwd,remoteBranch:remote.branch,configPath:resolveProjectConfigPath(cwd)})}catch(error){if(emitPreflightError(command,error)||emitApiError(command,error))return;throw error}if(!await confirmMutation(spec,locale,ctx.env,plan,options))return;try{await applyLocaleMutationCheckoutPlan(plan)}catch(error){if(emitPreflightError(command,error))return;throw error}let response;try{response=await spec.mutate(api,ctx.projectId,locale)}catch(error){if(emitApiError(command,error))return;throw error}let sync=await synchronizeLocaleMutationCheckout({cwd,remoteBranch:plan.state.remoteBranch}),data2={operation:spec.operation,env:ctx.env,applied:!0,...response,...sync.status==="required"?{code:"LOCALE_APPLIED_SYNC_REQUIRED"}:{},sync};ui.result({command,data:data2,render:__name(()=>renderMutationResult(spec,response,ctx.env,sync),"render")}),sync.status==="required"&&(process.exitCode=2)}__name(runLocaleMutation,"runLocaleMutation");async function localesAddCommand(locale,options,cmd){return runLocaleMutation(locale,options,cmd,{operation:"add",capability:"i18n.create",verb:"Add",destructive:!1,mutate:__name((api,projectId,value)=>api.addProjectLocale(projectId,{locale:value}),"mutate")})}__name(localesAddCommand,"localesAddCommand");async function localesSetDefaultCommand(locale,options,cmd){return runLocaleMutation(locale,options,cmd,{operation:"set-default",capability:"i18n.update",verb:"Set the default to",destructive:!1,mutate:__name((api,projectId,value)=>api.setProjectDefaultLocale(projectId,{locale:value}),"mutate")})}__name(localesSetDefaultCommand,"localesSetDefaultCommand");async function localesRemoveCommand(locale,options,cmd){return runLocaleMutation(locale,options,cmd,{operation:"remove",capability:"i18n.delete",verb:"Remove",destructive:!0,mutate:__name((api,projectId,value)=>api.removeProjectLocale(projectId,value),"mutate")})}__name(localesRemoveCommand,"localesRemoveCommand");function registerLocalesCommands(program2){let locales=program2.command("locales").description("Manage project locale lifecycle");locales.command("list").description("List configured locales and stored content coverage").option("-C, --cwd <dir>","Project directory").action(localesListCommand),locales.command("add <locale>").description("Add a locale to the selected environment").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Apply without an interactive confirmation").action(localesAddCommand),locales.command("set-default <locale>").description("Set the default locale for the selected environment").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Apply without an interactive confirmation").action(localesSetDefaultCommand),locales.command("remove <locale>").description("Remove a locale and permanently delete its stored content").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Apply without an interactive confirmation").action(localesRemoveCommand)}__name(registerLocalesCommands,"registerLocalesCommands");init_login();init_dist();init_auth();init_config();async function logoutCommand(){let cfg=loadConfig(),creds=readCredentials(cfg);if(!creds?.access_token){ui.info({command:"logout",message:"Already signed out."});return}clearCredentials(cfg),ui.ok({command:"logout",headline:`Signed out${creds.user?.email?` (${creds.user.email})`:""}.`,details:creds.user?.email?{email:creds.user.email}:void 0})}__name(logoutCommand,"logoutCommand");init_esm();import{z as z72}from"zod";var projectScopeShape={projectId:z72.uuid().optional().describe("The Fimo project ID. Optional when the MCP server is already bound to a project.")},envScopeShape={...projectScopeShape,env:EnvSchema.optional().describe("The environment name, for example 'main' or 'agents/content-review'. Optional when the server is bound to an environment.")},typeNameField=z72.string().min(1).max(255).describe("The content type name, for example BlogPost."),localeField=z72.string().min(1).optional().describe("The locale to read or write."),entryDataField=z72.record(z72.string(),z72.unknown()).describe("Entry field values, keyed by field name as declared in the content schema."),filePathField=z72.string().min(1).max(1024).describe("File path relative to the project root."),labelKeyField=z72.string().min(1).max(255).describe("The translation key, for example home.hero.title."),assetIdField=z72.uuid().describe("The Fimo media asset ID."),formIdField=z72.string().min(1).max(255).describe("The Fimo form ID."),formFieldsField=z72.record(z72.string().min(1),z72.unknown()).describe("Form fields keyed by field name; Fimo validates each field definition."),formContentShape={name:z72.string().min(1).max(255).describe("Stable form name."),label:z72.string().min(1).max(255).describe("Human-readable form label."),fields:formFieldsField},mediaGenerationSchema=z72.object({...envScopeShape,task:z72.string().min(1).optional().describe("A stable task, for example 'image.generate' or 'video.generate'."),model:z72.string().min(1).optional().describe("An explicit model ID, for example 'fal/...'."),options:z72.record(z72.string(),z72.unknown()).describe("Task or model options, such as prompt, quality, aspect ratio, and source assets."),name:z72.string().min(1).max(255).optional().describe("Optional name for the generated asset."),parentId:z72.uuid().nullable().optional().describe("Optional media-library folder ID."),altText:z72.string().max(2e3).optional().describe("Optional alternative text for the generated asset."),caption:z72.string().max(2e3).optional().describe("Optional caption for the generated asset.")}).superRefine((value,context)=>{!!value.task==!!value.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model.",path:["task"]})});function tenantPath(scope,suffix){return`/tenant/${encodeURIComponent(scope.projectId)}/envs/${encodeEnvPathSegment(scope.env)}${suffix}`}__name(tenantPath,"tenantPath");function managementProjectPath(scope,suffix){return`/management/projects/${encodeURIComponent(scope.projectId)}${suffix}`}__name(managementProjectPath,"managementProjectPath");function managementEnvPath(scope,suffix){return managementProjectPath(scope,`/envs/${encodeURIComponent(scope.env)}${suffix}`)}__name(managementEnvPath,"managementEnvPath");function addQuery(path49,query){let params=new URLSearchParams;for(let[key,value]of Object.entries(query))if(value!==void 0){if(Array.isArray(value)){value.length>0&¶ms.set(key,value.join(","));continue}params.set(key,String(value))}let queryString=params.toString();return queryString?`${path49}?${queryString}`:path49}__name(addQuery,"addQuery");var mcpToolCatalog={whoami:{description:"Return the authenticated Fimo user identity.",annotations:{readOnlyHint:!0},scope:"none",accessScope:"read",inputSchema:z72.object({})},projects_list:{description:"List the Fimo projects the authenticated user can access.",annotations:{readOnlyHint:!0},scope:"none",accessScope:"read",inputSchema:z72.object({}),buildRequest:__name(()=>({method:"GET",path:"/management/projects"}),"buildRequest")},envs_list:{description:"List the environments of a project.",annotations:{readOnlyHint:!0},scope:"project",accessScope:"read",inputSchema:z72.object(projectScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:managementProjectPath(scope,"/envs")}),"buildRequest")},schemas_list:{description:"List content schemas in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.schema.list",inputSchema:z72.object(envScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:tenantPath(scope,"/schema")}),"buildRequest")},entries_list:{description:"List entries for one content type in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.list",inputSchema:z72.object({...envScopeShape,typeName:typeNameField,locale:localeField,limit:z72.number().int().min(1).max(100).optional().describe("Maximum number of records to return."),offset:z72.number().int().min(0).optional().describe("Number of records to skip.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}`),{locale:input.locale,limit:input.limit,offset:input.offset})}),"buildRequest")},entries_get:{description:"Read one entry by ID from a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.get",inputSchema:z72.object({...envScopeShape,typeName:typeNameField,id:z72.uuid().describe("The entry ID."),locale:localeField,populate:z72.array(z72.string().min(1)).max(50).optional().describe("Reference fields to populate."),localeFallbacks:z72.boolean().optional().describe("Use the configured default locale when needed.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/${encodeURIComponent(input.id)}`),{locale:input.locale,populate:input.populate,localeFallbacks:input.localeFallbacks})}),"buildRequest")},entries_search:{description:"Search entries across content types in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.list",inputSchema:z72.object({...envScopeShape,search:z72.string().min(1).optional().describe("A text search applied to entry content."),locale:localeField,limit:z72.number().int().min(1).max(100).optional().describe("Maximum number of records to return."),offset:z72.number().int().min(0).optional().describe("Number of records to skip.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,"/entries"),{search:input.search,locale:input.locale,limit:input.limit,offset:input.offset})}),"buildRequest")},entries_create:{description:"Create one entry of a content type in a project environment.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.create",inputSchema:z72.object({...envScopeShape,typeName:typeNameField,data:entryDataField,locale:localeField,documentId:z72.string().min(1).optional().describe("Attach the new entry to an existing document (adds a locale variant).")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}`),body:{data:input.data,locale:input.locale,documentId:input.documentId}}),"buildRequest")},entries_update:{description:"Update one entry by ID in a project environment.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.update",inputSchema:z72.object({...envScopeShape,typeName:typeNameField,id:z72.uuid().describe("The entry ID."),data:entryDataField,locale:localeField}),buildRequest:__name((input,scope)=>({method:"PUT",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/${encodeURIComponent(input.id)}`),{locale:input.locale}),body:{data:input.data}}),"buildRequest")},entries_delete:{description:"Delete one entry by ID in a project environment.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"cms.delete",inputSchema:z72.object({...envScopeShape,typeName:typeNameField,id:z72.uuid().describe("The entry ID."),locale:localeField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/${encodeURIComponent(input.id)}`),{locale:input.locale})}),"buildRequest")},entries_bulk_create:{description:`Create up to ${MAX_BULK_ENTRIES} entries of one content type in a project environment.`,annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.bulk_create",inputSchema:z72.object({...envScopeShape,typeName:typeNameField,entries:z72.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES).describe("Entries to create.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/bulk-create`),body:{entries:input.entries}}),"buildRequest")},entries_bulk_update:{description:`Update up to ${MAX_BULK_ENTRIES} entries by IDs, a bounded filter, or per-entry updates.`,annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.bulk_update",inputSchema:z72.object({...envScopeShape,typeName:typeNameField,selection:z72.union([z72.object({ids:z72.array(z72.uuid()).min(1).max(MAX_BULK_ENTRIES)}),z72.object({where:EntryWhereSchema}),z72.object({updates:z72.array(z72.object({id:z72.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),body:EntryMutationBodySchema.optional().describe("Shared update body for ids or where selections.")}).superRefine((value,context)=>{let isPerEntry="updates"in value.selection;isPerEntry&&value.body!==void 0&&context.addIssue({code:"custom",message:"Do not pass body with per-entry updates.",path:["body"]}),!isPerEntry&&value.body===void 0&&context.addIssue({code:"custom",message:"Pass body with ids or where selections.",path:["body"]})}),buildRequest:__name((input,scope)=>{let{selection,body}=input;return{method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/bulk-update`),body:"updates"in selection?selection:{...selection,body}}},"buildRequest")},entries_bulk_delete:{description:`Delete up to ${MAX_BULK_ENTRIES} entries by IDs or a bounded filter.`,annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"cms.bulk_delete",inputSchema:z72.object({...envScopeShape,typeName:typeNameField,selection:z72.union([z72.object({ids:z72.array(z72.uuid()).min(1).max(MAX_BULK_ENTRIES)}),z72.object({where:EntryWhereSchema})]),locale:localeField}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/bulk-delete`),body:{...input.selection,locale:input.locale}}),"buildRequest")},singles_get:{description:"Read the document-scoped value of a Single content type.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.get",inputSchema:z72.object({...envScopeShape,typeName:typeNameField,locale:localeField,populate:z72.array(z72.string().min(1)).max(50).optional().describe("Reference fields to populate.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/documents/${encodeURIComponent(input.typeName)}`),{locale:input.locale,populate:input.populate})}),"buildRequest")},singles_update:{description:"Update the document-scoped value of a Single content type.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.update",inputSchema:z72.object({...envScopeShape,typeName:typeNameField,data:entryDataField,locale:localeField}),buildRequest:__name((input,scope)=>({method:"PUT",path:addQuery(tenantPath(scope,`/documents/${encodeURIComponent(input.typeName)}`),{locale:input.locale}),body:{data:input.data}}),"buildRequest")},labels_list:{description:'List localized labels in a project environment. Pass locale "*" to group all locales.',annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"i18n.list",inputSchema:z72.object({...envScopeShape,locale:z72.string().min(1).optional().describe('Locale code, or "*" for every configured locale.')}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,"/labels"),{locale:input.locale})}),"buildRequest")},labels_get:{description:"Read one localized label by locale and key.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"i18n.get",inputSchema:z72.object({...envScopeShape,locale:z72.string().min(1).describe("Locale code."),key:labelKeyField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/labels/${encodeURIComponent(input.locale)}/${encodeURIComponent(input.key)}`)}),"buildRequest")},labels_set:{description:"Create or set one localized label.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"i18n.create",inputSchema:z72.object({...envScopeShape,key:labelKeyField,value:z72.string().max(1e4).describe("Localized label text."),locale:localeField}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/labels"),body:{key:input.key,value:input.value,locale:input.locale}}),"buildRequest")},labels_set_many:{description:"Set many localized labels in one bounded request.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"i18n.update",inputSchema:z72.object({...envScopeShape,records:z72.array(z72.object({key:labelKeyField,value:z72.string().max(1e4),locale:localeField})).min(1).max(500).describe("Localized labels to set.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/labels/sync"),body:{created:input.records,updated:[],deleted:[]}}),"buildRequest")},labels_delete:{description:"Delete one localized label.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"i18n.delete",inputSchema:z72.object({...envScopeShape,locale:z72.string().min(1).describe("Locale code."),key:labelKeyField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:tenantPath(scope,`/labels/${encodeURIComponent(input.locale)}/${encodeURIComponent(input.key)}`)}),"buildRequest")},assets_list:{description:"List media assets and folders, including public URLs for files the user can access.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"assets.list",inputSchema:z72.object({...envScopeShape,parentId:z72.uuid().optional().describe("Limit results to one media-library folder."),search:z72.string().max(200).optional(),type:z72.enum(["file","folder"]).optional(),mimePrefix:z72.string().max(50).optional().describe("MIME prefix such as image/ or video/."),sortBy:z72.enum(["name","createdAt","updatedAt","fileSize","type"]).optional(),sortDirection:z72.enum(["asc","desc"]).optional(),includePath:z72.boolean().optional(),excludeHidden:z72.boolean().optional(),limit:z72.number().int().min(1).max(100).optional(),offset:z72.number().int().min(0).optional()}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,"/assets"),{parentId:input.parentId,search:input.search,type:input.type,mimePrefix:input.mimePrefix,sortBy:input.sortBy,sortDirection:input.sortDirection,includePath:input.includePath,excludeHidden:input.excludeHidden,limit:input.limit,offset:input.offset})}),"buildRequest")},assets_get:{description:"Read one media asset or folder, including its public URL when it is a file.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"assets.get",inputSchema:z72.object({...envScopeShape,id:assetIdField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/assets/${encodeURIComponent(input.id)}`)}),"buildRequest")},assets_generate:{description:"Generate an image or video asset with Fimo AI credits and save it to the media library.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"assets.generate",inputSchema:mediaGenerationSchema,buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/assets/generate"),body:{...input.task?{task:input.task}:{model:input.model},options:input.options,name:input.name,parentId:input.parentId,altText:input.altText,caption:input.caption}}),"buildRequest")},assets_create_folder:{description:"Create a media-library folder.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"assets.create_folder",inputSchema:z72.object({...envScopeShape,name:z72.string().min(1).max(255).describe("Folder name."),parentId:z72.uuid().nullable().optional().describe("Optional parent folder ID.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/assets/folders"),body:{name:input.name,parentId:input.parentId}}),"buildRequest")},assets_move:{description:"Move a media asset or folder to another media-library folder.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"assets.move",inputSchema:z72.object({...envScopeShape,id:assetIdField,parentId:z72.uuid().nullable().describe("Destination folder ID, or null for the library root.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/assets/${encodeURIComponent(input.id)}/move`),body:{parentId:input.parentId}}),"buildRequest")},assets_delete:{description:"Delete a media asset or folder.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"assets.delete",inputSchema:z72.object({...envScopeShape,id:assetIdField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:tenantPath(scope,`/assets/${encodeURIComponent(input.id)}`)}),"buildRequest")},forms_list:{description:"List the forms configured in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.list",inputSchema:z72.object(envScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:tenantPath(scope,"/forms")}),"buildRequest")},forms_get:{description:"Read one form definition.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.get",inputSchema:z72.object({...envScopeShape,id:formIdField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}`)}),"buildRequest")},forms_create:{description:"Create a form definition. Email notification settings stay in the Fimo UI.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"forms.push",inputSchema:z72.object({...envScopeShape,...formContentShape}).strict(),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/forms"),body:{name:input.name,label:input.label,fields:input.fields}}),"buildRequest")},forms_update:{description:"Update the name, label, or fields of one form definition.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"forms.push",inputSchema:z72.object({...envScopeShape,id:formIdField,...z72.object(formContentShape).partial().shape}).strict(),buildRequest:__name((input,scope)=>({method:"PUT",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}`),body:{name:input.name,label:input.label,fields:input.fields}}),"buildRequest")},forms_delete:{description:"Delete one form definition.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"forms.delete",inputSchema:z72.object({...envScopeShape,id:formIdField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}`)}),"buildRequest")},forms_submissions_list:{description:"List submissions for one form.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.list",inputSchema:z72.object({...envScopeShape,id:formIdField,limit:z72.number().int().min(1).max(100).optional(),offset:z72.number().int().min(0).optional(),searchQuery:z72.string().max(200).optional(),sortDirection:z72.enum(["asc","desc"]).optional()}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/forms/${encodeURIComponent(input.id)}/submissions`),{limit:input.limit,offset:input.offset,searchQuery:input.searchQuery,sortDirection:input.sortDirection})}),"buildRequest")},forms_submission_get:{description:"Read one submission for a form.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.get",inputSchema:z72.object({...envScopeShape,id:formIdField,submissionId:z72.string().min(1).max(255).describe("The submission ID.")}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}/submissions/${encodeURIComponent(input.submissionId)}`)}),"buildRequest")},forms_submissions_stats:{description:"Read aggregate submission statistics for a form.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.get",inputSchema:z72.object({...envScopeShape,id:formIdField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}/submissions/stats`)}),"buildRequest")},files_read:{description:"Read one project file from an environment. Hidden and sensitive files (.env, credentials, keys, lockfiles, .git, build output) are unavailable.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"files.read",inputSchema:z72.object({...envScopeShape,path:filePathField}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(managementEnvPath(scope,"/files/file"),{path:input.path})}),"buildRequest")},files_glob:{description:"List project file paths in an environment, optionally filtered by a glob pattern.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"files.read",inputSchema:z72.object({...envScopeShape,pattern:z72.string().min(1).max(300).optional().describe("Glob pattern, for example 'src/**/*.tsx'."),limit:z72.number().int().min(1).max(2e3).optional().describe("Maximum number of paths to return.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(managementEnvPath(scope,"/files/paths"),{pattern:input.pattern,limit:input.limit})}),"buildRequest")},files_grep:{description:"Search project file contents in an environment with a regular expression. Matching is bounded (file count, bytes, match count) and complex patterns that exceed the time budget are rejected.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"files.read",inputSchema:z72.object({...envScopeShape,pattern:z72.string().min(1).max(200).describe("Regular expression to search for."),include:z72.string().min(1).max(300).optional().describe("Glob pattern limiting which files are searched."),caseInsensitive:z72.boolean().optional().describe("Case-insensitive matching."),maxMatches:z72.number().int().min(1).max(200).optional().describe("Maximum number of matches to return.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(managementEnvPath(scope,"/files/grep"),{pattern:input.pattern,include:input.include,caseInsensitive:input.caseInsensitive,maxMatches:input.maxMatches})}),"buildRequest")},files_write:{description:"Create one project text file, or overwrite an existing one when overwrite is set. Fails if the file exists and overwrite is not set. The change lands as a reviewable commit on the environment branch.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"files.write",inputSchema:z72.object({...envScopeShape,path:filePathField,content:z72.string().max(262144).describe("Full UTF-8 text content of the file (256 KB max)."),overwrite:z72.boolean().optional().describe("Replace the file if it already exists. Without it, writing an existing path fails.")}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,"/files/write"),body:{path:input.path,content:input.content,overwrite:input.overwrite}}),"buildRequest")},files_edit:{description:"Edit one project file by exact string replacement. The old string must exist; set replaceAll when it occurs more than once. The change lands as a reviewable commit on the environment branch.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"files.write",inputSchema:z72.object({...envScopeShape,path:filePathField,oldString:z72.string().min(1).describe("Exact text to replace."),newString:z72.string().describe("Replacement text."),replaceAll:z72.boolean().optional().describe("Replace every occurrence instead of requiring a unique one.")}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,"/files/edit"),body:{path:input.path,oldString:input.oldString,newString:input.newString,replaceAll:input.replaceAll}}),"buildRequest")},files_delete:{description:"Delete one project file in an environment. The deletion lands as a reviewable commit on the environment branch.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"files.write",inputSchema:z72.object({...envScopeShape,path:filePathField}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,"/files/delete"),body:{path:input.path}}),"buildRequest")},agents_list:{description:"List the agent bundles declared in a project environment, with triggers and activations.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",inputSchema:z72.object(envScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:managementEnvPath(scope,"/agents")}),"buildRequest")},agents_run:{description:"Trigger a manual run of a project agent. Returns a durable session ID; poll agents_status for progress. The agent executes in the managed project sandbox under its declared capabilities.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"agents",operation:"agent.delegate",inputSchema:z72.object({...envScopeShape,agentName:z72.string().min(1).max(120).describe("The agent bundle name."),args:z72.record(z72.string(),z72.unknown()).optional().describe("Arguments passed to the agent run.")}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,`/agents/${encodeURIComponent(input.agentName)}/run`),body:input.args===void 0?{}:{args:input.args}}),"buildRequest")},agents_status:{description:"Read one agent session (status, report, checkpoints) by session ID.",annotations:{readOnlyHint:!0},scope:"project",accessScope:"read",inputSchema:z72.object({...projectScopeShape,sessionId:z72.uuid().describe("The agent session ID returned by agents_run.")}),buildRequest:__name((input,scope)=>({method:"GET",path:managementProjectPath(scope,`/agents/sessions/${encodeURIComponent(input.sessionId)}`)}),"buildRequest")}},mcpToolNames=Object.keys(mcpToolCatalog);import*as z3rt from"zod/v3";import*as z4mini from"zod/v4-mini";function isZ4Schema(s){return!!s._zod}__name(isZ4Schema,"isZ4Schema");function objectFromShape(shape){let values=Object.values(shape);if(values.length===0)return z4mini.object({});let allV4=values.every(isZ4Schema),allV3=values.every(s=>!isZ4Schema(s));if(allV4)return z4mini.object(shape);if(allV3)return z3rt.object(shape);throw new Error("Mixed Zod versions detected in object shape.")}__name(objectFromShape,"objectFromShape");function safeParse3(schema,data2){return isZ4Schema(schema)?z4mini.safeParse(schema,data2):schema.safeParse(data2)}__name(safeParse3,"safeParse");async function safeParseAsync2(schema,data2){return isZ4Schema(schema)?await z4mini.safeParseAsync(schema,data2):await schema.safeParseAsync(data2)}__name(safeParseAsync2,"safeParseAsync");function getObjectShape(schema){if(!schema)return;let rawShape;if(isZ4Schema(schema)?rawShape=schema._zod?.def?.shape:rawShape=schema.shape,!!rawShape){if(typeof rawShape=="function")try{return rawShape()}catch{return}return rawShape}}__name(getObjectShape,"getObjectShape");function normalizeObjectSchema(schema){if(schema){if(typeof schema=="object"){let asV3=schema,asV4=schema;if(!asV3._def&&!asV4._zod){let values=Object.values(schema);if(values.length>0&&values.every(v=>typeof v=="object"&&v!==null&&(v._def!==void 0||v._zod!==void 0||typeof v.parse=="function")))return objectFromShape(schema)}}if(isZ4Schema(schema)){let def=schema._zod?.def;if(def&&(def.type==="object"||def.shape!==void 0))return schema}else if(schema.shape!==void 0)return schema}}__name(normalizeObjectSchema,"normalizeObjectSchema");function getParseErrorMessage(error){if(error&&typeof error=="object"){if("message"in error&&typeof error.message=="string")return error.message;if("issues"in error&&Array.isArray(error.issues)&&error.issues.length>0){let firstIssue=error.issues[0];if(firstIssue&&typeof firstIssue=="object"&&"message"in firstIssue)return String(firstIssue.message)}try{return JSON.stringify(error)}catch{return String(error)}}return String(error)}__name(getParseErrorMessage,"getParseErrorMessage");function getSchemaDescription(schema){return schema.description}__name(getSchemaDescription,"getSchemaDescription");function isSchemaOptional(schema){if(isZ4Schema(schema))return schema._zod?.def?.type==="optional";let v3Schema=schema;return typeof schema.isOptional=="function"?schema.isOptional():v3Schema._def?.typeName==="ZodOptional"}__name(isSchemaOptional,"isSchemaOptional");function getLiteralValue(schema){if(isZ4Schema(schema)){let def2=schema._zod?.def;if(def2){if(def2.value!==void 0)return def2.value;if(Array.isArray(def2.values)&&def2.values.length>0)return def2.values[0]}}let def=schema._def;if(def){if(def.value!==void 0)return def.value;if(Array.isArray(def.values)&&def.values.length>0)return def.values[0]}let directValue=schema.value;if(directValue!==void 0)return directValue}__name(getLiteralValue,"getLiteralValue");import*as z73 from"zod/v4";var LATEST_PROTOCOL_VERSION="2025-11-25";var SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],RELATED_TASK_META_KEY="io.modelcontextprotocol/related-task",JSONRPC_VERSION="2.0",AssertObjectSchema=z73.custom(v=>v!==null&&(typeof v=="object"||typeof v=="function")),ProgressTokenSchema=z73.union([z73.string(),z73.number().int()]),CursorSchema=z73.string(),TaskCreationParamsSchema=z73.looseObject({ttl:z73.union([z73.number(),z73.null()]).optional(),pollInterval:z73.number().optional()}),TaskMetadataSchema=z73.object({ttl:z73.number().optional()}),RelatedTaskMetadataSchema=z73.object({taskId:z73.string()}),RequestMetaSchema=z73.looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=z73.object({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),isTaskAugmentedRequestParams=__name(value=>TaskAugmentedRequestParamsSchema.safeParse(value).success,"isTaskAugmentedRequestParams"),RequestSchema=z73.object({method:z73.string(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=z73.object({_meta:RequestMetaSchema.optional()}),NotificationSchema=z73.object({method:z73.string(),params:NotificationsParamsSchema.loose().optional()}),ResultSchema=z73.looseObject({_meta:RequestMetaSchema.optional()}),RequestIdSchema=z73.union([z73.string(),z73.number().int()]),JSONRPCRequestSchema=z73.object({jsonrpc:z73.literal(JSONRPC_VERSION),id:RequestIdSchema,...RequestSchema.shape}).strict(),isJSONRPCRequest=__name(value=>JSONRPCRequestSchema.safeParse(value).success,"isJSONRPCRequest"),JSONRPCNotificationSchema=z73.object({jsonrpc:z73.literal(JSONRPC_VERSION),...NotificationSchema.shape}).strict(),isJSONRPCNotification=__name(value=>JSONRPCNotificationSchema.safeParse(value).success,"isJSONRPCNotification"),JSONRPCResultResponseSchema=z73.object({jsonrpc:z73.literal(JSONRPC_VERSION),id:RequestIdSchema,result:ResultSchema}).strict(),isJSONRPCResultResponse=__name(value=>JSONRPCResultResponseSchema.safeParse(value).success,"isJSONRPCResultResponse");var ErrorCode;(function(ErrorCode2){ErrorCode2[ErrorCode2.ConnectionClosed=-32e3]="ConnectionClosed",ErrorCode2[ErrorCode2.RequestTimeout=-32001]="RequestTimeout",ErrorCode2[ErrorCode2.ParseError=-32700]="ParseError",ErrorCode2[ErrorCode2.InvalidRequest=-32600]="InvalidRequest",ErrorCode2[ErrorCode2.MethodNotFound=-32601]="MethodNotFound",ErrorCode2[ErrorCode2.InvalidParams=-32602]="InvalidParams",ErrorCode2[ErrorCode2.InternalError=-32603]="InternalError",ErrorCode2[ErrorCode2.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ErrorCode||(ErrorCode={}));var JSONRPCErrorResponseSchema=z73.object({jsonrpc:z73.literal(JSONRPC_VERSION),id:RequestIdSchema.optional(),error:z73.object({code:z73.number().int(),message:z73.string(),data:z73.unknown().optional()})}).strict();var isJSONRPCErrorResponse=__name(value=>JSONRPCErrorResponseSchema.safeParse(value).success,"isJSONRPCErrorResponse");var JSONRPCMessageSchema=z73.union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),JSONRPCResponseSchema=z73.union([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:z73.string().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:z73.literal("notifications/cancelled"),params:CancelledNotificationParamsSchema}),IconSchema=z73.object({src:z73.string(),mimeType:z73.string().optional(),sizes:z73.array(z73.string()).optional(),theme:z73.enum(["light","dark"]).optional()}),IconsSchema=z73.object({icons:z73.array(IconSchema).optional()}),BaseMetadataSchema=z73.object({name:z73.string(),title:z73.string().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:z73.string(),websiteUrl:z73.string().optional(),description:z73.string().optional()}),FormElicitationCapabilitySchema=z73.intersection(z73.object({applyDefaults:z73.boolean().optional()}),z73.record(z73.string(),z73.unknown())),ElicitationCapabilitySchema=z73.preprocess(value=>value&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0?{form:{}}:value,z73.intersection(z73.object({form:FormElicitationCapabilitySchema.optional(),url:AssertObjectSchema.optional()}),z73.record(z73.string(),z73.unknown()).optional())),ClientTasksCapabilitySchema=z73.looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:z73.looseObject({sampling:z73.looseObject({createMessage:AssertObjectSchema.optional()}).optional(),elicitation:z73.looseObject({create:AssertObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=z73.looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:z73.looseObject({tools:z73.looseObject({call:AssertObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=z73.object({experimental:z73.record(z73.string(),AssertObjectSchema).optional(),sampling:z73.object({context:AssertObjectSchema.optional(),tools:AssertObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:z73.object({listChanged:z73.boolean().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:z73.string(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:z73.literal("initialize"),params:InitializeRequestParamsSchema});var ServerCapabilitiesSchema=z73.object({experimental:z73.record(z73.string(),AssertObjectSchema).optional(),logging:AssertObjectSchema.optional(),completions:AssertObjectSchema.optional(),prompts:z73.object({listChanged:z73.boolean().optional()}).optional(),resources:z73.object({subscribe:z73.boolean().optional(),listChanged:z73.boolean().optional()}).optional(),tools:z73.object({listChanged:z73.boolean().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:z73.string(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:z73.string().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:z73.literal("notifications/initialized"),params:NotificationsParamsSchema.optional()});var PingRequestSchema=RequestSchema.extend({method:z73.literal("ping"),params:BaseRequestParamsSchema.optional()}),ProgressSchema=z73.object({progress:z73.number(),total:z73.optional(z73.number()),message:z73.optional(z73.string())}),ProgressNotificationParamsSchema=z73.object({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:z73.literal("notifications/progress"),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()}),TaskStatusSchema=z73.enum(["working","input_required","completed","failed","cancelled"]),TaskSchema=z73.object({taskId:z73.string(),status:TaskStatusSchema,ttl:z73.union([z73.number(),z73.null()]),createdAt:z73.string(),lastUpdatedAt:z73.string(),pollInterval:z73.optional(z73.number()),statusMessage:z73.optional(z73.string())}),CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:z73.literal("notifications/tasks/status"),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema.extend({method:z73.literal("tasks/get"),params:BaseRequestParamsSchema.extend({taskId:z73.string()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:z73.literal("tasks/result"),params:BaseRequestParamsSchema.extend({taskId:z73.string()})}),GetTaskPayloadResultSchema=ResultSchema.loose(),ListTasksRequestSchema=PaginatedRequestSchema.extend({method:z73.literal("tasks/list")}),ListTasksResultSchema=PaginatedResultSchema.extend({tasks:z73.array(TaskSchema)}),CancelTaskRequestSchema=RequestSchema.extend({method:z73.literal("tasks/cancel"),params:BaseRequestParamsSchema.extend({taskId:z73.string()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ResourceContentsSchema=z73.object({uri:z73.string(),mimeType:z73.optional(z73.string()),_meta:z73.record(z73.string(),z73.unknown()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:z73.string()}),Base64Schema=z73.string().refine(val2=>{try{return atob(val2),!0}catch{return!1}},{message:"Invalid Base64 string"}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),RoleSchema=z73.enum(["user","assistant"]),AnnotationsSchema=z73.object({audience:z73.array(RoleSchema).optional(),priority:z73.number().min(0).max(1).optional(),lastModified:z73.iso.datetime({offset:!0}).optional()}),ResourceSchema=z73.object({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:z73.string(),description:z73.optional(z73.string()),mimeType:z73.optional(z73.string()),annotations:AnnotationsSchema.optional(),_meta:z73.optional(z73.looseObject({}))}),ResourceTemplateSchema=z73.object({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:z73.string(),description:z73.optional(z73.string()),mimeType:z73.optional(z73.string()),annotations:AnnotationsSchema.optional(),_meta:z73.optional(z73.looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:z73.literal("resources/list")}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:z73.array(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:z73.literal("resources/templates/list")}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:z73.array(ResourceTemplateSchema)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:z73.string()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema.extend({method:z73.literal("resources/read"),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema=ResultSchema.extend({contents:z73.array(z73.union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:z73.literal("notifications/resources/list_changed"),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema.extend({method:z73.literal("resources/subscribe"),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema.extend({method:z73.literal("resources/unsubscribe"),params:UnsubscribeRequestParamsSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:z73.string()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:z73.literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=z73.object({name:z73.string(),description:z73.optional(z73.string()),required:z73.optional(z73.boolean())}),PromptSchema=z73.object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:z73.optional(z73.string()),arguments:z73.optional(z73.array(PromptArgumentSchema)),_meta:z73.optional(z73.looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:z73.literal("prompts/list")}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:z73.array(PromptSchema)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:z73.string(),arguments:z73.record(z73.string(),z73.string()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:z73.literal("prompts/get"),params:GetPromptRequestParamsSchema}),TextContentSchema=z73.object({type:z73.literal("text"),text:z73.string(),annotations:AnnotationsSchema.optional(),_meta:z73.record(z73.string(),z73.unknown()).optional()}),ImageContentSchema=z73.object({type:z73.literal("image"),data:Base64Schema,mimeType:z73.string(),annotations:AnnotationsSchema.optional(),_meta:z73.record(z73.string(),z73.unknown()).optional()}),AudioContentSchema=z73.object({type:z73.literal("audio"),data:Base64Schema,mimeType:z73.string(),annotations:AnnotationsSchema.optional(),_meta:z73.record(z73.string(),z73.unknown()).optional()}),ToolUseContentSchema=z73.object({type:z73.literal("tool_use"),name:z73.string(),id:z73.string(),input:z73.record(z73.string(),z73.unknown()),_meta:z73.record(z73.string(),z73.unknown()).optional()}),EmbeddedResourceSchema=z73.object({type:z73.literal("resource"),resource:z73.union([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:z73.record(z73.string(),z73.unknown()).optional()}),ResourceLinkSchema=ResourceSchema.extend({type:z73.literal("resource_link")}),ContentBlockSchema=z73.union([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=z73.object({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema=ResultSchema.extend({description:z73.string().optional(),messages:z73.array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:z73.literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=z73.object({title:z73.string().optional(),readOnlyHint:z73.boolean().optional(),destructiveHint:z73.boolean().optional(),idempotentHint:z73.boolean().optional(),openWorldHint:z73.boolean().optional()}),ToolExecutionSchema=z73.object({taskSupport:z73.enum(["required","optional","forbidden"]).optional()}),ToolSchema=z73.object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:z73.string().optional(),inputSchema:z73.object({type:z73.literal("object"),properties:z73.record(z73.string(),AssertObjectSchema).optional(),required:z73.array(z73.string()).optional()}).catchall(z73.unknown()),outputSchema:z73.object({type:z73.literal("object"),properties:z73.record(z73.string(),AssertObjectSchema).optional(),required:z73.array(z73.string()).optional()}).catchall(z73.unknown()).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:z73.record(z73.string(),z73.unknown()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:z73.literal("tools/list")}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:z73.array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:z73.array(ContentBlockSchema).default([]),structuredContent:z73.record(z73.string(),z73.unknown()).optional(),isError:z73.boolean().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:z73.unknown()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:z73.string(),arguments:z73.record(z73.string(),z73.unknown()).optional()}),CallToolRequestSchema=RequestSchema.extend({method:z73.literal("tools/call"),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:z73.literal("notifications/tools/list_changed"),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=z73.object({autoRefresh:z73.boolean().default(!0),debounceMs:z73.number().int().nonnegative().default(300)}),LoggingLevelSchema=z73.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema.extend({method:z73.literal("logging/setLevel"),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:z73.string().optional(),data:z73.unknown()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:z73.literal("notifications/message"),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=z73.object({name:z73.string().optional()}),ModelPreferencesSchema=z73.object({hints:z73.array(ModelHintSchema).optional(),costPriority:z73.number().min(0).max(1).optional(),speedPriority:z73.number().min(0).max(1).optional(),intelligencePriority:z73.number().min(0).max(1).optional()}),ToolChoiceSchema=z73.object({mode:z73.enum(["auto","required","none"]).optional()}),ToolResultContentSchema=z73.object({type:z73.literal("tool_result"),toolUseId:z73.string().describe("The unique identifier for the corresponding tool call."),content:z73.array(ContentBlockSchema).default([]),structuredContent:z73.object({}).loose().optional(),isError:z73.boolean().optional(),_meta:z73.record(z73.string(),z73.unknown()).optional()}),SamplingContentSchema=z73.discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema]),SamplingMessageContentBlockSchema=z73.discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=z73.object({role:RoleSchema,content:z73.union([SamplingMessageContentBlockSchema,z73.array(SamplingMessageContentBlockSchema)]),_meta:z73.record(z73.string(),z73.unknown()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:z73.array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:z73.string().optional(),includeContext:z73.enum(["none","thisServer","allServers"]).optional(),temperature:z73.number().optional(),maxTokens:z73.number().int(),stopSequences:z73.array(z73.string()).optional(),metadata:AssertObjectSchema.optional(),tools:z73.array(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema.extend({method:z73.literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema.extend({model:z73.string(),stopReason:z73.optional(z73.enum(["endTurn","stopSequence","maxTokens"]).or(z73.string())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:z73.string(),stopReason:z73.optional(z73.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(z73.string())),role:RoleSchema,content:z73.union([SamplingMessageContentBlockSchema,z73.array(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=z73.object({type:z73.literal("boolean"),title:z73.string().optional(),description:z73.string().optional(),default:z73.boolean().optional()}),StringSchemaSchema=z73.object({type:z73.literal("string"),title:z73.string().optional(),description:z73.string().optional(),minLength:z73.number().optional(),maxLength:z73.number().optional(),format:z73.enum(["email","uri","date","date-time"]).optional(),default:z73.string().optional()}),NumberSchemaSchema=z73.object({type:z73.enum(["number","integer"]),title:z73.string().optional(),description:z73.string().optional(),minimum:z73.number().optional(),maximum:z73.number().optional(),default:z73.number().optional()}),UntitledSingleSelectEnumSchemaSchema=z73.object({type:z73.literal("string"),title:z73.string().optional(),description:z73.string().optional(),enum:z73.array(z73.string()),default:z73.string().optional()}),TitledSingleSelectEnumSchemaSchema=z73.object({type:z73.literal("string"),title:z73.string().optional(),description:z73.string().optional(),oneOf:z73.array(z73.object({const:z73.string(),title:z73.string()})),default:z73.string().optional()}),LegacyTitledEnumSchemaSchema=z73.object({type:z73.literal("string"),title:z73.string().optional(),description:z73.string().optional(),enum:z73.array(z73.string()),enumNames:z73.array(z73.string()).optional(),default:z73.string().optional()}),SingleSelectEnumSchemaSchema=z73.union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=z73.object({type:z73.literal("array"),title:z73.string().optional(),description:z73.string().optional(),minItems:z73.number().optional(),maxItems:z73.number().optional(),items:z73.object({type:z73.literal("string"),enum:z73.array(z73.string())}),default:z73.array(z73.string()).optional()}),TitledMultiSelectEnumSchemaSchema=z73.object({type:z73.literal("array"),title:z73.string().optional(),description:z73.string().optional(),minItems:z73.number().optional(),maxItems:z73.number().optional(),items:z73.object({anyOf:z73.array(z73.object({const:z73.string(),title:z73.string()}))}),default:z73.array(z73.string()).optional()}),MultiSelectEnumSchemaSchema=z73.union([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=z73.union([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=z73.union([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:z73.literal("form").optional(),message:z73.string(),requestedSchema:z73.object({type:z73.literal("object"),properties:z73.record(z73.string(),PrimitiveSchemaDefinitionSchema),required:z73.array(z73.string()).optional()})}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:z73.literal("url"),message:z73.string(),elicitationId:z73.string(),url:z73.string().url()}),ElicitRequestParamsSchema=z73.union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:z73.literal("elicitation/create"),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:z73.string()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:z73.literal("notifications/elicitation/complete"),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:z73.enum(["accept","decline","cancel"]),content:z73.preprocess(val2=>val2===null?void 0:val2,z73.record(z73.string(),z73.union([z73.string(),z73.number(),z73.boolean(),z73.array(z73.string())])).optional())}),ResourceTemplateReferenceSchema=z73.object({type:z73.literal("ref/resource"),uri:z73.string()});var PromptReferenceSchema=z73.object({type:z73.literal("ref/prompt"),name:z73.string()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:z73.union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:z73.object({name:z73.string(),value:z73.string()}),context:z73.object({arguments:z73.record(z73.string(),z73.string()).optional()}).optional()}),CompleteRequestSchema=RequestSchema.extend({method:z73.literal("completion/complete"),params:CompleteRequestParamsSchema});function assertCompleteRequestPrompt(request){if(request.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`)}__name(assertCompleteRequestPrompt,"assertCompleteRequestPrompt");function assertCompleteRequestResourceTemplate(request){if(request.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`)}__name(assertCompleteRequestResourceTemplate,"assertCompleteRequestResourceTemplate");var CompleteResultSchema=ResultSchema.extend({completion:z73.looseObject({values:z73.array(z73.string()).max(100),total:z73.optional(z73.number().int()),hasMore:z73.optional(z73.boolean())})}),RootSchema=z73.object({uri:z73.string().startsWith("file://"),name:z73.string().optional(),_meta:z73.record(z73.string(),z73.unknown()).optional()}),ListRootsRequestSchema=RequestSchema.extend({method:z73.literal("roots/list"),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema.extend({roots:z73.array(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:z73.literal("notifications/roots/list_changed"),params:NotificationsParamsSchema.optional()}),ClientRequestSchema=z73.union([PingRequestSchema,InitializeRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,CallToolRequestSchema,ListToolsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ClientNotificationSchema=z73.union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema,TaskStatusNotificationSchema]),ClientResultSchema=z73.union([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),ServerRequestSchema=z73.union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ServerNotificationSchema=z73.union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,TaskStatusNotificationSchema,ElicitationCompleteNotificationSchema]),ServerResultSchema=z73.union([EmptyResultSchema,InitializeResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),McpError=class _McpError extends Error{static{__name(this,"McpError")}constructor(code2,message,data2){super(`MCP error ${code2}: ${message}`),this.code=code2,this.data=data2,this.name="McpError"}static fromError(code2,message,data2){if(code2===ErrorCode.UrlElicitationRequired&&data2){let errorData=data2;if(errorData.elicitations)return new UrlElicitationRequiredError(errorData.elicitations,message)}return new _McpError(code2,message,data2)}},UrlElicitationRequiredError=class extends McpError{static{__name(this,"UrlElicitationRequiredError")}constructor(elicitations,message=`URL elicitation${elicitations.length>1?"s":""} required`){super(ErrorCode.UrlElicitationRequired,message,{elicitations})}get elicitations(){return this.data?.elicitations??[]}};function isTerminal(status){return status==="completed"||status==="failed"||status==="cancelled"}__name(isTerminal,"isTerminal");import*as z4mini2 from"zod/v4-mini";var ignoreOverride=Symbol("Let zodToJsonSchema decide on which parser to use");var defaultOptions={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},getDefaultOptions=__name(options=>typeof options=="string"?{...defaultOptions,name:options}:{...defaultOptions,...options},"getDefaultOptions");var getRefs=__name(options=>{let _options=getDefaultOptions(options),currentPath=_options.name!==void 0?[..._options.basePath,_options.definitionPath,_options.name]:_options.basePath;return{..._options,flags:{hasReferencedOpenAiAnyType:!1},currentPath,propertyPath:void 0,seen:new Map(Object.entries(_options.definitions).map(([name,def])=>[def._def,{def:def._def,path:[..._options.basePath,_options.definitionPath,name],jsonSchema:void 0}]))}},"getRefs");function addErrorMessage(res,key,errorMessage3,refs){refs?.errorMessages&&errorMessage3&&(res.errorMessage={...res.errorMessage,[key]:errorMessage3})}__name(addErrorMessage,"addErrorMessage");function setResponseValueAndErrors(res,key,value,errorMessage3,refs){res[key]=value,addErrorMessage(res,key,errorMessage3,refs)}__name(setResponseValueAndErrors,"setResponseValueAndErrors");var getRelativePath=__name((pathA,pathB)=>{let i=0;for(;i<pathA.length&&i<pathB.length&&pathA[i]===pathB[i];i++);return[(pathA.length-i).toString(),...pathB.slice(i)].join("/")},"getRelativePath");import{ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3}from"zod/v3";function parseAnyDef(refs){if(refs.target!=="openAi")return{};let anyDefinitionPath=[...refs.basePath,refs.definitionPath,refs.openAiAnyTypeName];return refs.flags.hasReferencedOpenAiAnyType=!0,{$ref:refs.$refStrategy==="relative"?getRelativePath(anyDefinitionPath,refs.currentPath):anyDefinitionPath.join("/")}}__name(parseAnyDef,"parseAnyDef");import{ZodFirstPartyTypeKind}from"zod/v3";function parseArrayDef(def,refs){let res={type:"array"};return def.type?._def&&def.type?._def?.typeName!==ZodFirstPartyTypeKind.ZodAny&&(res.items=parseDef(def.type._def,{...refs,currentPath:[...refs.currentPath,"items"]})),def.minLength&&setResponseValueAndErrors(res,"minItems",def.minLength.value,def.minLength.message,refs),def.maxLength&&setResponseValueAndErrors(res,"maxItems",def.maxLength.value,def.maxLength.message,refs),def.exactLength&&(setResponseValueAndErrors(res,"minItems",def.exactLength.value,def.exactLength.message,refs),setResponseValueAndErrors(res,"maxItems",def.exactLength.value,def.exactLength.message,refs)),res}__name(parseArrayDef,"parseArrayDef");function parseBigintDef(def,refs){let res={type:"integer",format:"int64"};if(!def.checks)return res;for(let check of def.checks)switch(check.kind){case"min":refs.target==="jsonSchema7"?check.inclusive?setResponseValueAndErrors(res,"minimum",check.value,check.message,refs):setResponseValueAndErrors(res,"exclusiveMinimum",check.value,check.message,refs):(check.inclusive||(res.exclusiveMinimum=!0),setResponseValueAndErrors(res,"minimum",check.value,check.message,refs));break;case"max":refs.target==="jsonSchema7"?check.inclusive?setResponseValueAndErrors(res,"maximum",check.value,check.message,refs):setResponseValueAndErrors(res,"exclusiveMaximum",check.value,check.message,refs):(check.inclusive||(res.exclusiveMaximum=!0),setResponseValueAndErrors(res,"maximum",check.value,check.message,refs));break;case"multipleOf":setResponseValueAndErrors(res,"multipleOf",check.value,check.message,refs);break}return res}__name(parseBigintDef,"parseBigintDef");function parseBooleanDef(){return{type:"boolean"}}__name(parseBooleanDef,"parseBooleanDef");function parseBrandedDef(_def,refs){return parseDef(_def.type._def,refs)}__name(parseBrandedDef,"parseBrandedDef");var parseCatchDef=__name((def,refs)=>parseDef(def.innerType._def,refs),"parseCatchDef");function parseDateDef(def,refs,overrideDateStrategy){let strategy=overrideDateStrategy??refs.dateStrategy;if(Array.isArray(strategy))return{anyOf:strategy.map((item,i)=>parseDateDef(def,refs,item))};switch(strategy){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return integerDateParser(def,refs)}}__name(parseDateDef,"parseDateDef");var integerDateParser=__name((def,refs)=>{let res={type:"integer",format:"unix-time"};if(refs.target==="openApi3")return res;for(let check of def.checks)switch(check.kind){case"min":setResponseValueAndErrors(res,"minimum",check.value,check.message,refs);break;case"max":setResponseValueAndErrors(res,"maximum",check.value,check.message,refs);break}return res},"integerDateParser");function parseDefaultDef(_def,refs){return{...parseDef(_def.innerType._def,refs),default:_def.defaultValue()}}__name(parseDefaultDef,"parseDefaultDef");function parseEffectsDef(_def,refs){return refs.effectStrategy==="input"?parseDef(_def.schema._def,refs):parseAnyDef(refs)}__name(parseEffectsDef,"parseEffectsDef");function parseEnumDef(def){return{type:"string",enum:Array.from(def.values)}}__name(parseEnumDef,"parseEnumDef");var isJsonSchema7AllOfType=__name(type=>"type"in type&&type.type==="string"?!1:"allOf"in type,"isJsonSchema7AllOfType");function parseIntersectionDef(def,refs){let allOf=[parseDef(def.left._def,{...refs,currentPath:[...refs.currentPath,"allOf","0"]}),parseDef(def.right._def,{...refs,currentPath:[...refs.currentPath,"allOf","1"]})].filter(x=>!!x),unevaluatedProperties=refs.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,mergedAllOf=[];return allOf.forEach(schema=>{if(isJsonSchema7AllOfType(schema))mergedAllOf.push(...schema.allOf),schema.unevaluatedProperties===void 0&&(unevaluatedProperties=void 0);else{let nestedSchema=schema;if("additionalProperties"in schema&&schema.additionalProperties===!1){let{additionalProperties,...rest}=schema;nestedSchema=rest}else unevaluatedProperties=void 0;mergedAllOf.push(nestedSchema)}}),mergedAllOf.length?{allOf:mergedAllOf,...unevaluatedProperties}:void 0}__name(parseIntersectionDef,"parseIntersectionDef");function parseLiteralDef(def,refs){let parsedType=typeof def.value;return parsedType!=="bigint"&&parsedType!=="number"&&parsedType!=="boolean"&&parsedType!=="string"?{type:Array.isArray(def.value)?"array":"object"}:refs.target==="openApi3"?{type:parsedType==="bigint"?"integer":parsedType,enum:[def.value]}:{type:parsedType==="bigint"?"integer":parsedType,const:def.value}}__name(parseLiteralDef,"parseLiteralDef");import{ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2}from"zod/v3";var emojiRegex,zodPatterns={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:__name(()=>(emojiRegex===void 0&&(emojiRegex=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),emojiRegex),"emoji"),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function parseStringDef(def,refs){let res={type:"string"};if(def.checks)for(let check of def.checks)switch(check.kind){case"min":setResponseValueAndErrors(res,"minLength",typeof res.minLength=="number"?Math.max(res.minLength,check.value):check.value,check.message,refs);break;case"max":setResponseValueAndErrors(res,"maxLength",typeof res.maxLength=="number"?Math.min(res.maxLength,check.value):check.value,check.message,refs);break;case"email":switch(refs.emailStrategy){case"format:email":addFormat(res,"email",check.message,refs);break;case"format:idn-email":addFormat(res,"idn-email",check.message,refs);break;case"pattern:zod":addPattern(res,zodPatterns.email,check.message,refs);break}break;case"url":addFormat(res,"uri",check.message,refs);break;case"uuid":addFormat(res,"uuid",check.message,refs);break;case"regex":addPattern(res,check.regex,check.message,refs);break;case"cuid":addPattern(res,zodPatterns.cuid,check.message,refs);break;case"cuid2":addPattern(res,zodPatterns.cuid2,check.message,refs);break;case"startsWith":addPattern(res,RegExp(`^${escapeLiteralCheckValue(check.value,refs)}`),check.message,refs);break;case"endsWith":addPattern(res,RegExp(`${escapeLiteralCheckValue(check.value,refs)}$`),check.message,refs);break;case"datetime":addFormat(res,"date-time",check.message,refs);break;case"date":addFormat(res,"date",check.message,refs);break;case"time":addFormat(res,"time",check.message,refs);break;case"duration":addFormat(res,"duration",check.message,refs);break;case"length":setResponseValueAndErrors(res,"minLength",typeof res.minLength=="number"?Math.max(res.minLength,check.value):check.value,check.message,refs),setResponseValueAndErrors(res,"maxLength",typeof res.maxLength=="number"?Math.min(res.maxLength,check.value):check.value,check.message,refs);break;case"includes":{addPattern(res,RegExp(escapeLiteralCheckValue(check.value,refs)),check.message,refs);break}case"ip":{check.version!=="v6"&&addFormat(res,"ipv4",check.message,refs),check.version!=="v4"&&addFormat(res,"ipv6",check.message,refs);break}case"base64url":addPattern(res,zodPatterns.base64url,check.message,refs);break;case"jwt":addPattern(res,zodPatterns.jwt,check.message,refs);break;case"cidr":{check.version!=="v6"&&addPattern(res,zodPatterns.ipv4Cidr,check.message,refs),check.version!=="v4"&&addPattern(res,zodPatterns.ipv6Cidr,check.message,refs);break}case"emoji":addPattern(res,zodPatterns.emoji(),check.message,refs);break;case"ulid":{addPattern(res,zodPatterns.ulid,check.message,refs);break}case"base64":{switch(refs.base64Strategy){case"format:binary":{addFormat(res,"binary",check.message,refs);break}case"contentEncoding:base64":{setResponseValueAndErrors(res,"contentEncoding","base64",check.message,refs);break}case"pattern:zod":{addPattern(res,zodPatterns.base64,check.message,refs);break}}break}case"nanoid":addPattern(res,zodPatterns.nanoid,check.message,refs);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return res}__name(parseStringDef,"parseStringDef");function escapeLiteralCheckValue(literal2,refs){return refs.patternStrategy==="escape"?escapeNonAlphaNumeric(literal2):literal2}__name(escapeLiteralCheckValue,"escapeLiteralCheckValue");var ALPHA_NUMERIC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function escapeNonAlphaNumeric(source){let result="";for(let i=0;i<source.length;i++)ALPHA_NUMERIC.has(source[i])||(result+="\\"),result+=source[i];return result}__name(escapeNonAlphaNumeric,"escapeNonAlphaNumeric");function addFormat(schema,value,message,refs){schema.format||schema.anyOf?.some(x=>x.format)?(schema.anyOf||(schema.anyOf=[]),schema.format&&(schema.anyOf.push({format:schema.format,...schema.errorMessage&&refs.errorMessages&&{errorMessage:{format:schema.errorMessage.format}}}),delete schema.format,schema.errorMessage&&(delete schema.errorMessage.format,Object.keys(schema.errorMessage).length===0&&delete schema.errorMessage)),schema.anyOf.push({format:value,...message&&refs.errorMessages&&{errorMessage:{format:message}}})):setResponseValueAndErrors(schema,"format",value,message,refs)}__name(addFormat,"addFormat");function addPattern(schema,regex,message,refs){schema.pattern||schema.allOf?.some(x=>x.pattern)?(schema.allOf||(schema.allOf=[]),schema.pattern&&(schema.allOf.push({pattern:schema.pattern,...schema.errorMessage&&refs.errorMessages&&{errorMessage:{pattern:schema.errorMessage.pattern}}}),delete schema.pattern,schema.errorMessage&&(delete schema.errorMessage.pattern,Object.keys(schema.errorMessage).length===0&&delete schema.errorMessage)),schema.allOf.push({pattern:stringifyRegExpWithFlags(regex,refs),...message&&refs.errorMessages&&{errorMessage:{pattern:message}}})):setResponseValueAndErrors(schema,"pattern",stringifyRegExpWithFlags(regex,refs),message,refs)}__name(addPattern,"addPattern");function stringifyRegExpWithFlags(regex,refs){if(!refs.applyRegexFlags||!regex.flags)return regex.source;let flags={i:regex.flags.includes("i"),m:regex.flags.includes("m"),s:regex.flags.includes("s")},source=flags.i?regex.source.toLowerCase():regex.source,pattern="",isEscaped2=!1,inCharGroup=!1,inCharRange=!1;for(let i=0;i<source.length;i++){if(isEscaped2){pattern+=source[i],isEscaped2=!1;continue}if(flags.i){if(inCharGroup){if(source[i].match(/[a-z]/)){inCharRange?(pattern+=source[i],pattern+=`${source[i-2]}-${source[i]}`.toUpperCase(),inCharRange=!1):source[i+1]==="-"&&source[i+2]?.match(/[a-z]/)?(pattern+=source[i],inCharRange=!0):pattern+=`${source[i]}${source[i].toUpperCase()}`;continue}}else if(source[i].match(/[a-z]/)){pattern+=`[${source[i]}${source[i].toUpperCase()}]`;continue}}if(flags.m){if(source[i]==="^"){pattern+=`(^|(?<=[\r
|
|
1355
|
+
Remote config and local checkout are synchronized.`}__name(renderMutationResult,"renderMutationResult");async function runLocaleMutation(locale,options,cmd,spec){let command=`locales ${spec.operation}`;if(rejectMissingConfirmation(spec,options))return;let cwd=resolveProjectCwd(options.cwd),{ctx,api}=await bootstrapProjectCommand(options,cmd,{requireBranch:!0,refuseReadOnly:!0});await requireOperation(spec.capability,{projectId:ctx.projectId,env:ctx.env});let plan;try{let remote=await api.getGitRemote(ctx.projectId,ctx.env);await ensureFimoRemote(cwd,remote.url),plan=await planLocaleMutationCheckout({cwd,remoteBranch:remote.branch,configPath:resolveProjectConfigPath(cwd)})}catch(error){if(emitPreflightError(command,error)||emitApiError(command,error))return;throw error}if(!await confirmMutation(spec,locale,ctx.env,plan,options))return;try{await applyLocaleMutationCheckoutPlan(plan)}catch(error){if(emitPreflightError(command,error))return;throw error}let response;try{response=await spec.mutate(api,ctx.projectId,locale)}catch(error){if(emitApiError(command,error))return;throw error}let sync=await synchronizeLocaleMutationCheckout({cwd,remoteBranch:plan.state.remoteBranch}),data2={operation:spec.operation,env:ctx.env,applied:!0,...response,...sync.status==="required"?{code:"LOCALE_APPLIED_SYNC_REQUIRED"}:{},sync};ui.result({command,data:data2,render:__name(()=>renderMutationResult(spec,response,ctx.env,sync),"render")}),sync.status==="required"&&(process.exitCode=2)}__name(runLocaleMutation,"runLocaleMutation");async function localesAddCommand(locale,options,cmd){return runLocaleMutation(locale,options,cmd,{operation:"add",capability:"i18n.create",verb:"Add",destructive:!1,mutate:__name((api,projectId,value)=>api.addProjectLocale(projectId,{locale:value}),"mutate")})}__name(localesAddCommand,"localesAddCommand");async function localesSetDefaultCommand(locale,options,cmd){return runLocaleMutation(locale,options,cmd,{operation:"set-default",capability:"i18n.update",verb:"Set the default to",destructive:!1,mutate:__name((api,projectId,value)=>api.setProjectDefaultLocale(projectId,{locale:value}),"mutate")})}__name(localesSetDefaultCommand,"localesSetDefaultCommand");async function localesRemoveCommand(locale,options,cmd){return runLocaleMutation(locale,options,cmd,{operation:"remove",capability:"i18n.delete",verb:"Remove",destructive:!0,mutate:__name((api,projectId,value)=>api.removeProjectLocale(projectId,value),"mutate")})}__name(localesRemoveCommand,"localesRemoveCommand");function registerLocalesCommands(program2){let locales=program2.command("locales").description("Manage project locale lifecycle");locales.command("list").description("List configured locales and stored content coverage").option("-C, --cwd <dir>","Project directory").action(localesListCommand),locales.command("add <locale>").description("Add a locale to the selected Branch").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Apply without an interactive confirmation").action(localesAddCommand),locales.command("set-default <locale>").description("Set the default locale for the selected Branch").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Apply without an interactive confirmation").action(localesSetDefaultCommand),locales.command("remove <locale>").description("Remove a locale and permanently delete its stored content").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Apply without an interactive confirmation").action(localesRemoveCommand)}__name(registerLocalesCommands,"registerLocalesCommands");init_login();init_dist();init_auth();init_config();async function logoutCommand(){let cfg=loadConfig(),creds=readCredentials(cfg);if(!creds?.access_token){ui.info({command:"logout",message:"Already signed out."});return}clearCredentials(cfg),ui.ok({command:"logout",headline:`Signed out${creds.user?.email?` (${creds.user.email})`:""}.`,details:creds.user?.email?{email:creds.user.email}:void 0})}__name(logoutCommand,"logoutCommand");init_esm();import{z as z75}from"zod";var projectScopeShape={projectId:z75.uuid().optional().describe("The Fimo project ID. Optional when the MCP server is already bound to a project.")},envScopeShape={...projectScopeShape,env:EnvSchema.optional().describe("The environment name, for example 'main' or 'agents/content-review'. Optional when the server is bound to an environment.")},typeNameField=z75.string().min(1).max(255).describe("The content type name, for example BlogPost."),localeField=z75.string().min(1).optional().describe("The locale to read or write."),entryDataField=z75.record(z75.string(),z75.unknown()).describe("Entry field values, keyed by field name as declared in the content schema."),filePathField=z75.string().min(1).max(1024).describe("File path relative to the project root."),labelKeyField=z75.string().min(1).max(255).describe("The translation key, for example home.hero.title."),assetIdField=z75.uuid().describe("The Fimo media asset ID."),formIdField=z75.string().min(1).max(255).describe("The Fimo form ID."),formFieldsField=z75.record(z75.string().min(1),z75.unknown()).describe("Form fields keyed by field name; Fimo validates each field definition."),formContentShape={name:z75.string().min(1).max(255).describe("Stable form name."),label:z75.string().min(1).max(255).describe("Human-readable form label."),fields:formFieldsField},mediaGenerationSchema=z75.object({...envScopeShape,task:z75.string().min(1).optional().describe("A stable task, for example 'image.generate' or 'video.generate'."),model:z75.string().min(1).optional().describe("An explicit model ID, for example 'fal/...'."),options:z75.record(z75.string(),z75.unknown()).describe("Task or model options, such as prompt, quality, aspect ratio, and source assets."),name:z75.string().min(1).max(255).optional().describe("Optional name for the generated asset."),parentId:z75.uuid().nullable().optional().describe("Optional media-library folder ID."),altText:z75.string().max(2e3).optional().describe("Optional alternative text for the generated asset."),caption:z75.string().max(2e3).optional().describe("Optional caption for the generated asset.")}).superRefine((value,context)=>{!!value.task==!!value.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model.",path:["task"]})});function tenantPath(scope,suffix){return`/tenant/${encodeURIComponent(scope.projectId)}/envs/${encodeEnvPathSegment(scope.env)}${suffix}`}__name(tenantPath,"tenantPath");function managementProjectPath(scope,suffix){return`/management/projects/${encodeURIComponent(scope.projectId)}${suffix}`}__name(managementProjectPath,"managementProjectPath");function managementEnvPath(scope,suffix){return managementProjectPath(scope,`/envs/${encodeURIComponent(scope.env)}${suffix}`)}__name(managementEnvPath,"managementEnvPath");function addQuery(path49,query){let params=new URLSearchParams;for(let[key,value]of Object.entries(query))if(value!==void 0){if(Array.isArray(value)){value.length>0&¶ms.set(key,value.join(","));continue}params.set(key,String(value))}let queryString=params.toString();return queryString?`${path49}?${queryString}`:path49}__name(addQuery,"addQuery");var mcpToolCatalog={whoami:{description:"Return the authenticated Fimo user identity.",annotations:{readOnlyHint:!0},scope:"none",accessScope:"read",inputSchema:z75.object({})},projects_list:{description:"List the Fimo projects the authenticated user can access.",annotations:{readOnlyHint:!0},scope:"none",accessScope:"read",inputSchema:z75.object({}),buildRequest:__name(()=>({method:"GET",path:"/management/projects"}),"buildRequest")},envs_list:{description:"List the environments of a project.",annotations:{readOnlyHint:!0},scope:"project",accessScope:"read",inputSchema:z75.object(projectScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:managementProjectPath(scope,"/envs")}),"buildRequest")},schemas_list:{description:"List content schemas in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.schema.list",inputSchema:z75.object(envScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:tenantPath(scope,"/schema")}),"buildRequest")},entries_list:{description:"List entries for one content type in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.list",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,locale:localeField,limit:z75.number().int().min(1).max(100).optional().describe("Maximum number of records to return."),offset:z75.number().int().min(0).optional().describe("Number of records to skip.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}`),{locale:input.locale,limit:input.limit,offset:input.offset})}),"buildRequest")},entries_get:{description:"Read one entry by ID from a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.get",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,id:z75.uuid().describe("The entry ID."),locale:localeField,populate:z75.array(z75.string().min(1)).max(50).optional().describe("Reference fields to populate."),localeFallbacks:z75.boolean().optional().describe("Use the configured default locale when needed.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/${encodeURIComponent(input.id)}`),{locale:input.locale,populate:input.populate,localeFallbacks:input.localeFallbacks})}),"buildRequest")},entries_search:{description:"Search entries across content types in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.list",inputSchema:z75.object({...envScopeShape,search:z75.string().min(1).optional().describe("A text search applied to entry content."),locale:localeField,limit:z75.number().int().min(1).max(100).optional().describe("Maximum number of records to return."),offset:z75.number().int().min(0).optional().describe("Number of records to skip.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,"/entries"),{search:input.search,locale:input.locale,limit:input.limit,offset:input.offset})}),"buildRequest")},entries_create:{description:"Create one entry of a content type in a project environment.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.create",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,data:entryDataField,locale:localeField,documentId:z75.string().min(1).optional().describe("Attach the new entry to an existing document (adds a locale variant).")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}`),body:{data:input.data,locale:input.locale,documentId:input.documentId}}),"buildRequest")},entries_update:{description:"Update one entry by ID in a project environment.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.update",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,id:z75.uuid().describe("The entry ID."),data:entryDataField,locale:localeField}),buildRequest:__name((input,scope)=>({method:"PUT",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/${encodeURIComponent(input.id)}`),{locale:input.locale}),body:{data:input.data}}),"buildRequest")},entries_delete:{description:"Delete one entry by ID in a project environment.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"cms.delete",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,id:z75.uuid().describe("The entry ID."),locale:localeField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:addQuery(tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/${encodeURIComponent(input.id)}`),{locale:input.locale})}),"buildRequest")},entries_bulk_create:{description:`Create up to ${MAX_BULK_ENTRIES} entries of one content type in a project environment.`,annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.bulk_create",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,entries:z75.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES).describe("Entries to create.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/bulk-create`),body:{entries:input.entries}}),"buildRequest")},entries_bulk_update:{description:`Update up to ${MAX_BULK_ENTRIES} entries by IDs, a bounded filter, or per-entry updates.`,annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.bulk_update",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,selection:z75.union([z75.object({ids:z75.array(z75.uuid()).min(1).max(MAX_BULK_ENTRIES)}),z75.object({where:EntryWhereSchema}),z75.object({updates:z75.array(z75.object({id:z75.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),body:EntryMutationBodySchema.optional().describe("Shared update body for ids or where selections.")}).superRefine((value,context)=>{let isPerEntry="updates"in value.selection;isPerEntry&&value.body!==void 0&&context.addIssue({code:"custom",message:"Do not pass body with per-entry updates.",path:["body"]}),!isPerEntry&&value.body===void 0&&context.addIssue({code:"custom",message:"Pass body with ids or where selections.",path:["body"]})}),buildRequest:__name((input,scope)=>{let{selection,body}=input;return{method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/bulk-update`),body:"updates"in selection?selection:{...selection,body}}},"buildRequest")},entries_bulk_delete:{description:`Delete up to ${MAX_BULK_ENTRIES} entries by IDs or a bounded filter.`,annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"cms.bulk_delete",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,selection:z75.union([z75.object({ids:z75.array(z75.uuid()).min(1).max(MAX_BULK_ENTRIES)}),z75.object({where:EntryWhereSchema})]),locale:localeField}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/entries/${encodeURIComponent(input.typeName)}/bulk-delete`),body:{...input.selection,locale:input.locale}}),"buildRequest")},singles_get:{description:"Read the document-scoped value of a Single content type.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"cms.get",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,locale:localeField,populate:z75.array(z75.string().min(1)).max(50).optional().describe("Reference fields to populate.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/documents/${encodeURIComponent(input.typeName)}`),{locale:input.locale,populate:input.populate})}),"buildRequest")},singles_update:{description:"Update the document-scoped value of a Single content type.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"cms.update",inputSchema:z75.object({...envScopeShape,typeName:typeNameField,data:entryDataField,locale:localeField}),buildRequest:__name((input,scope)=>({method:"PUT",path:addQuery(tenantPath(scope,`/documents/${encodeURIComponent(input.typeName)}`),{locale:input.locale}),body:{data:input.data}}),"buildRequest")},labels_list:{description:'List localized labels in a project environment. Pass locale "*" to group all locales.',annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"i18n.list",inputSchema:z75.object({...envScopeShape,locale:z75.string().min(1).optional().describe('Locale code, or "*" for every configured locale.')}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,"/labels"),{locale:input.locale})}),"buildRequest")},labels_get:{description:"Read one localized label by locale and key.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"i18n.get",inputSchema:z75.object({...envScopeShape,locale:z75.string().min(1).describe("Locale code."),key:labelKeyField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/labels/${encodeURIComponent(input.locale)}/${encodeURIComponent(input.key)}`)}),"buildRequest")},labels_set:{description:"Create or set one localized label.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"i18n.create",inputSchema:z75.object({...envScopeShape,key:labelKeyField,value:z75.string().max(1e4).describe("Localized label text."),locale:localeField}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/labels"),body:{key:input.key,value:input.value,locale:input.locale}}),"buildRequest")},labels_set_many:{description:"Set many localized labels in one bounded request.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"i18n.update",inputSchema:z75.object({...envScopeShape,records:z75.array(z75.object({key:labelKeyField,value:z75.string().max(1e4),locale:localeField})).min(1).max(500).describe("Localized labels to set.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/labels/sync"),body:{created:input.records,updated:[],deleted:[]}}),"buildRequest")},labels_delete:{description:"Delete one localized label.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"i18n.delete",inputSchema:z75.object({...envScopeShape,locale:z75.string().min(1).describe("Locale code."),key:labelKeyField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:tenantPath(scope,`/labels/${encodeURIComponent(input.locale)}/${encodeURIComponent(input.key)}`)}),"buildRequest")},assets_list:{description:"List media assets and folders, including public URLs for files the user can access.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"assets.list",inputSchema:z75.object({...envScopeShape,parentId:z75.uuid().optional().describe("Limit results to one media-library folder."),search:z75.string().max(200).optional(),type:z75.enum(["file","folder"]).optional(),mimePrefix:z75.string().max(50).optional().describe("MIME prefix such as image/ or video/."),sortBy:z75.enum(["name","createdAt","updatedAt","fileSize","type"]).optional(),sortDirection:z75.enum(["asc","desc"]).optional(),includePath:z75.boolean().optional(),excludeHidden:z75.boolean().optional(),limit:z75.number().int().min(1).max(100).optional(),offset:z75.number().int().min(0).optional()}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,"/assets"),{parentId:input.parentId,search:input.search,type:input.type,mimePrefix:input.mimePrefix,sortBy:input.sortBy,sortDirection:input.sortDirection,includePath:input.includePath,excludeHidden:input.excludeHidden,limit:input.limit,offset:input.offset})}),"buildRequest")},assets_get:{description:"Read one media asset or folder, including its public URL when it is a file.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"assets.get",inputSchema:z75.object({...envScopeShape,id:assetIdField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/assets/${encodeURIComponent(input.id)}`)}),"buildRequest")},assets_generate:{description:"Generate an image or video asset with Fimo AI credits and save it to the media library.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"assets.generate",inputSchema:mediaGenerationSchema,buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/assets/generate"),body:{...input.task?{task:input.task}:{model:input.model},options:input.options,name:input.name,parentId:input.parentId,altText:input.altText,caption:input.caption}}),"buildRequest")},assets_create_folder:{description:"Create a media-library folder.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"assets.create_folder",inputSchema:z75.object({...envScopeShape,name:z75.string().min(1).max(255).describe("Folder name."),parentId:z75.uuid().nullable().optional().describe("Optional parent folder ID.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/assets/folders"),body:{name:input.name,parentId:input.parentId}}),"buildRequest")},assets_move:{description:"Move a media asset or folder to another media-library folder.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"assets.move",inputSchema:z75.object({...envScopeShape,id:assetIdField,parentId:z75.uuid().nullable().describe("Destination folder ID, or null for the library root.")}),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,`/assets/${encodeURIComponent(input.id)}/move`),body:{parentId:input.parentId}}),"buildRequest")},assets_delete:{description:"Delete a media asset or folder.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"assets.delete",inputSchema:z75.object({...envScopeShape,id:assetIdField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:tenantPath(scope,`/assets/${encodeURIComponent(input.id)}`)}),"buildRequest")},forms_list:{description:"List the forms configured in a project environment.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.list",inputSchema:z75.object(envScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:tenantPath(scope,"/forms")}),"buildRequest")},forms_get:{description:"Read one form definition.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.get",inputSchema:z75.object({...envScopeShape,id:formIdField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}`)}),"buildRequest")},forms_create:{description:"Create a form definition. Email notification settings stay in the Fimo UI.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"forms.push",inputSchema:z75.object({...envScopeShape,...formContentShape}).strict(),buildRequest:__name((input,scope)=>({method:"POST",path:tenantPath(scope,"/forms"),body:{name:input.name,label:input.label,fields:input.fields}}),"buildRequest")},forms_update:{description:"Update the name, label, or fields of one form definition.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"forms.push",inputSchema:z75.object({...envScopeShape,id:formIdField,...z75.object(formContentShape).partial().shape}).strict(),buildRequest:__name((input,scope)=>({method:"PUT",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}`),body:{name:input.name,label:input.label,fields:input.fields}}),"buildRequest")},forms_delete:{description:"Delete one form definition.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"forms.delete",inputSchema:z75.object({...envScopeShape,id:formIdField}),buildRequest:__name((input,scope)=>({method:"DELETE",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}`)}),"buildRequest")},forms_submissions_list:{description:"List submissions for one form.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.list",inputSchema:z75.object({...envScopeShape,id:formIdField,limit:z75.number().int().min(1).max(100).optional(),offset:z75.number().int().min(0).optional(),searchQuery:z75.string().max(200).optional(),sortDirection:z75.enum(["asc","desc"]).optional()}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(tenantPath(scope,`/forms/${encodeURIComponent(input.id)}/submissions`),{limit:input.limit,offset:input.offset,searchQuery:input.searchQuery,sortDirection:input.sortDirection})}),"buildRequest")},forms_submission_get:{description:"Read one submission for a form.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.get",inputSchema:z75.object({...envScopeShape,id:formIdField,submissionId:z75.string().min(1).max(255).describe("The submission ID.")}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}/submissions/${encodeURIComponent(input.submissionId)}`)}),"buildRequest")},forms_submissions_stats:{description:"Read aggregate submission statistics for a form.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"forms.get",inputSchema:z75.object({...envScopeShape,id:formIdField}),buildRequest:__name((input,scope)=>({method:"GET",path:tenantPath(scope,`/forms/${encodeURIComponent(input.id)}/submissions/stats`)}),"buildRequest")},files_read:{description:"Read one project file from an environment. Hidden and sensitive files (.env, credentials, keys, lockfiles, .git, build output) are unavailable.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"files.read",inputSchema:z75.object({...envScopeShape,path:filePathField}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(managementEnvPath(scope,"/files/file"),{path:input.path})}),"buildRequest")},files_glob:{description:"List project file paths in an environment, optionally filtered by a glob pattern.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"files.read",inputSchema:z75.object({...envScopeShape,pattern:z75.string().min(1).max(300).optional().describe("Glob pattern, for example 'src/**/*.tsx'."),limit:z75.number().int().min(1).max(2e3).optional().describe("Maximum number of paths to return.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(managementEnvPath(scope,"/files/paths"),{pattern:input.pattern,limit:input.limit})}),"buildRequest")},files_grep:{description:"Search project file contents in an environment with a regular expression. Matching is bounded (file count, bytes, match count) and complex patterns that exceed the time budget are rejected.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",operation:"files.read",inputSchema:z75.object({...envScopeShape,pattern:z75.string().min(1).max(200).describe("Regular expression to search for."),include:z75.string().min(1).max(300).optional().describe("Glob pattern limiting which files are searched."),caseInsensitive:z75.boolean().optional().describe("Case-insensitive matching."),maxMatches:z75.number().int().min(1).max(200).optional().describe("Maximum number of matches to return.")}),buildRequest:__name((input,scope)=>({method:"GET",path:addQuery(managementEnvPath(scope,"/files/grep"),{pattern:input.pattern,include:input.include,caseInsensitive:input.caseInsensitive,maxMatches:input.maxMatches})}),"buildRequest")},files_write:{description:"Create one project text file, or overwrite an existing one when overwrite is set. Fails if the file exists and overwrite is not set. The change lands as a reviewable commit on the environment branch.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"files.write",inputSchema:z75.object({...envScopeShape,path:filePathField,content:z75.string().max(262144).describe("Full UTF-8 text content of the file (256 KB max)."),overwrite:z75.boolean().optional().describe("Replace the file if it already exists. Without it, writing an existing path fails.")}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,"/files/write"),body:{path:input.path,content:input.content,overwrite:input.overwrite}}),"buildRequest")},files_edit:{description:"Edit one project file by exact string replacement. The old string must exist; set replaceAll when it occurs more than once. The change lands as a reviewable commit on the environment branch.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"write",operation:"files.write",inputSchema:z75.object({...envScopeShape,path:filePathField,oldString:z75.string().min(1).describe("Exact text to replace."),newString:z75.string().describe("Replacement text."),replaceAll:z75.boolean().optional().describe("Replace every occurrence instead of requiring a unique one.")}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,"/files/edit"),body:{path:input.path,oldString:input.oldString,newString:input.newString,replaceAll:input.replaceAll}}),"buildRequest")},files_delete:{description:"Delete one project file in an environment. The deletion lands as a reviewable commit on the environment branch.",annotations:{readOnlyHint:!1,destructiveHint:!0},scope:"project-env",accessScope:"write",operation:"files.write",inputSchema:z75.object({...envScopeShape,path:filePathField}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,"/files/delete"),body:{path:input.path}}),"buildRequest")},agents_list:{description:"List the agent bundles declared in a project environment, with triggers and activations.",annotations:{readOnlyHint:!0},scope:"project-env",accessScope:"read",inputSchema:z75.object(envScopeShape),buildRequest:__name((_input,scope)=>({method:"GET",path:managementEnvPath(scope,"/agents")}),"buildRequest")},agents_run:{description:"Trigger a manual run of a project agent. Returns a durable session ID; poll agents_status for progress. The agent executes in the managed project sandbox under its declared capabilities.",annotations:{readOnlyHint:!1},scope:"project-env",accessScope:"agents",operation:"agent.delegate",inputSchema:z75.object({...envScopeShape,agentName:z75.string().min(1).max(120).describe("The agent bundle name."),args:z75.record(z75.string(),z75.unknown()).optional().describe("Arguments passed to the agent run.")}),buildRequest:__name((input,scope)=>({method:"POST",path:managementEnvPath(scope,`/agents/${encodeURIComponent(input.agentName)}/run`),body:input.args===void 0?{}:{args:input.args}}),"buildRequest")},agents_status:{description:"Read one agent session (status, report, checkpoints) by session ID.",annotations:{readOnlyHint:!0},scope:"project",accessScope:"read",inputSchema:z75.object({...projectScopeShape,sessionId:z75.uuid().describe("The agent session ID returned by agents_run.")}),buildRequest:__name((input,scope)=>({method:"GET",path:managementProjectPath(scope,`/agents/sessions/${encodeURIComponent(input.sessionId)}`)}),"buildRequest")}},mcpToolNames=Object.keys(mcpToolCatalog);import*as z3rt from"zod/v3";import*as z4mini from"zod/v4-mini";function isZ4Schema(s){return!!s._zod}__name(isZ4Schema,"isZ4Schema");function objectFromShape(shape){let values=Object.values(shape);if(values.length===0)return z4mini.object({});let allV4=values.every(isZ4Schema),allV3=values.every(s=>!isZ4Schema(s));if(allV4)return z4mini.object(shape);if(allV3)return z3rt.object(shape);throw new Error("Mixed Zod versions detected in object shape.")}__name(objectFromShape,"objectFromShape");function safeParse3(schema,data2){return isZ4Schema(schema)?z4mini.safeParse(schema,data2):schema.safeParse(data2)}__name(safeParse3,"safeParse");async function safeParseAsync2(schema,data2){return isZ4Schema(schema)?await z4mini.safeParseAsync(schema,data2):await schema.safeParseAsync(data2)}__name(safeParseAsync2,"safeParseAsync");function getObjectShape(schema){if(!schema)return;let rawShape;if(isZ4Schema(schema)?rawShape=schema._zod?.def?.shape:rawShape=schema.shape,!!rawShape){if(typeof rawShape=="function")try{return rawShape()}catch{return}return rawShape}}__name(getObjectShape,"getObjectShape");function normalizeObjectSchema(schema){if(schema){if(typeof schema=="object"){let asV3=schema,asV4=schema;if(!asV3._def&&!asV4._zod){let values=Object.values(schema);if(values.length>0&&values.every(v=>typeof v=="object"&&v!==null&&(v._def!==void 0||v._zod!==void 0||typeof v.parse=="function")))return objectFromShape(schema)}}if(isZ4Schema(schema)){let def=schema._zod?.def;if(def&&(def.type==="object"||def.shape!==void 0))return schema}else if(schema.shape!==void 0)return schema}}__name(normalizeObjectSchema,"normalizeObjectSchema");function getParseErrorMessage(error){if(error&&typeof error=="object"){if("message"in error&&typeof error.message=="string")return error.message;if("issues"in error&&Array.isArray(error.issues)&&error.issues.length>0){let firstIssue=error.issues[0];if(firstIssue&&typeof firstIssue=="object"&&"message"in firstIssue)return String(firstIssue.message)}try{return JSON.stringify(error)}catch{return String(error)}}return String(error)}__name(getParseErrorMessage,"getParseErrorMessage");function getSchemaDescription(schema){return schema.description}__name(getSchemaDescription,"getSchemaDescription");function isSchemaOptional(schema){if(isZ4Schema(schema))return schema._zod?.def?.type==="optional";let v3Schema=schema;return typeof schema.isOptional=="function"?schema.isOptional():v3Schema._def?.typeName==="ZodOptional"}__name(isSchemaOptional,"isSchemaOptional");function getLiteralValue(schema){if(isZ4Schema(schema)){let def2=schema._zod?.def;if(def2){if(def2.value!==void 0)return def2.value;if(Array.isArray(def2.values)&&def2.values.length>0)return def2.values[0]}}let def=schema._def;if(def){if(def.value!==void 0)return def.value;if(Array.isArray(def.values)&&def.values.length>0)return def.values[0]}let directValue=schema.value;if(directValue!==void 0)return directValue}__name(getLiteralValue,"getLiteralValue");import*as z76 from"zod/v4";var LATEST_PROTOCOL_VERSION="2025-11-25";var SUPPORTED_PROTOCOL_VERSIONS=[LATEST_PROTOCOL_VERSION,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],RELATED_TASK_META_KEY="io.modelcontextprotocol/related-task",JSONRPC_VERSION="2.0",AssertObjectSchema=z76.custom(v=>v!==null&&(typeof v=="object"||typeof v=="function")),ProgressTokenSchema=z76.union([z76.string(),z76.number().int()]),CursorSchema=z76.string(),TaskCreationParamsSchema=z76.looseObject({ttl:z76.union([z76.number(),z76.null()]).optional(),pollInterval:z76.number().optional()}),TaskMetadataSchema=z76.object({ttl:z76.number().optional()}),RelatedTaskMetadataSchema=z76.object({taskId:z76.string()}),RequestMetaSchema=z76.looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=z76.object({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),isTaskAugmentedRequestParams=__name(value=>TaskAugmentedRequestParamsSchema.safeParse(value).success,"isTaskAugmentedRequestParams"),RequestSchema=z76.object({method:z76.string(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=z76.object({_meta:RequestMetaSchema.optional()}),NotificationSchema=z76.object({method:z76.string(),params:NotificationsParamsSchema.loose().optional()}),ResultSchema=z76.looseObject({_meta:RequestMetaSchema.optional()}),RequestIdSchema=z76.union([z76.string(),z76.number().int()]),JSONRPCRequestSchema=z76.object({jsonrpc:z76.literal(JSONRPC_VERSION),id:RequestIdSchema,...RequestSchema.shape}).strict(),isJSONRPCRequest=__name(value=>JSONRPCRequestSchema.safeParse(value).success,"isJSONRPCRequest"),JSONRPCNotificationSchema=z76.object({jsonrpc:z76.literal(JSONRPC_VERSION),...NotificationSchema.shape}).strict(),isJSONRPCNotification=__name(value=>JSONRPCNotificationSchema.safeParse(value).success,"isJSONRPCNotification"),JSONRPCResultResponseSchema=z76.object({jsonrpc:z76.literal(JSONRPC_VERSION),id:RequestIdSchema,result:ResultSchema}).strict(),isJSONRPCResultResponse=__name(value=>JSONRPCResultResponseSchema.safeParse(value).success,"isJSONRPCResultResponse");var ErrorCode;(function(ErrorCode2){ErrorCode2[ErrorCode2.ConnectionClosed=-32e3]="ConnectionClosed",ErrorCode2[ErrorCode2.RequestTimeout=-32001]="RequestTimeout",ErrorCode2[ErrorCode2.ParseError=-32700]="ParseError",ErrorCode2[ErrorCode2.InvalidRequest=-32600]="InvalidRequest",ErrorCode2[ErrorCode2.MethodNotFound=-32601]="MethodNotFound",ErrorCode2[ErrorCode2.InvalidParams=-32602]="InvalidParams",ErrorCode2[ErrorCode2.InternalError=-32603]="InternalError",ErrorCode2[ErrorCode2.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ErrorCode||(ErrorCode={}));var JSONRPCErrorResponseSchema=z76.object({jsonrpc:z76.literal(JSONRPC_VERSION),id:RequestIdSchema.optional(),error:z76.object({code:z76.number().int(),message:z76.string(),data:z76.unknown().optional()})}).strict();var isJSONRPCErrorResponse=__name(value=>JSONRPCErrorResponseSchema.safeParse(value).success,"isJSONRPCErrorResponse");var JSONRPCMessageSchema=z76.union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),JSONRPCResponseSchema=z76.union([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:z76.string().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/cancelled"),params:CancelledNotificationParamsSchema}),IconSchema=z76.object({src:z76.string(),mimeType:z76.string().optional(),sizes:z76.array(z76.string()).optional(),theme:z76.enum(["light","dark"]).optional()}),IconsSchema=z76.object({icons:z76.array(IconSchema).optional()}),BaseMetadataSchema=z76.object({name:z76.string(),title:z76.string().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:z76.string(),websiteUrl:z76.string().optional(),description:z76.string().optional()}),FormElicitationCapabilitySchema=z76.intersection(z76.object({applyDefaults:z76.boolean().optional()}),z76.record(z76.string(),z76.unknown())),ElicitationCapabilitySchema=z76.preprocess(value=>value&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0?{form:{}}:value,z76.intersection(z76.object({form:FormElicitationCapabilitySchema.optional(),url:AssertObjectSchema.optional()}),z76.record(z76.string(),z76.unknown()).optional())),ClientTasksCapabilitySchema=z76.looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:z76.looseObject({sampling:z76.looseObject({createMessage:AssertObjectSchema.optional()}).optional(),elicitation:z76.looseObject({create:AssertObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=z76.looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:z76.looseObject({tools:z76.looseObject({call:AssertObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=z76.object({experimental:z76.record(z76.string(),AssertObjectSchema).optional(),sampling:z76.object({context:AssertObjectSchema.optional(),tools:AssertObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:z76.object({listChanged:z76.boolean().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:z76.string(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:z76.literal("initialize"),params:InitializeRequestParamsSchema});var ServerCapabilitiesSchema=z76.object({experimental:z76.record(z76.string(),AssertObjectSchema).optional(),logging:AssertObjectSchema.optional(),completions:AssertObjectSchema.optional(),prompts:z76.object({listChanged:z76.boolean().optional()}).optional(),resources:z76.object({subscribe:z76.boolean().optional(),listChanged:z76.boolean().optional()}).optional(),tools:z76.object({listChanged:z76.boolean().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:z76.string(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:z76.string().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/initialized"),params:NotificationsParamsSchema.optional()});var PingRequestSchema=RequestSchema.extend({method:z76.literal("ping"),params:BaseRequestParamsSchema.optional()}),ProgressSchema=z76.object({progress:z76.number(),total:z76.optional(z76.number()),message:z76.optional(z76.string())}),ProgressNotificationParamsSchema=z76.object({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/progress"),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()}),TaskStatusSchema=z76.enum(["working","input_required","completed","failed","cancelled"]),TaskSchema=z76.object({taskId:z76.string(),status:TaskStatusSchema,ttl:z76.union([z76.number(),z76.null()]),createdAt:z76.string(),lastUpdatedAt:z76.string(),pollInterval:z76.optional(z76.number()),statusMessage:z76.optional(z76.string())}),CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/tasks/status"),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema.extend({method:z76.literal("tasks/get"),params:BaseRequestParamsSchema.extend({taskId:z76.string()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:z76.literal("tasks/result"),params:BaseRequestParamsSchema.extend({taskId:z76.string()})}),GetTaskPayloadResultSchema=ResultSchema.loose(),ListTasksRequestSchema=PaginatedRequestSchema.extend({method:z76.literal("tasks/list")}),ListTasksResultSchema=PaginatedResultSchema.extend({tasks:z76.array(TaskSchema)}),CancelTaskRequestSchema=RequestSchema.extend({method:z76.literal("tasks/cancel"),params:BaseRequestParamsSchema.extend({taskId:z76.string()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ResourceContentsSchema=z76.object({uri:z76.string(),mimeType:z76.optional(z76.string()),_meta:z76.record(z76.string(),z76.unknown()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:z76.string()}),Base64Schema=z76.string().refine(val2=>{try{return atob(val2),!0}catch{return!1}},{message:"Invalid Base64 string"}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),RoleSchema=z76.enum(["user","assistant"]),AnnotationsSchema=z76.object({audience:z76.array(RoleSchema).optional(),priority:z76.number().min(0).max(1).optional(),lastModified:z76.iso.datetime({offset:!0}).optional()}),ResourceSchema=z76.object({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:z76.string(),description:z76.optional(z76.string()),mimeType:z76.optional(z76.string()),annotations:AnnotationsSchema.optional(),_meta:z76.optional(z76.looseObject({}))}),ResourceTemplateSchema=z76.object({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:z76.string(),description:z76.optional(z76.string()),mimeType:z76.optional(z76.string()),annotations:AnnotationsSchema.optional(),_meta:z76.optional(z76.looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:z76.literal("resources/list")}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:z76.array(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:z76.literal("resources/templates/list")}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:z76.array(ResourceTemplateSchema)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:z76.string()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema.extend({method:z76.literal("resources/read"),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema=ResultSchema.extend({contents:z76.array(z76.union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/resources/list_changed"),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema.extend({method:z76.literal("resources/subscribe"),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema.extend({method:z76.literal("resources/unsubscribe"),params:UnsubscribeRequestParamsSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:z76.string()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=z76.object({name:z76.string(),description:z76.optional(z76.string()),required:z76.optional(z76.boolean())}),PromptSchema=z76.object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:z76.optional(z76.string()),arguments:z76.optional(z76.array(PromptArgumentSchema)),_meta:z76.optional(z76.looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:z76.literal("prompts/list")}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:z76.array(PromptSchema)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:z76.string(),arguments:z76.record(z76.string(),z76.string()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:z76.literal("prompts/get"),params:GetPromptRequestParamsSchema}),TextContentSchema=z76.object({type:z76.literal("text"),text:z76.string(),annotations:AnnotationsSchema.optional(),_meta:z76.record(z76.string(),z76.unknown()).optional()}),ImageContentSchema=z76.object({type:z76.literal("image"),data:Base64Schema,mimeType:z76.string(),annotations:AnnotationsSchema.optional(),_meta:z76.record(z76.string(),z76.unknown()).optional()}),AudioContentSchema=z76.object({type:z76.literal("audio"),data:Base64Schema,mimeType:z76.string(),annotations:AnnotationsSchema.optional(),_meta:z76.record(z76.string(),z76.unknown()).optional()}),ToolUseContentSchema=z76.object({type:z76.literal("tool_use"),name:z76.string(),id:z76.string(),input:z76.record(z76.string(),z76.unknown()),_meta:z76.record(z76.string(),z76.unknown()).optional()}),EmbeddedResourceSchema=z76.object({type:z76.literal("resource"),resource:z76.union([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:z76.record(z76.string(),z76.unknown()).optional()}),ResourceLinkSchema=ResourceSchema.extend({type:z76.literal("resource_link")}),ContentBlockSchema=z76.union([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=z76.object({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema=ResultSchema.extend({description:z76.string().optional(),messages:z76.array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=z76.object({title:z76.string().optional(),readOnlyHint:z76.boolean().optional(),destructiveHint:z76.boolean().optional(),idempotentHint:z76.boolean().optional(),openWorldHint:z76.boolean().optional()}),ToolExecutionSchema=z76.object({taskSupport:z76.enum(["required","optional","forbidden"]).optional()}),ToolSchema=z76.object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:z76.string().optional(),inputSchema:z76.object({type:z76.literal("object"),properties:z76.record(z76.string(),AssertObjectSchema).optional(),required:z76.array(z76.string()).optional()}).catchall(z76.unknown()),outputSchema:z76.object({type:z76.literal("object"),properties:z76.record(z76.string(),AssertObjectSchema).optional(),required:z76.array(z76.string()).optional()}).catchall(z76.unknown()).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:z76.record(z76.string(),z76.unknown()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:z76.literal("tools/list")}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:z76.array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:z76.array(ContentBlockSchema).default([]),structuredContent:z76.record(z76.string(),z76.unknown()).optional(),isError:z76.boolean().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:z76.unknown()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:z76.string(),arguments:z76.record(z76.string(),z76.unknown()).optional()}),CallToolRequestSchema=RequestSchema.extend({method:z76.literal("tools/call"),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/tools/list_changed"),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=z76.object({autoRefresh:z76.boolean().default(!0),debounceMs:z76.number().int().nonnegative().default(300)}),LoggingLevelSchema=z76.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema.extend({method:z76.literal("logging/setLevel"),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:z76.string().optional(),data:z76.unknown()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/message"),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=z76.object({name:z76.string().optional()}),ModelPreferencesSchema=z76.object({hints:z76.array(ModelHintSchema).optional(),costPriority:z76.number().min(0).max(1).optional(),speedPriority:z76.number().min(0).max(1).optional(),intelligencePriority:z76.number().min(0).max(1).optional()}),ToolChoiceSchema=z76.object({mode:z76.enum(["auto","required","none"]).optional()}),ToolResultContentSchema=z76.object({type:z76.literal("tool_result"),toolUseId:z76.string().describe("The unique identifier for the corresponding tool call."),content:z76.array(ContentBlockSchema).default([]),structuredContent:z76.object({}).loose().optional(),isError:z76.boolean().optional(),_meta:z76.record(z76.string(),z76.unknown()).optional()}),SamplingContentSchema=z76.discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema]),SamplingMessageContentBlockSchema=z76.discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=z76.object({role:RoleSchema,content:z76.union([SamplingMessageContentBlockSchema,z76.array(SamplingMessageContentBlockSchema)]),_meta:z76.record(z76.string(),z76.unknown()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:z76.array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:z76.string().optional(),includeContext:z76.enum(["none","thisServer","allServers"]).optional(),temperature:z76.number().optional(),maxTokens:z76.number().int(),stopSequences:z76.array(z76.string()).optional(),metadata:AssertObjectSchema.optional(),tools:z76.array(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema.extend({method:z76.literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema.extend({model:z76.string(),stopReason:z76.optional(z76.enum(["endTurn","stopSequence","maxTokens"]).or(z76.string())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:z76.string(),stopReason:z76.optional(z76.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(z76.string())),role:RoleSchema,content:z76.union([SamplingMessageContentBlockSchema,z76.array(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=z76.object({type:z76.literal("boolean"),title:z76.string().optional(),description:z76.string().optional(),default:z76.boolean().optional()}),StringSchemaSchema=z76.object({type:z76.literal("string"),title:z76.string().optional(),description:z76.string().optional(),minLength:z76.number().optional(),maxLength:z76.number().optional(),format:z76.enum(["email","uri","date","date-time"]).optional(),default:z76.string().optional()}),NumberSchemaSchema=z76.object({type:z76.enum(["number","integer"]),title:z76.string().optional(),description:z76.string().optional(),minimum:z76.number().optional(),maximum:z76.number().optional(),default:z76.number().optional()}),UntitledSingleSelectEnumSchemaSchema=z76.object({type:z76.literal("string"),title:z76.string().optional(),description:z76.string().optional(),enum:z76.array(z76.string()),default:z76.string().optional()}),TitledSingleSelectEnumSchemaSchema=z76.object({type:z76.literal("string"),title:z76.string().optional(),description:z76.string().optional(),oneOf:z76.array(z76.object({const:z76.string(),title:z76.string()})),default:z76.string().optional()}),LegacyTitledEnumSchemaSchema=z76.object({type:z76.literal("string"),title:z76.string().optional(),description:z76.string().optional(),enum:z76.array(z76.string()),enumNames:z76.array(z76.string()).optional(),default:z76.string().optional()}),SingleSelectEnumSchemaSchema=z76.union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=z76.object({type:z76.literal("array"),title:z76.string().optional(),description:z76.string().optional(),minItems:z76.number().optional(),maxItems:z76.number().optional(),items:z76.object({type:z76.literal("string"),enum:z76.array(z76.string())}),default:z76.array(z76.string()).optional()}),TitledMultiSelectEnumSchemaSchema=z76.object({type:z76.literal("array"),title:z76.string().optional(),description:z76.string().optional(),minItems:z76.number().optional(),maxItems:z76.number().optional(),items:z76.object({anyOf:z76.array(z76.object({const:z76.string(),title:z76.string()}))}),default:z76.array(z76.string()).optional()}),MultiSelectEnumSchemaSchema=z76.union([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=z76.union([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=z76.union([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:z76.literal("form").optional(),message:z76.string(),requestedSchema:z76.object({type:z76.literal("object"),properties:z76.record(z76.string(),PrimitiveSchemaDefinitionSchema),required:z76.array(z76.string()).optional()})}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:z76.literal("url"),message:z76.string(),elicitationId:z76.string(),url:z76.string().url()}),ElicitRequestParamsSchema=z76.union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:z76.literal("elicitation/create"),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:z76.string()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/elicitation/complete"),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:z76.enum(["accept","decline","cancel"]),content:z76.preprocess(val2=>val2===null?void 0:val2,z76.record(z76.string(),z76.union([z76.string(),z76.number(),z76.boolean(),z76.array(z76.string())])).optional())}),ResourceTemplateReferenceSchema=z76.object({type:z76.literal("ref/resource"),uri:z76.string()});var PromptReferenceSchema=z76.object({type:z76.literal("ref/prompt"),name:z76.string()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:z76.union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:z76.object({name:z76.string(),value:z76.string()}),context:z76.object({arguments:z76.record(z76.string(),z76.string()).optional()}).optional()}),CompleteRequestSchema=RequestSchema.extend({method:z76.literal("completion/complete"),params:CompleteRequestParamsSchema});function assertCompleteRequestPrompt(request){if(request.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`)}__name(assertCompleteRequestPrompt,"assertCompleteRequestPrompt");function assertCompleteRequestResourceTemplate(request){if(request.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`)}__name(assertCompleteRequestResourceTemplate,"assertCompleteRequestResourceTemplate");var CompleteResultSchema=ResultSchema.extend({completion:z76.looseObject({values:z76.array(z76.string()).max(100),total:z76.optional(z76.number().int()),hasMore:z76.optional(z76.boolean())})}),RootSchema=z76.object({uri:z76.string().startsWith("file://"),name:z76.string().optional(),_meta:z76.record(z76.string(),z76.unknown()).optional()}),ListRootsRequestSchema=RequestSchema.extend({method:z76.literal("roots/list"),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema.extend({roots:z76.array(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:z76.literal("notifications/roots/list_changed"),params:NotificationsParamsSchema.optional()}),ClientRequestSchema=z76.union([PingRequestSchema,InitializeRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,CallToolRequestSchema,ListToolsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ClientNotificationSchema=z76.union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema,TaskStatusNotificationSchema]),ClientResultSchema=z76.union([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),ServerRequestSchema=z76.union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ServerNotificationSchema=z76.union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,TaskStatusNotificationSchema,ElicitationCompleteNotificationSchema]),ServerResultSchema=z76.union([EmptyResultSchema,InitializeResultSchema,CompleteResultSchema,GetPromptResultSchema,ListPromptsResultSchema,ListResourcesResultSchema,ListResourceTemplatesResultSchema,ReadResourceResultSchema,CallToolResultSchema,ListToolsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),McpError=class _McpError extends Error{static{__name(this,"McpError")}constructor(code2,message,data2){super(`MCP error ${code2}: ${message}`),this.code=code2,this.data=data2,this.name="McpError"}static fromError(code2,message,data2){if(code2===ErrorCode.UrlElicitationRequired&&data2){let errorData=data2;if(errorData.elicitations)return new UrlElicitationRequiredError(errorData.elicitations,message)}return new _McpError(code2,message,data2)}},UrlElicitationRequiredError=class extends McpError{static{__name(this,"UrlElicitationRequiredError")}constructor(elicitations,message=`URL elicitation${elicitations.length>1?"s":""} required`){super(ErrorCode.UrlElicitationRequired,message,{elicitations})}get elicitations(){return this.data?.elicitations??[]}};function isTerminal(status){return status==="completed"||status==="failed"||status==="cancelled"}__name(isTerminal,"isTerminal");import*as z4mini2 from"zod/v4-mini";var ignoreOverride=Symbol("Let zodToJsonSchema decide on which parser to use");var defaultOptions={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},getDefaultOptions=__name(options=>typeof options=="string"?{...defaultOptions,name:options}:{...defaultOptions,...options},"getDefaultOptions");var getRefs=__name(options=>{let _options=getDefaultOptions(options),currentPath=_options.name!==void 0?[..._options.basePath,_options.definitionPath,_options.name]:_options.basePath;return{..._options,flags:{hasReferencedOpenAiAnyType:!1},currentPath,propertyPath:void 0,seen:new Map(Object.entries(_options.definitions).map(([name,def])=>[def._def,{def:def._def,path:[..._options.basePath,_options.definitionPath,name],jsonSchema:void 0}]))}},"getRefs");function addErrorMessage(res,key,errorMessage3,refs){refs?.errorMessages&&errorMessage3&&(res.errorMessage={...res.errorMessage,[key]:errorMessage3})}__name(addErrorMessage,"addErrorMessage");function setResponseValueAndErrors(res,key,value,errorMessage3,refs){res[key]=value,addErrorMessage(res,key,errorMessage3,refs)}__name(setResponseValueAndErrors,"setResponseValueAndErrors");var getRelativePath=__name((pathA,pathB)=>{let i=0;for(;i<pathA.length&&i<pathB.length&&pathA[i]===pathB[i];i++);return[(pathA.length-i).toString(),...pathB.slice(i)].join("/")},"getRelativePath");import{ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3}from"zod/v3";function parseAnyDef(refs){if(refs.target!=="openAi")return{};let anyDefinitionPath=[...refs.basePath,refs.definitionPath,refs.openAiAnyTypeName];return refs.flags.hasReferencedOpenAiAnyType=!0,{$ref:refs.$refStrategy==="relative"?getRelativePath(anyDefinitionPath,refs.currentPath):anyDefinitionPath.join("/")}}__name(parseAnyDef,"parseAnyDef");import{ZodFirstPartyTypeKind}from"zod/v3";function parseArrayDef(def,refs){let res={type:"array"};return def.type?._def&&def.type?._def?.typeName!==ZodFirstPartyTypeKind.ZodAny&&(res.items=parseDef(def.type._def,{...refs,currentPath:[...refs.currentPath,"items"]})),def.minLength&&setResponseValueAndErrors(res,"minItems",def.minLength.value,def.minLength.message,refs),def.maxLength&&setResponseValueAndErrors(res,"maxItems",def.maxLength.value,def.maxLength.message,refs),def.exactLength&&(setResponseValueAndErrors(res,"minItems",def.exactLength.value,def.exactLength.message,refs),setResponseValueAndErrors(res,"maxItems",def.exactLength.value,def.exactLength.message,refs)),res}__name(parseArrayDef,"parseArrayDef");function parseBigintDef(def,refs){let res={type:"integer",format:"int64"};if(!def.checks)return res;for(let check of def.checks)switch(check.kind){case"min":refs.target==="jsonSchema7"?check.inclusive?setResponseValueAndErrors(res,"minimum",check.value,check.message,refs):setResponseValueAndErrors(res,"exclusiveMinimum",check.value,check.message,refs):(check.inclusive||(res.exclusiveMinimum=!0),setResponseValueAndErrors(res,"minimum",check.value,check.message,refs));break;case"max":refs.target==="jsonSchema7"?check.inclusive?setResponseValueAndErrors(res,"maximum",check.value,check.message,refs):setResponseValueAndErrors(res,"exclusiveMaximum",check.value,check.message,refs):(check.inclusive||(res.exclusiveMaximum=!0),setResponseValueAndErrors(res,"maximum",check.value,check.message,refs));break;case"multipleOf":setResponseValueAndErrors(res,"multipleOf",check.value,check.message,refs);break}return res}__name(parseBigintDef,"parseBigintDef");function parseBooleanDef(){return{type:"boolean"}}__name(parseBooleanDef,"parseBooleanDef");function parseBrandedDef(_def,refs){return parseDef(_def.type._def,refs)}__name(parseBrandedDef,"parseBrandedDef");var parseCatchDef=__name((def,refs)=>parseDef(def.innerType._def,refs),"parseCatchDef");function parseDateDef(def,refs,overrideDateStrategy){let strategy=overrideDateStrategy??refs.dateStrategy;if(Array.isArray(strategy))return{anyOf:strategy.map((item,i)=>parseDateDef(def,refs,item))};switch(strategy){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return integerDateParser(def,refs)}}__name(parseDateDef,"parseDateDef");var integerDateParser=__name((def,refs)=>{let res={type:"integer",format:"unix-time"};if(refs.target==="openApi3")return res;for(let check of def.checks)switch(check.kind){case"min":setResponseValueAndErrors(res,"minimum",check.value,check.message,refs);break;case"max":setResponseValueAndErrors(res,"maximum",check.value,check.message,refs);break}return res},"integerDateParser");function parseDefaultDef(_def,refs){return{...parseDef(_def.innerType._def,refs),default:_def.defaultValue()}}__name(parseDefaultDef,"parseDefaultDef");function parseEffectsDef(_def,refs){return refs.effectStrategy==="input"?parseDef(_def.schema._def,refs):parseAnyDef(refs)}__name(parseEffectsDef,"parseEffectsDef");function parseEnumDef(def){return{type:"string",enum:Array.from(def.values)}}__name(parseEnumDef,"parseEnumDef");var isJsonSchema7AllOfType=__name(type=>"type"in type&&type.type==="string"?!1:"allOf"in type,"isJsonSchema7AllOfType");function parseIntersectionDef(def,refs){let allOf=[parseDef(def.left._def,{...refs,currentPath:[...refs.currentPath,"allOf","0"]}),parseDef(def.right._def,{...refs,currentPath:[...refs.currentPath,"allOf","1"]})].filter(x=>!!x),unevaluatedProperties=refs.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,mergedAllOf=[];return allOf.forEach(schema=>{if(isJsonSchema7AllOfType(schema))mergedAllOf.push(...schema.allOf),schema.unevaluatedProperties===void 0&&(unevaluatedProperties=void 0);else{let nestedSchema=schema;if("additionalProperties"in schema&&schema.additionalProperties===!1){let{additionalProperties,...rest}=schema;nestedSchema=rest}else unevaluatedProperties=void 0;mergedAllOf.push(nestedSchema)}}),mergedAllOf.length?{allOf:mergedAllOf,...unevaluatedProperties}:void 0}__name(parseIntersectionDef,"parseIntersectionDef");function parseLiteralDef(def,refs){let parsedType=typeof def.value;return parsedType!=="bigint"&&parsedType!=="number"&&parsedType!=="boolean"&&parsedType!=="string"?{type:Array.isArray(def.value)?"array":"object"}:refs.target==="openApi3"?{type:parsedType==="bigint"?"integer":parsedType,enum:[def.value]}:{type:parsedType==="bigint"?"integer":parsedType,const:def.value}}__name(parseLiteralDef,"parseLiteralDef");import{ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2}from"zod/v3";var emojiRegex,zodPatterns={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:__name(()=>(emojiRegex===void 0&&(emojiRegex=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),emojiRegex),"emoji"),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function parseStringDef(def,refs){let res={type:"string"};if(def.checks)for(let check of def.checks)switch(check.kind){case"min":setResponseValueAndErrors(res,"minLength",typeof res.minLength=="number"?Math.max(res.minLength,check.value):check.value,check.message,refs);break;case"max":setResponseValueAndErrors(res,"maxLength",typeof res.maxLength=="number"?Math.min(res.maxLength,check.value):check.value,check.message,refs);break;case"email":switch(refs.emailStrategy){case"format:email":addFormat(res,"email",check.message,refs);break;case"format:idn-email":addFormat(res,"idn-email",check.message,refs);break;case"pattern:zod":addPattern(res,zodPatterns.email,check.message,refs);break}break;case"url":addFormat(res,"uri",check.message,refs);break;case"uuid":addFormat(res,"uuid",check.message,refs);break;case"regex":addPattern(res,check.regex,check.message,refs);break;case"cuid":addPattern(res,zodPatterns.cuid,check.message,refs);break;case"cuid2":addPattern(res,zodPatterns.cuid2,check.message,refs);break;case"startsWith":addPattern(res,RegExp(`^${escapeLiteralCheckValue(check.value,refs)}`),check.message,refs);break;case"endsWith":addPattern(res,RegExp(`${escapeLiteralCheckValue(check.value,refs)}$`),check.message,refs);break;case"datetime":addFormat(res,"date-time",check.message,refs);break;case"date":addFormat(res,"date",check.message,refs);break;case"time":addFormat(res,"time",check.message,refs);break;case"duration":addFormat(res,"duration",check.message,refs);break;case"length":setResponseValueAndErrors(res,"minLength",typeof res.minLength=="number"?Math.max(res.minLength,check.value):check.value,check.message,refs),setResponseValueAndErrors(res,"maxLength",typeof res.maxLength=="number"?Math.min(res.maxLength,check.value):check.value,check.message,refs);break;case"includes":{addPattern(res,RegExp(escapeLiteralCheckValue(check.value,refs)),check.message,refs);break}case"ip":{check.version!=="v6"&&addFormat(res,"ipv4",check.message,refs),check.version!=="v4"&&addFormat(res,"ipv6",check.message,refs);break}case"base64url":addPattern(res,zodPatterns.base64url,check.message,refs);break;case"jwt":addPattern(res,zodPatterns.jwt,check.message,refs);break;case"cidr":{check.version!=="v6"&&addPattern(res,zodPatterns.ipv4Cidr,check.message,refs),check.version!=="v4"&&addPattern(res,zodPatterns.ipv6Cidr,check.message,refs);break}case"emoji":addPattern(res,zodPatterns.emoji(),check.message,refs);break;case"ulid":{addPattern(res,zodPatterns.ulid,check.message,refs);break}case"base64":{switch(refs.base64Strategy){case"format:binary":{addFormat(res,"binary",check.message,refs);break}case"contentEncoding:base64":{setResponseValueAndErrors(res,"contentEncoding","base64",check.message,refs);break}case"pattern:zod":{addPattern(res,zodPatterns.base64,check.message,refs);break}}break}case"nanoid":addPattern(res,zodPatterns.nanoid,check.message,refs);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return res}__name(parseStringDef,"parseStringDef");function escapeLiteralCheckValue(literal2,refs){return refs.patternStrategy==="escape"?escapeNonAlphaNumeric(literal2):literal2}__name(escapeLiteralCheckValue,"escapeLiteralCheckValue");var ALPHA_NUMERIC=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function escapeNonAlphaNumeric(source){let result="";for(let i=0;i<source.length;i++)ALPHA_NUMERIC.has(source[i])||(result+="\\"),result+=source[i];return result}__name(escapeNonAlphaNumeric,"escapeNonAlphaNumeric");function addFormat(schema,value,message,refs){schema.format||schema.anyOf?.some(x=>x.format)?(schema.anyOf||(schema.anyOf=[]),schema.format&&(schema.anyOf.push({format:schema.format,...schema.errorMessage&&refs.errorMessages&&{errorMessage:{format:schema.errorMessage.format}}}),delete schema.format,schema.errorMessage&&(delete schema.errorMessage.format,Object.keys(schema.errorMessage).length===0&&delete schema.errorMessage)),schema.anyOf.push({format:value,...message&&refs.errorMessages&&{errorMessage:{format:message}}})):setResponseValueAndErrors(schema,"format",value,message,refs)}__name(addFormat,"addFormat");function addPattern(schema,regex,message,refs){schema.pattern||schema.allOf?.some(x=>x.pattern)?(schema.allOf||(schema.allOf=[]),schema.pattern&&(schema.allOf.push({pattern:schema.pattern,...schema.errorMessage&&refs.errorMessages&&{errorMessage:{pattern:schema.errorMessage.pattern}}}),delete schema.pattern,schema.errorMessage&&(delete schema.errorMessage.pattern,Object.keys(schema.errorMessage).length===0&&delete schema.errorMessage)),schema.allOf.push({pattern:stringifyRegExpWithFlags(regex,refs),...message&&refs.errorMessages&&{errorMessage:{pattern:message}}})):setResponseValueAndErrors(schema,"pattern",stringifyRegExpWithFlags(regex,refs),message,refs)}__name(addPattern,"addPattern");function stringifyRegExpWithFlags(regex,refs){if(!refs.applyRegexFlags||!regex.flags)return regex.source;let flags={i:regex.flags.includes("i"),m:regex.flags.includes("m"),s:regex.flags.includes("s")},source=flags.i?regex.source.toLowerCase():regex.source,pattern="",isEscaped2=!1,inCharGroup=!1,inCharRange=!1;for(let i=0;i<source.length;i++){if(isEscaped2){pattern+=source[i],isEscaped2=!1;continue}if(flags.i){if(inCharGroup){if(source[i].match(/[a-z]/)){inCharRange?(pattern+=source[i],pattern+=`${source[i-2]}-${source[i]}`.toUpperCase(),inCharRange=!1):source[i+1]==="-"&&source[i+2]?.match(/[a-z]/)?(pattern+=source[i],inCharRange=!0):pattern+=`${source[i]}${source[i].toUpperCase()}`;continue}}else if(source[i].match(/[a-z]/)){pattern+=`[${source[i]}${source[i].toUpperCase()}]`;continue}}if(flags.m){if(source[i]==="^"){pattern+=`(^|(?<=[\r
|
|
1343
1356
|
]))`;continue}else if(source[i]==="$"){pattern+=`($|(?=[\r
|
|
1344
1357
|
]))`;continue}}if(flags.s&&source[i]==="."){pattern+=inCharGroup?`${source[i]}\r
|
|
1345
1358
|
`:`[${source[i]}\r
|
|
@@ -1348,13 +1361,13 @@ Remote config and local checkout are synchronized.`}__name(renderMutationResult,
|
|
|
1348
1361
|
`}__name(serializeMessage,"serializeMessage");var StdioServerTransport=class{static{__name(this,"StdioServerTransport")}constructor(_stdin=process8.stdin,_stdout=process8.stdout){this._stdin=_stdin,this._stdout=_stdout,this._readBuffer=new ReadBuffer,this._started=!1,this._ondata=chunk=>{this._readBuffer.append(chunk),this.processReadBuffer()},this._onerror=error=>{this.onerror?.(error)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let message=this._readBuffer.readMessage();if(message===null)break;this.onmessage?.(message)}catch(error){this.onerror?.(error)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(message){return new Promise(resolve10=>{let json=serializeMessage(message);this._stdout.write(json)?resolve10():this._stdout.once("drain",resolve10)})}};init_api();init_config();init_project_context();function createCliMcpHost(client,defaults={}){return{identity:__name(async()=>{let session=await client.getCurrentSession();if(!session)throw new Error("Not signed in. Run `fimo login` or set FIMO_API_TOKEN.");return{id:session.user.id,email:session.user.email??null,name:session.user.name??null}},"identity"),dispatch:__name(request=>client.fetchRaw(`/api${request.path}`,{method:request.method,body:request.body!==void 0?JSON.stringify(request.body):void 0}),"dispatch"),authorize:__name(async({operation,projectId,env})=>{if(operation)try{await requireOperation(operation,{projectId,env})}catch(error){throw error instanceof CapabilityDenied?Object.assign(error,{code:"capability_denied"}):error}},"authorize"),defaults}}__name(createCliMcpHost,"createCliMcpHost");async function resolveDefaults(cmd){try{let ctx=await getProjectContext({envOverride:envOverrideFromCommand(cmd)});return ctx.readOnly?{projectId:ctx.projectId}:{projectId:ctx.projectId,env:ctx.env}}catch(error){if(error instanceof NotInProjectError||error instanceof GitBranchUndetectedError)return{};throw error}}__name(resolveDefaults,"resolveDefaults");async function mcpCommand(_options,cmd){let client=new FimoApiClient(loadConfig()),defaults=await resolveDefaults(cmd),server=createFimoMcpServer(createCliMcpHost(client,defaults)),transport=new StdioServerTransport,closed=new Promise(resolve10=>{server.server.onclose=()=>resolve10()});await server.connect(transport),process.stderr.write(`fimo mcp: serving over stdio${defaults.projectId?` (project ${defaults.projectId}${defaults.env?`, env ${defaults.env}`:""})`:""}
|
|
1349
1362
|
`),await closed}__name(mcpCommand,"mcpCommand");init_esm();init_dist();init_project_context();function taskTokens(task){let argv=process.argv.slice(2),namespaceIndex=argv.indexOf(task.modality);if(namespaceIndex===-1)return[];let verbIndex=argv.indexOf(task.operation,namespaceIndex+1);return verbIndex===-1?[]:argv.slice(verbIndex+1)}__name(taskTokens,"taskTokens");function renderTaskHelp(task){return renderGenerationHelp({usage:`fimo ${task.modality} ${task.operation} [flags]`,description:task.description,flags:task.flags})}__name(renderTaskHelp,"renderTaskHelp");async function runTask(task,command){let tokens=taskTokens(task),wantsHelp=tokens.includes("--help")||tokens.includes("-h"),commandName2=`${task.modality} ${task.operation}`;if(wantsHelp){ui.result({command:commandName2,data:{task},render:__name(()=>renderTaskHelp(task),"render")});return}let{values,bools,options}=parseGenerationFlags({commandName:commandName2,subject:task.id,helpCommand:`fimo ${commandName2} --help`,flags:task.flags,tokens}),body={task:task.id,options,name:values.get("name")?.[0],parentId:values.get("parent")?.[0]??null},isJson=currentMode().format==="json",{ctx,api}=await bootstrapProjectCommand({cwd:values.get("cwd")?.[0]},command,{refuseReadOnly:!0,quiet:isJson});if(bools.get("dry-run")===!0){let estimate=await api.estimateGenerationTask(ctx.projectId,task.id,options),data2={...body,estimate};ui.result({command:commandName2,data:data2,render:__name(()=>JSON.stringify(data2,null,2),"render")});return}await submitGeneration({commandName:commandName2,ctx,api,body})}__name(runTask,"runTask");function registerTaskCommand(parent2,task){parent2.command(task.operation).description(task.description).allowUnknownOption(!0).allowExcessArguments(!0).helpOption(!1).action(async(_options,command)=>{await runTask(task,command)})}__name(registerTaskCommand,"registerTaskCommand");function registerMediaTaskCommands(program2){let image=program2.command("image").description("Generate and transform images"),video=program2.command("video").description("Generate and transform videos");for(let task of GENERATION_TASK_MANIFESTS)registerTaskCommand(task.modality==="image"?image:video,task)}__name(registerMediaTaskCommands,"registerMediaTaskCommands");init_dist5();init_dist();init_api();init_auth_errors();init_color();import{execSync,spawnSync as spawnSync3}from"node:child_process";import{mkdtempSync,readFileSync as readFileSync10,writeFileSync as writeFileSync5}from"node:fs";import{tmpdir as tmpdir3}from"node:os";import path39 from"node:path";function renderMergeSuccess(result,p2){let lines=[];if(lines.push(p2.green(`\u2713 Merged ${result.fromEnv} \u2192 ${result.toEnv}`)),result.summary&&lines.push(p2.dim(` ${result.summary}`)),result.applied.length>0){lines.push(""),lines.push(p2.bold("Applied:"));for(let a of result.applied)lines.push(p2.dim(` ${a.surface.padEnd(14)} ${a.count} item${a.count===1?"":"s"}`))}return lines.join(`
|
|
1350
1363
|
`)}__name(renderMergeSuccess,"renderMergeSuccess");function renderConflict(conflict,p2){let lines=[];return lines.push(`${p2.yellow("!")} ${p2.bold(`${conflict.surface}: ${conflict.key}`)}`),lines.push(p2.dim(` ${conflict.description}`)),conflict.parentValue!==void 0&&lines.push(p2.dim(" parent: ")+summariseValue(conflict.parentValue)),conflict.childValue!==void 0&&lines.push(p2.dim(" child: ")+summariseValue(conflict.childValue)),lines.join(`
|
|
1351
|
-
`)}__name(renderConflict,"renderConflict");function renderResolverHeader(conflicts,p2){let surfaceCounts=conflicts.reduce((acc,c2)=>(acc[c2.surface]=(acc[c2.surface]??0)+1,acc),{}),parts=Object.entries(surfaceCounts).map(([s,n])=>`${n} ${s}`);return p2.yellow(`! ${conflicts.length} conflict${conflicts.length===1?"":"s"} (${parts.join(", ")}) \u2014 resolve below.`)}__name(renderResolverHeader,"renderResolverHeader");function summariseValue(v){if(v===null)return"null";if(typeof v=="string")return v.length>60?v.slice(0,57)+"...":v;if(typeof v=="number"||typeof v=="boolean")return String(v);try{let s=JSON.stringify(v);return s.length>60?s.slice(0,57)+"...":s}catch{return"[unserialisable]"}}__name(summariseValue,"summariseValue");init_project_context();init_esm();var ProtectedFlowError=class extends Error{static{__name(this,"ProtectedFlowError")}env;constructor(env){super(`Refusing to run this mutating command against the protected
|
|
1364
|
+
`)}__name(renderConflict,"renderConflict");function renderResolverHeader(conflicts,p2){let surfaceCounts=conflicts.reduce((acc,c2)=>(acc[c2.surface]=(acc[c2.surface]??0)+1,acc),{}),parts=Object.entries(surfaceCounts).map(([s,n])=>`${n} ${s}`);return p2.yellow(`! ${conflicts.length} conflict${conflicts.length===1?"":"s"} (${parts.join(", ")}) \u2014 resolve below.`)}__name(renderResolverHeader,"renderResolverHeader");function summariseValue(v){if(v===null)return"null";if(typeof v=="string")return v.length>60?v.slice(0,57)+"...":v;if(typeof v=="number"||typeof v=="boolean")return String(v);try{let s=JSON.stringify(v);return s.length>60?s.slice(0,57)+"...":s}catch{return"[unserialisable]"}}__name(summariseValue,"summariseValue");init_project_context();init_esm();var ProtectedFlowError=class extends Error{static{__name(this,"ProtectedFlowError")}env;constructor(env){super(`Refusing to run this mutating command against the protected Branch '${env}'. Use the PR/review flow or pass --allow-direct-merge to override.`),this.name="ProtectedFlowError",this.env=env}};function assertNotOnMain(env,opts={}){let protectedEnvs=opts.protectedEnvs??[DEFAULT_ENV];if(!opts.allowDirectMerge&&protectedEnvs.includes(env))throw new ProtectedFlowError(env)}__name(assertNotOnMain,"assertNotOnMain");async function fetchDrillContext(args){let{api,ctx,fromEnv,conflict,p:p2}=args,surface=conflict.surface;try{switch(surface){case"code":{let payload=await api.getCodeFileDiff(ctx.projectId,fromEnv,conflict.key,{against:ctx.env});return renderCodeFileDiff(payload,p2,{bare:!1})}case"content":{let[collection,rowId]=splitOnce2(conflict.key,":");if(!collection||!rowId)return null;let payload=await api.getContentRowDiff(ctx.projectId,fromEnv,collection,rowId,{against:ctx.env});return renderContentRowDiff(payload,p2,{bare:!1})}case"translations":{let[locale,key]=splitOnce2(conflict.key,":");if(!locale||!key)return null;let payload=await api.getTranslationRowDiff(ctx.projectId,fromEnv,locale,key,{against:ctx.env});return renderTranslationRowDiff(payload,p2,{bare:!1})}case"schemas":{let payload=await api.getSchemaTypeDiff(ctx.projectId,fromEnv,conflict.key,{against:ctx.env});return renderSchemaTypeDiff(payload,p2,{bare:!1})}case"forms":{let payload=await api.getFormSchemaDiff(ctx.projectId,fromEnv,conflict.key,{against:ctx.env});return renderFormSchemaDiff(payload,p2,{bare:!1})}case"assets":{let payload=await api.getAssetDiff(ctx.projectId,fromEnv,conflict.key,{against:ctx.env});return renderAssetDiff(payload,p2,{bare:!1})}}}catch{return null}return null}__name(fetchDrillContext,"fetchDrillContext");function splitOnce2(s,sep2){let idx=s.indexOf(sep2);return idx<0?[s,""]:[s.slice(0,idx),s.slice(idx+1)]}__name(splitOnce2,"splitOnce");var DRAFT_DEBOUNCE_MS=1500;async function mergeCommand(from,options,cmd){let program2=cmd?.parent??cmd,envOverride2=envOverrideFromCommand(program2),ctx=await getProjectContext({cwd:options.cwd,envOverride:envOverride2}),api=new FimoApiClient().withEnv(ctx.env);try{assertNotOnMain(ctx.env,{allowDirectMerge:options.allowDirectMerge})}catch(err){if(err instanceof ProtectedFlowError){ui.error({command:"merge",code:"PROTECTED_FLOW",message:err.message,hint:"See: https://fimo.ai/docs/environments/overview#a-pr-style-flow"});return}throw err}let isJson=currentMode().format==="json",p2=options.noColor?makeColorPalette({forceDisable:!0}):palette;if(options.resume){if(isJson){ui.error({command:"merge",code:"NON_INTERACTIVE_REFUSAL",message:"--resume requires interactive mode"});return}return resumeMerge({api,ctx,from,options,p:p2})}isJson||mt(p2.bold(`Merging ${from} \u2192 ${ctx.env}`));let result;try{result=await api.mergeEnv(ctx.projectId,ctx.env,{from,allowDirectMerge:options.allowDirectMerge})}catch(err){rethrowCliAuthError(err),ui.error({command:"merge",code:"MERGE_REQUEST_FAILED",message:`Merge failed: ${err.message}`});return}if(result.ok){ui.result({command:"merge",data:result,render:__name(rctx=>renderMergeSuccess(result,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")});return}let conflicts=result.conflicts??[];if(conflicts.length===0){ui.error({command:"merge",code:"MERGE_EMPTY_CONFLICTS",message:"Merge returned ok=false but produced no conflicts. Aborting."});return}if(isJson){ui.result({command:"merge",data:result,render:__name(()=>"","render")});return}O2.warn(renderResolverHeader(conflicts,p2));let resolutions=await resolveConflictsInteractive({api,ctx,from,mergeId:result.mergeId,conflicts,drafted:[],p:p2,acceptDefaults:options.yes===!0});if(resolutions===null){await api.cancelMerge(ctx.projectId,ctx.env,result.mergeId).catch(()=>{}),ui.error({command:"merge",code:"MERGE_CANCELLED",message:"Merge cancelled; compensating actions triggered server-side."});return}await commitResolutions({api,ctx,from,mergeId:result.mergeId,resolutions})}__name(mergeCommand,"mergeCommand");async function resolveConflictsInteractive(args){let draftedMap=new Map;for(let d3 of args.drafted)draftedMap.set(`${d3.surface}:${d3.key}`,d3);let resolutions=[...args.drafted],pendingSave=null,flush=__name(async()=>{pendingSave&&(clearTimeout(pendingSave),pendingSave=null);try{await args.api.putResolveDraft(args.ctx.projectId,args.ctx.env,args.from,{mergeId:args.mergeId,resolutions})}catch{}},"flush"),scheduleSave=__name(()=>{pendingSave&&clearTimeout(pendingSave),pendingSave=setTimeout(()=>{flush().catch(()=>{})},DRAFT_DEBOUNCE_MS)},"scheduleSave");for(let conflict of args.conflicts){let key=`${conflict.surface}:${conflict.key}`;if(draftedMap.has(key))continue;if(await printConflictWithContext(args.api,args.ctx,args.from,conflict,args.p),args.acceptDefaults){resolutions.push({surface:conflict.surface,key:conflict.key,choice:"parent"}),scheduleSave();continue}let isCode=conflict.surface==="code",choice=await _t({message:"How should this conflict be resolved?",options:[{value:"parent",label:isCode?`parent \u2014 keep ${args.ctx.env}'s file`:"parent \u2014 keep target value"},{value:"child",label:isCode?`child \u2014 take ${args.from}'s file`:"child \u2014 take source value"},{value:"pick",label:isCode?"pick \u2014 resolve conflict markers in $EDITOR":"pick \u2014 edit a custom value in $EDITOR"},{value:"abort",label:"abort \u2014 cancel the merge"}]});if(q(choice)||choice==="abort")return await flush(),null;if(choice==="pick"){let picked=isCode?await openEditorForCodePick(args.api,args.ctx,args.from,conflict):openEditorForPick(conflict);if(picked===null)return O2.warn("Empty buffer \u2014 treating as abort. Re-run with --resume to continue."),await flush(),null;resolutions.push({surface:conflict.surface,key:conflict.key,choice:"pick",pickedValue:picked})}else resolutions.push({surface:conflict.surface,key:conflict.key,choice});scheduleSave()}return await flush(),resolutions}__name(resolveConflictsInteractive,"resolveConflictsInteractive");async function printConflictWithContext(api,ctx,fromEnv,conflict,p2){console.log(renderConflict(conflict,p2));try{let drill=await fetchDrillContext({api,ctx,fromEnv,conflict,p:p2});drill&&console.log(drill)}catch{}}__name(printConflictWithContext,"printConflictWithContext");async function commitResolutions(args){let resolved;try{resolved=await args.api.resolveMerge(args.ctx.projectId,args.ctx.env,args.from,{mergeId:args.mergeId,resolutions:args.resolutions})}catch(err){rethrowCliAuthError(err),ui.error({command:"merge",code:"MERGE_RESOLVE_FAILED",message:`Resolve failed: ${err.message}`});return}if(!resolved.ok){ui.error({command:"merge",code:"MERGE_RESOLUTION_REJECTED",message:"Server rejected the resolution batch. Run `fimo diff` and try again."});return}ui.result({command:"merge",data:resolved,render:__name(rctx=>renderMergeSuccess(resolved,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")})}__name(commitResolutions,"commitResolutions");async function resumeMerge(args){let hydration;try{hydration=await args.api.getMergeConflicts(args.ctx.projectId,args.ctx.env,args.from)}catch(err){rethrowCliAuthError(err),ui.error({command:"merge",code:"MERGE_RESUME_FAILED",message:`Failed to load in-progress merge: ${err.message}`});return}if(hydration.status!=="in_progress"&&hydration.status!=="conflicts"){ui.error({command:"merge",code:"MERGE_NOT_RESUMABLE",message:`Merge ${hydration.mergeId} is ${hydration.status}; nothing to resume.`});return}if(hydration.conflicts.length===0){ui.info({command:"merge",message:"No conflicts to resolve \u2014 submitting empty batch."}),await commitResolutions({api:args.api,ctx:args.ctx,from:args.from,mergeId:hydration.mergeId,resolutions:[]});return}mt(args.p.bold(`Resuming merge ${args.from} \u2192 ${args.ctx.env}`)),O2.info(`${hydration.draftResolutions.length} of ${hydration.conflicts.length} conflict${hydration.conflicts.length===1?"":"s"} already drafted`);let resolutions=await resolveConflictsInteractive({api:args.api,ctx:args.ctx,from:args.from,mergeId:hydration.mergeId,conflicts:hydration.conflicts,drafted:hydration.draftResolutions,p:args.p,acceptDefaults:args.options.yes===!0});if(resolutions===null){ui.info({command:"merge",message:"Cancelled \u2014 draft kept. Run --resume again to continue."});return}await commitResolutions({api:args.api,ctx:args.ctx,from:args.from,mergeId:hydration.mergeId,resolutions})}__name(resumeMerge,"resumeMerge");function openEditorForPick(conflict){let editor=process.env.EDITOR??process.env.VISUAL??"nano",tmp=mkdtempSync(path39.join(tmpdir3(),"fimo-merge-")),file=path39.join(tmp,`${conflict.surface}-${sanitiseKey(conflict.key)}.json`),seed=conflict.childValue!==void 0?JSON.stringify(conflict.childValue,null,2):`// Replace this comment with the resolved value as JSON
|
|
1352
1365
|
""`;writeFileSync5(file,seed,"utf8"),spawnSync3(editor,[file],{stdio:"inherit"});let raw=readFileSync10(file,"utf8").trim();if(raw===""||raw===seed.trim())return null;try{return JSON.parse(raw)}catch{return raw}}__name(openEditorForPick,"openEditorForPick");async function openEditorForCodePick(api,ctx,fromEnv,conflict){let filePath=conflict.code?.path??conflict.key,seed="",seedLoaded=!1;try{seed=(await api.getCodeConflictDetail(ctx.projectId,ctx.env,fromEnv,filePath)).result.content??"",seedLoaded=!0}catch{O2.warn(`Could not load the 3-way merge for ${filePath}; leaving it unresolved. Re-run with --resume.`)}let editor=process.env.EDITOR??process.env.VISUAL??"nano",tmp=mkdtempSync(path39.join(tmpdir3(),"fimo-merge-")),ext=path39.extname(filePath)||".txt",file=path39.join(tmp,`${sanitiseKey(filePath)}${ext}`);writeFileSync5(file,seed,"utf8"),spawnSync3(editor,[file],{stdio:"inherit"});let raw=readFileSync10(file,"utf8");return raw.trim()===""&&(seed.trim()!==""||!seedLoaded)?null:((raw.includes("<<<<<<<")||raw.includes(">>>>>>>"))&&O2.warn("Conflict markers remain \u2014 they will be committed as-is. Re-run with --resume to fix."),raw)}__name(openEditorForCodePick,"openEditorForCodePick");function sanitiseKey(key){return key.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,60)}__name(sanitiseKey,"sanitiseKey");init_migrate_refine();init_migrate();init_dist();init_api();init_config();init_project_context();function padRight(s,width){return s.length>=width?s:s+" ".repeat(width-s.length)}__name(padRight,"padRight");function fmtUsd(n){let trimmed=n.toFixed(4).replace(/0+$/,"").replace(/\.$/,"");return trimmed.includes(".")?trimmed:`${trimmed}.00`}__name(fmtUsd,"fmtUsd");function priceRate(price){let unit=price.unit.replace(/s$/,"");return`${price.confidence==="metered"?"~":""}$${fmtUsd(price.unitPrice)} / ${unit}`}__name(priceRate,"priceRate");function bestFor(description){let start=description.indexOf("Best for:");if(start===-1)return`${description.split(". ")[0]}.`;let rest=description.slice(start),notFor=rest.indexOf("Not for:");return(notFor===-1?rest:rest.slice(0,notFor)).replace(/^Best for:\s*/,"").trim()}__name(bestFor,"bestFor");function flagSignature(flag2){if(flag2.type==="boolean")return`--${flag2.name}`;let type=flag2.enumValues?.length?flag2.enumValues.join("|"):flag2.type;return`--${flag2.name} <${type}>`}__name(flagSignature,"flagSignature");function flagMeta(flag2){let parts=[flag2.required?"required":"optional"];return flag2.isArray&&parts.push("repeatable"),flag2.defaultValue!==void 0&&parts.push(`default ${JSON.stringify(flag2.defaultValue)}`),parts.join(", ")}__name(flagMeta,"flagMeta");function flagExample(flag2){let name=`--${flag2.name}`;if(flag2.type==="boolean")return flag2.defaultValue===!0?`--no-${flag2.name}`:name;let value;return flag2.enumValues?.length?value=String(flag2.enumValues[0]):/url|image/i.test(flag2.name)?value="<url>":flag2.type==="integer"||flag2.type==="number"?value=flag2.defaultValue!==void 0?String(flag2.defaultValue):"<n>":value='"\u2026"',flag2.isArray?`${name} ${value} ${name} ${value}`:`${name} ${value}`}__name(flagExample,"flagExample");function apiClient(){return new FimoApiClient(loadConfig())}__name(apiClient,"apiClient");async function modelsListCommand(opts){let context=await getProjectContext({cwd:opts.cwd}),models=await apiClient().listModels(context.projectId,{modality:opts.modality,tag:opts.tag,q:opts.search,category:opts.category});if(models.length===0){ui.info({command:"models list",message:"No models match the filter."});return}ui.result({command:"models list",data:{models},render:__name(()=>renderModelsListHuman(models,opts.extended===!0),"render")})}__name(modelsListCommand,"modelsListCommand");function renderModelsListHuman(models,extended){let groups=new Map;for(let m of models){let arr=groups.get(m.modality)??[];arr.push(m),groups.set(m.modality,arr)}let modalityOrder=["image","video","audio"],sortedModalities=Array.from(groups.keys()).sort((a,b)=>modalityOrder.indexOf(a)-modalityOrder.indexOf(b)),out=[],first2=!0;for(let modality of sortedModalities){first2||out.push(""),first2=!1;let group=groups.get(modality)??[];if(out.push(modality.toUpperCase()),extended){for(let m of group)out.push(renderExtendedEntry(m));continue}let nameWidth=Math.max(...group.map(m=>m.id.length));for(let m of group){let headline=m.description.split(". ")[0],tags=m.tags.length>0?`[${m.tags.join(", ")}]`:"",price=m.price?` ${priceRate(m.price)}`:"";out.push(` ${padRight(m.id,nameWidth)} ${tags}${price}`),out.push(` ${padRight("",nameWidth)} ${headline}.`)}}return out.join(`
|
|
1353
1366
|
`)}__name(renderModelsListHuman,"renderModelsListHuman");function renderExtendedEntry(m){let required=m.flags.filter(f=>f.required).map(f=>`--${f.name}`),optionalCount=m.flags.length-required.length,lines=[],row2=__name((label,value)=>{lines.push(` ${`${label}:`.padEnd(10)}${value}`)},"row"),flagsValue=m.flags.length===0?"none":`${required.length?`${required.join(", ")} (required)`:"none required"}${optionalCount?`, ${optionalCount} more`:""} \u2014 fimo models show ${m.id}`;return lines.push(` ${m.id} (${m.provider})`),row2("tags",m.tags.join(", ")||"\u2014"),m.price&&row2("price",priceRate(m.price)),row2("best for",bestFor(m.description)),row2("flags",flagsValue),lines.join(`
|
|
1354
1367
|
`)}__name(renderExtendedEntry,"renderExtendedEntry");async function modelsShowCommand(modelKey,opts){let context=await getProjectContext({cwd:opts.cwd}),model=await apiClient().getModel(context.projectId,modelKey);model||(ui.error({command:"models show",code:"UNKNOWN_MODEL",message:`Unknown model: "${modelKey}".`,hint:"Run `fimo models list` to see available names."}),process.exit(78)),ui.result({command:"models show",data:model,render:__name(()=>renderModelHuman(model),"render")})}__name(modelsShowCommand,"modelsShowCommand");function renderModelHuman(model){let lines=[];if(lines.push(model.displayName),lines.push(` id: ${model.id}`),lines.push(` provider: ${model.provider}`),lines.push(` source: ${model.source}`),lines.push(` modality: ${model.modality}`),lines.push(` tags: ${model.tags.join(", ")||"\u2014"}`),lines.push(""),lines.push(` ${model.description}`),model.price&&(lines.push(""),lines.push(" PRICING"),lines.push(` ${priceRate(model.price)}`),model.price.confidence==="metered"?lines.push(" (metered \u2014 final bill set by provider usage)"):model.price.confidence==="estimated"&&lines.push(" (estimated \u2014 exact quantity not known until the call runs)")),lines.push(""),lines.push(" OPTIONS"),model.flags.length===0)return lines.push(" (none)"),lines.join(`
|
|
1355
1368
|
`);for(let flag2 of model.flags){lines.push(""),lines.push(` ${flagSignature(flag2)} ${flagMeta(flag2)}`),flag2.description&&lines.push(` ${flag2.description}`);let repeatNote=flag2.isArray?" (repeat the flag for each value)":"";lines.push(` e.g. ${flagExample(flag2)}${repeatNote}`)}return lines.join(`
|
|
1356
1369
|
`)}__name(renderModelHuman,"renderModelHuman");init_dist();init_api();init_auth();init_config();async function orgsListCommand(){let cfg=loadConfig(),api=new FimoApiClient(cfg),activeId=requireCredentials(cfg)?.activeOrganization?.id,orgs2=await api.listOrganizations();if(orgs2.length===0){ui.info({command:"orgs list",message:"No organizations found for this account."});return}ui.table({command:"orgs list",columns:[{key:"id",label:"ID"},{key:"name",label:"NAME"},{key:"slug",label:"SLUG"}],rows:orgs2.map(org=>({id:org.id,name:org.name,slug:org.slug})),isActive:__name(row2=>row2.id===activeId,"isActive")})}__name(orgsListCommand,"orgsListCommand");async function orgsMembersCommand(options){let cfg=loadConfig(),api=new FimoApiClient(cfg),creds=requireCredentials(cfg),organizationId=options.org??creds?.activeOrganization?.id;if(!organizationId){ui.error({command:"orgs members",code:"NO_ORGANIZATION_SPECIFIED",message:"No organization specified and no active organization set.",hint:"Run `fimo switch` or pass --org <id>."});return}let members=await api.listOrganizationMembers(organizationId);if(members.length===0){ui.info({command:"orgs members",message:"No members found."});return}ui.table({command:"orgs members",columns:[{key:"role",label:"ROLE"},{key:"email",label:"EMAIL"},{key:"name",label:"NAME"}],rows:members.map(m=>({role:m.role,email:m.user?.email??"\u2014",name:m.user?.name??"\u2014"}))})}__name(orgsMembersCommand,"orgsMembersCommand");init_dist();init_config();init_project_context();function errorMessage2(error){return error instanceof Error?error.message:String(error)}__name(errorMessage2,"errorMessage");async function previewUrlCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);if(await requireOperation("fimo.preview.url",{projectId:ctx.projectId,env:ctx.env}),(await api.getProject(ctx.projectId)).previewEnabled===!1){ui.error({command:"preview url",code:"PREVIEW_DISABLED",message:"Preview is disabled for this project.",hint:"Turn off Disable Preview in Project settings before requesting a preview URL."});return}try{let session=await api.getPreviewUrl(ctx.projectId,ctx.env),dashboardUrl=buildProjectPreviewUrl(loadConfig().webUrl,ctx.projectId,ctx.env);ui.result({command:"preview url",data:{project_id:ctx.projectId,env:ctx.env,preview_url:session.url,dashboard_url:dashboardUrl,expires_at:session.expiresAt},render:__name(context=>context.hyperlinks?[`Preview: ${terminalLink("Open preview",session.url,!0)}`,`Fimo: ${terminalLink("Open in Fimo",dashboardUrl,!0)}`].join(`
|
|
1357
|
-
`):session.url,"render")})}catch(error){ui.error({command:"preview url",code:"PREVIEW_URL_FAILED",message:`Failed to get preview URL: ${errorMessage2(error)}`})}}__name(previewUrlCommand,"previewUrlCommand");function registerPreviewCommands(program2){program2.command("preview").description("Inspect
|
|
1370
|
+
`):session.url,"render")})}catch(error){ui.error({command:"preview url",code:"PREVIEW_URL_FAILED",message:`Failed to get preview URL: ${errorMessage2(error)}`})}}__name(previewUrlCommand,"previewUrlCommand");function registerPreviewCommands(program2){program2.command("preview").description("Inspect a Branch preview without deploying").command("url").description("Get a fresh preview URL for the current Branch (or --branch <name>) without deploying").option("-C, --cwd <dir>","Run against this directory instead of cwd").action((opts,cmd)=>previewUrlCommand(opts,cmd))}__name(registerPreviewCommands,"registerPreviewCommands");init_esm();init_dist();init_api();init_config();import fs42 from"node:fs";import path44 from"node:path";function mergeManagedEnvBlock(existing,entries2,spec){let block=renderBlock(entries2,spec),normalized=existing.replace(/\r\n/g,`
|
|
1358
1371
|
`),lines=normalized.endsWith(`
|
|
1359
1372
|
`)?normalized.slice(0,-1).split(`
|
|
1360
1373
|
`):normalized.split(`
|
|
@@ -1364,9 +1377,9 @@ Remote config and local checkout are synchronized.`}__name(renderMutationResult,
|
|
|
1364
1377
|
`)}
|
|
1365
1378
|
`;return{content:content3,changed:content3!==existing,created:!1}}return{content:`${[...lines,"",...block].join(`
|
|
1366
1379
|
`)}
|
|
1367
|
-
`,changed:!0,created:!0}}__name(mergeManagedEnvBlock,"mergeManagedEnvBlock");function renderBlock(entries2,spec){return[spec.start,...spec.header,...Object.entries(entries2).map(([key,value])=>`${key}=${quoteEnvValue(value)}`),spec.end]}__name(renderBlock,"renderBlock");function quoteEnvValue(value){return/^[A-Za-z0-9_./:@-]*$/.test(value)?value:JSON.stringify(value)}__name(quoteEnvValue,"quoteEnvValue");init_project();function registerProjectSecretsCommands(program2){let vars=program2.command("vars").description("Manage project variables");vars.command("list").description("List project variables").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action(opts=>listCommand2("variable",opts)),vars.command("add <key> [value]").description("Add a project variable").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--stdin","Read the value from stdin").option("--value <value>","Variable value").action((key,value,opts)=>writeCommand("variable","add",key,opts.value??value,opts)),vars.command("update <key> [value]").description("Update an existing project variable").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--stdin","Read the value from stdin").option("--value <value>","Variable value").action((key,value,opts)=>writeCommand("variable","update",key,opts.value??value,opts)),vars.command("unset <key>").alias("remove").description("Delete a project variable").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((key,opts)=>unsetCommand("variable",key,opts)),vars.command("pull [file]").description("Write public project variables to a local env file").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((file,opts)=>pullVarsCommand(file,opts));let secrets=program2.command("secrets").description("Manage project secrets");secrets.command("list").description("List project secrets without revealing values").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action(opts=>listCommand2("secret",opts)),secrets.command("add <key> [value]").description("Add a project secret").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--stdin","Read the value from stdin").option("--value <value>","Secret value (prefer --stdin in shells that record history)").action((key,value,opts)=>writeCommand("secret","add",key,opts.value??value,opts)),secrets.command("update <key> [value]").description("Update an existing project secret").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--stdin","Read the value from stdin").option("--value <value>","Secret value (prefer --stdin in shells that record history)").action((key,value,opts)=>writeCommand("secret","update",key,opts.value??value,opts)),secrets.command("unset <key>").alias("remove").description("Delete a project secret").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((key,opts)=>unsetCommand("secret",key,opts))}__name(registerProjectSecretsCommands,"registerProjectSecretsCommands");function commandName(kind,verb){return`${kind==="secret"?"secrets":"vars"} ${verb}`}__name(commandName,"commandName");async function listCommand2(kind,opts){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId4(opts),rows=await api.listProjectSecretEntries(projectId,{kind});if(rows.length===0){ui.info({command:commandName(kind,"list"),message:kind==="secret"?"No project secrets set.":"No project variables set."});return}ui.table({command:commandName(kind,"list"),columns:[{key:"key",label:"KEY"},{key:"value",label:kind==="secret"?"VALUE (masked)":"VALUE"}],rows:rows.map(row2=>({key:row2.key,value:row2.value??row2.maskedValue??""}))})}__name(listCommand2,"listCommand");async function writeCommand(kind,operation,key,valueArg,opts){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId4(opts),value=opts.stdin||valueArg===void 0?await readStdinValue3(kind):valueArg,input={projectId,key,kind,value};operation==="add"?await api.createProjectSecretEntry(input):await api.updateProjectSecretEntry(input);let envLocal=kind==="variable"?await syncDefaultLocalVars(api,projectId,opts):null,action=operation==="add"?"Added":"Updated";ui.ok({command:commandName(kind,operation),headline:`${action} project ${kind==="secret"?"secret":"variable"} ${key}`,details:{project_id:projectId,key,kind,...envLocal&&{env_local:envLocal}}})}__name(writeCommand,"writeCommand");async function unsetCommand(kind,key,opts){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId4(opts);await api.deleteProjectSecretEntry(projectId,key,kind);let envLocal=kind==="variable"?await syncDefaultLocalVars(api,projectId,opts):null;ui.ok({command:commandName(kind,"unset"),headline:`Removed project ${kind==="secret"?"secret":"variable"} ${key}`,details:{project_id:projectId,key,kind,...envLocal&&{env_local:envLocal}}})}__name(unsetCommand,"unsetCommand");async function pullVarsCommand(file,opts){let api=new FimoApiClient(loadConfig()),projectRoot=resolveProjectCwd(opts.cwd),projectId=resolveProjectId4(opts),result=await writePulledVars(api,projectRoot,projectId,file??".env.local");ui.ok({command:"vars pull",headline:`Wrote ${result.written} variable${result.written===1?"":"s"} to ${result.path}`,details:{project_id:projectId,file:result.path,written:result.written}})}__name(pullVarsCommand,"pullVarsCommand");async function syncDefaultLocalVars(api,projectId,opts){let projectRoot=resolveProjectCwd(opts.cwd);try{if(loadProjectSettings(projectRoot).projectId!==projectId)return null}catch{return null}return writePulledVars(api,projectRoot,projectId,".env.local")}__name(syncDefaultLocalVars,"syncDefaultLocalVars");async function writePulledVars(api,projectRoot,projectId,file){let rows=(await api.listProjectSecretEntries(projectId,{kind:"variable"})).filter(row2=>row2.exposure==="public"),target=path44.resolve(projectRoot,file),existing=fs42.existsSync(target)?fs42.readFileSync(target,"utf8"):"",body=mergeEnvFile(existing,rows);return fs42.writeFileSync(target,body),{path:target,written:rows.length}}__name(writePulledVars,"writePulledVars");function resolveProjectId4(opts){if(opts.project)return opts.project;let cwd=resolveProjectCwd(opts.cwd);return loadProjectSettings(cwd).projectId}__name(resolveProjectId4,"resolveProjectId");async function readStdinValue3(kind){if(process.stdin.isTTY)throw new Error(`Pass a ${kind} value or pipe one with --stdin.`);let chunks=[];for await(let chunk of process.stdin)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));return Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/,"")}__name(readStdinValue3,"readStdinValue");var VARS_BLOCK={start:"# fimo:vars:start",end:"# fimo:vars:end",header:["# Generated by fimo vars pull. Do not put secrets in this block."]};function mergeEnvFile(existing,rows){let entries2=Object.fromEntries(rows.map(row2=>[row2.key,row2.value??""]));return mergeManagedEnvBlock(existing,entries2,VARS_BLOCK).content}__name(mergeEnvFile,"mergeEnvFile");init_dist5();init_dist();init_api();init_auth();init_config();init_auth_errors();init_interactive();init_project();import fs43 from"node:fs";function resolveCwd2(options){return resolveProjectCwd(options.cwd)}__name(resolveCwd2,"resolveCwd");function readLocalConfig(options){let cwd=resolveCwd2(options);try{return loadProjectSettings(cwd)}catch{return null}}__name(readLocalConfig,"readLocalConfig");function resolveProjectId5(argv,options,command){if(argv)return argv;let local=readLocalConfig(options);return local?local.projectId:(ui.error({command,code:"NOT_IN_PROJECT",message:"No project ID and no Fimo project link found in the current directory.",hint:"Pass a project ID explicitly, or cd into a linked project."}),null)}__name(resolveProjectId5,"resolveProjectId");async function projectsListCommand(options){let cfg=loadConfig(),api=new FimoApiClient(cfg),creds=requireCredentials(cfg),organizationId=options.org??creds?.activeOrganization?.id;if(!organizationId){ui.error({command:"projects list",code:"NO_ORGANIZATION_SPECIFIED",message:"No organization specified and no active organization set.",hint:"Run `fimo switch` or pass --org <id>."});return}let projects2=await api.listProjects(organizationId);if(projects2.length===0){ui.info({command:"projects list",message:"No projects in this organization yet."});return}ui.table({command:"projects list",columns:[{key:"published",label:"PUB"},{key:"id",label:"ID"},{key:"name",label:"NAME"},{key:"displayName",label:"DISPLAY NAME"}],rows:projects2.map(p2=>({published:p2.appUrl?"\u{1F7E2}":"\u26AA",id:p2.id,name:p2.name,displayName:p2.displayName??""}))})}__name(projectsListCommand,"projectsListCommand");async function projectsDeleteCommand(projectIdArg,options){let cfg=loadConfig(),api=new FimoApiClient(cfg),projectId=resolveProjectId5(projectIdArg,options,"projects delete");if(projectId){if(!options.yes){assertInteractive("Pass --yes to skip confirmation.","projects delete");let confirmed=await ot2({message:`Delete project ${projectId}? This cannot be undone.`,initialValue:!1});if(q(confirmed)||!confirmed){ui.info({command:"projects delete",message:"Cancelled."});return}}await api.deleteProject(projectId),ui.ok({command:"projects delete",headline:`Deleted project ${projectId}.`,details:{project_id:projectId}})}}__name(projectsDeleteCommand,"projectsDeleteCommand");async function projectsRenameCommand(nameArg,projectIdArg,options){let cwd=resolveCwd2(options),local=readLocalConfig(options);if(!local){ui.error({command:"projects rename",code:"NOT_IN_PROJECT",message:"No Fimo project link found in the current directory.",hint:"`fimo rename` only operates on a local project. cd into the project root."});return}if(projectIdArg&&projectIdArg!==local.projectId){ui.error({command:"projects rename",code:"PROJECT_ID_MISMATCH",message:`Project ID ${projectIdArg} does not match this directory's project (${local.projectId}).`,hint:"cd into the project you want to rename."});return}let name=nameArg.trim();if(!name){ui.error({command:"projects rename",code:"EMPTY_DISPLAY_NAME",message:"Display name cannot be empty."});return}let configPath=resolveProjectConfigPath(cwd),config={};if(fs43.existsSync(configPath))try{config=JSON.parse(fs43.readFileSync(configPath,"utf-8"))}catch(error){ui.error({command:"projects rename",code:"CONFIG_PARSE_FAILED",message:`Could not parse ${configPath}: ${error instanceof Error?error.message:String(error)}`});return}let seo=config.seo??{};config.seo={...seo,siteName:name},fs43.writeFileSync(configPath,JSON.stringify(config,null,2)+`
|
|
1368
|
-
`),ui.ok({command:"projects rename",headline:`Renamed to "${name}".`,details:{project_id:local.projectId,display_name:name},hint:"Commit and `fimo deploy` to sync."})}__name(projectsRenameCommand,"projectsRenameCommand");async function projectsPublishCommand(projectIdArg,options){let cfg=loadConfig(),api=new FimoApiClient(cfg),projectId=
|
|
1369
|
-
`))},"render")})}__name(rulesSyncCommand,"rulesSyncCommand");init_esm();init_dist();init_api();init_config();init_project_context();init_project();var UUID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,RUN_POLL_INTERVAL_MS=2e3,RUN_POLL_TIMEOUT_MS=1800*1e3,TERMINAL_RUN_STATUSES=["succeeded","failed","skipped"],ScheduleCommandError=class extends Error{static{__name(this,"ScheduleCommandError")}code;constructor(code2,message){super(message),this.name="ScheduleCommandError",this.code=code2}};function
|
|
1380
|
+
`,changed:!0,created:!0}}__name(mergeManagedEnvBlock,"mergeManagedEnvBlock");function renderBlock(entries2,spec){return[spec.start,...spec.header,...Object.entries(entries2).map(([key,value])=>`${key}=${quoteEnvValue(value)}`),spec.end]}__name(renderBlock,"renderBlock");function quoteEnvValue(value){return/^[A-Za-z0-9_./:@-]*$/.test(value)?value:JSON.stringify(value)}__name(quoteEnvValue,"quoteEnvValue");init_project_context();init_project();function registerProjectSecretsCommands(program2){let vars=program2.command("vars").description("Manage project variables");vars.command("list").description("List project variables").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((opts,command)=>listCommand3("variable",opts,command)),vars.command("add <key> [value]").description("Add a project variable").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--stdin","Read the value from stdin").option("--value <value>","Variable value").action((key,value,opts,command)=>writeCommand("variable","add",key,opts.value??value,opts,command)),vars.command("update <key> [value]").description("Update an existing project variable").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--stdin","Read the value from stdin").option("--value <value>","Variable value").action((key,value,opts,command)=>writeCommand("variable","update",key,opts.value??value,opts,command)),vars.command("unset <key>").alias("remove").description("Delete a project variable").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((key,opts,command)=>unsetCommand("variable",key,opts,command)),vars.command("pull [file]").description("Write public project variables to a local env file").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((file,opts,command)=>pullVarsCommand(file,opts,command));let secrets=program2.command("secrets").description("Manage project secrets");secrets.command("list").description("List project secrets without revealing values").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((opts,command)=>listCommand3("secret",opts,command)),secrets.command("add <key> [value]").description("Add a project secret").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--stdin","Read the value from stdin").option("--value <value>","Secret value (prefer --stdin in shells that record history)").action((key,value,opts,command)=>writeCommand("secret","add",key,opts.value??value,opts,command)),secrets.command("update <key> [value]").description("Update an existing project secret").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").option("--stdin","Read the value from stdin").option("--value <value>","Secret value (prefer --stdin in shells that record history)").action((key,value,opts,command)=>writeCommand("secret","update",key,opts.value??value,opts,command)),secrets.command("unset <key>").alias("remove").description("Delete a project secret").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory").action((key,opts,command)=>unsetCommand("secret",key,opts,command))}__name(registerProjectSecretsCommands,"registerProjectSecretsCommands");function commandName(kind,verb){return`${kind==="secret"?"secrets":"vars"} ${verb}`}__name(commandName,"commandName");async function listCommand3(kind,opts,command){let{api,environment,projectId}=await resolveScope3(opts,command),rows=await api.listProjectSecretEntries(projectId,{kind,environment});if(rows.length===0){ui.info({command:commandName(kind,"list"),message:kind==="secret"?"No project secrets set.":"No project variables set."});return}ui.table({command:commandName(kind,"list"),columns:[{key:"key",label:"KEY"},{key:"value",label:kind==="secret"?"VALUE (masked)":"VALUE"}],rows:rows.map(row2=>({key:row2.key,value:row2.value??row2.maskedValue??""}))})}__name(listCommand3,"listCommand");async function writeCommand(kind,operation,key,valueArg,opts,command){let{api,environment,projectId}=await resolveScope3(opts,command),value=opts.stdin||valueArg===void 0?await readStdinValue3(kind):valueArg,input={projectId,key,kind,value,environment};operation==="add"?await api.createProjectSecretEntry(input):await api.updateProjectSecretEntry(input);let envLocal=kind==="variable"?await syncDefaultLocalVars(api,projectId,environment,opts):null,action=operation==="add"?"Added":"Updated";ui.ok({command:commandName(kind,operation),headline:`${action} project ${kind==="secret"?"secret":"variable"} ${key}`,details:{project_id:projectId,key,kind,environment,...envLocal&&{env_local:envLocal}}})}__name(writeCommand,"writeCommand");async function unsetCommand(kind,key,opts,command){let{api,environment,projectId}=await resolveScope3(opts,command);await api.deleteProjectSecretEntry(projectId,key,kind,environment);let envLocal=kind==="variable"?await syncDefaultLocalVars(api,projectId,environment,opts):null;ui.ok({command:commandName(kind,"unset"),headline:`Removed project ${kind==="secret"?"secret":"variable"} ${key}`,details:{project_id:projectId,key,kind,environment,...envLocal&&{env_local:envLocal}}})}__name(unsetCommand,"unsetCommand");async function pullVarsCommand(file,opts,command){let projectRoot=resolveProjectCwd(opts.cwd),{api,environment,projectId}=await resolveScope3(opts,command),result=await writePulledVars(api,projectRoot,projectId,environment,file??".env.local");ui.ok({command:"vars pull",headline:`Wrote ${result.written} variable${result.written===1?"":"s"} to ${result.path}`,details:{project_id:projectId,file:result.path,written:result.written}})}__name(pullVarsCommand,"pullVarsCommand");async function syncDefaultLocalVars(api,projectId,environment,opts){let projectRoot=resolveProjectCwd(opts.cwd);try{if(loadProjectSettings(projectRoot).projectId!==projectId)return null}catch{return null}return writePulledVars(api,projectRoot,projectId,environment,".env.local")}__name(syncDefaultLocalVars,"syncDefaultLocalVars");async function writePulledVars(api,projectRoot,projectId,environment,file){let rows=(await api.listProjectSecretEntries(projectId,{kind:"variable",environment})).filter(row2=>row2.exposure==="public"),target=path44.resolve(projectRoot,file),existing=fs42.existsSync(target)?fs42.readFileSync(target,"utf8"):"",body=mergeEnvFile(existing,rows);return fs42.writeFileSync(target,body),{path:target,written:rows.length}}__name(writePulledVars,"writePulledVars");function resolveProjectId5(opts){if(opts.project)return opts.project;let cwd=resolveProjectCwd(opts.cwd);return loadProjectSettings(cwd).projectId}__name(resolveProjectId5,"resolveProjectId");async function resolveScope3(opts,command){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId5(opts),branch=DEFAULT_ENV;try{branch=(await getProjectContext({cwd:opts.cwd,envOverride:envOverrideFromCommand(command)})).env}catch(error){if(!opts.project)throw error}let environment=await api.resolveProjectEnvironmentKey(projectId,branch);return{api,environment,projectId}}__name(resolveScope3,"resolveScope");async function readStdinValue3(kind){if(process.stdin.isTTY)throw new Error(`Pass a ${kind} value or pipe one with --stdin.`);let chunks=[];for await(let chunk of process.stdin)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));return Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/,"")}__name(readStdinValue3,"readStdinValue");var VARS_BLOCK={start:"# fimo:vars:start",end:"# fimo:vars:end",header:["# Generated by fimo vars pull. Do not put secrets in this block."]};function mergeEnvFile(existing,rows){let entries2=Object.fromEntries(rows.map(row2=>[row2.key,row2.value??""]));return mergeManagedEnvBlock(existing,entries2,VARS_BLOCK).content}__name(mergeEnvFile,"mergeEnvFile");init_dist5();init_dist();init_api();init_auth();init_config();init_auth_errors();init_interactive();init_project();import fs43 from"node:fs";function resolveCwd2(options){return resolveProjectCwd(options.cwd)}__name(resolveCwd2,"resolveCwd");function readLocalConfig(options){let cwd=resolveCwd2(options);try{return loadProjectSettings(cwd)}catch{return null}}__name(readLocalConfig,"readLocalConfig");function resolveProjectId6(argv,options,command){if(argv)return argv;let local=readLocalConfig(options);return local?local.projectId:(ui.error({command,code:"NOT_IN_PROJECT",message:"No project ID and no Fimo project link found in the current directory.",hint:"Pass a project ID explicitly, or cd into a linked project."}),null)}__name(resolveProjectId6,"resolveProjectId");async function projectsListCommand(options){let cfg=loadConfig(),api=new FimoApiClient(cfg),creds=requireCredentials(cfg),organizationId=options.org??creds?.activeOrganization?.id;if(!organizationId){ui.error({command:"projects list",code:"NO_ORGANIZATION_SPECIFIED",message:"No organization specified and no active organization set.",hint:"Run `fimo switch` or pass --org <id>."});return}let projects2=await api.listProjects(organizationId);if(projects2.length===0){ui.info({command:"projects list",message:"No projects in this organization yet."});return}ui.table({command:"projects list",columns:[{key:"published",label:"PUB"},{key:"id",label:"ID"},{key:"name",label:"NAME"},{key:"displayName",label:"DISPLAY NAME"}],rows:projects2.map(p2=>({published:p2.appUrl?"\u{1F7E2}":"\u26AA",id:p2.id,name:p2.name,displayName:p2.displayName??""}))})}__name(projectsListCommand,"projectsListCommand");async function projectsDeleteCommand(projectIdArg,options){let cfg=loadConfig(),api=new FimoApiClient(cfg),projectId=resolveProjectId6(projectIdArg,options,"projects delete");if(projectId){if(!options.yes){assertInteractive("Pass --yes to skip confirmation.","projects delete");let confirmed=await ot2({message:`Delete project ${projectId}? This cannot be undone.`,initialValue:!1});if(q(confirmed)||!confirmed){ui.info({command:"projects delete",message:"Cancelled."});return}}await api.deleteProject(projectId),ui.ok({command:"projects delete",headline:`Deleted project ${projectId}.`,details:{project_id:projectId}})}}__name(projectsDeleteCommand,"projectsDeleteCommand");async function projectsRenameCommand(nameArg,projectIdArg,options){let cwd=resolveCwd2(options),local=readLocalConfig(options);if(!local){ui.error({command:"projects rename",code:"NOT_IN_PROJECT",message:"No Fimo project link found in the current directory.",hint:"`fimo rename` only operates on a local project. cd into the project root."});return}if(projectIdArg&&projectIdArg!==local.projectId){ui.error({command:"projects rename",code:"PROJECT_ID_MISMATCH",message:`Project ID ${projectIdArg} does not match this directory's project (${local.projectId}).`,hint:"cd into the project you want to rename."});return}let name=nameArg.trim();if(!name){ui.error({command:"projects rename",code:"EMPTY_DISPLAY_NAME",message:"Display name cannot be empty."});return}let configPath=resolveProjectConfigPath(cwd),config={};if(fs43.existsSync(configPath))try{config=JSON.parse(fs43.readFileSync(configPath,"utf-8"))}catch(error){ui.error({command:"projects rename",code:"CONFIG_PARSE_FAILED",message:`Could not parse ${configPath}: ${error instanceof Error?error.message:String(error)}`});return}let seo=config.seo??{};config.seo={...seo,siteName:name},fs43.writeFileSync(configPath,JSON.stringify(config,null,2)+`
|
|
1381
|
+
`),ui.ok({command:"projects rename",headline:`Renamed to "${name}".`,details:{project_id:local.projectId,display_name:name},hint:"Commit and `fimo deploy` to sync."})}__name(projectsRenameCommand,"projectsRenameCommand");async function projectsPublishCommand(projectIdArg,options){let cfg=loadConfig(),api=new FimoApiClient(cfg),projectId=resolveProjectId6(projectIdArg,options,"projects publish");if(!projectId)return;let sp=spinner(`Publishing ${projectId}`);try{await api.publishProject(projectId),sp.succeed("Published")}catch(error){rethrowCliAuthError(error,()=>sp.fail("Authentication required")),sp.fail(),ui.error({command:"projects publish",code:"PROJECT_PUBLISH_FAILED",message:`Publish failed: ${error instanceof Error?error.message:String(error)}`});return}let appUrl=null;try{appUrl=(await api.getProject(projectId)).appUrl??null}catch{}ui.ok({command:"projects publish",headline:appUrl?`Live at ${appUrl}`:`Published ${projectId}.`,details:{project_id:projectId,app_url:appUrl}})}__name(projectsPublishCommand,"projectsPublishCommand");async function projectsUnpublishCommand(projectIdArg,options){let cfg=loadConfig(),api=new FimoApiClient(cfg),projectId=resolveProjectId6(projectIdArg,options,"projects unpublish");if(!projectId)return;let sp=spinner(`Unpublishing ${projectId}`);try{await api.unpublishProject(projectId),sp.succeed("Unpublished"),ui.ok({command:"projects unpublish",headline:`Unpublished ${projectId}.`,details:{project_id:projectId}})}catch(error){rethrowCliAuthError(error,()=>sp.fail("Authentication required")),sp.fail(),ui.error({command:"projects unpublish",code:"PROJECT_UNPUBLISH_FAILED",message:`Unpublish failed: ${error instanceof Error?error.message:String(error)}`})}}__name(projectsUnpublishCommand,"projectsUnpublishCommand");init_esm();init_dist();init_api();init_auth_errors();init_project_context();init_project();async function publishCommand(options,cmd){let program2=cmd?.parent??cmd,envOverride2=envOverrideFromCommand(program2),ctx=await getProjectContext({cwd:options.cwd,envOverride:envOverride2}),cwd=resolveProjectCwd(options.cwd);if(ctx.env!==DEFAULT_ENV){ui.error({command:"publish",code:"PUBLISH_REQUIRES_DEFAULT_ENV",message:`Refusing to publish from env '${ctx.env}'. Publish only runs from '${DEFAULT_ENV}'.`,hint:"Switch to main first: `fimo checkout main`."});return}if(!options.skipValidate){let sp=spinner("Running lint + codegen + smoke checks"),report=await runValidate({cwd,envOverride:envOverride2});if(!report.ok){sp.fail("Validation failed"),ui.result({command:"publish",data:{stage:"validate",report},render:__name(()=>formatReportHuman(report),"render")}),process.exitCode=report.exitCode;return}sp.succeed("Validation passed")}if(!options.version){ui.error({command:"publish",code:"PUBLISH_VERSION_REQUIRED",message:"--version is required (e.g. --version 1.4.2)."});return}let api=new FimoApiClient().withEnv(ctx.env),body={version:options.version,notes:options.notes},tagSp=spinner(`Tagging release/${options.version} and triggering prod swap`),result;try{result=await api.publishRelease(ctx.projectId,body)}catch(err){rethrowCliAuthError(err,()=>tagSp.fail("Authentication required")),tagSp.fail(),ui.error({command:"publish",code:"PUBLISH_FAILED",message:`Publish failed: ${err.message}`});return}tagSp.succeed(`Released ${result.releaseTag} @ ${result.sha.slice(0,8)}`),ui.ok({command:"publish",headline:"Release published \u2014 prod-swap detector will pick it up shortly.",details:{release_tag:result.releaseTag,sha:result.sha,version:options.version}})}__name(publishCommand,"publishCommand");init_dist();init_api();init_auth();init_config();async function referralLinkCommand(){let currentUser=await resolveCurrentCliUser("referral link");if(!currentUser)return;let cfg=loadConfig(),referralLink=new URL(`/invite/${encodeURIComponent(currentUser.id)}`,cfg.webUrl).toString();ui.raw({command:"referral link",value:referralLink,field:"url"})}__name(referralLinkCommand,"referralLinkCommand");async function referralStatsCommand(){let currentUser=await resolveCurrentCliUser("referral stats");if(!currentUser)return;let cfg=loadConfig(),summary2=await new FimoApiClient(cfg).getReferralSummary(currentUser.id),totalReferrals=summary2.counts.signed_up+summary2.counts.activated;ui.kv({command:"referral stats",headline:`Referral stats for ${currentUser.name||currentUser.email}`,fields:{total_referrals:totalReferrals,signed_up:summary2.counts.signed_up,activated:summary2.counts.activated,ai_credits_earned:summary2.credits.total}})}__name(referralStatsCommand,"referralStatsCommand");async function resolveCurrentCliUser(command){let cfg=loadConfig(),creds=requireCredentials(cfg);if(creds.user?.id)return creds.user;let session=await new FimoApiClient(cfg).getCurrentSession();return session?.user?.id?(writeCredentials({...creds,user:{id:session.user.id,email:session.user.email,name:session.user.name??""}},cfg),{id:session.user.id,email:session.user.email,name:session.user.name??""}):(ui.error({command,code:"SESSION_USER_MISSING",message:"Could not resolve the current user.",hint:"Run `fimo login` again."}),null)}__name(resolveCurrentCliUser,"resolveCurrentCliUser");init_dist();init_agents();init_scaffold();import fs44 from"node:fs";import path45 from"node:path";async function rulesSyncCommand(options={}){let cwd=path45.resolve(options.cwd??process.cwd()),agentsMdPath=path45.join(cwd,"AGENTS.md");if(!fs44.existsSync(agentsMdPath)){ui.error({command:"rules sync",code:"NO_AGENTS_MD",message:`No AGENTS.md found in ${cwd}.`,hint:"Run `fimo create` to scaffold a project, or create AGENTS.md manually before running `fimo rules sync`."});return}let selectedAgents;try{selectedAgents=await selectAgents(options,{promptMessage:"Which agents do you want to sync rules for?",detectFn:__name(()=>Promise.resolve(detectAgentsInProject(cwd)),"detectFn")})}catch(err){ui.error({command:"rules sync",code:"AGENT_SELECTION_FAILED",message:err instanceof Error?err.message:String(err)});return}if(selectedAgents.length===0){ui.result({command:"rules sync",data:{synced:[]},render:__name(()=>"Nothing to sync.","render")});return}let result=syncPerAgentVariants(cwd,selectedAgents),agentsWithVariants=new Set(["claude-code","cursor","windsurf","gemini-cli"]),noVariantAgents=selectedAgents.filter(a=>!agentsWithVariants.has(a)),data2={synced:result.perAgentVariants,skipped:result.perAgentVariantsSkipped,nativeAgentsMd:noVariantAgents};ui.result({command:"rules sync",data:data2,render:__name(()=>{let lines=[];return result.perAgentVariants.length>0&&lines.push(`Wrote: ${result.perAgentVariants.join(", ")}`),result.perAgentVariantsSkipped.length>0&&lines.push(`Skipped (already exist, preserved): ${result.perAgentVariantsSkipped.join(", ")}`),noVariantAgents.length>0&&lines.push(`${noVariantAgents.join(", ")}: read AGENTS.md natively \u2014 no extra file needed.`),lines.length===0?"Nothing to do.":(result.perAgentVariantsSkipped.length>0&&(lines.push(""),lines.push("Note: existing files are preserved. To regenerate a stale variant, delete it first then re-run `fimo rules sync`.")),lines.join(`
|
|
1382
|
+
`))},"render")})}__name(rulesSyncCommand,"rulesSyncCommand");init_esm();init_dist();init_api();init_config();init_project_context();init_project();var UUID_PATTERN=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,RUN_POLL_INTERVAL_MS=2e3,RUN_POLL_TIMEOUT_MS=1800*1e3,TERMINAL_RUN_STATUSES=["succeeded","failed","skipped"],ScheduleCommandError=class extends Error{static{__name(this,"ScheduleCommandError")}code;constructor(code2,message){super(message),this.name="ScheduleCommandError",this.code=code2}};function collect2(value,previous){return[...previous??[],value]}__name(collect2,"collect");function addScopeOptions3(command){return command.option("--branch <branch>","Target a specific Fimo Branch (defaults to the current git branch)").option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory")}__name(addScopeOptions3,"addScopeOptions");function registerSchedulesCommands(program2){let schedules=program2.command("schedules").description("Manage recurring project commands").addHelpText("after",`
|
|
1370
1383
|
Examples:
|
|
1371
1384
|
fimo schedules create nightly --cron "0 2 * * *" --do "fimo validate" --secret CMS_TOKEN
|
|
1372
1385
|
fimo schedules list
|
|
@@ -1384,16 +1397,16 @@ Limits:
|
|
|
1384
1397
|
Use \`fimo schedules list\` or \`show\` for the current policy and reset state.
|
|
1385
1398
|
|
|
1386
1399
|
Run \`fimo schedules <command> --help\` for command-specific help.
|
|
1387
|
-
`);addScopeOptions2(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 environment").option("--secret <key>","Expose a project secret to the command; repeat for multiple keys",collect).option("--paused","Save the schedule paused; it never runs until resumed and does not use an active slot")).action((name,opts)=>createCommand2(name,opts)),addScopeOptions2(schedules.command("list").description("List schedules for an environment")).action(opts=>listCommand3(opts)),addScopeOptions2(schedules.command("show <schedule>").description("Show a schedule configuration")).action((schedule,opts)=>showCommand(schedule,opts)),addScopeOptions2(schedules.command("update <schedule>").description("Update a schedule configuration").option("--name <name>","Change the schedule name").option("--cron <expr>","Change the cron expression").option("--do <command>","Change the command").option("--secret <key>","Replace exposed project secrets; repeat for multiple keys",collect).option("--clear-secrets","Remove all project secrets from the schedule")).action((schedule,opts)=>updateCommand(schedule,opts)),addScopeOptions2(schedules.command("run <schedule>").description("Run a schedule now").option("--no-wait","Return after the run is queued")).action((schedule,opts)=>runCommand2(schedule,opts)),addScopeOptions2(schedules.command("pause <schedule>").description("Pause future cron runs")).action((schedule,opts)=>toggleCommand(schedule,!1,opts)),addScopeOptions2(schedules.command("resume <schedule>").description("Resume future cron runs")).action((schedule,opts)=>toggleCommand(schedule,!0,opts));let runs=addScopeOptions2(schedules.command("runs [schedule]").description("List runs for a schedule").option("--limit <count>","Maximum runs per page (1-100)").option("--cursor <cursor>","Continue from an opaque cursor").option("--status <status>","Filter by queued, running, succeeded, failed, or skipped").option("--all","Fetch all pages"));runs.action((schedule,opts,command)=>{if(!schedule){command.help();return}return runsCommand(schedule,opts)}),addScopeOptions2(runs.command("show <runId>").description("Show run details and captured output")).action((runId,opts,command)=>runShowCommand(runId,{...command.parent?.opts(),...opts})),addScopeOptions2(schedules.command("delete <schedule>").description("Delete a schedule")).action((schedule,opts)=>deleteCommand(schedule,opts))}__name(registerSchedulesCommands,"registerSchedulesCommands");async function resolveScope3(op,opts){let baseApi=new FimoApiClient(loadConfig()),env=opts.env;if(!env)try{env=(await getProjectContext({cwd:opts.cwd})).env}catch(error){if(!opts.project)throw error;env=DEFAULT_ENV}let projectId=opts.project??loadProjectSettings(resolveProjectCwd(opts.cwd)).projectId;return await requireOperation(op,{projectId,env}),{projectId,api:baseApi.withEnv(env)}}__name(resolveScope3,"resolveScope");async function resolveScheduleId(api,projectId,reference){if(UUID_PATTERN.test(reference))return reference;let schedule=(await api.listSchedules(projectId)).find(candidate=>candidate.name===reference);if(!schedule)throw new ScheduleCommandError("SCHEDULE_NOT_FOUND",`Schedule '${reference}' was not found in this environment.`);return schedule.id}__name(resolveScheduleId,"resolveScheduleId");async function createCommand2(name,opts){let parsed=CreateProjectScheduleRequestSchema.safeParse({name,cron:opts.cron,command:opts.do,secretKeys:opts.secret??[],...opts.paused?{enabled:!1}:{}});if(!parsed.success)throw new ScheduleCommandError("SCHEDULE_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid schedule.");let{projectId,api}=await resolveScope3("schedules.create",opts),schedule;try{schedule=await api.createSchedule(projectId,parsed.data)}catch(error){if(renderSchedulePolicyRefusal("schedules create",error,"create"))return;throw error}renderSchedule("schedules create",schedule)}__name(createCommand2,"createCommand");async function listCommand3(opts){let{projectId,api}=await resolveScope3("schedules.list",opts);renderScheduleList("schedules list",await api.getSchedulesOverview(projectId))}__name(listCommand3,"listCommand");async function showCommand(reference,opts){let{projectId,api}=await resolveScope3("schedules.get",opts),scheduleId=await resolveScheduleId(api,projectId,reference);renderScheduleDetail("schedules show",await api.getSchedule(projectId,scheduleId))}__name(showCommand,"showCommand");async function updateCommand(reference,opts){if(opts.secret!==void 0&&opts.clearSecrets)throw new ScheduleCommandError("SCHEDULE_VALIDATION_FAILED","Use either --secret or --clear-secrets, not both.");let request={...opts.name!==void 0?{name:opts.name}:{},...opts.cron!==void 0?{cron:opts.cron}:{},...opts.do!==void 0?{command:opts.do}:{},...opts.clearSecrets?{secretKeys:[]}:opts.secret!==void 0?{secretKeys:opts.secret}:{}},parsed=UpdateProjectScheduleRequestSchema.safeParse(request);if(!parsed.success)throw new ScheduleCommandError("SCHEDULE_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid schedule update.");let{projectId,api}=await resolveScope3("schedules.update",opts),scheduleId=await resolveScheduleId(api,projectId,reference);try{renderSchedule("schedules update",await api.updateSchedule(projectId,scheduleId,parsed.data))}catch(error){if(renderSchedulePolicyRefusal("schedules update",error,"update"))return;throw error}}__name(updateCommand,"updateCommand");async function toggleCommand(reference,enabled,opts){let command=enabled?"schedules resume":"schedules pause",{projectId,api}=await resolveScope3(enabled?"schedules.resume":"schedules.pause",opts),scheduleId=await resolveScheduleId(api,projectId,reference),schedule;try{schedule=await api.setScheduleEnabled(projectId,scheduleId,enabled)}catch(error){if(renderSchedulePolicyRefusal(command,error,"resume"))return;throw error}renderSchedule(command,schedule)}__name(toggleCommand,"toggleCommand");async function runCommand2(reference,opts){let{projectId,api}=await resolveScope3("schedules.run",opts),scheduleId=await resolveScheduleId(api,projectId,reference),run;try{run=await api.runSchedule(projectId,scheduleId)}catch(error){if(renderSchedulePolicyRefusal("schedules run",error,"run"))return;if(error instanceof ApiRequestError&&error.status===409&&error.code==="run_in_progress"){let activeRunId=readActiveRunId(error.body);ui.error({command:"schedules run",code:"SCHEDULE_RUN_IN_PROGRESS",message:activeRunId?`Schedule already has an active run: ${activeRunId}`:"Schedule already has an active run.",hint:activeRunId?`Inspect it with: fimo schedules runs show ${activeRunId}`:void 0});return}throw error}if(opts.wait===!1){renderRun("schedules run",run);return}let progress=spinner(`Run ${run.id} is ${run.status}`),deadline=Date.now()+RUN_POLL_TIMEOUT_MS,detail=await api.getScheduleRun(projectId,run.id);for(;!TERMINAL_RUN_STATUSES.includes(detail.status)&&Date.now()<deadline;)progress.update(`Run ${run.id} is ${detail.status}`),await new Promise(resolve10=>setTimeout(resolve10,RUN_POLL_INTERVAL_MS)),detail=await api.getScheduleRun(projectId,run.id);if(progress.stop(),!TERMINAL_RUN_STATUSES.includes(detail.status))throw new ScheduleCommandError("SCHEDULE_RUN_TIMEOUT",`Run ${run.id} did not finish within ${RUN_POLL_TIMEOUT_MS/6e4} minutes.`);if(detail.status!=="succeeded"){let error=detail.error??"No error details were returned.";ui.error({command:"schedules run",code:"SCHEDULE_RUN_FAILED",message:`Schedule run ${detail.id} finished with status ${detail.status}: ${error}`,hint:`Inspect run ${detail.id} (status: ${detail.status}, error: ${error}) with: fimo schedules runs show ${detail.id}`});return}renderRunDetail("schedules run",detail)}__name(runCommand2,"runCommand");async function runsCommand(reference,opts){let parsed=ProjectScheduleRunsQuerySchema.safeParse({limit:opts.limit,cursor:opts.cursor,status:opts.status});if(!parsed.success)throw new ScheduleCommandError("SCHEDULE_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid run query.");let{projectId,api}=await resolveScope3("schedules.runs.list",opts),scheduleId=await resolveScheduleId(api,projectId,reference),page=await api.listScheduleRuns(projectId,scheduleId,parsed.data);if(opts.all){let items=[...page.items];for(;page.nextCursor;)page=await api.listScheduleRuns(projectId,scheduleId,{limit:parsed.data.limit,cursor:page.nextCursor,status:parsed.data.status}),items.push(...page.items);page={...page,items,nextCursor:null}}renderRuns("schedules runs",page)}__name(runsCommand,"runsCommand");async function runShowCommand(runId,opts){let{projectId,api}=await resolveScope3("schedules.runs.get",opts);renderRunDetail("schedules runs show",await api.getScheduleRun(projectId,runId))}__name(runShowCommand,"runShowCommand");async function deleteCommand(reference,opts){let{projectId,api}=await resolveScope3("schedules.delete",opts),scheduleId=await resolveScheduleId(api,projectId,reference),result=await api.deleteSchedule(projectId,scheduleId);ui.result({command:"schedules delete",data:result,render:__name(()=>`Deleted schedule ${reference} (${scheduleId})`,"render")})}__name(deleteCommand,"deleteCommand");function renderSchedulePolicyRefusal(command,error,context){if(!(error instanceof ApiRequestError)||!error.code)return!1;let presentation={active_schedule_limit_reached:{code:"SCHEDULE_LIMIT_REACHED",hint:context==="create"?"Pause another schedule, or re-run with --paused to save this one as a draft. Upgrade your plan for more active schedules.":"Pause another schedule first, then resume this one. Upgrade your plan for more active schedules."},cadence_too_frequent:{code:"SCHEDULE_CADENCE_TOO_FREQUENT",hint:"Pick a less frequent --cron expression; `fimo schedules list` shows your plan cadence floor. Upgrade your plan if you need a more frequent schedule."},allowance_exhausted:{code:"SCHEDULE_COMPUTE_EXHAUSTED",hint:"Cron runs are skipped and manual runs are rejected until the cycle resets; `fimo schedules list` shows the reset time. Editing schedules still works. Upgrade your plan for more schedule compute."},concurrency_limited:{code:"SCHEDULE_CONCURRENCY_LIMITED",hint:"Wait for a running schedule in this organization to finish, then retry. Upgrade your plan for more concurrent runs."},invalid_cron:{code:"SCHEDULE_INVALID_CRON",hint:"Use standard five-field cron syntax: minute hour day-of-month month day-of-week (for example, `0 2 * * *`)."}}[error.code];if(!presentation)return!1;let serverMessage=error.body&&typeof error.body=="object"&&typeof error.body.message=="string"?error.body.message:error.detail;return ui.error({command,code:presentation.code,message:serverMessage,hint:presentation.hint}),!0}__name(renderSchedulePolicyRefusal,"renderSchedulePolicyRefusal");function formatPlanMinutes(minutes){return minutes%60===0&&minutes>=60?`${minutes/60} h`:`${minutes} min`}__name(formatPlanMinutes,"formatPlanMinutes");function formatPlanMs(ms){return formatPlanMinutes(Math.round(ms/6e4))}__name(formatPlanMs,"formatPlanMs");function planStateNote(plan){switch(plan.state){case"near_limit":return"Over 80% of the compute cycle is used.";case"exhausted":return`Compute is exhausted. Cron runs are skipped and manual runs are rejected until ${String(plan.compute.resetsAt)}. Editing schedules still works.`;case"over_policy":return`Some schedules exceed the current plan limits (${plan.overPolicyReasons.join(", ")}). They keep running; enabling more or making them more frequent is blocked.`;default:return null}}__name(planStateNote,"planStateNote");function planFields(plan){return{Plan:plan.code,"Active schedules":`${plan.activeSchedules.used} of ${plan.activeSchedules.limit}`,"Cadence floor":`every ${formatPlanMinutes(plan.minCadenceMinutes)} or less often`,"Max run time":formatPlanMs(plan.maxRunMs),"Concurrent runs":`${plan.concurrency.used} of ${plan.concurrency.limit}`,"Compute used":`${formatPlanMs(plan.compute.settledMs+plan.compute.reservedMs)} of ${formatPlanMs(plan.compute.includedMs)}${plan.compute.reservedMs>0?` (${formatPlanMs(plan.compute.reservedMs)} reserved)`:""}`,"Cycle resets":String(plan.compute.resetsAt)}}__name(planFields,"planFields");function renderSchedule(command,schedule){ui.result({command,data:schedule,render:__name(()=>renderFields({ID:schedule.id,Name:schedule.name,Environment:schedule.env,Cron:schedule.cron,Command:schedule.command,Enabled:schedule.enabled?"yes":"no",Secrets:schedule.secretKeys.join(", ")||"none"}),"render")})}__name(renderSchedule,"renderSchedule");function renderScheduleList(command,data2){ui.result({command,data:data2,render:__name(()=>{let table=renderTable(["ID","NAME","CRON","COMMAND","ENABLED","LAST STATUS","POLICY"],data2.items.map(schedule=>[schedule.id,schedule.name,schedule.cron,schedule.command,schedule.enabled?"yes":"no",schedule.lastStatus??"",schedule.overPolicyReasons?.join(", ")??""])),note=planStateNote(data2.plan);return`${table}
|
|
1400
|
+
`);addScopeOptions3(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 Branch").option("--secret <key>","Expose a project secret to the command; repeat for multiple keys",collect2).option("--paused","Save the schedule paused; it never runs until resumed and does not use an active slot")).action((name,opts)=>createCommand3(name,opts)),addScopeOptions3(schedules.command("list").description("List schedules for a Branch")).action(opts=>listCommand4(opts)),addScopeOptions3(schedules.command("show <schedule>").description("Show a schedule configuration")).action((schedule,opts)=>showCommand(schedule,opts)),addScopeOptions3(schedules.command("update <schedule>").description("Update a schedule configuration").option("--name <name>","Change the schedule name").option("--cron <expr>","Change the cron expression").option("--do <command>","Change the command").option("--secret <key>","Replace exposed project secrets; repeat for multiple keys",collect2).option("--clear-secrets","Remove all project secrets from the schedule")).action((schedule,opts)=>updateCommand2(schedule,opts)),addScopeOptions3(schedules.command("run <schedule>").description("Run a schedule now").option("--no-wait","Return after the run is queued")).action((schedule,opts)=>runCommand2(schedule,opts)),addScopeOptions3(schedules.command("pause <schedule>").description("Pause future cron runs")).action((schedule,opts)=>toggleCommand(schedule,!1,opts)),addScopeOptions3(schedules.command("resume <schedule>").description("Resume future cron runs")).action((schedule,opts)=>toggleCommand(schedule,!0,opts));let runs=addScopeOptions3(schedules.command("runs [schedule]").description("List runs for a schedule").option("--limit <count>","Maximum runs per page (1-100)").option("--cursor <cursor>","Continue from an opaque cursor").option("--status <status>","Filter by queued, running, succeeded, failed, or skipped").option("--all","Fetch all pages"));runs.action((schedule,opts,command)=>{if(!schedule){command.help();return}return runsCommand(schedule,opts)}),addScopeOptions3(runs.command("show <runId>").description("Show run details and captured output")).action((runId,opts,command)=>runShowCommand(runId,{...command.parent?.opts(),...opts})),addScopeOptions3(schedules.command("delete <schedule>").description("Delete a schedule")).action((schedule,opts)=>deleteCommand2(schedule,opts))}__name(registerSchedulesCommands,"registerSchedulesCommands");async function resolveScope4(op,opts){let baseApi=new FimoApiClient(loadConfig()),branch=opts.branch;if(!branch)try{branch=(await getProjectContext({cwd:opts.cwd})).env}catch(error){if(!opts.project)throw error;branch=DEFAULT_ENV}let projectId=opts.project??loadProjectSettings(resolveProjectCwd(opts.cwd)).projectId;return await requireOperation(op,{projectId,env:branch}),{projectId,api:baseApi.withEnv(branch)}}__name(resolveScope4,"resolveScope");async function resolveScheduleId(api,projectId,reference){if(UUID_PATTERN.test(reference))return reference;let schedule=(await api.listSchedules(projectId)).find(candidate=>candidate.name===reference);if(!schedule)throw new ScheduleCommandError("SCHEDULE_NOT_FOUND",`Schedule '${reference}' was not found in this Branch.`);return schedule.id}__name(resolveScheduleId,"resolveScheduleId");async function createCommand3(name,opts){let parsed=CreateProjectScheduleRequestSchema.safeParse({name,cron:opts.cron,command:opts.do,secretKeys:opts.secret??[],...opts.paused?{enabled:!1}:{}});if(!parsed.success)throw new ScheduleCommandError("SCHEDULE_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid schedule.");let{projectId,api}=await resolveScope4("schedules.create",opts),schedule;try{schedule=await api.createSchedule(projectId,parsed.data)}catch(error){if(renderSchedulePolicyRefusal("schedules create",error,"create"))return;throw error}renderSchedule("schedules create",schedule)}__name(createCommand3,"createCommand");async function listCommand4(opts){let{projectId,api}=await resolveScope4("schedules.list",opts);renderScheduleList("schedules list",await api.getSchedulesOverview(projectId))}__name(listCommand4,"listCommand");async function showCommand(reference,opts){let{projectId,api}=await resolveScope4("schedules.get",opts),scheduleId=await resolveScheduleId(api,projectId,reference);renderScheduleDetail("schedules show",await api.getSchedule(projectId,scheduleId))}__name(showCommand,"showCommand");async function updateCommand2(reference,opts){if(opts.secret!==void 0&&opts.clearSecrets)throw new ScheduleCommandError("SCHEDULE_VALIDATION_FAILED","Use either --secret or --clear-secrets, not both.");let request={...opts.name!==void 0?{name:opts.name}:{},...opts.cron!==void 0?{cron:opts.cron}:{},...opts.do!==void 0?{command:opts.do}:{},...opts.clearSecrets?{secretKeys:[]}:opts.secret!==void 0?{secretKeys:opts.secret}:{}},parsed=UpdateProjectScheduleRequestSchema.safeParse(request);if(!parsed.success)throw new ScheduleCommandError("SCHEDULE_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid schedule update.");let{projectId,api}=await resolveScope4("schedules.update",opts),scheduleId=await resolveScheduleId(api,projectId,reference);try{renderSchedule("schedules update",await api.updateSchedule(projectId,scheduleId,parsed.data))}catch(error){if(renderSchedulePolicyRefusal("schedules update",error,"update"))return;throw error}}__name(updateCommand2,"updateCommand");async function toggleCommand(reference,enabled,opts){let command=enabled?"schedules resume":"schedules pause",{projectId,api}=await resolveScope4(enabled?"schedules.resume":"schedules.pause",opts),scheduleId=await resolveScheduleId(api,projectId,reference),schedule;try{schedule=await api.setScheduleEnabled(projectId,scheduleId,enabled)}catch(error){if(renderSchedulePolicyRefusal(command,error,"resume"))return;throw error}renderSchedule(command,schedule)}__name(toggleCommand,"toggleCommand");async function runCommand2(reference,opts){let{projectId,api}=await resolveScope4("schedules.run",opts),scheduleId=await resolveScheduleId(api,projectId,reference),run;try{run=await api.runSchedule(projectId,scheduleId)}catch(error){if(renderSchedulePolicyRefusal("schedules run",error,"run"))return;if(error instanceof ApiRequestError&&error.status===409&&error.code==="run_in_progress"){let activeRunId=readActiveRunId(error.body);ui.error({command:"schedules run",code:"SCHEDULE_RUN_IN_PROGRESS",message:activeRunId?`Schedule already has an active run: ${activeRunId}`:"Schedule already has an active run.",hint:activeRunId?`Inspect it with: fimo schedules runs show ${activeRunId}`:void 0});return}throw error}if(opts.wait===!1){renderRun("schedules run",run);return}let progress=spinner(`Run ${run.id} is ${run.status}`),deadline=Date.now()+RUN_POLL_TIMEOUT_MS,detail=await api.getScheduleRun(projectId,run.id);for(;!TERMINAL_RUN_STATUSES.includes(detail.status)&&Date.now()<deadline;)progress.update(`Run ${run.id} is ${detail.status}`),await new Promise(resolve10=>setTimeout(resolve10,RUN_POLL_INTERVAL_MS)),detail=await api.getScheduleRun(projectId,run.id);if(progress.stop(),!TERMINAL_RUN_STATUSES.includes(detail.status))throw new ScheduleCommandError("SCHEDULE_RUN_TIMEOUT",`Run ${run.id} did not finish within ${RUN_POLL_TIMEOUT_MS/6e4} minutes.`);if(detail.status!=="succeeded"){let error=detail.error??"No error details were returned.";ui.error({command:"schedules run",code:"SCHEDULE_RUN_FAILED",message:`Schedule run ${detail.id} finished with status ${detail.status}: ${error}`,hint:`Inspect run ${detail.id} (status: ${detail.status}, error: ${error}) with: fimo schedules runs show ${detail.id}`});return}renderRunDetail("schedules run",detail)}__name(runCommand2,"runCommand");async function runsCommand(reference,opts){let parsed=ProjectScheduleRunsQuerySchema.safeParse({limit:opts.limit,cursor:opts.cursor,status:opts.status});if(!parsed.success)throw new ScheduleCommandError("SCHEDULE_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid run query.");let{projectId,api}=await resolveScope4("schedules.runs.list",opts),scheduleId=await resolveScheduleId(api,projectId,reference),page=await api.listScheduleRuns(projectId,scheduleId,parsed.data);if(opts.all){let items=[...page.items];for(;page.nextCursor;)page=await api.listScheduleRuns(projectId,scheduleId,{limit:parsed.data.limit,cursor:page.nextCursor,status:parsed.data.status}),items.push(...page.items);page={...page,items,nextCursor:null}}renderRuns("schedules runs",page)}__name(runsCommand,"runsCommand");async function runShowCommand(runId,opts){let{projectId,api}=await resolveScope4("schedules.runs.get",opts);renderRunDetail("schedules runs show",await api.getScheduleRun(projectId,runId))}__name(runShowCommand,"runShowCommand");async function deleteCommand2(reference,opts){let{projectId,api}=await resolveScope4("schedules.delete",opts),scheduleId=await resolveScheduleId(api,projectId,reference),result=await api.deleteSchedule(projectId,scheduleId);ui.result({command:"schedules delete",data:result,render:__name(()=>`Deleted schedule ${reference} (${scheduleId})`,"render")})}__name(deleteCommand2,"deleteCommand");function renderSchedulePolicyRefusal(command,error,context){if(!(error instanceof ApiRequestError)||!error.code)return!1;let presentation={active_schedule_limit_reached:{code:"SCHEDULE_LIMIT_REACHED",hint:context==="create"?"Pause another schedule, or re-run with --paused to save this one as a draft. Upgrade your plan for more active schedules.":"Pause another schedule first, then resume this one. Upgrade your plan for more active schedules."},cadence_too_frequent:{code:"SCHEDULE_CADENCE_TOO_FREQUENT",hint:"Pick a less frequent --cron expression; `fimo schedules list` shows your plan cadence floor. Upgrade your plan if you need a more frequent schedule."},allowance_exhausted:{code:"SCHEDULE_COMPUTE_EXHAUSTED",hint:"Cron runs are skipped and manual runs are rejected until the cycle resets; `fimo schedules list` shows the reset time. Editing schedules still works. Upgrade your plan for more schedule compute."},concurrency_limited:{code:"SCHEDULE_CONCURRENCY_LIMITED",hint:"Wait for a running schedule in this organization to finish, then retry. Upgrade your plan for more concurrent runs."},invalid_cron:{code:"SCHEDULE_INVALID_CRON",hint:"Use standard five-field cron syntax: minute hour day-of-month month day-of-week (for example, `0 2 * * *`)."}}[error.code];if(!presentation)return!1;let serverMessage=error.body&&typeof error.body=="object"&&typeof error.body.message=="string"?error.body.message:error.detail;return ui.error({command,code:presentation.code,message:serverMessage,hint:presentation.hint}),!0}__name(renderSchedulePolicyRefusal,"renderSchedulePolicyRefusal");function formatPlanMinutes(minutes){return minutes%60===0&&minutes>=60?`${minutes/60} h`:`${minutes} min`}__name(formatPlanMinutes,"formatPlanMinutes");function formatPlanMs(ms){return formatPlanMinutes(Math.round(ms/6e4))}__name(formatPlanMs,"formatPlanMs");function planStateNote(plan){switch(plan.state){case"near_limit":return"Over 80% of the compute cycle is used.";case"exhausted":return`Compute is exhausted. Cron runs are skipped and manual runs are rejected until ${String(plan.compute.resetsAt)}. Editing schedules still works.`;case"over_policy":return`Some schedules exceed the current plan limits (${plan.overPolicyReasons.join(", ")}). They keep running; enabling more or making them more frequent is blocked.`;default:return null}}__name(planStateNote,"planStateNote");function planFields(plan){return{Plan:plan.code,"Active schedules":`${plan.activeSchedules.used} of ${plan.activeSchedules.limit}`,"Cadence floor":`every ${formatPlanMinutes(plan.minCadenceMinutes)} or less often`,"Max run time":formatPlanMs(plan.maxRunMs),"Concurrent runs":`${plan.concurrency.used} of ${plan.concurrency.limit}`,"Compute used":`${formatPlanMs(plan.compute.settledMs+plan.compute.reservedMs)} of ${formatPlanMs(plan.compute.includedMs)}${plan.compute.reservedMs>0?` (${formatPlanMs(plan.compute.reservedMs)} reserved)`:""}`,"Cycle resets":String(plan.compute.resetsAt)}}__name(planFields,"planFields");function renderSchedule(command,schedule){ui.result({command,data:schedule,render:__name(()=>renderFields({ID:schedule.id,Name:schedule.name,Branch:schedule.env,Cron:schedule.cron,Command:schedule.command,Enabled:schedule.enabled?"yes":"no",Secrets:schedule.secretKeys.join(", ")||"none"}),"render")})}__name(renderSchedule,"renderSchedule");function renderScheduleList(command,data2){ui.result({command,data:data2,render:__name(()=>{let table=renderTable(["ID","NAME","CRON","COMMAND","ENABLED","LAST STATUS","POLICY"],data2.items.map(schedule=>[schedule.id,schedule.name,schedule.cron,schedule.command,schedule.enabled?"yes":"no",schedule.lastStatus??"",schedule.overPolicyReasons?.join(", ")??""])),note=planStateNote(data2.plan);return`${table}
|
|
1388
1401
|
|
|
1389
1402
|
${renderFields(planFields(data2.plan))}${note?`
|
|
1390
1403
|
|
|
1391
|
-
${note}`:""}`},"render")})}__name(renderScheduleList,"renderScheduleList");function renderScheduleDetail(command,data2){ui.result({command,data:data2,render:__name(()=>{let note=planStateNote(data2.plan),overPolicyReasons=data2.schedule.overPolicyReasons??[];return`${renderFields({ID:data2.schedule.id,Name:data2.schedule.name,
|
|
1404
|
+
${note}`:""}`},"render")})}__name(renderScheduleList,"renderScheduleList");function renderScheduleDetail(command,data2){ui.result({command,data:data2,render:__name(()=>{let note=planStateNote(data2.plan),overPolicyReasons=data2.schedule.overPolicyReasons??[];return`${renderFields({ID:data2.schedule.id,Name:data2.schedule.name,Branch:data2.schedule.env,Cron:data2.schedule.cron,Command:data2.schedule.command,Enabled:data2.schedule.enabled?"yes":"no",Secrets:data2.schedule.secretKeys.join(", ")||"none",...overPolicyReasons.length>0?{"Policy reasons":overPolicyReasons.join(", ")}:{},Runs:data2.usage.runCount,"Runs with output":data2.usage.runsWithOutput,"Maximum runs":data2.policy.maxRuns,"Metadata retention":data2.policy.retentionDays===null?"pending":`${data2.policy.retentionDays} days`,"Output retention":`${data2.policy.outputRetentionDays} days`,"Maximum output":`${data2.policy.maxOutputBytes} bytes`,...planFields(data2.plan)})}${note?`
|
|
1392
1405
|
|
|
1393
1406
|
${note}`:""}
|
|
1394
1407
|
`},"render")})}__name(renderScheduleDetail,"renderScheduleDetail");function renderRun(command,run){ui.result({command,data:run,render:__name(()=>renderFields({"Run ID":run.id,Schedule:run.scheduleName,Command:run.command,Status:run.status,Trigger:run.trigger,Queued:String(run.queuedAt)}),"render")})}__name(renderRun,"renderRun");function renderRuns(command,data2){ui.result({command,data:data2,render:__name(()=>`${renderTable(["RUN ID","STATUS","TRIGGER","ACTOR","QUEUED","STARTED","FINISHED"],data2.items.map(run=>[run.id,run.status,run.trigger,run.triggeredBy?.name??"",String(run.queuedAt),run.startedAt?String(run.startedAt):"",run.finishedAt?String(run.finishedAt):""]))}
|
|
1395
1408
|
|
|
1396
|
-
${renderFields({"Run count":data2.usage.runCount,"Runs with output":data2.usage.runsWithOutput,"Maximum runs":data2.policy.maxRuns,"Metadata retention":data2.policy.retentionDays===null?"pending":`${data2.policy.retentionDays} days`,"Output retention":`${data2.policy.outputRetentionDays} days`,"Maximum output":`${data2.policy.maxOutputBytes} bytes`,"Next cursor":data2.nextCursor??"none"})}`,"render")})}__name(renderRuns,"renderRuns");function renderRunDetail(command,run){ui.result({command,data:run,render:__name(()=>{let fields=renderFields({"Run ID":run.id,"Schedule ID":run.scheduleId,Schedule:run.scheduleName,Command:run.command,
|
|
1409
|
+
${renderFields({"Run count":data2.usage.runCount,"Runs with output":data2.usage.runsWithOutput,"Maximum runs":data2.policy.maxRuns,"Metadata retention":data2.policy.retentionDays===null?"pending":`${data2.policy.retentionDays} days`,"Output retention":`${data2.policy.outputRetentionDays} days`,"Maximum output":`${data2.policy.maxOutputBytes} bytes`,"Next cursor":data2.nextCursor??"none"})}`,"render")})}__name(renderRuns,"renderRuns");function renderRunDetail(command,run){ui.result({command,data:run,render:__name(()=>{let fields=renderFields({"Run ID":run.id,"Schedule ID":run.scheduleId,Schedule:run.scheduleName,Command:run.command,Branch:run.env,Status:run.status,Trigger:run.trigger,Actor:run.triggeredBy?.name??"",Queued:String(run.queuedAt),Started:run.startedAt?String(run.startedAt):"",Finished:run.finishedAt?String(run.finishedAt):"","Exit code":run.exitCode??"","Error code":run.errorCode??"",Error:run.error??"","Output bytes":run.outputBytes,"Output truncated":run.outputTruncated?"yes":"no","Output expires":run.outputExpiresAt?String(run.outputExpiresAt):"","Metadata expires":run.metadataExpiresAt?String(run.metadataExpiresAt):"","Secret snapshot":run.secretSnapshot.state,Secrets:run.secretSnapshot.items.map(item=>`${item.key} (${item.resolution})`).join(", ")||"none"});return run.output?`${fields}
|
|
1397
1410
|
|
|
1398
1411
|
Output
|
|
1399
1412
|
${run.output}`:fields},"render")})}__name(renderRunDetail,"renderRunDetail");function renderFields(fields){let width=Math.max(...Object.keys(fields).map(key=>key.length));return Object.entries(fields).map(([key,value])=>`${key.padEnd(width)} ${String(value)}`).join(`
|
|
@@ -1409,7 +1422,7 @@ Examples:
|
|
|
1409
1422
|
Report: ${result.id}
|
|
1410
1423
|
Project: ${reportContext.projectName}
|
|
1411
1424
|
Environment: ${reportContext.environment}`,"render")})}catch(error){rethrowCliAuthError(error),ui.error({command:"support report",code:"SUPPORT_REPORT_FAILED",message:error instanceof Error?error.message:"The support report could not be sent.",hint:"Try again later, or contact Fimo support through the app."})}}__name(supportReportCommand,"supportReportCommand");function resolveSupportMessage(messageParts,messageFile){if(messageParts.length>0&&messageFile)return ui.error({command:"support report",code:"SUPPORT_MESSAGE_CONFLICT",message:"Pass the report as text or with --message-file, not both."}),null;let message=messageParts.join(" ").trim();if(messageFile)try{message=readFileSync11(path47.resolve(messageFile),"utf8").trim()}catch(error){return ui.error({command:"support report",code:"SUPPORT_MESSAGE_READ_FAILED",message:error instanceof Error?error.message:"The report file could not be read."}),null}return message||(ui.error({command:"support report",code:"SUPPORT_MESSAGE_REQUIRED",message:"Describe what went wrong or which capability is missing, or pass --message-file <path>."}),null)}__name(resolveSupportMessage,"resolveSupportMessage");function buildSupportMessage(context){return[context.message,"","Fimo CLI context",`Project: ${context.projectName} (${context.projectId})`,`Environment: ${context.environment}`,`Fimo CLI: ${context.cliVersion}`].join(`
|
|
1412
|
-
`)}__name(buildSupportMessage,"buildSupportMessage");init_dist5();init_dist();init_api();init_auth();init_config();init_interactive();async function switchCommand(options={}){let cfg=loadConfig(),creds=requireCredentials(cfg),orgs2=await new FimoApiClient(cfg).listOrganizations();if(orgs2.length===0){ui.error({command:"orgs switch",code:"NO_ORGANIZATIONS",message:"No organization found for this account."});return}if(options.org){let target2=orgs2.find(org=>org.id===options.org)??orgs2.find(org=>org.slug===options.org);if(!target2){ui.error({command:"orgs switch",code:"ORGANIZATION_NOT_FOUND",message:`No organization matched "${options.org}".`,hint:"Run `fimo orgs list` to see available orgs."});return}setActiveOrganization({id:target2.id,name:target2.name,slug:target2.slug},cfg),ui.ok({command:"orgs switch",headline:`Active organization: ${target2.name}`,details:{id:target2.id,name:target2.name,slug:target2.slug}});return}assertInteractive("Pass --org <id-or-slug>.","orgs switch"),mt("Switch active organization");let currentId=creds.activeOrganization?.id,selected=await _t({message:"Select an organization",initialValue:currentId,options:orgs2.map(org=>({value:org.id,label:org.name,hint:org.id===currentId?"current":org.slug}))});if(q(selected)){ui.info({command:"orgs switch",message:"Cancelled."});return}let target=orgs2.find(org=>org.id===selected);if(!target){ui.error({command:"orgs switch",code:"ORGANIZATION_NOT_FOUND",message:"Selected organization not found."});return}setActiveOrganization({id:target.id,name:target.name,slug:target.slug},cfg),ui.ok({command:"orgs switch",headline:`Active organization: ${target.name}`,details:{id:target.id,name:target.name,slug:target.slug}})}__name(switchCommand,"switchCommand");init_esm();init_dist();init_api();init_config();import{readFile as readFile5}from"node:fs/promises";import{resolve as resolve9}from"node:path";init_project_context();init_project();var WebhookCommandError=class extends Error{static{__name(this,"WebhookCommandError")}code;constructor(code2,message){super(message),this.name="WebhookCommandError",this.code=code2}};function
|
|
1425
|
+
`)}__name(buildSupportMessage,"buildSupportMessage");init_dist5();init_dist();init_api();init_auth();init_config();init_interactive();async function switchCommand(options={}){let cfg=loadConfig(),creds=requireCredentials(cfg),orgs2=await new FimoApiClient(cfg).listOrganizations();if(orgs2.length===0){ui.error({command:"orgs switch",code:"NO_ORGANIZATIONS",message:"No organization found for this account."});return}if(options.org){let target2=orgs2.find(org=>org.id===options.org)??orgs2.find(org=>org.slug===options.org);if(!target2){ui.error({command:"orgs switch",code:"ORGANIZATION_NOT_FOUND",message:`No organization matched "${options.org}".`,hint:"Run `fimo orgs list` to see available orgs."});return}setActiveOrganization({id:target2.id,name:target2.name,slug:target2.slug},cfg),ui.ok({command:"orgs switch",headline:`Active organization: ${target2.name}`,details:{id:target2.id,name:target2.name,slug:target2.slug}});return}assertInteractive("Pass --org <id-or-slug>.","orgs switch"),mt("Switch active organization");let currentId=creds.activeOrganization?.id,selected=await _t({message:"Select an organization",initialValue:currentId,options:orgs2.map(org=>({value:org.id,label:org.name,hint:org.id===currentId?"current":org.slug}))});if(q(selected)){ui.info({command:"orgs switch",message:"Cancelled."});return}let target=orgs2.find(org=>org.id===selected);if(!target){ui.error({command:"orgs switch",code:"ORGANIZATION_NOT_FOUND",message:"Selected organization not found."});return}setActiveOrganization({id:target.id,name:target.name,slug:target.slug},cfg),ui.ok({command:"orgs switch",headline:`Active organization: ${target.name}`,details:{id:target.id,name:target.name,slug:target.slug}})}__name(switchCommand,"switchCommand");init_esm();init_dist();init_api();init_config();import{readFile as readFile5}from"node:fs/promises";import{resolve as resolve9}from"node:path";init_project_context();init_project();var WebhookCommandError=class extends Error{static{__name(this,"WebhookCommandError")}code;constructor(code2,message){super(message),this.name="WebhookCommandError",this.code=code2}};function addScopeOptions4(command){return command.option("--project <id>","Project id (defaults to the locally linked project)").option("-C, --cwd <dir>","Project directory")}__name(addScopeOptions4,"addScopeOptions");function collect3(value,previous){return[...previous??[],value]}__name(collect3,"collect");function registerWebhooksCommands(program2){let webhooks=program2.command("webhooks").description("Manage outbound project webhooks").addHelpText("after",`
|
|
1413
1426
|
Examples:
|
|
1414
1427
|
fimo webhooks events
|
|
1415
1428
|
fimo webhooks events form.submitted
|
|
@@ -1419,10 +1432,10 @@ Examples:
|
|
|
1419
1432
|
fimo webhooks deliveries <webhook-id>
|
|
1420
1433
|
|
|
1421
1434
|
Header values use Name=secret:KEY, Name=bearer:KEY, Name=token:KEY, or Name=literal:value. There are no CLI presets: pass the provider request explicitly.
|
|
1422
|
-
`);addScopeOptions3(webhooks.command("events [eventType]").description("List events or describe one event and its example payload")).action((eventType,opts,command)=>eventsCommand(eventType,opts,command)),addScopeOptions3(webhooks.command("list").description("List project webhooks")).action((opts,command)=>listCommand4(opts,command)),addScopeOptions3(webhooks.command("get <webhookId>").description("Show a webhook configuration")).action((webhookId,opts,command)=>getCommand(webhookId,opts,command)),addScopeOptions3(webhooks.command("create <name>").description("Create an outbound webhook").requiredOption("--event <event>","Event type, for example form.submitted").requiredOption("--url <url>","HTTPS destination URL").option("--header <name=source:value>","Add a literal or secret-backed header; repeat for multiple headers",collect2).option("--body <json|@file|->","Custom JSON payload inline, from @file, or stdin with -").option("--form <id>","Only form.submitted events for this form id").option("--agent <name>","Only agent events for this agent name").option("--media-type <type>","Only media events for image, video, audio, document, or other").option("--action <action>","Only entry.changed events with created, updated, or deleted entries").option("--content-type <name>","Only entry.changed events for this content type").option("--locale <locale>","Only entry.changed events for this locale").option("--environments <main|all>","Deliver events from main or all environments","main").option("--debounce-changes <immediate|5s|30s|1m>","Combine rapid entry.changed events into one delivery").option("--disabled","Create the webhook disabled").option("--no-signing","Do not add X-Fimo-Signature headers")).action((name,opts,command)=>createCommand3(name,opts,command)),addScopeOptions3(webhooks.command("update <webhookId>").description("Update an outbound webhook").option("--name <name>","Change the webhook name").option("--event <event>","Change the event type").option("--url <url>","Change the HTTPS destination URL").option("--header <name=source:value>","Replace headers; repeat for multiple headers",collect2).option("--clear-headers","Remove all configured destination headers").option("--body <json|@file|->","Replace the custom payload inline, from @file, or stdin with -").option("--default-body","Send the full event envelope instead of a custom template").option("--form <id>","Filter form.submitted by form id").option("--agent <name>","Filter agent events by agent name").option("--media-type <type>","Filter media events by media type").option("--action <action>","Filter entry.changed by created, updated, or deleted").option("--content-type <name>","Filter entry.changed by content type").option("--locale <locale>","Filter entry.changed by locale").option("--environments <main|all>","Deliver events from main or all environments").option("--debounce-changes <immediate|5s|30s|1m>","Change the entry.changed debounce window").option("--clear-filter","Remove all event filters").option("--enabled <on|off>","Enable or disable delivery").option("--signing <on|off>","Enable or disable X-Fimo-Signature headers")).action((webhookId,opts,command)=>updateCommand2(webhookId,opts,command)),addScopeOptions3(webhooks.command("delete <webhookId>").description("Delete an outbound webhook")).action((webhookId,opts,command)=>deleteCommand2(webhookId,opts,command)),addScopeOptions3(webhooks.command("test <webhookId>").description("Queue a test delivery using example event data").option("--data <json>","Override the event data with a JSON object").option("--wait","Wait up to 60 seconds for the delivery to succeed or fail")).action((webhookId,opts,command)=>testCommand(webhookId,opts,command)),addScopeOptions3(webhooks.command("deliveries <webhookId>").description("List recent webhook deliveries").option("--limit <count>","Maximum deliveries to return (1-100)")).action((webhookId,opts,command)=>deliveriesCommand(webhookId,opts,command)),addScopeOptions3(webhooks.command("delivery <webhookId> <deliveryId>").description("Show a delivery and all attempts")).action((webhookId,deliveryId,opts,command)=>deliveryCommand(webhookId,deliveryId,opts,command)),addScopeOptions3(webhooks.command("retry <webhookId> <deliveryId>").description("Retry an exhausted failed delivery now")).action((webhookId,deliveryId,opts,command)=>retryCommand2(webhookId,deliveryId,opts,command)),addScopeOptions3(webhooks.command("rotate-secret <webhookId>").description("Rotate and reveal a new signing secret once")).action((webhookId,opts,command)=>rotateSecretCommand(webhookId,opts,command))}__name(registerWebhooksCommands,"registerWebhooksCommands");async function resolveScope4(op,opts,_command){let scope;if(opts.project)scope={projectId:opts.project};else{let ctx=await getProjectContext({cwd:opts.cwd});scope={projectId:ctx.projectId,env:ctx.env}}return await requireOperation(op,scope),{...scope,api:new FimoApiClient(loadConfig())}}__name(resolveScope4,"resolveScope");async function eventsCommand(eventType,opts,command){let{api,projectId}=await resolveScope4("webhooks.events",opts,command),events=await api.listWebhookEvents(projectId);if(eventType){let event=events.find(candidate=>candidate.type===eventType);if(!event)throw new WebhookCommandError("WEBHOOK_EVENT_NOT_FOUND",`Unknown webhook event '${eventType}'.`);renderJson("webhooks events",event);return}ui.table({command:"webhooks events",columns:[{key:"event",label:"EVENT"},{key:"family",label:"FAMILY"},{key:"description",label:"DESCRIPTION"},{key:"variables",label:"VARIABLES"}],rows:events.map(event=>({event:event.type,family:event.family,description:event.description,variables:event.variables.join(", ")}))})}__name(eventsCommand,"eventsCommand");async function listCommand4(opts,command){let{api,projectId}=await resolveScope4("webhooks.list",opts,command),webhooks=await api.listProjectWebhooks(projectId);ui.table({command:"webhooks list",columns:[{key:"id",label:"ID"},{key:"name",label:"NAME"},{key:"event",label:"EVENT"},{key:"destination",label:"DESTINATION"},{key:"enabled",label:"ENABLED"},{key:"last",label:"LAST DELIVERY"}],rows:webhooks.map(webhook=>({id:webhook.id,name:webhook.name,event:webhook.eventType,destination:webhook.destination.maskedUrl,enabled:webhook.enabled?"yes":"no",last:webhook.lastDeliveryStatus??""}))})}__name(listCommand4,"listCommand");async function getCommand(webhookId,opts,command){let{api,projectId}=await resolveScope4("webhooks.get",opts,command);renderJson("webhooks get",await api.getProjectWebhook(projectId,webhookId))}__name(getCommand,"getCommand");async function createCommand3(name,opts,command){let{api,projectId}=await resolveScope4("webhooks.create",opts,command),parsed=CreateProjectWebhookRequestSchema.safeParse({name,eventType:opts.event,url:opts.url,enabled:!opts.disabled,filter:createFilter(opts),headers:parseHeaders(opts.header),bodyTemplate:opts.body===void 0?null:await parseJsonInput(opts.body,"--body",opts.cwd),signingEnabled:opts.signing!==!1,entryBatchWindowSeconds:parseEntryBatchWindow(opts.debounceChanges??(opts.event==="entry.changed"?"5s":"immediate"))});if(!parsed.success)throw new WebhookCommandError("WEBHOOK_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid webhook.");let result=await api.createProjectWebhook(projectId,parsed.data);renderJson("webhooks create",{webhook:result.webhook,signingSecret:result.signingSecret,note:"Save the signing secret now. Fimo will not show this value again."})}__name(createCommand3,"createCommand");async function updateCommand2(webhookId,opts,command){let{api,projectId}=await resolveScope4("webhooks.update",opts,command);if(opts.header&&opts.clearHeaders)throw new WebhookCommandError("WEBHOOK_FLAGS_CONFLICT","Use either --header or --clear-headers, not both.");if(opts.body!==void 0&&opts.defaultBody)throw new WebhookCommandError("WEBHOOK_FLAGS_CONFLICT","Use either --body or --default-body, not both.");let current=await api.getProjectWebhook(projectId,webhookId),filter4=createUpdateFilter(current,opts),request={...opts.name!==void 0?{name:opts.name}:{},...opts.event!==void 0?{eventType:opts.event}:{},...opts.url!==void 0?{url:opts.url}:{},...opts.header!==void 0||opts.clearHeaders?{headers:parseHeaders(opts.header)}:{},...opts.body!==void 0?{bodyTemplate:await parseJsonInput(opts.body,"--body",opts.cwd)}:{},...opts.defaultBody?{bodyTemplate:null}:{},...filter4?{filter:filter4}:{},...opts.enabled!==void 0?{enabled:parseOnOff(opts.enabled,"--enabled")}:{},...opts.signing!==void 0?{signingEnabled:parseOnOff(opts.signing,"--signing")}:{},...opts.debounceChanges!==void 0?{entryBatchWindowSeconds:parseEntryBatchWindow(opts.debounceChanges)}:opts.event==="entry.changed"&¤t.eventType!=="entry.changed"?{entryBatchWindowSeconds:5}:{}},parsed=UpdateProjectWebhookRequestSchema.safeParse(request);if(!parsed.success)throw new WebhookCommandError("WEBHOOK_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid webhook.");if(Object.keys(parsed.data).length===0)throw new WebhookCommandError("WEBHOOK_UPDATE_EMPTY","Pass at least one field to update.");renderJson("webhooks update",await api.updateProjectWebhook(projectId,webhookId,parsed.data))}__name(updateCommand2,"updateCommand");async function deleteCommand2(webhookId,opts,command){let{api,projectId}=await resolveScope4("webhooks.delete",opts,command);await api.deleteProjectWebhook(projectId,webhookId),ui.ok({command:"webhooks delete",headline:`Deleted webhook ${webhookId}`,details:{project_id:projectId,webhook_id:webhookId}})}__name(deleteCommand2,"deleteCommand");async function testCommand(webhookId,opts,command){let{api,projectId}=await resolveScope4("webhooks.test",opts,command),data2=opts.data===void 0?void 0:parseJsonObject3(opts.data,"--data"),delivery=await api.testProjectWebhook(projectId,webhookId,{data:data2});if(opts.wait){let deadline=Date.now()+6e4;for(;!["succeeded","failed"].includes(delivery.status)&&Date.now()<deadline;)await new Promise(resolveWait=>setTimeout(resolveWait,500)),delivery=(await api.getProjectWebhookDelivery(projectId,webhookId,delivery.id)).delivery;if(!["succeeded","failed"].includes(delivery.status))throw new WebhookCommandError("WEBHOOK_DELIVERY_TIMEOUT",`Delivery ${delivery.id} did not finish within 60 seconds.`)}renderJson("webhooks test",delivery)}__name(testCommand,"testCommand");async function deliveriesCommand(webhookId,opts,command){let{api,projectId}=await resolveScope4("webhooks.deliveries.list",opts,command),limit=opts.limit===void 0?void 0:parseLimit2(opts.limit),deliveries=await api.listProjectWebhookDeliveries(projectId,webhookId,limit);ui.table({command:"webhooks deliveries",columns:[{key:"id",label:"DELIVERY"},{key:"event",label:"EVENT"},{key:"status",label:"STATUS"},{key:"attempts",label:"ATTEMPTS"},{key:"response",label:"RESPONSE"},{key:"created",label:"CREATED"}],rows:deliveries.map(delivery=>({id:delivery.id,event:delivery.eventType,status:delivery.status,attempts:delivery.attemptCount,response:delivery.responseStatus??"",created:String(delivery.createdAt)}))})}__name(deliveriesCommand,"deliveriesCommand");async function deliveryCommand(webhookId,deliveryId,opts,command){let{api,projectId}=await resolveScope4("webhooks.deliveries.get",opts,command);renderJson("webhooks delivery",await api.getProjectWebhookDelivery(projectId,webhookId,deliveryId))}__name(deliveryCommand,"deliveryCommand");async function retryCommand2(webhookId,deliveryId,opts,command){let{api,projectId}=await resolveScope4("webhooks.deliveries.retry",opts,command);renderJson("webhooks retry",await api.retryProjectWebhookDelivery(projectId,webhookId,deliveryId))}__name(retryCommand2,"retryCommand");async function rotateSecretCommand(webhookId,opts,command){let{api,projectId}=await resolveScope4("webhooks.rotate_secret",opts,command),signingSecret=await api.rotateProjectWebhookSecret(projectId,webhookId);renderJson("webhooks rotate-secret",{webhookId,signingSecret,note:"Save the signing secret now. Fimo will not show this value again."})}__name(rotateSecretCommand,"rotateSecretCommand");function createFilter(opts){return parseFilter({...opts.environments?{environment:opts.environments}:{},...opts.form?{formId:opts.form}:{},...opts.agent?{agentName:opts.agent}:{},...opts.mediaType?{mediaType:opts.mediaType}:{},...opts.action?{action:opts.action}:{},...opts.contentType?{contentType:opts.contentType}:{},...opts.locale?{locale:opts.locale}:{}})}__name(createFilter,"createFilter");function parseFilter(value){let parsed=WebhookFilterSchema.safeParse(value);if(!parsed.success)throw new WebhookCommandError("WEBHOOK_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid webhook filter.");return parsed.data}__name(parseFilter,"parseFilter");function parseEntryBatchWindow(value){let parsed={immediate:0,"5s":5,"30s":30,"1m":60}[value.toLowerCase()];if(parsed===void 0)throw new WebhookCommandError("WEBHOOK_GROUPING_INVALID",`Invalid grouping window '${value}'. Use immediate, 5s, 30s, or 1m.`);return parsed}__name(parseEntryBatchWindow,"parseEntryBatchWindow");function hasFilterOptions(opts){return!!(opts.clearFilter||opts.environments||opts.form||opts.agent||opts.mediaType||opts.action||opts.contentType||opts.locale)}__name(hasFilterOptions,"hasFilterOptions");function createUpdateFilter(current,opts){if(!hasFilterOptions(opts))return;if(opts.clearFilter)return createFilter({environments:opts.environments??"main"});let environment=opts.environments??current.filter.environment??"main";return!(opts.form||opts.agent||opts.mediaType||opts.action||opts.contentType||opts.locale)?parseFilter({...current.filter,environment}):createFilter({...opts,environments:environment})}__name(createUpdateFilter,"createUpdateFilter");function parseHeaders(values){return(values??[]).map(entry=>{let separator=entry.indexOf("=");if(separator<=0)throw new WebhookCommandError("WEBHOOK_HEADER_INVALID",`Invalid --header '${entry}'. Use Name=secret:KEY, Name=bearer:KEY, Name=token:KEY, or Name=literal:value.`);let name=entry.slice(0,separator).trim(),encoded=entry.slice(separator+1);if(encoded.startsWith("secret:"))return{name,value:{source:"secret",key:encoded.slice(7)}};if(encoded.startsWith("bearer:"))return{name,value:{source:"secret",key:encoded.slice(7),prefix:"Bearer "}};if(encoded.startsWith("token:"))return{name,value:{source:"secret",key:encoded.slice(6),prefix:"token "}};if(encoded.startsWith("literal:"))return{name,value:{source:"literal",value:encoded.slice(8)}};throw new WebhookCommandError("WEBHOOK_HEADER_INVALID",`Invalid --header '${entry}'. Use Name=secret:KEY, Name=bearer:KEY, Name=token:KEY, or Name=literal:value.`)})}__name(parseHeaders,"parseHeaders");function parseJson(value,flag2){try{return JSON.parse(value)}catch{throw new WebhookCommandError("WEBHOOK_JSON_INVALID",`${flag2} must be valid JSON. Quote the value so your shell passes it as one argument.`)}}__name(parseJson,"parseJson");async function parseJsonInput(value,flag2,cwd){let input=value;if(value==="-")input=await readStdin2();else if(value.startsWith("@")){let path49=resolve9(resolveProjectCwd(cwd),value.slice(1));try{input=await readFile5(path49,"utf8")}catch{throw new WebhookCommandError("WEBHOOK_INPUT_READ_FAILED",`Could not read ${flag2} input from '${path49}'.`)}}return parseJson(input,flag2)}__name(parseJsonInput,"parseJsonInput");async function readStdin2(){let input="";process.stdin.setEncoding("utf8");for await(let chunk of process.stdin)input+=chunk;return input}__name(readStdin2,"readStdin");function parseJsonObject3(value,flag2){let parsed=parseJson(value,flag2);if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new WebhookCommandError("WEBHOOK_DATA_INVALID",`${flag2} must be a JSON object.`);return parsed}__name(parseJsonObject3,"parseJsonObject");function parseOnOff(value,flag2){if(value==="on")return!0;if(value==="off")return!1;throw new WebhookCommandError("WEBHOOK_TOGGLE_INVALID",`${flag2} must be 'on' or 'off'.`)}__name(parseOnOff,"parseOnOff");function parseLimit2(value){let limit=Number(value);if(!Number.isInteger(limit)||limit<1||limit>100)throw new WebhookCommandError("WEBHOOK_LIMIT_INVALID","--limit must be an integer from 1 to 100.");return limit}__name(parseLimit2,"parseLimit");function renderJson(command,data2){ui.result({command,data:data2,render:__name(()=>JSON.stringify(data2,null,2),"render")})}__name(renderJson,"renderJson");init_dist();init_auth();async function whoamiCommand(){let creds=requireCredentials();if(!creds.user){ui.error({command:"whoami",code:"NOT_AUTHENTICATED",message:"Could not resolve the current user from local credentials.",hint:"Run `fimo login` again."});return}let displayName=creds.user.name||creds.user.email,activeOrganization=creds.activeOrganization?.name??null;ui.kv({command:"whoami",headline:`Signed in as ${displayName} (${creds.user.email})`,fields:{user:displayName,email:creds.user.email,active_organization:activeOrganization},hint:activeOrganization===null?"Run `fimo orgs switch` to pick an active organization.":void 0})}__name(whoamiCommand,"whoamiCommand");init_config();var TOP_LEVEL_HELP_GROUPS=[{title:"Account",commands:["login","logout","whoami"]},{title:"Project lifecycle",commands:["create","migrate","deploy","validate","describe"]},{title:"Projects & teams",commands:["projects","orgs","invite","credits","referral","rename","delete","unpublish"]},{title:"Environments & releases",commands:["status","branch","checkout","switch","pull","diff","merge","publish","preview"]},{title:"Content & media",commands:["schemas","entries","forms","translations","assets","generate","models"]},{title:"Domains & analytics",commands:["domains","analytics"]},{title:"Agents & integrations",commands:["agents","skills","rules","integrations","channels","mcp"]},{title:"Configuration",commands:["vars","secrets"]},{title:"Help",commands:["support","help"]}];function configureGroupedHelp(program2){program2.configureHelp({...program2.configureHelp(),formatHelp:__name((cmd,helper)=>formatHelpWithGroupedCommands(cmd,helper,TOP_LEVEL_HELP_GROUPS),"formatHelp")})}__name(configureGroupedHelp,"configureGroupedHelp");function formatHelpWithGroupedCommands(cmd,helper,groups){let termWidth=helper.padWidth(cmd,helper),helpWidth=helper.helpWidth??80,formatItem=__name((term,description)=>helper.formatItem(term,termWidth,description,helper),"formatItem"),output=[`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,""],commandDescription=helper.commandDescription(cmd);commandDescription.length>0&&(output=output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription),helpWidth),""]));let argumentList=helper.visibleArguments(cmd).map(argument=>formatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)),helper.styleArgumentDescription(helper.argumentDescription(argument))));argumentList.length>0&&(output=output.concat([helper.styleTitle("Arguments:"),...argumentList,""]));let optionList=helper.visibleOptions(cmd).map(option=>formatItem(helper.styleOptionTerm(helper.optionTerm(option)),helper.styleOptionDescription(helper.optionDescription(option))));if(optionList.length>0&&(output=output.concat([helper.styleTitle("Options:"),...optionList,""])),helper.showGlobalOptions){let globalOptionList=helper.visibleGlobalOptions(cmd).map(option=>formatItem(helper.styleOptionTerm(helper.optionTerm(option)),helper.styleOptionDescription(helper.optionDescription(option))));globalOptionList.length>0&&(output=output.concat([helper.styleTitle("Global Options:"),...globalOptionList,""]))}let commandSections=formatGroupedCommandSections(cmd,helper,groups,termWidth);return commandSections.length>0&&(output=output.concat([helper.styleTitle("Commands:"),...commandSections,""])),output.join(`
|
|
1435
|
+
`);addScopeOptions4(webhooks.command("events [eventType]").description("List events or describe one event and its example payload")).action((eventType,opts,command)=>eventsCommand(eventType,opts,command)),addScopeOptions4(webhooks.command("list").description("List project webhooks")).action((opts,command)=>listCommand5(opts,command)),addScopeOptions4(webhooks.command("get <webhookId>").description("Show a webhook configuration")).action((webhookId,opts,command)=>getCommand(webhookId,opts,command)),addScopeOptions4(webhooks.command("create <name>").description("Create an outbound webhook").requiredOption("--event <event>","Event type, for example form.submitted").requiredOption("--url <url>","HTTPS destination URL").option("--header <name=source:value>","Add a literal or secret-backed header; repeat for multiple headers",collect3).option("--body <json|@file|->","Custom JSON payload inline, from @file, or stdin with -").option("--form <id>","Only form.submitted events for this form id").option("--agent <name>","Only agent events for this agent name").option("--media-type <type>","Only media events for image, video, audio, document, or other").option("--action <action>","Only entry.changed events with created, updated, or deleted entries").option("--content-type <name>","Only entry.changed events for this content type").option("--locale <locale>","Only entry.changed events for this locale").option("--environments <selector>","Deliver from main, all Branches, Production, Automatic previews, or a custom Environment id","main").option("--debounce-changes <immediate|5s|30s|1m>","Combine rapid entry.changed events into one delivery").option("--disabled","Create the webhook disabled").option("--no-signing","Do not add X-Fimo-Signature headers")).action((name,opts,command)=>createCommand4(name,opts,command)),addScopeOptions4(webhooks.command("update <webhookId>").description("Update an outbound webhook").option("--name <name>","Change the webhook name").option("--event <event>","Change the event type").option("--url <url>","Change the HTTPS destination URL").option("--header <name=source:value>","Replace headers; repeat for multiple headers",collect3).option("--clear-headers","Remove all configured destination headers").option("--body <json|@file|->","Replace the custom payload inline, from @file, or stdin with -").option("--default-body","Send the full event envelope instead of a custom template").option("--form <id>","Filter form.submitted by form id").option("--agent <name>","Filter agent events by agent name").option("--media-type <type>","Filter media events by media type").option("--action <action>","Filter entry.changed by created, updated, or deleted").option("--content-type <name>","Filter entry.changed by content type").option("--locale <locale>","Filter entry.changed by locale").option("--environments <selector>","Deliver from main, all Branches, Production, Automatic previews, or a custom Environment id").option("--debounce-changes <immediate|5s|30s|1m>","Change the entry.changed debounce window").option("--clear-filter","Remove all event filters").option("--enabled <on|off>","Enable or disable delivery").option("--signing <on|off>","Enable or disable X-Fimo-Signature headers")).action((webhookId,opts,command)=>updateCommand3(webhookId,opts,command)),addScopeOptions4(webhooks.command("delete <webhookId>").description("Delete an outbound webhook")).action((webhookId,opts,command)=>deleteCommand3(webhookId,opts,command)),addScopeOptions4(webhooks.command("test <webhookId>").description("Queue a test delivery using example event data").option("--data <json>","Override the event data with a JSON object").option("--wait","Wait up to 60 seconds for the delivery to succeed or fail")).action((webhookId,opts,command)=>testCommand(webhookId,opts,command)),addScopeOptions4(webhooks.command("deliveries <webhookId>").description("List recent webhook deliveries").option("--limit <count>","Maximum deliveries to return (1-100)")).action((webhookId,opts,command)=>deliveriesCommand(webhookId,opts,command)),addScopeOptions4(webhooks.command("delivery <webhookId> <deliveryId>").description("Show a delivery and all attempts")).action((webhookId,deliveryId,opts,command)=>deliveryCommand(webhookId,deliveryId,opts,command)),addScopeOptions4(webhooks.command("retry <webhookId> <deliveryId>").description("Retry an exhausted failed delivery now")).action((webhookId,deliveryId,opts,command)=>retryCommand2(webhookId,deliveryId,opts,command)),addScopeOptions4(webhooks.command("rotate-secret <webhookId>").description("Rotate and reveal a new signing secret once")).action((webhookId,opts,command)=>rotateSecretCommand(webhookId,opts,command))}__name(registerWebhooksCommands,"registerWebhooksCommands");async function resolveScope5(op,opts,_command){let scope;if(opts.project)scope={projectId:opts.project};else{let ctx=await getProjectContext({cwd:opts.cwd});scope={projectId:ctx.projectId,env:ctx.env}}return await requireOperation(op,scope),{...scope,api:new FimoApiClient(loadConfig())}}__name(resolveScope5,"resolveScope");async function eventsCommand(eventType,opts,command){let{api,projectId}=await resolveScope5("webhooks.events",opts,command),events=await api.listWebhookEvents(projectId);if(eventType){let event=events.find(candidate=>candidate.type===eventType);if(!event)throw new WebhookCommandError("WEBHOOK_EVENT_NOT_FOUND",`Unknown webhook event '${eventType}'.`);renderJson("webhooks events",event);return}ui.table({command:"webhooks events",columns:[{key:"event",label:"EVENT"},{key:"family",label:"FAMILY"},{key:"description",label:"DESCRIPTION"},{key:"variables",label:"VARIABLES"}],rows:events.map(event=>({event:event.type,family:event.family,description:event.description,variables:event.variables.join(", ")}))})}__name(eventsCommand,"eventsCommand");async function listCommand5(opts,command){let{api,projectId}=await resolveScope5("webhooks.list",opts,command),webhooks=await api.listProjectWebhooks(projectId);ui.table({command:"webhooks list",columns:[{key:"id",label:"ID"},{key:"name",label:"NAME"},{key:"event",label:"EVENT"},{key:"destination",label:"DESTINATION"},{key:"enabled",label:"ENABLED"},{key:"last",label:"LAST DELIVERY"}],rows:webhooks.map(webhook=>({id:webhook.id,name:webhook.name,event:webhook.eventType,destination:webhook.destination.maskedUrl,enabled:webhook.enabled?"yes":"no",last:webhook.lastDeliveryStatus??""}))})}__name(listCommand5,"listCommand");async function getCommand(webhookId,opts,command){let{api,projectId}=await resolveScope5("webhooks.get",opts,command);renderJson("webhooks get",await api.getProjectWebhook(projectId,webhookId))}__name(getCommand,"getCommand");async function createCommand4(name,opts,command){let{api,projectId}=await resolveScope5("webhooks.create",opts,command),parsed=CreateProjectWebhookRequestSchema.safeParse({name,eventType:opts.event,url:opts.url,enabled:!opts.disabled,filter:createFilter(opts),headers:parseHeaders(opts.header),bodyTemplate:opts.body===void 0?null:await parseJsonInput(opts.body,"--body",opts.cwd),signingEnabled:opts.signing!==!1,entryBatchWindowSeconds:parseEntryBatchWindow(opts.debounceChanges??(opts.event==="entry.changed"?"5s":"immediate"))});if(!parsed.success)throw new WebhookCommandError("WEBHOOK_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid webhook.");let result=await api.createProjectWebhook(projectId,parsed.data);renderJson("webhooks create",{webhook:result.webhook,signingSecret:result.signingSecret,note:"Save the signing secret now. Fimo will not show this value again."})}__name(createCommand4,"createCommand");async function updateCommand3(webhookId,opts,command){let{api,projectId}=await resolveScope5("webhooks.update",opts,command);if(opts.header&&opts.clearHeaders)throw new WebhookCommandError("WEBHOOK_FLAGS_CONFLICT","Use either --header or --clear-headers, not both.");if(opts.body!==void 0&&opts.defaultBody)throw new WebhookCommandError("WEBHOOK_FLAGS_CONFLICT","Use either --body or --default-body, not both.");let current=await api.getProjectWebhook(projectId,webhookId),filter4=createUpdateFilter(current,opts),request={...opts.name!==void 0?{name:opts.name}:{},...opts.event!==void 0?{eventType:opts.event}:{},...opts.url!==void 0?{url:opts.url}:{},...opts.header!==void 0||opts.clearHeaders?{headers:parseHeaders(opts.header)}:{},...opts.body!==void 0?{bodyTemplate:await parseJsonInput(opts.body,"--body",opts.cwd)}:{},...opts.defaultBody?{bodyTemplate:null}:{},...filter4?{filter:filter4}:{},...opts.enabled!==void 0?{enabled:parseOnOff(opts.enabled,"--enabled")}:{},...opts.signing!==void 0?{signingEnabled:parseOnOff(opts.signing,"--signing")}:{},...opts.debounceChanges!==void 0?{entryBatchWindowSeconds:parseEntryBatchWindow(opts.debounceChanges)}:opts.event==="entry.changed"&¤t.eventType!=="entry.changed"?{entryBatchWindowSeconds:5}:{}},parsed=UpdateProjectWebhookRequestSchema.safeParse(request);if(!parsed.success)throw new WebhookCommandError("WEBHOOK_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid webhook.");if(Object.keys(parsed.data).length===0)throw new WebhookCommandError("WEBHOOK_UPDATE_EMPTY","Pass at least one field to update.");renderJson("webhooks update",await api.updateProjectWebhook(projectId,webhookId,parsed.data))}__name(updateCommand3,"updateCommand");async function deleteCommand3(webhookId,opts,command){let{api,projectId}=await resolveScope5("webhooks.delete",opts,command);await api.deleteProjectWebhook(projectId,webhookId),ui.ok({command:"webhooks delete",headline:`Deleted webhook ${webhookId}`,details:{project_id:projectId,webhook_id:webhookId}})}__name(deleteCommand3,"deleteCommand");async function testCommand(webhookId,opts,command){let{api,projectId}=await resolveScope5("webhooks.test",opts,command),data2=opts.data===void 0?void 0:parseJsonObject3(opts.data,"--data"),delivery=await api.testProjectWebhook(projectId,webhookId,{data:data2});if(opts.wait){let deadline=Date.now()+6e4;for(;!["succeeded","failed"].includes(delivery.status)&&Date.now()<deadline;)await new Promise(resolveWait=>setTimeout(resolveWait,500)),delivery=(await api.getProjectWebhookDelivery(projectId,webhookId,delivery.id)).delivery;if(!["succeeded","failed"].includes(delivery.status))throw new WebhookCommandError("WEBHOOK_DELIVERY_TIMEOUT",`Delivery ${delivery.id} did not finish within 60 seconds.`)}renderJson("webhooks test",delivery)}__name(testCommand,"testCommand");async function deliveriesCommand(webhookId,opts,command){let{api,projectId}=await resolveScope5("webhooks.deliveries.list",opts,command),limit=opts.limit===void 0?void 0:parseLimit2(opts.limit),deliveries=await api.listProjectWebhookDeliveries(projectId,webhookId,limit);ui.table({command:"webhooks deliveries",columns:[{key:"id",label:"DELIVERY"},{key:"event",label:"EVENT"},{key:"status",label:"STATUS"},{key:"attempts",label:"ATTEMPTS"},{key:"response",label:"RESPONSE"},{key:"created",label:"CREATED"}],rows:deliveries.map(delivery=>({id:delivery.id,event:delivery.eventType,status:delivery.status,attempts:delivery.attemptCount,response:delivery.responseStatus??"",created:String(delivery.createdAt)}))})}__name(deliveriesCommand,"deliveriesCommand");async function deliveryCommand(webhookId,deliveryId,opts,command){let{api,projectId}=await resolveScope5("webhooks.deliveries.get",opts,command);renderJson("webhooks delivery",await api.getProjectWebhookDelivery(projectId,webhookId,deliveryId))}__name(deliveryCommand,"deliveryCommand");async function retryCommand2(webhookId,deliveryId,opts,command){let{api,projectId}=await resolveScope5("webhooks.deliveries.retry",opts,command);renderJson("webhooks retry",await api.retryProjectWebhookDelivery(projectId,webhookId,deliveryId))}__name(retryCommand2,"retryCommand");async function rotateSecretCommand(webhookId,opts,command){let{api,projectId}=await resolveScope5("webhooks.rotate_secret",opts,command),signingSecret=await api.rotateProjectWebhookSecret(projectId,webhookId);renderJson("webhooks rotate-secret",{webhookId,signingSecret,note:"Save the signing secret now. Fimo will not show this value again."})}__name(rotateSecretCommand,"rotateSecretCommand");function createFilter(opts){return parseFilter({...opts.environments?{environment:opts.environments}:{},...opts.form?{formId:opts.form}:{},...opts.agent?{agentName:opts.agent}:{},...opts.mediaType?{mediaType:opts.mediaType}:{},...opts.action?{action:opts.action}:{},...opts.contentType?{contentType:opts.contentType}:{},...opts.locale?{locale:opts.locale}:{}})}__name(createFilter,"createFilter");function parseFilter(value){let parsed=WebhookFilterSchema.safeParse(value);if(!parsed.success)throw new WebhookCommandError("WEBHOOK_VALIDATION_FAILED",parsed.error.issues[0]?.message??"Invalid webhook filter.");return parsed.data}__name(parseFilter,"parseFilter");function parseEntryBatchWindow(value){let parsed={immediate:0,"5s":5,"30s":30,"1m":60}[value.toLowerCase()];if(parsed===void 0)throw new WebhookCommandError("WEBHOOK_GROUPING_INVALID",`Invalid grouping window '${value}'. Use immediate, 5s, 30s, or 1m.`);return parsed}__name(parseEntryBatchWindow,"parseEntryBatchWindow");function hasFilterOptions(opts){return!!(opts.clearFilter||opts.environments||opts.form||opts.agent||opts.mediaType||opts.action||opts.contentType||opts.locale)}__name(hasFilterOptions,"hasFilterOptions");function createUpdateFilter(current,opts){if(!hasFilterOptions(opts))return;if(opts.clearFilter)return createFilter({environments:opts.environments??"main"});let environment=opts.environments??current.filter.environment??"main";return!(opts.form||opts.agent||opts.mediaType||opts.action||opts.contentType||opts.locale)?parseFilter({...current.filter,environment}):createFilter({...opts,environments:environment})}__name(createUpdateFilter,"createUpdateFilter");function parseHeaders(values){return(values??[]).map(entry=>{let separator=entry.indexOf("=");if(separator<=0)throw new WebhookCommandError("WEBHOOK_HEADER_INVALID",`Invalid --header '${entry}'. Use Name=secret:KEY, Name=bearer:KEY, Name=token:KEY, or Name=literal:value.`);let name=entry.slice(0,separator).trim(),encoded=entry.slice(separator+1);if(encoded.startsWith("secret:"))return{name,value:{source:"secret",key:encoded.slice(7)}};if(encoded.startsWith("bearer:"))return{name,value:{source:"secret",key:encoded.slice(7),prefix:"Bearer "}};if(encoded.startsWith("token:"))return{name,value:{source:"secret",key:encoded.slice(6),prefix:"token "}};if(encoded.startsWith("literal:"))return{name,value:{source:"literal",value:encoded.slice(8)}};throw new WebhookCommandError("WEBHOOK_HEADER_INVALID",`Invalid --header '${entry}'. Use Name=secret:KEY, Name=bearer:KEY, Name=token:KEY, or Name=literal:value.`)})}__name(parseHeaders,"parseHeaders");function parseJson(value,flag2){try{return JSON.parse(value)}catch{throw new WebhookCommandError("WEBHOOK_JSON_INVALID",`${flag2} must be valid JSON. Quote the value so your shell passes it as one argument.`)}}__name(parseJson,"parseJson");async function parseJsonInput(value,flag2,cwd){let input=value;if(value==="-")input=await readStdin2();else if(value.startsWith("@")){let path49=resolve9(resolveProjectCwd(cwd),value.slice(1));try{input=await readFile5(path49,"utf8")}catch{throw new WebhookCommandError("WEBHOOK_INPUT_READ_FAILED",`Could not read ${flag2} input from '${path49}'.`)}}return parseJson(input,flag2)}__name(parseJsonInput,"parseJsonInput");async function readStdin2(){let input="";process.stdin.setEncoding("utf8");for await(let chunk of process.stdin)input+=chunk;return input}__name(readStdin2,"readStdin");function parseJsonObject3(value,flag2){let parsed=parseJson(value,flag2);if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new WebhookCommandError("WEBHOOK_DATA_INVALID",`${flag2} must be a JSON object.`);return parsed}__name(parseJsonObject3,"parseJsonObject");function parseOnOff(value,flag2){if(value==="on")return!0;if(value==="off")return!1;throw new WebhookCommandError("WEBHOOK_TOGGLE_INVALID",`${flag2} must be 'on' or 'off'.`)}__name(parseOnOff,"parseOnOff");function parseLimit2(value){let limit=Number(value);if(!Number.isInteger(limit)||limit<1||limit>100)throw new WebhookCommandError("WEBHOOK_LIMIT_INVALID","--limit must be an integer from 1 to 100.");return limit}__name(parseLimit2,"parseLimit");function renderJson(command,data2){ui.result({command,data:data2,render:__name(()=>JSON.stringify(data2,null,2),"render")})}__name(renderJson,"renderJson");init_dist();init_auth();async function whoamiCommand(){let creds=requireCredentials();if(!creds.user){ui.error({command:"whoami",code:"NOT_AUTHENTICATED",message:"Could not resolve the current user from local credentials.",hint:"Run `fimo login` again."});return}let displayName=creds.user.name||creds.user.email,activeOrganization=creds.activeOrganization?.name??null;ui.kv({command:"whoami",headline:`Signed in as ${displayName} (${creds.user.email})`,fields:{user:displayName,email:creds.user.email,active_organization:activeOrganization},hint:activeOrganization===null?"Run `fimo orgs switch` to pick an active organization.":void 0})}__name(whoamiCommand,"whoamiCommand");init_config();var TOP_LEVEL_HELP_GROUPS=[{title:"Account",commands:["login","logout","whoami"]},{title:"Project lifecycle",commands:["create","migrate","deploy","validate","describe"]},{title:"Projects & teams",commands:["projects","orgs","invite","credits","referral","rename","delete","unpublish"]},{title:"Environments & releases",commands:["environments","status","branch","checkout","switch","pull","diff","merge","publish","preview"]},{title:"Content & media",commands:["schemas","entries","forms","translations","assets","generate","models"]},{title:"Domains & analytics",commands:["domains","analytics"]},{title:"Agents & integrations",commands:["agents","skills","rules","integrations","channels","mcp"]},{title:"Configuration",commands:["vars","secrets"]},{title:"Help",commands:["support","help"]}];function configureGroupedHelp(program2){program2.configureHelp({...program2.configureHelp(),formatHelp:__name((cmd,helper)=>formatHelpWithGroupedCommands(cmd,helper,TOP_LEVEL_HELP_GROUPS),"formatHelp")})}__name(configureGroupedHelp,"configureGroupedHelp");function formatHelpWithGroupedCommands(cmd,helper,groups){let termWidth=helper.padWidth(cmd,helper),helpWidth=helper.helpWidth??80,formatItem=__name((term,description)=>helper.formatItem(term,termWidth,description,helper),"formatItem"),output=[`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,""],commandDescription=helper.commandDescription(cmd);commandDescription.length>0&&(output=output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription),helpWidth),""]));let argumentList=helper.visibleArguments(cmd).map(argument=>formatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)),helper.styleArgumentDescription(helper.argumentDescription(argument))));argumentList.length>0&&(output=output.concat([helper.styleTitle("Arguments:"),...argumentList,""]));let optionList=helper.visibleOptions(cmd).map(option=>formatItem(helper.styleOptionTerm(helper.optionTerm(option)),helper.styleOptionDescription(helper.optionDescription(option))));if(optionList.length>0&&(output=output.concat([helper.styleTitle("Options:"),...optionList,""])),helper.showGlobalOptions){let globalOptionList=helper.visibleGlobalOptions(cmd).map(option=>formatItem(helper.styleOptionTerm(helper.optionTerm(option)),helper.styleOptionDescription(helper.optionDescription(option))));globalOptionList.length>0&&(output=output.concat([helper.styleTitle("Global Options:"),...globalOptionList,""]))}let commandSections=formatGroupedCommandSections(cmd,helper,groups,termWidth);return commandSections.length>0&&(output=output.concat([helper.styleTitle("Commands:"),...commandSections,""])),output.join(`
|
|
1423
1436
|
`)}__name(formatHelpWithGroupedCommands,"formatHelpWithGroupedCommands");function formatGroupedCommandSections(cmd,helper,groups,termWidth){let visibleCommands=helper.visibleCommands(cmd);if(visibleCommands.length===0)return[];let commandByName=new Map(visibleCommands.map(command=>[command.name(),command])),renderedNames=new Set,sections=[];for(let group of groups){let rows=group.commands.map(name=>commandByName.get(name)).filter(command=>command!==void 0).map(command=>(renderedNames.add(command.name()),indentBlock(helper.formatItem(helper.styleSubcommandTerm(helper.subcommandTerm(command)),termWidth,helper.styleSubcommandDescription(helper.subcommandDescription(command)),helper))));rows.length>0&&(sections.length>0&§ions.push(""),sections.push(` ${group.title}:`,...rows))}let ungroupedRows=visibleCommands.filter(command=>!renderedNames.has(command.name())).map(command=>indentBlock(helper.formatItem(helper.styleSubcommandTerm(helper.subcommandTerm(command)),termWidth,helper.styleSubcommandDescription(helper.subcommandDescription(command)),helper)));return ungroupedRows.length>0&&(sections.length>0&§ions.push(""),sections.push(" Other commands:",...ungroupedRows)),sections}__name(formatGroupedCommandSections,"formatGroupedCommandSections");function indentBlock(value){return value.split(`
|
|
1424
1437
|
`).map(line=>` ${line}`).join(`
|
|
1425
|
-
`)}__name(indentBlock,"indentBlock");init_agents();init_auth_errors();init_project_context();function computeVersionString(){let pkgVersion="0.0.0";try{let pkg=JSON.parse(fs46.readFileSync(path48.join(CLI_ROOT,"package.json"),"utf8"));typeof pkg.version=="string"&&pkg.version.length>0&&(pkgVersion=pkg.version)}catch{}let releaseId;try{let release=JSON.parse(fs46.readFileSync(path48.join(CLI_ROOT,"release.json"),"utf8"));typeof release.id=="string"&&release.id.length>0&&(releaseId=release.id)}catch{}let{apiUrl}=loadConfig(),detailParts=[];return releaseId&&detailParts.push(`release ${releaseId}`),detailParts.push(apiUrl),`fimo ${pkgVersion} (${detailParts.join(", ")})`}__name(computeVersionString,"computeVersionString");program.name("fimo").description("Fimo CLI").version(computeVersionString()).option("--env <name>","Override the env this command targets (defaults to the current git branch, falling back to `main`)").option("--json","Emit one structured JSON envelope per command (for tools / agents). FIMO_OUTPUT=json env also enables this.").option("--no-color","Disable colour in pretty mode (NO_COLOR env var also honoured)").option("--ascii","Use ASCII fallbacks for unicode glyphs (\u2713 \u2192 [ok], etc.) - for legacy terminals").hook("preAction",thisCommand=>{let opts=thisCommand.optsWithGlobals();initUi({json:opts.json===!0,noColor:opts.color===!1,ascii:opts.ascii===!0,jsonEnvVar:"FIMO_OUTPUT",asciiEnvVar:"FIMO_ASCII"})});program.command("login").description("Sign in through your browser").action(loginCommand);program.command("logout").description("Revoke the current session and clear local credentials").action(logoutCommand);program.command("whoami").description("Show the current signed-in user").action(whoamiCommand);registerProjectSecretsCommands(program);registerIntegrationsCommands(program);registerChannelsCommands(program);registerSchedulesCommands(program);registerHistoryCommands(program);registerSupportCommands(program);registerWebhooksCommands(program);registerLocalesCommands(program);program.command("invite").description("Invite a user to an organization or project").option("--target <target>","Invite target: organization or project").option("--org <organizationId>","Organization ID (defaults to active when needed)").option("--project <projectId>","Project ID (defaults to the current project when available)").option("--email <email>","Email address of the user to invite").option("--role <role>","Role or access level to grant").option("-C, --cwd <dir>","Project directory used to resolve the current project").option("-y, --yes","Skip the confirmation prompt").option("--resend","Resend an existing pending organization invite").action(inviteCommand);program.command("mcp").description("Serve the Fimo MCP server over stdio (for MCP clients such as Claude Code or Cursor)").action(mcpCommand);program.command("clone").description("Clone an existing Fimo project locally").argument("[projectId]","Project ID to clone").argument("[dir]","Target directory (defaults to the project name)").option("--env <name>","Env to clone (defaults to main)").action(cloneCommand);program.command("link").description("Link the current application to a Fimo project, in place (repairs an existing link)").argument("[projectId]","Project ID to link (defaults to the linked project, else prompts)").option("--env <name>","Env to link (defaults to the current git branch, else main)").option("-C, --cwd <dir>","Application directory").action(linkCommand);program.command("init").description("Set up a Fimo project locally: sign in, create or link a project, install deps and skills").argument("[dir]","Target directory").option("--project-id <id>","Link an existing project instead of creating a new one").option("--org <organizationId>","Target organization ID when creating (recommended for agents and CI)").option("--env <name>","Env to check out when linking an existing project (defaults to main)").option("--framework <framework>","Project scaffold: react-router | astro | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory when creating").option("--starter <id>","Add an opt-in project starter (for example fimo-site@1)").option("--package-manager <pm>","Install dependencies with: npm | pnpm | yarn | bun").option("--install","Install dependencies after checkout").option("--no-install","Skip dependency installation after checkout").option("--skills","Install the global Fimo skill for your AI coding agents").option("--no-skills","Skip installing the global Fimo skill").option("--agents <list>",'Comma-separated list of AI agents to install the global Fimo skill for (e.g. claude-code,cursor). Pass "none" to skip.').option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("-y, --yes","Run non-interactively using defaults (no prompts)").action(initCommand);var migrate=program.command("migrate").description("Prepare agent-ready migrations from existing websites into Fimo").argument("[url]","Published source site URL for the agent-ready migration draft").argument("[dir]","Target Fimo project directory (creates one if empty/missing)").option("-C, --cwd <dir>","Existing project directory when omitting [dir]").option("--org <organizationId>","Target organization ID when creating a new project").option("--template-root <path>","Override template directory when creating a new project").option("--install","Install dependencies after scaffolding a new project").option("--no-install","Skip dependency installation after scaffolding a new project").option("--agents <list>","Comma-separated list of AI agents to set up when creating a new project (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("--mode <mode>","Project skill install method for newly created projects: symlink | copy").option("--max-pages <n>","Maximum number of HTML pages to crawl (default 12)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--route <path>",'Limit the refinement pack to one route (for example "/contact")').action((url,dir,options)=>{if(!url){migrate.help();return}return migrateRunCommand(url,dir,options)});migrate.command("init").description("Create or reuse a Fimo project, crawl a live site, and write migration artifacts").argument("<url>","Published source site URL").argument("[dir]","Target Fimo project directory (creates one if empty/missing)").option("-C, --cwd <dir>","Existing project directory when omitting [dir]").option("--org <organizationId>","Target organization ID when creating a new project").option("--template-root <path>","Override template directory when creating a new project").option("--install","Install dependencies after scaffolding a new project").option("--no-install","Skip dependency installation after scaffolding a new project").option("--agents <list>","Comma-separated list of AI agents to set up when creating a new project (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("--mode <mode>","Project skill install method for newly created projects: symlink | copy").option("--max-pages <n>","Maximum number of HTML pages to crawl (default 12)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--json","Output the resulting manifest as JSON").action(migrateInitCommand);migrate.command("pull").description("Refresh the current migration artifacts from the source URL stored in manifest.json").option("-C, --cwd <dir>","Project directory").option("--max-pages <n>","Maximum number of HTML pages to crawl (default uses previous manifest)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--json","Output the refreshed manifest as JSON").action(migratePullCommand);migrate.command("inspect").description("Print a summary of the current migration manifest").option("-C, --cwd <dir>","Project directory").option("--json","Output the manifest as JSON").action(migrateInspectCommand);migrate.command("inventory").description("Inspect source-backed migration evidence and write the deterministic inventory").argument("[project-root]","Source-backed project directory").option("-C, --cwd <dir>","Source-backed project directory").option("--json","Output the inventory as JSON").option("--prepare","Prepare the deterministic inventory plan").option("--area <area>","Run one planned inventory area").option("--reconcile","Reconcile existing inventory fragments").option("--sequential","Run planned areas sequentially").action(migrateInventoryCommand);migrate.command("apply").description("Generate an agent-ready Fimo scaffold from the current migration manifest").option("-C, --cwd <dir>","Project directory").option("--json","Output the apply result as JSON").action(migrateApplyCommand);migrate.command("refine").description("Prepare a high-context agent handoff to refine the generated migration toward the source site").option("-C, --cwd <dir>","Project directory").option("--route <path>",'Limit the refinement pack to one route (for example "/contact")').option("--json","Output the refine result as JSON").action(migrateRefineCommand);migrate.command("import").description("Print regular Fimo CLI commands for importing reviewed migration artifacts").option("-C, --cwd <dir>","Project directory").option("--json","Output suggested commands as JSON").action(migrateImportCommand);migrate.command("manifest").description("Build or refresh the canonical migration manifest at .fimo/migration/manifest.json").option("-C, --cwd <dir>","Project directory").option("--output <path>","Manifest output path relative to the project directory").option("--fresh","Discard previous canonical manifest progress while rebuilding").action(migrateManifestCommand);migrate.command("report").description("Write the migration QA report from the canonical manifest").option("-C, --cwd <dir>","Project directory").option("--manifest <path>","Canonical manifest path relative to the project directory").option("--output <path>","Report output path relative to the project directory").option("--no-update-manifest","Do not write qa.status and qa.checks back to the manifest").action(migrateReportCommand);program.command("deploy").description("Push main to Fimo and deploy to preview (use --publish to also go live)").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--publish","Also publish the new version after deploying to preview").option("-m, --message <msg>","Commit message for any uncommitted changes").option("--no-restart","Don't restart the sandbox dev server after pull \u2014 rely on Vite HMR. Use when only HMR-safe files changed (components/pages/styles/content). See the `fimo` skill for when to use this.").option("--force","Deploy even if validation fails (escape hatch; may still fail later in the sandbox)").action(deployCommand);program.command("validate").description("Run all checks and sync local state with the Fimo backend").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--json","Emit structured JSON output (for CI / agents)").action(validateCommand);program.command("describe [path]").description("Print a structured snapshot of the current Fimo project (read-only)").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--depth <n>","Tree depth (default 3). Ignored when --full is set.").option("--full","Disable depth and width truncation (still respects the 10k-entry cap)").option("--json","Emit structured JSON output (for CI / agents)").action(describeCommand);program.command("credits").description("Show the current project credit balance").option("-C, --cwd <dir>","Project directory").option("--project <projectId>","Project ID (defaults to the current project)").option("--json","Emit structured JSON output").action(creditsCommand);program.command("delete").description("Delete the current linked project").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Skip confirmation prompt").action(options=>projectsDeleteCommand(void 0,options));program.command("unpublish").description("Unpublish the current project").option("-C, --cwd <dir>","Project directory").action(options=>projectsUnpublishCommand(void 0,options));program.command("rename").description("Set the display name of the current project").argument("<name>",'New display name (e.g. "Acme Blog")').option("-C, --cwd <dir>","Project directory").action((name,options)=>projectsRenameCommand(name,void 0,options));var orgs=program.command("orgs").description("Manage organizations");orgs.command("list").description("List organizations you belong to").action(orgsListCommand);orgs.command("switch").description("Switch the active organization used by `fimo init`").option("--org <id-or-slug>","Switch to this organization without prompting").action(switchCommand);orgs.command("members").description("List members of an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(orgsMembersCommand);var referral=program.command("referral").description("Share and inspect your referral program tools");referral.command("link").description("Print your referral link").action(referralLinkCommand);referral.command("stats").description("Show your referral stats").action(referralStatsCommand);var projects=program.command("projects").description("Manage projects across an organization");projects.command("list").description("List projects in an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(projectsListCommand);projects.command("create").description("Scaffold a new project (alias of `fimo init`)").argument("[dir]","Target directory").option("--org <organizationId>","Target organization ID (auto if you belong to one)").option("--framework <framework>","Project scaffold: react-router | astro | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory").option("--starter <id>","Add an opt-in project starter (for example fimo-site@1)").option("--package-manager <pm>","Install dependencies with: npm | pnpm | yarn | bun").option("--install","Install dependencies after scaffolding").option("--no-install","Skip dependency installation after scaffolding").action(initCommand);projects.command("clone").description("Clone an existing Fimo project locally").argument("[projectId]","Project ID to clone").argument("[dir]","Target directory (defaults to the project name)").option("--env <name>","Env to clone (defaults to main)").action(cloneCommand);projects.command("delete").description("Delete a project (defaults to the current linked project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Skip confirmation prompt").action(projectsDeleteCommand);projects.command("publish").description("Publish a project (defaults to the current project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsPublishCommand);projects.command("unpublish").description("Unpublish a project (defaults to the current project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsUnpublishCommand);projects.command("rename").description("Set the display name of a project (defaults to the current project)").argument("<name>",'New display name (e.g. "Acme Blog")').argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsRenameCommand);var domains=program.command("domains").description("Manage your default URL and custom domains");domains.command("list").alias("ls").description("Show the default URL and any custom domains").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON").action(domainsListCommand);domains.command("rename-default").description("Rename your default URL (the <slug>.fimo.site subdomain Fimo provides)").argument("<slug>",'New slug (e.g. "acme-coffee")').option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON").action(domainsRenameDefaultCommand);domains.command("suggest-default").description("Suggest available default URLs; pick one to claim (or list with --json)").option("--base <text>","Override the base text used to generate suggestions (defaults to your project display name)").option("--max <n>","Number of suggestions to fetch (1\u201310, default 5)").option("--pick <slug-or-index>","Non-interactive: claim this suggestion by slug or numeric index").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON (no prompt, no claim)").action(domainsSuggestDefaultCommand);domains.command("add").description("Attach a custom domain to your project (Premium plan required)").argument("<hostname>",'The hostname to attach (e.g. "blog.example.com")').option("--redirect-www","Also configure an apex \u2192 www redirect").option("--wait [duration]","Poll until DNS is verified (e.g. --wait, --wait 10m)").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output the resulting domain record as JSON after instructions").action(domainsAddCommand);domains.command("remove").alias("rm").description("Detach a custom domain by hostname or ID").argument("<hostname-or-id>","Hostname or domain ID").option("-y, --yes","Skip the confirmation prompt").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").action(domainsRemoveCommand);domains.command("refresh").description("Re-check DNS and SSL status for a custom domain").argument("<hostname-or-id>","Hostname or domain ID").option("--wait [duration]","Poll until SSL is active (default; pass --no-wait to print one snapshot)").option("--no-wait","Print the refreshed status once and exit").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output the resulting domain record as JSON").action(domainsRefreshCommand);domains.command("search").description("Search for available domain names to buy through Fimo").argument("<keyword>",'Search keyword (e.g. "acme coffee")').option("--tld <list>",'Restrict TLDs (comma-separated, e.g. "com,io,dev")').option("--max-price <amount>","Filter results to this purchase price ceiling (in dollars)").option("--limit <n>","Truncate to the first N results (default 20)").option("--json","Output as JSON").action(domainsSearchCommand);domains.command("pricing").description("Show the price for a specific domain (purchase + renewal)").argument("<domain>",'Domain name (e.g. "example.com")').option("--years <n>","Multiply purchase price by this many years (default 1)").option("--json","Output as JSON").action(domainsPricingCommand);domains.command("buy").description("Buy a domain through Fimo. Creates a checkout invoice; no charge until you pay it in the browser.").argument("<domain>",'Domain name to register (e.g. "example.com")').option("--years <n>","Years to register for (default uses the TLD minimum)").option("--auto-renew","Enable auto-renewal (default)").option("--no-auto-renew","Disable auto-renewal \u2014 domain will not renew automatically").option("-y, --yes","Skip the interactive confirmation prompt").option("--open","Open the checkout URL in your browser after creating the invoice").option("--wait [duration]","Poll until payment completes and registration succeeds").option("--org <organizationId>","Organization ID (defaults to the current project's org)").option("-C, --cwd <dir>","Project directory used to resolve the org").option("--json","Output the resulting invoice record as JSON").action(domainsBuyCommand);domains.command("owned").description("List domains your organization has registered through Fimo").option("--org <organizationId>","Organization ID (defaults to the current project's org)").option("--status <list>",'Filter by status (comma-separated, e.g. "owned,pending_payment")').option("--limit <n>","Truncate to the first N results").option("-C, --cwd <dir>","Project directory used to resolve the org").option("--json","Output as JSON").action(domainsOwnedCommand);var scripts=program.command("scripts",{hidden:!0}).description("Internal/advanced primitives. Most users want `fimo validate`.");scripts.command("sync-schemas").description("Regenerate TypeScript clients for src/schemas/*.json").option("-C, --cwd <dir>","Project directory").action(syncSchemasCommand);scripts.command("sync-forms").description("Regenerate TypeScript clients for src/forms/*.json").option("-C, --cwd <dir>","Project directory").action(syncFormsCommand);scripts.command("validate-route-metadata").description("Cross-validate src/routes.ts against .fimo/config.json#routes (v4)").option("-C, --cwd <dir>","Project directory").action(validateRouteMetadataCommand);scripts.command("extract-translations").description("Legacy local helper: scan src/ for literal t() label keys").option("-C, --cwd <dir>","Project directory").action(extractTranslationsCommand);scripts.command("lint").description("Lint project files (translation keys + oxlint)").argument("[path]","Single file to lint (omit for whole project)").option("-C, --cwd <dir>","Project directory").action(lintCommand);program.command("export-static",{hidden:!0}).description("Post-build: clean dist/server and *.data files (after react-router build)").option("-C, --cwd <dir>","Project directory").action(exportStaticCommand);program.command("resolve-routes",{hidden:!0}).description("Map changed files back to affected preview routes").argument("[files...]","Changed files to resolve").option("-C, --cwd <dir>","Project directory").action(resolveRoutesCommand);var branchCmd=program.command("branch").description("List, create, or delete envs (multi-surface env = git branch + per-env Neon DB + sandbox)").argument("[name]","Env name (omit to list)").option("-v, --verbose","Show preview URLs + deleted envs").option("--all","Also list Fimo's own agent envs (task/*), normally hidden").option("-d, --delete","Delete the named env (drops sandbox + Neon branch + R2 prefix)").option("--from <env>","Parent env to fork from when creating (defaults to current)").action(async(name,_options,command)=>{if(!name){await branchListCommand(command);return}if(command.opts().delete){await branchDeleteCommand(name,command);return}await branchCreateCommand(name,command)});program.command("checkout").description("Switch to an env (or create + switch with -b)").argument("<name>","Env name").option("-b, --create","Create the env if it does not exist").option("--from <env>","Parent env (only with -b)").action(checkoutCommand);program.command("switch").description("Alias for `fimo checkout` (switch envs)").argument("<name>","Env name").action(checkoutCommand);program.command("pull").description("Sync the current env's data plane from its parent").option("--from <env>","Sync from an explicit ancestor (defaults to declared parent)").action(pullCommand);program.command("diff").description("Two-env diff across all surfaces").argument("[from]","From env (defaults to current env)").argument("[to]","To env (defaults to main)").option("-C, --cwd <dir>","Project directory").option("--surface <name>","Limit to a single surface (code | schemas | content | ...)").option("--key <key>","Drill into one item within --surface (W2 \u2014 per-item before/after)").option("--all","Render the full item list, bypassing the per-surface cap").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(diffCommand);program.command("merge").description("Merge another env into the current one (multi-surface, atomic, with conflict resolver)").argument("<from>","Source env").option("-C, --cwd <dir>","Project directory").option("--allow-direct-merge","Override the main-branch protected-flow gate").option("-y, --yes","Accept parent-wins for every conflict (non-interactive)").option("--resume","Resume an in-flight merge from its persisted draft (W3.6)").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(mergeCommand);program.command("publish").description("Tag main@HEAD as release/<version> + trigger prod swap").option("-C, --cwd <dir>","Project directory").option("--version <ver>","Semver version for the release (e.g. 1.4.2)").option("--notes <text>","Optional release notes (markdown)").option("--skip-validate","Skip the lint + codegen + smoke pre-checks (operator override)").action(publishCommand);program.command("status").description("Multi-surface env status \u2014 the showcase command").option("-C, --cwd <dir>","Project directory").option("--short","One-line summary per surface (no bodies)").option("--json","Emit raw JSON instead of the rendered report").option("--vs <env>","Comparison target (defaults to the parent env or main)").option("--no-color","Disable ANSI colour output").option("--code","Limit to the code surface").option("--content","Limit to the content surface").option("--i18n","Limit to the translations surface").option("--assets","Limit to the assets surface").option("--forms","Limit to the forms surface").option("--all","Render the full item list, bypassing the per-surface cap").action(statusCommand2);registerAgentsCommands(program);registerPreviewCommands(program);program.addCommand(new Command("git-credential").argument("<operation>","get | store | erase (git credential protocol)").description("Internal git credential helper (invoked by git)").action(gitCredentialCommand),{hidden:!0});registerGenerate(program);registerMediaTaskCommands(program);var schemas2=program.command("schemas").description("Manage content-type schemas");schemas2.command("list").description("List all registered schemas").option("-C, --cwd <dir>","Project directory").action(schemaListCommand);schemas2.command("get").description("Get a schema by type name").argument("<typeName>","Content type name (e.g. BlogPost)").option("-C, --cwd <dir>","Project directory").action(schemaGetCommand);schemas2.command("push").description("Push schema JSON files to the API (create or update)").argument("[typeName]","Schema name to push (omit to push all)").option("-C, --cwd <dir>","Project directory").option("--rename <from=to>","Preserve a renamed field (repeatable, supports nested paths)",(value,previous)=>[...previous,value],[]).action(schemaPushCommand);schemas2.command("delete").description("Delete a schema by type name").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").action(schemaDeleteCommand);var entries=program.command("entries").description("Manage content entries");entries.command("list").description("List entries of a content type").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--limit <n>","Max entries to return").option("--offset <n>","Offset for pagination").option("--search <query>","Search query").option("--where <json>",`JSON filter object, e.g. '{"featured":true}'`).option("--sort <field>","Sort field, prefix with - for descending").option("--fields <fields>","Comma-separated fields to return, e.g. slug,title,excerpt").option("--populate <fields>","Comma-separated reference fields to populate, e.g. author,contributors").option("--locale <locale>","Locale to list (default en)").option("--sort-by <field>","Sort field").option("--sort-direction <dir>","Sort direction (asc|desc)").action(entriesListCommand);entries.command("get").description("Get a single entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesGetCommand);entries.command("create").description("Create a new entry").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").requiredOption("--body <json>","Entry JSON body (slug + data)").option("--locale <locale>","Entry locale (default en)").option("--document-id <id>","Document ID shared by localized variants").action(entriesCreateCommand);entries.command("update").description("Update an existing entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").requiredOption("--body <json>","Updated entry JSON body").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesUpdateCommand);entries.command("delete").description("Delete an entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesDeleteCommand);entries.command("query").description("Run a read-only SQL query over the entries table").option("-C, --cwd <dir>","Project directory").option("--sql <query>","SQL SELECT query").option("--file <path>","Read the SQL query from a file").option("--stdin","Read the SQL query from stdin").action(entriesQueryCommand);entries.command("bulk-create").description("Create multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--body <json>","JSON array of entry bodies").option("--file <path>","Read entry bodies from a JSON file").option("--stdin","Read entry bodies from stdin").action(entriesBulkCreateCommand);entries.command("bulk-update").description("Update multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"status":"draft"}'`).option("--body <json>","Updated entry JSON body").option("--file <path>","Read per-entry updates from a JSON file").option("--stdin","Read per-entry updates from stdin").action(entriesBulkUpdateCommand);entries.command("bulk-delete").description("Delete multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"archived":true}'`).option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesBulkDeleteCommand);var singles=program.command("singles").description("Manage single content types");singles.command("get").description("Get a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Single locale (defaults to the project locale)").option("--populate <fields>","Comma-separated reference fields to populate").action(singlesGetCommand);singles.command("update").description("Update a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Project directory").option("--body <json>","Updated Single JSON body").option("--file <path>","Read the updated Single JSON body from a file").option("--stdin","Read the updated Single JSON body from stdin").option("--locale <locale>","Single locale (defaults to the project locale)").action(singlesUpdateCommand);var assets2=program.command("assets").description("Manage media assets");assets2.command("list").description("List assets").option("-C, --cwd <dir>","Project directory").option("--parent-id <id>","Filter by parent folder").option("--search <query>","Search across name, alt text, caption, and AI-generated alt / caption (case-insensitive)").option("--type <type>","Filter by entry type (file|folder)").option("--image","Filter to image MIME types (shortcut for --mime-prefix image/)").option("--video","Filter to video MIME types (shortcut for --mime-prefix video/)").option("--audio","Filter to audio MIME types (shortcut for --mime-prefix audio/)").option("--mime-prefix <prefix>",'Filter by MIME type prefix (e.g. "image/png")').option("--sort-by <field>","Sort field").option("--limit <n>","Max results").option("--offset <n>","Offset").action(assetsListCommand);assets2.command("upload").description("Upload a file to the media library").argument("<file>","Path to the file to upload").option("-C, --cwd <dir>","Project directory").option("--name <name>","Asset display name").option("--parent-id <id>","Target folder ID").option("--folder-path <path>","Target folder path, creating missing folders").action(assetsUploadCommand);var modelsCmd=new Command("models").description("Browse available media generation models");program.addCommand(modelsCmd,{hidden:!0});modelsCmd.command("list").description("List Fal models enabled for this project").option("-C, --cwd <dir>","Project directory").option("--modality <m>","Filter by modality (image | video | audio)").option("--search <query>","Search names and descriptions").option("--category <category>","Filter by Fal media category").option("--tag <t>","Filter by tag (repeatable; AND semantics \u2014 model must have every tag)",(value,previous)=>[...previous,value],[]).option("--extended","Per-model card: alias, provider, tags, price, best-for, flags").option("--json","Machine-readable JSON output").action(modelsListCommand);modelsCmd.command("show").description("Show a Fal model and its available flags").argument("<key>","Namespaced model id from `fimo models list`").option("-C, --cwd <dir>","Project directory").option("--json","Machine-readable JSON output (includes the per-model flag list)").action(modelsShowCommand);assets2.command("create-folder").description("Create a folder in the media library").argument("<name>","Folder name").option("-C, --cwd <dir>","Project directory").option("--parent-id <id>","Parent folder ID").action(assetsCreateFolderCommand);assets2.command("move").description("Move an asset to a different folder").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").requiredOption("--parent-id <id>",'Target folder ID (use "null" for root)').action(assetsMoveCommand);assets2.command("delete").description("Delete an asset").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").action(assetsDeleteCommand);assets2.command("open").description("Fetch asset metadata; optionally download locally or open in default viewer").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").option("--download","Download the asset bytes to a local file and print the path").option("--browser","Open the asset URL in the OS default viewer (open / xdg-open / start)").option("--path <path>","Override download destination (default: <tmpdir>/fimo-assets/<id>.<ext>). Implies --download.").action((id,options,cmd)=>(options.path&&!options.download&&(options.download=!0),assetsOpenCommand(id,options,cmd)));var forms2=program.command("forms").description("Manage forms");forms2.command("list").description("List all forms").option("-C, --cwd <dir>","Project directory").action(formsListCommand);forms2.command("get").description("Get a form by ID").argument("<id>","Form ID").option("-C, --cwd <dir>","Project directory").action(formsGetCommand);forms2.command("push").description("Push form JSON files to the API (create or update, patches id back)").argument("[formName]","Form name to push (omit to push all)").option("-C, --cwd <dir>","Project directory").action(formsPushCommand);forms2.command("delete").description("Delete a form").argument("<id>","Form ID").option("-C, --cwd <dir>","Project directory").action(formsDeleteCommand);var supportedAgentsHelp=`
|
|
1438
|
+
`)}__name(indentBlock,"indentBlock");init_agents();init_auth_errors();init_project_context();function computeVersionString(){let pkgVersion="0.0.0";try{let pkg=JSON.parse(fs46.readFileSync(path48.join(CLI_ROOT,"package.json"),"utf8"));typeof pkg.version=="string"&&pkg.version.length>0&&(pkgVersion=pkg.version)}catch{}let releaseId;try{let release=JSON.parse(fs46.readFileSync(path48.join(CLI_ROOT,"release.json"),"utf8"));typeof release.id=="string"&&release.id.length>0&&(releaseId=release.id)}catch{}let{apiUrl}=loadConfig(),detailParts=[];return releaseId&&detailParts.push(`release ${releaseId}`),detailParts.push(apiUrl),`fimo ${pkgVersion} (${detailParts.join(", ")})`}__name(computeVersionString,"computeVersionString");program.name("fimo").description("Fimo CLI").version(computeVersionString()).option("--env <name>","Override the env this command targets (defaults to the current git branch, falling back to `main`)").option("--branch <name>","Override the Fimo Branch this command targets (legacy alias: `--env`)").option("--json","Emit one structured JSON envelope per command (for tools / agents). FIMO_OUTPUT=json env also enables this.").option("--no-color","Disable colour in pretty mode (NO_COLOR env var also honoured)").option("--ascii","Use ASCII fallbacks for unicode glyphs (\u2713 \u2192 [ok], etc.) - for legacy terminals").hook("preAction",thisCommand=>{let opts=thisCommand.optsWithGlobals();initUi({json:opts.json===!0,noColor:opts.color===!1,ascii:opts.ascii===!0,jsonEnvVar:"FIMO_OUTPUT",asciiEnvVar:"FIMO_ASCII"})});program.command("login").description("Sign in through your browser").action(loginCommand);program.command("logout").description("Revoke the current session and clear local credentials").action(logoutCommand);program.command("whoami").description("Show the current signed-in user").action(whoamiCommand);registerProjectSecretsCommands(program);registerIntegrationsCommands(program);registerChannelsCommands(program);registerSchedulesCommands(program);registerHistoryCommands(program);registerSupportCommands(program);registerWebhooksCommands(program);registerLocalesCommands(program);registerEnvironmentsCommands(program);program.command("invite").description("Invite a user to an organization or project").option("--target <target>","Invite target: organization or project").option("--org <organizationId>","Organization ID (defaults to active when needed)").option("--project <projectId>","Project ID (defaults to the current project when available)").option("--email <email>","Email address of the user to invite").option("--role <role>","Role or access level to grant").option("-C, --cwd <dir>","Project directory used to resolve the current project").option("-y, --yes","Skip the confirmation prompt").option("--resend","Resend an existing pending organization invite").action(inviteCommand);program.command("mcp").description("Serve the Fimo MCP server over stdio (for MCP clients such as Claude Code or Cursor)").action(mcpCommand);program.command("clone").description("Clone an existing Fimo project locally").argument("[projectId]","Project ID to clone").argument("[dir]","Target directory (defaults to the project name)").option("--env <name>","Env to clone (defaults to main)").action(cloneCommand);program.command("link").description("Link the current application to a Fimo project, in place (repairs an existing link)").argument("[projectId]","Project ID to link (defaults to the linked project, else prompts)").option("--env <name>","Env to link (defaults to the current git branch, else main)").option("-C, --cwd <dir>","Application directory").action(linkCommand);program.command("init").description("Set up a Fimo project locally: sign in, create or link a project, install deps and skills").argument("[dir]","Target directory").option("--project-id <id>","Link an existing project instead of creating a new one").option("--org <organizationId>","Target organization ID when creating (recommended for agents and CI)").option("--env <name>","Env to check out when linking an existing project (defaults to main)").option("--framework <framework>","Project scaffold: react-router | astro | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory when creating").option("--starter <id>","Add an opt-in project starter (for example fimo-site@1)").option("--package-manager <pm>","Install dependencies with: npm | pnpm | yarn | bun").option("--install","Install dependencies after checkout").option("--no-install","Skip dependency installation after checkout").option("--skills","Install the global Fimo skill for your AI coding agents").option("--no-skills","Skip installing the global Fimo skill").option("--agents <list>",'Comma-separated list of AI agents to install the global Fimo skill for (e.g. claude-code,cursor). Pass "none" to skip.').option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("-y, --yes","Run non-interactively using defaults (no prompts)").action(initCommand);var migrate=program.command("migrate").description("Prepare agent-ready migrations from existing websites into Fimo").argument("[url]","Published source site URL for the agent-ready migration draft").argument("[dir]","Target Fimo project directory (creates one if empty/missing)").option("-C, --cwd <dir>","Existing project directory when omitting [dir]").option("--org <organizationId>","Target organization ID when creating a new project").option("--template-root <path>","Override template directory when creating a new project").option("--install","Install dependencies after scaffolding a new project").option("--no-install","Skip dependency installation after scaffolding a new project").option("--agents <list>","Comma-separated list of AI agents to set up when creating a new project (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("--mode <mode>","Project skill install method for newly created projects: symlink | copy").option("--max-pages <n>","Maximum number of HTML pages to crawl (default 12)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--route <path>",'Limit the refinement pack to one route (for example "/contact")').action((url,dir,options)=>{if(!url){migrate.help();return}return migrateRunCommand(url,dir,options)});migrate.command("init").description("Create or reuse a Fimo project, crawl a live site, and write migration artifacts").argument("<url>","Published source site URL").argument("[dir]","Target Fimo project directory (creates one if empty/missing)").option("-C, --cwd <dir>","Existing project directory when omitting [dir]").option("--org <organizationId>","Target organization ID when creating a new project").option("--template-root <path>","Override template directory when creating a new project").option("--install","Install dependencies after scaffolding a new project").option("--no-install","Skip dependency installation after scaffolding a new project").option("--agents <list>","Comma-separated list of AI agents to set up when creating a new project (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev2=[])=>[...prev2,value]).option("--mode <mode>","Project skill install method for newly created projects: symlink | copy").option("--max-pages <n>","Maximum number of HTML pages to crawl (default 12)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--json","Output the resulting manifest as JSON").action(migrateInitCommand);migrate.command("pull").description("Refresh the current migration artifacts from the source URL stored in manifest.json").option("-C, --cwd <dir>","Project directory").option("--max-pages <n>","Maximum number of HTML pages to crawl (default uses previous manifest)").option("--max-assets <n>","Maximum media assets to download into the migration pack (default 40)").option("--download-media","Download detected media assets into the migration pack").option("--no-download-media","Skip downloading detected media assets").option("--json","Output the refreshed manifest as JSON").action(migratePullCommand);migrate.command("inspect").description("Print a summary of the current migration manifest").option("-C, --cwd <dir>","Project directory").option("--json","Output the manifest as JSON").action(migrateInspectCommand);migrate.command("inventory").description("Inspect source-backed migration evidence and write the deterministic inventory").argument("[project-root]","Source-backed project directory").option("-C, --cwd <dir>","Source-backed project directory").option("--json","Output the inventory as JSON").option("--prepare","Prepare the deterministic inventory plan").option("--area <area>","Run one planned inventory area").option("--reconcile","Reconcile existing inventory fragments").option("--sequential","Run planned areas sequentially").action(migrateInventoryCommand);migrate.command("apply").description("Generate an agent-ready Fimo scaffold from the current migration manifest").option("-C, --cwd <dir>","Project directory").option("--json","Output the apply result as JSON").action(migrateApplyCommand);migrate.command("refine").description("Prepare a high-context agent handoff to refine the generated migration toward the source site").option("-C, --cwd <dir>","Project directory").option("--route <path>",'Limit the refinement pack to one route (for example "/contact")').option("--json","Output the refine result as JSON").action(migrateRefineCommand);migrate.command("import").description("Print regular Fimo CLI commands for importing reviewed migration artifacts").option("-C, --cwd <dir>","Project directory").option("--json","Output suggested commands as JSON").action(migrateImportCommand);migrate.command("manifest").description("Build or refresh the canonical migration manifest at .fimo/migration/manifest.json").option("-C, --cwd <dir>","Project directory").option("--output <path>","Manifest output path relative to the project directory").option("--fresh","Discard previous canonical manifest progress while rebuilding").action(migrateManifestCommand);migrate.command("report").description("Write the migration QA report from the canonical manifest").option("-C, --cwd <dir>","Project directory").option("--manifest <path>","Canonical manifest path relative to the project directory").option("--output <path>","Report output path relative to the project directory").option("--no-update-manifest","Do not write qa.status and qa.checks back to the manifest").action(migrateReportCommand);program.command("deploy").description("Push main to Fimo and deploy to preview (use --publish to also go live)").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--publish","Also publish the new version after deploying to preview").option("-m, --message <msg>","Commit message for any uncommitted changes").option("--no-restart","Don't restart the sandbox dev server after pull \u2014 rely on Vite HMR. Use when only HMR-safe files changed (components/pages/styles/content). See the `fimo` skill for when to use this.").option("--force","Deploy even if validation fails (escape hatch; may still fail later in the sandbox)").action(deployCommand);program.command("validate").description("Run all checks and sync local state with the Fimo backend").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--json","Emit structured JSON output (for CI / agents)").action(validateCommand);program.command("describe [path]").description("Print a structured snapshot of the current Fimo project (read-only)").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--depth <n>","Tree depth (default 3). Ignored when --full is set.").option("--full","Disable depth and width truncation (still respects the 10k-entry cap)").option("--json","Emit structured JSON output (for CI / agents)").action(describeCommand);program.command("credits").description("Show the current project credit balance").option("-C, --cwd <dir>","Project directory").option("--project <projectId>","Project ID (defaults to the current project)").option("--json","Emit structured JSON output").action(creditsCommand);program.command("delete").description("Delete the current linked project").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Skip confirmation prompt").action(options=>projectsDeleteCommand(void 0,options));program.command("unpublish").description("Unpublish the current project").option("-C, --cwd <dir>","Project directory").action(options=>projectsUnpublishCommand(void 0,options));program.command("rename").description("Set the display name of the current project").argument("<name>",'New display name (e.g. "Acme Blog")').option("-C, --cwd <dir>","Project directory").action((name,options)=>projectsRenameCommand(name,void 0,options));var orgs=program.command("orgs").description("Manage organizations");orgs.command("list").description("List organizations you belong to").action(orgsListCommand);orgs.command("switch").description("Switch the active organization used by `fimo init`").option("--org <id-or-slug>","Switch to this organization without prompting").action(switchCommand);orgs.command("members").description("List members of an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(orgsMembersCommand);var referral=program.command("referral").description("Share and inspect your referral program tools");referral.command("link").description("Print your referral link").action(referralLinkCommand);referral.command("stats").description("Show your referral stats").action(referralStatsCommand);var projects=program.command("projects").description("Manage projects across an organization");projects.command("list").description("List projects in an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(projectsListCommand);projects.command("create").description("Scaffold a new project (alias of `fimo init`)").argument("[dir]","Target directory").option("--org <organizationId>","Target organization ID (auto if you belong to one)").option("--framework <framework>","Project scaffold: react-router | astro | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory").option("--starter <id>","Add an opt-in project starter (for example fimo-site@1)").option("--package-manager <pm>","Install dependencies with: npm | pnpm | yarn | bun").option("--install","Install dependencies after scaffolding").option("--no-install","Skip dependency installation after scaffolding").action(initCommand);projects.command("clone").description("Clone an existing Fimo project locally").argument("[projectId]","Project ID to clone").argument("[dir]","Target directory (defaults to the project name)").option("--env <name>","Env to clone (defaults to main)").action(cloneCommand);projects.command("delete").description("Delete a project (defaults to the current linked project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").option("-y, --yes","Skip confirmation prompt").action(projectsDeleteCommand);projects.command("publish").description("Publish a project (defaults to the current project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsPublishCommand);projects.command("unpublish").description("Unpublish a project (defaults to the current project)").argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsUnpublishCommand);projects.command("rename").description("Set the display name of a project (defaults to the current project)").argument("<name>",'New display name (e.g. "Acme Blog")').argument("[projectId]","Explicit project ID").option("-C, --cwd <dir>","Project directory").action(projectsRenameCommand);var domains=program.command("domains").description("Manage your default URL and custom domains");domains.command("list").alias("ls").description("Show the default URL and any custom domains").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON").action(domainsListCommand);domains.command("rename-default").description("Rename your default URL (the <slug>.fimo.site subdomain Fimo provides)").argument("<slug>",'New slug (e.g. "acme-coffee")').option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON").action(domainsRenameDefaultCommand);domains.command("suggest-default").description("Suggest available default URLs; pick one to claim (or list with --json)").option("--base <text>","Override the base text used to generate suggestions (defaults to your project display name)").option("--max <n>","Number of suggestions to fetch (1\u201310, default 5)").option("--pick <slug-or-index>","Non-interactive: claim this suggestion by slug or numeric index").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output as JSON (no prompt, no claim)").action(domainsSuggestDefaultCommand);domains.command("add").description("Attach a custom domain to your project (Premium plan required)").argument("<hostname>",'The hostname to attach (e.g. "blog.example.com")').option("--redirect-www","Also configure an apex \u2192 www redirect").option("--wait [duration]","Poll until DNS is verified (e.g. --wait, --wait 10m)").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output the resulting domain record as JSON after instructions").action(domainsAddCommand);domains.command("remove").alias("rm").description("Detach a custom domain by hostname or ID").argument("<hostname-or-id>","Hostname or domain ID").option("-y, --yes","Skip the confirmation prompt").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").action(domainsRemoveCommand);domains.command("refresh").description("Re-check DNS and SSL status for a custom domain").argument("<hostname-or-id>","Hostname or domain ID").option("--wait [duration]","Poll until SSL is active (default; pass --no-wait to print one snapshot)").option("--no-wait","Print the refreshed status once and exit").option("--project <projectId>","Project ID (defaults to the current project)").option("-C, --cwd <dir>","Project directory").option("--json","Output the resulting domain record as JSON").action(domainsRefreshCommand);domains.command("search").description("Search for available domain names to buy through Fimo").argument("<keyword>",'Search keyword (e.g. "acme coffee")').option("--tld <list>",'Restrict TLDs (comma-separated, e.g. "com,io,dev")').option("--max-price <amount>","Filter results to this purchase price ceiling (in dollars)").option("--limit <n>","Truncate to the first N results (default 20)").option("--json","Output as JSON").action(domainsSearchCommand);domains.command("pricing").description("Show the price for a specific domain (purchase + renewal)").argument("<domain>",'Domain name (e.g. "example.com")').option("--years <n>","Multiply purchase price by this many years (default 1)").option("--json","Output as JSON").action(domainsPricingCommand);domains.command("buy").description("Buy a domain through Fimo. Creates a checkout invoice; no charge until you pay it in the browser.").argument("<domain>",'Domain name to register (e.g. "example.com")').option("--years <n>","Years to register for (default uses the TLD minimum)").option("--auto-renew","Enable auto-renewal (default)").option("--no-auto-renew","Disable auto-renewal \u2014 domain will not renew automatically").option("-y, --yes","Skip the interactive confirmation prompt").option("--open","Open the checkout URL in your browser after creating the invoice").option("--wait [duration]","Poll until payment completes and registration succeeds").option("--org <organizationId>","Organization ID (defaults to the current project's org)").option("-C, --cwd <dir>","Project directory used to resolve the org").option("--json","Output the resulting invoice record as JSON").action(domainsBuyCommand);domains.command("owned").description("List domains your organization has registered through Fimo").option("--org <organizationId>","Organization ID (defaults to the current project's org)").option("--status <list>",'Filter by status (comma-separated, e.g. "owned,pending_payment")').option("--limit <n>","Truncate to the first N results").option("-C, --cwd <dir>","Project directory used to resolve the org").option("--json","Output as JSON").action(domainsOwnedCommand);var scripts=program.command("scripts",{hidden:!0}).description("Internal/advanced primitives. Most users want `fimo validate`.");scripts.command("sync-schemas").description("Regenerate TypeScript clients for src/schemas/*.json").option("-C, --cwd <dir>","Project directory").action(syncSchemasCommand);scripts.command("sync-forms").description("Regenerate TypeScript clients for src/forms/*.json").option("-C, --cwd <dir>","Project directory").action(syncFormsCommand);scripts.command("validate-route-metadata").description("Cross-validate src/routes.ts against .fimo/config.json#routes (v4)").option("-C, --cwd <dir>","Project directory").action(validateRouteMetadataCommand);scripts.command("extract-translations").description("Legacy local helper: scan src/ for literal t() label keys").option("-C, --cwd <dir>","Project directory").action(extractTranslationsCommand);scripts.command("lint").description("Lint project files (translation keys + oxlint)").argument("[path]","Single file to lint (omit for whole project)").option("-C, --cwd <dir>","Project directory").action(lintCommand);program.command("export-static",{hidden:!0}).description("Post-build: clean dist/server and *.data files (after react-router build)").option("-C, --cwd <dir>","Project directory").action(exportStaticCommand);program.command("resolve-routes",{hidden:!0}).description("Map changed files back to affected preview routes").argument("[files...]","Changed files to resolve").option("-C, --cwd <dir>","Project directory").action(resolveRoutesCommand);var branchCmd=program.command("branch").description("List, create, or delete envs (multi-surface env = git branch + per-env Neon DB + sandbox)").argument("[name]","Env name (omit to list)").option("-v, --verbose","Show preview URLs + deleted envs").option("--all","Also list Fimo's own agent envs (task/*), normally hidden").option("-d, --delete","Delete the named env (drops sandbox + Neon branch + R2 prefix)").option("--from <env>","Parent env to fork from when creating (defaults to current)").action(async(name,_options,command)=>{if(!name){await branchListCommand(command);return}if(command.opts().delete){await branchDeleteCommand(name,command);return}await branchCreateCommand(name,command)});program.command("checkout").description("Switch to an env (or create + switch with -b)").argument("<name>","Env name").option("-b, --create","Create the env if it does not exist").option("--from <env>","Parent env (only with -b)").action(checkoutCommand);program.command("switch").description("Alias for `fimo checkout` (switch envs)").argument("<name>","Env name").action(checkoutCommand);program.command("pull").description("Sync the current env's data plane from its parent").option("--from <env>","Sync from an explicit ancestor (defaults to declared parent)").action(pullCommand);program.command("diff").description("Two-env diff across all surfaces").argument("[from]","From env (defaults to current env)").argument("[to]","To env (defaults to main)").option("-C, --cwd <dir>","Project directory").option("--surface <name>","Limit to a single surface (code | schemas | content | ...)").option("--key <key>","Drill into one item within --surface (W2 \u2014 per-item before/after)").option("--all","Render the full item list, bypassing the per-surface cap").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(diffCommand);program.command("merge").description("Merge another env into the current one (multi-surface, atomic, with conflict resolver)").argument("<from>","Source env").option("-C, --cwd <dir>","Project directory").option("--allow-direct-merge","Override the main-branch protected-flow gate").option("-y, --yes","Accept parent-wins for every conflict (non-interactive)").option("--resume","Resume an in-flight merge from its persisted draft (W3.6)").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(mergeCommand);program.command("publish").description("Tag main@HEAD as release/<version> + trigger prod swap").option("-C, --cwd <dir>","Project directory").option("--version <ver>","Semver version for the release (e.g. 1.4.2)").option("--notes <text>","Optional release notes (markdown)").option("--skip-validate","Skip the lint + codegen + smoke pre-checks (operator override)").action(publishCommand);program.command("status").description("Multi-surface env status \u2014 the showcase command").option("-C, --cwd <dir>","Project directory").option("--short","One-line summary per surface (no bodies)").option("--json","Emit raw JSON instead of the rendered report").option("--vs <env>","Comparison target (defaults to the parent env or main)").option("--no-color","Disable ANSI colour output").option("--code","Limit to the code surface").option("--content","Limit to the content surface").option("--i18n","Limit to the translations surface").option("--assets","Limit to the assets surface").option("--forms","Limit to the forms surface").option("--all","Render the full item list, bypassing the per-surface cap").action(statusCommand2);registerAgentsCommands(program);registerPreviewCommands(program);program.addCommand(new Command("git-credential").argument("<operation>","get | store | erase (git credential protocol)").description("Internal git credential helper (invoked by git)").action(gitCredentialCommand),{hidden:!0});registerGenerate(program);registerMediaTaskCommands(program);var schemas2=program.command("schemas").description("Manage content-type schemas");schemas2.command("list").description("List all registered schemas").option("-C, --cwd <dir>","Project directory").action(schemaListCommand);schemas2.command("get").description("Get a schema by type name").argument("<typeName>","Content type name (e.g. BlogPost)").option("-C, --cwd <dir>","Project directory").action(schemaGetCommand);schemas2.command("push").description("Push schema JSON files to the API (create or update)").argument("[typeName]","Schema name to push (omit to push all)").option("-C, --cwd <dir>","Project directory").option("--rename <from=to>","Preserve a renamed field (repeatable, supports nested paths)",(value,previous)=>[...previous,value],[]).action(schemaPushCommand);schemas2.command("delete").description("Delete a schema by type name").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").action(schemaDeleteCommand);var entries=program.command("entries").description("Manage content entries");entries.command("list").description("List entries of a content type").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--limit <n>","Max entries to return").option("--offset <n>","Offset for pagination").option("--search <query>","Search query").option("--where <json>",`JSON filter object, e.g. '{"featured":true}'`).option("--sort <field>","Sort field, prefix with - for descending").option("--fields <fields>","Comma-separated fields to return, e.g. slug,title,excerpt").option("--populate <fields>","Comma-separated reference fields to populate, e.g. author,contributors").option("--locale <locale>","Locale to list (default en)").option("--sort-by <field>","Sort field").option("--sort-direction <dir>","Sort direction (asc|desc)").action(entriesListCommand);entries.command("get").description("Get a single entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesGetCommand);entries.command("create").description("Create a new entry").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").requiredOption("--body <json>","Entry JSON body (slug + data)").option("--locale <locale>","Entry locale (default en)").option("--document-id <id>","Document ID shared by localized variants").action(entriesCreateCommand);entries.command("update").description("Update an existing entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").requiredOption("--body <json>","Updated entry JSON body").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesUpdateCommand);entries.command("delete").description("Delete an entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesDeleteCommand);entries.command("query").description("Run a read-only SQL query over the entries table").option("-C, --cwd <dir>","Project directory").option("--sql <query>","SQL SELECT query").option("--file <path>","Read the SQL query from a file").option("--stdin","Read the SQL query from stdin").action(entriesQueryCommand);entries.command("bulk-create").description("Create multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--body <json>","JSON array of entry bodies").option("--file <path>","Read entry bodies from a JSON file").option("--stdin","Read entry bodies from stdin").action(entriesBulkCreateCommand);entries.command("bulk-update").description("Update multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"status":"draft"}'`).option("--body <json>","Updated entry JSON body").option("--file <path>","Read per-entry updates from a JSON file").option("--stdin","Read per-entry updates from stdin").action(entriesBulkUpdateCommand);entries.command("bulk-delete").description("Delete multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Project directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"archived":true}'`).option("--locale <locale>","Entry locale (defaults to the project locale)").action(entriesBulkDeleteCommand);var singles=program.command("singles").description("Manage single content types");singles.command("get").description("Get a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Project directory").option("--locale <locale>","Single locale (defaults to the project locale)").option("--populate <fields>","Comma-separated reference fields to populate").action(singlesGetCommand);singles.command("update").description("Update a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Project directory").option("--body <json>","Updated Single JSON body").option("--file <path>","Read the updated Single JSON body from a file").option("--stdin","Read the updated Single JSON body from stdin").option("--locale <locale>","Single locale (defaults to the project locale)").action(singlesUpdateCommand);var assets2=program.command("assets").description("Manage media assets");assets2.command("list").description("List assets").option("-C, --cwd <dir>","Project directory").option("--parent-id <id>","Filter by parent folder").option("--search <query>","Search across name, alt text, caption, and AI-generated alt / caption (case-insensitive)").option("--type <type>","Filter by entry type (file|folder)").option("--image","Filter to image MIME types (shortcut for --mime-prefix image/)").option("--video","Filter to video MIME types (shortcut for --mime-prefix video/)").option("--audio","Filter to audio MIME types (shortcut for --mime-prefix audio/)").option("--mime-prefix <prefix>",'Filter by MIME type prefix (e.g. "image/png")').option("--sort-by <field>","Sort field").option("--limit <n>","Max results").option("--offset <n>","Offset").action(assetsListCommand);assets2.command("upload").description("Upload a file to the media library").argument("<file>","Path to the file to upload").option("-C, --cwd <dir>","Project directory").option("--name <name>","Asset display name").option("--parent-id <id>","Target folder ID").option("--folder-path <path>","Target folder path, creating missing folders").action(assetsUploadCommand);var modelsCmd=new Command("models").description("Browse available media generation models");program.addCommand(modelsCmd,{hidden:!0});modelsCmd.command("list").description("List Fal models enabled for this project").option("-C, --cwd <dir>","Project directory").option("--modality <m>","Filter by modality (image | video | audio)").option("--search <query>","Search names and descriptions").option("--category <category>","Filter by Fal media category").option("--tag <t>","Filter by tag (repeatable; AND semantics \u2014 model must have every tag)",(value,previous)=>[...previous,value],[]).option("--extended","Per-model card: alias, provider, tags, price, best-for, flags").option("--json","Machine-readable JSON output").action(modelsListCommand);modelsCmd.command("show").description("Show a Fal model and its available flags").argument("<key>","Namespaced model id from `fimo models list`").option("-C, --cwd <dir>","Project directory").option("--json","Machine-readable JSON output (includes the per-model flag list)").action(modelsShowCommand);assets2.command("create-folder").description("Create a folder in the media library").argument("<name>","Folder name").option("-C, --cwd <dir>","Project directory").option("--parent-id <id>","Parent folder ID").action(assetsCreateFolderCommand);assets2.command("move").description("Move an asset to a different folder").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").requiredOption("--parent-id <id>",'Target folder ID (use "null" for root)').action(assetsMoveCommand);assets2.command("delete").description("Delete an asset").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").action(assetsDeleteCommand);assets2.command("open").description("Fetch asset metadata; optionally download locally or open in default viewer").argument("<id>","Asset ID").option("-C, --cwd <dir>","Project directory").option("--download","Download the asset bytes to a local file and print the path").option("--browser","Open the asset URL in the OS default viewer (open / xdg-open / start)").option("--path <path>","Override download destination (default: <tmpdir>/fimo-assets/<id>.<ext>). Implies --download.").action((id,options,cmd)=>(options.path&&!options.download&&(options.download=!0),assetsOpenCommand(id,options,cmd)));var forms2=program.command("forms").description("Manage forms");forms2.command("list").description("List all forms").option("-C, --cwd <dir>","Project directory").action(formsListCommand);forms2.command("get").description("Get a form by ID").argument("<id>","Form ID").option("-C, --cwd <dir>","Project directory").action(formsGetCommand);forms2.command("push").description("Push form JSON files to the API (create or update, patches id back)").argument("[formName]","Form name to push (omit to push all)").option("-C, --cwd <dir>","Project directory").action(formsPushCommand);forms2.command("delete").description("Delete a form").argument("<id>","Form ID").option("-C, --cwd <dir>","Project directory").action(formsDeleteCommand);var supportedAgentsHelp=`
|
|
1426
1439
|
Supported agents:
|
|
1427
1440
|
Universal (always covered via AGENTS.md, no per-agent file needed):
|
|
1428
1441
|
Codex, OpenCode, Aider, and other AGENTS.md-native tools
|