fimo 0.12.0 → 0.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/agent-templates/broken-link-sweeper/capabilities.yaml +0 -4
- package/assets/agent-templates/content-translator/capabilities.yaml +0 -2
- package/assets/agent-templates/seo-audit/capabilities.yaml +0 -1
- package/assets/content-templates/types-template.eta +13 -7
- package/assets/skills/fimo/SKILL.md +2 -2
- package/assets/skills/fimo-cli/SKILL.md +8 -8
- package/assets/skills/fimo-cli/references/agent-setup.md +1 -1
- package/assets/skills/fimo-cli/references/agents.md +5 -12
- package/assets/skills/fimo-cli/references/assets.md +2 -2
- package/assets/skills/fimo-cli/references/content.md +16 -30
- package/assets/skills/fimo-cli/references/describe.md +1 -1
- package/assets/skills/fimo-cli/references/forms.md +8 -8
- package/assets/skills/fimo-cli/references/init.md +5 -4
- package/assets/skills/fimo-cli/references/labels.md +4 -4
- package/assets/skills/fimo-cli/references/locales.md +3 -3
- package/assets/skills/fimo-cli/references/project-vars-and-secrets.md +1 -1
- package/assets/skills/fimo-code/SKILL.md +40 -50
- package/assets/skills/fimo-code/references/assets.md +6 -4
- package/assets/skills/fimo-code/references/content/clients.md +130 -0
- package/assets/skills/fimo-code/references/content/primitives.md +5 -0
- package/assets/skills/fimo-code/references/content/richtext.md +48 -0
- package/assets/skills/fimo-code/references/content/schema.md +122 -0
- package/assets/skills/fimo-code/references/content.md +12 -597
- package/assets/skills/fimo-code/references/design.md +1 -1
- package/assets/skills/fimo-code/references/frameworks/next/app-router.md +116 -0
- package/assets/skills/fimo-code/references/frameworks/next/locales.md +59 -0
- package/assets/skills/fimo-code/references/frameworks/next/pages-router.md +99 -0
- package/assets/skills/fimo-code/references/frameworks/next.md +116 -0
- package/assets/skills/fimo-code/references/frameworks/react-router.md +295 -0
- package/assets/skills/fimo-code/references/frameworks/vite-react.md +225 -0
- package/assets/skills/fimo-code/references/labels.md +24 -83
- package/assets/skills/fimo-code/references/locales.md +22 -111
- package/assets/skills/fimo-code/references/setup-plain-vite.md +3 -227
- package/assets/skills/fimo-code/references/setup-react-router.md +3 -276
- package/assets/skills/fimo-code/references/ui.md +32 -78
- package/dist/cli/bundle.json +2 -2
- package/dist/cli/index.js +16 -16
- package/dist/scripts/extract-translations.js +8 -1
- package/package.json +1 -1
- package/templates/react-router/AGENTS.md +10 -10
- package/templates/react-router/package.json +1 -1
- package/templates/react-router/react-router.config.ts +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -39,7 +39,7 @@ Expecting one of '${allowedValues.join("', '")}'`);return this._lifeCycleHooks[e
|
|
|
39
39
|
`),this.outputHelp({error:!0}));let config=errorOptions||{},exitCode=config.exitCode||1,code2=config.code||"commander.error";this._exit(exitCode,code2,message)}_parseOptionsEnv(){this.options.forEach(option=>{if(option.envVar&&option.envVar in 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=path43.basename(filename,path43.extname(filename)),this}executableDir(path44){return path44===void 0?this._executableDir:(this._executableDir=path44,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,ProjectVisibilitySchema,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"]),ProjectVisibilitySchema=z4.enum(["public","private"]),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_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image"},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image"},{mime:"image/webp",extensions:[".webp"],category:"image"},{mime:"image/avif",extensions:[".avif"],category:"image"},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:5242880},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:5242880},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:5242880}],ATTACHMENT_MIME_TYPES=ATTACHMENT_TYPES.map(t2=>t2.mime),ATTACHMENT_IMAGE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="image").map(t2=>t2.mime),ATTACHMENT_DOCUMENT_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="document").map(t2=>t2.mime),ATTACHMENT_ACCEPT_EXTENSIONS=ATTACHMENT_TYPES.flatMap(t2=>t2.extensions),ATTACHMENT_ACCEPT_STRING=[...ATTACHMENT_ACCEPT_EXTENSIONS,...ATTACHMENT_MIME_TYPES].join(","),ATTACHMENT_DROPZONE_ACCEPT=Object.fromEntries(ATTACHMENT_TYPES.map(t2=>[t2.mime,t2.extensions]))}});import{z as 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}var ENV_ID_REGEX,MAX_ENV_LENGTH,EnvSchema,DEFAULT_ENV,PRODUCTION_ENV,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";ENV_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_ENV_LENGTH=255;__name(isValidEnv,"isValidEnv");__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")}});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,path43){let conditionPath=[...path43,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,path43)=>{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,path43));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path43,fieldName,variant.uid]);else walk(field.schema.fields,[...path43,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path43,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path43,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","cutover_step","agent_delegate","ops_access_change","ops_service_token_change","ops_project_search","ops_project_inspect","ops_project_chat_read","ops_recent_chat_read","ops_project_snapshot","ops_support_thread_read","ops_support_report_read","ops_support_report_change","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send","ops_project_operation"],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,OPS_PROJECT_OPERATIONS,OpsProjectOperationKindSchema,ExactVersionSchema,OpsProjectOperationPlanInputSchema,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:logs:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","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: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:logs:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","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)}),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")})]),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)})}});var FIMO_CONFIG_PATH,LEGACY_FIMO_CONFIG_PATHS,ALL_FIMO_CONFIG_PATHS,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]}});import{z as z11}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","google/gemini-3.1-pro-preview","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=z11.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z11.string(),displayName:z11.string().nullable(),subdomain:z11.string().nullable().optional(),subdomainUpdatedAt:z11.date().nullable().optional(),organizationId:z11.string().nullable(),createdBy:z11.string().nullable(),visibility:ProjectVisibilitySchema,previewEnabled:z11.boolean().default(!0),enabledChatModels:z11.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z11.string(),thumbnailUrl:z11.string().nullable(),publishedThumbnailUrl:z11.string().nullable(),category:z11.string().nullable(),appUrl:z11.string().nullable(),lastPublishedAt:z11.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z11.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z11.object({id:z11.uuid(),name:z11.string(),displayName:z11.string().nullable(),thumbnailUrl:z11.string().nullable(),visibility:ProjectVisibilitySchema,category:z11.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z11.object({id:z11.string(),name:z11.string(),avatar:z11.string().nullable(),color:z11.object({bg:z11.string(),text:z11.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z11.object({path:z11.string(),content:z11.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z11.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z11.object({id:z11.string(),messageId:z11.string(),versionId:z11.string().nullable(),role:ProjectChatMessageRole,parts:z11.array(z11.any()),createdAt:z11.coerce.date()}),MessageUserMetadataSchema=z11.object({id:z11.string(),name:z11.string().nullable().optional(),image:z11.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z11.number(),metadata:z11.object({user:MessageUserMetadataSchema,changeManifest:z11.array(z11.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z11.object({versionId:z11.uuid(),commitHash:z11.string(),name:z11.string(),description:z11.string().nullable(),kind:z11.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z11.object({versionCount:z11.number().int().nonnegative(),snapshotBytes:z11.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z11.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z11.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z11.object({content:z11.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z11.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z11.object({success:z11.boolean(),message:z11.string().optional(),warning:z11.string().optional(),durationMs:z11.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z11.object({isPublished:z11.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z11.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublicationMutationDTOSchema=z11.object({success:z11.boolean(),message:z11.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z11.boolean()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z12}from"zod";var ProjectEnvStatusSchema,ProjectEnvDTOSchema,ProjectEnvDTO,CreateProjectEnvRequestSchema,SyncProjectEnvRequestSchema,ProjectEnvResponseSchema,ProjectEnvsListResponseSchema,EnvSurfaceDiffSchema,EnvDiffResultSchema,EnvDiffResultDTO,init_project_env_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-env.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();ProjectEnvStatusSchema=z12.enum(["provisioning","active","deleted"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z12.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,previewUrl:z12.string().nullable(),parentEnv:EnvSchema.nullable(),createdBy:z12.string().nullable(),deletedAt:z12.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),CreateProjectEnvRequestSchema=z12.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z12.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z12.array(ProjectEnvDTOSchema)),EnvSurfaceDiffSchema=z12.object({surface:z12.enum(["code","schemas","content","translations","assets","forms"]),status:z12.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z12.number().int().nonnegative(),conflictCount:z12.number().int().nonnegative()}),EnvDiffResultSchema=z12.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z12.coerce.date(),surfaces:z12.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z13}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=z13.object({success:z13.literal(!0),downloadUrl:z13.string(),expiresAt:z13.string(),fileSize:z13.number(),duration:z13.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z13.object({success:z13.literal(!0),projectId:z13.string(),projectName:z13.string(),displayName:z13.string(),projectUrl:z13.string(),duration:z13.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z13.object({contentTypes:z13.number(),entries:z13.number(),assets:z13.number(),translations:z13.number(),forms:z13.number(),codeFiles:z13.number(),assetFiles:z13.number()}),ImportPreviewSurfaceDTOSchema=z13.object({name:z13.string(),included:z13.boolean(),count:z13.number().optional(),note:z13.string().optional()}),ImportPreviewDTOSchema=z13.object({projectName:z13.string(),displayName:z13.string().nullable(),visibility:z13.string().nullable(),category:z13.string().nullable(),exportedAt:z13.string(),version:z13.string(),envScope:z13.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z13.array(ImportPreviewSurfaceDTOSchema),fileSize:z13.number(),fileName:z13.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z13.object({success:z13.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z14}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=z14.enum(["manual","schedule","webhook"]),ManualTriggerSchema=z14.object({type:z14.literal("manual")}),ScheduleTriggerSchema=z14.object({type:z14.literal("schedule"),cron:z14.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:z14.string().optional()}),WebhookTriggerSchema=z14.object({type:z14.literal("webhook"),path:z14.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z14.discriminatedUnion("type",[ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema])}});import{z as z15}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=z15.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z15.object({token:z15.string().min(1),risk:CapabilityRiskTierSchema,description:z15.string()}),AgentSubAgentSummarySchema=z15.object({name:z15.string().min(1),grant:z15.enum(["inherit","explicit"]),effectiveCaps:z15.array(z15.string().min(1))}),AgentInstallSummaryDTOSchema=z15.object({agentName:z15.string().min(1),env:z15.string().min(1),declaredCapabilities:z15.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z15.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z15.array(CapabilitySummaryEntrySchema),criticalCapabilities:z15.array(CapabilitySummaryEntrySchema),subAgents:z15.array(AgentSubAgentSummarySchema),declaresDelegate:z15.boolean(),cycle:z15.array(z15.string()).nullable(),missingSubAgents:z15.array(z15.string()),warnings:z15.array(z15.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z16}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=z16.object({kind:TriggerKindSchema,summary:z16.string()}),AgentListItemTriggerStateSchema=z16.object({triggerIndex:z16.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z16.boolean(),wired:z16.boolean(),syncError:z16.string().nullable()}),AgentListItemDTOSchema=z16.object({name:z16.string().min(1),description:z16.string().nullable(),goalFirstLine:z16.string().nullable(),declaredCapabilities:z16.array(CapabilitySummaryEntrySchema),triggers:z16.array(AgentListItemTriggerSchema),triggerStates:z16.array(AgentListItemTriggerStateSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z16.array(AgentListItemDTOSchema))}});import{z as z17}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=z17.object({args:z17.unknown().optional(),requestId:z17.string().min(1).max(128).optional()}),DispatchSkippedSchema=z17.object({skipped:z17.enum(["no-manual-trigger","trigger-not-wired","run-in-progress","task-env-budget"])}),DispatchAcceptedSchema=z17.object({sessionId:z17.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z17.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z18}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=z18.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z18.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z18.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z18.object({verb:SurfaceDeltaVerbSchema,key:z18.string(),detail:z18.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z18.record(z18.string(),z18.unknown()).optional()}),PerSurfaceDeltaSchema=z18.object({surface:SurfaceNameSchema,status:z18.enum(["ok","timed_out","failed","unchanged"]),durationMs:z18.number().int().nonnegative().optional(),changedCount:z18.number().int().nonnegative(),conflictCount:z18.number().int().nonnegative(),items:z18.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z18.boolean().optional(),error:z18.string().optional()}),CrossSurfaceFindingSchema=z18.object({id:z18.string(),kind:z18.string(),description:z18.string(),severity:z18.enum(["warning","error"]),source:z18.object({surface:SurfaceNameSchema,key:z18.string()}),target:z18.object({surface:SurfaceNameSchema,key:z18.string()}),actions:z18.array(z18.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z18.object({env:EnvSchema,vs:EnvSchema,syncState:z18.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z18.coerce.date(),surfaces:z18.array(PerSurfaceDeltaSchema),agents:z18.array(z18.object({id:z18.string(),name:z18.string(),status:z18.enum(["active","paused","failed"]),lastRunAt:z18.coerce.date().nullable()})).optional(),crossSurface:z18.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z18.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z18.coerce.date(),surfaces:z18.array(PerSurfaceDeltaSchema),crossSurface:z18.array(CrossSurfaceFindingSchema).optional(),fingerprint:z18.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z18.object({path:z18.string(),state:z18.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z18.string(),additions:z18.number().int().nonnegative(),deletions:z18.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z18.object({oid:z18.string().optional(),content:z18.string().optional(),truncated:z18.boolean(),binary:z18.boolean()}),CodeConflictDetailSchema=z18.object({path:z18.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z18.string(),targetTipSha:z18.string(),mergeBaseSha:z18.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z18.object({id:z18.string(),slug:z18.string(),contentType:z18.string(),data:z18.record(z18.string(),z18.unknown()),updatedAt:z18.coerce.date()}),ContentRowDiffSchema=z18.object({collection:z18.string(),rowId:z18.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z18.object({name:z18.string(),label:z18.string(),isSingleton:z18.boolean(),fields:z18.record(z18.string(),z18.unknown())}),SchemaTypeDiffSchema=z18.object({typeName:z18.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z18.object({id:z18.string(),name:z18.string(),type:z18.enum(["file","folder"]),mimeType:z18.string().nullable(),storageKey:z18.string().nullable(),url:z18.string().nullable(),fileSize:z18.number().nullable(),width:z18.number().nullable(),height:z18.number().nullable(),altText:z18.string().nullable(),caption:z18.string().nullable(),createdAt:z18.coerce.date(),updatedAt:z18.coerce.date()}),AssetDiffSchema=z18.object({assetId:z18.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z18.object({locale:z18.string(),key:z18.string(),parent:z18.string().nullable(),child:z18.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z18.object({formName:z18.string(),label:z18.string().nullable(),schemaFingerprint:z18.string(),fields:z18.record(z18.string(),z18.unknown()),settings:z18.record(z18.string(),z18.unknown()).optional()}),FormSchemaDiffSchema=z18.object({formName:z18.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=z18.enum(CONFLICT_KINDS),ConflictSchema=z18.object({surface:SurfaceNameSchema,key:z18.string(),kind:ConflictKindSchema.optional(),description:z18.string(),parentValue:z18.unknown().optional(),childValue:z18.unknown().optional(),conflictingFields:z18.array(z18.string()).optional(),code:z18.object({path:z18.string(),unresolvable:z18.boolean().optional(),reason:z18.string().optional()}).optional()}),FieldPickSchema=z18.object({field:z18.string(),choice:z18.enum(["parent","child","pick","ai-pick"]),pickedValue:z18.unknown().optional(),aiSessionId:z18.string().optional()}),ConflictResolutionSchema=z18.object({surface:SurfaceNameSchema,key:z18.string(),choice:z18.enum(["parent","child","pick"]),pickedValue:z18.unknown().optional(),fieldPicks:z18.array(FieldPickSchema).optional()}),MergeResultSchema=z18.object({ok:z18.boolean(),mergeId:z18.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z18.array(z18.object({surface:SurfaceNameSchema,count:z18.number().int().nonnegative()})),conflicts:z18.array(ConflictSchema).optional(),summary:z18.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z18.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z18.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z18.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z18.boolean().optional()}),ResolvedStrategySchema=z18.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z18.boolean()}),MergeRequestSchema=z18.object({from:EnvSchema,allowDirectMerge:z18.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z18.object({mergeId:z18.string().uuid(),streamUrl:z18.string(),strategy:ResolvedStrategySchema,acceptedAt:z18.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z18.object({mergeId:z18.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z18.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z18.array(ConflictSchema),draftResolutions:z18.array(ConflictResolutionSchema),lastEditedBy:z18.string().nullable(),lastEditedAt:z18.coerce.date().nullable(),initiator:z18.object({userId:z18.string().nullable(),role:z18.string().nullable(),agentName:z18.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z18.object({resolutions:z18.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z18.object({mergeId:z18.string().uuid(),draftResolutions:z18.array(ConflictResolutionSchema),lastEditedAt:z18.coerce.date(),lastEditedBy:z18.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z18.object({mergeId:z18.string().uuid(),resolutions:z18.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z18.object({mergeId:z18.string().uuid()}),PublishReleaseRequestSchema=z18.object({version:z18.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z18.string().max(2e4).optional()}),PublishReleaseResultSchema=z18.object({releaseTag:z18.string(),sha:z18.string(),publishedAt:z18.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z19}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=z19.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z19.object({cpuMs:z19.number().nonnegative().default(0),netBytes:z19.number().nonnegative().default(0),walltimeMs:z19.number().nonnegative().default(0),llmTokensIn:z19.number().nonnegative().optional(),llmTokensOut:z19.number().nonnegative().optional()}),AgentSessionReviewPublicationSchema=z19.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z19.object({capturedAt:z19.coerce.date(),fingerprint:z19.string().min(1).max(256),counts:z19.object({code:z19.number().int().nonnegative(),content:z19.number().int().nonnegative(),schemas:z19.number().int().nonnegative(),labels:z19.number().int().nonnegative()}),publication:AgentSessionReviewPublicationSchema,mergeId:z19.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z19.object({diff:DiffReportSchema,code:z19.array(CodeFileDiffSchema.extend({raw:z19.string().max(24576)})).max(200),schemas:z19.array(SchemaTypeDiffSchema).max(200),content:z19.array(z19.object({key:z19.string().min(1).max(512),collection:z19.string().min(1).max(256),slug:z19.string().max(512).optional(),verb:z19.enum(["added","modified","deleted"]),fields:z19.array(z19.object({name:z19.string().min(1).max(256),before:z19.unknown().optional(),after:z19.unknown().optional()})).max(20)})).max(200),labels:z19.array(z19.object({key:z19.string().min(1).max(512),locale:z19.string().min(1).max(64).optional(),before:z19.unknown().nullable(),after:z19.unknown().nullable()})).max(200)}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),AgentSessionDTOSchema=z19.object({id:z19.uuid(),projectId:z19.uuid(),env:EnvSchema,agentName:z19.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z19.unknown().optional(),capabilities:z19.array(z19.string()).optional(),dataSources:z19.array(z19.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z19.string().nullable(),startedAt:z19.coerce.date().nullable(),finishedAt:z19.coerce.date().nullable(),cancelledAt:z19.coerce.date().nullable(),costUsd:z19.number().nonnegative(),costCeilingUsd:z19.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z19.boolean(),lastCheckpointId:z19.uuid().nullable(),branchEnvId:z19.uuid().nullable(),parentSessionId:z19.uuid().nullable(),terminalReason:z19.string().nullable(),errorMessage:z19.string().nullable(),report:z19.string().nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z19.string().nullable(),createdAt:z19.coerce.date(),updatedAt:z19.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z19.object({id:z19.uuid(),sessionId:z19.uuid(),checkpointIdx:z19.number().int().nonnegative(),payloadRef:z19.string(),payloadSizeBytes:z19.number().int().nonnegative(),checksum:z19.string().length(64),createdAt:z19.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z19.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z19.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z19.object({session:AgentSessionDTOSchema,checkpoints:z19.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z19.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=z19.object({reason:z19.string().min(1).max(120).optional()})}});import{z as z20}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=z20.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z20.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z20.object({id:z20.uuid(),envId:z20.uuid(),sessionId:z20.uuid().nullable(),skillName:z20.string().min(1),classification:AgentBranchClassificationSchema,rationale:z20.string().nullable(),summary:z20.string().nullable(),surfaceDeltas:z20.record(z20.string(),z20.unknown()),createdAt:z20.coerce.date(),decidedAt:z20.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z20.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z20.object({path:z20.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z20.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z20.object({code:z20.literal("merge_conflict"),message:z20.string(),conflicts:z20.record(z20.string(),z20.number().int().nonnegative())})}});import{z as z21}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=z21.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z21.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z21.enum(["secret_text"]),IntegrationCredentialUsageSchema=z21.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z21.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z21.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z21.object({mode:IntegrationAuthModeSchema,label:z21.string().min(1),description:z21.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z21.object({id:z21.string().min(1),label:z21.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z21.boolean()}),IntegrationToolDefinitionDTOSchema=z21.object({key:z21.string().min(1),name:z21.string().min(1),description:z21.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z21.object({title:z21.string().min(1),description:z21.string().min(1),command:z21.string().min(1).optional()}),IntegrationInfoDTOSchema=z21.object({key:z21.string().min(1),name:z21.string().min(1),summary:z21.string().min(1),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z21.array(IntegrationAuthModeDTOSchema),credentials:z21.array(IntegrationCredentialDefinitionDTOSchema),tools:z21.array(IntegrationToolDefinitionDTOSchema),recipes:z21.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z21.object({projectId:z21.uuid(),integrationKey:z21.string().min(1),name:z21.string().min(1),summary:z21.string().min(1),installed:z21.boolean(),enabled:z21.boolean(),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z21.string().nullable(),connectionId:z21.uuid().nullable().optional(),connectionAlias:z21.string().min(1).nullable().optional(),connectionStatus:z21.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z21.array(z21.string()),installedAt:z21.coerce.date().nullable(),updatedAt:z21.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z21.object({id:z21.uuid(),projectId:z21.uuid(),integrationKey:z21.string().min(1),enabled:z21.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z21.string(),connectionId:z21.uuid().nullable().optional(),connectionAlias:z21.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z21.array(z21.string()),createdAt:z21.coerce.date(),updatedAt:z21.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z21.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z21.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z21.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z21.object({value:z21.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z21.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z21.object({id:z21.uuid(),organizationId:z21.string().min(1),integrationKey:z21.string().min(1),alias:z21.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z21.string().min(1),externalAccountName:z21.string().nullable(),externalBotUserId:z21.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z21.array(z21.string()),connectedAt:z21.coerce.date(),updatedAt:z21.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ConnectOrganizationIntegrationRequestSchema=z21.object({alias:z21.string().min(1).max(120).optional(),token:z21.string().min(1).optional()}),ProjectIntegrationReturnPathSchema=z21.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),ConnectProjectIntegrationRequestSchema=z21.discriminatedUnion("mode",[z21.object({mode:z21.literal("personal"),alias:z21.string().min(1).max(120),token:z21.string().min(1)}),z21.object({mode:z21.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional()})]),StartProjectIntegrationConnectResponseSchema=z21.object({integrationKey:z21.string().min(1),connectUrl:z21.string().url(),expiresAt:z21.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z21.discriminatedUnion("mode",[z21.object({mode:z21.literal("personal"),integrationKey:z21.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z21.object({mode:z21.literal("oauth"),integrationKey:z21.string().min(1),connectUrl:z21.string().url(),expiresAt:z21.coerce.date()})]),BindProjectChannelRequestSchema=z21.object({ref:z21.string().min(1),connectionAlias:z21.string().min(1).optional(),agentName:z21.string().min(1).max(160).nullable().optional(),force:z21.boolean().optional()}),ListProjectChannelsQuerySchema=z21.object({integrationKey:z21.string().min(1)}),SearchProjectChannelsQuerySchema=z21.object({integrationKey:z21.string().min(1),connectionAlias:z21.string().min(1),query:z21.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z21.object({id:z21.uuid(),projectId:z21.uuid(),integrationKey:z21.string().min(1),connectionId:z21.uuid(),externalWorkspaceId:z21.string().min(1),externalChannelId:z21.string().min(1),externalChannelName:z21.string().nullable(),agentName:z21.string().nullable(),enabled:z21.boolean(),createdAt:z21.coerce.date(),updatedAt:z21.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z21.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z21.object({id:z21.string().min(1),name:z21.string().min(1),visibility:z21.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z21.string().min(1).nullable(),canMove:z21.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z21.object({markdown:z21.boolean().optional(),summary:z21.boolean().optional(),links:z21.boolean().optional(),images:z21.boolean().optional(),html:z21.union([z21.literal("cleaned"),z21.literal("raw"),z21.boolean()]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z21.object({url:z21.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z21.boolean().optional(),timeoutMs:z21.number().int().positive().max(12e4).optional(),waitForMs:z21.number().int().min(0).max(3e4).optional()}),FirecrawlSearchToolInputSchema=z21.object({query:z21.string().min(1),maxResults:z21.number().int().positive().max(20).optional(),sources:z21.array(z21.enum(["web","news","images"])).min(1).max(3).optional(),categories:z21.array(z21.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z21.array(z21.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z21.array(z21.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z21.enum(["hour","day","week","month","year"]).optional(),location:z21.string().min(1).max(160).optional(),country:z21.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z21.boolean().optional(),timeoutMs:z21.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlMapToolInputSchema=z21.object({url:z21.string().url(),search:z21.string().min(1).optional(),limit:z21.number().int().positive().max(200).optional(),includeSubdomains:z21.boolean().optional(),timeoutMs:z21.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z21.object({url:z21.string().url(),limit:z21.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z21.boolean().optional(),timeoutMs:z21.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z21.object({text:z21.string().min(1).max(200).optional(),cron:z21.string().min(1).max(120).optional(),timezone:z21.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorTargetInputSchema=z21.object({type:z21.enum(["scrape","crawl"]).default("scrape"),urls:z21.array(z21.string().url()).min(1).max(50),scrapeOptions:z21.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z21.boolean().optional(),timeoutMs:z21.number().int().positive().max(12e4).optional(),waitForMs:z21.number().int().min(0).max(3e4).optional()}).optional()}),FirecrawlMonitorCreateToolInputSchema=z21.object({name:z21.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z21.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z21.string().min(1).max(2e3).optional(),judgeEnabled:z21.boolean().optional(),retentionDays:z21.number().int().min(1).max(365).optional(),notification:z21.object({email:z21.object({enabled:z21.boolean().default(!0),recipients:z21.array(z21.string().email()).min(1).max(20),includeDiffs:z21.boolean().optional()}).optional()}).optional()}),FirecrawlMonitorIdToolInputSchema=z21.object({monitorId:z21.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z21.string().uuid()}),RunProjectIntegrationToolRequestSchema=z21.object({tool:z21.string().min(1),input:z21.record(z21.string(),z21.unknown()),connectionAlias:z21.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z21.object({provider:z21.string().min(1),providerCredits:z21.number().nonnegative().optional(),providerCostUsd:z21.number().nonnegative().optional(),requests:z21.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z21.object({credits:z21.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z21.object({url:z21.string(),provider:z21.literal("firecrawl"),title:z21.string().optional(),statusCode:z21.number().optional(),markdown:z21.string().optional(),summary:z21.string().optional(),links:z21.array(z21.string()).optional(),images:z21.array(z21.string()).optional(),html:z21.string().optional(),warning:z21.string().optional()}),FirecrawlSearchToolOutputSchema=z21.object({query:z21.string(),provider:z21.literal("firecrawl"),warning:z21.string().optional(),results:z21.array(z21.object({title:z21.string(),url:z21.string(),snippet:z21.string().optional(),content:z21.string().optional(),score:z21.number().optional(),publishedAt:z21.string().optional()}))}),FirecrawlMapToolOutputSchema=z21.object({url:z21.string(),provider:z21.literal("firecrawl"),count:z21.number(),links:z21.array(z21.object({url:z21.string(),title:z21.string().optional(),description:z21.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z21.object({url:z21.string(),provider:z21.literal("firecrawl"),total:z21.number(),pages:z21.array(z21.object({url:z21.string(),title:z21.string().optional(),statusCode:z21.number().optional(),markdown:z21.string().optional(),summary:z21.string().optional(),links:z21.array(z21.string()).optional(),images:z21.array(z21.string()).optional(),html:z21.string().optional(),warning:z21.string().optional()})),warning:z21.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z21.object({cron:z21.string().optional(),text:z21.string().optional(),timezone:z21.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z21.object({id:z21.string().optional(),urls:z21.array(z21.string()).optional(),scrapeOptions:z21.record(z21.string(),z21.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z21.object({id:z21.string(),name:z21.string(),status:z21.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z21.string().nullable().optional(),lastRunAt:z21.string().nullable().optional(),currentCheckId:z21.string().nullable().optional(),targets:z21.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z21.string().nullable().optional(),judgeEnabled:z21.boolean().optional(),estimatedCreditsPerMonth:z21.number().optional(),createdAt:z21.string().optional(),updatedAt:z21.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z21.object({id:z21.string(),monitorId:z21.string(),scheduledFor:z21.string().nullable().optional(),startedAt:z21.string().nullable().optional(),finishedAt:z21.string().nullable().optional(),estimatedCredits:z21.number().optional(),reservedCredits:z21.number().optional(),actualCredits:z21.number().optional(),billingStatus:z21.string().nullable().optional(),summary:z21.object({totalPages:z21.number().optional(),same:z21.number().optional(),changed:z21.number().optional(),new:z21.number().optional(),removed:z21.number().optional(),error:z21.number().optional()}).passthrough().optional(),error:z21.string().nullable().optional(),createdAt:z21.string().optional(),updatedAt:z21.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z21.object({provider:z21.literal("firecrawl"),monitors:z21.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z21.object({provider:z21.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z21.object({provider:z21.literal("firecrawl"),monitorId:z21.string(),deleted:z21.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z21.object({provider:z21.literal("firecrawl"),monitorId:z21.string(),checks:z21.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z21.object({provider:z21.literal("firecrawl"),monitorId:z21.string(),check:FirecrawlMonitorCheckOutputSchema,next:z21.string().optional()}),FirecrawlToolKeySchema=z21.enum(["search","scrape","map","crawl","monitor.create","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z21.union([FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z21.object({projectId:z21.uuid(),integrationKey:z21.string().min(1),tool:z21.string().min(1),connectionAlias:z21.string().min(1).nullable().optional(),output:z21.record(z21.string(),z21.unknown()),executedAt:z21.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z21.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z21.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z21.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z21.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z21.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z21.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z21.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z21.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z21.array(OrganizationIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z21.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z21.array(ProjectChannelCandidateDTOSchema))}});import{z as z22}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,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_create_dto();init_response();PROJECT_SECRET_KEY_PATTERN=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN=/^(PUBLIC_|VITE_|NEXT_PUBLIC_)/,RESERVED_PROJECT_SECRET_KEYS=new Set(["FIMO_API_URL","FIMO_API_TOKEN","FIMO_PROJECT_ID","FIMO_ENV","FIMO_AGENT_SESSION","FIMO_DATA_SOURCES","FIMO_SCHEDULE_ID","FIMO_SCHEDULE_RUN_ID","FIMO_SCHEDULE_NAME","VITE_API_URL","VITE_ENABLE_ANALYTICS","VITE_FIMO_BRANCH","VITE_FIMO_IMAGE_HOSTS"]),ProjectSecretKeySchema=z22.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=z22.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z22.uuid(),env:z22.string().min(1),name:z22.string().min(1),cron:z22.string().min(1),command:z22.string().min(1),secretKeys:z22.array(z22.string().min(1)),enabled:z22.boolean(),lastRunAt:z22.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z22.string().nullable()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z22.object({name:z22.string().min(1).max(120),cron:z22.string().min(1).max(120),command:z22.string().min(1).max(500),secretKeys:z22.array(ProjectSecretKeySchema).default([])}),UpdateProjectScheduleRequestSchema=z22.object({name:z22.string().min(1).max(120).optional(),cron:z22.string().min(1).max(120).optional(),command:z22.string().min(1).max(500).optional(),secretKeys:z22.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z22.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z22.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z22.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z22.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z22.object({maxRuns:z22.number().int().positive(),retentionDays:z22.number().int().positive().nullable(),outputRetentionDays:z22.number().int().positive(),maxOutputBytes:z22.number().int().positive()}),ProjectScheduleUsageSchema=z22.object({runCount:z22.number().int().nonnegative(),runsWithOutput:z22.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z22.object({id:z22.uuid(),scheduleId:z22.uuid(),projectId:z22.uuid(),env:z22.string().min(1),scheduleName:z22.string().min(1),command:z22.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z22.object({id:z22.string().min(1),name:z22.string().min(1)}).nullable(),queuedAt:z22.coerce.date(),startedAt:z22.coerce.date().nullable(),finishedAt:z22.coerce.date().nullable(),exitCode:z22.number().int().nullable(),errorCode:z22.string().nullable(),error:z22.string().nullable(),outputBytes:z22.number().int().nonnegative(),outputTruncated:z22.boolean(),outputExpiresAt:z22.coerce.date().nullable(),metadataExpiresAt:z22.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z22.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z22.coerce.date().nullable(),items:z22.array(z22.object({key:z22.string().min(1),updatedAt:z22.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z22.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z22.object({trigger:z22.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z22.object({limit:z22.coerce.number().int().min(1).max(100).default(25),cursor:z22.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z22.object({items:z22.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z22.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z22.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z22.object({items:z22.array(ProjectScheduleRunDTOSchema),nextCursor:z22.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z23}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=z23.object({id:z23.uuid(),occurredAt:z23.coerce.date(),projectId:z23.uuid().nullable(),env:z23.string().nullable(),actor:z23.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z23.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z23.unknown().optional(),ipAddress:z23.string().nullable().optional(),userAgent:z23.string().nullable().optional(),error:z23.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z23.object({rows:z23.array(AuditLogRowDTOSchema),nextCursor:z23.string().nullable()})),AuditLogQuerySchema=z23.object({env:z23.string().optional(),action:AuditActionSchema.optional(),actor:z23.string().optional(),from:z23.coerce.date().optional(),to:z23.coerce.date().optional(),limit:z23.coerce.number().int().min(1).max(200).optional(),cursor:z23.string().optional()})}});import{z as z24}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=z24.object({surface:SurfaceNameSchema,key:z24.string(),label:z24.string()}),InlineSchema=z24.object({text:z24.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z24.discriminatedUnion("type",[z24.object({type:z24.literal("paragraph"),content:z24.array(InlineSchema).max(24)}),z24.object({type:z24.literal("preview"),ref:DiffRefSchema,caption:z24.string().optional()}),z24.object({type:z24.literal("code"),code:z24.string(),lang:z24.string().optional(),caption:z24.string().optional()}),z24.object({type:z24.literal("risk"),level:z24.enum(["warning","error"]),content:z24.array(InlineSchema).max(24)}),z24.object({type:z24.literal("list"),items:z24.array(z24.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z24.object({headline:z24.string(),blocks:z24.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z24.object({summary:EnvDiffSummarySchema,fingerprint:z24.string(),generatedAt:z24.coerce.date(),cached:z24.boolean().optional(),credits:z24.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z25}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=z25.object({date:z25.string(),visitors:z25.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z25.object({key:z25.string(),visitors:z25.number().int().nonnegative(),pageviews:z25.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z25.object({path:z25.string(),pageName:z25.string().nullable().optional(),visitors:z25.number().int().nonnegative(),pageviews:z25.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z25.object({preset:z25.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z25.string(),requestedTo:z25.string(),effectiveFrom:z25.string(),effectiveTo:z25.string(),isRetentionLimited:z25.boolean(),groupBy:z25.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z25.object({date:z25.string(),content:z25.string(),updatedAt:z25.string(),updatedByUserId:z25.string()}),ProjectPageviewAnalyticsDTOSchema=z25.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z25.number().int().nonnegative(),pageviews:z25.number().int().nonnegative(),bounceRate:z25.number().min(0).max(100),viewsPerVisit:z25.number().nonnegative(),averageVisitDurationSeconds:z25.number().nonnegative(),visitorsSeries:z25.array(ProjectDailyVisitorsDTOSchema),topPages:z25.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z25.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z25.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z25.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z25.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z25.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z26}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=z26.object({id:z26.string(),email:z26.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z26.coerce.date(),createdAt:z26.coerce.date(),inviterUserId:z26.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z26.object({id:z26.string(),token:z26.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z26.object({success:z26.boolean(),projectId:z26.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z27}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=z27.object({id:z27.string(),name:z27.string(),image:z27.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z27.object({count:z27.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z27.object({counts:z27.object({signed_up:z27.int(),activated:z27.int()}),credits:z27.object({total:z27.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z27.email(),emailVerified:z27.boolean(),createdAt:z27.coerce.date(),updatedAt:z27.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z28}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=z28.object({id:z28.string(),principalType:ProjectPrincipalTypeSchema,principalId:z28.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z28.coerce.date(),expiresAt:z28.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","preview:view","realtime:connect","analytics:view","logs:view","domain:manage","agent:run"],ProjectPermissionKeySchema=z28.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z28.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z28.record(z28.string(),z28.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z28.object({access:z28.array(ProjectAccessItemDTOSchema),invites:z28.array(ProjectInviteDTOSchema),organization:z28.object({name:z28.string().nullable(),logo:z28.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z28.object({success:z28.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z28.object({success:z28.boolean(),projectId:z28.uuid()}))}});import{z as z29}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=z29.object({publicationStatus:PublicationStatusSchema,appUrl:z29.string().nullable(),lastPublishedAt:z29.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z30}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=z30.object({url:z30.url(),expiresAt:z30.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema)}});import{z as z31}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:z31.string(),slug:z31.string().nullable(),logo:z31.string().nullable(),metadata:z31.record(z31.string(),z31.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z31.object({id:z31.string(),name:z31.string(),email:z31.email(),image:z31.string().nullable()}),OrganizationMemberDTOSchema=z31.object({id:z31.string(),userId:z31.string(),organizationId:z31.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z31.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z32}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common();init_create_dto();init_response();CancellationReasonCodeSchema=z32.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z32.object({reason:CancellationReasonCodeSchema,details:z32.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z32.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),AiCreditsEntitlementSchema=z32.object({included:z32.number().optional(),unitPrice:z32.number().optional(),dailyCap:z32.number().nullable().optional()}),EntitlementsDTOSchema=z32.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z32.object({retentionDays:z32.number().int().positive(),canUseExtendedDateRanges:z32.boolean()}).optional(),history:z32.object({retentionDays:z32.number().int().positive()}).optional(),members:z32.object({canInvite:z32.boolean(),maxMembers:z32.number().int().positive().nullable()}).optional(),projects:z32.object({canCreatePrivateProjects:z32.boolean(),maxPrivateProjects:z32.number().int().positive().nullable()}).optional(),domains:z32.object({canUseCustomDomains:z32.boolean(),maxDomains:z32.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z32.object({id:z32.string(),external_id:z32.string(),customerId:z32.string(),planId:z32.string(),planCode:TemplateCodeSchema,currentPeriod:z32.object({start:z32.string(),end:z32.string().nullable()}),cancelAt:z32.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z32.string(),nextPaymentAt:z32.string().nullable(),baseAmount:z32.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z32.object({totalCap:z32.number(),dailyCap:z32.number(),usedTotal:z32.number()}),CreditBalanceDTOSchema=z32.object({total:z32.number(),base:z32.number(),dailyBase:z32.number(),purchases:z32.number(),awards:z32.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z32.object({total:z32.number(),nearLimit:z32.boolean(),canChat:z32.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z32.object({dailyFreeAvailable:z32.number(),monthlyAvailable:z32.number(),purchasedAvailable:z32.number(),awardedAvailable:z32.number()}),ProjectDailyCreditAllowanceDTOSchema=z32.object({periodCap:z32.number(),dailyGrant:z32.number(),usedThisPeriod:z32.number(),remainingThisPeriod:z32.number()}),ProjectCreditBalanceDTOSchema=z32.object({projectId:z32.uuid(),organizationId:z32.string(),balance:z32.object({totalAvailable:z32.number(),nearLimit:z32.boolean(),canUseAi:z32.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z32.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),SuccessfulPurchaseDTOSchema=z32.object({invoiceId:z32.string(),newBalance:z32.int(),creditCount:z32.int(),amountUsd:z32.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z32.object({url:z32.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema)}});import{z as z33}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=z33.object({brand:z33.string(),last4:z33.string(),exp:z33.string(),isDefault:z33.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z34}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=z34.string().superRefine((path43,ctx)=>{let segments=path43.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=z34.object({type:z34.literal("renameField"),contentType:z34.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z34.object({enabled:z34.boolean()}).strict(),ContentTypeDTOSchema=z34.object({id:z34.string(),name:z34.string(),label:z34.string(),isSingleton:z34.boolean(),i18n:ContentTypeI18nSchema,fields:z34.record(z34.string(),FieldDefinitionSchema),createdAt:z34.string(),updatedAt:z34.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z34.object({contentTypes:z34.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z34.object({id:z34.string(),entryId:z34.string(),documentId:z34.string(),slug:z34.string(),locale:z34.string().optional(),createdAt:z34.string(),updatedAt:z34.string(),__fimo:z34.object({contentType:z34.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z34.object({data:z34.array(EntryDTOSchema),meta:z34.object({limit:z34.number(),offset:z34.number(),total:z34.number(),hasMore:z34.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z34.object({contentType:z34.string(),count:z34.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z34.object({counts:z34.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z34.object({count:z34.number().int().nonnegative(),sourceLocale:z34.string(),targetLocale:z34.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z34.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z34.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z34.union([z34.string(),z34.number(),z34.boolean(),z34.null()]),entryWhereOperatorSchema=z34.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z34.array(entryWhereScalarSchema).optional(),$nin:z34.array(entryWhereScalarSchema).optional(),$contains:z34.string().optional(),$startsWith:z34.string().optional(),$null:z34.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z34.record(z34.string(),z34.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z34.record(z34.string(),z34.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z34.object({data:z34.record(z34.string(),z34.unknown()),locale:z34.string().min(1).optional(),documentId:z34.uuid().optional()}),entryIdsSchema=z34.array(z34.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z34.object({sql:z34.string().min(1)}),BulkCreateEntriesRequestSchema=z34.object({entries:z34.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z34.union([z34.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z34.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z34.object({updates:z34.array(z34.object({id:z34.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z34.union([z34.object({ids:entryIdsSchema,locale:z34.string().min(1).optional()}),z34.object({where:EntryWhereSchema,locale:z34.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z34.object({data:z34.array(z34.record(z34.string(),z34.unknown())),meta:z34.object({rowCount:z34.number().int().nonnegative(),truncated:z34.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z34.object({data:z34.array(EntryDTOSchema),meta:z34.object({created:z34.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z34.object({data:z34.array(EntryDTOSchema),meta:z34.object({updated:z34.number().int().nonnegative(),missing:z34.array(z34.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z34.object({data:z34.array(EntryDTOSchema),meta:z34.object({deleted:z34.number().int().nonnegative(),missing:z34.array(z34.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z35}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z35.object({index:z35.number().int().nonnegative(),contentType:z35.string(),field:z35.string(),value:z35.string(),against:z35.enum(["stored","batch"]),ownerDocumentId:z35.uuid().optional(),ownerIndex:z35.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z35.object({code:z35.literal("unique_conflict"),message:z35.string(),conflicts:z35.array(UniqueConflictSchema),truncated:z35.boolean().optional()})}});import{z as z36}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=z36.object({kind:z36.literal("unique_conflict"),contentType:z36.string(),field:z36.string(),value:z36.string(),documentCount:z36.number().int().positive(),documentIds:z36.array(z36.uuid()),documentIdsTruncated:z36.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z36.object({code:z36.literal("schema_transition_rejected"),message:z36.string(),issues:z36.array(SchemaTransitionIssueSchema),truncated:z36.boolean().optional()})}});import{z as z37}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=z37.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z37.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z37.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z37.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z37.object({field:CmsFieldNameSchema,direction:z37.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z37.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z37.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z37.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z37.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z37.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z38}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=z38.object({id:z38.string(),name:z38.string()}),AssetDTOSchema=z38.object({id:z38.string(),name:z38.string(),type:AssetTypeSchema,originalFileName:z38.string().nullable(),parentId:z38.string().nullable(),mimeType:z38.string().nullable(),fileSize:z38.number().nullable(),url:z38.string().nullable(),storageKey:z38.string().nullable(),createdAt:z38.string(),updatedAt:z38.string(),altText:z38.string().nullable().optional(),caption:z38.string().nullable().optional(),aiCaption:z38.string().nullable().optional(),aiAltText:z38.string().nullable().optional(),aiTags:z38.array(z38.string()).nullable().optional(),aiPrimaryColor:z38.string().nullable().optional(),aiProcessingStatus:z38.string().nullable().optional(),width:z38.number().nullable().optional(),height:z38.number().nullable().optional(),path:z38.array(AssetPathItemSchema).optional(),hasChildren:z38.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z38.lazy(()=>z38.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z38.array(AssetDTOSchema))}});import{z as z39}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z39.object({key:z39.string(),value:z39.string().optional(),defaultValue:z39.string(),locale:z39.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z40}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=z40.object({id:z40.string(),name:z40.string(),type:z40.enum(["file","folder"]),path:z40.string(),children:z40.lazy(()=>z40.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z40.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z40.object({path:z40.string(),exists:z40.boolean(),type:z40.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z41}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=z41.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z41.object({items:z41.array(ProjectMessagePublicDTOSchema),nextCursor:z41.string().nullable()}),ChatLiveTurnDTOSchema=z41.object({invocationId:z41.string(),step:z41.enum(["preparing","working","merging"]),startedAt:z41.string()}),ChatLiveTurnStateDTOSchema=z41.object({threadId:z41.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z41.object({id:z41.string(),role:z41.enum(["user","assistant"]),parts:z41.array(z41.unknown()),metadata:z41.record(z41.string(),z41.unknown()).nullable(),createdAt:z41.date().transform(value=>value.toISOString()),providerMessageId:z41.string().nullable().optional(),invocationId:z41.string().nullable().optional(),invocationStatus:z41.string().nullable().optional(),invocationTerminalReason:z41.string().nullable().optional()}),ChatAttentionDTOSchema=z41.object({type:z41.literal("merge_conflict"),merge:z41.object({mergeId:z41.string().uuid(),projectId:z41.string(),fromEnv:z41.string(),toEnv:z41.string()}),publishAfterMerge:z41.boolean()}),ChatThreadMessagesPageDTOSchema=z41.object({threadId:z41.string().nullable(),title:z41.string().nullable(),messages:z41.array(ChatThreadMessageDTOSchema),nextCursor:z41.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z41.object({kind:z41.literal("replay"),threadId:z41.string(),userMessageId:z41.string()}),ChatQueuedOutcomeDTOSchema=z41.object({kind:z41.literal("queued"),threadId:z41.string(),userMessageId:z41.string(),blockingRootId:z41.string()}),ChatBusyOutcomeDTOSchema=z41.object({kind:z41.literal("busy"),threadId:z41.string(),userMessageId:z41.string(),blockingRootId:z41.string().optional()}),ChatRefusedOutcomeDTOSchema=z41.object({kind:z41.literal("refused"),threadId:z41.string(),userMessageId:z41.string(),refusedInvocationId:z41.string(),terminalReason:z41.string()}),ChatNonStreamingOutcomeDTOSchema=z41.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z41.object({success:z41.boolean(),deletedCount:z41.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z41.object({code:z41.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z41.string()})}});import{z as z42}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=z42.object({url:z42.string().url(),key:z42.string(),size:z42.number(),contentType:z42.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z43}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=z43.object({canAccess:z43.boolean(),permissions:z43.record(z43.string(),z43.boolean()),role:z43.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z44}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:z44.string().trim().default(""),sort:z44.enum(["recent","name","relevance"]).default("recent"),category:z44.string().optional(),visibility:z44.enum(["public","private"]).optional()})}});import{z as z45}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=z45.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z45.enum(["fimo","external"]),PaymentStatusSchema=z45.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z45.object({id:z45.string().uuid(),domain:z45.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z45.boolean(),price:z45.number().int().nullable(),renewalPrice:z45.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z45.string().nullable(),failureReason:z45.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z45.object({domain:z45.string(),available:z45.boolean(),premium:z45.boolean(),price:z45.number().nullable(),renewalPrice:z45.number().nullable(),purchaseType:z45.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z45.object({domain:z45.string(),price:z45.number().nullable(),renewalPrice:z45.number().nullable(),premium:z45.boolean(),allowedYears:z45.array(z45.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z45.object({firstName:z45.string().max(100),lastName:z45.string().max(100),companyName:z45.string().max(100).optional(),address1:z45.string().max(255),address2:z45.string().max(255).optional(),city:z45.string().max(100),state:z45.string().max(100),zip:z45.string().max(20),country:z45.string().max(2),phone:z45.string().max(30),email:z45.union([z45.string().email().max(255),z45.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z45.object({firstName:z45.string().min(1).max(100),lastName:z45.string().min(1).max(100),companyName:z45.string().max(100).optional(),address1:z45.string().min(1).max(255),address2:z45.string().max(255).optional(),city:z45.string().min(1).max(100),state:z45.string().min(1).max(100),zip:z45.string().min(1).max(20),country:z45.string().min(1).max(2),phone:z45.string().min(1).max(30),email:z45.string().email().max(255)}),SearchDomainsRequestSchema=z45.object({keyword:z45.string().min(1).max(100),tldFilter:z45.array(z45.string()).optional()}),CheckAvailabilityRequestSchema=z45.object({domains:z45.array(z45.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=z45.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z45.object({domain:DomainNameSchema,years:z45.number().int().min(1).max(10).optional().default(3),autoRenew:z45.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z45.object({autoRenew:z45.boolean().optional()}),RenewDomainRequestSchema=z45.object({years:z45.number().int().min(1).max(10).optional().default(1),autoRenew:z45.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z45.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z45.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z45.object({verified:z45.boolean(),email:z45.string().nullable(),verifyBy:z45.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z46}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=z46.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=z46.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=z46.object({txtName:z46.string().nullable().optional(),txtValue:z46.string().nullable().optional(),httpUrl:z46.string().nullable().optional(),httpBody:z46.string().nullable().optional(),cname:z46.string().nullable().optional(),cnameTarget:z46.string().nullable().optional()}),SSLValidationErrorSchema=z46.object({message:z46.string()}),OwnershipVerificationSchema=z46.object({type:z46.string(),name:z46.string(),value:z46.string()}),ProjectDomainSSLDTOSchema=z46.object({status:z46.string(),method:z46.string().nullable(),type:z46.string().nullable(),validationRecords:z46.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z46.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z46.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z46.enum(["subdomain","apex"]),RedirectConfigSchema=z46.object({type:z46.literal("apex_to_www"),linkedDomainId:z46.string()}).nullable().optional(),ProjectDomainDTOSchema=z46.object({id:z46.string(),hostname:z46.string(),status:z46.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z46.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z46.string(),scdCnameTarget:z46.string().optional(),apexTargets:z46.array(z46.string()),dnsAutoConfigured:z46.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z46.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z46.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z46.object({hostname:z46.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:z46.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z46.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z46.object({available:z46.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z46.object({success:z46.boolean(),hostname:z46.string()}))}});import{z as z47}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=z47.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z47.object({available:z47.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z47.object({slug:z47.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z47.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z47.object({subdomain:z47.string(),subdomainUpdatedAt:z47.coerce.date()})),SubdomainSuggestionsQuerySchema=z47.object({base:z47.string().max(100).optional(),max:z47.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z47.object({suggestions:z47.array(z47.string())}))}});import{z as z48}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=z48.object({translated:z48.number().int().nonnegative(),total:z48.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z48.object({locale:z48.string(),isDefault:z48.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z48.object({defaultLocale:z48.string(),routing:z48.object({strategy:z48.literal("path-prefix"),prefixDefaultLocale:z48.boolean()}),locales:z48.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z48.object({locale:z48.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z48.object({locale:z48.string().min(1).max(40)}),ProjectLocaleMutationSchema=z48.object({locale:z48.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z48.object({locale:z48.string(),entriesDeleted:z48.number().int().nonnegative(),labelsDeleted:z48.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z49}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=z49.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z49.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=z49.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z49.number(),credits:z49.number().optional(),billingMode:z49.enum(["fimo-credits","provider-account"]).optional(),confidence:z49.enum(["exact","estimated","metered"]),basis:z49.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z50}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=z50.object({options:z50.record(z50.string(),z50.unknown()),name:z50.string().optional(),parentId:z50.string().nullable().optional(),altText:z50.string().optional(),caption:z50.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z50.string().min(1).optional(),model:z50.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=z50.object({jobId:z50.string(),status:z50.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z50.string().nullable().optional(),credits:z50.number().optional(),costUsd:z50.number().optional(),billingMode:z50.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z50.object({error:z50.string(),code:z50.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:z50.array(GenerationTaskIdSchema).optional(),availableModels:z50.array(z50.string()).optional(),issues:z50.array(z50.unknown()).optional()})}});import{z as z51}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=z51.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z51.object({name:z51.string(),key:z51.string(),description:z51.string(),type:FlagTypeSchema,required:z51.boolean(),defaultValue:z51.unknown().optional(),enumValues:z51.array(z51.string()).optional(),isArray:z51.boolean()}),AssetModelPriceSchema=z51.object({unitPrice:z51.number(),unit:z51.string(),confidence:z51.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z51.object({id:z51.string(),shortName:z51.string(),provider:z51.string(),source:z51.string(),modality:z51.enum(["image","video","audio"]),tags:z51.array(z51.string()),displayName:z51.string(),description:z51.string(),flags:z51.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z51.object({model:z51.string(),costUsd:z51.number(),credits:z51.number(),billingMode:z51.enum(["fimo-credits","provider-account"]),confidence:z51.enum(["exact","estimated","metered"]),basis:z51.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z52}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=z52.object({tourId:z52.string(),version:z52.string(),status:z52.string(),completedAt:z52.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z52.array(UserTourDTOSchema))}});import{z as z53}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=z53.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z53.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z53.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z53.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z53.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z53.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z53.enum(["user","agent","system"]),SupportReportTagSchema=z53.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z53.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z53.object({organization:z53.object({id:z53.string().trim().min(1).max(255),name:z53.string().trim().max(240).optional()}),project:z53.object({id:z53.uuid(),name:z53.string().trim().max(240).optional(),createdAt:z53.coerce.date().optional()}).optional(),environment:z53.string().trim().max(255).optional(),clientVersion:z53.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z53.object({message:z53.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z53.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z53.string().trim().max(200).optional(),limit:z53.coerce.number().int().min(1).max(100).default(50),offset:z53.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z53.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z53.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z53.uuid().nullable().optional(),note:z53.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=z53.object({message:z53.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z53.object({kind:SupportReportLinkKindSchema,label:z53.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z53.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z53.object({kind:SupportReportActorKindSchema,id:z53.string().nullable(),name:z53.string().nullable()}),SupportReportLinkDTOSchema=z53.object({id:z53.uuid(),kind:SupportReportLinkKindSchema,label:z53.string(),url:SupportReportHttpUrlSchema,externalId:z53.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z53.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z53.object({id:z53.uuid(),kind:SupportReportEventKindSchema,body:z53.string().nullable(),metadata:z53.record(z53.string(),z53.unknown()),actor:SupportReportActorDTOSchema,createdAt:z53.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z53.object({id:z53.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z53.array(z53.string()),source:SupportReportSourceSchema,message:z53.string(),reporter:z53.object({id:z53.string().nullable(),name:z53.string().nullable(),email:z53.string().nullable()}),organization:z53.object({id:z53.string().nullable(),name:z53.string()}),project:z53.object({id:z53.uuid().nullable(),name:z53.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z53.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z53.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z53.string().nullable(),deliveredAt:z53.coerce.date().nullable()}).nullable(),duplicateOfReportId:z53.uuid().nullable(),resolvedAt:z53.coerce.date().nullable(),createdAt:z53.coerce.date(),updatedAt:z53.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z53.string().nullable(),clientVersion:z53.string().nullable(),links:z53.array(SupportReportLinkDTOSchema),events:z53.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z53.object({reports:z53.array(SupportReportSummaryDTOSchema),total:z53.number().int().nonnegative(),statusCounts:z53.object({new:z53.number().int().nonnegative(),in_progress:z53.number().int().nonnegative(),waiting:z53.number().int().nonnegative(),resolved:z53.number().int().nonnegative(),duplicate:z53.number().int().nonnegative(),irrelevant:z53.number().int().nonnegative(),ignored:z53.number().int().nonnegative()}),limit:z53.number().int().positive(),offset:z53.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z53.object({id:z53.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z53.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z54}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=z54.iso.datetime({offset:!0}).pipe(z54.coerce.date()),OpsRecentChatInputSchema=z54.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z54.string().trim().min(1).max(255).optional(),limit:z54.coerce.number().int().min(1).max(200).default(100),cursor:z54.string().trim().min(1).max(2e3).optional(),slim:z54.boolean().default(!0),reason:z54.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=z54.object({id:z54.string(),threadId:z54.string(),providerMessageId:z54.string().nullable(),invocationId:z54.string().nullable(),env:z54.string().nullable(),role:z54.string(),parts:z54.array(z54.record(z54.string(),z54.unknown())),metadata:z54.object({status:z54.string().optional(),traceUrl:z54.string().optional(),externalFileChanges:z54.array(z54.unknown()).optional()}),stats:z54.object({toolCount:z54.number().int().nonnegative(),failedToolCount:z54.number().int().nonnegative()}),createdAt:z54.iso.datetime({offset:!0}),project:z54.object({id:z54.string(),name:z54.string(),displayName:z54.string().nullable(),organizationId:z54.string().nullable()})}),OpsRecentChatResponseSchema=z54.object({target:z54.object({backendProfile:OpsBackendProfileSchema,projectEnv:z54.string().nullable()}),window:z54.object({from:z54.iso.datetime({offset:!0}),to:z54.iso.datetime({offset:!0})}),messages:z54.object({items:z54.array(OpsRecentChatMessageSchema),nextCursor:z54.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z55}from"zod";function createAgentRunWebhookEventDataSchema(status){return z55.object({run:z55.object({id:z55.string(),agentName:z55.string(),trigger:z55.string(),status:z55.literal(status),startedAt:z55.string().nullable(),finishedAt:z55.string().nullable(),reason:z55.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=z55.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z55.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z55.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z55.enum(["main","all"]),WebhookEntryBatchWindowSecondsSchema=z55.union([z55.literal(0),z55.literal(5),z55.literal(30),z55.literal(60)]),EntryChangedWebhookEventDataSchema=z55.object({reason:WebhookEntryChangeReasonSchema,operationId:z55.string().optional(),batch:z55.object({index:z55.number().int().positive(),total:z55.number().int().positive()}).optional(),changes:z55.array(z55.object({action:WebhookEntryChangeActionSchema,contentType:z55.string(),id:z55.string(),documentId:z55.string(),locale:z55.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z55.object({form:z55.object({id:z55.string(),label:z55.string()}),submission:z55.object({id:z55.string(),data:z55.record(z55.string(),z55.unknown()),submittedAt:z55.string()})}),PublishStartedWebhookEventDataSchema=z55.object({publication:z55.object({status:z55.literal("publishing"),startedAt:z55.string()})}),PublishSucceededWebhookEventDataSchema=z55.object({publication:z55.object({status:z55.literal("published"),url:z55.string(),publishedAt:z55.string(),firstPublish:z55.boolean()})}),PublishFailedWebhookEventDataSchema=z55.object({publication:z55.object({status:z55.literal("failed"),reason:z55.string()})}),PublishUnpublishedWebhookEventDataSchema=z55.object({publication:z55.object({previousUrl:z55.string(),unpublishedAt:z55.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z55.object({review:z55.object({id:z55.string(),runId:z55.string(),agentName:z55.string(),classification:z55.string(),summary:z55.string(),reasons:z55.array(z55.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z55.object({review:z55.object({id:z55.string(),runId:z55.string(),agentName:z55.string(),resolution:z55.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z55.object({report:z55.object({weekStart:z55.string(),weekEnd:z55.string(),pageviews:z55.number(),visitors:z55.number(),previousPageviews:z55.number(),previousVisitors:z55.number()})}),MediaAssetWebhookEventDataSchema=z55.object({id:z55.string().nullable(),name:z55.string().nullable(),type:z55.string(),mimeType:z55.string().nullable(),fileSize:z55.number().nullable()}),MediaUploadedWebhookEventDataSchema=z55.object({asset:MediaAssetWebhookEventDataSchema,operation:z55.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z55.object({asset:MediaAssetWebhookEventDataSchema,operation:z55.enum(["updated","moved","analysis"]),analysis:z55.object({category:z55.string(),status:z55.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z55.object({asset:MediaAssetWebhookEventDataSchema,operation:z55.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z55.object({asset:MediaAssetWebhookEventDataSchema,operation:z55.literal("generated"),generation:z55.object({model:z55.string(),mode:z55.string()})}),MediaProcessingFailedWebhookEventDataSchema=z55.object({asset:MediaAssetWebhookEventDataSchema,operation:z55.enum(["analysis","generation"]),failure:z55.object({code:z55.string()})}),DomainCreatedWebhookEventDataSchema=z55.object({domain:z55.object({id:z55.string(),hostname:z55.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z55.object({domain:z55.object({id:z55.string(),hostname:z55.string()})}),LabelChangedWebhookEventDataSchema=z55.object({changes:z55.array(z55.object({action:z55.enum(["created","updated","deleted"]),key:z55.string(),locale:z55.string(),value:z55.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z55.object({locale:z55.object({code:z55.string(),isDefault:z55.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z55.object({locale:z55.object({code:z55.string(),previousCode:z55.string()})}),LocaleDeletedWebhookEventDataSchema=z55.object({locale:z55.object({code:z55.string(),entriesDeleted:z55.number().int().nonnegative(),labelsDeleted:z55.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z55.object({environment:z55.object({name:EnvSchema,parent:EnvSchema})}),EnvironmentDeletedWebhookEventDataSchema=z55.object({environment:z55.object({name:EnvSchema})}),EnvironmentMergedWebhookEventDataSchema=z55.object({merge:z55.object({id:z55.string(),from:EnvSchema,to:EnvSchema,applied:z55.array(z55.object({surface:SurfaceNameSchema,count:z55.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z55.object({environment:z55.object({name:EnvSchema}),version:z55.object({versionId:z55.uuid(),name:z55.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=z55.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z55.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z55.discriminatedUnion("source",[z55.object({source:z55.literal("literal"),value:z55.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z55.object({source:z55.literal("secret"),key:z55.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z55.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z55.object({name:z55.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z55.object({name:z55.string(),source:z55.enum(["literal","secret"]),secretKey:z55.string().nullable(),secretPrefix:z55.string().nullable(),configured:z55.literal(!0)}),WebhookFilterSchema=z55.object({environment:WebhookEnvironmentScopeSchema.optional(),formId:z55.string().min(1).max(255).optional(),agentName:z55.string().min(1).max(120).optional(),mediaType:z55.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z55.string().min(1).max(255).optional(),locale:z55.string().min(1).max(120).optional()}),JsonValueSchema=z55.lazy(()=>z55.union([z55.string(),z55.number(),z55.boolean(),z55.null(),z55.array(JsonValueSchema),z55.record(z55.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z55.object({name:z55.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z55.url(),enabled:z55.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z55.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z55.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z55.object({name:z55.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z55.url().optional(),enabled:z55.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z55.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z55.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z55.object({eventType:WebhookEventTypeSchema.optional(),data:z55.record(z55.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z55.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z55.uuid(),name:z55.string(),eventType:WebhookEventTypeSchema,enabled:z55.boolean(),destination:z55.object({host:z55.string(),maskedUrl:z55.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z55.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z55.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z55.coerce.date().nullable(),deliveryStats24h:z55.object({succeeded:z55.number().int().nonnegative(),failed:z55.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z55.uuid(),projectId:z55.uuid(),env:EnvSchema,eventId:z55.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z55.number().int().positive(),test:z55.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z55.number().int().nonnegative(),responseStatus:z55.number().int().nullable(),lastErrorCode:z55.string().nullable(),lastErrorMessage:z55.string().nullable(),payloadAvailable:z55.boolean(),destination:z55.object({host:z55.string(),maskedUrl:z55.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z55.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z55.string().nullable(),qstashMessageId:z55.string().nullable(),deliveredAt:z55.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z55.object({items:z55.array(WebhookDeliveryDTOSchema),pagination:z55.object({page:z55.number().int().positive(),limit:z55.number().int().positive(),total:z55.number().int().nonnegative(),totalPages:z55.number().int().positive(),hasMore:z55.boolean()}),stats:z55.object({total:z55.number().int().nonnegative(),succeeded:z55.number().int().nonnegative(),failed:z55.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z55.object({id:z55.uuid(),deliveryId:z55.uuid(),attempt:z55.number().int().positive(),status:z55.enum(["delivering","succeeded","failed"]),responseStatus:z55.number().int().nullable(),durationMs:z55.number().int().nonnegative(),responseExcerpt:z55.string().nullable(),errorCode:z55.string().nullable(),errorMessage:z55.string().nullable(),createdAt:z55.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z55.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z55.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z56}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=z56.object({key:z56.enum(previewFeatureKeys),enabled:z56.boolean(),dismissed:z56.boolean().default(!1),interacted:z56.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema),PreviewFeatureResponseSchema=createResponseSchema(PreviewFeatureDTOSchema),PreviewFeatureListResponseSchema=createResponseSchema(z56.array(PreviewFeatureDTOSchema))}});import{z as z57}from"zod";var SubscriptionStatusSchema,CreditBalanceBreakdownDTOSchema,CreditBalanceBreakdownDTO,SubscriptionPlanDTOSchema,SubscriptionPlanDTO,SubscriptionPaymentMethodDTOSchema,SubscriptionPaymentMethodDTO,SubscriptionPricingDTOSchema,SubscriptionPricingDTO,SubscriptionDetailsDTOSchema,SubscriptionDetailsDTO,CreditAlertDTOSchema,CreditAlertDTO,PlanAllocationDTOSchema,PlanAllocationDTO,LatestCancellationDTOSchema,LatestCancellationDTO,OrganizationSubscriptionDTOSchema,OrganizationSubscriptionDTO,BaseCreditTopupRequestSchema,FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema,CreditTopupRequestDTOSchema,CreditTopupRequestDTO,CreditTopupResponseDTOSchema,CreditTopupResponseDTO,init_subscription_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/subscription.dto.js"(){"use strict";init_common();init_create_dto();init_billing_dto();SubscriptionStatusSchema=z57.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z57.object({total:z57.number(),base:z57.number(),purchases:z57.number(),awards:z57.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z57.object({id:z57.string(),name:z57.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z57.object({type:z57.string(),brand:z57.string().nullable(),last4:z57.string().nullable(),expirationDate:z57.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z57.object({currency:z57.string(),nextPaymentAmount:z57.number().nullable(),nextPaymentAt:z57.string().nullable(),billingInterval:z57.string().nullable(),totalAmount:z57.number().nullable(),discountAmount:z57.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z57.object({id:z57.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z57.string().nullable(),currentPeriodEndsAt:z57.string().nullable(),renewsAt:z57.string().nullable(),cancelAt:z57.string().nullable(),renewAutomatically:z57.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z57.object({type:z57.enum(["low_balance","critical_balance","approaching_limit"]),message:z57.string(),estimatedPromptsRemaining:z57.number().nullable(),avgCostPerPrompt:z57.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z57.object({monthlyCredits:z57.number().nullable(),usedThisPeriod:z57.number(),remainingThisPeriod:z57.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z57.object({organizationId:z57.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z57.string().nullable(),tenureDays:z57.number().int().nonnegative(),capturedAt:z57.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z57.object({hasSubscription:z57.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z57.number().nullable(),alerts:z57.array(CreditAlertDTOSchema),portalUrl:z57.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z57.object({creditCount:z57.number().int().positive(),expiresAt:z57.string().datetime().nullable().optional(),message:z57.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z57.literal("free"),amountCents:z57.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z57.literal("purchase"),amountCents:z57.number().int().positive()}),CreditTopupRequestDTOSchema=z57.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z57.object({success:z57.boolean(),transactionId:z57.string().nullable(),newBalance:z57.number(),creditCount:z57.number(),type:z57.enum(["free","purchase"]),invoiceId:z57.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z58}from"zod";var UsageSummaryDTOSchema,UsageSummaryDTO,UsageByProjectDTOSchema,UsageByProjectDTO,UsageByUserDTOSchema,UsageByUserDTO,UsageTimelineItemDTOSchema,UsageTimelineItemDTO,UsageByUserForProjectDTOSchema,UsageByUserForProjectDTO,ProjectUsageDetailDTOSchema,ProjectUsageDetailDTO,OrganizationUsageDTOSchema,OrganizationUsageDTO,init_usage_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage.dto.js"(){"use strict";init_create_dto();UsageSummaryDTOSchema=z58.object({totalCredits:z58.number(),totalCostUsd:z58.number(),totalMessages:z58.number(),avgCostPerMessage:z58.number(),periodStart:z58.string().nullable(),periodEnd:z58.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z58.object({projectId:z58.string(),projectName:z58.string(),projectDisplayName:z58.string().nullable(),credits:z58.number(),costUsd:z58.number(),messages:z58.number(),percentage:z58.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z58.object({userId:z58.string(),userName:z58.string().nullable(),userEmail:z58.string().email().nullable(),credits:z58.number(),costUsd:z58.number(),messages:z58.number(),percentage:z58.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z58.object({date:z58.string(),credits:z58.number(),costUsd:z58.number(),messages:z58.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z58.object({userId:z58.string(),userName:z58.string().nullable(),userEmail:z58.string().email().nullable(),credits:z58.number(),costUsd:z58.number(),messages:z58.number(),percentage:z58.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z58.object({projectId:z58.string(),projectName:z58.string(),projectDisplayName:z58.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z58.array(UsageByUserForProjectDTOSchema),timeline:z58.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z58.object({summary:UsageSummaryDTOSchema,byProject:z58.array(UsageByProjectDTOSchema),byUser:z58.array(UsageByUserDTOSchema),timeline:z58.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z59}from"zod";var TimeRangePresetSchema,SortOrderSchema,UsageAnalyticsQuerySchema,UsageOverviewSummaryDTOSchema,UsageOverviewSummaryDTO,UsageTimelinePointDTOSchema,UsageTimelinePointDTO,OrganizationUsageRowDTOSchema,OrganizationUsageRowDTO,UserUsageRowDTOSchema,UserUsageRowDTO,ProjectUsageRowDTOSchema,ProjectUsageRowDTO,UsageDistributionItemDTOSchema,UsageDistributionItemDTO,UsageHeatmapPointDTOSchema,UsageHeatmapPointDTO,UsageOverviewResponseDTOSchema,UsageOverviewResponseDTO,UsagePaginationDTOSchema,UsagePaginationDTO,UsageByOrganizationResponseDTOSchema,UsageByOrganizationResponseDTO,ExtendedUserUsageRowDTOSchema,ExtendedUserUsageRowDTO,UsageByUserResponseDTOSchema,UsageByUserResponseDTO,ExtendedProjectUsageRowDTOSchema,ExtendedProjectUsageRowDTO,UsageByProjectResponseDTOSchema,UsageByProjectResponseDTO,ExportFormatSchema,UsageExportQuerySchema,PeekUsageMetricsDTOSchema,PeekUsageMetricsDTO,OrganizationPeekDTOSchema,OrganizationPeekDTO,UserPeekDTOSchema,UserPeekDTO,ProjectPeekDTOSchema,ProjectPeekDTO,init_usage_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage-analytics.dto.js"(){"use strict";init_create_dto();TimeRangePresetSchema=z59.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z59.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z59.object({startDate:z59.string().optional(),endDate:z59.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z59.coerce.number().int().positive().default(1),limit:z59.coerce.number().int().positive().max(100).default(20),sortBy:z59.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z59.string().optional()}),UsageOverviewSummaryDTOSchema=z59.object({totalCredits:z59.number(),totalCostUsd:z59.number(),totalMessages:z59.number(),avgCostPerMessage:z59.number(),avgCreditsPerMessage:z59.number(),periodStart:z59.string(),periodEnd:z59.string(),creditsChange:z59.number().nullable(),costChange:z59.number().nullable(),messagesChange:z59.number().nullable()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z59.object({date:z59.string(),credits:z59.number(),costUsd:z59.number(),messages:z59.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z59.object({organizationId:z59.string(),organizationName:z59.string(),credits:z59.number(),costUsd:z59.number(),messages:z59.number(),percentage:z59.number(),userCount:z59.number(),projectCount:z59.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z59.object({userId:z59.string(),userName:z59.string().nullable(),userEmail:z59.string().nullable(),userImage:z59.string().nullable(),organizationId:z59.string().nullable(),organizationName:z59.string().nullable(),credits:z59.number(),costUsd:z59.number(),messages:z59.number(),percentage:z59.number(),projectCount:z59.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z59.object({projectId:z59.string(),projectName:z59.string(),projectDisplayName:z59.string().nullable(),organizationId:z59.string(),organizationName:z59.string(),credits:z59.number(),costUsd:z59.number(),messages:z59.number(),percentage:z59.number(),userCount:z59.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z59.object({id:z59.string(),name:z59.string(),value:z59.number(),percentage:z59.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z59.object({day:z59.number(),hour:z59.number(),value:z59.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z59.object({summary:UsageOverviewSummaryDTOSchema,timeline:z59.array(UsageTimelinePointDTOSchema),topOrganizations:z59.array(OrganizationUsageRowDTOSchema),topUsers:z59.array(UserUsageRowDTOSchema),topProjects:z59.array(ProjectUsageRowDTOSchema),creditDistribution:z59.array(UsageDistributionItemDTOSchema),heatmap:z59.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z59.object({page:z59.number(),limit:z59.number(),totalItems:z59.number(),totalPages:z59.number(),hasMore:z59.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z59.object({organizations:z59.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z59.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z59.object({users:z59.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z59.string(),ownerName:z59.string().nullable(),ownerEmail:z59.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z59.object({projects:z59.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z59.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z59.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z59.object({credits:z59.number(),costUsd:z59.number(),messages:z59.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z59.object({id:z59.string(),name:z59.string(),createdAt:z59.string(),memberCount:z59.number(),projectCount:z59.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z59.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z59.object({id:z59.string(),name:z59.string().nullable(),email:z59.string(),image:z59.string().nullable(),createdAt:z59.string(),organizationCount:z59.number(),projectCount:z59.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z59.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z59.object({id:z59.string(),name:z59.string(),displayName:z59.string().nullable(),createdAt:z59.string(),organizationId:z59.string(),organizationName:z59.string(),ownerId:z59.string(),ownerName:z59.string().nullable(),ownerEmail:z59.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z59.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z60}from"zod";var SandboxProcessStatusSchema,PresetSandboxCommandSchema,ExecuteSandboxCommandRequestDTOSchema,ExecuteSandboxCommandRequestDTO,SandboxProcessInfoDTOSchema,SandboxProcessInfoDTO,SandboxProcessInfoResponseSchema,SandboxProcessListDTOSchema,SandboxProcessListDTO,SandboxProcessListResponseSchema,ExecuteSandboxCommandResponseDTOSchema,ExecuteSandboxCommandResponseDTO,PresetCommandResponseDTOSchema,PresetCommandResponseDTO,PresetCommandResponseSchema,init_sandbox_command_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/sandbox-command.dto.js"(){"use strict";init_env();init_create_dto();init_response();SandboxProcessStatusSchema=z60.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z60.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z60.object({command:z60.string().min(1).max(1e4),cwd:z60.string().optional(),projectEnv:EnvSchema.optional(),env:z60.record(z60.string(),z60.string()).optional(),name:z60.string().optional(),waitForCompletion:z60.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z60.object({identifier:z60.string(),status:SandboxProcessStatusSchema,command:z60.string().optional(),startedAt:z60.string().optional(),exitCode:z60.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z60.object({processes:z60.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z60.object({processId:z60.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z60.object({success:z60.boolean(),message:z60.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z61}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common();init_attachments();init_env();init_realtime();init_references();init_content_fields();init_audit_log();init_ops();init_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_audit_log_dto();init_env_status_dto();init_env_diff_summary_dto();init_project_analytics_dto();init_project_access_dto();init_project_invite_dto();init_publication_dto();init_sandbox_dto();init_organization_dto();init_billing_dto();init_payment_method_dto();init_user_dto();init_content_dto();init_unique_conflict_dto();init_schema_transition_rejected_dto();init_cms_display_defaults_dto();init_asset_dto();init_translation_dto();init_document_dto();init_chat_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_webhook_dto();init_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:path43,message}=issue;return`${Array.isArray(path43)&&path43.length>0?`${path43.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}var ApiRequestError,UnauthorizedError,PermissionDeniedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_ENV_HEADER,FimoApiClient,init_api=__esm({"src/cli/api.ts"(){init_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,path43,status,detail,code2,body){super(`API ${method} ${path43} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path43,this.status=status,this.detail=detail,this.code=code2,this.body=body}},UnauthorizedError=class extends Error{static{__name(this,"UnauthorizedError")}apiUrl;status;constructor(apiUrl,status,message){super(message??`Session for ${apiUrl} expired or invalid (HTTP ${status}).`),this.name="UnauthorizedError",this.apiUrl=apiUrl,this.status=status}},PermissionDeniedError=class extends Error{static{__name(this,"PermissionDeniedError")}apiUrl;required;constructor(apiUrl,required=[],message){let detail=required.length?` Missing permission: ${required.join(", ")}.`:"";super(message??`You don't have permission to do this on ${apiUrl}.${detail}`),this.name="PermissionDeniedError",this.apiUrl=apiUrl,this.required=required}};__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");CLI_VERSION_HEADER="X-Fimo-CLI-Version",CLI_LATEST_HEADER="X-Fimo-CLI-Latest",CLI_AUTO_UPGRADE_HEADER="X-Fimo-CLI-Auto-Upgrade",FIMO_ENV_HEADER="X-Fimo-Env";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");FimoApiClient=class _FimoApiClient{constructor(cfg=loadConfig()){this.cfg=cfg}static{__name(this,"FimoApiClient")}env;withEnv(env){let next2=new _FimoApiClient(this.cfg);return next2.env=env,next2}formatError(status,text3,body){if(!text3)return String(status);if(body&&typeof body=="object"&&!Array.isArray(body)){let parsed=body;if(typeof parsed.message=="string"&&parsed.message.length>0){let partial=formatPartialResult(parsed);return partial?`${parsed.message} ${partial}`:parsed.message}if(typeof parsed.error=="string"&&parsed.error.length>0)return parsed.error;if(parsed.error&&typeof parsed.error=="object"&&"message"in parsed.error&&typeof parsed.error.message=="string")return parsed.error.message;let zodIssues=formatZodIssues(parsed);if(zodIssues)return zodIssues}return text3}async parseError(response){let text3=await response.text(),body;try{body=text3?JSON.parse(text3):void 0}catch{return{detail:this.formatError(response.status,text3)}}let code2=body&&typeof body=="object"&&!Array.isArray(body)&&typeof body.code=="string"?body.code:void 0;return{detail:this.formatError(response.status,text3,body),code:code2,body}}resolveAuthToken(){return process.env.FIMO_API_TOKEN?.trim()||requireToken(this.cfg)}async request(path43,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}${path43}`,{...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",path43,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async fetchRaw(path43,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}${path43}`,{...init,headers})}async rawRequest(path43,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}${path43}`,{...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"} ${path43} 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 qs=opts.includeDeleted?"?includeDeleted=true":"";return(await this.request(`/api/management/projects/${projectId}/envs${qs}`)).data}async getEnv(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`)).data}async createEnv(projectId,input){return(await this.request(`/api/management/projects/${projectId}/envs`,{method:"POST",body:JSON.stringify(input)})).data}async syncEnv(projectId,env,input={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sync`,{method:"POST",body:JSON.stringify(input)})).data}async deleteEnv(projectId,env){await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`,{method:"DELETE"})}async getEnvDiff(projectId,env,opts={}){let params=new URLSearchParams;opts.against&¶ms.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&¶ms.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff${qs?`?${qs}`:""}`)).data}async getEnvStatus(projectId,env,opts={}){let params=new URLSearchParams;opts.against&¶ms.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&¶ms.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/status${qs?`?${qs}`:""}`)).data}async getCodeFileDiff(projectId,env,path43,opts={}){let qs=lazyFetchQs(opts.against,{path:path43});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),path43=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path43}?${qs}`:path43)).data}async getSchemaTypeDiff(projectId,env,typeName,opts={}){let qs=lazyFetchQs(opts.against),path43=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path43}?${qs}`:path43)).data}async getAssetDiff(projectId,env,assetId,opts={}){let qs=lazyFetchQs(opts.against),path43=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path43}?${qs}`:path43)).data}async getTranslationRowDiff(projectId,env,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path43=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path43}?${qs}`:path43)).data}async getFormSchemaDiff(projectId,env,formName,opts={}){let qs=lazyFetchQs(opts.against),path43=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path43}?${qs}`:path43)).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){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-remote`,{},{allow403:!0})).data}async getGitCredential(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-credential`,{},{allow403:!0})).data}async getPreviewUrl(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sandbox`)).data}async sandboxPull(projectId,onProgress,env,options={}){let query=options.noRestart?"?noRestart=true":"",response=await this.rawRequest(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sandbox/pull${query}`,{method:"POST",headers:{Accept:"text/event-stream"}});if(!response.body)throw new Error("Sandbox pull failed: empty response stream");let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",errorMessage3=null,completed=!1;try{for(;;){let{value,done}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});let separatorIndex=buffer.indexOf(`
|
|
42
|
+
`)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();helpOption&&args.find(arg=>helpOption.is(arg))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;return(match=arg.match(/^(--inspect(-brk)?)$/))!==null?debugOption=match[1]:(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(debugOption=match[1],/^\d+$/.test(match[3])?debugPort=match[3]:debugHost=match[3]):(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match[1],debugHost=match[3],debugPort=match[4]),debugOption&&debugPort!=="0"?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}__name(incrementNodeInspectorPort,"incrementNodeInspectorPort");function useColor(){if(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,ProjectVisibilitySchema,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"]),ProjectVisibilitySchema=z4.enum(["public","private"]),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_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image"},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image"},{mime:"image/webp",extensions:[".webp"],category:"image"},{mime:"image/avif",extensions:[".avif"],category:"image"},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:5242880},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:5242880},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:5242880}],ATTACHMENT_MIME_TYPES=ATTACHMENT_TYPES.map(t2=>t2.mime),ATTACHMENT_IMAGE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="image").map(t2=>t2.mime),ATTACHMENT_DOCUMENT_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="document").map(t2=>t2.mime),ATTACHMENT_ACCEPT_EXTENSIONS=ATTACHMENT_TYPES.flatMap(t2=>t2.extensions),ATTACHMENT_ACCEPT_STRING=[...ATTACHMENT_ACCEPT_EXTENSIONS,...ATTACHMENT_MIME_TYPES].join(","),ATTACHMENT_DROPZONE_ACCEPT=Object.fromEntries(ATTACHMENT_TYPES.map(t2=>[t2.mime,t2.extensions]))}});import{z as 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}var ENV_ID_REGEX,MAX_ENV_LENGTH,EnvSchema,DEFAULT_ENV,PRODUCTION_ENV,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";ENV_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_ENV_LENGTH=255;__name(isValidEnv,"isValidEnv");__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")}});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,path43){let conditionPath=[...path43,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,path43)=>{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,path43));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path43,fieldName,variant.uid]);else walk(field.schema.fields,[...path43,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path43,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path43,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","cutover_step","agent_delegate","ops_access_change","ops_service_token_change","ops_project_search","ops_project_inspect","ops_project_chat_read","ops_recent_chat_read","ops_sentry_issue_change","ops_project_snapshot","ops_support_thread_read","ops_support_report_read","ops_support_report_change","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send","ops_project_operation"],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,OPS_PROJECT_OPERATIONS,OpsProjectOperationKindSchema,ExactVersionSchema,OpsProjectOperationPlanInputSchema,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:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","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: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:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","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)}),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")})]),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)})}});var FIMO_CONFIG_PATH,LEGACY_FIMO_CONFIG_PATHS,ALL_FIMO_CONFIG_PATHS,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]}});import{z as z11}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","google/gemini-3.1-pro-preview","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=z11.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z11.string(),displayName:z11.string().nullable(),subdomain:z11.string().nullable().optional(),subdomainUpdatedAt:z11.date().nullable().optional(),organizationId:z11.string().nullable(),createdBy:z11.string().nullable(),visibility:ProjectVisibilitySchema,previewEnabled:z11.boolean().default(!0),enabledChatModels:z11.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z11.string(),thumbnailUrl:z11.string().nullable(),publishedThumbnailUrl:z11.string().nullable(),category:z11.string().nullable(),appUrl:z11.string().nullable(),lastPublishedAt:z11.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z11.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z11.object({id:z11.uuid(),name:z11.string(),displayName:z11.string().nullable(),thumbnailUrl:z11.string().nullable(),visibility:ProjectVisibilitySchema,category:z11.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z11.object({id:z11.string(),name:z11.string(),avatar:z11.string().nullable(),color:z11.object({bg:z11.string(),text:z11.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z11.object({path:z11.string(),content:z11.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z11.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z11.object({id:z11.string(),messageId:z11.string(),versionId:z11.string().nullable(),role:ProjectChatMessageRole,parts:z11.array(z11.any()),createdAt:z11.coerce.date()}),MessageUserMetadataSchema=z11.object({id:z11.string(),name:z11.string().nullable().optional(),image:z11.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z11.number(),metadata:z11.object({user:MessageUserMetadataSchema,changeManifest:z11.array(z11.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z11.object({versionId:z11.uuid(),commitHash:z11.string(),name:z11.string(),description:z11.string().nullable(),kind:z11.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z11.object({versionCount:z11.number().int().nonnegative(),snapshotBytes:z11.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z11.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z11.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z11.object({content:z11.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z11.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z11.object({success:z11.boolean(),message:z11.string().optional(),warning:z11.string().optional(),durationMs:z11.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z11.object({isPublished:z11.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z11.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublicationMutationDTOSchema=z11.object({success:z11.boolean(),message:z11.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z11.boolean()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z12}from"zod";var ProjectEnvStatusSchema,ProjectEnvDTOSchema,ProjectEnvDTO,CreateProjectEnvRequestSchema,SyncProjectEnvRequestSchema,ProjectEnvResponseSchema,ProjectEnvsListResponseSchema,EnvSurfaceDiffSchema,EnvDiffResultSchema,EnvDiffResultDTO,init_project_env_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-env.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();ProjectEnvStatusSchema=z12.enum(["provisioning","active","deleted"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z12.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,previewUrl:z12.string().nullable(),parentEnv:EnvSchema.nullable(),createdBy:z12.string().nullable(),deletedAt:z12.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),CreateProjectEnvRequestSchema=z12.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z12.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z12.array(ProjectEnvDTOSchema)),EnvSurfaceDiffSchema=z12.object({surface:z12.enum(["code","schemas","content","translations","assets","forms"]),status:z12.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z12.number().int().nonnegative(),conflictCount:z12.number().int().nonnegative()}),EnvDiffResultSchema=z12.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z12.coerce.date(),surfaces:z12.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z13}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=z13.object({success:z13.literal(!0),downloadUrl:z13.string(),expiresAt:z13.string(),fileSize:z13.number(),duration:z13.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z13.object({success:z13.literal(!0),projectId:z13.string(),projectName:z13.string(),displayName:z13.string(),projectUrl:z13.string(),duration:z13.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z13.object({contentTypes:z13.number(),entries:z13.number(),assets:z13.number(),translations:z13.number(),forms:z13.number(),codeFiles:z13.number(),assetFiles:z13.number()}),ImportPreviewSurfaceDTOSchema=z13.object({name:z13.string(),included:z13.boolean(),count:z13.number().optional(),note:z13.string().optional()}),ImportPreviewDTOSchema=z13.object({projectName:z13.string(),displayName:z13.string().nullable(),visibility:z13.string().nullable(),category:z13.string().nullable(),exportedAt:z13.string(),version:z13.string(),envScope:z13.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z13.array(ImportPreviewSurfaceDTOSchema),fileSize:z13.number(),fileName:z13.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z13.object({success:z13.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z14}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=z14.enum(["manual","schedule","webhook"]),ManualTriggerSchema=z14.object({type:z14.literal("manual")}),ScheduleTriggerSchema=z14.object({type:z14.literal("schedule"),cron:z14.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:z14.string().optional()}),WebhookTriggerSchema=z14.object({type:z14.literal("webhook"),path:z14.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z14.discriminatedUnion("type",[ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema])}});import{z as z15}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=z15.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z15.object({token:z15.string().min(1),risk:CapabilityRiskTierSchema,description:z15.string()}),AgentSubAgentSummarySchema=z15.object({name:z15.string().min(1),grant:z15.enum(["inherit","explicit"]),effectiveCaps:z15.array(z15.string().min(1))}),AgentInstallSummaryDTOSchema=z15.object({agentName:z15.string().min(1),env:z15.string().min(1),declaredCapabilities:z15.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z15.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z15.array(CapabilitySummaryEntrySchema),criticalCapabilities:z15.array(CapabilitySummaryEntrySchema),subAgents:z15.array(AgentSubAgentSummarySchema),declaresDelegate:z15.boolean(),cycle:z15.array(z15.string()).nullable(),missingSubAgents:z15.array(z15.string()),warnings:z15.array(z15.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z16}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=z16.object({kind:TriggerKindSchema,summary:z16.string()}),AgentListItemTriggerStateSchema=z16.object({triggerIndex:z16.number().int().nonnegative(),triggerKind:TriggerKindSchema,enabled:z16.boolean(),wired:z16.boolean(),syncError:z16.string().nullable()}),AgentListItemDTOSchema=z16.object({name:z16.string().min(1),description:z16.string().nullable(),goalFirstLine:z16.string().nullable(),declaredCapabilities:z16.array(CapabilitySummaryEntrySchema),triggers:z16.array(AgentListItemTriggerSchema),triggerStates:z16.array(AgentListItemTriggerStateSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z16.array(AgentListItemDTOSchema))}});import{z as z17}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=z17.object({args:z17.unknown().optional(),requestId:z17.string().min(1).max(128).optional()}),DispatchSkippedSchema=z17.object({skipped:z17.enum(["no-manual-trigger","trigger-not-wired","run-in-progress","task-env-budget"])}),DispatchAcceptedSchema=z17.object({sessionId:z17.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z17.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z18}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=z18.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z18.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z18.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z18.object({verb:SurfaceDeltaVerbSchema,key:z18.string(),detail:z18.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z18.record(z18.string(),z18.unknown()).optional()}),PerSurfaceDeltaSchema=z18.object({surface:SurfaceNameSchema,status:z18.enum(["ok","timed_out","failed","unchanged"]),durationMs:z18.number().int().nonnegative().optional(),changedCount:z18.number().int().nonnegative(),conflictCount:z18.number().int().nonnegative(),items:z18.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z18.boolean().optional(),error:z18.string().optional()}),CrossSurfaceFindingSchema=z18.object({id:z18.string(),kind:z18.string(),description:z18.string(),severity:z18.enum(["warning","error"]),source:z18.object({surface:SurfaceNameSchema,key:z18.string()}),target:z18.object({surface:SurfaceNameSchema,key:z18.string()}),actions:z18.array(z18.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z18.object({env:EnvSchema,vs:EnvSchema,syncState:z18.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z18.coerce.date(),surfaces:z18.array(PerSurfaceDeltaSchema),agents:z18.array(z18.object({id:z18.string(),name:z18.string(),status:z18.enum(["active","paused","failed"]),lastRunAt:z18.coerce.date().nullable()})).optional(),crossSurface:z18.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z18.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z18.coerce.date(),surfaces:z18.array(PerSurfaceDeltaSchema),crossSurface:z18.array(CrossSurfaceFindingSchema).optional(),fingerprint:z18.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z18.object({path:z18.string(),state:z18.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z18.string(),additions:z18.number().int().nonnegative(),deletions:z18.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z18.object({oid:z18.string().optional(),content:z18.string().optional(),truncated:z18.boolean(),binary:z18.boolean()}),CodeConflictDetailSchema=z18.object({path:z18.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z18.string(),targetTipSha:z18.string(),mergeBaseSha:z18.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z18.object({id:z18.string(),slug:z18.string(),contentType:z18.string(),data:z18.record(z18.string(),z18.unknown()),updatedAt:z18.coerce.date()}),ContentRowDiffSchema=z18.object({collection:z18.string(),rowId:z18.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z18.object({name:z18.string(),label:z18.string(),isSingleton:z18.boolean(),fields:z18.record(z18.string(),z18.unknown())}),SchemaTypeDiffSchema=z18.object({typeName:z18.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z18.object({id:z18.string(),name:z18.string(),type:z18.enum(["file","folder"]),mimeType:z18.string().nullable(),storageKey:z18.string().nullable(),url:z18.string().nullable(),fileSize:z18.number().nullable(),width:z18.number().nullable(),height:z18.number().nullable(),altText:z18.string().nullable(),caption:z18.string().nullable(),createdAt:z18.coerce.date(),updatedAt:z18.coerce.date()}),AssetDiffSchema=z18.object({assetId:z18.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z18.object({locale:z18.string(),key:z18.string(),parent:z18.string().nullable(),child:z18.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z18.object({formName:z18.string(),label:z18.string().nullable(),schemaFingerprint:z18.string(),fields:z18.record(z18.string(),z18.unknown()),settings:z18.record(z18.string(),z18.unknown()).optional()}),FormSchemaDiffSchema=z18.object({formName:z18.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=z18.enum(CONFLICT_KINDS),ConflictSchema=z18.object({surface:SurfaceNameSchema,key:z18.string(),kind:ConflictKindSchema.optional(),description:z18.string(),parentValue:z18.unknown().optional(),childValue:z18.unknown().optional(),conflictingFields:z18.array(z18.string()).optional(),code:z18.object({path:z18.string(),unresolvable:z18.boolean().optional(),reason:z18.string().optional()}).optional()}),FieldPickSchema=z18.object({field:z18.string(),choice:z18.enum(["parent","child","pick","ai-pick"]),pickedValue:z18.unknown().optional(),aiSessionId:z18.string().optional()}),ConflictResolutionSchema=z18.object({surface:SurfaceNameSchema,key:z18.string(),choice:z18.enum(["parent","child","pick"]),pickedValue:z18.unknown().optional(),fieldPicks:z18.array(FieldPickSchema).optional()}),MergeResultSchema=z18.object({ok:z18.boolean(),mergeId:z18.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z18.array(z18.object({surface:SurfaceNameSchema,count:z18.number().int().nonnegative()})),conflicts:z18.array(ConflictSchema).optional(),summary:z18.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z18.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z18.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z18.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z18.boolean().optional()}),ResolvedStrategySchema=z18.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z18.boolean()}),MergeRequestSchema=z18.object({from:EnvSchema,allowDirectMerge:z18.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z18.object({mergeId:z18.string().uuid(),streamUrl:z18.string(),strategy:ResolvedStrategySchema,acceptedAt:z18.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z18.object({mergeId:z18.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z18.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z18.array(ConflictSchema),draftResolutions:z18.array(ConflictResolutionSchema),lastEditedBy:z18.string().nullable(),lastEditedAt:z18.coerce.date().nullable(),initiator:z18.object({userId:z18.string().nullable(),role:z18.string().nullable(),agentName:z18.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z18.object({resolutions:z18.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z18.object({mergeId:z18.string().uuid(),draftResolutions:z18.array(ConflictResolutionSchema),lastEditedAt:z18.coerce.date(),lastEditedBy:z18.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z18.object({mergeId:z18.string().uuid(),resolutions:z18.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z18.object({mergeId:z18.string().uuid()}),PublishReleaseRequestSchema=z18.object({version:z18.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z18.string().max(2e4).optional()}),PublishReleaseResultSchema=z18.object({releaseTag:z18.string(),sha:z18.string(),publishedAt:z18.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z19}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=z19.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z19.object({cpuMs:z19.number().nonnegative().default(0),netBytes:z19.number().nonnegative().default(0),walltimeMs:z19.number().nonnegative().default(0),llmTokensIn:z19.number().nonnegative().optional(),llmTokensOut:z19.number().nonnegative().optional(),stepCount:z19.number().int().nonnegative().optional(),toolCallCounts:z19.record(z19.string().min(1).max(120),z19.number().int().nonnegative()).optional()}),AgentSessionReviewPublicationSchema=z19.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z19.object({capturedAt:z19.coerce.date(),fingerprint:z19.string().min(1).max(256),counts:z19.object({code:z19.number().int().nonnegative(),content:z19.number().int().nonnegative(),schemas:z19.number().int().nonnegative(),labels:z19.number().int().nonnegative()}),publication:AgentSessionReviewPublicationSchema,mergeId:z19.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z19.object({diff:DiffReportSchema,code:z19.array(CodeFileDiffSchema.extend({raw:z19.string().max(24576)})).max(200),schemas:z19.array(SchemaTypeDiffSchema).max(200),content:z19.array(z19.object({key:z19.string().min(1).max(512),collection:z19.string().min(1).max(256),slug:z19.string().max(512).optional(),verb:z19.enum(["added","modified","deleted"]),fields:z19.array(z19.object({name:z19.string().min(1).max(256),before:z19.unknown().optional(),after:z19.unknown().optional()})).max(20)})).max(200),labels:z19.array(z19.object({key:z19.string().min(1).max(512),locale:z19.string().min(1).max(64).optional(),before:z19.unknown().nullable(),after:z19.unknown().nullable()})).max(200)}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),AgentSessionDTOSchema=z19.object({id:z19.uuid(),projectId:z19.uuid(),env:EnvSchema,agentName:z19.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z19.unknown().optional(),capabilities:z19.array(z19.string()).optional(),dataSources:z19.array(z19.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z19.string().nullable(),startedAt:z19.coerce.date().nullable(),finishedAt:z19.coerce.date().nullable(),cancelledAt:z19.coerce.date().nullable(),costUsd:z19.number().nonnegative(),costCeilingUsd:z19.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z19.boolean(),lastCheckpointId:z19.uuid().nullable(),branchEnvId:z19.uuid().nullable(),parentSessionId:z19.uuid().nullable(),terminalReason:z19.string().nullable(),errorMessage:z19.string().nullable(),report:z19.string().nullable(),reviewSummary:AgentSessionReviewSummarySchema.nullable(),reviewCaptureError:z19.string().nullable(),createdAt:z19.coerce.date(),updatedAt:z19.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z19.object({id:z19.uuid(),sessionId:z19.uuid(),checkpointIdx:z19.number().int().nonnegative(),payloadRef:z19.string(),payloadSizeBytes:z19.number().int().nonnegative(),checksum:z19.string().length(64),createdAt:z19.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z19.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z19.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z19.object({session:AgentSessionDTOSchema,checkpoints:z19.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z19.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=z19.object({reason:z19.string().min(1).max(120).optional()})}});import{z as z20}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=z20.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z20.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z20.object({id:z20.uuid(),envId:z20.uuid(),sessionId:z20.uuid().nullable(),skillName:z20.string().min(1),classification:AgentBranchClassificationSchema,rationale:z20.string().nullable(),summary:z20.string().nullable(),surfaceDeltas:z20.record(z20.string(),z20.unknown()),createdAt:z20.coerce.date(),decidedAt:z20.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z20.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z20.object({path:z20.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z20.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z20.object({code:z20.literal("merge_conflict"),message:z20.string(),conflicts:z20.record(z20.string(),z20.number().int().nonnegative())})}});import{z as z21}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=z21.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z21.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z21.enum(["secret_text"]),IntegrationCredentialUsageSchema=z21.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z21.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z21.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z21.object({mode:IntegrationAuthModeSchema,label:z21.string().min(1),description:z21.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z21.object({id:z21.string().min(1),label:z21.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z21.boolean()}),IntegrationToolDefinitionDTOSchema=z21.object({key:z21.string().min(1),name:z21.string().min(1),description:z21.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z21.object({title:z21.string().min(1),description:z21.string().min(1),command:z21.string().min(1).optional()}),IntegrationInfoDTOSchema=z21.object({key:z21.string().min(1),name:z21.string().min(1),summary:z21.string().min(1),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z21.array(IntegrationAuthModeDTOSchema),credentials:z21.array(IntegrationCredentialDefinitionDTOSchema),tools:z21.array(IntegrationToolDefinitionDTOSchema),recipes:z21.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z21.object({projectId:z21.uuid(),integrationKey:z21.string().min(1),name:z21.string().min(1),summary:z21.string().min(1),installed:z21.boolean(),enabled:z21.boolean(),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z21.string().nullable(),connectionId:z21.uuid().nullable().optional(),connectionAlias:z21.string().min(1).nullable().optional(),connectionStatus:z21.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z21.array(z21.string()),installedAt:z21.coerce.date().nullable(),updatedAt:z21.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z21.object({id:z21.uuid(),projectId:z21.uuid(),integrationKey:z21.string().min(1),enabled:z21.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z21.string(),connectionId:z21.uuid().nullable().optional(),connectionAlias:z21.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z21.array(z21.string()),createdAt:z21.coerce.date(),updatedAt:z21.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z21.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z21.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z21.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z21.object({value:z21.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z21.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z21.object({id:z21.uuid(),organizationId:z21.string().min(1),integrationKey:z21.string().min(1),alias:z21.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z21.string().min(1),externalAccountName:z21.string().nullable(),externalBotUserId:z21.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z21.array(z21.string()),connectedAt:z21.coerce.date(),updatedAt:z21.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ConnectOrganizationIntegrationRequestSchema=z21.object({alias:z21.string().min(1).max(120).optional(),token:z21.string().min(1).optional()}),ProjectIntegrationReturnPathSchema=z21.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),ConnectProjectIntegrationRequestSchema=z21.discriminatedUnion("mode",[z21.object({mode:z21.literal("personal"),alias:z21.string().min(1).max(120),token:z21.string().min(1)}),z21.object({mode:z21.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional()})]),StartProjectIntegrationConnectResponseSchema=z21.object({integrationKey:z21.string().min(1),connectUrl:z21.string().url(),expiresAt:z21.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z21.discriminatedUnion("mode",[z21.object({mode:z21.literal("personal"),integrationKey:z21.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z21.object({mode:z21.literal("oauth"),integrationKey:z21.string().min(1),connectUrl:z21.string().url(),expiresAt:z21.coerce.date()})]),BindProjectChannelRequestSchema=z21.object({ref:z21.string().min(1),connectionAlias:z21.string().min(1).optional(),agentName:z21.string().min(1).max(160).nullable().optional(),force:z21.boolean().optional()}),ListProjectChannelsQuerySchema=z21.object({integrationKey:z21.string().min(1)}),SearchProjectChannelsQuerySchema=z21.object({integrationKey:z21.string().min(1),connectionAlias:z21.string().min(1),query:z21.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z21.object({id:z21.uuid(),projectId:z21.uuid(),integrationKey:z21.string().min(1),connectionId:z21.uuid(),externalWorkspaceId:z21.string().min(1),externalChannelId:z21.string().min(1),externalChannelName:z21.string().nullable(),agentName:z21.string().nullable(),enabled:z21.boolean(),createdAt:z21.coerce.date(),updatedAt:z21.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z21.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z21.object({id:z21.string().min(1),name:z21.string().min(1),visibility:z21.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z21.string().min(1).nullable(),canMove:z21.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z21.object({markdown:z21.boolean().optional(),summary:z21.boolean().optional(),links:z21.boolean().optional(),images:z21.boolean().optional(),html:z21.union([z21.literal("cleaned"),z21.literal("raw"),z21.boolean()]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z21.object({url:z21.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z21.boolean().optional(),timeoutMs:z21.number().int().positive().max(12e4).optional(),waitForMs:z21.number().int().min(0).max(3e4).optional()}),FirecrawlSearchToolInputSchema=z21.object({query:z21.string().min(1),maxResults:z21.number().int().positive().max(20).optional(),sources:z21.array(z21.enum(["web","news","images"])).min(1).max(3).optional(),categories:z21.array(z21.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z21.array(z21.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z21.array(z21.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z21.enum(["hour","day","week","month","year"]).optional(),location:z21.string().min(1).max(160).optional(),country:z21.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z21.boolean().optional(),timeoutMs:z21.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlMapToolInputSchema=z21.object({url:z21.string().url(),search:z21.string().min(1).optional(),limit:z21.number().int().positive().max(200).optional(),includeSubdomains:z21.boolean().optional(),timeoutMs:z21.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z21.object({url:z21.string().url(),limit:z21.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z21.boolean().optional(),timeoutMs:z21.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z21.object({text:z21.string().min(1).max(200).optional(),cron:z21.string().min(1).max(120).optional(),timezone:z21.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorTargetInputSchema=z21.object({type:z21.enum(["scrape","crawl"]).default("scrape"),urls:z21.array(z21.string().url()).min(1).max(50),scrapeOptions:z21.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z21.boolean().optional(),timeoutMs:z21.number().int().positive().max(12e4).optional(),waitForMs:z21.number().int().min(0).max(3e4).optional()}).optional()}),FirecrawlMonitorCreateToolInputSchema=z21.object({name:z21.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z21.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z21.string().min(1).max(2e3).optional(),judgeEnabled:z21.boolean().optional(),retentionDays:z21.number().int().min(1).max(365).optional(),notification:z21.object({email:z21.object({enabled:z21.boolean().default(!0),recipients:z21.array(z21.string().email()).min(1).max(20),includeDiffs:z21.boolean().optional()}).optional()}).optional()}),FirecrawlMonitorIdToolInputSchema=z21.object({monitorId:z21.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z21.string().uuid()}),RunProjectIntegrationToolRequestSchema=z21.object({tool:z21.string().min(1),input:z21.record(z21.string(),z21.unknown()),connectionAlias:z21.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z21.object({provider:z21.string().min(1),providerCredits:z21.number().nonnegative().optional(),providerCostUsd:z21.number().nonnegative().optional(),requests:z21.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z21.object({credits:z21.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z21.object({url:z21.string(),provider:z21.literal("firecrawl"),title:z21.string().optional(),statusCode:z21.number().optional(),markdown:z21.string().optional(),summary:z21.string().optional(),links:z21.array(z21.string()).optional(),images:z21.array(z21.string()).optional(),html:z21.string().optional(),warning:z21.string().optional()}),FirecrawlSearchToolOutputSchema=z21.object({query:z21.string(),provider:z21.literal("firecrawl"),warning:z21.string().optional(),results:z21.array(z21.object({title:z21.string(),url:z21.string(),snippet:z21.string().optional(),content:z21.string().optional(),score:z21.number().optional(),publishedAt:z21.string().optional()}))}),FirecrawlMapToolOutputSchema=z21.object({url:z21.string(),provider:z21.literal("firecrawl"),count:z21.number(),links:z21.array(z21.object({url:z21.string(),title:z21.string().optional(),description:z21.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z21.object({url:z21.string(),provider:z21.literal("firecrawl"),total:z21.number(),pages:z21.array(z21.object({url:z21.string(),title:z21.string().optional(),statusCode:z21.number().optional(),markdown:z21.string().optional(),summary:z21.string().optional(),links:z21.array(z21.string()).optional(),images:z21.array(z21.string()).optional(),html:z21.string().optional(),warning:z21.string().optional()})),warning:z21.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z21.object({cron:z21.string().optional(),text:z21.string().optional(),timezone:z21.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z21.object({id:z21.string().optional(),urls:z21.array(z21.string()).optional(),scrapeOptions:z21.record(z21.string(),z21.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z21.object({id:z21.string(),name:z21.string(),status:z21.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z21.string().nullable().optional(),lastRunAt:z21.string().nullable().optional(),currentCheckId:z21.string().nullable().optional(),targets:z21.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z21.string().nullable().optional(),judgeEnabled:z21.boolean().optional(),estimatedCreditsPerMonth:z21.number().optional(),createdAt:z21.string().optional(),updatedAt:z21.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z21.object({id:z21.string(),monitorId:z21.string(),scheduledFor:z21.string().nullable().optional(),startedAt:z21.string().nullable().optional(),finishedAt:z21.string().nullable().optional(),estimatedCredits:z21.number().optional(),reservedCredits:z21.number().optional(),actualCredits:z21.number().optional(),billingStatus:z21.string().nullable().optional(),summary:z21.object({totalPages:z21.number().optional(),same:z21.number().optional(),changed:z21.number().optional(),new:z21.number().optional(),removed:z21.number().optional(),error:z21.number().optional()}).passthrough().optional(),error:z21.string().nullable().optional(),createdAt:z21.string().optional(),updatedAt:z21.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z21.object({provider:z21.literal("firecrawl"),monitors:z21.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z21.object({provider:z21.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z21.object({provider:z21.literal("firecrawl"),monitorId:z21.string(),deleted:z21.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z21.object({provider:z21.literal("firecrawl"),monitorId:z21.string(),checks:z21.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z21.object({provider:z21.literal("firecrawl"),monitorId:z21.string(),check:FirecrawlMonitorCheckOutputSchema,next:z21.string().optional()}),FirecrawlToolKeySchema=z21.enum(["search","scrape","map","crawl","monitor.create","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z21.union([FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z21.object({projectId:z21.uuid(),integrationKey:z21.string().min(1),tool:z21.string().min(1),connectionAlias:z21.string().min(1).nullable().optional(),output:z21.record(z21.string(),z21.unknown()),executedAt:z21.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z21.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z21.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z21.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z21.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z21.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z21.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z21.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z21.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z21.array(OrganizationIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z21.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z21.array(ProjectChannelCandidateDTOSchema))}});import{z as z22}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,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_create_dto();init_response();PROJECT_SECRET_KEY_PATTERN=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN=/^(PUBLIC_|VITE_|NEXT_PUBLIC_)/,RESERVED_PROJECT_SECRET_KEYS=new Set(["FIMO_API_URL","FIMO_API_TOKEN","FIMO_PROJECT_ID","FIMO_ENV","FIMO_AGENT_SESSION","FIMO_DATA_SOURCES","FIMO_SCHEDULE_ID","FIMO_SCHEDULE_RUN_ID","FIMO_SCHEDULE_NAME","VITE_API_URL","VITE_ENABLE_ANALYTICS","VITE_FIMO_BRANCH","VITE_FIMO_IMAGE_HOSTS"]),ProjectSecretKeySchema=z22.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=z22.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z22.uuid(),env:z22.string().min(1),name:z22.string().min(1),cron:z22.string().min(1),command:z22.string().min(1),secretKeys:z22.array(z22.string().min(1)),enabled:z22.boolean(),lastRunAt:z22.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z22.string().nullable()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z22.object({name:z22.string().min(1).max(120),cron:z22.string().min(1).max(120),command:z22.string().min(1).max(500),secretKeys:z22.array(ProjectSecretKeySchema).default([])}),UpdateProjectScheduleRequestSchema=z22.object({name:z22.string().min(1).max(120).optional(),cron:z22.string().min(1).max(120).optional(),command:z22.string().min(1).max(500).optional(),secretKeys:z22.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z22.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z22.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z22.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z22.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z22.object({maxRuns:z22.number().int().positive(),retentionDays:z22.number().int().positive().nullable(),outputRetentionDays:z22.number().int().positive(),maxOutputBytes:z22.number().int().positive()}),ProjectScheduleUsageSchema=z22.object({runCount:z22.number().int().nonnegative(),runsWithOutput:z22.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z22.object({id:z22.uuid(),scheduleId:z22.uuid(),projectId:z22.uuid(),env:z22.string().min(1),scheduleName:z22.string().min(1),command:z22.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z22.object({id:z22.string().min(1),name:z22.string().min(1)}).nullable(),queuedAt:z22.coerce.date(),startedAt:z22.coerce.date().nullable(),finishedAt:z22.coerce.date().nullable(),exitCode:z22.number().int().nullable(),errorCode:z22.string().nullable(),error:z22.string().nullable(),outputBytes:z22.number().int().nonnegative(),outputTruncated:z22.boolean(),outputExpiresAt:z22.coerce.date().nullable(),metadataExpiresAt:z22.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z22.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z22.coerce.date().nullable(),items:z22.array(z22.object({key:z22.string().min(1),updatedAt:z22.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z22.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z22.object({trigger:z22.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z22.object({limit:z22.coerce.number().int().min(1).max(100).default(25),cursor:z22.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z22.object({items:z22.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z22.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z22.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z22.object({items:z22.array(ProjectScheduleRunDTOSchema),nextCursor:z22.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z23}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=z23.object({id:z23.uuid(),occurredAt:z23.coerce.date(),projectId:z23.uuid().nullable(),env:z23.string().nullable(),actor:z23.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z23.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z23.unknown().optional(),ipAddress:z23.string().nullable().optional(),userAgent:z23.string().nullable().optional(),error:z23.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z23.object({rows:z23.array(AuditLogRowDTOSchema),nextCursor:z23.string().nullable()})),AuditLogQuerySchema=z23.object({env:z23.string().optional(),action:AuditActionSchema.optional(),actor:z23.string().optional(),from:z23.coerce.date().optional(),to:z23.coerce.date().optional(),limit:z23.coerce.number().int().min(1).max(200).optional(),cursor:z23.string().optional()})}});import{z as z24}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=z24.object({surface:SurfaceNameSchema,key:z24.string(),label:z24.string()}),InlineSchema=z24.object({text:z24.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z24.discriminatedUnion("type",[z24.object({type:z24.literal("paragraph"),content:z24.array(InlineSchema).max(24)}),z24.object({type:z24.literal("preview"),ref:DiffRefSchema,caption:z24.string().optional()}),z24.object({type:z24.literal("code"),code:z24.string(),lang:z24.string().optional(),caption:z24.string().optional()}),z24.object({type:z24.literal("risk"),level:z24.enum(["warning","error"]),content:z24.array(InlineSchema).max(24)}),z24.object({type:z24.literal("list"),items:z24.array(z24.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z24.object({headline:z24.string(),blocks:z24.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z24.object({summary:EnvDiffSummarySchema,fingerprint:z24.string(),generatedAt:z24.coerce.date(),cached:z24.boolean().optional(),credits:z24.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z25}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=z25.object({date:z25.string(),visitors:z25.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z25.object({key:z25.string(),visitors:z25.number().int().nonnegative(),pageviews:z25.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z25.object({path:z25.string(),pageName:z25.string().nullable().optional(),visitors:z25.number().int().nonnegative(),pageviews:z25.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z25.object({preset:z25.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z25.string(),requestedTo:z25.string(),effectiveFrom:z25.string(),effectiveTo:z25.string(),isRetentionLimited:z25.boolean(),groupBy:z25.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z25.object({date:z25.string(),content:z25.string(),updatedAt:z25.string(),updatedByUserId:z25.string()}),ProjectPageviewAnalyticsDTOSchema=z25.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z25.number().int().nonnegative(),pageviews:z25.number().int().nonnegative(),bounceRate:z25.number().min(0).max(100),viewsPerVisit:z25.number().nonnegative(),averageVisitDurationSeconds:z25.number().nonnegative(),visitorsSeries:z25.array(ProjectDailyVisitorsDTOSchema),topPages:z25.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z25.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z25.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z25.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z25.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z25.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z26}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=z26.object({id:z26.string(),email:z26.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z26.coerce.date(),createdAt:z26.coerce.date(),inviterUserId:z26.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z26.object({id:z26.string(),token:z26.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z26.object({success:z26.boolean(),projectId:z26.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z27}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=z27.object({id:z27.string(),name:z27.string(),image:z27.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z27.object({count:z27.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z27.object({counts:z27.object({signed_up:z27.int(),activated:z27.int()}),credits:z27.object({total:z27.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z27.email(),emailVerified:z27.boolean(),createdAt:z27.coerce.date(),updatedAt:z27.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z28}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=z28.object({id:z28.string(),principalType:ProjectPrincipalTypeSchema,principalId:z28.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z28.coerce.date(),expiresAt:z28.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","preview:view","realtime:connect","analytics:view","logs:view","domain:manage","agent:run"],ProjectPermissionKeySchema=z28.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z28.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z28.record(z28.string(),z28.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z28.object({access:z28.array(ProjectAccessItemDTOSchema),invites:z28.array(ProjectInviteDTOSchema),organization:z28.object({name:z28.string().nullable(),logo:z28.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z28.object({success:z28.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z28.object({success:z28.boolean(),projectId:z28.uuid()}))}});import{z as z29}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=z29.object({publicationStatus:PublicationStatusSchema,appUrl:z29.string().nullable(),lastPublishedAt:z29.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z30}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=z30.object({url:z30.url(),expiresAt:z30.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema)}});import{z as z31}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:z31.string(),slug:z31.string().nullable(),logo:z31.string().nullable(),metadata:z31.record(z31.string(),z31.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z31.object({id:z31.string(),name:z31.string(),email:z31.email(),image:z31.string().nullable()}),OrganizationMemberDTOSchema=z31.object({id:z31.string(),userId:z31.string(),organizationId:z31.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z31.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z32}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common();init_create_dto();init_response();CancellationReasonCodeSchema=z32.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z32.object({reason:CancellationReasonCodeSchema,details:z32.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z32.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),AiCreditsEntitlementSchema=z32.object({included:z32.number().optional(),unitPrice:z32.number().optional(),dailyCap:z32.number().nullable().optional()}),EntitlementsDTOSchema=z32.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z32.object({retentionDays:z32.number().int().positive(),canUseExtendedDateRanges:z32.boolean()}).optional(),history:z32.object({retentionDays:z32.number().int().positive()}).optional(),members:z32.object({canInvite:z32.boolean(),maxMembers:z32.number().int().positive().nullable()}).optional(),projects:z32.object({canCreatePrivateProjects:z32.boolean(),maxPrivateProjects:z32.number().int().positive().nullable()}).optional(),domains:z32.object({canUseCustomDomains:z32.boolean(),maxDomains:z32.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z32.object({id:z32.string(),external_id:z32.string(),customerId:z32.string(),planId:z32.string(),planCode:TemplateCodeSchema,currentPeriod:z32.object({start:z32.string(),end:z32.string().nullable()}),cancelAt:z32.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z32.string(),nextPaymentAt:z32.string().nullable(),baseAmount:z32.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z32.object({totalCap:z32.number(),dailyCap:z32.number(),usedTotal:z32.number()}),CreditBalanceDTOSchema=z32.object({total:z32.number(),base:z32.number(),dailyBase:z32.number(),purchases:z32.number(),awards:z32.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z32.object({total:z32.number(),nearLimit:z32.boolean(),canChat:z32.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z32.object({dailyFreeAvailable:z32.number(),monthlyAvailable:z32.number(),purchasedAvailable:z32.number(),awardedAvailable:z32.number()}),ProjectDailyCreditAllowanceDTOSchema=z32.object({periodCap:z32.number(),dailyGrant:z32.number(),usedThisPeriod:z32.number(),remainingThisPeriod:z32.number()}),ProjectCreditBalanceDTOSchema=z32.object({projectId:z32.uuid(),organizationId:z32.string(),balance:z32.object({totalAvailable:z32.number(),nearLimit:z32.boolean(),canUseAi:z32.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z32.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),SuccessfulPurchaseDTOSchema=z32.object({invoiceId:z32.string(),newBalance:z32.int(),creditCount:z32.int(),amountUsd:z32.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z32.object({url:z32.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema)}});import{z as z33}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=z33.object({brand:z33.string(),last4:z33.string(),exp:z33.string(),isDefault:z33.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z34}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=z34.string().superRefine((path43,ctx)=>{let segments=path43.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=z34.object({type:z34.literal("renameField"),contentType:z34.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z34.object({enabled:z34.boolean()}).strict(),ContentTypeDTOSchema=z34.object({id:z34.string(),name:z34.string(),label:z34.string(),isSingleton:z34.boolean(),i18n:ContentTypeI18nSchema,fields:z34.record(z34.string(),FieldDefinitionSchema),createdAt:z34.string(),updatedAt:z34.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z34.object({contentTypes:z34.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z34.object({id:z34.string(),entryId:z34.string(),documentId:z34.string(),slug:z34.string(),locale:z34.string().optional(),createdAt:z34.string(),updatedAt:z34.string(),__fimo:z34.object({contentType:z34.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z34.object({data:z34.array(EntryDTOSchema),meta:z34.object({limit:z34.number(),offset:z34.number(),total:z34.number(),hasMore:z34.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z34.object({contentType:z34.string(),count:z34.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z34.object({counts:z34.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z34.object({count:z34.number().int().nonnegative(),sourceLocale:z34.string(),targetLocale:z34.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z34.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z34.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z34.union([z34.string(),z34.number(),z34.boolean(),z34.null()]),entryWhereOperatorSchema=z34.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z34.array(entryWhereScalarSchema).optional(),$nin:z34.array(entryWhereScalarSchema).optional(),$contains:z34.string().optional(),$startsWith:z34.string().optional(),$null:z34.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z34.record(z34.string(),z34.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z34.record(z34.string(),z34.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z34.object({data:z34.record(z34.string(),z34.unknown()),locale:z34.string().min(1).optional(),documentId:z34.uuid().optional()}),entryIdsSchema=z34.array(z34.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z34.object({sql:z34.string().min(1)}),BulkCreateEntriesRequestSchema=z34.object({entries:z34.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z34.union([z34.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z34.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z34.object({updates:z34.array(z34.object({id:z34.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z34.union([z34.object({ids:entryIdsSchema,locale:z34.string().min(1).optional()}),z34.object({where:EntryWhereSchema,locale:z34.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z34.object({data:z34.array(z34.record(z34.string(),z34.unknown())),meta:z34.object({rowCount:z34.number().int().nonnegative(),truncated:z34.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z34.object({data:z34.array(EntryDTOSchema),meta:z34.object({created:z34.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z34.object({data:z34.array(EntryDTOSchema),meta:z34.object({updated:z34.number().int().nonnegative(),missing:z34.array(z34.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z34.object({data:z34.array(EntryDTOSchema),meta:z34.object({deleted:z34.number().int().nonnegative(),missing:z34.array(z34.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z35}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z35.object({index:z35.number().int().nonnegative(),contentType:z35.string(),field:z35.string(),value:z35.string(),against:z35.enum(["stored","batch"]),ownerDocumentId:z35.uuid().optional(),ownerIndex:z35.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z35.object({code:z35.literal("unique_conflict"),message:z35.string(),conflicts:z35.array(UniqueConflictSchema),truncated:z35.boolean().optional()})}});import{z as z36}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=z36.object({kind:z36.literal("unique_conflict"),contentType:z36.string(),field:z36.string(),value:z36.string(),documentCount:z36.number().int().positive(),documentIds:z36.array(z36.uuid()),documentIdsTruncated:z36.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z36.object({code:z36.literal("schema_transition_rejected"),message:z36.string(),issues:z36.array(SchemaTransitionIssueSchema),truncated:z36.boolean().optional()})}});import{z as z37}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=z37.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z37.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z37.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z37.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z37.object({field:CmsFieldNameSchema,direction:z37.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z37.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z37.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z37.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z37.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z37.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z38}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=z38.object({id:z38.string(),name:z38.string()}),AssetDTOSchema=z38.object({id:z38.string(),name:z38.string(),type:AssetTypeSchema,originalFileName:z38.string().nullable(),parentId:z38.string().nullable(),mimeType:z38.string().nullable(),fileSize:z38.number().nullable(),url:z38.string().nullable(),storageKey:z38.string().nullable(),createdAt:z38.string(),updatedAt:z38.string(),altText:z38.string().nullable().optional(),caption:z38.string().nullable().optional(),aiCaption:z38.string().nullable().optional(),aiAltText:z38.string().nullable().optional(),aiTags:z38.array(z38.string()).nullable().optional(),aiPrimaryColor:z38.string().nullable().optional(),aiProcessingStatus:z38.string().nullable().optional(),width:z38.number().nullable().optional(),height:z38.number().nullable().optional(),path:z38.array(AssetPathItemSchema).optional(),hasChildren:z38.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z38.lazy(()=>z38.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z38.array(AssetDTOSchema))}});import{z as z39}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z39.object({key:z39.string(),value:z39.string().optional(),defaultValue:z39.string(),locale:z39.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z40}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=z40.object({id:z40.string(),name:z40.string(),type:z40.enum(["file","folder"]),path:z40.string(),children:z40.lazy(()=>z40.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z40.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z40.object({path:z40.string(),exists:z40.boolean(),type:z40.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z41}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=z41.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z41.object({items:z41.array(ProjectMessagePublicDTOSchema),nextCursor:z41.string().nullable()}),ChatLiveTurnDTOSchema=z41.object({invocationId:z41.string(),step:z41.enum(["preparing","working","compacting","merging"]),startedAt:z41.string()}),ChatLiveTurnStateDTOSchema=z41.object({threadId:z41.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatThreadMessageDTOSchema=z41.object({id:z41.string(),role:z41.enum(["user","assistant"]),parts:z41.array(z41.unknown()),metadata:z41.record(z41.string(),z41.unknown()).nullable(),createdAt:z41.date().transform(value=>value.toISOString()),providerMessageId:z41.string().nullable().optional(),invocationId:z41.string().nullable().optional(),invocationStatus:z41.string().nullable().optional(),invocationTerminalReason:z41.string().nullable().optional()}),ChatAttentionDTOSchema=z41.object({type:z41.literal("merge_conflict"),merge:z41.object({mergeId:z41.string().uuid(),projectId:z41.string(),fromEnv:z41.string(),toEnv:z41.string()}),publishAfterMerge:z41.boolean()}),ChatThreadMessagesPageDTOSchema=z41.object({threadId:z41.string().nullable(),title:z41.string().nullable(),messages:z41.array(ChatThreadMessageDTOSchema),nextCursor:z41.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z41.object({kind:z41.literal("replay"),threadId:z41.string(),userMessageId:z41.string()}),ChatQueuedOutcomeDTOSchema=z41.object({kind:z41.literal("queued"),threadId:z41.string(),userMessageId:z41.string(),blockingRootId:z41.string()}),ChatBusyOutcomeDTOSchema=z41.object({kind:z41.literal("busy"),threadId:z41.string(),userMessageId:z41.string(),blockingRootId:z41.string().optional()}),ChatRefusedOutcomeDTOSchema=z41.object({kind:z41.literal("refused"),threadId:z41.string(),userMessageId:z41.string(),refusedInvocationId:z41.string(),terminalReason:z41.string()}),ChatNonStreamingOutcomeDTOSchema=z41.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z41.object({success:z41.boolean(),deletedCount:z41.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z41.object({code:z41.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z41.string()})}});import{z as z42}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=z42.object({url:z42.string().url(),key:z42.string(),size:z42.number(),contentType:z42.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z43}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=z43.object({canAccess:z43.boolean(),permissions:z43.record(z43.string(),z43.boolean()),role:z43.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z44}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:z44.string().trim().default(""),sort:z44.enum(["recent","name","relevance"]).default("recent"),category:z44.string().optional(),visibility:z44.enum(["public","private"]).optional()})}});import{z as z45}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=z45.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z45.enum(["fimo","external"]),PaymentStatusSchema=z45.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z45.object({id:z45.string().uuid(),domain:z45.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z45.boolean(),price:z45.number().int().nullable(),renewalPrice:z45.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z45.string().nullable(),failureReason:z45.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z45.object({domain:z45.string(),available:z45.boolean(),premium:z45.boolean(),price:z45.number().nullable(),renewalPrice:z45.number().nullable(),purchaseType:z45.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z45.object({domain:z45.string(),price:z45.number().nullable(),renewalPrice:z45.number().nullable(),premium:z45.boolean(),allowedYears:z45.array(z45.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z45.object({firstName:z45.string().max(100),lastName:z45.string().max(100),companyName:z45.string().max(100).optional(),address1:z45.string().max(255),address2:z45.string().max(255).optional(),city:z45.string().max(100),state:z45.string().max(100),zip:z45.string().max(20),country:z45.string().max(2),phone:z45.string().max(30),email:z45.union([z45.string().email().max(255),z45.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z45.object({firstName:z45.string().min(1).max(100),lastName:z45.string().min(1).max(100),companyName:z45.string().max(100).optional(),address1:z45.string().min(1).max(255),address2:z45.string().max(255).optional(),city:z45.string().min(1).max(100),state:z45.string().min(1).max(100),zip:z45.string().min(1).max(20),country:z45.string().min(1).max(2),phone:z45.string().min(1).max(30),email:z45.string().email().max(255)}),SearchDomainsRequestSchema=z45.object({keyword:z45.string().min(1).max(100),tldFilter:z45.array(z45.string()).optional()}),CheckAvailabilityRequestSchema=z45.object({domains:z45.array(z45.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=z45.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z45.object({domain:DomainNameSchema,years:z45.number().int().min(1).max(10).optional().default(3),autoRenew:z45.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z45.object({autoRenew:z45.boolean().optional()}),RenewDomainRequestSchema=z45.object({years:z45.number().int().min(1).max(10).optional().default(1),autoRenew:z45.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z45.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z45.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z45.object({verified:z45.boolean(),email:z45.string().nullable(),verifyBy:z45.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z46}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=z46.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=z46.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=z46.object({txtName:z46.string().nullable().optional(),txtValue:z46.string().nullable().optional(),httpUrl:z46.string().nullable().optional(),httpBody:z46.string().nullable().optional(),cname:z46.string().nullable().optional(),cnameTarget:z46.string().nullable().optional()}),SSLValidationErrorSchema=z46.object({message:z46.string()}),OwnershipVerificationSchema=z46.object({type:z46.string(),name:z46.string(),value:z46.string()}),ProjectDomainSSLDTOSchema=z46.object({status:z46.string(),method:z46.string().nullable(),type:z46.string().nullable(),validationRecords:z46.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z46.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z46.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z46.enum(["subdomain","apex"]),RedirectConfigSchema=z46.object({type:z46.literal("apex_to_www"),linkedDomainId:z46.string()}).nullable().optional(),ProjectDomainDTOSchema=z46.object({id:z46.string(),hostname:z46.string(),status:z46.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z46.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z46.string(),scdCnameTarget:z46.string().optional(),apexTargets:z46.array(z46.string()),dnsAutoConfigured:z46.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z46.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z46.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z46.object({hostname:z46.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:z46.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z46.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z46.object({available:z46.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z46.object({success:z46.boolean(),hostname:z46.string()}))}});import{z as z47}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=z47.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z47.object({available:z47.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z47.object({slug:z47.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z47.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z47.object({subdomain:z47.string(),subdomainUpdatedAt:z47.coerce.date()})),SubdomainSuggestionsQuerySchema=z47.object({base:z47.string().max(100).optional(),max:z47.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z47.object({suggestions:z47.array(z47.string())}))}});import{z as z48}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=z48.object({translated:z48.number().int().nonnegative(),total:z48.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z48.object({locale:z48.string(),isDefault:z48.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z48.object({defaultLocale:z48.string(),routing:z48.object({strategy:z48.literal("path-prefix"),prefixDefaultLocale:z48.boolean()}),locales:z48.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z48.object({locale:z48.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z48.object({locale:z48.string().min(1).max(40)}),ProjectLocaleMutationSchema=z48.object({locale:z48.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z48.object({locale:z48.string(),entriesDeleted:z48.number().int().nonnegative(),labelsDeleted:z48.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z49}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=z49.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z49.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=z49.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z49.number(),credits:z49.number().optional(),billingMode:z49.enum(["fimo-credits","provider-account"]).optional(),confidence:z49.enum(["exact","estimated","metered"]),basis:z49.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z50}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=z50.object({options:z50.record(z50.string(),z50.unknown()),name:z50.string().optional(),parentId:z50.string().nullable().optional(),altText:z50.string().optional(),caption:z50.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z50.string().min(1).optional(),model:z50.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=z50.object({jobId:z50.string(),status:z50.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z50.string().nullable().optional(),credits:z50.number().optional(),costUsd:z50.number().optional(),billingMode:z50.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z50.object({error:z50.string(),code:z50.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:z50.array(GenerationTaskIdSchema).optional(),availableModels:z50.array(z50.string()).optional(),issues:z50.array(z50.unknown()).optional()})}});import{z as z51}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=z51.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z51.object({name:z51.string(),key:z51.string(),description:z51.string(),type:FlagTypeSchema,required:z51.boolean(),defaultValue:z51.unknown().optional(),enumValues:z51.array(z51.string()).optional(),isArray:z51.boolean()}),AssetModelPriceSchema=z51.object({unitPrice:z51.number(),unit:z51.string(),confidence:z51.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z51.object({id:z51.string(),shortName:z51.string(),provider:z51.string(),source:z51.string(),modality:z51.enum(["image","video","audio"]),tags:z51.array(z51.string()),displayName:z51.string(),description:z51.string(),flags:z51.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z51.object({model:z51.string(),costUsd:z51.number(),credits:z51.number(),billingMode:z51.enum(["fimo-credits","provider-account"]),confidence:z51.enum(["exact","estimated","metered"]),basis:z51.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z52}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=z52.object({tourId:z52.string(),version:z52.string(),status:z52.string(),completedAt:z52.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z52.array(UserTourDTOSchema))}});import{z as z53}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=z53.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z53.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z53.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z53.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z53.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z53.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z53.enum(["user","agent","system"]),SupportReportTagSchema=z53.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z53.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z53.object({organization:z53.object({id:z53.string().trim().min(1).max(255),name:z53.string().trim().max(240).optional()}),project:z53.object({id:z53.uuid(),name:z53.string().trim().max(240).optional(),createdAt:z53.coerce.date().optional()}).optional(),environment:z53.string().trim().max(255).optional(),clientVersion:z53.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z53.object({message:z53.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z53.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z53.string().trim().max(200).optional(),limit:z53.coerce.number().int().min(1).max(100).default(50),offset:z53.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z53.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z53.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z53.uuid().nullable().optional(),note:z53.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=z53.object({message:z53.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z53.object({kind:SupportReportLinkKindSchema,label:z53.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z53.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z53.object({kind:SupportReportActorKindSchema,id:z53.string().nullable(),name:z53.string().nullable()}),SupportReportLinkDTOSchema=z53.object({id:z53.uuid(),kind:SupportReportLinkKindSchema,label:z53.string(),url:SupportReportHttpUrlSchema,externalId:z53.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z53.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z53.object({id:z53.uuid(),kind:SupportReportEventKindSchema,body:z53.string().nullable(),metadata:z53.record(z53.string(),z53.unknown()),actor:SupportReportActorDTOSchema,createdAt:z53.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z53.object({id:z53.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z53.array(z53.string()),source:SupportReportSourceSchema,message:z53.string(),reporter:z53.object({id:z53.string().nullable(),name:z53.string().nullable(),email:z53.string().nullable()}),organization:z53.object({id:z53.string().nullable(),name:z53.string()}),project:z53.object({id:z53.uuid().nullable(),name:z53.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z53.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z53.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z53.string().nullable(),deliveredAt:z53.coerce.date().nullable()}).nullable(),duplicateOfReportId:z53.uuid().nullable(),resolvedAt:z53.coerce.date().nullable(),createdAt:z53.coerce.date(),updatedAt:z53.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z53.string().nullable(),clientVersion:z53.string().nullable(),links:z53.array(SupportReportLinkDTOSchema),events:z53.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z53.object({reports:z53.array(SupportReportSummaryDTOSchema),total:z53.number().int().nonnegative(),statusCounts:z53.object({new:z53.number().int().nonnegative(),in_progress:z53.number().int().nonnegative(),waiting:z53.number().int().nonnegative(),resolved:z53.number().int().nonnegative(),duplicate:z53.number().int().nonnegative(),irrelevant:z53.number().int().nonnegative(),ignored:z53.number().int().nonnegative()}),limit:z53.number().int().positive(),offset:z53.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z53.object({id:z53.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z53.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z54}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=z54.iso.datetime({offset:!0}).pipe(z54.coerce.date()),OpsRecentChatInputSchema=z54.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z54.string().trim().min(1).max(255).optional(),limit:z54.coerce.number().int().min(1).max(200).default(100),cursor:z54.string().trim().min(1).max(2e3).optional(),slim:z54.boolean().default(!0),reason:z54.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=z54.object({id:z54.string(),threadId:z54.string(),providerMessageId:z54.string().nullable(),invocationId:z54.string().nullable(),env:z54.string().nullable(),role:z54.string(),parts:z54.array(z54.record(z54.string(),z54.unknown())),metadata:z54.object({status:z54.string().optional(),traceUrl:z54.string().optional(),externalFileChanges:z54.array(z54.unknown()).optional()}),stats:z54.object({toolCount:z54.number().int().nonnegative(),failedToolCount:z54.number().int().nonnegative()}),createdAt:z54.iso.datetime({offset:!0}),project:z54.object({id:z54.string(),name:z54.string(),displayName:z54.string().nullable(),organizationId:z54.string().nullable()})}),OpsRecentChatResponseSchema=z54.object({target:z54.object({backendProfile:OpsBackendProfileSchema,projectEnv:z54.string().nullable()}),window:z54.object({from:z54.iso.datetime({offset:!0}),to:z54.iso.datetime({offset:!0})}),messages:z54.object({items:z54.array(OpsRecentChatMessageSchema),nextCursor:z54.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z55}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=z55.object({backendProfile:OpsBackendProfileSchema,provider:z55.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z55.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z55.object({backendProfile:OpsBackendProfileSchema,provider:z55.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z55.literal(!1),reason:z55.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z56}from"zod";function createAgentRunWebhookEventDataSchema(status){return z56.object({run:z56.object({id:z56.string(),agentName:z56.string(),trigger:z56.string(),status:z56.literal(status),startedAt:z56.string().nullable(),finishedAt:z56.string().nullable(),reason:z56.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEntryBatchWindowSecondsSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AgentReviewRequestedWebhookEventDataSchema,AgentReviewResolvedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,MediaGeneratedWebhookEventDataSchema,MediaProcessingFailedWebhookEventDataSchema,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=z56.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z56.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z56.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z56.enum(["main","all"]),WebhookEntryBatchWindowSecondsSchema=z56.union([z56.literal(0),z56.literal(5),z56.literal(30),z56.literal(60)]),EntryChangedWebhookEventDataSchema=z56.object({reason:WebhookEntryChangeReasonSchema,operationId:z56.string().optional(),batch:z56.object({index:z56.number().int().positive(),total:z56.number().int().positive()}).optional(),changes:z56.array(z56.object({action:WebhookEntryChangeActionSchema,contentType:z56.string(),id:z56.string(),documentId:z56.string(),locale:z56.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z56.object({form:z56.object({id:z56.string(),label:z56.string()}),submission:z56.object({id:z56.string(),data:z56.record(z56.string(),z56.unknown()),submittedAt:z56.string()})}),PublishStartedWebhookEventDataSchema=z56.object({publication:z56.object({status:z56.literal("publishing"),startedAt:z56.string()})}),PublishSucceededWebhookEventDataSchema=z56.object({publication:z56.object({status:z56.literal("published"),url:z56.string(),publishedAt:z56.string(),firstPublish:z56.boolean()})}),PublishFailedWebhookEventDataSchema=z56.object({publication:z56.object({status:z56.literal("failed"),reason:z56.string()})}),PublishUnpublishedWebhookEventDataSchema=z56.object({publication:z56.object({previousUrl:z56.string(),unpublishedAt:z56.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z56.object({review:z56.object({id:z56.string(),runId:z56.string(),agentName:z56.string(),classification:z56.string(),summary:z56.string(),reasons:z56.array(z56.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z56.object({review:z56.object({id:z56.string(),runId:z56.string(),agentName:z56.string(),resolution:z56.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z56.object({report:z56.object({weekStart:z56.string(),weekEnd:z56.string(),pageviews:z56.number(),visitors:z56.number(),previousPageviews:z56.number(),previousVisitors:z56.number()})}),MediaAssetWebhookEventDataSchema=z56.object({id:z56.string().nullable(),name:z56.string().nullable(),type:z56.string(),mimeType:z56.string().nullable(),fileSize:z56.number().nullable()}),MediaUploadedWebhookEventDataSchema=z56.object({asset:MediaAssetWebhookEventDataSchema,operation:z56.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z56.object({asset:MediaAssetWebhookEventDataSchema,operation:z56.enum(["updated","moved","analysis"]),analysis:z56.object({category:z56.string(),status:z56.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z56.object({asset:MediaAssetWebhookEventDataSchema,operation:z56.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z56.object({asset:MediaAssetWebhookEventDataSchema,operation:z56.literal("generated"),generation:z56.object({model:z56.string(),mode:z56.string()})}),MediaProcessingFailedWebhookEventDataSchema=z56.object({asset:MediaAssetWebhookEventDataSchema,operation:z56.enum(["analysis","generation"]),failure:z56.object({code:z56.string()})}),DomainCreatedWebhookEventDataSchema=z56.object({domain:z56.object({id:z56.string(),hostname:z56.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z56.object({domain:z56.object({id:z56.string(),hostname:z56.string()})}),LabelChangedWebhookEventDataSchema=z56.object({changes:z56.array(z56.object({action:z56.enum(["created","updated","deleted"]),key:z56.string(),locale:z56.string(),value:z56.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z56.object({locale:z56.object({code:z56.string(),isDefault:z56.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z56.object({locale:z56.object({code:z56.string(),previousCode:z56.string()})}),LocaleDeletedWebhookEventDataSchema=z56.object({locale:z56.object({code:z56.string(),entriesDeleted:z56.number().int().nonnegative(),labelsDeleted:z56.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z56.object({environment:z56.object({name:EnvSchema,parent:EnvSchema})}),EnvironmentDeletedWebhookEventDataSchema=z56.object({environment:z56.object({name:EnvSchema})}),EnvironmentMergedWebhookEventDataSchema=z56.object({merge:z56.object({id:z56.string(),from:EnvSchema,to:EnvSchema,applied:z56.array(z56.object({surface:SurfaceNameSchema,count:z56.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z56.object({environment:z56.object({name:EnvSchema}),version:z56.object({versionId:z56.uuid(),name:z56.string()})}),WEBHOOK_EVENT_DATA_SCHEMAS={"entry.changed":EntryChangedWebhookEventDataSchema,"form.submitted":FormSubmittedWebhookEventDataSchema,"publish.started":PublishStartedWebhookEventDataSchema,"publish.succeeded":PublishSucceededWebhookEventDataSchema,"publish.failed":PublishFailedWebhookEventDataSchema,"publish.unpublished":PublishUnpublishedWebhookEventDataSchema,"agent.run.started":createAgentRunWebhookEventDataSchema("running"),"agent.run.completed":createAgentRunWebhookEventDataSchema("completed"),"agent.run.failed":createAgentRunWebhookEventDataSchema("failed"),"agent.run.cancelled":createAgentRunWebhookEventDataSchema("cancelled"),"agent.review.requested":AgentReviewRequestedWebhookEventDataSchema,"agent.review.resolved":AgentReviewResolvedWebhookEventDataSchema,"analytics.report_ready":AnalyticsReportReadyWebhookEventDataSchema,"media.uploaded":MediaUploadedWebhookEventDataSchema,"media.updated":MediaUpdatedWebhookEventDataSchema,"media.deleted":MediaDeletedWebhookEventDataSchema,"media.generated":MediaGeneratedWebhookEventDataSchema,"media.processing_failed":MediaProcessingFailedWebhookEventDataSchema,"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=z56.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z56.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z56.discriminatedUnion("source",[z56.object({source:z56.literal("literal"),value:z56.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z56.object({source:z56.literal("secret"),key:z56.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z56.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z56.object({name:z56.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z56.object({name:z56.string(),source:z56.enum(["literal","secret"]),secretKey:z56.string().nullable(),secretPrefix:z56.string().nullable(),configured:z56.literal(!0)}),WebhookFilterSchema=z56.object({environment:WebhookEnvironmentScopeSchema.optional(),formId:z56.string().min(1).max(255).optional(),agentName:z56.string().min(1).max(120).optional(),mediaType:z56.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z56.string().min(1).max(255).optional(),locale:z56.string().min(1).max(120).optional()}),JsonValueSchema=z56.lazy(()=>z56.union([z56.string(),z56.number(),z56.boolean(),z56.null(),z56.array(JsonValueSchema),z56.record(z56.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z56.object({name:z56.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z56.url(),enabled:z56.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z56.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z56.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z56.object({name:z56.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z56.url().optional(),enabled:z56.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z56.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z56.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z56.object({eventType:WebhookEventTypeSchema.optional(),data:z56.record(z56.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z56.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z56.uuid(),name:z56.string(),eventType:WebhookEventTypeSchema,enabled:z56.boolean(),destination:z56.object({host:z56.string(),maskedUrl:z56.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z56.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z56.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z56.coerce.date().nullable(),deliveryStats24h:z56.object({succeeded:z56.number().int().nonnegative(),failed:z56.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z56.uuid(),projectId:z56.uuid(),env:EnvSchema,eventId:z56.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z56.number().int().positive(),test:z56.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z56.number().int().nonnegative(),responseStatus:z56.number().int().nullable(),lastErrorCode:z56.string().nullable(),lastErrorMessage:z56.string().nullable(),payloadAvailable:z56.boolean(),destination:z56.object({host:z56.string(),maskedUrl:z56.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z56.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z56.string().nullable(),qstashMessageId:z56.string().nullable(),deliveredAt:z56.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z56.object({items:z56.array(WebhookDeliveryDTOSchema),pagination:z56.object({page:z56.number().int().positive(),limit:z56.number().int().positive(),total:z56.number().int().nonnegative(),totalPages:z56.number().int().positive(),hasMore:z56.boolean()}),stats:z56.object({total:z56.number().int().nonnegative(),succeeded:z56.number().int().nonnegative(),failed:z56.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z56.object({id:z56.uuid(),deliveryId:z56.uuid(),attempt:z56.number().int().positive(),status:z56.enum(["delivering","succeeded","failed"]),responseStatus:z56.number().int().nullable(),durationMs:z56.number().int().nonnegative(),responseExcerpt:z56.string().nullable(),errorCode:z56.string().nullable(),errorMessage:z56.string().nullable(),createdAt:z56.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z56.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z56.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z57}from"zod";var 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=z57.object({key:z57.enum(previewFeatureKeys),enabled:z57.boolean(),dismissed:z57.boolean().default(!1),interacted:z57.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema),PreviewFeatureResponseSchema=createResponseSchema(PreviewFeatureDTOSchema),PreviewFeatureListResponseSchema=createResponseSchema(z57.array(PreviewFeatureDTOSchema))}});import{z as z58}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=z58.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z58.object({total:z58.number(),base:z58.number(),purchases:z58.number(),awards:z58.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z58.object({id:z58.string(),name:z58.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z58.object({type:z58.string(),brand:z58.string().nullable(),last4:z58.string().nullable(),expirationDate:z58.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z58.object({currency:z58.string(),nextPaymentAmount:z58.number().nullable(),nextPaymentAt:z58.string().nullable(),billingInterval:z58.string().nullable(),totalAmount:z58.number().nullable(),discountAmount:z58.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z58.object({id:z58.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z58.string().nullable(),currentPeriodEndsAt:z58.string().nullable(),renewsAt:z58.string().nullable(),cancelAt:z58.string().nullable(),renewAutomatically:z58.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z58.object({type:z58.enum(["low_balance","critical_balance","approaching_limit"]),message:z58.string(),estimatedPromptsRemaining:z58.number().nullable(),avgCostPerPrompt:z58.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z58.object({monthlyCredits:z58.number().nullable(),usedThisPeriod:z58.number(),remainingThisPeriod:z58.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z58.object({organizationId:z58.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z58.string().nullable(),tenureDays:z58.number().int().nonnegative(),capturedAt:z58.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z58.object({hasSubscription:z58.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z58.number().nullable(),alerts:z58.array(CreditAlertDTOSchema),portalUrl:z58.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z58.object({creditCount:z58.number().int().positive(),expiresAt:z58.string().datetime().nullable().optional(),message:z58.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z58.literal("free"),amountCents:z58.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z58.literal("purchase"),amountCents:z58.number().int().positive()}),CreditTopupRequestDTOSchema=z58.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z58.object({success:z58.boolean(),transactionId:z58.string().nullable(),newBalance:z58.number(),creditCount:z58.number(),type:z58.enum(["free","purchase"]),invoiceId:z58.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z59}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=z59.object({totalCredits:z59.number(),totalCostUsd:z59.number(),totalMessages:z59.number(),avgCostPerMessage:z59.number(),periodStart:z59.string().nullable(),periodEnd:z59.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z59.object({projectId:z59.string(),projectName:z59.string(),projectDisplayName:z59.string().nullable(),credits:z59.number(),costUsd:z59.number(),messages:z59.number(),percentage:z59.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z59.object({userId:z59.string(),userName:z59.string().nullable(),userEmail:z59.string().email().nullable(),credits:z59.number(),costUsd:z59.number(),messages:z59.number(),percentage:z59.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z59.object({date:z59.string(),credits:z59.number(),costUsd:z59.number(),messages:z59.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z59.object({userId:z59.string(),userName:z59.string().nullable(),userEmail:z59.string().email().nullable(),credits:z59.number(),costUsd:z59.number(),messages:z59.number(),percentage:z59.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z59.object({projectId:z59.string(),projectName:z59.string(),projectDisplayName:z59.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z59.array(UsageByUserForProjectDTOSchema),timeline:z59.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z59.object({summary:UsageSummaryDTOSchema,byProject:z59.array(UsageByProjectDTOSchema),byUser:z59.array(UsageByUserDTOSchema),timeline:z59.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z60}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=z60.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z60.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z60.object({startDate:z60.string().optional(),endDate:z60.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z60.coerce.number().int().positive().default(1),limit:z60.coerce.number().int().positive().max(100).default(20),sortBy:z60.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z60.string().optional()}),UsageOverviewSummaryDTOSchema=z60.object({totalCredits:z60.number(),totalCostUsd:z60.number(),totalMessages:z60.number(),avgCostPerMessage:z60.number(),avgCreditsPerMessage:z60.number(),periodStart:z60.string(),periodEnd:z60.string(),creditsChange:z60.number().nullable(),costChange:z60.number().nullable(),messagesChange:z60.number().nullable()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z60.object({date:z60.string(),credits:z60.number(),costUsd:z60.number(),messages:z60.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z60.object({organizationId:z60.string(),organizationName:z60.string(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number(),userCount:z60.number(),projectCount:z60.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z60.object({userId:z60.string(),userName:z60.string().nullable(),userEmail:z60.string().nullable(),userImage:z60.string().nullable(),organizationId:z60.string().nullable(),organizationName:z60.string().nullable(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number(),projectCount:z60.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z60.object({projectId:z60.string(),projectName:z60.string(),projectDisplayName:z60.string().nullable(),organizationId:z60.string(),organizationName:z60.string(),credits:z60.number(),costUsd:z60.number(),messages:z60.number(),percentage:z60.number(),userCount:z60.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z60.object({id:z60.string(),name:z60.string(),value:z60.number(),percentage:z60.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z60.object({day:z60.number(),hour:z60.number(),value:z60.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z60.object({summary:UsageOverviewSummaryDTOSchema,timeline:z60.array(UsageTimelinePointDTOSchema),topOrganizations:z60.array(OrganizationUsageRowDTOSchema),topUsers:z60.array(UserUsageRowDTOSchema),topProjects:z60.array(ProjectUsageRowDTOSchema),creditDistribution:z60.array(UsageDistributionItemDTOSchema),heatmap:z60.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z60.object({page:z60.number(),limit:z60.number(),totalItems:z60.number(),totalPages:z60.number(),hasMore:z60.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z60.object({organizations:z60.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z60.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z60.object({users:z60.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z60.string(),ownerName:z60.string().nullable(),ownerEmail:z60.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z60.object({projects:z60.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z60.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z60.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z60.object({credits:z60.number(),costUsd:z60.number(),messages:z60.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z60.object({id:z60.string(),name:z60.string(),createdAt:z60.string(),memberCount:z60.number(),projectCount:z60.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z60.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z60.object({id:z60.string(),name:z60.string().nullable(),email:z60.string(),image:z60.string().nullable(),createdAt:z60.string(),organizationCount:z60.number(),projectCount:z60.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z60.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z60.object({id:z60.string(),name:z60.string(),displayName:z60.string().nullable(),createdAt:z60.string(),organizationId:z60.string(),organizationName:z60.string(),ownerId:z60.string(),ownerName:z60.string().nullable(),ownerEmail:z60.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z60.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z61}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=z61.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z61.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z61.object({command:z61.string().min(1).max(1e4),cwd:z61.string().optional(),projectEnv:EnvSchema.optional(),env:z61.record(z61.string(),z61.string()).optional(),name:z61.string().optional(),waitForCompletion:z61.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z61.object({identifier:z61.string(),status:SandboxProcessStatusSchema,command:z61.string().optional(),startedAt:z61.string().optional(),exitCode:z61.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z61.object({processes:z61.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z61.object({processId:z61.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z61.object({success:z61.boolean(),message:z61.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z62}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_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:path43,message}=issue;return`${Array.isArray(path43)&&path43.length>0?`${path43.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}var ApiRequestError,UnauthorizedError,PermissionDeniedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_ENV_HEADER,FimoApiClient,init_api=__esm({"src/cli/api.ts"(){init_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,path43,status,detail,code2,body){super(`API ${method} ${path43} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path43,this.status=status,this.detail=detail,this.code=code2,this.body=body}},UnauthorizedError=class extends Error{static{__name(this,"UnauthorizedError")}apiUrl;status;constructor(apiUrl,status,message){super(message??`Session for ${apiUrl} expired or invalid (HTTP ${status}).`),this.name="UnauthorizedError",this.apiUrl=apiUrl,this.status=status}},PermissionDeniedError=class extends Error{static{__name(this,"PermissionDeniedError")}apiUrl;required;constructor(apiUrl,required=[],message){let detail=required.length?` Missing permission: ${required.join(", ")}.`:"";super(message??`You don't have permission to do this on ${apiUrl}.${detail}`),this.name="PermissionDeniedError",this.apiUrl=apiUrl,this.required=required}};__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");CLI_VERSION_HEADER="X-Fimo-CLI-Version",CLI_LATEST_HEADER="X-Fimo-CLI-Latest",CLI_AUTO_UPGRADE_HEADER="X-Fimo-CLI-Auto-Upgrade",FIMO_ENV_HEADER="X-Fimo-Env";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");FimoApiClient=class _FimoApiClient{constructor(cfg=loadConfig()){this.cfg=cfg}static{__name(this,"FimoApiClient")}env;withEnv(env){let next2=new _FimoApiClient(this.cfg);return next2.env=env,next2}formatError(status,text3,body){if(!text3)return String(status);if(body&&typeof body=="object"&&!Array.isArray(body)){let parsed=body;if(typeof parsed.message=="string"&&parsed.message.length>0){let partial=formatPartialResult(parsed);return partial?`${parsed.message} ${partial}`:parsed.message}if(typeof parsed.error=="string"&&parsed.error.length>0)return parsed.error;if(parsed.error&&typeof parsed.error=="object"&&"message"in parsed.error&&typeof parsed.error.message=="string")return parsed.error.message;let zodIssues=formatZodIssues(parsed);if(zodIssues)return zodIssues}return text3}async parseError(response){let text3=await response.text(),body;try{body=text3?JSON.parse(text3):void 0}catch{return{detail:this.formatError(response.status,text3)}}let code2=body&&typeof body=="object"&&!Array.isArray(body)&&typeof body.code=="string"?body.code:void 0;return{detail:this.formatError(response.status,text3,body),code:code2,body}}resolveAuthToken(){return process.env.FIMO_API_TOKEN?.trim()||requireToken(this.cfg)}async request(path43,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}${path43}`,{...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",path43,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async fetchRaw(path43,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}${path43}`,{...init,headers})}async rawRequest(path43,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}${path43}`,{...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"} ${path43} 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 qs=opts.includeDeleted?"?includeDeleted=true":"";return(await this.request(`/api/management/projects/${projectId}/envs${qs}`)).data}async getEnv(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`)).data}async createEnv(projectId,input){return(await this.request(`/api/management/projects/${projectId}/envs`,{method:"POST",body:JSON.stringify(input)})).data}async syncEnv(projectId,env,input={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sync`,{method:"POST",body:JSON.stringify(input)})).data}async deleteEnv(projectId,env){await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`,{method:"DELETE"})}async getEnvDiff(projectId,env,opts={}){let params=new URLSearchParams;opts.against&¶ms.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&¶ms.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff${qs?`?${qs}`:""}`)).data}async getEnvStatus(projectId,env,opts={}){let params=new URLSearchParams;opts.against&¶ms.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&¶ms.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/status${qs?`?${qs}`:""}`)).data}async getCodeFileDiff(projectId,env,path43,opts={}){let qs=lazyFetchQs(opts.against,{path:path43});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),path43=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path43}?${qs}`:path43)).data}async getSchemaTypeDiff(projectId,env,typeName,opts={}){let qs=lazyFetchQs(opts.against),path43=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path43}?${qs}`:path43)).data}async getAssetDiff(projectId,env,assetId,opts={}){let qs=lazyFetchQs(opts.against),path43=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path43}?${qs}`:path43)).data}async getTranslationRowDiff(projectId,env,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path43=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path43}?${qs}`:path43)).data}async getFormSchemaDiff(projectId,env,formName,opts={}){let qs=lazyFetchQs(opts.against),path43=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path43}?${qs}`:path43)).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){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-remote`,{},{allow403:!0})).data}async getGitCredential(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-credential`,{},{allow403:!0})).data}async getPreviewUrl(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sandbox`)).data}async sandboxPull(projectId,onProgress,env,options={}){let query=options.noRestart?"?noRestart=true":"",response=await this.rawRequest(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sandbox/pull${query}`,{method:"POST",headers:{Accept:"text/event-stream"}});if(!response.body)throw new Error("Sandbox pull failed: empty response stream");let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",errorMessage3=null,completed=!1;try{for(;;){let{value,done}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});let separatorIndex=buffer.indexOf(`
|
|
43
43
|
|
|
44
44
|
`);for(;separatorIndex!==-1;){let rawEvent=buffer.slice(0,separatorIndex);buffer=buffer.slice(separatorIndex+2),separatorIndex=buffer.indexOf(`
|
|
45
45
|
|
|
@@ -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,z68,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"),z68=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",z68)} ${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",z68)} ${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",z68)} ${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(`
|
|
@@ -254,11 +254,11 @@ ${a}${o}
|
|
|
254
254
|
${c2}`:""}`}default:{let o=i?`${t("cyan",d2)} `:"",c2=i?t("cyan",E2):"";return`${s}${o}${u2}
|
|
255
255
|
${c2}
|
|
256
256
|
`}}}}).prompt(),"Ot")}});function planRemoteConfig(remoteUrl){let u2=new URL(remoteUrl),cleanUrl=`${u2.protocol}//${u2.host}${u2.pathname}`,credentialKey=`credential.${u2.protocol}//${u2.host}`;return{cleanUrl,credentialKey}}function shellQuote(value){return`'${value.replace(/'/g,"'\\''")}'`}function credentialHelperCommand(argv=process.argv){let entry=argv[1];return entry?`!${shellQuote(process.execPath)} ${shellQuote(entry)} git-credential`:"!fimo git-credential"}async function ensureFimoRemote(cwd,remoteUrl){let{cleanUrl,credentialKey}=planRemoteConfig(remoteUrl);await runGit(["remote","set-url","fimo",cleanUrl],cwd).catch(async()=>{await runGit(["remote","add","fimo",cleanUrl],cwd)}),await runGit(["config","--unset-all",`${credentialKey}.helper`],cwd).catch(()=>{}),await runGit(["config","--add",`${credentialKey}.helper`,""],cwd),await runGit(["config","--add",`${credentialKey}.helper`,credentialHelperCommand()],cwd),await runGit(["config",`${credentialKey}.useHttpPath`,"true"],cwd),await runGit(["config",`${credentialKey}.username`,"t"],cwd)}var init_git_credential_setup=__esm({"src/cli/utils/git-credential-setup.ts"(){init_git();__name(planRemoteConfig,"planRemoteConfig");__name(shellQuote,"shellQuote");__name(credentialHelperCommand,"credentialHelperCommand");__name(ensureFimoRemote,"ensureFimoRemote")}});function isInteractive(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}function assertInteractive(hint,command="fimo"){currentMode().format==="json"&&(ui.error({command,code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in --json mode.",hint}),process.exit(1)),!isInteractive()&&(ui.error({command,code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in a non-interactive shell.",hint}),process.exit(1))}var init_interactive=__esm({"src/cli/utils/interactive.ts"(){init_dist();__name(isInteractive,"isInteractive");__name(assertInteractive,"assertInteractive")}});import fs13 from"node:fs";import path15 from"node:path";function writeLocalProjectFiles(args){let{targetDir,project,apiUrl,tenantApiUrl}=args,fimoJson={projectId:project.id,organizationId:project.organizationId,name:project.name,apiUrl},layout=resolveProjectLayoutPaths(targetDir),projectPath=path15.join(targetDir,layout.project);fs13.mkdirSync(path15.dirname(projectPath),{recursive:!0}),writeIfChanged(projectPath,`${JSON.stringify(fimoJson,null,2)}
|
|
257
|
-
`);let envPath=path15.join(targetDir,".env"),
|
|
258
|
-
`).some(line=>line.trim().startsWith(
|
|
257
|
+
`);let envPath=path15.join(targetDir,".env"),env=fs13.existsSync(envPath)?fs13.readFileSync(envPath,"utf-8"):"";for(let name of["VITE_API_URL","FIMO_API_URL","NEXT_PUBLIC_FIMO_API_URL"]){if(env.split(`
|
|
258
|
+
`).some(line=>line.trim().startsWith(`${name}=`)))continue;let prefix=env.length===0||env.endsWith(`
|
|
259
259
|
`)?"":`
|
|
260
|
-
`;
|
|
261
|
-
`)}
|
|
260
|
+
`;env=`${env}${prefix}${name}=${tenantApiUrl}
|
|
261
|
+
`}fs13.writeFileSync(envPath,env)}function seedSiteName(args){let{targetDir,project}=args,configPath=resolveProjectConfigPath(targetDir);if(fs13.existsSync(configPath))try{let original=fs13.readFileSync(configPath,"utf-8"),config=JSON.parse(original),seo=config.seo??{},existingName=typeof seo.siteName=="string"?seo.siteName:"";if(!existingName.trim()||existingName===STARTER_SITE_NAME){let initialSiteName=project.displayName?.trim()||project.name;config.seo={...seo,siteName:initialSiteName},writeIfChanged(configPath,`${JSON.stringify(config,null,2)}
|
|
262
262
|
`)}}catch{}}function writeIfChanged(filePath,content2){fs13.existsSync(filePath)&&fs13.readFileSync(filePath,"utf-8")===content2||fs13.writeFileSync(filePath,content2)}var STARTER_SITE_NAME,init_local_project_files=__esm({"src/cli/utils/local-project-files.ts"(){init_project();STARTER_SITE_NAME="Fimo Starter Site";__name(writeLocalProjectFiles,"writeLocalProjectFiles");__name(seedSiteName,"seedSiteName");__name(writeIfChanged,"writeIfChanged")}});function slugifyName(input){return input.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var init_slug=__esm({"src/cli/utils/slug.ts"(){__name(slugifyName,"slugifyName")}});import fs14 from"node:fs";import path16 from"node:path";function defaultDirectoryName(project){let source=project.displayName?.trim()||project.name||project.id;return slugifyName(source)||project.id}function explainCloneRemoteError(error){return error instanceof ApiRequestError&&error.status===403?"Only users with manage access to this project can clone it locally.":error instanceof ApiRequestError&&error.status===404?"Project or env not found.":error instanceof Error?error.message:String(error)}function chooseCloneEnv(envs,requestedEnv){return requestedEnv?envs.find(env=>env.env===requestedEnv)??null:envs.find(env=>env.env===DEFAULT_ENV)??envs[0]??null}function projectFallback(projectId){return{id:projectId,name:projectId,displayName:null,organizationId:null}}function isNotFound(error){return error instanceof ApiRequestError&&error.status===404}async function selectProjectId(args){if(currentMode().format==="json")return{status:"error",code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in --json mode.",hint:PICKER_HINT};if(!isInteractive())return{status:"error",code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in a non-interactive shell.",hint:PICKER_HINT};if(!args.activeOrganizationId)return{status:"error",code:"NO_ORGANIZATION_SPECIFIED",message:"No active organization set.",hint:"Run `fimo orgs switch`, or pass a project ID explicitly."};let listSp=spinner("Loading projects"),projects2;try{projects2=await args.api.listProjects(args.activeOrganizationId),listSp.succeed("Projects loaded")}catch(error){return listSp.fail("Could not load projects"),{status:"error",code:"PROJECT_LIST_FAILED",message:error instanceof Error?error.message:String(error)}}if(projects2.length===0)return{status:"empty",message:"No projects in the active organization yet."};let selected=await _t({message:args.message??"Select a project to clone",options:projects2.map(project=>({value:project.id,label:project.displayName??project.name,hint:project.id}))});return q(selected)?{status:"cancelled"}:{status:"selected",projectId:selected}}function projectNotFound(projectId,apiUrl){return{ok:!1,code:"PROJECT_NOT_FOUND",message:`Project ${projectId} was not found on ${apiUrl}.`,hint:"Check `fimo projects list`, or set FIMO_API_URL to the backend that owns this project."}}async function resolveRemote(args){let{api,projectId,requestedEnv,apiUrl}=args,firstEnv=requestedEnv??DEFAULT_ENV;try{return{ok:!0,env:firstEnv,remote:await api.withEnv(firstEnv).getGitRemote(projectId,firstEnv)}}catch(firstError){if(requestedEnv||!isNotFound(firstError))throw firstError;let envs;try{envs=await api.listEnvs(projectId)}catch(listError){if(isNotFound(listError))return projectNotFound(projectId,apiUrl);throw firstError}let fallbackEnv=chooseCloneEnv(envs,void 0);if(!fallbackEnv)return{ok:!1,code:"NO_CLONEABLE_ENVS",message:"This project does not have any cloneable envs.",hint:"Create an env before cloning this project."};if(fallbackEnv.env===firstEnv)throw firstError;return{ok:!0,env:fallbackEnv.env,remote:await api.withEnv(fallbackEnv.env).getGitRemote(projectId,fallbackEnv.env)}}}async function cloneProject(args){let{api,cfg,projectId,dir,env:requestedEnv}=args,remoteSp=spinner("Checking access and fetching git remote"),remote,env;try{let resolved=await resolveRemote({api,projectId,requestedEnv,apiUrl:cfg.apiUrl});if(!resolved.ok)throw remoteSp.fail("Could not fetch git remote"),new CloneError(resolved.code,resolved.message,resolved.hint);({remote,env}=resolved),remoteSp.succeed(`Remote ready (branch ${remote.branch})`)}catch(error){throw error instanceof CloneError?error:(remoteSp.fail("Could not fetch git remote"),new CloneError(error instanceof ApiRequestError&&error.status===403?"PROJECT_MANAGE_REQUIRED":"CLONE_FAILED",explainCloneRemoteError(error)))}let project=projectFallback(projectId),projectSp=spinner("Loading project details");try{project=await api.getProject(projectId),projectSp.succeed(`Project loaded (${project.displayName??project.name})`)}catch{projectSp.succeed("Project metadata unavailable; using project ID locally")}let targetDir=path16.resolve(dir??defaultDirectoryName(project));if(fs14.existsSync(targetDir)&&fs14.readdirSync(targetDir).length>0){let name=path16.basename(targetDir);throw new CloneError("DIRECTORY_NOT_EMPTY",`The folder "${name}" already exists and isn't empty.`,`Pick a different directory (e.g. \`fimo clone ${projectId} <dir>\`), or empty "${name}" first.`)}let relativeTarget=path16.relative(process.cwd(),targetDir)||".";if(!await remoteHasBranch(remote.url,remote.branch))throw new CloneError("EMPTY_REMOTE",`The project's repository has no "${remote.branch}" branch yet \u2014 its initial commit was never pushed.`,"Run `fimo init --project-id <id>` to scaffold and push it, or `fimo deploy` from an existing checkout.",{project,remote,env,targetDir,relativeTarget});let cloneSp=spinner(`Cloning ${remote.branch} into ${targetDir}`);try{await cloneRepo({url:remote.url,branch:remote.branch,targetDir}),cloneSp.succeed("Repository cloned")}catch(error){throw cloneSp.fail("Git clone failed"),isMissingRemoteBranch(error)?new CloneError("EMPTY_REMOTE",`The project's repository has no "${remote.branch}" branch yet \u2014 its initial commit was never pushed.`,"Deploy the project once (`fimo deploy` from the source checkout, or from Fimo), then clone again."):new CloneError("GIT_CLONE_FAILED",error instanceof Error?error.message:String(error))}let linkSp=spinner("Linking local project");try{let{cleanUrl}=planRemoteConfig(remote.url);await runGit(["remote","set-url","origin",cleanUrl],targetDir).catch(()=>{}),await ensureFimoRemote(targetDir,remote.url),writeLocalProjectFiles({targetDir,project,apiUrl:cfg.apiUrl,tenantApiUrl:remote.tenantApiUrl}),linkSp.succeed("Local project linked")}catch(error){throw linkSp.fail("Local project link failed"),new CloneError("PROJECT_LINK_FAILED",error instanceof Error?error.message:String(error))}return{project,env,branch:remote.branch,targetDir,relativeTarget}}async function cloneCommand(projectIdArg,dirArg,options={}){let cfg=loadConfig(),creds=requireCredentials(cfg),api=new FimoApiClient(cfg),projectId=projectIdArg;if(!projectId){let picked=await selectProjectId({api,activeOrganizationId:creds?.activeOrganization?.id});switch(picked.status){case"selected":projectId=picked.projectId;break;case"cancelled":ui.info({command:"clone",message:"Cancelled."});return;case"empty":ui.info({command:"clone",message:picked.message});return;case"error":ui.error({command:"clone",code:picked.code,message:picked.message,...picked.hint?{hint:picked.hint}:{}});return}}currentMode().format==="pretty"&&mt(`Cloning Fimo project ${projectId}`);let result;try{result=await cloneProject({api,cfg,projectId,dir:dirArg,env:options.env})}catch(error){if(error instanceof CloneError){ui.error({command:"clone",code:error.code,message:error.message,hint:error.hint});return}throw error}let{project,env,branch,targetDir,relativeTarget}=result;ui.ok({command:"clone",headline:`Project ${project.displayName??project.name} cloned.`,details:{project_id:project.id,project_name:project.name,display_name:project.displayName,organization_id:project.organizationId,env,branch,target_dir:targetDir,relative_dir:relativeTarget},hint:`cd ${relativeTarget}`})}var CloneError,PICKER_HINT,init_clone=__esm({"src/cli/commands/clone.ts"(){init_dist5();init_esm();init_dist();init_api();init_auth();init_config();init_git_credential_setup();init_git();init_interactive();init_local_project_files();init_slug();CloneError=class extends Error{static{__name(this,"CloneError")}code;hint;emptyRemote;constructor(code2,message,hint,emptyRemote){super(message),this.name="CloneError",this.code=code2,this.hint=hint,this.emptyRemote=emptyRemote}};__name(defaultDirectoryName,"defaultDirectoryName");__name(explainCloneRemoteError,"explainCloneRemoteError");__name(chooseCloneEnv,"chooseCloneEnv");__name(projectFallback,"projectFallback");__name(isNotFound,"isNotFound");PICKER_HINT="Pass a project ID explicitly, e.g. `fimo clone <projectId>`.";__name(selectProjectId,"selectProjectId");__name(projectNotFound,"projectNotFound");__name(resolveRemote,"resolveRemote");__name(cloneProject,"cloneProject");__name(cloneCommand,"cloneCommand")}});var require_common=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/common.js"(exports2,module2){"use strict";function isNothing(subject){return typeof subject>"u"||subject===null}__name(isNothing,"isNothing");function isObject(subject){return typeof subject=="object"&&subject!==null}__name(isObject,"isObject");function toArray2(sequence){return Array.isArray(sequence)?sequence:isNothing(sequence)?[]:[sequence]}__name(toArray2,"toArray");function extend(target,source){var index2,length,key,sourceKeys;if(source)for(sourceKeys=Object.keys(source),index2=0,length=sourceKeys.length;index2<length;index2+=1)key=sourceKeys[index2],target[key]=source[key];return target}__name(extend,"extend");function repeat(string2,count){var result="",cycle;for(cycle=0;cycle<count;cycle+=1)result+=string2;return result}__name(repeat,"repeat");function isNegativeZero(number2){return number2===0&&Number.NEGATIVE_INFINITY===1/number2}__name(isNegativeZero,"isNegativeZero");module2.exports.isNothing=isNothing;module2.exports.isObject=isObject;module2.exports.toArray=toArray2;module2.exports.repeat=repeat;module2.exports.isNegativeZero=isNegativeZero;module2.exports.extend=extend}});var require_exception=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/exception.js"(exports2,module2){"use strict";function YAMLException(reason,mark){Error.call(this),this.name="YAMLException",this.reason=reason,this.mark=mark,this.message=(this.reason||"(unknown reason)")+(this.mark?" "+this.mark.toString():""),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}__name(YAMLException,"YAMLException");YAMLException.prototype=Object.create(Error.prototype);YAMLException.prototype.constructor=YAMLException;YAMLException.prototype.toString=__name(function(compact){var result=this.name+": ";return result+=this.reason||"(unknown reason)",!compact&&this.mark&&(result+=" "+this.mark.toString()),result},"toString");module2.exports=YAMLException}});var require_mark=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/mark.js"(exports2,module2){"use strict";var common=require_common();function Mark(name,buffer,position,line,column){this.name=name,this.buffer=buffer,this.position=position,this.line=line,this.column=column}__name(Mark,"Mark");Mark.prototype.getSnippet=__name(function(indent,maxLength){var head,start,tail,end2,snippet;if(!this.buffer)return null;for(indent=indent||4,maxLength=maxLength||75,head="",start=this.position;start>0&&`\0\r
|
|
263
263
|
\x85\u2028\u2029`.indexOf(this.buffer.charAt(start-1))===-1;)if(start-=1,this.position-start>maxLength/2-1){head=" ... ",start+=5;break}for(tail="",end2=this.position;end2<this.buffer.length&&`\0\r
|
|
264
264
|
\x85\u2028\u2029`.indexOf(this.buffer.charAt(end2))===-1;)if(end2+=1,end2-this.position>maxLength/2-1){tail=" ... ",end2-=5;break}return snippet=this.buffer.slice(start,end2),common.repeat(" ",indent)+head+snippet+tail+`
|
|
@@ -358,7 +358,7 @@ return __eta.res;
|
|
|
358
358
|
`)}}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(`
|
|
359
359
|
`).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,`
|
|
360
360
|
`).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(path43){let res="";try{res=fs16.readFileSync(path43,"utf8")}catch(err){throw err?.code==="ENOENT"?new EtaFileResolutionError(`Could not find template: ${path43}`):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+=path18.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=path18.join(views,formattedPath)}else resolvedFilePath=path18.join(path18.dirname(baseFilePath),templatePath2)}else resolvedFilePath=path18.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=path18.relative(parent2,dir);return relative3&&!relative3.startsWith("..")&&!path18.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(path43){try{return JSON.parse(readFileSync4(path43,"utf-8"))}catch{return null}}function generateIndexContent(forms3){let lines=["// AUTO-GENERATED \u26A0\uFE0F \u2014 do not edit by hand",""];for(let form of forms3){let pascal=pascalCase(form.name),varName=pascal.charAt(0).toLowerCase()+pascal.slice(1);lines.push(`export { ${pascal}Schema, submit${pascal}, FORM_ID as ${varName}FormId } from "./${form.name}";`),lines.push(`export type { ${pascal}Data } from "./${form.name}";`)}return lines.push(""),lines.join(`
|
|
361
|
-
`)}function syncForms(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),formsDir=resolve4(cwd,FORMS_REL),templatePath2=assetPath("content-templates","form-template.eta"),templateSource=readFileSync4(templatePath2,"utf-8"),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),formFiles=getFormFiles(formsDir),expectedTsFiles=new Set,allForms=[],created=0,updated=0,deleted=0;for(let jsonPath of formFiles){let form=readForm(jsonPath);if(!form){console.error(`Failed to parse form: ${jsonPath}`);continue}form.name||(form.name=jsonPath.split("/").pop().replace(/\.json$/,"")),allForms.push(form);let tsPath=join5(formsDir,`${form.name}.ts`);expectedTsFiles.add(tsPath);try{let content2=eta.renderString(templateSource,{form:{...form,pascal:pascalCase(form.name)}}),dir=dirname4(tsPath);if(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_dist7();init_eta_module();init_assets();FORMS_REL="src/forms";__name(getFormFiles,"getFormFiles");__name(readForm,"readForm");__name(generateIndexContent,"generateIndexContent");__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
|
|
361
|
+
`)}function syncForms(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),formsDir=resolve4(cwd,FORMS_REL),templatePath2=assetPath("content-templates","form-template.eta"),templateSource=readFileSync4(templatePath2,"utf-8"),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),formFiles=getFormFiles(formsDir),expectedTsFiles=new Set,allForms=[],created=0,updated=0,deleted=0;for(let jsonPath of formFiles){let form=readForm(jsonPath);if(!form){console.error(`Failed to parse form: ${jsonPath}`);continue}form.name||(form.name=jsonPath.split("/").pop().replace(/\.json$/,"")),allForms.push(form);let tsPath=join5(formsDir,`${form.name}.ts`);expectedTsFiles.add(tsPath);try{let content2=eta.renderString(templateSource,{form:{...form,pascal:pascalCase(form.name)}}),dir=dirname4(tsPath);if(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_dist7();init_eta_module();init_assets();FORMS_REL="src/forms";__name(getFormFiles,"getFormFiles");__name(readForm,"readForm");__name(generateIndexContent,"generateIndexContent");__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 z69}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")}}function contentRuntimeImportFor(framework){return framework==="nextjs"?"fimo/next":"fimo/ui"}function templatePath(runtime,fileName){return runtime&&!isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)?join6(runtime.packageRoot,"assets","content-templates",fileName):assetPath("content-templates",fileName)}function resolveSchemaGenerationTarget(runtimeImport,runtime){if(runtimeImport==="fimo/ui")return"react";if(!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.`);return"next"}function templatesForTarget(target,runtime,runtimeImport){return target==="next"?[{suffix:".types.ts",path:templatePath(runtime,"types-template.eta"),runtimeImport:"fimo/next"},{suffix:".ts",path:templatePath(runtime,"next-server-template.eta"),runtimeImport:"fimo/next"},{suffix:".client.ts",path:templatePath(runtime,"next-client-template.eta"),runtimeImport:"fimo/next/client"}]:[{suffix:".types.ts",path:templatePath(runtime,"types-template.eta"),runtimeImport},{suffix:".ts",path:templatePath(runtime,"hooks-template.eta"),runtimeImport}]}function loadSchemas(schemaFiles){let errors=[],schemas3=[],outputOwners=new Map,registryOwners=new Map;for(let path43 of schemaFiles){let fileUid=basename(path43,".json"),pascal=pascalCase(fileUid),existingOwner=outputOwners.get(pascal);existingOwner&&existingOwner!==fileUid?errors.push(`${basename(path43)} 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(path43,"utf-8"))}catch(error){errors.push(`${basename(path43)} is invalid JSON: ${error instanceof Error?error.message:String(error)}`);continue}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){errors.push(`${basename(path43)} must contain a JSON object.`);continue}let candidate=parsed;if(typeof candidate.uid!="string"||candidate.uid.length===0){errors.push(`${basename(path43)} is missing "uid". Set it to "${fileUid}".`);continue}if(candidate.uid!==fileUid){errors.push(`${basename(path43)} 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(path43)} 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(path43)} 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:
|
|
362
362
|
- ${errors.join(`
|
|
363
363
|
- `)}
|
|
364
364
|
No generated files were changed.`);return schemas3}function renderContentRegistry(schemas3){let imports=schemas3.map(({pascal})=>`import * as ${pascal} from "./${pascal}";`).join(`
|
|
@@ -371,7 +371,7 @@ ${imports}
|
|
|
371
371
|
export const content = {
|
|
372
372
|
${entries2}
|
|
373
373
|
} as const;
|
|
374
|
-
`}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,needsNextRegistry=generationTarget==="next"&&schemas3.length>0,ownsExistingRegistry=existsSync5(registryPath)&&readFileSync5(registryPath,"utf-8").startsWith(GENERATED_REGISTRY_MARKER),shouldGenerateRegistry=needsNextRegistry&&(!existsSync5(registryPath)||ownsExistingRegistry);needsNextRegistry&&!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,init_sync_schemas=__esm({"src/scripts/sync-schemas.ts"(){init_dist7();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=
|
|
374
|
+
`}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,needsNextRegistry=generationTarget==="next"&&schemas3.length>0,ownsExistingRegistry=existsSync5(registryPath)&&readFileSync5(registryPath,"utf-8").startsWith(GENERATED_REGISTRY_MARKER),shouldGenerateRegistry=needsNextRegistry&&(!existsSync5(registryPath)||ownsExistingRegistry);needsNextRegistry&&!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,init_sync_schemas=__esm({"src/scripts/sync-schemas.ts"(){init_dist7();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=z69.object({uid:z69.string().min(1),name:z69.string().min(1).optional(),isSingleton:z69.boolean().optional(),i18n:z69.object({enabled:z69.boolean().optional()}).optional(),fields:z69.record(z69.string(),z69.unknown()).optional()});__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(`
|
|
375
375
|
`)}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(`
|
|
376
376
|
`);if(delta.status==="failed")return lines.push(p2.red(` (surface check failed: ${delta.error??"unknown"})`)),lines.join(`
|
|
377
377
|
`);if(delta.status==="unchanged"||delta.changedCount===0&&delta.conflictCount===0)return lines.push(p2.dim(display.emptyCopy)),lines.join(`
|
|
@@ -1162,7 +1162,7 @@ ${html3}`.toLowerCase();return haystack.includes("webflow")||haystack.includes("
|
|
|
1162
1162
|
`)}function readGeneratedArtifacts(cwd){let artifactsPath=path37.join(cwd,GENERATED_ARTIFACTS_PATH);if(!fs37.existsSync(artifactsPath))return null;try{return JSON.parse(fs37.readFileSync(artifactsPath,"utf8"))}catch{return null}}function readMediaMap(cwd,manifest){let mediaMapPath=manifest.assets.manifest;if(!mediaMapPath)return[];let fullPath=path37.join(cwd,mediaMapPath);if(!fs37.existsSync(fullPath))return[];try{let parsed=JSON.parse(fs37.readFileSync(fullPath,"utf8"));return Array.isArray(parsed)?parsed.filter(isMigrationMediaMapAsset):[]}catch{return[]}}function isMigrationMediaMapAsset(value){return isRecord2(value)&&typeof value.sourceUrl=="string"&&(typeof value.fileName=="string"||value.fileName===void 0)&&(typeof value.localPath=="string"||value.localPath===null)&&typeof value.status=="string"}function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function resolveGeneratedPageModule(cwd,routePath,generatedArtifacts){let expected=path37.join(cwd,"src","pages","migrated",`${pageComponentName2(routePath)}.tsx`);if(fs37.existsSync(expected))return expected;let pageFiles=generatedArtifacts?.pageFiles??[],expectedBase=`${pageComponentName2(routePath)}.tsx`,fallback=pageFiles.map(relativePath=>path37.join(cwd,relativePath)).find(filePath=>path37.basename(filePath)===expectedBase);return fallback&&fs37.existsSync(fallback)?fallback:null}function detectCurrentTemplate(targetModule){return!targetModule||!fs37.existsSync(targetModule)?"custom-or-missing":fs37.readFileSync(targetModule,"utf8").includes("MigrationPageTemplate")?"generic-migration-template":"custom-or-missing"}function routeToBriefFile(routePath){return routePath==="/"?"home":slugify3(routePath.replace(/^\//,"").replace(/\//g,"-"))||"page"}function normalizeRoute(routePath){if(!routePath)return"/";let trimmed=routePath.trim();return trimmed==="/"?"/":`/${trimmed.replace(/^\/+/,"").replace(/\/+$/,"")}`}function normalizeUrlForMatch(value){try{let url=new URL(value);return url.hash="",url.toString()}catch{return value}}function cleanText3(value){return value.replace(/\s+/g," ").trim()}function shouldKeepAction(label){return label.length>=2&&label.length<=80}function absolutizeHref(value,baseUrl){if(!value||value.startsWith("#")||value.startsWith("javascript:")||value.startsWith("mailto:"))return value;try{return new URL(value,baseUrl).toString()}catch{return value}}function writeFile3(cwd,relativePath,content2,written){let fullPath=path37.join(cwd,relativePath);fs37.mkdirSync(path37.dirname(fullPath),{recursive:!0}),fs37.writeFileSync(fullPath,content2,"utf8"),written.push(relativePath)}function unique3(values){let seen=new Set,result=[];for(let value of values){let normalized=value.trim();!normalized||seen.has(normalized)||(seen.add(normalized),result.push(normalized))}return result}function uniqueLinkObjects(values){let seen=new Set,result=[];for(let value of values){let key=`${value.label}::${value.href??""}`;seen.has(key)||(seen.add(key),result.push(value))}return result}function uniqueActionObjects(values){let seen=new Set,result=[];for(let value of values){let key=`${value.kind}::${value.label}::${value.href??""}`;seen.has(key)||(seen.add(key),result.push(value))}return result}function uniqueImageObjects3(values){let seen=new Set,result=[];for(let value of values){let key=`${value.src}::${value.alt??""}`;seen.has(key)||(seen.add(key),result.push(value))}return result}function pageComponentName2(routePath){if(routePath==="/")return"HomePage";let normalized=`${routePath.replace(/^\//,"").split("/").filter(Boolean).map(part=>titleize3(part).replace(/\s+/g,"")).join("")||"Page"}Page`;return/^[A-Za-z_$]/.test(normalized)?normalized:`Route${normalized}`}function titleize3(value){return value.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,match=>match.toUpperCase())}function slugify3(value){return value.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function toPosix3(value){return value.split(path37.sep).join("/")}var REFINE_ROOT,PAGE_BRIEFS_DIR,GENERATED_ARTIFACTS_PATH,init_migrate_refine=__esm({"src/cli/commands/migrate-refine.ts"(){init_dist();init_slim();init_migrate();REFINE_ROOT=path37.join(MIGRATION_DIR2,"refine"),PAGE_BRIEFS_DIR=path37.join(REFINE_ROOT,"pages"),GENERATED_ARTIFACTS_PATH=path37.join(MIGRATION_DIR2,"generated","artifacts.json");__name(migrateRefineCommand,"migrateRefineCommand");__name(prepareMigrationRefineArtifacts,"prepareMigrationRefineArtifacts");__name(selectPagesForRefine,"selectPagesForRefine");__name(writePageBrief,"writePageBrief");__name(analyzeSourceHtml,"analyzeSourceHtml");__name(buildPageBrief,"buildPageBrief");__name(buildAgentPrompt,"buildAgentPrompt");__name(readGeneratedArtifacts,"readGeneratedArtifacts");__name(readMediaMap,"readMediaMap");__name(isMigrationMediaMapAsset,"isMigrationMediaMapAsset");__name(isRecord2,"isRecord");__name(resolveGeneratedPageModule,"resolveGeneratedPageModule");__name(detectCurrentTemplate,"detectCurrentTemplate");__name(routeToBriefFile,"routeToBriefFile");__name(normalizeRoute,"normalizeRoute");__name(normalizeUrlForMatch,"normalizeUrlForMatch");__name(cleanText3,"cleanText");__name(shouldKeepAction,"shouldKeepAction");__name(absolutizeHref,"absolutizeHref");__name(writeFile3,"writeFile");__name(unique3,"unique");__name(uniqueLinkObjects,"uniqueLinkObjects");__name(uniqueActionObjects,"uniqueActionObjects");__name(uniqueImageObjects3,"uniqueImageObjects");__name(pageComponentName2,"pageComponentName");__name(titleize3,"titleize");__name(slugify3,"slugify");__name(toPosix3,"toPosix")}});function syncStateColor(state,p2){switch(state){case"in-sync":return p2.green("in sync");case"ahead":return p2.blue("ahead");case"behind":return p2.yellow("behind");case"diverged":return p2.red("diverged");default:return p2.dim("unknown")}}function renderStatus2(report,p2,opts={}){let lines=[],sep2=opts.ascii?"|":"\xB7",header=`${p2.bold(`env: ${report.env}`)} ${p2.dim(`vs ${report.vs} ${sep2}`)} ${syncStateColor(report.syncState,p2)}`;if(lines.push(header),lines.push(""),opts.short){for(let name of SURFACE_NAMES){if(opts.surface&&opts.surface!==name)continue;let delta=report.surfaces.find(s=>s.surface===name);if(!delta)continue;let innerSep=opts.ascii?"|":"\xB7",counts=`${delta.changedCount} changed${delta.conflictCount>0?` ${innerSep} ${delta.conflictCount} conflicts`:""}`,truncatedHint=delta.truncated&&delta.items&&delta.items.length<delta.changedCount?p2.dim(` ${innerSep} ${delta.items.length} of ${delta.changedCount} shown`):"";lines.push(` ${p2.bold(name.padEnd(14))} ${p2.dim(counts)}${truncatedHint}`)}return lines.join(`
|
|
1163
1163
|
`)}let surfaceOpts={ascii:opts.ascii,...opts.all?{maxItems:Number.MAX_SAFE_INTEGER}:{}};for(let name of SURFACE_NAMES){if(opts.surface&&opts.surface!==name)continue;let delta=report.surfaces.find(s=>s.surface===name);delta&&(lines.push(renderSurface(delta,p2,surfaceOpts)),lines.push(""))}if(!opts.surface&&report.crossSurface&&report.crossSurface.length>0&&(lines.push(renderCrossSurface(report.crossSurface,p2,{ascii:opts.ascii})),lines.push("")),report.agents&&report.agents.length>0){lines.push(p2.bold("AGENTS")),lines.push(p2.dim(" declared \xB7 active \xB7 last run"));for(let agent of report.agents){let status=agent.status==="active"?p2.green("active"):agent.status==="paused"?p2.yellow("paused"):p2.red("failed"),lastRun=agent.lastRunAt?p2.dim(new Date(agent.lastRunAt).toISOString().slice(0,19)+"Z"):p2.dim("never");lines.push(` ${agent.name.padEnd(18)} ${status.padEnd(7)} ${lastRun}`)}lines.push("")}return lines.join(`
|
|
1164
1164
|
`).replace(/\n+$/,"")}var init_render_status=__esm({"src/cli/utils/format/render-status.ts"(){init_esm();init_cross_surface();init_surface();__name(syncStateColor,"syncStateColor");__name(renderStatus2,"renderStatus")}});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(`
|
|
1165
|
-
`).filter(Boolean).map(line=>{let code2=line.slice(0,2),path43=line.slice(3).trim();return{verb:code2.startsWith("A")||code2.startsWith("?")?"added":code2.startsWith("D")?"removed":"changed",key:path43,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),serverPromise=withSoftTimeout(api.getEnvStatus(ctx.projectId,ctx.env,{against:options.vs,surfaces}),SOFT_TIMEOUT_MS*15),[local,serverResult]=await Promise.all([codePromise,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,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});return renderStatus2(merged,p2,{short:options.short,surface:surfaces?.length===1?surfaces[0]:void 0,all:options.all,ascii:rctx.ascii})},"render")})}var SOFT_TIMEOUT_MS,init_status=__esm({"src/cli/commands/status.ts"(){init_dist();init_api();init_color();init_render_status();init_git();init_project_context();init_project();SOFT_TIMEOUT_MS=2e3;__name(pickSurfaces,"pickSurfaces");__name(withSoftTimeout,"withSoftTimeout");__name(localCodeSurface,"localCodeSurface");__name(mergeCodeSurfaces,"mergeCodeSurfaces");__name(statusCommand2,"statusCommand")}});init_dist();import fs42 from"node:fs";import path42 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 z62}from"zod";var CapabilityTokenSchema=z62.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=z62.array(CapabilityTokenSchema);import{z as z63}from"zod";var CronTriggerSchema=z63.object({type:z63.literal("schedule"),cron:z63.string().min(1,"cron expression required"),tz:z63.string().optional()}),ManualTriggerSchema2=z63.object({type:z63.literal("manual")}),WebhookTriggerSchema2=z63.object({type:z63.literal("webhook"),path:z63.string().min(1).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z63.discriminatedUnion("type",[ManualTriggerSchema2,CronTriggerSchema,WebhookTriggerSchema2]),SubAgentRefSchema=z63.object({name:z63.string().min(1),capability_grant:z63.enum(["inherit","explicit"]).optional(),explicit_grants:z63.array(z63.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=z63.object({"sub-agents":z63.array(SubAgentRefSchema)}),RuntimeConfigSchema=z63.object({cloud:z63.boolean().optional(),dev:z63.boolean().optional(),long_running:z63.boolean().optional()}),DataSourceSchema=z63.enum(["main","prod"]),ConfigValueKeySchema=z63.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=z63.preprocess(value=>typeof value=="string"?{key:value}:value,z63.object({key:ConfigValueKeySchema.refine(key=>!PUBLIC_CONFIG_PREFIX.test(key),{message:"agent secrets cannot use public variable prefixes (PUBLIC_, VITE_, NEXT_PUBLIC_)"}),required:z63.boolean().default(!0),delivery:z63.literal("process_env").default("process_env")})),IntegrationKeySchema=z63.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*$/,"integration keys must be lowercase alphanumeric with optional _ or -"),IntegrationToolKeySchema=z63.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=z63.preprocess(value=>typeof value=="boolean"?{enabled:value}:value,z63.object({enabled:z63.boolean().default(!0),tools:z63.record(IntegrationToolKeySchema,z63.boolean()).optional()})),IntegrationPolicySchema=z63.record(IntegrationKeySchema,IntegrationPolicyEntrySchema),AgentConfigSchema=z63.object({version:z63.literal(1),description:z63.string().min(1).max(280).optional(),runtime:RuntimeConfigSchema.optional(),triggers:z63.array(TriggerSchema2).optional(),composition:CompositionConfigSchema.optional(),data_sources:z63.array(DataSourceSchema).optional(),secrets:z63.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",description:"Read project files"},{token:"files:write",risk:"medium",description:"Write or delete project files"},{token:"cms:read",risk:"low",description:"Read CMS content"},{token:"cms:write",risk:"medium",description:"Create, update, or delete CMS entries"},{token:"cms:schema:read",risk:"low",description:"Read CMS schemas"},{token:"cms:schema:write",risk:"high",description:"Modify CMS schemas (destructive \u2014 alters all entries of the type)"},{token:"assets:read",risk:"low",description:"Read uploaded media"},{token:"assets:write",risk:"medium",description:"Upload, replace, or delete media"},{token:"i18n:read",risk:"low",description:"Read translation catalogs"},{token:"i18n:write",risk:"medium",description:"Modify translation catalogs via the fimo i18n CLI"},{token:"forms:read",risk:"low",description:"Read form schemas and submissions"},{token:"forms:write",risk:"medium",description:"Modify form schemas or clear submissions"},{token:"webhooks:read",risk:"low",description:"Read webhook configurations and delivery history"},{token:"webhooks:write",risk:"high",description:"Create, modify, delete, or trigger webhooks that send project data to external URLs"},{token:"schedules:read",risk:"low",description:"Read schedule configurations and run history"},{token:"schedules:write",risk:"critical",description:"Create, modify, delete, or trigger scheduled commands that run with publish and code-edit rights"},{token:"git:read",risk:"low",description:"Read git state"},{token:"git:branch",risk:"medium",description:"Create agent-proposed branches off main"},{token:"git:commit",risk:"medium",description:"Commit changes to an agent branch"},{token:"git:push",risk:"high",description:"Push to the project remote (main push is intercepted)"},{token:"git:tag",risk:"high",runtimeOnly:!0,description:"Used by runtime for prod release tags; agents cannot call directly"},{token:"fimo:deploy",risk:"critical",description:"Trigger a production deploy"},{token:"fimo:logs:read",risk:"low",description:"Read production logs"},{token:"fimo:analytics:read",risk:"low",description:"Read analytics data"},{token:"fimo:preview:read",risk:"low",description:"Read a current preview URL for an env (no commit, no deploy)"},{token:"net:fetch",risk:"medium",description:"Make outbound HTTP requests"},{token:"integrations:run",risk:"high",description:"Run enabled project integration tools allowed by the agent policy"},{token:"shell:exec",risk:"high",description:"Run arbitrary shell commands inside the sandbox"},{token:"agent:delegate",risk:"medium",description:"Invoke declared sub-agents"},{token:"runtime:long_running",risk:"high",description:"Run autonomously past the default 30 min limit (up to 4h walltime / 12h ceiling)"},{token:"runtime:auto_merge",risk:"critical",description:"Auto-merge trivial proposed branches to main without per-change human review"}],BY_TOKEN=new Map(ENTRIES.map(e=>[e.token,e])),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 isRuntimeOnly(token){return getCapability(token)?.runtimeOnly===!0}__name(isRuntimeOnly,"isRuntimeOnly");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}isRuntimeOnly(token)&&issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is runtime-orchestration-only; agents cannot declare it (the runtime intercepts)`,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=[],runtimeOnly=[],highRisk=[];for(let token of tokens){let def=byToken.get(token);if(!def){unknown2.push(token);continue}def.runtimeOnly&&runtimeOnly.push(token),(def.risk==="high"||def.risk==="critical")&&highRisk.push(token)}return{ok:unknown2.length===0&&runtimeOnly.length===0,unknown:unknown2,runtimeOnly,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 z64}from"zod";var SurfaceGuardPolicySchema=z64.enum(["block","warn","allow"]),ClassificationSchema=z64.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z64.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z64.object({enabled:z64.boolean(),allowed_skills:z64.array(z64.string().min(1)).default([]),allowed_classifications:z64.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z64.enum(["off","daily","weekly"]),NotificationFormatSchema=z64.object({markdown:z64.boolean().default(!0),html:z64.boolean().default(!1)}),NotificationsPolicySchema=z64.object({email_recipients:z64.array(z64.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z64.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z64.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 z65}from"zod";function toSpec(def){return{token:def.token,riskTier:def.risk,description:def.description,...def.runtimeOnly?{runtimeOnly:!0}:{}}}__name(toSpec,"toSpec");var VOCABULARY=Object.freeze(Object.fromEntries(CAPABILITY_VOCABULARY.filter(d3=>!d3.runtimeOnly).map(d3=>[d3.token,toSpec(d3)]))),CapabilityToken=z65.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z65.array(CapabilityToken);function isCapability(token){return Object.prototype.hasOwnProperty.call(VOCABULARY,token)}__name(isCapability,"isCapability");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","git.push":"git:push","shell.exec":"shell:exec","fimo.deploy":"fimo:deploy","fimo.logs.read":"fimo:logs:read","fimo.analytics.read":"fimo:analytics:read","fimo.preview.url":"fimo:preview: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
|
|
1165
|
+
`).filter(Boolean).map(line=>{let code2=line.slice(0,2),path43=line.slice(3).trim();return{verb:code2.startsWith("A")||code2.startsWith("?")?"added":code2.startsWith("D")?"removed":"changed",key:path43,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),serverPromise=withSoftTimeout(api.getEnvStatus(ctx.projectId,ctx.env,{against:options.vs,surfaces}),SOFT_TIMEOUT_MS*15),[local,serverResult]=await Promise.all([codePromise,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,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});return renderStatus2(merged,p2,{short:options.short,surface:surfaces?.length===1?surfaces[0]:void 0,all:options.all,ascii:rctx.ascii})},"render")})}var SOFT_TIMEOUT_MS,init_status=__esm({"src/cli/commands/status.ts"(){init_dist();init_api();init_color();init_render_status();init_git();init_project_context();init_project();SOFT_TIMEOUT_MS=2e3;__name(pickSurfaces,"pickSurfaces");__name(withSoftTimeout,"withSoftTimeout");__name(localCodeSurface,"localCodeSurface");__name(mergeCodeSurfaces,"mergeCodeSurfaces");__name(statusCommand2,"statusCommand")}});init_dist();import fs42 from"node:fs";import path42 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 z63}from"zod";var CapabilityTokenSchema=z63.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=z63.array(CapabilityTokenSchema);import{z as z64}from"zod";var CronTriggerSchema=z64.object({type:z64.literal("schedule"),cron:z64.string().min(1,"cron expression required"),tz:z64.string().optional()}),ManualTriggerSchema2=z64.object({type:z64.literal("manual")}),WebhookTriggerSchema2=z64.object({type:z64.literal("webhook"),path:z64.string().min(1).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z64.discriminatedUnion("type",[ManualTriggerSchema2,CronTriggerSchema,WebhookTriggerSchema2]),SubAgentRefSchema=z64.object({name:z64.string().min(1),capability_grant:z64.enum(["inherit","explicit"]).optional(),explicit_grants:z64.array(z64.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=z64.object({"sub-agents":z64.array(SubAgentRefSchema)}),RuntimeConfigSchema=z64.object({cloud:z64.boolean().optional(),dev:z64.boolean().optional(),long_running:z64.boolean().optional()}),DataSourceSchema=z64.enum(["main","prod"]),ConfigValueKeySchema=z64.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=z64.preprocess(value=>typeof value=="string"?{key:value}:value,z64.object({key:ConfigValueKeySchema.refine(key=>!PUBLIC_CONFIG_PREFIX.test(key),{message:"agent secrets cannot use public variable prefixes (PUBLIC_, VITE_, NEXT_PUBLIC_)"}),required:z64.boolean().default(!0),delivery:z64.literal("process_env").default("process_env")})),IntegrationKeySchema=z64.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*$/,"integration keys must be lowercase alphanumeric with optional _ or -"),IntegrationToolKeySchema=z64.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=z64.preprocess(value=>typeof value=="boolean"?{enabled:value}:value,z64.object({enabled:z64.boolean().default(!0),tools:z64.record(IntegrationToolKeySchema,z64.boolean()).optional()})),IntegrationPolicySchema=z64.record(IntegrationKeySchema,IntegrationPolicyEntrySchema),AgentConfigSchema=z64.object({version:z64.literal(1),description:z64.string().min(1).max(280).optional(),runtime:RuntimeConfigSchema.optional(),triggers:z64.array(TriggerSchema2).optional(),composition:CompositionConfigSchema.optional(),data_sources:z64.array(DataSourceSchema).optional(),secrets:z64.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",runtimeOnly:!0,description:"Read project files"},{token:"files:write",risk:"medium",runtimeOnly:!0,description:"Write or delete project files"},{token:"cms:read",risk:"low",description:"Read CMS content"},{token:"cms:write",risk:"medium",description:"Create, update, or delete CMS entries"},{token:"cms:schema:read",risk:"low",description:"Read CMS schemas"},{token:"cms:schema:write",risk:"high",description:"Modify CMS schemas (destructive \u2014 alters all entries of the type)"},{token:"assets:read",risk:"low",description:"Read uploaded media"},{token:"assets:write",risk:"medium",description:"Upload, replace, or delete media"},{token:"i18n:read",risk:"low",description:"Read translation catalogs"},{token:"i18n:write",risk:"medium",description:"Modify translation catalogs via the fimo i18n CLI"},{token:"forms:read",risk:"low",description:"Read form schemas and submissions"},{token:"forms:write",risk:"medium",description:"Modify form schemas or clear submissions"},{token:"webhooks:read",risk:"low",description:"Read webhook configurations and delivery history"},{token:"webhooks:write",risk:"high",description:"Create, modify, delete, or trigger webhooks that send project data to external URLs"},{token:"schedules:read",risk:"low",description:"Read schedule configurations and run history"},{token:"schedules:write",risk:"critical",description:"Create, modify, delete, or trigger scheduled commands that run with publish and code-edit rights"},{token:"git:read",risk:"low",runtimeOnly:!0,description:"Read git state"},{token:"git:branch",risk:"medium",runtimeOnly:!0,description:"Create agent-proposed branches off main"},{token:"git:commit",risk:"medium",runtimeOnly:!0,description:"Commit changes to an agent branch"},{token:"git:push",risk:"high",runtimeOnly:!0,description:"Push to the project remote (main push is intercepted)"},{token:"git:tag",risk:"high",runtimeOnly:!0,description:"Used by runtime for prod release tags; agents cannot call directly"},{token:"fimo:deploy",risk:"critical",description:"Trigger a production deploy"},{token:"fimo:logs:read",risk:"low",description:"Read production logs"},{token:"fimo:analytics:read",risk:"low",description:"Read analytics data"},{token:"fimo:preview:read",risk:"low",description:"Read a current preview URL for an env (no commit, no deploy)"},{token:"net:fetch",risk:"medium",description:"Make outbound HTTP requests"},{token:"integrations:run",risk:"high",description:"Run enabled project integration tools allowed by the agent policy"},{token:"shell:exec",risk:"high",runtimeOnly:!0,description:"Run arbitrary shell commands inside the sandbox"},{token:"agent:delegate",risk:"medium",description:"Invoke declared sub-agents"},{token:"runtime:long_running",risk:"high",description:"Run autonomously past the default 30 min limit (up to 4h walltime / 12h ceiling)"},{token:"runtime:auto_merge",risk:"critical",description:"Auto-merge trivial proposed branches to main without per-change human review"}],BY_TOKEN=new Map(ENTRIES.map(e=>[e.token,e])),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 isRuntimeOnly(token){return getCapability(token)?.runtimeOnly===!0}__name(isRuntimeOnly,"isRuntimeOnly");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}isRuntimeOnly(token)&&issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is runtime-orchestration-only; agents cannot declare it (the runtime intercepts)`,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=[],runtimeOnly=[],highRisk=[];for(let token of tokens){let def=byToken.get(token);if(!def){unknown2.push(token);continue}def.runtimeOnly&&runtimeOnly.push(token),(def.risk==="high"||def.risk==="critical")&&highRisk.push(token)}return{ok:unknown2.length===0&&runtimeOnly.length===0,unknown:unknown2,runtimeOnly,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 z65}from"zod";var SurfaceGuardPolicySchema=z65.enum(["block","warn","allow"]),ClassificationSchema=z65.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z65.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z65.object({enabled:z65.boolean(),allowed_skills:z65.array(z65.string().min(1)).default([]),allowed_classifications:z65.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z65.enum(["off","daily","weekly"]),NotificationFormatSchema=z65.object({markdown:z65.boolean().default(!0),html:z65.boolean().default(!1)}),NotificationsPolicySchema=z65.object({email_recipients:z65.array(z65.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z65.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z65.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 z66}from"zod";function toSpec(def){return{token:def.token,riskTier:def.risk,description:def.description,...def.runtimeOnly?{runtimeOnly:!0}:{}}}__name(toSpec,"toSpec");var VOCABULARY=Object.freeze(Object.fromEntries(CAPABILITY_VOCABULARY.filter(d3=>!d3.runtimeOnly).map(d3=>[d3.token,toSpec(d3)]))),CapabilityToken=z66.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z66.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","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
|
|
1166
1166
|
${line}`):next2=(content2.endsWith(`
|
|
1167
1167
|
`)?content2:content2+`
|
|
1168
1168
|
`)+line+`
|
|
@@ -1175,7 +1175,7 @@ ${report}`,"render")})}catch(err){printBundleError("agents report",err)}}__name(
|
|
|
1175
1175
|
${result.driftLines.map(l=>` ${l}`).join(`
|
|
1176
1176
|
`)}`,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:"ENV"},{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(`
|
|
1177
1177
|
`)},"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.runtimeOnly){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(`
|
|
1178
|
-
`)}__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 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_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});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}ui.ok({command:"checkout",headline:`Now on env '${name}'`,details:{env:name,created,git_switched:gitSwitched,parent_env:opts.from??null}})}__name(checkoutCommand,"checkoutCommand");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",`
|
|
1178
|
+
`)}__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_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});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}ui.ok({command:"checkout",headline:`Now on env '${name}'`,details:{env:name,created,git_switched:gitSwitched,parent_env:opts.from??null}})}__name(checkoutCommand,"checkoutCommand");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",`
|
|
1179
1179
|
Examples:
|
|
1180
1180
|
fimo integrations connect slack
|
|
1181
1181
|
fimo channels bind slack:#launch
|
|
@@ -1186,7 +1186,7 @@ Run \`fimo channels <command> --help\` for command-specific help.
|
|
|
1186
1186
|
`)}__name(renderCreditsHuman,"renderCreditsHuman");async function creditsCommand(options){let api=new FimoApiClient(loadConfig()),projectId=resolveProjectId2(options),credits=await api.getProjectCredits(projectId);ui.result({command:"credits",data:credits,render:__name(()=>renderCreditsHuman(credits),"render")})}__name(creditsCommand,"creditsCommand");init_dist5();init_esm();init_dist();import fs21 from"node:fs";function skippedPhase(name,reason){return{name,ok:!1,errors:[],skipped:{reason}}}__name(skippedPhase,"skippedPhase");function allErrors(report){return[...report.phases.checks.errors,...report.phases.codegen.errors,...report.phases.sync.errors]}__name(allErrors,"allErrors");function computeExitCode(report){let errors=allErrors(report);return errors.some(e=>e.kind==="infra")?2:errors.some(e=>e.kind==="author")?1:0}__name(computeExitCode,"computeExitCode");function finalizeReport(report){let full={...report,ok:!1,exitCode:0};return full.exitCode=computeExitCode(full),full.ok=full.exitCode===0,full}__name(finalizeReport,"finalizeReport");function authorError(opts){return{kind:"author",...opts}}__name(authorError,"authorError");function infraErrorFromException(rule,error){return{kind:"infra",rule,message:error instanceof Error?error.message:String(error)}}__name(infraErrorFromException,"infraErrorFromException");function formatReportHuman(report){let lines=[];for(let phase of[report.phases.checks,report.phases.codegen,report.phases.sync])lines.push(formatPhaseHuman(phase));return lines.push(""),report.ok?lines.push("\u2713 All checks passed."):report.exitCode===1?lines.push("\u2717 Validation failed \u2014 fix the author errors above and re-run."):lines.push("\u2717 Infrastructure error \u2014 Fimo backend was unreachable or returned an error. Try again later."),lines.join(`
|
|
1187
1187
|
`)}__name(formatReportHuman,"formatReportHuman");function formatPhaseHuman(phase){let out=[],header=phase.skipped?`\u21B7 ${phase.name} \u2014 skipped (${phase.skipped.reason})`:phase.ok?`\u2713 ${phase.name}`:`\u2717 ${phase.name}`;if(out.push(header),phase.stats){let parts=Object.entries(phase.stats).map(([k,v])=>`${k}: ${v}`);parts.length>0&&out.push(` ${parts.join(", ")}`)}for(let err of phase.errors){let loc=err.file?` (${err.file}${err.line?`:${err.line}`:""}${err.column?`:${err.column}`:""})`:"";out.push(` [${err.kind}] ${err.rule}: ${err.message}${loc}`)}return out.join(`
|
|
1188
1188
|
`)}__name(formatPhaseHuman,"formatPhaseHuman");init_api();init_config();init_auth_errors();init_templates();import fs15 from"node:fs";import path17 from"node:path";var DEP_FIELDS=["dependencies","devDependencies"],DEPENDENCY_LOCKFILES=["pnpm-lock.yaml","package-lock.json","npm-shrinkwrap.json","yarn.lock","bun.lock","bun.lockb"];function resolveDevFimoDependencyForDeploy(cwd){let packagePath=path17.join(cwd,"package.json");if(!fs15.existsSync(packagePath))return null;let original=fs15.readFileSync(packagePath,"utf8"),pkg=JSON.parse(original),fileSpec=findLocalFimoSpec(pkg);if(!fileSpec)return null;let localPackageRoot=resolveFileSpec(fileSpec,cwd);if(isInsideProject(cwd,localPackageRoot))return null;let devRelease=readDevReleaseVersion(localPackageRoot);if(!devRelease.version||!devRelease.devJsonPath)throw new Error(`Found local fimo dependency "${fileSpec}", but no .fimo/dev.json with an exact development package exists above ${localPackageRoot}. Run \`pnpm -F fimo publish-cli -- --id <task-name>\` from that Fimo checkout, then retry.`);return{devJsonPath:devRelease.devJsonPath,packagePath,version:devRelease.version}}__name(resolveDevFimoDependencyForDeploy,"resolveDevFimoDependencyForDeploy");function prepareDevFimoDependencyForDeploy(cwd,selection=resolveDevFimoDependencyForDeploy(cwd)){if(!selection)return null;let original=fs15.readFileSync(selection.packagePath,"utf8"),pkg=JSON.parse(original),lockfiles=snapshotDependencyLockfiles(cwd);if(!replaceLocalFimoSpecs(pkg,selection.version))return null;try{fs15.writeFileSync(selection.packagePath,JSON.stringify(pkg,null,2)+`
|
|
1189
|
-
`);for(let lockfile of lockfiles)fs15.rmSync(lockfile.path)}catch(error){restoreFile(selection.packagePath,Buffer.from(original));for(let lockfile of lockfiles)restoreFile(lockfile.path,lockfile.content,lockfile.mode);throw error}return{...selection,restore:__name(()=>{restoreFile(selection.packagePath,Buffer.from(original));for(let lockfile of lockfiles)restoreFile(lockfile.path,lockfile.content,lockfile.mode)},"restore")}}__name(prepareDevFimoDependencyForDeploy,"prepareDevFimoDependencyForDeploy");function snapshotDependencyLockfiles(cwd){return DEPENDENCY_LOCKFILES.flatMap(name=>{let lockfilePath=path17.join(cwd,name);return fs15.existsSync(lockfilePath)?[{content:fs15.readFileSync(lockfilePath),mode:fs15.statSync(lockfilePath).mode,path:lockfilePath}]:[]})}__name(snapshotDependencyLockfiles,"snapshotDependencyLockfiles");function restoreFile(filePath,content2,mode2){fs15.writeFileSync(filePath,content2,mode2===void 0?void 0:{mode:mode2})}__name(restoreFile,"restoreFile");function findLocalFimoSpec(pkg){for(let field of DEP_FIELDS){let spec=pkg[field]?.fimo;if(typeof spec=="string"&&spec.startsWith("file:"))return spec}return null}__name(findLocalFimoSpec,"findLocalFimoSpec");function replaceLocalFimoSpecs(pkg,version){let changed=!1;for(let field of DEP_FIELDS){let deps=pkg[field];if(!deps)continue;let spec=deps.fimo;typeof spec=="string"&&spec.startsWith("file:")&&spec!==version&&(deps.fimo=version,changed=!0)}return changed}__name(replaceLocalFimoSpecs,"replaceLocalFimoSpecs");function resolveFileSpec(spec,cwd){let rawPath=spec.slice(5),packagePath=path17.isAbsolute(rawPath)?rawPath:path17.resolve(cwd,rawPath);return path17.resolve(packagePath)}__name(resolveFileSpec,"resolveFileSpec");function isInsideProject(cwd,targetPath){let relative3=path17.relative(path17.resolve(cwd),path17.resolve(targetPath));return relative3===""||!relative3.startsWith("..")&&!path17.isAbsolute(relative3)}__name(isInsideProject,"isInsideProject");init_git_credential_setup();init_git();init_interactive();init_project_context();function buildProjectPreviewUrl(webUrl,projectId,env){return new URL(`/app/projects/${encodeURIComponent(projectId)}/env/${encodeURIComponent(env)}/preview`,webUrl).toString()}__name(buildProjectPreviewUrl,"buildProjectPreviewUrl");init_project();init_dist();import{readFile as readFile3}from"node:fs/promises";import path23 from"node:path";var import_frameworks=__toESM(require_frameworks(),1),import_detect_framework=__toESM(require_detect_framework(),1),import_local_file_system_detector=__toESM(require_local_file_system_detector(),1);import{readFile}from"node:fs/promises";import{resolve}from"node:path";var FRAMEWORK_LIST=import_frameworks.frameworks;function detectorFor(projectRoot){return new import_local_file_system_detector.LocalFileSystemDetector(resolve(projectRoot))}__name(detectorFor,"detectorFor");async function readPackageManifest(projectRoot){try{return JSON.parse(await readFile(resolve(projectRoot,"package.json"),"utf8"))}catch{return{}}}__name(readPackageManifest,"readPackageManifest");function packageNameFor(framework){return[...framework.detectors?.every??[],...framework.detectors?.some??[]].find(detector=>detector.matchPackage)?.matchPackage??framework.dependency}__name(packageNameFor,"packageNameFor");function declaredVersionFor(framework,manifest){if(framework.detectedVersion)return framework.detectedVersion;let packageName=packageNameFor(framework);if(packageName)for(let group of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let version=manifest[group]?.[packageName];if(version)return version}}__name(declaredVersionFor,"declaredVersionFor");function normalizeFramework(framework,manifest){if(!framework.slug)return null;let declaredVersion=declaredVersionFor(framework,manifest);return{slug:framework.slug,name:framework.name,...declaredVersion?{declaredVersion}:{}}}__name(normalizeFramework,"normalizeFramework");async function detectProjectFramework(projectRoot){let[framework,manifest]=await Promise.all([(0,import_detect_framework.detectFrameworkRecord)({fs:detectorFor(projectRoot),frameworkList:FRAMEWORK_LIST}),readPackageManifest(projectRoot)]);return framework?normalizeFramework(framework,manifest):null}__name(detectProjectFramework,"detectProjectFramework");init_project_layout();import{existsSync,readFileSync}from"fs";import{resolve as resolve2}from"path";var defaultConfig={seo:void 0};function getConfigServer(rootDir){try{let configPath=resolveFimoConfigPath(rootDir),content2=readFileSync(configPath,"utf-8"),raw=JSON.parse(content2);return{seo:raw.seo,i18n:raw.i18n,routes:raw.routes,version:raw.version}}catch{return defaultConfig}}__name(getConfigServer,"getConfigServer");function resolveFimoConfigPath(rootDir){let existing=[CURRENT_PROJECT_LAYOUT.project,LEGACY_PROJECT_LAYOUT.project,CURRENT_PROJECT_LAYOUT.config,LEGACY_PROJECT_LAYOUT.config,LEGACY_AGENT_POLICY_PATH].filter(candidate=>existsSync(resolve2(rootDir,candidate)));return resolve2(rootDir,selectProjectConfigPath(existing))}__name(resolveFimoConfigPath,"resolveFimoConfigPath");import{existsSync as existsSync2,readFileSync as readFileSync2,readdirSync,statSync}from"node:fs";import{join as join3}from"node:path";import{parseSync}from"oxc-parser";function findReactFiles(dir,files=[]){if(!existsSync2(dir))return files;let entries2=readdirSync(dir);for(let entry of entries2){let fullPath=join3(dir,entry);if(statSync(fullPath).isDirectory()){if(entry==="ui"||entry==="node_modules")continue;findReactFiles(fullPath,files)}else/\.(ts|tsx|js|jsx)$/.test(entry)&&files.push(fullPath)}return files}__name(findReactFiles,"findReactFiles");function extractFromFile(filePath){let declarations=[];try{let visit2=function(node){if(!(!node||typeof node!="object")){if(node.type==="CallExpression"){let callee=node.callee;if(callee?.type==="Identifier"&&callee?.name==="t"){let firstArg=(node.arguments||[])[0];if(firstArg?.type==="Literal"&&typeof firstArg.value=="string"){let key=firstArg.value;declarations.push({key,file:filePath})}}}for(let key of Object.keys(node)){let child=node[key];if(Array.isArray(child))for(let item of child)visit2(item);else typeof child=="object"&&child!==null&&visit2(child)}}};__name(visit2,"visit");let code2=readFileSync2(filePath,"utf-8"),ast=parseSync(filePath,code2).program;visit2(ast)}catch(error){console.error(`Failed to parse ${filePath}:`,error)}return declarations}__name(extractFromFile,"extractFromFile");function extractLabelKeys(options={}){let cwd=options.cwd??process.cwd(),srcDir=join3(cwd,"src"),declarations=[],seen=new Set;for(let file of findReactFiles(srcDir))for(let declaration of extractFromFile(file))seen.has(declaration.key)||(seen.add(declaration.key),declarations.push(declaration));return declarations.sort((a,b)=>a.key.localeCompare(b.key))}__name(extractLabelKeys,"extractLabelKeys");function extractTranslations(options={}){return{keys:extractLabelKeys(options)}}__name(extractTranslations,"extractTranslations");init_sync_forms();init_sync_schemas();import fs17 from"node:fs";import path19 from"node:path";function parseRoutesSource(source){let stripped=source.replace(/\/\/.*$/gm,""),seen=new Set,routes=[];function add2(entry){let key=`${entry.path??"<layout>"}|${entry.file}|${entry.isIndex?"index":"route"}|${entry.isLayout?"layout":""}`;seen.has(key)||(seen.add(key),routes.push(entry))}__name(add2,"add");function normalizePath(p2){return p2?`/${p2}`.replace(/^\/\//,"/"):"/"}__name(normalizePath,"normalizePath");for(let match of stripped.matchAll(/\bindex\(\s*['"]([^'"]+)['"](?:\s*,[^)]*)?\)/g))add2({path:"/",file:match[1],isIndex:!0});for(let match of stripped.matchAll(/\broute\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]/g))add2({path:normalizePath(match[1]),file:match[2],isIndex:!1});for(let match of stripped.matchAll(/\blayout\(\s*['"]([^'"]+)['"]/g))add2({path:null,file:match[1],isIndex:!1,isLayout:!0});for(let match of stripped.matchAll(/\{\s*path:\s*['"]([^'"]+)['"][^}]*?file:\s*['"]([^'"]+)['"][^}]*\}/g))add2({path:normalizePath(match[1]),file:match[2],isIndex:!1});for(let match of stripped.matchAll(/\{\s*file:\s*['"]([^'"]+)['"]([^}]*)\}/g)){let file=match[1],rest=match[2],pathMatch=rest.match(/path:\s*['"]([^'"]+)['"]/),isIndex=/index:\s*true/.test(rest);add2({path:pathMatch?normalizePath(pathMatch[1]):"/",file,isIndex})}return routes}__name(parseRoutesSource,"parseRoutesSource");function readJson(filePath){try{return JSON.parse(fs17.readFileSync(filePath,"utf-8"))}catch{return{}}}__name(readJson,"readJson");function getParamNamesFromPath(routePath){return(routePath==="/"?"/":routePath.replace(/\/+$/,"")).split("/").filter(Boolean).filter(segment=>segment.startsWith(":")).map(segment=>segment.slice(1))}__name(getParamNamesFromPath,"getParamNamesFromPath");function loadConfigRoutes(config){let configRoutes=config.routes??{};return Object.entries(configRoutes).map(([id,route])=>({id,path:route.path??"/",label:route.label??null,paramNames:getParamNamesFromPath(route.path??"/"),params:route.params??null,seo:route.seo??null}))}__name(loadConfigRoutes,"loadConfigRoutes");function validateRouteMetadata(options={}){let cwd=options.cwd??process.cwd(),configFilePath=resolveFimoConfigPath(cwd),configDisplayPath=path19.relative(cwd,configFilePath).replaceAll(path19.sep,"/"),srcDir=path19.resolve(cwd,"src"),routesFilePath=path19.resolve(srcDir,"routes.ts"),errors=[],fileRoutes=[];if(!fs17.existsSync(routesFilePath))errors.push("Missing src/routes.ts.");else{let source=fs17.readFileSync(routesFilePath,"utf-8");fileRoutes=parseRoutesSource(source)}let pathToFile=new Map;for(let fr of fileRoutes)fr.path&&fr.file&&pathToFile.set(fr.path,fr.file);let config=readJson(configFilePath),i18n=validateI18nConfig(config);errors.push(...i18n.errors);let configRoutes=loadConfigRoutes(config),configPaths=new Set(configRoutes.map(r=>r.path));for(let fileRoute of fileRoutes)fileRoute.isLayout||fileRoute.path&&!configPaths.has(fileRoute.path)&&errors.push(`Route with path "${fileRoute.path}" (file: "${fileRoute.file}") exists in src/routes.ts but has no matching entry in ${configDisplayPath}.
|
|
1189
|
+
`);for(let lockfile of lockfiles)fs15.rmSync(lockfile.path)}catch(error){restoreFile(selection.packagePath,Buffer.from(original));for(let lockfile of lockfiles)restoreFile(lockfile.path,lockfile.content,lockfile.mode);throw error}return{...selection,restore:__name(()=>{restoreFile(selection.packagePath,Buffer.from(original));for(let lockfile of lockfiles)restoreFile(lockfile.path,lockfile.content,lockfile.mode)},"restore")}}__name(prepareDevFimoDependencyForDeploy,"prepareDevFimoDependencyForDeploy");function snapshotDependencyLockfiles(cwd){return DEPENDENCY_LOCKFILES.flatMap(name=>{let lockfilePath=path17.join(cwd,name);return fs15.existsSync(lockfilePath)?[{content:fs15.readFileSync(lockfilePath),mode:fs15.statSync(lockfilePath).mode,path:lockfilePath}]:[]})}__name(snapshotDependencyLockfiles,"snapshotDependencyLockfiles");function restoreFile(filePath,content2,mode2){fs15.writeFileSync(filePath,content2,mode2===void 0?void 0:{mode:mode2})}__name(restoreFile,"restoreFile");function findLocalFimoSpec(pkg){for(let field of DEP_FIELDS){let spec=pkg[field]?.fimo;if(typeof spec=="string"&&spec.startsWith("file:"))return spec}return null}__name(findLocalFimoSpec,"findLocalFimoSpec");function replaceLocalFimoSpecs(pkg,version){let changed=!1;for(let field of DEP_FIELDS){let deps=pkg[field];if(!deps)continue;let spec=deps.fimo;typeof spec=="string"&&spec.startsWith("file:")&&spec!==version&&(deps.fimo=version,changed=!0)}return changed}__name(replaceLocalFimoSpecs,"replaceLocalFimoSpecs");function resolveFileSpec(spec,cwd){let rawPath=spec.slice(5),packagePath=path17.isAbsolute(rawPath)?rawPath:path17.resolve(cwd,rawPath);return path17.resolve(packagePath)}__name(resolveFileSpec,"resolveFileSpec");function isInsideProject(cwd,targetPath){let relative3=path17.relative(path17.resolve(cwd),path17.resolve(targetPath));return relative3===""||!relative3.startsWith("..")&&!path17.isAbsolute(relative3)}__name(isInsideProject,"isInsideProject");init_git_credential_setup();init_git();init_interactive();init_project_context();function buildProjectPreviewUrl(webUrl,projectId,env){return new URL(`/app/projects/${encodeURIComponent(projectId)}/env/${encodeURIComponent(env)}/preview`,webUrl).toString()}__name(buildProjectPreviewUrl,"buildProjectPreviewUrl");init_project();init_dist();import{readFile as readFile3}from"node:fs/promises";import path23 from"node:path";var import_frameworks=__toESM(require_frameworks(),1),import_detect_framework=__toESM(require_detect_framework(),1),import_local_file_system_detector=__toESM(require_local_file_system_detector(),1);import{readFile}from"node:fs/promises";import{resolve}from"node:path";var FRAMEWORK_LIST=import_frameworks.frameworks;function detectorFor(projectRoot){return new import_local_file_system_detector.LocalFileSystemDetector(resolve(projectRoot))}__name(detectorFor,"detectorFor");async function readPackageManifest(projectRoot){try{return JSON.parse(await readFile(resolve(projectRoot,"package.json"),"utf8"))}catch{return{}}}__name(readPackageManifest,"readPackageManifest");function packageNameFor(framework){return[...framework.detectors?.every??[],...framework.detectors?.some??[]].find(detector=>detector.matchPackage)?.matchPackage??framework.dependency}__name(packageNameFor,"packageNameFor");function declaredVersionFor(framework,manifest){if(framework.detectedVersion)return framework.detectedVersion;let packageName=packageNameFor(framework);if(packageName)for(let group of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let version=manifest[group]?.[packageName];if(version)return version}}__name(declaredVersionFor,"declaredVersionFor");function normalizeFramework(framework,manifest){if(!framework.slug)return null;let declaredVersion=declaredVersionFor(framework,manifest);return{slug:framework.slug,name:framework.name,...declaredVersion?{declaredVersion}:{}}}__name(normalizeFramework,"normalizeFramework");async function detectProjectFramework(projectRoot){let[framework,manifest]=await Promise.all([(0,import_detect_framework.detectFrameworkRecord)({fs:detectorFor(projectRoot),frameworkList:FRAMEWORK_LIST}),readPackageManifest(projectRoot)]);return framework?normalizeFramework(framework,manifest):null}__name(detectProjectFramework,"detectProjectFramework");init_project_layout();import{existsSync,readFileSync}from"fs";import{resolve as resolve2}from"path";var defaultConfig={seo:void 0};function getConfigServer(rootDir){try{let configPath=resolveFimoConfigPath(rootDir),content2=readFileSync(configPath,"utf-8"),raw=JSON.parse(content2);return{seo:raw.seo,i18n:raw.i18n,routes:raw.routes,version:raw.version}}catch{return defaultConfig}}__name(getConfigServer,"getConfigServer");function resolveFimoConfigPath(rootDir){let existing=[CURRENT_PROJECT_LAYOUT.project,LEGACY_PROJECT_LAYOUT.project,CURRENT_PROJECT_LAYOUT.config,LEGACY_PROJECT_LAYOUT.config,LEGACY_AGENT_POLICY_PATH].filter(candidate=>existsSync(resolve2(rootDir,candidate)));return resolve2(rootDir,selectProjectConfigPath(existing))}__name(resolveFimoConfigPath,"resolveFimoConfigPath");import{existsSync as existsSync2,readFileSync as readFileSync2,readdirSync,statSync}from"node:fs";import{join as join3}from"node:path";import{parseSync}from"oxc-parser";function findReactFiles(dir,files=[]){if(!existsSync2(dir))return files;let entries2=readdirSync(dir);for(let entry of entries2){let fullPath=join3(dir,entry);if(statSync(fullPath).isDirectory()){if(entry==="ui"||entry==="node_modules")continue;findReactFiles(fullPath,files)}else/\.(ts|tsx|js|jsx)$/.test(entry)&&files.push(fullPath)}return files}__name(findReactFiles,"findReactFiles");function extractFromFile(filePath){let declarations=[];try{let visit2=function(node){if(!(!node||typeof node!="object")){if(node.type==="CallExpression"){let callee=node.callee;if(callee?.type==="Identifier"&&callee.name==="t"||callee?.type==="MemberExpression"&&callee.computed===!1&&callee.object?.type==="Identifier"&&callee.object.name==="labels"&&callee.property?.type==="Identifier"&&callee.property.name==="t"){let firstArg=(node.arguments||[])[0];if(firstArg?.type==="Literal"&&typeof firstArg.value=="string"){let key=firstArg.value;declarations.push({key,file:filePath})}}}for(let key of Object.keys(node)){let child=node[key];if(Array.isArray(child))for(let item of child)visit2(item);else typeof child=="object"&&child!==null&&visit2(child)}}};__name(visit2,"visit");let code2=readFileSync2(filePath,"utf-8"),ast=parseSync(filePath,code2).program;visit2(ast)}catch(error){console.error(`Failed to parse ${filePath}:`,error)}return declarations}__name(extractFromFile,"extractFromFile");function extractLabelKeys(options={}){let cwd=options.cwd??process.cwd(),srcDir=join3(cwd,"src"),declarations=[],seen=new Set;for(let file of findReactFiles(srcDir))for(let declaration of extractFromFile(file))seen.has(declaration.key)||(seen.add(declaration.key),declarations.push(declaration));return declarations.sort((a,b)=>a.key.localeCompare(b.key))}__name(extractLabelKeys,"extractLabelKeys");function extractTranslations(options={}){return{keys:extractLabelKeys(options)}}__name(extractTranslations,"extractTranslations");init_sync_forms();init_sync_schemas();import fs17 from"node:fs";import path19 from"node:path";function parseRoutesSource(source){let stripped=source.replace(/\/\/.*$/gm,""),seen=new Set,routes=[];function add2(entry){let key=`${entry.path??"<layout>"}|${entry.file}|${entry.isIndex?"index":"route"}|${entry.isLayout?"layout":""}`;seen.has(key)||(seen.add(key),routes.push(entry))}__name(add2,"add");function normalizePath(p2){return p2?`/${p2}`.replace(/^\/\//,"/"):"/"}__name(normalizePath,"normalizePath");for(let match of stripped.matchAll(/\bindex\(\s*['"]([^'"]+)['"](?:\s*,[^)]*)?\)/g))add2({path:"/",file:match[1],isIndex:!0});for(let match of stripped.matchAll(/\broute\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]/g))add2({path:normalizePath(match[1]),file:match[2],isIndex:!1});for(let match of stripped.matchAll(/\blayout\(\s*['"]([^'"]+)['"]/g))add2({path:null,file:match[1],isIndex:!1,isLayout:!0});for(let match of stripped.matchAll(/\{\s*path:\s*['"]([^'"]+)['"][^}]*?file:\s*['"]([^'"]+)['"][^}]*\}/g))add2({path:normalizePath(match[1]),file:match[2],isIndex:!1});for(let match of stripped.matchAll(/\{\s*file:\s*['"]([^'"]+)['"]([^}]*)\}/g)){let file=match[1],rest=match[2],pathMatch=rest.match(/path:\s*['"]([^'"]+)['"]/),isIndex=/index:\s*true/.test(rest);add2({path:pathMatch?normalizePath(pathMatch[1]):"/",file,isIndex})}return routes}__name(parseRoutesSource,"parseRoutesSource");function readJson(filePath){try{return JSON.parse(fs17.readFileSync(filePath,"utf-8"))}catch{return{}}}__name(readJson,"readJson");function getParamNamesFromPath(routePath){return(routePath==="/"?"/":routePath.replace(/\/+$/,"")).split("/").filter(Boolean).filter(segment=>segment.startsWith(":")).map(segment=>segment.slice(1))}__name(getParamNamesFromPath,"getParamNamesFromPath");function loadConfigRoutes(config){let configRoutes=config.routes??{};return Object.entries(configRoutes).map(([id,route])=>({id,path:route.path??"/",label:route.label??null,paramNames:getParamNamesFromPath(route.path??"/"),params:route.params??null,seo:route.seo??null}))}__name(loadConfigRoutes,"loadConfigRoutes");function validateRouteMetadata(options={}){let cwd=options.cwd??process.cwd(),configFilePath=resolveFimoConfigPath(cwd),configDisplayPath=path19.relative(cwd,configFilePath).replaceAll(path19.sep,"/"),srcDir=path19.resolve(cwd,"src"),routesFilePath=path19.resolve(srcDir,"routes.ts"),errors=[],fileRoutes=[];if(!fs17.existsSync(routesFilePath))errors.push("Missing src/routes.ts.");else{let source=fs17.readFileSync(routesFilePath,"utf-8");fileRoutes=parseRoutesSource(source)}let pathToFile=new Map;for(let fr of fileRoutes)fr.path&&fr.file&&pathToFile.set(fr.path,fr.file);let config=readJson(configFilePath),i18n=validateI18nConfig(config);errors.push(...i18n.errors);let configRoutes=loadConfigRoutes(config),configPaths=new Set(configRoutes.map(r=>r.path));for(let fileRoute of fileRoutes)fileRoute.isLayout||fileRoute.path&&!configPaths.has(fileRoute.path)&&errors.push(`Route with path "${fileRoute.path}" (file: "${fileRoute.file}") exists in src/routes.ts but has no matching entry in ${configDisplayPath}.
|
|
1190
1190
|
Fix: add a route entry to ${configDisplayPath} "routes" with a matching "path".`);let filePaths=new Set(fileRoutes.filter(r=>!r.isLayout&&r.path).map(r=>r.path));for(let route of configRoutes)filePaths.has(route.path)||errors.push(`Route "${route.id}" (${route.path}) exists in ${configDisplayPath} but is not registered in src/routes.ts.
|
|
1191
1191
|
Fix: add the route to src/routes.ts. Example: route('${route.path.replace(/^\//,"")}', './pages/YourPage.tsx')`);i18n.routingStrategy==="path-prefix"&&i18n.locales.length>1&&errors.push(...validateLocaleRouteCollisions({configRoutes,fileRoutes,i18n,configDisplayPath,routesSourceUsesFimoRoutes:sourceUsesFimoRoutes(fileRoutes,routesFilePath)}));let routeById=new Map;for(let route of configRoutes){if(routeById.has(route.id)){let previousPath=routeById.get(route.id).path;errors.push(`Duplicate route id "${route.id}" found for paths "${previousPath}" and "${route.path}".`);continue}routeById.set(route.id,route)}for(let route of configRoutes){let file=pathToFile.get(route.path);if(!file)continue;let routeModulePath=path19.resolve(srcDir,file);if(!fs17.existsSync(routeModulePath)){errors.push(`Route "${route.id}" (${route.path}) references missing module "${file}".
|
|
1192
1192
|
Fix: create the file at src/${file}.`);continue}if(route.paramNames.length>0)if(!route.params)errors.push(`Dynamic route "${route.id}" (${route.path}) needs \`params\` metadata to generate prerender URLs.
|
|
@@ -1226,7 +1226,7 @@ This breaks source tracking for inline editing. Translation keys must be statica
|
|
|
1226
1226
|
\u274C Found ${errors.length} error(s) in ${reactFiles.length} files.
|
|
1227
1227
|
`),process.exit(1)}}import fs20 from"node:fs";import path22 from"node:path";var SCAN_EXTENSIONS=[".ts",".tsx",".js",".jsx",".mjs"],SCAN_EXTENSIONS_SET=new Set(SCAN_EXTENSIONS),SKIP_DIRS=new Set(["node_modules","dist",".next",".fimo",".git","public"]),GLOBAL_PATTERNS=[/\.css$/,/\.scss$/,/tailwind\.config/,/postcss\.config/,/vite\.config/,/tsconfig/,/package\.json$/,/src\/main\.[tj]sx?$/,/src\/index\.[tj]sx?$/,/src\/root\.[tj]sx?$/,/react-router\.config/];function isGlobalFile(filePath){return GLOBAL_PATTERNS.some(p2=>p2.test(filePath))}__name(isGlobalFile,"isGlobalFile");function collectFiles(dir){let files=[];if(!fs20.existsSync(dir))return files;let entries2=fs20.readdirSync(dir,{withFileTypes:!0});for(let entry of entries2){if(SKIP_DIRS.has(entry.name))continue;let fullPath=path22.join(dir,entry.name);entry.isDirectory()?files.push(...collectFiles(fullPath)):SCAN_EXTENSIONS_SET.has(path22.extname(entry.name))&&files.push(fullPath)}return files}__name(collectFiles,"collectFiles");function extractImports(content2){let imports=[],staticRegex=/(?:import|export)\s+(?:[\s\S]*?)\s+from\s+['"]([^'"]+)['"]/g;for(let match of content2.matchAll(staticRegex))imports.push(match[1]);let dynamicRegex=/import\(\s*['"]([^'"]+)['"]\s*\)/g;for(let match of content2.matchAll(dynamicRegex))imports.push(match[1]);let requireRegex=/require\(\s*['"]([^'"]+)['"]\s*\)/g;for(let match of content2.matchAll(requireRegex))imports.push(match[1]);return imports.filter(s=>s.startsWith(".")||s.startsWith("@/"))}__name(extractImports,"extractImports");function resolveImport(specifier,fromDir,srcDir){let targetPath;if(specifier.startsWith("@/"))targetPath=path22.resolve(srcDir,specifier.slice(2));else if(specifier.startsWith("."))targetPath=path22.resolve(fromDir,specifier);else return null;if(fs20.existsSync(targetPath)&&fs20.statSync(targetPath).isFile())return targetPath;for(let ext of SCAN_EXTENSIONS){let withExt=targetPath+ext;if(fs20.existsSync(withExt))return withExt}for(let ext of SCAN_EXTENSIONS){let indexFile=path22.join(targetPath,"index"+ext);if(fs20.existsSync(indexFile))return indexFile}return null}__name(resolveImport,"resolveImport");function discoverRoutes(srcDir,root2){let routesFilePath=path22.resolve(srcDir,"routes.ts");if(!fs20.existsSync(routesFilePath))return new Map;let source=fs20.readFileSync(routesFilePath,"utf-8"),parsed=parseRoutesSource(source),fileToRoutes=new Map;for(let r of parsed){if(r.isLayout||!r.path||!r.file)continue;let resolved=resolveImport(r.file,srcDir,srcDir);if(!resolved)continue;let rel=path22.relative(root2,resolved);fileToRoutes.has(rel)||fileToRoutes.set(rel,new Set),fileToRoutes.get(rel).add(r.path)}return fileToRoutes}__name(discoverRoutes,"discoverRoutes");function buildReverseImportGraph(srcDir,root2){let fileToImporters=new Map,allFiles=collectFiles(srcDir);for(let filePath of allFiles){let content2;try{content2=fs20.readFileSync(filePath,"utf-8")}catch{continue}let imports=extractImports(content2);for(let specifier of imports){let resolved=resolveImport(specifier,path22.dirname(filePath),srcDir);if(!resolved)continue;let resolvedRel=path22.relative(root2,resolved),importerRel=path22.relative(root2,filePath);fileToImporters.has(resolvedRel)||fileToImporters.set(resolvedRel,new Set),fileToImporters.get(resolvedRel).add(importerRel)}}return fileToImporters}__name(buildReverseImportGraph,"buildReverseImportGraph");function resolveAffectedRoutes(file,fileToImporters,fileToRoutes){let visited=new Set,queue=[file],affectedRoutes=new Set;for(;queue.length>0;){let current=queue.shift();if(visited.has(current))continue;visited.add(current);let routes=fileToRoutes.get(current);if(routes)for(let route of routes)affectedRoutes.add(route);let importers=fileToImporters.get(current);if(importers)for(let importer of importers)visited.has(importer)||queue.push(importer)}return Array.from(affectedRoutes)}__name(resolveAffectedRoutes,"resolveAffectedRoutes");function resolveRoutes(changedFiles,options={}){let root2=options.cwd??process.cwd(),srcDir=path22.resolve(root2,"src"),normalizedChangedFiles=changedFiles.map(f=>f.replace(/^\/+/,""));if(normalizedChangedFiles.length===0)return{routeMap:{},routes:[],unresolvedFiles:[]};let fileToRoutes=discoverRoutes(srcDir,root2),fileToImporters=buildReverseImportGraph(srcDir,root2),routeMap={},unresolvedFiles=[];for(let file of normalizedChangedFiles){if(isGlobalFile(file)){routeMap[file]=["*"];continue}let routes=resolveAffectedRoutes(file,fileToImporters,fileToRoutes);routes.length>0?routeMap[file]=routes:unresolvedFiles.push(file)}let allRoutes=[...new Set(Object.values(routeMap).flat().filter(r=>r!=="*"))];return{routeMap,routes:allRoutes,unresolvedFiles}}__name(resolveRoutes,"resolveRoutes");init_sync_forms();init_sync_schemas();function resolveCwd(options){return options.cwd?resolve7(options.cwd):process.cwd()}__name(resolveCwd,"resolveCwd");function renderPrettyJson4(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson4,"renderPrettyJson");async function syncSchemasCommand(options){let cwd=resolveCwd(options),framework=await detectProjectFramework(cwd),result=syncSchemas({cwd,framework:framework?.slug??null});ui.result({command:"scripts sync-schemas",data:result,render:__name(()=>renderPrettyJson4(result),"render")})}__name(syncSchemasCommand,"syncSchemasCommand");function syncFormsCommand(options){let result=syncForms({cwd:resolveCwd(options)});ui.result({command:"scripts sync-forms",data:result,render:__name(()=>renderPrettyJson4(result),"render")})}__name(syncFormsCommand,"syncFormsCommand");async function exportStaticCommand(options){let result=await exportStatic({cwd:resolveCwd(options)});ui.result({command:"export-static",data:result??{ok:!0},render:__name(()=>renderPrettyJson4(result??{ok:!0}),"render")})}__name(exportStaticCommand,"exportStaticCommand");function validateRouteMetadataCommand(options){let result=validateRouteMetadata({cwd:resolveCwd(options)});result.errors.length>0&&(ui.error({command:"scripts validate-route-metadata",code:"ROUTE_METADATA_INVALID",message:`Route metadata validation failed (${result.errors.length} issue(s)):
|
|
1228
1228
|
${result.errors.map(e=>` - ${e}`).join(`
|
|
1229
|
-
`)}`}),process.exit(1)),ui.ok({command:"scripts validate-route-metadata",headline:`Route metadata validation passed (${result.routesChecked} route${result.routesChecked===1?"":"s"}).`,details:{routes_checked:result.routesChecked}})}__name(validateRouteMetadataCommand,"validateRouteMetadataCommand");function extractTranslationsCommand(options){let cwd=resolveCwd(options),data2={keys:extractTranslations({cwd}).keys.length};ui.result({command:"scripts extract-translations",data:data2,render:__name(()=>JSON.stringify(data2),"render")})}__name(extractTranslationsCommand,"extractTranslationsCommand");function resolveRoutesCommand(changedFiles,options){let cwd=resolveCwd(options),files=[];if(changedFiles.length===1&&changedFiles[0].startsWith("{"))try{files=JSON.parse(changedFiles[0]).files??[]}catch{files=[]}else files=changedFiles;let output=resolveRoutes(files,{cwd});ui.result({command:"resolve-routes",data:output,render:__name(()=>JSON.stringify(output),"render")})}__name(resolveRoutesCommand,"resolveRoutesCommand");function lintProject(opts){let files=opts.targetPath?[resolve7(opts.cwd,opts.targetPath)]:collectFiles2(resolve7(opts.cwd,"src")),errors=[],filesChecked=0;for(let file of files)if(/\.(tsx?|jsx?)$/.test(file))try{let code2=readFileSync8(file,"utf-8");errors.push(...lintTranslationKeys(file,code2)),filesChecked++}catch{}return{errors,filesChecked}}__name(lintProject,"lintProject");function lintCommand(targetPath,options){let cwd=resolveCwd(options),result=lintProject({cwd,targetPath});ui.result({command:"scripts lint",data:result,render:__name(()=>JSON.stringify(result),"render")}),result.errors.length>0&&process.exit(1)}__name(lintCommand,"lintCommand");function collectFiles2(root2){if(!existsSync8(root2))return[];let results=[];for(let name of readdirSync6(root2)){if(name==="node_modules"||name==="dist"||name===".git")continue;let full=join9(root2,name);statSync3(full).isDirectory()?results.push(...collectFiles2(full)):results.push(full)}return results}__name(collectFiles2,"collectFiles");async function validateCommand(options,cmd){let cwd=resolveProjectCwd(options.cwd),envOverride2=envOverrideFromCommand(cmd),report=await runValidate({cwd,envOverride:envOverride2}),warnings=[getDbLabelsRuntimeWarning(cwd)].filter(warning=>!!warning);ui.result({command:"validate",data:report,render:__name(()=>formatReportHuman(report),"render"),warnings:warnings.length>0?warnings:void 0}),report.ok||(process.exitCode=report.exitCode)}__name(validateCommand,"validateCommand");async function runValidate(opts){let{cwd,envOverride:envOverride2}=opts,checks=await runChecksPhase({cwd}),codegen,labelKeys=null;if(checks.errors.length>0)codegen=skippedPhase("Codegen","static checks failed");else{let codegenResult=await runCodegenPhase({cwd});codegen=codegenResult.phase,labelKeys=codegenResult.labelKeys}let sync;return checks.errors.length>0?sync=skippedPhase("Labels","static checks failed"):labelKeys===null?sync=skippedPhase("Labels","label key scan failed"):sync=await runLabelsPhase({cwd,labelKeys,envOverride:envOverride2}),finalizeReport({phases:{checks,codegen,sync}})}__name(runValidate,"runValidate");async function runChecksPhase(opts){let{cwd}=opts,[lintResult,routeResult,agentsResult,schemasResult]=await Promise.allSettled([Promise.resolve().then(()=>lintProject({cwd})),Promise.resolve().then(()=>runRouteMetadataCheck({cwd})),Promise.resolve().then(()=>runAgentsCheck({cwd})),Promise.resolve().then(()=>validateSchemas({cwd}))]),errors=[],stats={};if(lintResult.status==="fulfilled"){stats.filesLinted=lintResult.value.filesChecked;for(let err of lintResult.value.errors)errors.push(authorError({rule:`lint/${err.rule}`,message:err.message,file:err.file,line:err.line,column:err.column}))}else errors.push(infraErrorFromException("lint",lintResult.reason));if(routeResult.status==="fulfilled"){if(routeResult.value){stats.routesChecked=routeResult.value.routesChecked;for(let message of routeResult.value.errors)errors.push(authorError({rule:"route-metadata",message}))}}else errors.push(infraErrorFromException("route-metadata",routeResult.reason));if(agentsResult.status==="fulfilled"?(Object.assign(stats,agentsResult.value.stats),errors.push(...agentsResult.value.errors)):errors.push(infraErrorFromException("agents",agentsResult.reason)),schemasResult.status==="fulfilled"){stats.schemasChecked=schemasResult.value.schemasChecked;for(let err of schemasResult.value.errors)errors.push(authorError({rule:err.rule,message:err.message,file:err.file}))}else errors.push(infraErrorFromException("schemas",schemasResult.reason));return{name:"Checks",ok:errors.length===0,errors,stats}}__name(runChecksPhase,"runChecksPhase");async function runAgentsCheck(opts){let{cwd}=opts,report=await runValidateAgents({cwd,json:!0}),errors=[];if(report.policy&&!report.policy.ok)for(let issue of report.policy.issues)errors.push(authorError({rule:"agents/policy",message:issue.message,file:issue.pointer}));for(let bundle of report.bundles)for(let phase of["parse","capabilities","composition","semantics"])for(let issue of bundle.phases[phase].issues)errors.push(authorError({rule:`agents/${phase}`,message:`${bundle.name}: ${issue.message}`,file:issue.pointer}));return{errors,stats:{agentsChecked:report.bundles.length}}}__name(runAgentsCheck,"runAgentsCheck");function runRouteMetadataCheck(opts){return validateRouteMetadata({cwd:opts.cwd})}__name(runRouteMetadataCheck,"runRouteMetadataCheck");async function runCodegenPhase(opts){let{cwd}=opts,[schemasResult,formsResult,labelsResult]=await Promise.allSettled([detectProjectFramework(cwd).then(framework=>syncSchemas({cwd,framework:framework?.slug??null,verbose:!1})),Promise.resolve().then(()=>syncForms({cwd,verbose:!1})),Promise.resolve().then(()=>extractLabelKeys({cwd}))]),errors=[],stats={};schemasResult.status==="fulfilled"?(stats.schemasCreated=schemasResult.value.created,stats.schemasUpdated=schemasResult.value.updated,stats.schemasDeleted=schemasResult.value.deleted):errors.push(infraErrorFromException("sync-schemas",schemasResult.reason)),formsResult.status==="fulfilled"?(stats.formsCreated=formsResult.value.created,stats.formsUpdated=formsResult.value.updated,stats.formsDeleted=formsResult.value.deleted):errors.push(infraErrorFromException("sync-forms",formsResult.reason));let labelKeys=null;return labelsResult.status==="fulfilled"?(labelKeys=labelsResult.value,stats.labelsDeclared=labelKeys.length):errors.push(infraErrorFromException("extract-label-keys",labelsResult.reason)),{phase:{name:"Codegen",ok:errors.length===0,errors,stats},labelKeys}}__name(runCodegenPhase,"runCodegenPhase");async function runLabelsPhase(opts){let{cwd,labelKeys,envOverride:envOverride2}=opts;if(labelKeys.length===0)return{name:"Labels",ok:!0,errors:[],stats:{labelsDeclared:0,labelsMissing:0}};let ctx;try{ctx=await getProjectContext({cwd,envOverride:envOverride2})}catch(error){return rethrowCliAuthError(error),{name:"Labels",ok:!1,errors:[infraErrorFromException("load-project-settings",error)]}}let api=new FimoApiClient(loadConfig()).withEnv(ctx.env),locale=getConfigServer(cwd).i18n?.defaultLocale??"en";try{let labels2=await loadLabelsForValidation({cwd,locale,projectId:ctx.projectId,loadAuthenticatedLabels:__name(()=>api.listLabels(ctx.projectId,locale),"loadAuthenticatedLabels")}),existingKeys=new Set(Object.keys(labels2)),missing=labelKeys.filter(label=>!existingKeys.has(label.key));return{name:"Labels",ok:missing.length===0,errors:missing.map(label=>authorError({rule:"labels/missing",message:`Missing label "${label.key}" for locale "${locale}". Run: fimo labels set ${JSON.stringify(label.key)} --locale ${locale} --value "...".`,file:label.file})),stats:{labelsDeclared:labelKeys.length,labelsMissing:missing.length}}}catch(error){return rethrowCliAuthError(error),{name:"Labels",ok:!1,errors:[infraErrorFromException("labels-check",error)]}}}__name(runLabelsPhase,"runLabelsPhase");function labelsToRecord(labels2){return Object.fromEntries(labels2.map(label=>[label.key,label.value??label.defaultValue??""]))}__name(labelsToRecord,"labelsToRecord");async function loadPublicTenantLabels(cwd,locale){let env=await readProjectEnv(cwd),apiUrl=env.VITE_API_URL;if(!apiUrl)return null;try{let url=new URL("/labels",apiUrl);url.searchParams.set("locale",locale);let headers=env.FIMO_ENV?{"X-Fimo-Env":env.FIMO_ENV}:{},response=await fetchWithTimeout(url,3e4,headers);if(!response.ok)return null;let body=await response.json();return Array.isArray(body.data)?labelsToRecord(body.data):body.data?.labels??null}catch{return null}}__name(loadPublicTenantLabels,"loadPublicTenantLabels");async function loadLabelsForValidation({cwd,locale,projectId,loadAuthenticatedLabels}){let env=await readProjectEnv(cwd);if(!env.VITE_API_URL)return labelsToRecord(await loadAuthenticatedLabels());let labels2=await loadPublicTenantLabels(cwd,locale);if(labels2==null)throw new Error(`Could not read labels from project "${projectId}" env "${env.FIMO_ENV??"main"}"`);return labels2}__name(loadLabelsForValidation,"loadLabelsForValidation");async function fetchWithTimeout(url,timeoutMs,headers){let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),timeoutMs);try{return await fetch(url,{signal:controller.signal,headers})}finally{clearTimeout(timeout)}}__name(fetchWithTimeout,"fetchWithTimeout");async function readProjectEnv(cwd){let values={...await readEnvFile(path23.join(cwd,".env")),...await readEnvFile(path23.join(cwd,".env.local"))};return process.env.VITE_API_URL&&(values.VITE_API_URL=process.env.VITE_API_URL),process.env.FIMO_ENV&&(values.FIMO_ENV=process.env.FIMO_ENV),values}__name(readProjectEnv,"readProjectEnv");async function readEnvFile(filePath){try{let content2=await readFile3(filePath,"utf8"),values={};for(let line of content2.split(/\r?\n/)){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;let index2=trimmed.indexOf("=");if(index2===-1)continue;let key=trimmed.slice(0,index2).trim(),value=trimmed.slice(index2+1).trim().replace(/^['"]|['"]$/g,"");values[key]=value}return values}catch{return{}}}__name(readEnvFile,"readEnvFile");async function deployCommand(options,cmd){let cwd=resolveProjectCwd(options.cwd),local;try{local=loadProjectSettings(cwd)}catch{ui.error({command:"deploy",code:"NOT_IN_PROJECT",message:"You are not in a Fimo project.",hint:"Run `fimo create` to start one, or cd into a linked project."});return}if(!await isGitRepo(cwd)){ui.error({command:"deploy",code:"NOT_A_GIT_REPO",message:"Not a git repository."});return}let isPretty2=currentMode().format==="pretty";isPretty2&&mt(options.publish?"Deploying and publishing":"Deploying to preview");let envOverride2=envOverrideFromCommand(cmd),ctx=await getProjectContext({cwd,envOverride:envOverride2});if(isPretty2&&process.stderr.write(`${envSourceBanner(ctx)}
|
|
1229
|
+
`)}`}),process.exit(1)),ui.ok({command:"scripts validate-route-metadata",headline:`Route metadata validation passed (${result.routesChecked} route${result.routesChecked===1?"":"s"}).`,details:{routes_checked:result.routesChecked}})}__name(validateRouteMetadataCommand,"validateRouteMetadataCommand");function extractTranslationsCommand(options){let cwd=resolveCwd(options),data2={keys:extractTranslations({cwd}).keys.length};ui.result({command:"scripts extract-translations",data:data2,render:__name(()=>JSON.stringify(data2),"render")})}__name(extractTranslationsCommand,"extractTranslationsCommand");function resolveRoutesCommand(changedFiles,options){let cwd=resolveCwd(options),files=[];if(changedFiles.length===1&&changedFiles[0].startsWith("{"))try{files=JSON.parse(changedFiles[0]).files??[]}catch{files=[]}else files=changedFiles;let output=resolveRoutes(files,{cwd});ui.result({command:"resolve-routes",data:output,render:__name(()=>JSON.stringify(output),"render")})}__name(resolveRoutesCommand,"resolveRoutesCommand");function lintProject(opts){let files=opts.targetPath?[resolve7(opts.cwd,opts.targetPath)]:collectFiles2(resolve7(opts.cwd,"src")),errors=[],filesChecked=0;for(let file of files)if(/\.(tsx?|jsx?)$/.test(file))try{let code2=readFileSync8(file,"utf-8");errors.push(...lintTranslationKeys(file,code2)),filesChecked++}catch{}return{errors,filesChecked}}__name(lintProject,"lintProject");function lintCommand(targetPath,options){let cwd=resolveCwd(options),result=lintProject({cwd,targetPath});ui.result({command:"scripts lint",data:result,render:__name(()=>JSON.stringify(result),"render")}),result.errors.length>0&&process.exit(1)}__name(lintCommand,"lintCommand");function collectFiles2(root2){if(!existsSync8(root2))return[];let results=[];for(let name of readdirSync6(root2)){if(name==="node_modules"||name==="dist"||name===".git")continue;let full=join9(root2,name);statSync3(full).isDirectory()?results.push(...collectFiles2(full)):results.push(full)}return results}__name(collectFiles2,"collectFiles");async function validateCommand(options,cmd){let cwd=resolveProjectCwd(options.cwd),envOverride2=envOverrideFromCommand(cmd),report=await runValidate({cwd,envOverride:envOverride2}),warnings=[getDbLabelsRuntimeWarning(cwd)].filter(warning=>!!warning);ui.result({command:"validate",data:report,render:__name(()=>formatReportHuman(report),"render"),warnings:warnings.length>0?warnings:void 0}),report.ok||(process.exitCode=report.exitCode)}__name(validateCommand,"validateCommand");async function runValidate(opts){let{cwd,envOverride:envOverride2}=opts,checks=await runChecksPhase({cwd}),codegen,labelKeys=null;if(checks.errors.length>0)codegen=skippedPhase("Codegen","static checks failed");else{let codegenResult=await runCodegenPhase({cwd});codegen=codegenResult.phase,labelKeys=codegenResult.labelKeys}let sync;return checks.errors.length>0?sync=skippedPhase("Labels","static checks failed"):labelKeys===null?sync=skippedPhase("Labels","label key scan failed"):sync=await runLabelsPhase({cwd,labelKeys,envOverride:envOverride2}),finalizeReport({phases:{checks,codegen,sync}})}__name(runValidate,"runValidate");async function runChecksPhase(opts){let{cwd}=opts,[lintResult,routeResult,agentsResult,schemasResult]=await Promise.allSettled([Promise.resolve().then(()=>lintProject({cwd})),Promise.resolve().then(()=>runRouteMetadataCheck({cwd})),Promise.resolve().then(()=>runAgentsCheck({cwd})),Promise.resolve().then(()=>validateSchemas({cwd}))]),errors=[],stats={};if(lintResult.status==="fulfilled"){stats.filesLinted=lintResult.value.filesChecked;for(let err of lintResult.value.errors)errors.push(authorError({rule:`lint/${err.rule}`,message:err.message,file:err.file,line:err.line,column:err.column}))}else errors.push(infraErrorFromException("lint",lintResult.reason));if(routeResult.status==="fulfilled"){if(routeResult.value){stats.routesChecked=routeResult.value.routesChecked;for(let message of routeResult.value.errors)errors.push(authorError({rule:"route-metadata",message}))}}else errors.push(infraErrorFromException("route-metadata",routeResult.reason));if(agentsResult.status==="fulfilled"?(Object.assign(stats,agentsResult.value.stats),errors.push(...agentsResult.value.errors)):errors.push(infraErrorFromException("agents",agentsResult.reason)),schemasResult.status==="fulfilled"){stats.schemasChecked=schemasResult.value.schemasChecked;for(let err of schemasResult.value.errors)errors.push(authorError({rule:err.rule,message:err.message,file:err.file}))}else errors.push(infraErrorFromException("schemas",schemasResult.reason));return{name:"Checks",ok:errors.length===0,errors,stats}}__name(runChecksPhase,"runChecksPhase");async function runAgentsCheck(opts){let{cwd}=opts,report=await runValidateAgents({cwd,json:!0}),errors=[];if(report.policy&&!report.policy.ok)for(let issue of report.policy.issues)errors.push(authorError({rule:"agents/policy",message:issue.message,file:issue.pointer}));for(let bundle of report.bundles)for(let phase of["parse","capabilities","composition","semantics"])for(let issue of bundle.phases[phase].issues)errors.push(authorError({rule:`agents/${phase}`,message:`${bundle.name}: ${issue.message}`,file:issue.pointer}));return{errors,stats:{agentsChecked:report.bundles.length}}}__name(runAgentsCheck,"runAgentsCheck");async function runRouteMetadataCheck(opts){return(await detectProjectFramework(opts.cwd))?.slug==="nextjs"?null:validateRouteMetadata({cwd:opts.cwd})}__name(runRouteMetadataCheck,"runRouteMetadataCheck");async function runCodegenPhase(opts){let{cwd}=opts,[schemasResult,formsResult,labelsResult]=await Promise.allSettled([detectProjectFramework(cwd).then(framework=>syncSchemas({cwd,framework:framework?.slug??null,verbose:!1})),Promise.resolve().then(()=>syncForms({cwd,verbose:!1})),Promise.resolve().then(()=>extractLabelKeys({cwd}))]),errors=[],stats={};schemasResult.status==="fulfilled"?(stats.schemasCreated=schemasResult.value.created,stats.schemasUpdated=schemasResult.value.updated,stats.schemasDeleted=schemasResult.value.deleted):errors.push(infraErrorFromException("sync-schemas",schemasResult.reason)),formsResult.status==="fulfilled"?(stats.formsCreated=formsResult.value.created,stats.formsUpdated=formsResult.value.updated,stats.formsDeleted=formsResult.value.deleted):errors.push(infraErrorFromException("sync-forms",formsResult.reason));let labelKeys=null;return labelsResult.status==="fulfilled"?(labelKeys=labelsResult.value,stats.labelsDeclared=labelKeys.length):errors.push(infraErrorFromException("extract-label-keys",labelsResult.reason)),{phase:{name:"Codegen",ok:errors.length===0,errors,stats},labelKeys}}__name(runCodegenPhase,"runCodegenPhase");async function runLabelsPhase(opts){let{cwd,labelKeys,envOverride:envOverride2}=opts;if(labelKeys.length===0)return{name:"Labels",ok:!0,errors:[],stats:{labelsDeclared:0,labelsMissing:0}};let ctx;try{ctx=await getProjectContext({cwd,envOverride:envOverride2})}catch(error){return rethrowCliAuthError(error),{name:"Labels",ok:!1,errors:[infraErrorFromException("load-project-settings",error)]}}let api=new FimoApiClient(loadConfig()).withEnv(ctx.env),locale=getConfigServer(cwd).i18n?.defaultLocale??"en";try{let labels2=await loadLabelsForValidation({cwd,locale,projectId:ctx.projectId,loadAuthenticatedLabels:__name(()=>api.listLabels(ctx.projectId,locale),"loadAuthenticatedLabels")}),existingKeys=new Set(Object.keys(labels2)),missing=labelKeys.filter(label=>!existingKeys.has(label.key));return{name:"Labels",ok:missing.length===0,errors:missing.map(label=>authorError({rule:"labels/missing",message:`Missing label "${label.key}" for locale "${locale}". Run: fimo labels set ${JSON.stringify(label.key)} --locale ${locale} --value "...".`,file:label.file})),stats:{labelsDeclared:labelKeys.length,labelsMissing:missing.length}}}catch(error){return rethrowCliAuthError(error),{name:"Labels",ok:!1,errors:[infraErrorFromException("labels-check",error)]}}}__name(runLabelsPhase,"runLabelsPhase");function labelsToRecord(labels2){return Object.fromEntries(labels2.map(label=>[label.key,label.value??label.defaultValue??""]))}__name(labelsToRecord,"labelsToRecord");async function loadPublicTenantLabels(cwd,locale){let env=await readProjectEnv(cwd),apiUrl=env.VITE_API_URL;if(!apiUrl)return null;try{let url=new URL("/labels",apiUrl);url.searchParams.set("locale",locale);let headers=env.FIMO_ENV?{"X-Fimo-Env":env.FIMO_ENV}:{},response=await fetchWithTimeout(url,3e4,headers);if(!response.ok)return null;let body=await response.json();return Array.isArray(body.data)?labelsToRecord(body.data):body.data?.labels??null}catch{return null}}__name(loadPublicTenantLabels,"loadPublicTenantLabels");async function loadLabelsForValidation({cwd,locale,projectId,loadAuthenticatedLabels}){let env=await readProjectEnv(cwd);if(!env.VITE_API_URL)return labelsToRecord(await loadAuthenticatedLabels());let labels2=await loadPublicTenantLabels(cwd,locale);if(labels2==null)throw new Error(`Could not read labels from project "${projectId}" env "${env.FIMO_ENV??"main"}"`);return labels2}__name(loadLabelsForValidation,"loadLabelsForValidation");async function fetchWithTimeout(url,timeoutMs,headers){let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),timeoutMs);try{return await fetch(url,{signal:controller.signal,headers})}finally{clearTimeout(timeout)}}__name(fetchWithTimeout,"fetchWithTimeout");async function readProjectEnv(cwd){let values={...await readEnvFile(path23.join(cwd,".env")),...await readEnvFile(path23.join(cwd,".env.local"))};return process.env.VITE_API_URL&&(values.VITE_API_URL=process.env.VITE_API_URL),process.env.FIMO_ENV&&(values.FIMO_ENV=process.env.FIMO_ENV),values}__name(readProjectEnv,"readProjectEnv");async function readEnvFile(filePath){try{let content2=await readFile3(filePath,"utf8"),values={};for(let line of content2.split(/\r?\n/)){let trimmed=line.trim();if(!trimmed||trimmed.startsWith("#"))continue;let index2=trimmed.indexOf("=");if(index2===-1)continue;let key=trimmed.slice(0,index2).trim(),value=trimmed.slice(index2+1).trim().replace(/^['"]|['"]$/g,"");values[key]=value}return values}catch{return{}}}__name(readEnvFile,"readEnvFile");async function deployCommand(options,cmd){let cwd=resolveProjectCwd(options.cwd),local;try{local=loadProjectSettings(cwd)}catch{ui.error({command:"deploy",code:"NOT_IN_PROJECT",message:"You are not in a Fimo project.",hint:"Run `fimo create` to start one, or cd into a linked project."});return}if(!await isGitRepo(cwd)){ui.error({command:"deploy",code:"NOT_A_GIT_REPO",message:"Not a git repository."});return}let isPretty2=currentMode().format==="pretty";isPretty2&&mt(options.publish?"Deploying and publishing":"Deploying to preview");let envOverride2=envOverrideFromCommand(cmd),ctx=await getProjectContext({cwd,envOverride:envOverride2});if(isPretty2&&process.stderr.write(`${envSourceBanner(ctx)}
|
|
1230
1230
|
`),ctx.readOnly){ui.error({command:"deploy",code:"ENV_READONLY",message:`Refusing to deploy to read-only env '${ctx.env}'.`,hint:"Switch off the release/* tag or pass --env <writable-env>."});return}if(options.publish&&ctx.env!==DEFAULT_ENV){ui.error({command:"deploy",code:"PUBLISH_REQUIRES_DEFAULT_ENV",message:`Refusing to --publish from env '${ctx.env}'. Publish only runs from '${DEFAULT_ENV}'.`,hint:`Drop --publish to deploy a preview, or switch to '${DEFAULT_ENV}' first.`});return}let devFimoSelection;try{devFimoSelection=resolveDevFimoDependencyForDeploy(cwd)}catch(error){ui.error({command:"deploy",code:"DEV_FIMO_VERSION_MISSING",message:errorMessage(error)});return}await requireOperation("fimo.deploy",{projectId:ctx.projectId,env:ctx.env});let cfg=loadConfig(),api=new FimoApiClient(cfg).withEnv(ctx.env),dashboardUrl=buildProjectPreviewUrl(cfg.webUrl,local.projectId,ctx.env),previewEnabled=(await api.getProject(local.projectId)).previewEnabled!==!1,validateSp=spinner("Validating project"),report=await runValidate({cwd,envOverride:envOverride2});if(report.ok)validateSp.succeed("Validation passed");else if(options.force)validateSp.fail("Validation failed \u2014 continuing anyway (--force)"),ui.warn({command:"deploy",message:"Bypassing validation errors because --force was passed. The deploy may still fail later in the sandbox."});else{validateSp.fail("Validation failed"),ui.result({command:"deploy",data:{stage:"validate",report},render:__name(()=>formatReportHuman(report),"render")}),process.exitCode=report.exitCode;return}let devFimoDependency=null;try{devFimoDependency=prepareDevFimoDependencyForDeploy(cwd,devFimoSelection)}catch(error){ui.error({command:"deploy",code:"DEV_FIMO_VERSION_MISSING",message:errorMessage(error)});return}devFimoDependency&&isPretty2&&O2.info(`Deploying with fimo ${devFimoDependency.version}; restoring local dependency state after push.`);try{if(await hasUncommittedChanges(cwd)){let message;if(options.message!==void 0)message=options.message;else{assertInteractive('Pass -m "<message>" or commit your changes manually.',"deploy"),isPretty2&&O2.warn("You have uncommitted changes. Commit them before deploying.");let answer=await Ot({message:"Commit message",placeholder:"Deploy",defaultValue:"Deploy"});if(q(answer)){ui.info({command:"deploy",message:"Cancelled."});return}message=String(answer)}let commitSp=spinner("Committing pending changes");await runGit(["add","-A"],cwd),await runGit(["commit","-m",message],cwd),commitSp.succeed("Changes committed")}let remoteSp=spinner("Refreshing git remote URL"),remote=await api.getGitRemote(local.projectId,ctx.env);await ensureFimoRemote(cwd,remote.url);let remoteBranch=remote.branch;remoteSp.succeed(`Remote ready (branch ${remoteBranch})`);let pushSp=spinner(`Pushing to fimo/${remoteBranch}`);try{await runGit(["push","fimo",`HEAD:${remoteBranch}`],cwd),pushSp.succeed("Pushed to Fimo")}catch(error){pushSp.fail("Push failed");let failure=classifyPushError(error);emitPushFailure(failure,remoteBranch);return}}finally{devFimoDependency?.restore()}let stepLabel="",stepStartedAt=0,stepSp=null,finalizeStep=__name((status="ok",failMessage)=>{if(!stepSp)return;let elapsed=((Date.now()-stepStartedAt)/1e3).toFixed(1);status==="ok"?stepSp.succeed(`${stepLabel} (${elapsed}s)`):stepSp.fail(failMessage??`${stepLabel} failed`),stepSp=null},"finalizeStep");try{await api.sandboxPull(local.projectId,({message})=>{finalizeStep("ok"),stepLabel=message,stepStartedAt=Date.now(),stepSp=spinner(message)},ctx.env,{noRestart:options.restart===!1}),finalizeStep("ok")}catch(error){rethrowCliAuthError(error,()=>finalizeStep("fail","Authentication required")),finalizeStep("fail",`Sandbox sync failed: ${errorMessage(error)}`),ui.error({command:"deploy",code:"SANDBOX_SYNC_FAILED",message:`Sandbox sync failed: ${errorMessage(error)}`});return}await syncDisplayNameIfRenamed({cwd,projectId:local.projectId,api});let previewUrl=null;if(previewEnabled)try{previewUrl=(await api.getPreviewUrl(local.projectId,ctx.env)).url}catch(error){isPretty2&&O2.warn(`Could not fetch preview URL: ${errorMessage(error)}`)}if(!options.publish){ui.result({command:"deploy",data:{project_id:local.projectId,env:ctx.env,preview_enabled:previewEnabled,preview_url:previewUrl,dashboard_url:dashboardUrl,published:!1},render:__name(context=>renderDeployResult({previewUrl,dashboardUrl,appUrl:null,previewEnabled,published:!1},context),"render")});return}let publishSp=spinner("Publishing (this can take a few minutes)");try{await api.publishProject(local.projectId)}catch(error){rethrowCliAuthError(error,()=>publishSp.fail("Authentication required")),publishSp.fail(),ui.error({command:"deploy",code:"PUBLISH_FAILED",message:`Publish failed: ${errorMessage(error)}`});return}publishSp.succeed("Published");let appUrl=null;try{appUrl=(await api.getProject(local.projectId)).appUrl}catch(error){isPretty2&&O2.warn(`Could not fetch published URL: ${errorMessage(error)}`)}ui.result({command:"deploy",data:{project_id:local.projectId,env:ctx.env,preview_enabled:previewEnabled,preview_url:previewUrl,dashboard_url:dashboardUrl,published:!0,app_url:appUrl},render:__name(context=>renderDeployResult({previewUrl,dashboardUrl,appUrl,previewEnabled,published:!0},context),"render")})}__name(deployCommand,"deployCommand");function renderDeployResult(result,context){let lines=[];return result.previewUrl&&lines.push(`Preview: ${terminalLink("Open preview",result.previewUrl,context.hyperlinks)}`),result.appUrl&&lines.push(`Live: ${terminalLink("Open site",result.appUrl,context.hyperlinks)}`),lines.push(`Fimo: ${terminalLink("Open in Fimo",result.dashboardUrl,context.hyperlinks)}`),result.published?lines.push(result.appUrl?"Your site is live.":"Publish completed. Check Fimo for the live URL."):lines.push(result.previewEnabled?"Deployed to preview. Run `fimo deploy --publish` or `fimo publish` to publish a new version.":"Changes synced. Preview is disabled for this project."),lines.join(`
|
|
1231
1231
|
`)}__name(renderDeployResult,"renderDeployResult");function emitPushFailure(failure,env){switch(failure.kind){case"non-fast-forward":ui.error({command:"deploy",code:"PUSH_NON_FAST_FORWARD",message:`The remote \`fimo/${env}\` has commits your local branch does not.`,hint:`Fix it manually, then re-run \`fimo deploy\`:
|
|
1232
1232
|
1. git pull --rebase fimo ${env}
|
|
@@ -1316,7 +1316,7 @@ Run \`fimo integrations <command> --help\` for command-specific help.
|
|
|
1316
1316
|
...`}__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()}
|
|
1317
1317
|
...`}__name(trimSearchExcerpt,"trimSearchExcerpt");function resolveProjectId3(opts){if(opts.project)return opts.project;let cwd=resolveProjectCwd(opts.cwd);return loadProjectSettings(cwd).projectId}__name(resolveProjectId3,"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(`
|
|
1318
1318
|
`),"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(`
|
|
1319
|
-
`),"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 fs34 from"node:fs";import path33 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=path33.resolve(projectRoot,options.file);return fs34.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_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 z69}from"zod";var projectScopeShape={projectId:z69.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=z69.string().min(1).max(255).describe("The content type name, for example BlogPost."),localeField=z69.string().min(1).optional().describe("The locale to read or write."),entryDataField=z69.record(z69.string(),z69.unknown()).describe("Entry field values, keyed by field name as declared in the content schema."),filePathField=z69.string().min(1).max(1024).describe("File path relative to the project root."),labelKeyField=z69.string().min(1).max(255).describe("The translation key, for example home.hero.title."),assetIdField=z69.uuid().describe("The Fimo media asset ID."),formIdField=z69.string().min(1).max(255).describe("The Fimo form ID."),formFieldsField=z69.record(z69.string().min(1),z69.unknown()).describe("Form fields keyed by field name; Fimo validates each field definition."),formContentShape={name:z69.string().min(1).max(255).describe("Stable form name."),label:z69.string().min(1).max(255).describe("Human-readable form label."),fields:formFieldsField},mediaGenerationSchema=z69.object({...envScopeShape,task:z69.string().min(1).optional().describe("A stable task, for example 'image.generate' or 'video.generate'."),model:z69.string().min(1).optional().describe("An explicit model ID, for example 'fal/...'."),options:z69.record(z69.string(),z69.unknown()).describe("Task or model options, such as prompt, quality, aspect ratio, and source assets."),name:z69.string().min(1).max(255).optional().describe("Optional name for the generated asset."),parentId:z69.uuid().nullable().optional().describe("Optional media-library folder ID."),altText:z69.string().max(2e3).optional().describe("Optional alternative text for the generated asset."),caption:z69.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(path43,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?`${path43}?${queryString}`:path43}__name(addQuery,"addQuery");var mcpToolCatalog={whoami:{description:"Return the authenticated Fimo user identity.",annotations:{readOnlyHint:!0},scope:"none",accessScope:"read",inputSchema:z69.object({})},projects_list:{description:"List the Fimo projects the authenticated user can access.",annotations:{readOnlyHint:!0},scope:"none",accessScope:"read",inputSchema:z69.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:z69.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:z69.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:z69.object({...envScopeShape,typeName:typeNameField,locale:localeField,limit:z69.number().int().min(1).max(100).optional().describe("Maximum number of records to return."),offset:z69.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:z69.object({...envScopeShape,typeName:typeNameField,id:z69.uuid().describe("The entry ID."),locale:localeField,populate:z69.array(z69.string().min(1)).max(50).optional().describe("Reference fields to populate."),localeFallbacks:z69.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:z69.object({...envScopeShape,search:z69.string().min(1).optional().describe("A text search applied to entry content."),locale:localeField,limit:z69.number().int().min(1).max(100).optional().describe("Maximum number of records to return."),offset:z69.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:z69.object({...envScopeShape,typeName:typeNameField,data:entryDataField,locale:localeField,documentId:z69.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:z69.object({...envScopeShape,typeName:typeNameField,id:z69.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:z69.object({...envScopeShape,typeName:typeNameField,id:z69.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:z69.object({...envScopeShape,typeName:typeNameField,entries:z69.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:z69.object({...envScopeShape,typeName:typeNameField,selection:z69.union([z69.object({ids:z69.array(z69.uuid()).min(1).max(MAX_BULK_ENTRIES)}),z69.object({where:EntryWhereSchema}),z69.object({updates:z69.array(z69.object({id:z69.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:z69.object({...envScopeShape,typeName:typeNameField,selection:z69.union([z69.object({ids:z69.array(z69.uuid()).min(1).max(MAX_BULK_ENTRIES)}),z69.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:z69.object({...envScopeShape,typeName:typeNameField,locale:localeField,populate:z69.array(z69.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:z69.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:z69.object({...envScopeShape,locale:z69.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:z69.object({...envScopeShape,locale:z69.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:z69.object({...envScopeShape,key:labelKeyField,value:z69.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:z69.object({...envScopeShape,records:z69.array(z69.object({key:labelKeyField,value:z69.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:z69.object({...envScopeShape,locale:z69.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:z69.object({...envScopeShape,parentId:z69.uuid().optional().describe("Limit results to one media-library folder."),search:z69.string().max(200).optional(),type:z69.enum(["file","folder"]).optional(),mimePrefix:z69.string().max(50).optional().describe("MIME prefix such as image/ or video/."),sortBy:z69.enum(["name","createdAt","updatedAt","fileSize","type"]).optional(),sortDirection:z69.enum(["asc","desc"]).optional(),includePath:z69.boolean().optional(),excludeHidden:z69.boolean().optional(),limit:z69.number().int().min(1).max(100).optional(),offset:z69.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:z69.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:z69.object({...envScopeShape,name:z69.string().min(1).max(255).describe("Folder name."),parentId:z69.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:z69.object({...envScopeShape,id:assetIdField,parentId:z69.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:z69.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:z69.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:z69.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:z69.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:z69.object({...envScopeShape,id:formIdField,...z69.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:z69.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:z69.object({...envScopeShape,id:formIdField,limit:z69.number().int().min(1).max(100).optional(),offset:z69.number().int().min(0).optional(),searchQuery:z69.string().max(200).optional(),sortDirection:z69.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:z69.object({...envScopeShape,id:formIdField,submissionId:z69.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:z69.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:z69.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:z69.object({...envScopeShape,pattern:z69.string().min(1).max(300).optional().describe("Glob pattern, for example 'src/**/*.tsx'."),limit:z69.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:z69.object({...envScopeShape,pattern:z69.string().min(1).max(200).describe("Regular expression to search for."),include:z69.string().min(1).max(300).optional().describe("Glob pattern limiting which files are searched."),caseInsensitive:z69.boolean().optional().describe("Case-insensitive matching."),maxMatches:z69.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:z69.object({...envScopeShape,path:filePathField,content:z69.string().max(262144).describe("Full UTF-8 text content of the file (256 KB max)."),overwrite:z69.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:z69.object({...envScopeShape,path:filePathField,oldString:z69.string().min(1).describe("Exact text to replace."),newString:z69.string().describe("Replacement text."),replaceAll:z69.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:z69.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:z69.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:z69.object({...envScopeShape,agentName:z69.string().min(1).max(120).describe("The agent bundle name."),args:z69.record(z69.string(),z69.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:z69.object({...projectScopeShape,sessionId:z69.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 z70 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=z70.custom(v=>v!==null&&(typeof v=="object"||typeof v=="function")),ProgressTokenSchema=z70.union([z70.string(),z70.number().int()]),CursorSchema=z70.string(),TaskCreationParamsSchema=z70.looseObject({ttl:z70.union([z70.number(),z70.null()]).optional(),pollInterval:z70.number().optional()}),TaskMetadataSchema=z70.object({ttl:z70.number().optional()}),RelatedTaskMetadataSchema=z70.object({taskId:z70.string()}),RequestMetaSchema=z70.looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=z70.object({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),isTaskAugmentedRequestParams=__name(value=>TaskAugmentedRequestParamsSchema.safeParse(value).success,"isTaskAugmentedRequestParams"),RequestSchema=z70.object({method:z70.string(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=z70.object({_meta:RequestMetaSchema.optional()}),NotificationSchema=z70.object({method:z70.string(),params:NotificationsParamsSchema.loose().optional()}),ResultSchema=z70.looseObject({_meta:RequestMetaSchema.optional()}),RequestIdSchema=z70.union([z70.string(),z70.number().int()]),JSONRPCRequestSchema=z70.object({jsonrpc:z70.literal(JSONRPC_VERSION),id:RequestIdSchema,...RequestSchema.shape}).strict(),isJSONRPCRequest=__name(value=>JSONRPCRequestSchema.safeParse(value).success,"isJSONRPCRequest"),JSONRPCNotificationSchema=z70.object({jsonrpc:z70.literal(JSONRPC_VERSION),...NotificationSchema.shape}).strict(),isJSONRPCNotification=__name(value=>JSONRPCNotificationSchema.safeParse(value).success,"isJSONRPCNotification"),JSONRPCResultResponseSchema=z70.object({jsonrpc:z70.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=z70.object({jsonrpc:z70.literal(JSONRPC_VERSION),id:RequestIdSchema.optional(),error:z70.object({code:z70.number().int(),message:z70.string(),data:z70.unknown().optional()})}).strict();var isJSONRPCErrorResponse=__name(value=>JSONRPCErrorResponseSchema.safeParse(value).success,"isJSONRPCErrorResponse");var JSONRPCMessageSchema=z70.union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),JSONRPCResponseSchema=z70.union([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:z70.string().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:z70.literal("notifications/cancelled"),params:CancelledNotificationParamsSchema}),IconSchema=z70.object({src:z70.string(),mimeType:z70.string().optional(),sizes:z70.array(z70.string()).optional(),theme:z70.enum(["light","dark"]).optional()}),IconsSchema=z70.object({icons:z70.array(IconSchema).optional()}),BaseMetadataSchema=z70.object({name:z70.string(),title:z70.string().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:z70.string(),websiteUrl:z70.string().optional(),description:z70.string().optional()}),FormElicitationCapabilitySchema=z70.intersection(z70.object({applyDefaults:z70.boolean().optional()}),z70.record(z70.string(),z70.unknown())),ElicitationCapabilitySchema=z70.preprocess(value=>value&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0?{form:{}}:value,z70.intersection(z70.object({form:FormElicitationCapabilitySchema.optional(),url:AssertObjectSchema.optional()}),z70.record(z70.string(),z70.unknown()).optional())),ClientTasksCapabilitySchema=z70.looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:z70.looseObject({sampling:z70.looseObject({createMessage:AssertObjectSchema.optional()}).optional(),elicitation:z70.looseObject({create:AssertObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=z70.looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:z70.looseObject({tools:z70.looseObject({call:AssertObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=z70.object({experimental:z70.record(z70.string(),AssertObjectSchema).optional(),sampling:z70.object({context:AssertObjectSchema.optional(),tools:AssertObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:z70.object({listChanged:z70.boolean().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:z70.string(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:z70.literal("initialize"),params:InitializeRequestParamsSchema});var ServerCapabilitiesSchema=z70.object({experimental:z70.record(z70.string(),AssertObjectSchema).optional(),logging:AssertObjectSchema.optional(),completions:AssertObjectSchema.optional(),prompts:z70.object({listChanged:z70.boolean().optional()}).optional(),resources:z70.object({subscribe:z70.boolean().optional(),listChanged:z70.boolean().optional()}).optional(),tools:z70.object({listChanged:z70.boolean().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:z70.string(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:z70.string().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:z70.literal("notifications/initialized"),params:NotificationsParamsSchema.optional()});var PingRequestSchema=RequestSchema.extend({method:z70.literal("ping"),params:BaseRequestParamsSchema.optional()}),ProgressSchema=z70.object({progress:z70.number(),total:z70.optional(z70.number()),message:z70.optional(z70.string())}),ProgressNotificationParamsSchema=z70.object({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:z70.literal("notifications/progress"),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()}),TaskStatusSchema=z70.enum(["working","input_required","completed","failed","cancelled"]),TaskSchema=z70.object({taskId:z70.string(),status:TaskStatusSchema,ttl:z70.union([z70.number(),z70.null()]),createdAt:z70.string(),lastUpdatedAt:z70.string(),pollInterval:z70.optional(z70.number()),statusMessage:z70.optional(z70.string())}),CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:z70.literal("notifications/tasks/status"),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema.extend({method:z70.literal("tasks/get"),params:BaseRequestParamsSchema.extend({taskId:z70.string()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:z70.literal("tasks/result"),params:BaseRequestParamsSchema.extend({taskId:z70.string()})}),GetTaskPayloadResultSchema=ResultSchema.loose(),ListTasksRequestSchema=PaginatedRequestSchema.extend({method:z70.literal("tasks/list")}),ListTasksResultSchema=PaginatedResultSchema.extend({tasks:z70.array(TaskSchema)}),CancelTaskRequestSchema=RequestSchema.extend({method:z70.literal("tasks/cancel"),params:BaseRequestParamsSchema.extend({taskId:z70.string()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ResourceContentsSchema=z70.object({uri:z70.string(),mimeType:z70.optional(z70.string()),_meta:z70.record(z70.string(),z70.unknown()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:z70.string()}),Base64Schema=z70.string().refine(val2=>{try{return atob(val2),!0}catch{return!1}},{message:"Invalid Base64 string"}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),RoleSchema=z70.enum(["user","assistant"]),AnnotationsSchema=z70.object({audience:z70.array(RoleSchema).optional(),priority:z70.number().min(0).max(1).optional(),lastModified:z70.iso.datetime({offset:!0}).optional()}),ResourceSchema=z70.object({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:z70.string(),description:z70.optional(z70.string()),mimeType:z70.optional(z70.string()),annotations:AnnotationsSchema.optional(),_meta:z70.optional(z70.looseObject({}))}),ResourceTemplateSchema=z70.object({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:z70.string(),description:z70.optional(z70.string()),mimeType:z70.optional(z70.string()),annotations:AnnotationsSchema.optional(),_meta:z70.optional(z70.looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:z70.literal("resources/list")}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:z70.array(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:z70.literal("resources/templates/list")}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:z70.array(ResourceTemplateSchema)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:z70.string()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema.extend({method:z70.literal("resources/read"),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema=ResultSchema.extend({contents:z70.array(z70.union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:z70.literal("notifications/resources/list_changed"),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema.extend({method:z70.literal("resources/subscribe"),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema.extend({method:z70.literal("resources/unsubscribe"),params:UnsubscribeRequestParamsSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:z70.string()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:z70.literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=z70.object({name:z70.string(),description:z70.optional(z70.string()),required:z70.optional(z70.boolean())}),PromptSchema=z70.object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:z70.optional(z70.string()),arguments:z70.optional(z70.array(PromptArgumentSchema)),_meta:z70.optional(z70.looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:z70.literal("prompts/list")}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:z70.array(PromptSchema)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:z70.string(),arguments:z70.record(z70.string(),z70.string()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:z70.literal("prompts/get"),params:GetPromptRequestParamsSchema}),TextContentSchema=z70.object({type:z70.literal("text"),text:z70.string(),annotations:AnnotationsSchema.optional(),_meta:z70.record(z70.string(),z70.unknown()).optional()}),ImageContentSchema=z70.object({type:z70.literal("image"),data:Base64Schema,mimeType:z70.string(),annotations:AnnotationsSchema.optional(),_meta:z70.record(z70.string(),z70.unknown()).optional()}),AudioContentSchema=z70.object({type:z70.literal("audio"),data:Base64Schema,mimeType:z70.string(),annotations:AnnotationsSchema.optional(),_meta:z70.record(z70.string(),z70.unknown()).optional()}),ToolUseContentSchema=z70.object({type:z70.literal("tool_use"),name:z70.string(),id:z70.string(),input:z70.record(z70.string(),z70.unknown()),_meta:z70.record(z70.string(),z70.unknown()).optional()}),EmbeddedResourceSchema=z70.object({type:z70.literal("resource"),resource:z70.union([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:z70.record(z70.string(),z70.unknown()).optional()}),ResourceLinkSchema=ResourceSchema.extend({type:z70.literal("resource_link")}),ContentBlockSchema=z70.union([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=z70.object({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema=ResultSchema.extend({description:z70.string().optional(),messages:z70.array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:z70.literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=z70.object({title:z70.string().optional(),readOnlyHint:z70.boolean().optional(),destructiveHint:z70.boolean().optional(),idempotentHint:z70.boolean().optional(),openWorldHint:z70.boolean().optional()}),ToolExecutionSchema=z70.object({taskSupport:z70.enum(["required","optional","forbidden"]).optional()}),ToolSchema=z70.object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:z70.string().optional(),inputSchema:z70.object({type:z70.literal("object"),properties:z70.record(z70.string(),AssertObjectSchema).optional(),required:z70.array(z70.string()).optional()}).catchall(z70.unknown()),outputSchema:z70.object({type:z70.literal("object"),properties:z70.record(z70.string(),AssertObjectSchema).optional(),required:z70.array(z70.string()).optional()}).catchall(z70.unknown()).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:z70.record(z70.string(),z70.unknown()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:z70.literal("tools/list")}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:z70.array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:z70.array(ContentBlockSchema).default([]),structuredContent:z70.record(z70.string(),z70.unknown()).optional(),isError:z70.boolean().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:z70.unknown()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:z70.string(),arguments:z70.record(z70.string(),z70.unknown()).optional()}),CallToolRequestSchema=RequestSchema.extend({method:z70.literal("tools/call"),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:z70.literal("notifications/tools/list_changed"),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=z70.object({autoRefresh:z70.boolean().default(!0),debounceMs:z70.number().int().nonnegative().default(300)}),LoggingLevelSchema=z70.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema.extend({method:z70.literal("logging/setLevel"),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:z70.string().optional(),data:z70.unknown()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:z70.literal("notifications/message"),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=z70.object({name:z70.string().optional()}),ModelPreferencesSchema=z70.object({hints:z70.array(ModelHintSchema).optional(),costPriority:z70.number().min(0).max(1).optional(),speedPriority:z70.number().min(0).max(1).optional(),intelligencePriority:z70.number().min(0).max(1).optional()}),ToolChoiceSchema=z70.object({mode:z70.enum(["auto","required","none"]).optional()}),ToolResultContentSchema=z70.object({type:z70.literal("tool_result"),toolUseId:z70.string().describe("The unique identifier for the corresponding tool call."),content:z70.array(ContentBlockSchema).default([]),structuredContent:z70.object({}).loose().optional(),isError:z70.boolean().optional(),_meta:z70.record(z70.string(),z70.unknown()).optional()}),SamplingContentSchema=z70.discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema]),SamplingMessageContentBlockSchema=z70.discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=z70.object({role:RoleSchema,content:z70.union([SamplingMessageContentBlockSchema,z70.array(SamplingMessageContentBlockSchema)]),_meta:z70.record(z70.string(),z70.unknown()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:z70.array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:z70.string().optional(),includeContext:z70.enum(["none","thisServer","allServers"]).optional(),temperature:z70.number().optional(),maxTokens:z70.number().int(),stopSequences:z70.array(z70.string()).optional(),metadata:AssertObjectSchema.optional(),tools:z70.array(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema.extend({method:z70.literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema.extend({model:z70.string(),stopReason:z70.optional(z70.enum(["endTurn","stopSequence","maxTokens"]).or(z70.string())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:z70.string(),stopReason:z70.optional(z70.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(z70.string())),role:RoleSchema,content:z70.union([SamplingMessageContentBlockSchema,z70.array(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=z70.object({type:z70.literal("boolean"),title:z70.string().optional(),description:z70.string().optional(),default:z70.boolean().optional()}),StringSchemaSchema=z70.object({type:z70.literal("string"),title:z70.string().optional(),description:z70.string().optional(),minLength:z70.number().optional(),maxLength:z70.number().optional(),format:z70.enum(["email","uri","date","date-time"]).optional(),default:z70.string().optional()}),NumberSchemaSchema=z70.object({type:z70.enum(["number","integer"]),title:z70.string().optional(),description:z70.string().optional(),minimum:z70.number().optional(),maximum:z70.number().optional(),default:z70.number().optional()}),UntitledSingleSelectEnumSchemaSchema=z70.object({type:z70.literal("string"),title:z70.string().optional(),description:z70.string().optional(),enum:z70.array(z70.string()),default:z70.string().optional()}),TitledSingleSelectEnumSchemaSchema=z70.object({type:z70.literal("string"),title:z70.string().optional(),description:z70.string().optional(),oneOf:z70.array(z70.object({const:z70.string(),title:z70.string()})),default:z70.string().optional()}),LegacyTitledEnumSchemaSchema=z70.object({type:z70.literal("string"),title:z70.string().optional(),description:z70.string().optional(),enum:z70.array(z70.string()),enumNames:z70.array(z70.string()).optional(),default:z70.string().optional()}),SingleSelectEnumSchemaSchema=z70.union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=z70.object({type:z70.literal("array"),title:z70.string().optional(),description:z70.string().optional(),minItems:z70.number().optional(),maxItems:z70.number().optional(),items:z70.object({type:z70.literal("string"),enum:z70.array(z70.string())}),default:z70.array(z70.string()).optional()}),TitledMultiSelectEnumSchemaSchema=z70.object({type:z70.literal("array"),title:z70.string().optional(),description:z70.string().optional(),minItems:z70.number().optional(),maxItems:z70.number().optional(),items:z70.object({anyOf:z70.array(z70.object({const:z70.string(),title:z70.string()}))}),default:z70.array(z70.string()).optional()}),MultiSelectEnumSchemaSchema=z70.union([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=z70.union([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=z70.union([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:z70.literal("form").optional(),message:z70.string(),requestedSchema:z70.object({type:z70.literal("object"),properties:z70.record(z70.string(),PrimitiveSchemaDefinitionSchema),required:z70.array(z70.string()).optional()})}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:z70.literal("url"),message:z70.string(),elicitationId:z70.string(),url:z70.string().url()}),ElicitRequestParamsSchema=z70.union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:z70.literal("elicitation/create"),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:z70.string()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:z70.literal("notifications/elicitation/complete"),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:z70.enum(["accept","decline","cancel"]),content:z70.preprocess(val2=>val2===null?void 0:val2,z70.record(z70.string(),z70.union([z70.string(),z70.number(),z70.boolean(),z70.array(z70.string())])).optional())}),ResourceTemplateReferenceSchema=z70.object({type:z70.literal("ref/resource"),uri:z70.string()});var PromptReferenceSchema=z70.object({type:z70.literal("ref/prompt"),name:z70.string()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:z70.union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:z70.object({name:z70.string(),value:z70.string()}),context:z70.object({arguments:z70.record(z70.string(),z70.string()).optional()}).optional()}),CompleteRequestSchema=RequestSchema.extend({method:z70.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:z70.looseObject({values:z70.array(z70.string()).max(100),total:z70.optional(z70.number().int()),hasMore:z70.optional(z70.boolean())})}),RootSchema=z70.object({uri:z70.string().startsWith("file://"),name:z70.string().optional(),_meta:z70.record(z70.string(),z70.unknown()).optional()}),ListRootsRequestSchema=RequestSchema.extend({method:z70.literal("roots/list"),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema.extend({roots:z70.array(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:z70.literal("notifications/roots/list_changed"),params:NotificationsParamsSchema.optional()}),ClientRequestSchema=z70.union([PingRequestSchema,InitializeRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,CallToolRequestSchema,ListToolsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ClientNotificationSchema=z70.union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema,TaskStatusNotificationSchema]),ClientResultSchema=z70.union([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),ServerRequestSchema=z70.union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ServerNotificationSchema=z70.union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,TaskStatusNotificationSchema,ElicitationCompleteNotificationSchema]),ServerResultSchema=z70.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
|
|
1319
|
+
`),"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 fs34 from"node:fs";import path33 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=path33.resolve(projectRoot,options.file);return fs34.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_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 z70}from"zod";var projectScopeShape={projectId:z70.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=z70.string().min(1).max(255).describe("The content type name, for example BlogPost."),localeField=z70.string().min(1).optional().describe("The locale to read or write."),entryDataField=z70.record(z70.string(),z70.unknown()).describe("Entry field values, keyed by field name as declared in the content schema."),filePathField=z70.string().min(1).max(1024).describe("File path relative to the project root."),labelKeyField=z70.string().min(1).max(255).describe("The translation key, for example home.hero.title."),assetIdField=z70.uuid().describe("The Fimo media asset ID."),formIdField=z70.string().min(1).max(255).describe("The Fimo form ID."),formFieldsField=z70.record(z70.string().min(1),z70.unknown()).describe("Form fields keyed by field name; Fimo validates each field definition."),formContentShape={name:z70.string().min(1).max(255).describe("Stable form name."),label:z70.string().min(1).max(255).describe("Human-readable form label."),fields:formFieldsField},mediaGenerationSchema=z70.object({...envScopeShape,task:z70.string().min(1).optional().describe("A stable task, for example 'image.generate' or 'video.generate'."),model:z70.string().min(1).optional().describe("An explicit model ID, for example 'fal/...'."),options:z70.record(z70.string(),z70.unknown()).describe("Task or model options, such as prompt, quality, aspect ratio, and source assets."),name:z70.string().min(1).max(255).optional().describe("Optional name for the generated asset."),parentId:z70.uuid().nullable().optional().describe("Optional media-library folder ID."),altText:z70.string().max(2e3).optional().describe("Optional alternative text for the generated asset."),caption:z70.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(path43,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?`${path43}?${queryString}`:path43}__name(addQuery,"addQuery");var mcpToolCatalog={whoami:{description:"Return the authenticated Fimo user identity.",annotations:{readOnlyHint:!0},scope:"none",accessScope:"read",inputSchema:z70.object({})},projects_list:{description:"List the Fimo projects the authenticated user can access.",annotations:{readOnlyHint:!0},scope:"none",accessScope:"read",inputSchema:z70.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:z70.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:z70.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:z70.object({...envScopeShape,typeName:typeNameField,locale:localeField,limit:z70.number().int().min(1).max(100).optional().describe("Maximum number of records to return."),offset:z70.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:z70.object({...envScopeShape,typeName:typeNameField,id:z70.uuid().describe("The entry ID."),locale:localeField,populate:z70.array(z70.string().min(1)).max(50).optional().describe("Reference fields to populate."),localeFallbacks:z70.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:z70.object({...envScopeShape,search:z70.string().min(1).optional().describe("A text search applied to entry content."),locale:localeField,limit:z70.number().int().min(1).max(100).optional().describe("Maximum number of records to return."),offset:z70.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:z70.object({...envScopeShape,typeName:typeNameField,data:entryDataField,locale:localeField,documentId:z70.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:z70.object({...envScopeShape,typeName:typeNameField,id:z70.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:z70.object({...envScopeShape,typeName:typeNameField,id:z70.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:z70.object({...envScopeShape,typeName:typeNameField,entries:z70.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:z70.object({...envScopeShape,typeName:typeNameField,selection:z70.union([z70.object({ids:z70.array(z70.uuid()).min(1).max(MAX_BULK_ENTRIES)}),z70.object({where:EntryWhereSchema}),z70.object({updates:z70.array(z70.object({id:z70.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:z70.object({...envScopeShape,typeName:typeNameField,selection:z70.union([z70.object({ids:z70.array(z70.uuid()).min(1).max(MAX_BULK_ENTRIES)}),z70.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:z70.object({...envScopeShape,typeName:typeNameField,locale:localeField,populate:z70.array(z70.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:z70.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:z70.object({...envScopeShape,locale:z70.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:z70.object({...envScopeShape,locale:z70.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:z70.object({...envScopeShape,key:labelKeyField,value:z70.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:z70.object({...envScopeShape,records:z70.array(z70.object({key:labelKeyField,value:z70.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:z70.object({...envScopeShape,locale:z70.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:z70.object({...envScopeShape,parentId:z70.uuid().optional().describe("Limit results to one media-library folder."),search:z70.string().max(200).optional(),type:z70.enum(["file","folder"]).optional(),mimePrefix:z70.string().max(50).optional().describe("MIME prefix such as image/ or video/."),sortBy:z70.enum(["name","createdAt","updatedAt","fileSize","type"]).optional(),sortDirection:z70.enum(["asc","desc"]).optional(),includePath:z70.boolean().optional(),excludeHidden:z70.boolean().optional(),limit:z70.number().int().min(1).max(100).optional(),offset:z70.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:z70.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:z70.object({...envScopeShape,name:z70.string().min(1).max(255).describe("Folder name."),parentId:z70.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:z70.object({...envScopeShape,id:assetIdField,parentId:z70.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:z70.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:z70.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:z70.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:z70.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:z70.object({...envScopeShape,id:formIdField,...z70.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:z70.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:z70.object({...envScopeShape,id:formIdField,limit:z70.number().int().min(1).max(100).optional(),offset:z70.number().int().min(0).optional(),searchQuery:z70.string().max(200).optional(),sortDirection:z70.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:z70.object({...envScopeShape,id:formIdField,submissionId:z70.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:z70.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:z70.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:z70.object({...envScopeShape,pattern:z70.string().min(1).max(300).optional().describe("Glob pattern, for example 'src/**/*.tsx'."),limit:z70.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:z70.object({...envScopeShape,pattern:z70.string().min(1).max(200).describe("Regular expression to search for."),include:z70.string().min(1).max(300).optional().describe("Glob pattern limiting which files are searched."),caseInsensitive:z70.boolean().optional().describe("Case-insensitive matching."),maxMatches:z70.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:z70.object({...envScopeShape,path:filePathField,content:z70.string().max(262144).describe("Full UTF-8 text content of the file (256 KB max)."),overwrite:z70.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:z70.object({...envScopeShape,path:filePathField,oldString:z70.string().min(1).describe("Exact text to replace."),newString:z70.string().describe("Replacement text."),replaceAll:z70.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:z70.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:z70.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:z70.object({...envScopeShape,agentName:z70.string().min(1).max(120).describe("The agent bundle name."),args:z70.record(z70.string(),z70.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:z70.object({...projectScopeShape,sessionId:z70.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 z71 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=z71.custom(v=>v!==null&&(typeof v=="object"||typeof v=="function")),ProgressTokenSchema=z71.union([z71.string(),z71.number().int()]),CursorSchema=z71.string(),TaskCreationParamsSchema=z71.looseObject({ttl:z71.union([z71.number(),z71.null()]).optional(),pollInterval:z71.number().optional()}),TaskMetadataSchema=z71.object({ttl:z71.number().optional()}),RelatedTaskMetadataSchema=z71.object({taskId:z71.string()}),RequestMetaSchema=z71.looseObject({progressToken:ProgressTokenSchema.optional(),[RELATED_TASK_META_KEY]:RelatedTaskMetadataSchema.optional()}),BaseRequestParamsSchema=z71.object({_meta:RequestMetaSchema.optional()}),TaskAugmentedRequestParamsSchema=BaseRequestParamsSchema.extend({task:TaskMetadataSchema.optional()}),isTaskAugmentedRequestParams=__name(value=>TaskAugmentedRequestParamsSchema.safeParse(value).success,"isTaskAugmentedRequestParams"),RequestSchema=z71.object({method:z71.string(),params:BaseRequestParamsSchema.loose().optional()}),NotificationsParamsSchema=z71.object({_meta:RequestMetaSchema.optional()}),NotificationSchema=z71.object({method:z71.string(),params:NotificationsParamsSchema.loose().optional()}),ResultSchema=z71.looseObject({_meta:RequestMetaSchema.optional()}),RequestIdSchema=z71.union([z71.string(),z71.number().int()]),JSONRPCRequestSchema=z71.object({jsonrpc:z71.literal(JSONRPC_VERSION),id:RequestIdSchema,...RequestSchema.shape}).strict(),isJSONRPCRequest=__name(value=>JSONRPCRequestSchema.safeParse(value).success,"isJSONRPCRequest"),JSONRPCNotificationSchema=z71.object({jsonrpc:z71.literal(JSONRPC_VERSION),...NotificationSchema.shape}).strict(),isJSONRPCNotification=__name(value=>JSONRPCNotificationSchema.safeParse(value).success,"isJSONRPCNotification"),JSONRPCResultResponseSchema=z71.object({jsonrpc:z71.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=z71.object({jsonrpc:z71.literal(JSONRPC_VERSION),id:RequestIdSchema.optional(),error:z71.object({code:z71.number().int(),message:z71.string(),data:z71.unknown().optional()})}).strict();var isJSONRPCErrorResponse=__name(value=>JSONRPCErrorResponseSchema.safeParse(value).success,"isJSONRPCErrorResponse");var JSONRPCMessageSchema=z71.union([JSONRPCRequestSchema,JSONRPCNotificationSchema,JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),JSONRPCResponseSchema=z71.union([JSONRPCResultResponseSchema,JSONRPCErrorResponseSchema]),EmptyResultSchema=ResultSchema.strict(),CancelledNotificationParamsSchema=NotificationsParamsSchema.extend({requestId:RequestIdSchema.optional(),reason:z71.string().optional()}),CancelledNotificationSchema=NotificationSchema.extend({method:z71.literal("notifications/cancelled"),params:CancelledNotificationParamsSchema}),IconSchema=z71.object({src:z71.string(),mimeType:z71.string().optional(),sizes:z71.array(z71.string()).optional(),theme:z71.enum(["light","dark"]).optional()}),IconsSchema=z71.object({icons:z71.array(IconSchema).optional()}),BaseMetadataSchema=z71.object({name:z71.string(),title:z71.string().optional()}),ImplementationSchema=BaseMetadataSchema.extend({...BaseMetadataSchema.shape,...IconsSchema.shape,version:z71.string(),websiteUrl:z71.string().optional(),description:z71.string().optional()}),FormElicitationCapabilitySchema=z71.intersection(z71.object({applyDefaults:z71.boolean().optional()}),z71.record(z71.string(),z71.unknown())),ElicitationCapabilitySchema=z71.preprocess(value=>value&&typeof value=="object"&&!Array.isArray(value)&&Object.keys(value).length===0?{form:{}}:value,z71.intersection(z71.object({form:FormElicitationCapabilitySchema.optional(),url:AssertObjectSchema.optional()}),z71.record(z71.string(),z71.unknown()).optional())),ClientTasksCapabilitySchema=z71.looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:z71.looseObject({sampling:z71.looseObject({createMessage:AssertObjectSchema.optional()}).optional(),elicitation:z71.looseObject({create:AssertObjectSchema.optional()}).optional()}).optional()}),ServerTasksCapabilitySchema=z71.looseObject({list:AssertObjectSchema.optional(),cancel:AssertObjectSchema.optional(),requests:z71.looseObject({tools:z71.looseObject({call:AssertObjectSchema.optional()}).optional()}).optional()}),ClientCapabilitiesSchema=z71.object({experimental:z71.record(z71.string(),AssertObjectSchema).optional(),sampling:z71.object({context:AssertObjectSchema.optional(),tools:AssertObjectSchema.optional()}).optional(),elicitation:ElicitationCapabilitySchema.optional(),roots:z71.object({listChanged:z71.boolean().optional()}).optional(),tasks:ClientTasksCapabilitySchema.optional()}),InitializeRequestParamsSchema=BaseRequestParamsSchema.extend({protocolVersion:z71.string(),capabilities:ClientCapabilitiesSchema,clientInfo:ImplementationSchema}),InitializeRequestSchema=RequestSchema.extend({method:z71.literal("initialize"),params:InitializeRequestParamsSchema});var ServerCapabilitiesSchema=z71.object({experimental:z71.record(z71.string(),AssertObjectSchema).optional(),logging:AssertObjectSchema.optional(),completions:AssertObjectSchema.optional(),prompts:z71.object({listChanged:z71.boolean().optional()}).optional(),resources:z71.object({subscribe:z71.boolean().optional(),listChanged:z71.boolean().optional()}).optional(),tools:z71.object({listChanged:z71.boolean().optional()}).optional(),tasks:ServerTasksCapabilitySchema.optional()}),InitializeResultSchema=ResultSchema.extend({protocolVersion:z71.string(),capabilities:ServerCapabilitiesSchema,serverInfo:ImplementationSchema,instructions:z71.string().optional()}),InitializedNotificationSchema=NotificationSchema.extend({method:z71.literal("notifications/initialized"),params:NotificationsParamsSchema.optional()});var PingRequestSchema=RequestSchema.extend({method:z71.literal("ping"),params:BaseRequestParamsSchema.optional()}),ProgressSchema=z71.object({progress:z71.number(),total:z71.optional(z71.number()),message:z71.optional(z71.string())}),ProgressNotificationParamsSchema=z71.object({...NotificationsParamsSchema.shape,...ProgressSchema.shape,progressToken:ProgressTokenSchema}),ProgressNotificationSchema=NotificationSchema.extend({method:z71.literal("notifications/progress"),params:ProgressNotificationParamsSchema}),PaginatedRequestParamsSchema=BaseRequestParamsSchema.extend({cursor:CursorSchema.optional()}),PaginatedRequestSchema=RequestSchema.extend({params:PaginatedRequestParamsSchema.optional()}),PaginatedResultSchema=ResultSchema.extend({nextCursor:CursorSchema.optional()}),TaskStatusSchema=z71.enum(["working","input_required","completed","failed","cancelled"]),TaskSchema=z71.object({taskId:z71.string(),status:TaskStatusSchema,ttl:z71.union([z71.number(),z71.null()]),createdAt:z71.string(),lastUpdatedAt:z71.string(),pollInterval:z71.optional(z71.number()),statusMessage:z71.optional(z71.string())}),CreateTaskResultSchema=ResultSchema.extend({task:TaskSchema}),TaskStatusNotificationParamsSchema=NotificationsParamsSchema.merge(TaskSchema),TaskStatusNotificationSchema=NotificationSchema.extend({method:z71.literal("notifications/tasks/status"),params:TaskStatusNotificationParamsSchema}),GetTaskRequestSchema=RequestSchema.extend({method:z71.literal("tasks/get"),params:BaseRequestParamsSchema.extend({taskId:z71.string()})}),GetTaskResultSchema=ResultSchema.merge(TaskSchema),GetTaskPayloadRequestSchema=RequestSchema.extend({method:z71.literal("tasks/result"),params:BaseRequestParamsSchema.extend({taskId:z71.string()})}),GetTaskPayloadResultSchema=ResultSchema.loose(),ListTasksRequestSchema=PaginatedRequestSchema.extend({method:z71.literal("tasks/list")}),ListTasksResultSchema=PaginatedResultSchema.extend({tasks:z71.array(TaskSchema)}),CancelTaskRequestSchema=RequestSchema.extend({method:z71.literal("tasks/cancel"),params:BaseRequestParamsSchema.extend({taskId:z71.string()})}),CancelTaskResultSchema=ResultSchema.merge(TaskSchema),ResourceContentsSchema=z71.object({uri:z71.string(),mimeType:z71.optional(z71.string()),_meta:z71.record(z71.string(),z71.unknown()).optional()}),TextResourceContentsSchema=ResourceContentsSchema.extend({text:z71.string()}),Base64Schema=z71.string().refine(val2=>{try{return atob(val2),!0}catch{return!1}},{message:"Invalid Base64 string"}),BlobResourceContentsSchema=ResourceContentsSchema.extend({blob:Base64Schema}),RoleSchema=z71.enum(["user","assistant"]),AnnotationsSchema=z71.object({audience:z71.array(RoleSchema).optional(),priority:z71.number().min(0).max(1).optional(),lastModified:z71.iso.datetime({offset:!0}).optional()}),ResourceSchema=z71.object({...BaseMetadataSchema.shape,...IconsSchema.shape,uri:z71.string(),description:z71.optional(z71.string()),mimeType:z71.optional(z71.string()),annotations:AnnotationsSchema.optional(),_meta:z71.optional(z71.looseObject({}))}),ResourceTemplateSchema=z71.object({...BaseMetadataSchema.shape,...IconsSchema.shape,uriTemplate:z71.string(),description:z71.optional(z71.string()),mimeType:z71.optional(z71.string()),annotations:AnnotationsSchema.optional(),_meta:z71.optional(z71.looseObject({}))}),ListResourcesRequestSchema=PaginatedRequestSchema.extend({method:z71.literal("resources/list")}),ListResourcesResultSchema=PaginatedResultSchema.extend({resources:z71.array(ResourceSchema)}),ListResourceTemplatesRequestSchema=PaginatedRequestSchema.extend({method:z71.literal("resources/templates/list")}),ListResourceTemplatesResultSchema=PaginatedResultSchema.extend({resourceTemplates:z71.array(ResourceTemplateSchema)}),ResourceRequestParamsSchema=BaseRequestParamsSchema.extend({uri:z71.string()}),ReadResourceRequestParamsSchema=ResourceRequestParamsSchema,ReadResourceRequestSchema=RequestSchema.extend({method:z71.literal("resources/read"),params:ReadResourceRequestParamsSchema}),ReadResourceResultSchema=ResultSchema.extend({contents:z71.array(z71.union([TextResourceContentsSchema,BlobResourceContentsSchema]))}),ResourceListChangedNotificationSchema=NotificationSchema.extend({method:z71.literal("notifications/resources/list_changed"),params:NotificationsParamsSchema.optional()}),SubscribeRequestParamsSchema=ResourceRequestParamsSchema,SubscribeRequestSchema=RequestSchema.extend({method:z71.literal("resources/subscribe"),params:SubscribeRequestParamsSchema}),UnsubscribeRequestParamsSchema=ResourceRequestParamsSchema,UnsubscribeRequestSchema=RequestSchema.extend({method:z71.literal("resources/unsubscribe"),params:UnsubscribeRequestParamsSchema}),ResourceUpdatedNotificationParamsSchema=NotificationsParamsSchema.extend({uri:z71.string()}),ResourceUpdatedNotificationSchema=NotificationSchema.extend({method:z71.literal("notifications/resources/updated"),params:ResourceUpdatedNotificationParamsSchema}),PromptArgumentSchema=z71.object({name:z71.string(),description:z71.optional(z71.string()),required:z71.optional(z71.boolean())}),PromptSchema=z71.object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:z71.optional(z71.string()),arguments:z71.optional(z71.array(PromptArgumentSchema)),_meta:z71.optional(z71.looseObject({}))}),ListPromptsRequestSchema=PaginatedRequestSchema.extend({method:z71.literal("prompts/list")}),ListPromptsResultSchema=PaginatedResultSchema.extend({prompts:z71.array(PromptSchema)}),GetPromptRequestParamsSchema=BaseRequestParamsSchema.extend({name:z71.string(),arguments:z71.record(z71.string(),z71.string()).optional()}),GetPromptRequestSchema=RequestSchema.extend({method:z71.literal("prompts/get"),params:GetPromptRequestParamsSchema}),TextContentSchema=z71.object({type:z71.literal("text"),text:z71.string(),annotations:AnnotationsSchema.optional(),_meta:z71.record(z71.string(),z71.unknown()).optional()}),ImageContentSchema=z71.object({type:z71.literal("image"),data:Base64Schema,mimeType:z71.string(),annotations:AnnotationsSchema.optional(),_meta:z71.record(z71.string(),z71.unknown()).optional()}),AudioContentSchema=z71.object({type:z71.literal("audio"),data:Base64Schema,mimeType:z71.string(),annotations:AnnotationsSchema.optional(),_meta:z71.record(z71.string(),z71.unknown()).optional()}),ToolUseContentSchema=z71.object({type:z71.literal("tool_use"),name:z71.string(),id:z71.string(),input:z71.record(z71.string(),z71.unknown()),_meta:z71.record(z71.string(),z71.unknown()).optional()}),EmbeddedResourceSchema=z71.object({type:z71.literal("resource"),resource:z71.union([TextResourceContentsSchema,BlobResourceContentsSchema]),annotations:AnnotationsSchema.optional(),_meta:z71.record(z71.string(),z71.unknown()).optional()}),ResourceLinkSchema=ResourceSchema.extend({type:z71.literal("resource_link")}),ContentBlockSchema=z71.union([TextContentSchema,ImageContentSchema,AudioContentSchema,ResourceLinkSchema,EmbeddedResourceSchema]),PromptMessageSchema=z71.object({role:RoleSchema,content:ContentBlockSchema}),GetPromptResultSchema=ResultSchema.extend({description:z71.string().optional(),messages:z71.array(PromptMessageSchema)}),PromptListChangedNotificationSchema=NotificationSchema.extend({method:z71.literal("notifications/prompts/list_changed"),params:NotificationsParamsSchema.optional()}),ToolAnnotationsSchema=z71.object({title:z71.string().optional(),readOnlyHint:z71.boolean().optional(),destructiveHint:z71.boolean().optional(),idempotentHint:z71.boolean().optional(),openWorldHint:z71.boolean().optional()}),ToolExecutionSchema=z71.object({taskSupport:z71.enum(["required","optional","forbidden"]).optional()}),ToolSchema=z71.object({...BaseMetadataSchema.shape,...IconsSchema.shape,description:z71.string().optional(),inputSchema:z71.object({type:z71.literal("object"),properties:z71.record(z71.string(),AssertObjectSchema).optional(),required:z71.array(z71.string()).optional()}).catchall(z71.unknown()),outputSchema:z71.object({type:z71.literal("object"),properties:z71.record(z71.string(),AssertObjectSchema).optional(),required:z71.array(z71.string()).optional()}).catchall(z71.unknown()).optional(),annotations:ToolAnnotationsSchema.optional(),execution:ToolExecutionSchema.optional(),_meta:z71.record(z71.string(),z71.unknown()).optional()}),ListToolsRequestSchema=PaginatedRequestSchema.extend({method:z71.literal("tools/list")}),ListToolsResultSchema=PaginatedResultSchema.extend({tools:z71.array(ToolSchema)}),CallToolResultSchema=ResultSchema.extend({content:z71.array(ContentBlockSchema).default([]),structuredContent:z71.record(z71.string(),z71.unknown()).optional(),isError:z71.boolean().optional()}),CompatibilityCallToolResultSchema=CallToolResultSchema.or(ResultSchema.extend({toolResult:z71.unknown()})),CallToolRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({name:z71.string(),arguments:z71.record(z71.string(),z71.unknown()).optional()}),CallToolRequestSchema=RequestSchema.extend({method:z71.literal("tools/call"),params:CallToolRequestParamsSchema}),ToolListChangedNotificationSchema=NotificationSchema.extend({method:z71.literal("notifications/tools/list_changed"),params:NotificationsParamsSchema.optional()}),ListChangedOptionsBaseSchema=z71.object({autoRefresh:z71.boolean().default(!0),debounceMs:z71.number().int().nonnegative().default(300)}),LoggingLevelSchema=z71.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),SetLevelRequestParamsSchema=BaseRequestParamsSchema.extend({level:LoggingLevelSchema}),SetLevelRequestSchema=RequestSchema.extend({method:z71.literal("logging/setLevel"),params:SetLevelRequestParamsSchema}),LoggingMessageNotificationParamsSchema=NotificationsParamsSchema.extend({level:LoggingLevelSchema,logger:z71.string().optional(),data:z71.unknown()}),LoggingMessageNotificationSchema=NotificationSchema.extend({method:z71.literal("notifications/message"),params:LoggingMessageNotificationParamsSchema}),ModelHintSchema=z71.object({name:z71.string().optional()}),ModelPreferencesSchema=z71.object({hints:z71.array(ModelHintSchema).optional(),costPriority:z71.number().min(0).max(1).optional(),speedPriority:z71.number().min(0).max(1).optional(),intelligencePriority:z71.number().min(0).max(1).optional()}),ToolChoiceSchema=z71.object({mode:z71.enum(["auto","required","none"]).optional()}),ToolResultContentSchema=z71.object({type:z71.literal("tool_result"),toolUseId:z71.string().describe("The unique identifier for the corresponding tool call."),content:z71.array(ContentBlockSchema).default([]),structuredContent:z71.object({}).loose().optional(),isError:z71.boolean().optional(),_meta:z71.record(z71.string(),z71.unknown()).optional()}),SamplingContentSchema=z71.discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema]),SamplingMessageContentBlockSchema=z71.discriminatedUnion("type",[TextContentSchema,ImageContentSchema,AudioContentSchema,ToolUseContentSchema,ToolResultContentSchema]),SamplingMessageSchema=z71.object({role:RoleSchema,content:z71.union([SamplingMessageContentBlockSchema,z71.array(SamplingMessageContentBlockSchema)]),_meta:z71.record(z71.string(),z71.unknown()).optional()}),CreateMessageRequestParamsSchema=TaskAugmentedRequestParamsSchema.extend({messages:z71.array(SamplingMessageSchema),modelPreferences:ModelPreferencesSchema.optional(),systemPrompt:z71.string().optional(),includeContext:z71.enum(["none","thisServer","allServers"]).optional(),temperature:z71.number().optional(),maxTokens:z71.number().int(),stopSequences:z71.array(z71.string()).optional(),metadata:AssertObjectSchema.optional(),tools:z71.array(ToolSchema).optional(),toolChoice:ToolChoiceSchema.optional()}),CreateMessageRequestSchema=RequestSchema.extend({method:z71.literal("sampling/createMessage"),params:CreateMessageRequestParamsSchema}),CreateMessageResultSchema=ResultSchema.extend({model:z71.string(),stopReason:z71.optional(z71.enum(["endTurn","stopSequence","maxTokens"]).or(z71.string())),role:RoleSchema,content:SamplingContentSchema}),CreateMessageResultWithToolsSchema=ResultSchema.extend({model:z71.string(),stopReason:z71.optional(z71.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(z71.string())),role:RoleSchema,content:z71.union([SamplingMessageContentBlockSchema,z71.array(SamplingMessageContentBlockSchema)])}),BooleanSchemaSchema=z71.object({type:z71.literal("boolean"),title:z71.string().optional(),description:z71.string().optional(),default:z71.boolean().optional()}),StringSchemaSchema=z71.object({type:z71.literal("string"),title:z71.string().optional(),description:z71.string().optional(),minLength:z71.number().optional(),maxLength:z71.number().optional(),format:z71.enum(["email","uri","date","date-time"]).optional(),default:z71.string().optional()}),NumberSchemaSchema=z71.object({type:z71.enum(["number","integer"]),title:z71.string().optional(),description:z71.string().optional(),minimum:z71.number().optional(),maximum:z71.number().optional(),default:z71.number().optional()}),UntitledSingleSelectEnumSchemaSchema=z71.object({type:z71.literal("string"),title:z71.string().optional(),description:z71.string().optional(),enum:z71.array(z71.string()),default:z71.string().optional()}),TitledSingleSelectEnumSchemaSchema=z71.object({type:z71.literal("string"),title:z71.string().optional(),description:z71.string().optional(),oneOf:z71.array(z71.object({const:z71.string(),title:z71.string()})),default:z71.string().optional()}),LegacyTitledEnumSchemaSchema=z71.object({type:z71.literal("string"),title:z71.string().optional(),description:z71.string().optional(),enum:z71.array(z71.string()),enumNames:z71.array(z71.string()).optional(),default:z71.string().optional()}),SingleSelectEnumSchemaSchema=z71.union([UntitledSingleSelectEnumSchemaSchema,TitledSingleSelectEnumSchemaSchema]),UntitledMultiSelectEnumSchemaSchema=z71.object({type:z71.literal("array"),title:z71.string().optional(),description:z71.string().optional(),minItems:z71.number().optional(),maxItems:z71.number().optional(),items:z71.object({type:z71.literal("string"),enum:z71.array(z71.string())}),default:z71.array(z71.string()).optional()}),TitledMultiSelectEnumSchemaSchema=z71.object({type:z71.literal("array"),title:z71.string().optional(),description:z71.string().optional(),minItems:z71.number().optional(),maxItems:z71.number().optional(),items:z71.object({anyOf:z71.array(z71.object({const:z71.string(),title:z71.string()}))}),default:z71.array(z71.string()).optional()}),MultiSelectEnumSchemaSchema=z71.union([UntitledMultiSelectEnumSchemaSchema,TitledMultiSelectEnumSchemaSchema]),EnumSchemaSchema=z71.union([LegacyTitledEnumSchemaSchema,SingleSelectEnumSchemaSchema,MultiSelectEnumSchemaSchema]),PrimitiveSchemaDefinitionSchema=z71.union([EnumSchemaSchema,BooleanSchemaSchema,StringSchemaSchema,NumberSchemaSchema]),ElicitRequestFormParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:z71.literal("form").optional(),message:z71.string(),requestedSchema:z71.object({type:z71.literal("object"),properties:z71.record(z71.string(),PrimitiveSchemaDefinitionSchema),required:z71.array(z71.string()).optional()})}),ElicitRequestURLParamsSchema=TaskAugmentedRequestParamsSchema.extend({mode:z71.literal("url"),message:z71.string(),elicitationId:z71.string(),url:z71.string().url()}),ElicitRequestParamsSchema=z71.union([ElicitRequestFormParamsSchema,ElicitRequestURLParamsSchema]),ElicitRequestSchema=RequestSchema.extend({method:z71.literal("elicitation/create"),params:ElicitRequestParamsSchema}),ElicitationCompleteNotificationParamsSchema=NotificationsParamsSchema.extend({elicitationId:z71.string()}),ElicitationCompleteNotificationSchema=NotificationSchema.extend({method:z71.literal("notifications/elicitation/complete"),params:ElicitationCompleteNotificationParamsSchema}),ElicitResultSchema=ResultSchema.extend({action:z71.enum(["accept","decline","cancel"]),content:z71.preprocess(val2=>val2===null?void 0:val2,z71.record(z71.string(),z71.union([z71.string(),z71.number(),z71.boolean(),z71.array(z71.string())])).optional())}),ResourceTemplateReferenceSchema=z71.object({type:z71.literal("ref/resource"),uri:z71.string()});var PromptReferenceSchema=z71.object({type:z71.literal("ref/prompt"),name:z71.string()}),CompleteRequestParamsSchema=BaseRequestParamsSchema.extend({ref:z71.union([PromptReferenceSchema,ResourceTemplateReferenceSchema]),argument:z71.object({name:z71.string(),value:z71.string()}),context:z71.object({arguments:z71.record(z71.string(),z71.string()).optional()}).optional()}),CompleteRequestSchema=RequestSchema.extend({method:z71.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:z71.looseObject({values:z71.array(z71.string()).max(100),total:z71.optional(z71.number().int()),hasMore:z71.optional(z71.boolean())})}),RootSchema=z71.object({uri:z71.string().startsWith("file://"),name:z71.string().optional(),_meta:z71.record(z71.string(),z71.unknown()).optional()}),ListRootsRequestSchema=RequestSchema.extend({method:z71.literal("roots/list"),params:BaseRequestParamsSchema.optional()}),ListRootsResultSchema=ResultSchema.extend({roots:z71.array(RootSchema)}),RootsListChangedNotificationSchema=NotificationSchema.extend({method:z71.literal("notifications/roots/list_changed"),params:NotificationsParamsSchema.optional()}),ClientRequestSchema=z71.union([PingRequestSchema,InitializeRequestSchema,CompleteRequestSchema,SetLevelRequestSchema,GetPromptRequestSchema,ListPromptsRequestSchema,ListResourcesRequestSchema,ListResourceTemplatesRequestSchema,ReadResourceRequestSchema,SubscribeRequestSchema,UnsubscribeRequestSchema,CallToolRequestSchema,ListToolsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ClientNotificationSchema=z71.union([CancelledNotificationSchema,ProgressNotificationSchema,InitializedNotificationSchema,RootsListChangedNotificationSchema,TaskStatusNotificationSchema]),ClientResultSchema=z71.union([EmptyResultSchema,CreateMessageResultSchema,CreateMessageResultWithToolsSchema,ElicitResultSchema,ListRootsResultSchema,GetTaskResultSchema,ListTasksResultSchema,CreateTaskResultSchema]),ServerRequestSchema=z71.union([PingRequestSchema,CreateMessageRequestSchema,ElicitRequestSchema,ListRootsRequestSchema,GetTaskRequestSchema,GetTaskPayloadRequestSchema,ListTasksRequestSchema,CancelTaskRequestSchema]),ServerNotificationSchema=z71.union([CancelledNotificationSchema,ProgressNotificationSchema,LoggingMessageNotificationSchema,ResourceUpdatedNotificationSchema,ResourceListChangedNotificationSchema,ToolListChangedNotificationSchema,PromptListChangedNotificationSchema,TaskStatusNotificationSchema,ElicitationCompleteNotificationSchema]),ServerResultSchema=z71.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
|
|
1320
1320
|
]))`;continue}else if(source[i]==="$"){pattern+=`($|(?=[\r
|
|
1321
1321
|
]))`;continue}}if(flags.s&&source[i]==="."){pattern+=inCharGroup?`${source[i]}\r
|
|
1322
1322
|
`:`[${source[i]}\r
|