fimo 0.10.1-staging.2 → 0.10.1-staging.4

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.
@@ -4,6 +4,8 @@
4
4
 
5
5
  History is scoped to the selected project environment. A restore point records the environment's CMS content and the matching Git commit so code and content can be recovered together.
6
6
 
7
+ Fimo also creates restore points automatically after a successful deploy, on the destination of a completed environment merge, and after direct content editing has been quiet for 30 seconds. Rapid Studio auto-saves are grouped into one content point.
8
+
7
9
  ```bash
8
10
  fimo history list
9
11
  fimo history show <version-id>
@@ -37,4 +39,4 @@ If another history create, update, delete, or restore is already running, the co
37
39
 
38
40
  If content or Git restore does not finish cleanly, the command fails with `RESTORE_INCOMPLETE` and names the automatic safety point. Stop active editing, inspect the environment, and retry the restore. Collaborative-editor resync continues in the background after code and content are ready.
39
41
 
40
- Normal CMS edits, Git pushes, and unsaved collaborative-editor changes do not take the history-operation lock. Avoid starting a restore while someone is actively editing the same environment.
42
+ Normal CMS requests and Git pushes do not wait for snapshot creation. Their queued restore-point capture takes the history-operation lock later and retries if another History operation is active. Unsaved collaborative-editor changes are not captured. Avoid starting a restore while someone is actively editing the same environment.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "bundled": true,
3
3
  "bundler": "esbuild",
4
- "bundledAt": "2026-07-28T15:18:08.648Z",
4
+ "bundledAt": "2026-07-28T17:34:40.817Z",
5
5
  "cliVersion": "0.10.0",
6
6
  "external": [
7
7
  "oxc-parser",
package/dist/cli/index.js CHANGED
@@ -39,7 +39,7 @@ Expecting one of '${allowedValues.join("', '")}'`);return this._lifeCycleHooks[e
39
39
  `),this.outputHelp({error:!0}));let config=errorOptions||{},exitCode=config.exitCode||1,code2=config.code||"commander.error";this._exit(exitCode,code2,message)}_parseOptionsEnv(){this.options.forEach(option=>{if(option.envVar&&option.envVar in process8.env){let optionKey=option.attributeName();(this.getOptionValue(optionKey)===void 0||["default","config","env"].includes(this.getOptionValueSource(optionKey)))&&(option.required||option.optional?this.emit(`optionEnv:${option.name()}`,process8.env[option.envVar]):this.emit(`optionEnv:${option.name()}`))}})}_parseOptionsImplied(){let dualHelper=new DualOptions(this.options),hasCustomOptionValue=__name(optionKey=>this.getOptionValue(optionKey)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(optionKey)),"hasCustomOptionValue");this.options.filter(option=>option.implied!==void 0&&hasCustomOptionValue(option.attributeName())&&dualHelper.valueFromOption(this.getOptionValue(option.attributeName()),option)).forEach(option=>{Object.keys(option.implied).filter(impliedKey=>!hasCustomOptionValue(impliedKey)).forEach(impliedKey=>{this.setOptionValueWithSource(impliedKey,option.implied[impliedKey],"implied")})})}missingArgument(name){let message=`error: missing required argument '${name}'`;this.error(message,{code:"commander.missingArgument"})}optionMissingArgument(option){let message=`error: option '${option.flags}' argument missing`;this.error(message,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(option){let message=`error: required option '${option.flags}' not specified`;this.error(message,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(option,conflictingOption){let findBestOptionFromValue=__name(option2=>{let optionKey=option2.attributeName(),optionValue=this.getOptionValue(optionKey),negativeOption=this.options.find(target=>target.negate&&optionKey===target.attributeName()),positiveOption=this.options.find(target=>!target.negate&&optionKey===target.attributeName());return negativeOption&&(negativeOption.presetArg===void 0&&optionValue===!1||negativeOption.presetArg!==void 0&&optionValue===negativeOption.presetArg)?negativeOption:positiveOption||option2},"findBestOptionFromValue"),getErrorMessage=__name(option2=>{let bestOption=findBestOptionFromValue(option2),optionKey=bestOption.attributeName();return this.getOptionValueSource(optionKey)==="env"?`environment variable '${bestOption.envVar}'`:`option '${bestOption.flags}'`},"getErrorMessage"),message=`error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;this.error(message,{code:"commander.conflictingOption"})}unknownOption(flag2){if(this._allowUnknownOption)return;let suggestion="";if(flag2.startsWith("--")&&this._showSuggestionAfterError){let candidateFlags=[],command=this;do{let moreFlags=command.createHelp().visibleOptions(command).filter(option=>option.long).map(option=>option.long);candidateFlags=candidateFlags.concat(moreFlags),command=command.parent}while(command&&!command._enablePositionalOptions);suggestion=suggestSimilar(flag2,candidateFlags)}let message=`error: unknown option '${flag2}'${suggestion}`;this.error(message,{code:"commander.unknownOption"})}_excessArguments(receivedArgs){if(this._allowExcessArguments)return;let expected=this.registeredArguments.length,s=expected===1?"":"s",message=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;this.error(message,{code:"commander.excessArguments"})}unknownCommand(){let unknownName=this.args[0],suggestion="";if(this._showSuggestionAfterError){let candidateNames=[];this.createHelp().visibleCommands(this).forEach(command=>{candidateNames.push(command.name()),command.alias()&&candidateNames.push(command.alias())}),suggestion=suggestSimilar(unknownName,candidateNames)}let message=`error: unknown command '${unknownName}'${suggestion}`;this.error(message,{code:"commander.unknownCommand"})}version(str,flags,description){if(str===void 0)return this._version;this._version=str,flags=flags||"-V, --version",description=description||"output the version number";let versionOption=this.createOption(flags,description);return this._versionOptionName=versionOption.attributeName(),this._registerOption(versionOption),this.on("option:"+versionOption.name(),()=>{this._outputConfiguration.writeOut(`${str}
40
40
  `),this._exit(0,"commander.version",str)}),this}description(str,argsDescription){return str===void 0&&argsDescription===void 0?this._description:(this._description=str,argsDescription&&(this._argsDescription=argsDescription),this)}summary(str){return str===void 0?this._summary:(this._summary=str,this)}alias(alias){if(alias===void 0)return this._aliases[0];let command=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(command=this.commands[this.commands.length-1]),alias===command._name)throw new Error("Command alias can't be the same as its name");let matchingCommand=this.parent?._findCommand(alias);if(matchingCommand){let existingCmd=[matchingCommand.name()].concat(matchingCommand.aliases()).join("|");throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`)}return command._aliases.push(alias),this}aliases(aliases2){return aliases2===void 0?this._aliases:(aliases2.forEach(alias=>this.alias(alias)),this)}usage(str){if(str===void 0){if(this._usage)return this._usage;let args=this.registeredArguments.map(arg=>humanReadableArgName(arg));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?args:[]).join(" ")}return this._usage=str,this}name(str){return str===void 0?this._name:(this._name=str,this)}nameFromFilename(filename){return this._name=path47.basename(filename,path47.extname(filename)),this}executableDir(path48){return path48===void 0?this._executableDir:(this._executableDir=path48,this)}helpInformation(contextOptions){let helper=this.createHelp(),context=this._getOutputContext(contextOptions);helper.prepareContext({error:context.error,helpWidth:context.helpWidth,outputHasColors:context.hasColors});let text3=helper.formatHelp(this,helper);return context.hasColors?text3:this._outputConfiguration.stripColor(text3)}_getOutputContext(contextOptions){contextOptions=contextOptions||{};let error=!!contextOptions.error,baseWrite,hasColors,helpWidth;return error?(baseWrite=__name(str=>this._outputConfiguration.writeErr(str),"baseWrite"),hasColors=this._outputConfiguration.getErrHasColors(),helpWidth=this._outputConfiguration.getErrHelpWidth()):(baseWrite=__name(str=>this._outputConfiguration.writeOut(str),"baseWrite"),hasColors=this._outputConfiguration.getOutHasColors(),helpWidth=this._outputConfiguration.getOutHelpWidth()),{error,write:__name(str=>(hasColors||(str=this._outputConfiguration.stripColor(str)),baseWrite(str)),"write"),hasColors,helpWidth}}outputHelp(contextOptions){let deprecatedCallback;typeof contextOptions=="function"&&(deprecatedCallback=contextOptions,contextOptions=void 0);let outputContext=this._getOutputContext(contextOptions),eventContext={error:outputContext.error,write:outputContext.write,command:this};this._getCommandAndAncestors().reverse().forEach(command=>command.emit("beforeAllHelp",eventContext)),this.emit("beforeHelp",eventContext);let helpInformation=this.helpInformation({error:outputContext.error});if(deprecatedCallback&&(helpInformation=deprecatedCallback(helpInformation),typeof helpInformation!="string"&&!Buffer.isBuffer(helpInformation)))throw new Error("outputHelp callback must return a string or a Buffer");outputContext.write(helpInformation),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",eventContext),this._getCommandAndAncestors().forEach(command=>command.emit("afterAllHelp",eventContext))}helpOption(flags,description){return typeof flags=="boolean"?(flags?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(flags=flags??"-h, --help",description=description??"display help for command",this._helpOption=this.createOption(flags,description),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(option){return this._helpOption=option,this}help(contextOptions){this.outputHelp(contextOptions);let exitCode=Number(process8.exitCode??0);exitCode===0&&contextOptions&&typeof contextOptions!="function"&&contextOptions.error&&(exitCode=1),this._exit(exitCode,"commander.help","(outputHelp)")}addHelpText(position,text3){let allowedValues=["beforeAll","before","after","afterAll"];if(!allowedValues.includes(position))throw new Error(`Unexpected value for position to addHelpText.
41
41
  Expecting one of '${allowedValues.join("', '")}'`);let helpEvent=`${position}Help`;return this.on(helpEvent,context=>{let helpStr;typeof text3=="function"?helpStr=text3({error:context.error,command:context.command}):helpStr=text3,helpStr&&context.write(`${helpStr}
42
- `)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();helpOption&&args.find(arg=>helpOption.is(arg))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;return(match=arg.match(/^(--inspect(-brk)?)$/))!==null?debugOption=match[1]:(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(debugOption=match[1],/^\d+$/.test(match[3])?debugPort=match[3]:debugHost=match[3]):(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match[1],debugHost=match[3],debugPort=match[4]),debugOption&&debugPort!=="0"?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}__name(incrementNodeInspectorPort,"incrementNodeInspectorPort");function useColor(){if(process8.env.NO_COLOR||process8.env.FORCE_COLOR==="0"||process8.env.FORCE_COLOR==="false")return!1;if(process8.env.FORCE_COLOR||process8.env.CLICOLOR_FORCE!==void 0)return!0}__name(useColor,"useColor");exports2.Command=Command2;exports2.useColor=useColor}});var require_commander=__commonJS({"../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js"(exports2){var{Argument:Argument2}=require_argument(),{Command:Command2}=require_command(),{CommanderError:CommanderError2,InvalidArgumentError:InvalidArgumentError2}=require_error(),{Help:Help2}=require_help(),{Option:Option2}=require_option();exports2.program=new Command2;exports2.createCommand=name=>new Command2(name);exports2.createOption=(flags,description)=>new Option2(flags,description);exports2.createArgument=(name,description)=>new Argument2(name,description);exports2.Command=Command2;exports2.Option=Option2;exports2.Argument=Argument2;exports2.Help=Help2;exports2.CommanderError=CommanderError2;exports2.InvalidArgumentError=InvalidArgumentError2;exports2.InvalidOptionArgumentError=InvalidArgumentError2}});import{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,RESERVED_CONTENT_FIELD_NAMES,CONTENT_TYPE_NAME_PATTERN,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION,CONTENT_FIELD_NAME_PATTERN,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION,init_common=__esm({"../../packages/api-contracts/dist/esm/types/common.js"(){"use strict";CommonSchemas={timestamp: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"]),RESERVED_CONTENT_FIELD_NAMES=["id","entryId","documentId","slug","locale","createdAt","updatedAt","__fimo"],CONTENT_TYPE_NAME_PATTERN=/^[A-Za-z]\w*$/,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter",CONTENT_FIELD_NAME_PATTERN=/^[A-Za-z_]\w*$/,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter or underscore"}});var ATTACHMENT_TYPES,ATTACHMENT_MIME_TYPES,ATTACHMENT_IMAGE_MIME_TYPES,ATTACHMENT_DOCUMENT_MIME_TYPES,ATTACHMENT_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image"},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image"},{mime:"image/webp",extensions:[".webp"],category:"image"},{mime:"image/avif",extensions:[".avif"],category:"image"},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:5242880},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:5242880},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:5242880}],ATTACHMENT_MIME_TYPES=ATTACHMENT_TYPES.map(t2=>t2.mime),ATTACHMENT_IMAGE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="image").map(t2=>t2.mime),ATTACHMENT_DOCUMENT_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="document").map(t2=>t2.mime),ATTACHMENT_ACCEPT_EXTENSIONS=ATTACHMENT_TYPES.flatMap(t2=>t2.extensions),ATTACHMENT_ACCEPT_STRING=[...ATTACHMENT_ACCEPT_EXTENSIONS,...ATTACHMENT_MIME_TYPES].join(","),ATTACHMENT_DROPZONE_ACCEPT=Object.fromEntries(ATTACHMENT_TYPES.map(t2=>[t2.mime,t2.extensions]))}});import{z as 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,path47){let conditionPath=[...path47,fieldName,condition.key],trigger=fields[clause.field];if(trigger===void 0)return[{path:conditionPath,message:`"${condition.key}" references unknown field "${clause.field}".`}];if(trigger.showIf!==void 0||trigger.showIfAny!==void 0)return[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is conditional too. Conditions are one level deep.`}];if(trigger.type!=="boolean"&&trigger.type!=="number"&&trigger.type!=="string")return[{path:conditionPath,message:`"${condition.key}" can only reference boolean, number, and string fields. "${clause.field}" is a ${trigger.type} field.`}];let triggerOptions=trigger.type==="string"?trigger.options:void 0;if(trigger.type==="string"&&triggerOptions===void 0)return[{path:conditionPath,message:`"${condition.key}" can only reference a string field that declares "options". Add options to "${clause.field}".`}];let values=getConditionValues(clause);if(values.some(value=>typeof value!==trigger.type))return[{path:conditionPath,message:`"${condition.key}" on "${clause.field}" expects a ${trigger.type} value.`}];if(triggerOptions!==void 0){let invalidValues=values.filter(value=>!triggerOptions.includes(value));if(invalidValues.length>0)return invalidValues.map(value=>({path:conditionPath,message:`"${value}" is not one of the options declared by "${clause.field}".`}))}return trigger.editable===!1?[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is not editable.`}]:[]}function collectConditionProblems(fields){let problems=[],walk=__name((currentFields,path47)=>{for(let[fieldName,field]of Object.entries(currentFields)){let condition=getConditionDefinition(field);if(condition!==void 0)for(let clause of condition.clauses)problems.push(...collectClauseProblems(fieldName,condition,clause,currentFields,path47));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path47,fieldName,variant.uid]);else walk(field.schema.fields,[...path47,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path47,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path47,fieldName];visit2({field,path:fieldPath,structuredDepth,insideStructuredContent});let nextDepth=structuredDepth+1;if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...fieldPath,variant.uid],nextDepth,!0);else walk(field.schema.fields,fieldPath,nextDepth,!0)}},"walk");walk(fields,[],0,!1)}var UNIQUE_FIELD_TYPES,utf8,MAX_STRUCTURED_CONTENT_DEPTH,MAX_BLOCK_VARIANTS,MAX_BLOCK_ITEMS,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES,showIfClauseSchema,commonFieldShape,FIELD_I18N_UNSUPPORTED_MESSAGE,uniqueFieldTypes,UNSUPPORTED_UNIQUE_MESSAGE,scalarFieldSchema,referenceFieldSchema,reservedStructuredContentNames,ContentFieldDefinitionSchema,blockFieldsSchema,blockVariantSchema,fixedBlocksSchema,blocksSchema,blocksFieldSchema,contentFieldDefinitionSchema,init_content_fields=__esm({"../../packages/api-contracts/dist/esm/types/content-fields.js"(){"use strict";init_common();UNIQUE_FIELD_TYPES=["string","text","number","boolean","date"],utf8=new TextEncoder,MAX_STRUCTURED_CONTENT_DEPTH=3,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],showIfClauseSchema=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"],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,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:sentry:read","ops:logs:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview","ops:notification:approve","ops:notification:send"],OpsPermissionSchema=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:investigations:read","ops:investigations:write","ops:known-issues:read","ops:validations:read","ops:notification:preview"],engineer:["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:sentry:read","ops:logs:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview"],full:[...OPS_PERMISSIONS]},OPS_SERVICE_PERMISSION_PRESETS={support:OPS_PERMISSION_PRESETS.support,engineer:OPS_PERMISSION_PRESETS.engineer,full:OPS_PERMISSION_PRESETS.full.filter(permission=>permission!=="ops:notification:approve")},OpsAccessGrantInputSchema=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)})}});import{z as z10}from"zod";var ProjectDTOSchema,ProjectDTO,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,QuestionAnswerMetadataSchema,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_common();init_create_dto();init_response();ProjectDTOSchema=BaseEntitySchema.extend({name:z10.string(),displayName:z10.string().nullable(),subdomain:z10.string().nullable().optional(),subdomainUpdatedAt:z10.date().nullable().optional(),organizationId:z10.string().nullable(),createdBy:z10.string().nullable(),visibility:ProjectVisibilitySchema,previewEnabled:z10.boolean().default(!0),status:ProjectStatusSchema,creationStatus:z10.string(),thumbnailUrl:z10.string().nullable(),publishedThumbnailUrl:z10.string().nullable(),category:z10.string().nullable(),appUrl:z10.string().nullable(),lastPublishedAt:z10.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z10.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z10.object({id:z10.uuid(),name:z10.string(),displayName:z10.string().nullable(),thumbnailUrl:z10.string().nullable(),visibility:ProjectVisibilitySchema,category:z10.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z10.object({id:z10.string(),name:z10.string(),avatar:z10.string().nullable(),color:z10.object({bg:z10.string(),text:z10.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z10.object({path:z10.string(),content:z10.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z10.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z10.object({id:z10.string(),messageId:z10.string(),versionId:z10.string().nullable(),role:ProjectChatMessageRole,parts:z10.array(z10.any()),createdAt:z10.coerce.date()}),MessageUserMetadataSchema=z10.object({id:z10.string(),name:z10.string().nullable().optional(),image:z10.string().nullable().optional()}).nullable().optional(),QuestionAnswerMetadataSchema=z10.object({shortTitle:z10.string().optional(),questions:z10.array(z10.object({header:z10.string(),question:z10.string(),answer:z10.string(),selectedLabels:z10.array(z10.string()),freeText:z10.string(),skipped:z10.boolean()}))}).optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z10.number(),metadata:z10.object({user:MessageUserMetadataSchema,changeManifest:z10.array(z10.any()).optional(),questionAnswer:QuestionAnswerMetadataSchema}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z10.object({versionId:z10.uuid(),commitHash:z10.string(),name:z10.string(),description:z10.string().nullable(),kind:z10.enum(["manual","agent","restore-safety","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z10.object({versionCount:z10.number().int().nonnegative(),snapshotBytes:z10.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z10.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z10.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z10.object({content:z10.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z10.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z10.object({success:z10.boolean(),message:z10.string().optional(),warning:z10.string().optional(),durationMs:z10.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z10.object({isPublished:z10.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z10.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublicationMutationDTOSchema=z10.object({success:z10.boolean(),message:z10.string().optional(),publishedAt:CommonSchemas.timestamp.optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z11}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=z11.enum(["provisioning","active","deleted"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z11.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,previewUrl:z11.string().nullable(),parentEnv:EnvSchema.nullable(),createdBy:z11.string().nullable(),deletedAt:z11.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),CreateProjectEnvRequestSchema=z11.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z11.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z11.array(ProjectEnvDTOSchema)),EnvSurfaceDiffSchema=z11.object({surface:z11.enum(["code","schemas","content","translations","assets","forms","activations"]),status:z11.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z11.number().int().nonnegative(),conflictCount:z11.number().int().nonnegative()}),EnvDiffResultSchema=z11.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z11.coerce.date(),surfaces:z11.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z12}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=z12.object({success:z12.literal(!0),downloadUrl:z12.string(),expiresAt:z12.string(),fileSize:z12.number(),duration:z12.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z12.object({success:z12.literal(!0),projectId:z12.string(),projectName:z12.string(),displayName:z12.string(),projectUrl:z12.string(),duration:z12.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z12.object({contentTypes:z12.number(),entries:z12.number(),assets:z12.number(),translations:z12.number(),forms:z12.number(),codeFiles:z12.number(),assetFiles:z12.number()}),ImportPreviewSurfaceDTOSchema=z12.object({name:z12.string(),included:z12.boolean(),count:z12.number().optional(),note:z12.string().optional()}),ImportPreviewDTOSchema=z12.object({projectName:z12.string(),displayName:z12.string().nullable(),visibility:z12.string().nullable(),category:z12.string().nullable(),exportedAt:z12.string(),version:z12.string(),envScope:z12.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z12.array(ImportPreviewSurfaceDTOSchema),fileSize:z12.number(),fileName:z12.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z12.object({success:z12.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z13}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=z13.enum(["manual","schedule","webhook"]),ManualTriggerSchema=z13.object({type:z13.literal("manual")}),ScheduleTriggerSchema=z13.object({type:z13.literal("schedule"),cron:z13.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:z13.string().optional()}),WebhookTriggerSchema=z13.object({type:z13.literal("webhook"),path:z13.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z13.discriminatedUnion("type",[ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema])}});import{z as z14}from"zod";var ActivateRequestSchema,DeactivateRequestSchema,AgentActivationDTOSchema,AgentActivationDTO,AgentActivationsListResponseSchema,AgentActivationResponseSchema,WebhookPathTakenErrorSchema,ManualRunRequestSchema,DispatchSkippedSchema,DispatchAcceptedSchema,ManualRunResponseSchema,init_agent_activation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-activation.dto.js"(){"use strict";init_env();init_create_dto();init_response();init_agent_trigger_dto();ActivateRequestSchema=z14.object({triggerIndices:z14.array(z14.number().int().nonnegative()).optional()}),DeactivateRequestSchema=z14.object({triggerIndices:z14.array(z14.number().int().nonnegative()).optional()}),AgentActivationDTOSchema=z14.object({projectId:z14.uuid(),env:EnvSchema,agentName:z14.string().min(1),triggerIndex:z14.number().int().nonnegative(),triggerKind:TriggerKindSchema,trigger:TriggerSchema,enabled:z14.boolean(),lastFiredAt:z14.coerce.date().nullable(),webhookPath:z14.string().nullable(),createdAt:z14.coerce.date(),updatedAt:z14.coerce.date()}),AgentActivationDTO=createDTO(AgentActivationDTOSchema),AgentActivationsListResponseSchema=createResponseSchema(z14.array(AgentActivationDTOSchema)),AgentActivationResponseSchema=createResponseSchema(AgentActivationDTOSchema),WebhookPathTakenErrorSchema=z14.object({error:z14.literal("webhook_path_taken"),conflictAgent:z14.string(),path:z14.string()}),ManualRunRequestSchema=z14.object({args:z14.unknown().optional(),requestId:z14.string().min(1).max(128).optional()}),DispatchSkippedSchema=z14.object({skipped:z14.enum(["duplicate","no-activation","agent-not-cloud","bundle-missing","trigger-stale"])}),DispatchAcceptedSchema=z14.object({sessionId:z14.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z14.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});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,AgentListItemActivationSchema,AgentListItemDTOSchema,AgentListItemDTO,AgentListResponseSchema,init_agent_list_item_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-list-item.dto.js"(){"use strict";init_create_dto();init_response();init_agent_install_summary_dto();init_agent_trigger_dto();AgentListItemTriggerSchema=z16.object({kind:TriggerKindSchema,summary:z16.string()}),AgentListItemActivationSchema=z16.object({triggerIndex:z16.number().int().nonnegative(),triggerKind:TriggerKindSchema,env:z16.string().min(1),active:z16.boolean()}),AgentListItemDTOSchema=z16.object({name:z16.string().min(1),description:z16.string().nullable(),goalFirstLine:z16.string().nullable(),declaredCapabilities:z16.array(CapabilitySummaryEntrySchema),triggers:z16.array(AgentListItemTriggerSchema),activations:z16.array(AgentListItemActivationSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z16.array(AgentListItemDTOSchema))}});import{z as z17}from"zod";var AgentSessionStatusSchema,SessionMetricsSchema,AgentSessionDTOSchema,AgentSessionDTO,AgentSessionCheckpointDTOSchema,AgentSessionCheckpointDTO,AgentSessionResponseSchema,AgentSessionsListResponseSchema,AgentSessionCheckpointsListResponseSchema,AgentSessionWithCheckpointsResponseSchema,SessionErrorCodeSchema,CancelSessionRequestSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_env();init_create_dto();init_response();init_agent_trigger_dto();AgentSessionStatusSchema=z17.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z17.object({cpuMs:z17.number().nonnegative().default(0),netBytes:z17.number().nonnegative().default(0),walltimeMs:z17.number().nonnegative().default(0),llmTokensIn:z17.number().nonnegative().optional(),llmTokensOut:z17.number().nonnegative().optional()}),AgentSessionDTOSchema=z17.object({id:z17.uuid(),projectId:z17.uuid(),env:EnvSchema,agentName:z17.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z17.unknown().optional(),capabilities:z17.array(z17.string()).optional(),dataSources:z17.array(z17.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z17.string().nullable(),startedAt:z17.coerce.date().nullable(),finishedAt:z17.coerce.date().nullable(),cancelledAt:z17.coerce.date().nullable(),costUsd:z17.number().nonnegative(),costCeilingUsd:z17.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z17.boolean(),lastCheckpointId:z17.uuid().nullable(),branchEnvId:z17.uuid().nullable(),parentSessionId:z17.uuid().nullable(),terminalReason:z17.string().nullable(),errorMessage:z17.string().nullable(),report:z17.string().nullable(),createdAt:z17.coerce.date(),updatedAt:z17.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z17.object({id:z17.uuid(),sessionId:z17.uuid(),checkpointIdx:z17.number().int().nonnegative(),payloadRef:z17.string(),payloadSizeBytes:z17.number().int().nonnegative(),checksum:z17.string().length(64),createdAt:z17.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z17.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z17.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z17.object({session:AgentSessionDTOSchema,checkpoints:z17.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z17.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","too_many_agent_envs","env_provisioning_failed"]),CancelSessionRequestSchema=z17.object({reason:z17.string().min(1).max(120).optional()})}});import{z as z18}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=z18.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z18.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z18.object({id:z18.uuid(),envId:z18.uuid(),sessionId:z18.uuid().nullable(),skillName:z18.string().min(1),classification:AgentBranchClassificationSchema,rationale:z18.string().nullable(),summary:z18.string().nullable(),surfaceDeltas:z18.record(z18.string(),z18.unknown()),createdAt:z18.coerce.date(),decidedAt:z18.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z18.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z18.object({path:z18.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z18.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z18.object({code:z18.literal("merge_conflict"),message:z18.string(),conflicts:z18.record(z18.string(),z18.number().int().nonnegative())})}});import{z as z19}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,SetProjectIntegrationCredentialRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,ConnectOrganizationIntegrationRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,BindProjectChannelRequestSchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolOptionsSchema,RunProjectIntegrationToolRequestSchema,ProjectIntegrationToolRunUsageSchema,ProjectIntegrationToolRunBillingSchema,FirecrawlScrapeToolOutputSchema,FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlMonitorScheduleOutputSchema,FirecrawlMonitorTargetOutputSchema,FirecrawlMonitorOutputSchema,FirecrawlMonitorCheckOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema,FirecrawlToolKeySchema,FirecrawlToolOutputSchema,ProjectIntegrationToolRunBaseSchema,ProjectIntegrationToolRunDTOSchema,ProjectIntegrationToolRunDTO,IntegrationsListResponseSchema,IntegrationInfoResponseSchema,ProjectIntegrationStatusResponseSchema,ProjectIntegrationInstallationResponseSchema,ProjectIntegrationToolRunResponseSchema,StartProjectIntegrationConnectResponseResponseSchema,OrganizationIntegrationConnectionResponseSchema,ProjectChannelBindingResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z19.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z19.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z19.enum(["secret_text"]),IntegrationCredentialUsageSchema=z19.enum(["http_bearer","api_key"]),ProjectIntegrationCredentialStatusSchema=z19.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z19.object({mode:IntegrationAuthModeSchema,label:z19.string().min(1),description:z19.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z19.object({id:z19.string().min(1),label:z19.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z19.boolean()}),IntegrationToolDefinitionDTOSchema=z19.object({key:z19.string().min(1),name:z19.string().min(1),description:z19.string().min(1)}),IntegrationRecipeDTOSchema=z19.object({title:z19.string().min(1),description:z19.string().min(1),command:z19.string().min(1).optional()}),IntegrationInfoDTOSchema=z19.object({key:z19.string().min(1),name:z19.string().min(1),summary:z19.string().min(1),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z19.array(IntegrationAuthModeDTOSchema),credentials:z19.array(IntegrationCredentialDefinitionDTOSchema),tools:z19.array(IntegrationToolDefinitionDTOSchema),recipes:z19.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z19.object({projectId:z19.uuid(),integrationKey:z19.string().min(1),installed:z19.boolean(),enabled:z19.boolean(),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z19.string().nullable(),connectionId:z19.uuid().nullable().optional(),connectionAlias:z19.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z19.array(z19.string()),installedAt:z19.coerce.date().nullable(),updatedAt:z19.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z19.object({id:z19.uuid(),projectId:z19.uuid(),integrationKey:z19.string().min(1),enabled:z19.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z19.string(),connectionId:z19.uuid().nullable().optional(),connectionAlias:z19.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z19.array(z19.string()),createdAt:z19.coerce.date(),updatedAt:z19.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z19.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z19.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z19.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z19.object({value:z19.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z19.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z19.object({id:z19.uuid(),organizationId:z19.string().min(1),integrationKey:z19.string().min(1),alias:z19.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z19.string().min(1),externalAccountName:z19.string().nullable(),externalBotUserId:z19.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z19.array(z19.string()),connectedAt:z19.coerce.date(),updatedAt:z19.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ConnectOrganizationIntegrationRequestSchema=z19.object({alias:z19.string().min(1).max(120).optional(),token:z19.string().min(1).optional()}),StartProjectIntegrationConnectResponseSchema=z19.object({integrationKey:z19.string().min(1),connectUrl:z19.string().url(),expiresAt:z19.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),BindProjectChannelRequestSchema=z19.object({ref:z19.string().min(1),connectionAlias:z19.string().min(1).optional(),agentName:z19.string().min(1).max(160).nullable().optional(),force:z19.boolean().optional()}),ProjectChannelBindingDTOSchema=z19.object({id:z19.uuid(),projectId:z19.uuid(),integrationKey:z19.string().min(1),connectionId:z19.uuid(),externalWorkspaceId:z19.string().min(1),externalChannelId:z19.string().min(1),externalChannelName:z19.string().nullable(),agentName:z19.string().nullable(),enabled:z19.boolean(),createdAt:z19.coerce.date(),updatedAt:z19.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),FirecrawlScrapeFormatsSchema=z19.object({markdown:z19.boolean().optional(),summary:z19.boolean().optional(),links:z19.boolean().optional(),images:z19.boolean().optional(),html:z19.union([z19.literal("cleaned"),z19.literal("raw"),z19.boolean()]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z19.object({url:z19.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z19.boolean().optional(),timeoutMs:z19.number().int().positive().max(12e4).optional(),waitForMs:z19.number().int().min(0).max(3e4).optional()}),FirecrawlSearchToolInputSchema=z19.object({query:z19.string().min(1),maxResults:z19.number().int().positive().max(20).optional(),sources:z19.array(z19.enum(["web","news","images"])).min(1).max(3).optional(),categories:z19.array(z19.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z19.array(z19.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z19.array(z19.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z19.enum(["hour","day","week","month","year"]).optional(),location:z19.string().min(1).max(160).optional(),country:z19.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z19.boolean().optional(),timeoutMs:z19.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlMapToolInputSchema=z19.object({url:z19.string().url(),search:z19.string().min(1).optional(),limit:z19.number().int().positive().max(200).optional(),includeSubdomains:z19.boolean().optional(),timeoutMs:z19.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z19.object({url:z19.string().url(),limit:z19.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z19.boolean().optional(),timeoutMs:z19.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z19.object({text:z19.string().min(1).max(200).optional(),cron:z19.string().min(1).max(120).optional(),timezone:z19.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorTargetInputSchema=z19.object({type:z19.enum(["scrape","crawl"]).default("scrape"),urls:z19.array(z19.string().url()).min(1).max(50),scrapeOptions:z19.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z19.boolean().optional(),timeoutMs:z19.number().int().positive().max(12e4).optional(),waitForMs:z19.number().int().min(0).max(3e4).optional()}).optional()}),FirecrawlMonitorCreateToolInputSchema=z19.object({name:z19.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z19.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z19.string().min(1).max(2e3).optional(),judgeEnabled:z19.boolean().optional(),retentionDays:z19.number().int().min(1).max(365).optional(),notification:z19.object({email:z19.object({enabled:z19.boolean().default(!0),recipients:z19.array(z19.string().email()).min(1).max(20),includeDiffs:z19.boolean().optional()}).optional()}).optional()}),FirecrawlMonitorIdToolInputSchema=z19.object({monitorId:z19.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z19.string().uuid()}),RunProjectIntegrationToolOptionsSchema=z19.object({connectionAlias:z19.string().min(1).optional()}),RunProjectIntegrationToolRequestSchema=z19.discriminatedUnion("tool",[RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("search"),input:FirecrawlSearchToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("scrape"),input:FirecrawlScrapeToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("map"),input:FirecrawlMapToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("crawl"),input:FirecrawlCrawlToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.create"),input:FirecrawlMonitorCreateToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.list"),input:z19.object({}).default({})}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.get"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.pause"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.resume"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.delete"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.run"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.checks"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.check"),input:FirecrawlMonitorCheckToolInputSchema})]),ProjectIntegrationToolRunUsageSchema=z19.object({provider:z19.string().min(1),providerCredits:z19.number().nonnegative().optional(),providerCostUsd:z19.number().nonnegative().optional(),requests:z19.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z19.object({credits:z19.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z19.object({url:z19.string(),provider:z19.literal("firecrawl"),title:z19.string().optional(),statusCode:z19.number().optional(),markdown:z19.string().optional(),summary:z19.string().optional(),links:z19.array(z19.string()).optional(),images:z19.array(z19.string()).optional(),html:z19.string().optional(),warning:z19.string().optional()}),FirecrawlSearchToolOutputSchema=z19.object({query:z19.string(),provider:z19.literal("firecrawl"),warning:z19.string().optional(),results:z19.array(z19.object({title:z19.string(),url:z19.string(),snippet:z19.string().optional(),content:z19.string().optional(),score:z19.number().optional(),publishedAt:z19.string().optional()}))}),FirecrawlMapToolOutputSchema=z19.object({url:z19.string(),provider:z19.literal("firecrawl"),count:z19.number(),links:z19.array(z19.object({url:z19.string(),title:z19.string().optional(),description:z19.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z19.object({url:z19.string(),provider:z19.literal("firecrawl"),total:z19.number(),pages:z19.array(z19.object({url:z19.string(),title:z19.string().optional(),statusCode:z19.number().optional(),markdown:z19.string().optional(),summary:z19.string().optional(),links:z19.array(z19.string()).optional(),images:z19.array(z19.string()).optional(),html:z19.string().optional(),warning:z19.string().optional()})),warning:z19.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z19.object({cron:z19.string().optional(),text:z19.string().optional(),timezone:z19.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z19.object({id:z19.string().optional(),urls:z19.array(z19.string()).optional(),scrapeOptions:z19.record(z19.string(),z19.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z19.object({id:z19.string(),name:z19.string(),status:z19.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z19.string().nullable().optional(),lastRunAt:z19.string().nullable().optional(),currentCheckId:z19.string().nullable().optional(),targets:z19.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z19.string().nullable().optional(),judgeEnabled:z19.boolean().optional(),estimatedCreditsPerMonth:z19.number().optional(),createdAt:z19.string().optional(),updatedAt:z19.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z19.object({id:z19.string(),monitorId:z19.string(),scheduledFor:z19.string().nullable().optional(),startedAt:z19.string().nullable().optional(),finishedAt:z19.string().nullable().optional(),estimatedCredits:z19.number().optional(),reservedCredits:z19.number().optional(),actualCredits:z19.number().optional(),billingStatus:z19.string().nullable().optional(),summary:z19.object({totalPages:z19.number().optional(),same:z19.number().optional(),changed:z19.number().optional(),new:z19.number().optional(),removed:z19.number().optional(),error:z19.number().optional()}).passthrough().optional(),error:z19.string().nullable().optional(),createdAt:z19.string().optional(),updatedAt:z19.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z19.object({provider:z19.literal("firecrawl"),monitors:z19.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z19.object({provider:z19.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z19.object({provider:z19.literal("firecrawl"),monitorId:z19.string(),deleted:z19.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z19.object({provider:z19.literal("firecrawl"),monitorId:z19.string(),checks:z19.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z19.object({provider:z19.literal("firecrawl"),monitorId:z19.string(),check:FirecrawlMonitorCheckOutputSchema,next:z19.string().optional()}),FirecrawlToolKeySchema=z19.enum(["search","scrape","map","crawl","monitor.create","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z19.union([FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z19.object({projectId:z19.uuid(),integrationKey:z19.string().min(1),tool:FirecrawlToolKeySchema,connectionAlias:z19.string().min(1).nullable().optional(),output:FirecrawlToolOutputSchema,executedAt:z19.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z19.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z19.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z19.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z19.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z19.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z19.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z19.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z19.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema)}});import{z as z20}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=z20.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=z20.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z20.uuid(),env:z20.string().min(1),name:z20.string().min(1),cron:z20.string().min(1),command:z20.string().min(1),secretKeys:z20.array(z20.string().min(1)),enabled:z20.boolean(),lastRunAt:z20.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z20.string().nullable()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z20.object({name:z20.string().min(1).max(120),cron:z20.string().min(1).max(120),command:z20.string().min(1).max(500),secretKeys:z20.array(ProjectSecretKeySchema).default([])}),UpdateProjectScheduleRequestSchema=z20.object({name:z20.string().min(1).max(120).optional(),cron:z20.string().min(1).max(120).optional(),command:z20.string().min(1).max(500).optional(),secretKeys:z20.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z20.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z20.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z20.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z20.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z20.object({maxRuns:z20.number().int().positive(),retentionDays:z20.number().int().positive().nullable(),outputRetentionDays:z20.number().int().positive(),maxOutputBytes:z20.number().int().positive()}),ProjectScheduleUsageSchema=z20.object({runCount:z20.number().int().nonnegative(),runsWithOutput:z20.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z20.object({id:z20.uuid(),scheduleId:z20.uuid(),projectId:z20.uuid(),env:z20.string().min(1),scheduleName:z20.string().min(1),command:z20.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z20.object({id:z20.string().min(1),name:z20.string().min(1)}).nullable(),queuedAt:z20.coerce.date(),startedAt:z20.coerce.date().nullable(),finishedAt:z20.coerce.date().nullable(),exitCode:z20.number().int().nullable(),errorCode:z20.string().nullable(),error:z20.string().nullable(),outputBytes:z20.number().int().nonnegative(),outputTruncated:z20.boolean(),outputExpiresAt:z20.coerce.date().nullable(),metadataExpiresAt:z20.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z20.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z20.coerce.date().nullable(),items:z20.array(z20.object({key:z20.string().min(1),updatedAt:z20.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z20.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z20.object({trigger:z20.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z20.object({limit:z20.coerce.number().int().min(1).max(100).default(25),cursor:z20.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z20.object({items:z20.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z20.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z20.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z20.object({items:z20.array(ProjectScheduleRunDTOSchema),nextCursor:z20.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z21}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=z21.object({id:z21.uuid(),occurredAt:z21.coerce.date(),projectId:z21.uuid().nullable(),env:z21.string().nullable(),actor:z21.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z21.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z21.unknown().optional(),ipAddress:z21.string().nullable().optional(),userAgent:z21.string().nullable().optional(),error:z21.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z21.object({rows:z21.array(AuditLogRowDTOSchema),nextCursor:z21.string().nullable()})),AuditLogQuerySchema=z21.object({env:z21.string().optional(),action:AuditActionSchema.optional(),actor:z21.string().optional(),from:z21.coerce.date().optional(),to:z21.coerce.date().optional(),limit:z21.coerce.number().int().min(1).max(200).optional(),cursor:z21.string().optional()})}});import{z as z22}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,ActivationSnapshotSchema,ActivationDiffSchema,ActivationDiffDTO,ActivationDiffResponseSchema,CONFLICT_KINDS,ConflictKindSchema,ConflictSchema,FieldPickSchema,ConflictResolutionSchema,MergeResultSchema,MergeResultDTO,MergeResultResponseSchema,EngineStrategySchema,VendorStrategySchema,MergeStrategySchema,ResolvedStrategySchema,MergeRequestSchema,MergeInitiateResultSchema,MergeInitiateResultDTO,MergeInitiateResponseSchema,MergeConflictsHydrationSchema,MergeConflictsHydrationDTO,MergeConflictsHydrationResponseSchema,MergeResolveDraftRequestSchema,MergeResolveDraftResultSchema,MergeResolveDraftResultDTO,MergeResolveRequestSchema,MergeCancelRequestSchema,PublishReleaseRequestSchema,PublishReleaseResultSchema,PublishReleaseResultDTO,PublishReleaseResponseSchema,init_env_status_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-status.dto.js"(){"use strict";init_env();init_create_dto();init_response();SurfaceNameSchema=z22.enum(["code","schemas","content","translations","assets","forms","activations"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms","activations"],SurfaceDeltaVerbSchema=z22.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z22.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z22.object({verb:SurfaceDeltaVerbSchema,key:z22.string(),detail:z22.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z22.record(z22.string(),z22.unknown()).optional()}),PerSurfaceDeltaSchema=z22.object({surface:SurfaceNameSchema,status:z22.enum(["ok","timed_out","failed","unchanged"]),durationMs:z22.number().int().nonnegative().optional(),changedCount:z22.number().int().nonnegative(),conflictCount:z22.number().int().nonnegative(),items:z22.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z22.boolean().optional(),error:z22.string().optional()}),CrossSurfaceFindingSchema=z22.object({id:z22.string(),kind:z22.string(),description:z22.string(),severity:z22.enum(["warning","error"]),source:z22.object({surface:SurfaceNameSchema,key:z22.string()}),target:z22.object({surface:SurfaceNameSchema,key:z22.string()}),actions:z22.array(z22.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z22.object({env:EnvSchema,vs:EnvSchema,syncState:z22.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z22.coerce.date(),surfaces:z22.array(PerSurfaceDeltaSchema),agents:z22.array(z22.object({id:z22.string(),name:z22.string(),status:z22.enum(["active","paused","failed"]),lastRunAt:z22.coerce.date().nullable()})).optional(),crossSurface:z22.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z22.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z22.coerce.date(),surfaces:z22.array(PerSurfaceDeltaSchema),crossSurface:z22.array(CrossSurfaceFindingSchema).optional(),fingerprint:z22.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z22.object({path:z22.string(),state:z22.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z22.string(),additions:z22.number().int().nonnegative(),deletions:z22.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z22.object({oid:z22.string().optional(),content:z22.string().optional(),truncated:z22.boolean(),binary:z22.boolean()}),CodeConflictDetailSchema=z22.object({path:z22.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z22.string(),targetTipSha:z22.string(),mergeBaseSha:z22.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z22.object({id:z22.string(),slug:z22.string(),contentType:z22.string(),data:z22.record(z22.string(),z22.unknown()),updatedAt:z22.coerce.date()}),ContentRowDiffSchema=z22.object({collection:z22.string(),rowId:z22.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z22.object({name:z22.string(),label:z22.string(),isSingleton:z22.boolean(),fields:z22.record(z22.string(),z22.unknown())}),SchemaTypeDiffSchema=z22.object({typeName:z22.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z22.object({id:z22.string(),name:z22.string(),type:z22.enum(["file","folder"]),mimeType:z22.string().nullable(),storageKey:z22.string().nullable(),url:z22.string().nullable(),fileSize:z22.number().nullable(),width:z22.number().nullable(),height:z22.number().nullable(),altText:z22.string().nullable(),caption:z22.string().nullable(),createdAt:z22.coerce.date(),updatedAt:z22.coerce.date()}),AssetDiffSchema=z22.object({assetId:z22.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z22.object({locale:z22.string(),key:z22.string(),parent:z22.string().nullable(),child:z22.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z22.object({formName:z22.string(),label:z22.string().nullable(),schemaFingerprint:z22.string(),fields:z22.record(z22.string(),z22.unknown()),settings:z22.record(z22.string(),z22.unknown()).optional()}),FormSchemaDiffSchema=z22.object({formName:z22.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),ActivationSnapshotSchema=z22.object({agentName:z22.string(),triggerIndex:z22.number().int().nonnegative(),triggerKind:z22.string(),triggerSpec:z22.record(z22.string(),z22.unknown()),enabled:z22.boolean(),emailRecipients:z22.array(z22.string()).nullable(),qstashScheduleId:z22.string().nullable()}),ActivationDiffSchema=z22.object({agentName:z22.string(),triggerIndex:z22.number().int().nonnegative(),parent:ActivationSnapshotSchema.nullable(),child:ActivationSnapshotSchema.nullable()}),ActivationDiffDTO=createDTO(ActivationDiffSchema),ActivationDiffResponseSchema=createResponseSchema(ActivationDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z22.enum(CONFLICT_KINDS),ConflictSchema=z22.object({surface:SurfaceNameSchema,key:z22.string(),kind:ConflictKindSchema.optional(),description:z22.string(),parentValue:z22.unknown().optional(),childValue:z22.unknown().optional(),conflictingFields:z22.array(z22.string()).optional(),code:z22.object({path:z22.string(),unresolvable:z22.boolean().optional(),reason:z22.string().optional()}).optional()}),FieldPickSchema=z22.object({field:z22.string(),choice:z22.enum(["parent","child","pick","ai-pick"]),pickedValue:z22.unknown().optional(),aiSessionId:z22.string().optional()}),ConflictResolutionSchema=z22.object({surface:SurfaceNameSchema,key:z22.string(),choice:z22.enum(["parent","child","pick"]),pickedValue:z22.unknown().optional(),fieldPicks:z22.array(FieldPickSchema).optional()}),MergeResultSchema=z22.object({ok:z22.boolean(),mergeId:z22.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z22.array(z22.object({surface:SurfaceNameSchema,count:z22.number().int().nonnegative()})),conflicts:z22.array(ConflictSchema).optional(),summary:z22.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z22.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z22.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z22.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z22.boolean().optional()}),ResolvedStrategySchema=z22.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z22.boolean()}),MergeRequestSchema=z22.object({from:EnvSchema,allowDirectMerge:z22.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z22.object({mergeId:z22.string().uuid(),streamUrl:z22.string(),strategy:ResolvedStrategySchema,acceptedAt:z22.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z22.object({mergeId:z22.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z22.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z22.array(ConflictSchema),draftResolutions:z22.array(ConflictResolutionSchema),lastEditedBy:z22.string().nullable(),lastEditedAt:z22.coerce.date().nullable(),initiator:z22.object({userId:z22.string().nullable(),role:z22.string().nullable(),agentName:z22.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z22.object({resolutions:z22.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z22.object({mergeId:z22.string().uuid(),draftResolutions:z22.array(ConflictResolutionSchema),lastEditedAt:z22.coerce.date(),lastEditedBy:z22.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z22.object({mergeId:z22.string().uuid(),resolutions:z22.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z22.object({mergeId:z22.string().uuid()}),PublishReleaseRequestSchema=z22.object({version:z22.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z22.string().max(2e4).optional()}),PublishReleaseResultSchema=z22.object({releaseTag:z22.string(),sha:z22.string(),publishedAt:z22.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z23}from"zod";var 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=z23.object({surface:SurfaceNameSchema,key:z23.string(),label:z23.string()}),InlineSchema=z23.object({text:z23.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z23.discriminatedUnion("type",[z23.object({type:z23.literal("paragraph"),content:z23.array(InlineSchema).max(24)}),z23.object({type:z23.literal("preview"),ref:DiffRefSchema,caption:z23.string().optional()}),z23.object({type:z23.literal("code"),code:z23.string(),lang:z23.string().optional(),caption:z23.string().optional()}),z23.object({type:z23.literal("risk"),level:z23.enum(["warning","error"]),content:z23.array(InlineSchema).max(24)}),z23.object({type:z23.literal("list"),items:z23.array(z23.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z23.object({headline:z23.string(),blocks:z23.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z23.object({summary:EnvDiffSummarySchema,fingerprint:z23.string(),generatedAt:z23.coerce.date(),cached:z23.boolean().optional(),credits:z23.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z24}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=z24.object({date:z24.string(),visitors:z24.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z24.object({key:z24.string(),visitors:z24.number().int().nonnegative(),pageviews:z24.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z24.object({path:z24.string(),pageName:z24.string().nullable().optional(),visitors:z24.number().int().nonnegative(),pageviews:z24.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z24.object({preset:z24.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z24.string(),requestedTo:z24.string(),effectiveFrom:z24.string(),effectiveTo:z24.string(),isRetentionLimited:z24.boolean(),groupBy:z24.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z24.object({date:z24.string(),content:z24.string(),updatedAt:z24.string(),updatedByUserId:z24.string()}),ProjectPageviewAnalyticsDTOSchema=z24.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z24.number().int().nonnegative(),pageviews:z24.number().int().nonnegative(),bounceRate:z24.number().min(0).max(100),viewsPerVisit:z24.number().nonnegative(),averageVisitDurationSeconds:z24.number().nonnegative(),visitorsSeries:z24.array(ProjectDailyVisitorsDTOSchema),topPages:z24.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z24.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z24.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z24.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z24.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z24.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z25}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=z25.object({id:z25.string(),email:z25.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z25.coerce.date(),createdAt:z25.coerce.date(),inviterUserId:z25.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z25.object({id:z25.string(),token:z25.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z25.object({success:z25.boolean(),projectId:z25.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z26}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=z26.object({id:z26.string(),name:z26.string(),image:z26.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z26.object({count:z26.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z26.object({counts:z26.object({signed_up:z26.int(),activated:z26.int()}),credits:z26.object({total:z26.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z26.email(),emailVerified:z26.boolean(),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z27}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,ProjectPermissionsDTOSchema,ProjectPermissionsDTO,ProjectAccessDTOSchema,ProjectAccessDTO,AccessMutationResponseSchema,InviteAcceptResponseSchema,init_project_access_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-access.dto.js"(){"use strict";init_common();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z27.object({id:z27.string(),principalType:ProjectPrincipalTypeSchema,principalId:z27.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z27.coerce.date(),expiresAt:z27.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),ProjectPermissionsDTOSchema=z27.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z27.record(z27.string(),z27.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z27.object({access:z27.array(ProjectAccessItemDTOSchema),invites:z27.array(ProjectInviteDTOSchema),organization:z27.object({name:z27.string().nullable(),logo:z27.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z27.object({success:z27.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z27.object({success:z27.boolean(),projectId:z27.uuid()}))}});import{z as z28}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=z28.object({publicationStatus:PublicationStatusSchema,appUrl:z28.string().nullable(),lastPublishedAt:z28.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z29}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=z29.object({url:z29.url(),expiresAt:z29.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema)}});import{z as z30}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:z30.string(),slug:z30.string().nullable(),logo:z30.string().nullable(),metadata:z30.record(z30.string(),z30.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z30.object({id:z30.string(),name:z30.string(),email:z30.email(),image:z30.string().nullable()}),OrganizationMemberDTOSchema=z30.object({id:z30.string(),userId:z30.string(),organizationId:z30.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z30.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z31}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=z31.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z31.object({reason:CancellationReasonCodeSchema,details:z31.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z31.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),AiCreditsEntitlementSchema=z31.object({included:z31.number().optional(),unitPrice:z31.number().optional(),dailyCap:z31.number().nullable().optional()}),EntitlementsDTOSchema=z31.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z31.object({retentionDays:z31.number().int().positive(),canUseExtendedDateRanges:z31.boolean()}).optional(),history:z31.object({retentionDays:z31.number().int().positive()}).optional(),members:z31.object({canInvite:z31.boolean(),maxMembers:z31.number().int().positive().nullable()}).optional(),projects:z31.object({canCreatePrivateProjects:z31.boolean(),maxPrivateProjects:z31.number().int().positive().nullable()}).optional(),domains:z31.object({canUseCustomDomains:z31.boolean(),maxDomains:z31.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z31.object({id:z31.string(),external_id:z31.string(),customerId:z31.string(),planId:z31.string(),planCode:TemplateCodeSchema,currentPeriod:z31.object({start:z31.string(),end:z31.string().nullable()}),cancelAt:z31.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z31.string(),nextPaymentAt:z31.string().nullable(),baseAmount:z31.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z31.object({totalCap:z31.number(),dailyCap:z31.number(),usedTotal:z31.number()}),CreditBalanceDTOSchema=z31.object({total:z31.number(),base:z31.number(),dailyBase:z31.number(),purchases:z31.number(),awards:z31.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z31.object({total:z31.number(),nearLimit:z31.boolean(),canChat:z31.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z31.object({dailyFreeAvailable:z31.number(),monthlyAvailable:z31.number(),purchasedAvailable:z31.number(),awardedAvailable:z31.number()}),ProjectDailyCreditAllowanceDTOSchema=z31.object({periodCap:z31.number(),dailyGrant:z31.number(),usedThisPeriod:z31.number(),remainingThisPeriod:z31.number()}),ProjectCreditBalanceDTOSchema=z31.object({projectId:z31.uuid(),organizationId:z31.string(),balance:z31.object({totalAvailable:z31.number(),nearLimit:z31.boolean(),canUseAi:z31.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z31.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),SuccessfulPurchaseDTOSchema=z31.object({invoiceId:z31.string(),newBalance:z31.int(),creditCount:z31.int(),amountUsd:z31.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z31.object({url:z31.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 z32}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=z32.object({brand:z32.string(),last4:z32.string(),exp:z32.string(),isDefault:z32.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z33}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=z33.string().superRefine((path47,ctx)=>{let segments=path47.split(".");(segments.length===0||segments.some(segment=>!CONTENT_FIELD_NAME_PATTERN.test(segment)))&&ctx.addIssue({code:"custom",message:"Field paths must use dot-separated field or block variant names."})}),SchemaMigrationOperationSchema=z33.object({type:z33.literal("renameField"),contentType:z33.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z33.object({enabled:z33.boolean()}).strict(),ContentTypeDTOSchema=z33.object({id:z33.string(),name:z33.string(),label:z33.string(),isSingleton:z33.boolean(),i18n:ContentTypeI18nSchema,fields:z33.record(z33.string(),FieldDefinitionSchema),createdAt:z33.string(),updatedAt:z33.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z33.object({contentTypes:z33.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z33.object({id:z33.string(),entryId:z33.string(),documentId:z33.string(),slug:z33.string(),locale:z33.string().optional(),createdAt:z33.string(),updatedAt:z33.string(),__fimo:z33.object({contentType:z33.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z33.object({data:z33.array(EntryDTOSchema),meta:z33.object({limit:z33.number(),offset:z33.number(),total:z33.number(),hasMore:z33.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z33.object({contentType:z33.string(),count:z33.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z33.object({counts:z33.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z33.object({count:z33.number().int().nonnegative(),sourceLocale:z33.string(),targetLocale:z33.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z33.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z33.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z33.union([z33.string(),z33.number(),z33.boolean(),z33.null()]),entryWhereOperatorSchema=z33.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z33.array(entryWhereScalarSchema).optional(),$nin:z33.array(entryWhereScalarSchema).optional(),$contains:z33.string().optional(),$startsWith:z33.string().optional(),$null:z33.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z33.record(z33.string(),z33.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z33.record(z33.string(),z33.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z33.object({data:z33.record(z33.string(),z33.unknown()),locale:z33.string().min(1).optional(),documentId:z33.uuid().optional()}),entryIdsSchema=z33.array(z33.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z33.object({sql:z33.string().min(1)}),BulkCreateEntriesRequestSchema=z33.object({entries:z33.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z33.union([z33.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z33.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z33.object({updates:z33.array(z33.object({id:z33.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z33.union([z33.object({ids:entryIdsSchema,locale:z33.string().min(1).optional()}),z33.object({where:EntryWhereSchema,locale:z33.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z33.object({data:z33.array(z33.record(z33.string(),z33.unknown())),meta:z33.object({rowCount:z33.number().int().nonnegative(),truncated:z33.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z33.object({data:z33.array(EntryDTOSchema),meta:z33.object({created:z33.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z33.object({data:z33.array(EntryDTOSchema),meta:z33.object({updated:z33.number().int().nonnegative(),missing:z33.array(z33.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z33.object({data:z33.array(EntryDTOSchema),meta:z33.object({deleted:z33.number().int().nonnegative(),missing:z33.array(z33.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z34}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z34.object({index:z34.number().int().nonnegative(),contentType:z34.string(),field:z34.string(),value:z34.string(),against:z34.enum(["stored","batch"]),ownerDocumentId:z34.uuid().optional(),ownerIndex:z34.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z34.object({code:z34.literal("unique_conflict"),message:z34.string(),conflicts:z34.array(UniqueConflictSchema),truncated:z34.boolean().optional()})}});import{z as z35}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=z35.object({kind:z35.literal("unique_conflict"),contentType:z35.string(),field:z35.string(),value:z35.string(),documentCount:z35.number().int().positive(),documentIds:z35.array(z35.uuid()),documentIdsTruncated:z35.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z35.object({code:z35.literal("schema_transition_rejected"),message:z35.string(),issues:z35.array(SchemaTransitionIssueSchema),truncated:z35.boolean().optional()})}});import{z as z36}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=z36.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z36.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z36.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z36.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z36.object({field:CmsFieldNameSchema,direction:z36.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z36.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z36.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z36.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z36.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z36.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z37}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=z37.object({id:z37.string(),name:z37.string()}),AssetDTOSchema=z37.object({id:z37.string(),name:z37.string(),type:AssetTypeSchema,originalFileName:z37.string().nullable(),parentId:z37.string().nullable(),mimeType:z37.string().nullable(),fileSize:z37.number().nullable(),url:z37.string().nullable(),storageKey:z37.string().nullable(),createdAt:z37.string(),updatedAt:z37.string(),altText:z37.string().nullable().optional(),caption:z37.string().nullable().optional(),aiCaption:z37.string().nullable().optional(),aiAltText:z37.string().nullable().optional(),aiTags:z37.array(z37.string()).nullable().optional(),aiPrimaryColor:z37.string().nullable().optional(),aiProcessingStatus:z37.string().nullable().optional(),width:z37.number().nullable().optional(),height:z37.number().nullable().optional(),path:z37.array(AssetPathItemSchema).optional(),hasChildren:z37.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z37.lazy(()=>z37.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z37.array(AssetDTOSchema))}});import{z as z38}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z38.object({key:z38.string(),value:z38.string().optional(),defaultValue:z38.string(),locale:z38.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z39}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=z39.object({id:z39.string(),name:z39.string(),type:z39.enum(["file","folder"]),path:z39.string(),children:z39.lazy(()=>z39.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z39.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z39.object({path:z39.string(),exists:z39.boolean(),type:z39.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z40}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatDeletionDTOSchema,ChatDeletionDTO,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,ChatDeletionResponseSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_create_dto();init_response();init_project_dto();ChatMessageListDTOSchema=z40.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z40.object({items:z40.array(ProjectMessagePublicDTOSchema),nextCursor:z40.string().nullable()}),ChatDeletionDTOSchema=z40.object({success:z40.boolean(),deletedCount:z40.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema)}});import{z as z41}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=z41.object({url:z41.string().url(),key:z41.string(),size:z41.number(),contentType:z41.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z42}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=z42.object({canAccess:z42.boolean(),permissions:z42.record(z42.string(),z42.boolean()),role:z42.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z43}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:z43.string().trim().default(""),sort:z43.enum(["recent","name","relevance"]).default("recent"),category:z43.string().optional(),visibility:z43.enum(["public","private"]).optional()})}});import{z as z44}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=z44.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z44.enum(["fimo","external"]),PaymentStatusSchema=z44.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z44.object({id:z44.string().uuid(),domain:z44.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z44.boolean(),price:z44.number().int().nullable(),renewalPrice:z44.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z44.string().nullable(),failureReason:z44.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z44.object({domain:z44.string(),available:z44.boolean(),premium:z44.boolean(),price:z44.number().nullable(),renewalPrice:z44.number().nullable(),purchaseType:z44.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z44.object({domain:z44.string(),price:z44.number().nullable(),renewalPrice:z44.number().nullable(),premium:z44.boolean(),allowedYears:z44.array(z44.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z44.object({firstName:z44.string().max(100),lastName:z44.string().max(100),companyName:z44.string().max(100).optional(),address1:z44.string().max(255),address2:z44.string().max(255).optional(),city:z44.string().max(100),state:z44.string().max(100),zip:z44.string().max(20),country:z44.string().max(2),phone:z44.string().max(30),email:z44.union([z44.string().email().max(255),z44.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z44.object({firstName:z44.string().min(1).max(100),lastName:z44.string().min(1).max(100),companyName:z44.string().max(100).optional(),address1:z44.string().min(1).max(255),address2:z44.string().max(255).optional(),city:z44.string().min(1).max(100),state:z44.string().min(1).max(100),zip:z44.string().min(1).max(20),country:z44.string().min(1).max(2),phone:z44.string().min(1).max(30),email:z44.string().email().max(255)}),SearchDomainsRequestSchema=z44.object({keyword:z44.string().min(1).max(100),tldFilter:z44.array(z44.string()).optional()}),CheckAvailabilityRequestSchema=z44.object({domains:z44.array(z44.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=z44.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z44.object({domain:DomainNameSchema,years:z44.number().int().min(1).max(10).optional().default(3),autoRenew:z44.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z44.object({autoRenew:z44.boolean().optional()}),RenewDomainRequestSchema=z44.object({years:z44.number().int().min(1).max(10).optional().default(1),autoRenew:z44.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z44.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z44.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z44.object({verified:z44.boolean(),email:z44.string().nullable(),verifyBy:z44.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z45}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=z45.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=z45.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=z45.object({txtName:z45.string().nullable().optional(),txtValue:z45.string().nullable().optional(),httpUrl:z45.string().nullable().optional(),httpBody:z45.string().nullable().optional(),cname:z45.string().nullable().optional(),cnameTarget:z45.string().nullable().optional()}),SSLValidationErrorSchema=z45.object({message:z45.string()}),OwnershipVerificationSchema=z45.object({type:z45.string(),name:z45.string(),value:z45.string()}),ProjectDomainSSLDTOSchema=z45.object({status:z45.string(),method:z45.string().nullable(),type:z45.string().nullable(),validationRecords:z45.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z45.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z45.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z45.enum(["subdomain","apex"]),RedirectConfigSchema=z45.object({type:z45.literal("apex_to_www"),linkedDomainId:z45.string()}).nullable().optional(),ProjectDomainDTOSchema=z45.object({id:z45.string(),hostname:z45.string(),status:z45.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z45.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z45.string(),scdCnameTarget:z45.string().optional(),apexTargets:z45.array(z45.string()),dnsAutoConfigured:z45.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z45.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z45.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z45.object({hostname:z45.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:z45.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z45.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z45.object({available:z45.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z45.object({success:z45.boolean(),hostname:z45.string()}))}});import{z as z46}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=z46.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z46.object({available:z46.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z46.object({slug:z46.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z46.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z46.object({subdomain:z46.string(),subdomainUpdatedAt:z46.coerce.date()})),SubdomainSuggestionsQuerySchema=z46.object({base:z46.string().max(100).optional(),max:z46.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z46.object({suggestions:z46.array(z46.string())}))}});import{z as z47}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=z47.object({translated:z47.number().int().nonnegative(),total:z47.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z47.object({locale:z47.string(),isDefault:z47.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z47.object({defaultLocale:z47.string(),routing:z47.object({strategy:z47.literal("path-prefix"),prefixDefaultLocale:z47.boolean()}),locales:z47.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z47.object({locale:z47.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z47.object({locale:z47.string().min(1).max(40)}),ProjectLocaleMutationSchema=z47.object({locale:z47.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z47.object({locale:z47.string(),entriesDeleted:z47.number().int().nonnegative(),labelsDeleted:z47.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z48}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=z48.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z48.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=z48.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z48.number(),credits:z48.number().optional(),billingMode:z48.enum(["fimo-credits","provider-account"]).optional(),confidence:z48.enum(["exact","estimated","metered"]),basis:z48.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z49}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=z49.object({options:z49.record(z49.string(),z49.unknown()),name:z49.string().optional(),parentId:z49.string().nullable().optional(),altText:z49.string().optional(),caption:z49.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z49.string().min(1).optional(),model:z49.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=z49.object({jobId:z49.string(),status:z49.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z49.string().nullable().optional(),credits:z49.number().optional(),costUsd:z49.number().optional(),billingMode:z49.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z49.object({error:z49.string(),code:z49.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:z49.array(GenerationTaskIdSchema).optional(),availableModels:z49.array(z49.string()).optional(),issues:z49.array(z49.unknown()).optional()})}});import{z as z50}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=z50.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z50.object({name:z50.string(),key:z50.string(),description:z50.string(),type:FlagTypeSchema,required:z50.boolean(),defaultValue:z50.unknown().optional(),enumValues:z50.array(z50.string()).optional(),isArray:z50.boolean()}),AssetModelPriceSchema=z50.object({unitPrice:z50.number(),unit:z50.string(),confidence:z50.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z50.object({id:z50.string(),shortName:z50.string(),provider:z50.string(),source:z50.string(),modality:z50.enum(["image","video","audio"]),tags:z50.array(z50.string()),displayName:z50.string(),description:z50.string(),flags:z50.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z50.object({model:z50.string(),costUsd:z50.number(),credits:z50.number(),billingMode:z50.enum(["fimo-credits","provider-account"]),confidence:z50.enum(["exact","estimated","metered"]),basis:z50.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z51}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=z51.object({tourId:z51.string(),version:z51.string(),status:z51.string(),completedAt:z51.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z51.array(UserTourDTOSchema))}});import{z as z52}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=z52.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z52.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z52.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z52.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z52.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z52.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z52.enum(["user","agent","system"]),SupportReportTagSchema=z52.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z52.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z52.object({organization:z52.object({id:z52.string().trim().min(1).max(255),name:z52.string().trim().max(240).optional()}),project:z52.object({id:z52.uuid(),name:z52.string().trim().max(240).optional(),createdAt:z52.coerce.date().optional()}).optional(),environment:z52.string().trim().max(255).optional(),clientVersion:z52.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z52.object({message:z52.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z52.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z52.string().trim().max(200).optional(),limit:z52.coerce.number().int().min(1).max(100).default(50),offset:z52.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z52.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z52.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z52.uuid().nullable().optional(),note:z52.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=z52.object({message:z52.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z52.object({kind:SupportReportLinkKindSchema,label:z52.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z52.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z52.object({kind:SupportReportActorKindSchema,id:z52.string().nullable(),name:z52.string().nullable()}),SupportReportLinkDTOSchema=z52.object({id:z52.uuid(),kind:SupportReportLinkKindSchema,label:z52.string(),url:SupportReportHttpUrlSchema,externalId:z52.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z52.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z52.object({id:z52.uuid(),kind:SupportReportEventKindSchema,body:z52.string().nullable(),metadata:z52.record(z52.string(),z52.unknown()),actor:SupportReportActorDTOSchema,createdAt:z52.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z52.object({id:z52.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z52.array(z52.string()),source:SupportReportSourceSchema,message:z52.string(),reporter:z52.object({id:z52.string().nullable(),name:z52.string().nullable(),email:z52.string().nullable()}),organization:z52.object({id:z52.string().nullable(),name:z52.string()}),project:z52.object({id:z52.uuid().nullable(),name:z52.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z52.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z52.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z52.string().nullable(),deliveredAt:z52.coerce.date().nullable()}).nullable(),duplicateOfReportId:z52.uuid().nullable(),resolvedAt:z52.coerce.date().nullable(),createdAt:z52.coerce.date(),updatedAt:z52.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z52.string().nullable(),clientVersion:z52.string().nullable(),links:z52.array(SupportReportLinkDTOSchema),events:z52.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z52.object({reports:z52.array(SupportReportSummaryDTOSchema),total:z52.number().int().nonnegative(),statusCounts:z52.object({new:z52.number().int().nonnegative(),in_progress:z52.number().int().nonnegative(),waiting:z52.number().int().nonnegative(),resolved:z52.number().int().nonnegative(),duplicate:z52.number().int().nonnegative(),irrelevant:z52.number().int().nonnegative(),ignored:z52.number().int().nonnegative()}),limit:z52.number().int().positive(),offset:z52.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z52.object({id:z52.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z52.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z53}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=z53.iso.datetime({offset:!0}).pipe(z53.coerce.date()),OpsRecentChatInputSchema=z53.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z53.string().trim().min(1).max(255).optional(),limit:z53.coerce.number().int().min(1).max(200).default(100),cursor:z53.string().trim().min(1).max(2e3).optional(),slim:z53.boolean().default(!0),reason:z53.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=z53.object({id:z53.string(),messageId:z53.string(),env:z53.string(),versionId:z53.string().nullable(),userId:z53.string().nullable(),role:z53.string(),parts:z53.array(z53.record(z53.string(),z53.unknown())),metadata:z53.object({status:z53.string().optional(),traceUrl:z53.string().optional(),externalFileChanges:z53.array(z53.unknown()).optional()}),stats:z53.object({toolCount:z53.number().int().nonnegative(),failedToolCount:z53.number().int().nonnegative()}),createdAt:z53.iso.datetime({offset:!0}),project:z53.object({id:z53.string(),name:z53.string(),displayName:z53.string().nullable(),organizationId:z53.string().nullable()})}),OpsRecentChatResponseSchema=z53.object({target:z53.object({backendProfile:OpsBackendProfileSchema,projectEnv:z53.string().nullable()}),window:z53.object({from:z53.iso.datetime({offset:!0}),to:z53.iso.datetime({offset:!0})}),messages:z53.object({items:z53.array(OpsRecentChatMessageSchema),nextCursor:z53.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z54}from"zod";function createAgentRunWebhookEventDataSchema(status){return z54.object({run:z54.object({id:z54.string(),agentName:z54.string(),trigger:z54.string(),status:z54.literal(status),startedAt:z54.string().nullable(),finishedAt:z54.string().nullable(),reason:z54.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=z54.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z54.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z54.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z54.enum(["main","all"]),WebhookEntryBatchWindowSecondsSchema=z54.union([z54.literal(0),z54.literal(5),z54.literal(30),z54.literal(60)]),EntryChangedWebhookEventDataSchema=z54.object({reason:WebhookEntryChangeReasonSchema,operationId:z54.string().optional(),batch:z54.object({index:z54.number().int().positive(),total:z54.number().int().positive()}).optional(),changes:z54.array(z54.object({action:WebhookEntryChangeActionSchema,contentType:z54.string(),id:z54.string(),documentId:z54.string(),locale:z54.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z54.object({form:z54.object({id:z54.string(),label:z54.string()}),submission:z54.object({id:z54.string(),data:z54.record(z54.string(),z54.unknown()),submittedAt:z54.string()})}),PublishStartedWebhookEventDataSchema=z54.object({publication:z54.object({status:z54.literal("publishing"),startedAt:z54.string()})}),PublishSucceededWebhookEventDataSchema=z54.object({publication:z54.object({status:z54.literal("published"),url:z54.string(),publishedAt:z54.string(),firstPublish:z54.boolean()})}),PublishFailedWebhookEventDataSchema=z54.object({publication:z54.object({status:z54.literal("failed"),reason:z54.string()})}),PublishUnpublishedWebhookEventDataSchema=z54.object({publication:z54.object({previousUrl:z54.string(),unpublishedAt:z54.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z54.object({review:z54.object({id:z54.string(),runId:z54.string(),agentName:z54.string(),classification:z54.string(),summary:z54.string(),reasons:z54.array(z54.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z54.object({review:z54.object({id:z54.string(),runId:z54.string(),agentName:z54.string(),resolution:z54.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z54.object({report:z54.object({weekStart:z54.string(),weekEnd:z54.string(),pageviews:z54.number(),visitors:z54.number(),previousPageviews:z54.number(),previousVisitors:z54.number()})}),MediaAssetWebhookEventDataSchema=z54.object({id:z54.string().nullable(),name:z54.string().nullable(),type:z54.string(),mimeType:z54.string().nullable(),fileSize:z54.number().nullable()}),MediaUploadedWebhookEventDataSchema=z54.object({asset:MediaAssetWebhookEventDataSchema,operation:z54.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z54.object({asset:MediaAssetWebhookEventDataSchema,operation:z54.enum(["updated","moved","analysis"]),analysis:z54.object({category:z54.string(),status:z54.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z54.object({asset:MediaAssetWebhookEventDataSchema,operation:z54.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z54.object({asset:MediaAssetWebhookEventDataSchema,operation:z54.literal("generated"),generation:z54.object({model:z54.string(),mode:z54.string()})}),MediaProcessingFailedWebhookEventDataSchema=z54.object({asset:MediaAssetWebhookEventDataSchema,operation:z54.enum(["analysis","generation"]),failure:z54.object({code:z54.string()})}),DomainCreatedWebhookEventDataSchema=z54.object({domain:z54.object({id:z54.string(),hostname:z54.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z54.object({domain:z54.object({id:z54.string(),hostname:z54.string()})}),LabelChangedWebhookEventDataSchema=z54.object({changes:z54.array(z54.object({action:z54.enum(["created","updated","deleted"]),key:z54.string(),locale:z54.string(),value:z54.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z54.object({locale:z54.object({code:z54.string(),isDefault:z54.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z54.object({locale:z54.object({code:z54.string(),previousCode:z54.string()})}),LocaleDeletedWebhookEventDataSchema=z54.object({locale:z54.object({code:z54.string(),entriesDeleted:z54.number().int().nonnegative(),labelsDeleted:z54.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z54.object({environment:z54.object({name:EnvSchema,parent:EnvSchema})}),EnvironmentDeletedWebhookEventDataSchema=z54.object({environment:z54.object({name:EnvSchema})}),EnvironmentMergedWebhookEventDataSchema=z54.object({merge:z54.object({id:z54.string(),from:EnvSchema,to:EnvSchema,applied:z54.array(z54.object({surface:SurfaceNameSchema,count:z54.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z54.object({environment:z54.object({name:EnvSchema}),version:z54.object({versionId:z54.uuid(),name:z54.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=z54.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z54.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z54.discriminatedUnion("source",[z54.object({source:z54.literal("literal"),value:z54.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z54.object({source:z54.literal("secret"),key:z54.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z54.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z54.object({name:z54.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z54.object({name:z54.string(),source:z54.enum(["literal","secret"]),secretKey:z54.string().nullable(),secretPrefix:z54.string().nullable(),configured:z54.literal(!0)}),WebhookFilterSchema=z54.object({environment:WebhookEnvironmentScopeSchema.optional(),formId:z54.string().min(1).max(255).optional(),agentName:z54.string().min(1).max(120).optional(),mediaType:z54.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z54.string().min(1).max(255).optional(),locale:z54.string().min(1).max(120).optional()}),JsonValueSchema=z54.lazy(()=>z54.union([z54.string(),z54.number(),z54.boolean(),z54.null(),z54.array(JsonValueSchema),z54.record(z54.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z54.object({name:z54.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z54.url(),enabled:z54.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z54.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z54.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z54.object({name:z54.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z54.url().optional(),enabled:z54.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z54.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z54.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z54.object({eventType:WebhookEventTypeSchema.optional(),data:z54.record(z54.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z54.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z54.uuid(),name:z54.string(),eventType:WebhookEventTypeSchema,enabled:z54.boolean(),destination:z54.object({host:z54.string(),maskedUrl:z54.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z54.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z54.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z54.coerce.date().nullable(),deliveryStats24h:z54.object({succeeded:z54.number().int().nonnegative(),failed:z54.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z54.uuid(),projectId:z54.uuid(),env:EnvSchema,eventId:z54.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z54.number().int().positive(),test:z54.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z54.number().int().nonnegative(),responseStatus:z54.number().int().nullable(),lastErrorCode:z54.string().nullable(),lastErrorMessage:z54.string().nullable(),payloadAvailable:z54.boolean(),destination:z54.object({host:z54.string(),maskedUrl:z54.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z54.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z54.string().nullable(),qstashMessageId:z54.string().nullable(),deliveredAt:z54.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z54.object({items:z54.array(WebhookDeliveryDTOSchema),pagination:z54.object({page:z54.number().int().positive(),limit:z54.number().int().positive(),total:z54.number().int().nonnegative(),totalPages:z54.number().int().positive(),hasMore:z54.boolean()}),stats:z54.object({total:z54.number().int().nonnegative(),succeeded:z54.number().int().nonnegative(),failed:z54.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z54.object({id:z54.uuid(),deliveryId:z54.uuid(),attempt:z54.number().int().positive(),status:z54.enum(["delivering","succeeded","failed"]),responseStatus:z54.number().int().nullable(),durationMs:z54.number().int().nonnegative(),responseExcerpt:z54.string().nullable(),errorCode:z54.string().nullable(),errorMessage:z54.string().nullable(),createdAt:z54.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z54.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z54.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z55}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=z55.object({key:z55.enum(previewFeatureKeys),enabled:z55.boolean(),dismissed:z55.boolean().default(!1),interacted:z55.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema),PreviewFeatureResponseSchema=createResponseSchema(PreviewFeatureDTOSchema),PreviewFeatureListResponseSchema=createResponseSchema(z55.array(PreviewFeatureDTOSchema))}});import{z as z56}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=z56.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z56.object({total:z56.number(),base:z56.number(),purchases:z56.number(),awards:z56.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z56.object({id:z56.string(),name:z56.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z56.object({type:z56.string(),brand:z56.string().nullable(),last4:z56.string().nullable(),expirationDate:z56.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z56.object({currency:z56.string(),nextPaymentAmount:z56.number().nullable(),nextPaymentAt:z56.string().nullable(),billingInterval:z56.string().nullable(),totalAmount:z56.number().nullable(),discountAmount:z56.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z56.object({id:z56.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z56.string().nullable(),currentPeriodEndsAt:z56.string().nullable(),renewsAt:z56.string().nullable(),cancelAt:z56.string().nullable(),renewAutomatically:z56.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z56.object({type:z56.enum(["low_balance","critical_balance","approaching_limit"]),message:z56.string(),estimatedPromptsRemaining:z56.number().nullable(),avgCostPerPrompt:z56.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z56.object({monthlyCredits:z56.number().nullable(),usedThisPeriod:z56.number(),remainingThisPeriod:z56.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z56.object({organizationId:z56.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z56.string().nullable(),tenureDays:z56.number().int().nonnegative(),capturedAt:z56.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z56.object({hasSubscription:z56.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z56.number().nullable(),alerts:z56.array(CreditAlertDTOSchema),portalUrl:z56.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z56.object({creditCount:z56.number().int().positive(),expiresAt:z56.string().datetime().nullable().optional(),message:z56.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z56.literal("free"),amountCents:z56.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z56.literal("purchase"),amountCents:z56.number().int().positive()}),CreditTopupRequestDTOSchema=z56.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z56.object({success:z56.boolean(),transactionId:z56.string().nullable(),newBalance:z56.number(),creditCount:z56.number(),type:z56.enum(["free","purchase"]),invoiceId:z56.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z57}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=z57.object({totalCredits:z57.number(),totalCostUsd:z57.number(),totalMessages:z57.number(),avgCostPerMessage:z57.number(),periodStart:z57.string().nullable(),periodEnd:z57.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z57.object({projectId:z57.string(),projectName:z57.string(),projectDisplayName:z57.string().nullable(),credits:z57.number(),costUsd:z57.number(),messages:z57.number(),percentage:z57.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z57.object({userId:z57.string(),userName:z57.string().nullable(),userEmail:z57.string().email().nullable(),credits:z57.number(),costUsd:z57.number(),messages:z57.number(),percentage:z57.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z57.object({date:z57.string(),credits:z57.number(),costUsd:z57.number(),messages:z57.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z57.object({userId:z57.string(),userName:z57.string().nullable(),userEmail:z57.string().email().nullable(),credits:z57.number(),costUsd:z57.number(),messages:z57.number(),percentage:z57.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z57.object({projectId:z57.string(),projectName:z57.string(),projectDisplayName:z57.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z57.array(UsageByUserForProjectDTOSchema),timeline:z57.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z57.object({summary:UsageSummaryDTOSchema,byProject:z57.array(UsageByProjectDTOSchema),byUser:z57.array(UsageByUserDTOSchema),timeline:z57.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z58}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=z58.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z58.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z58.object({startDate:z58.string().optional(),endDate:z58.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z58.coerce.number().int().positive().default(1),limit:z58.coerce.number().int().positive().max(100).default(20),sortBy:z58.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z58.string().optional()}),UsageOverviewSummaryDTOSchema=z58.object({totalCredits:z58.number(),totalCostUsd:z58.number(),totalMessages:z58.number(),avgCostPerMessage:z58.number(),avgCreditsPerMessage:z58.number(),periodStart:z58.string(),periodEnd:z58.string(),creditsChange:z58.number().nullable(),costChange:z58.number().nullable(),messagesChange:z58.number().nullable()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z58.object({date:z58.string(),credits:z58.number(),costUsd:z58.number(),messages:z58.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z58.object({organizationId:z58.string(),organizationName:z58.string(),credits:z58.number(),costUsd:z58.number(),messages:z58.number(),percentage:z58.number(),userCount:z58.number(),projectCount:z58.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z58.object({userId:z58.string(),userName:z58.string().nullable(),userEmail:z58.string().nullable(),userImage:z58.string().nullable(),organizationId:z58.string().nullable(),organizationName:z58.string().nullable(),credits:z58.number(),costUsd:z58.number(),messages:z58.number(),percentage:z58.number(),projectCount:z58.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z58.object({projectId:z58.string(),projectName:z58.string(),projectDisplayName:z58.string().nullable(),organizationId:z58.string(),organizationName:z58.string(),credits:z58.number(),costUsd:z58.number(),messages:z58.number(),percentage:z58.number(),userCount:z58.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z58.object({id:z58.string(),name:z58.string(),value:z58.number(),percentage:z58.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z58.object({day:z58.number(),hour:z58.number(),value:z58.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z58.object({summary:UsageOverviewSummaryDTOSchema,timeline:z58.array(UsageTimelinePointDTOSchema),topOrganizations:z58.array(OrganizationUsageRowDTOSchema),topUsers:z58.array(UserUsageRowDTOSchema),topProjects:z58.array(ProjectUsageRowDTOSchema),creditDistribution:z58.array(UsageDistributionItemDTOSchema),heatmap:z58.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z58.object({page:z58.number(),limit:z58.number(),totalItems:z58.number(),totalPages:z58.number(),hasMore:z58.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z58.object({organizations:z58.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z58.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z58.object({users:z58.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z58.string(),ownerName:z58.string().nullable(),ownerEmail:z58.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z58.object({projects:z58.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z58.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z58.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z58.object({credits:z58.number(),costUsd:z58.number(),messages:z58.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z58.object({id:z58.string(),name:z58.string(),createdAt:z58.string(),memberCount:z58.number(),projectCount:z58.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z58.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z58.object({id:z58.string(),name:z58.string().nullable(),email:z58.string(),image:z58.string().nullable(),createdAt:z58.string(),organizationCount:z58.number(),projectCount:z58.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z58.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z58.object({id:z58.string(),name:z58.string(),displayName:z58.string().nullable(),createdAt:z58.string(),organizationId:z58.string(),organizationName:z58.string(),ownerId:z58.string(),ownerName:z58.string().nullable(),ownerEmail:z58.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z58.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z59}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=z59.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z59.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z59.object({command:z59.string().min(1).max(1e4),cwd:z59.string().optional(),projectEnv:EnvSchema.optional(),env:z59.record(z59.string(),z59.string()).optional(),name:z59.string().optional(),waitForCompletion:z59.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z59.object({identifier:z59.string(),status:SandboxProcessStatusSchema,command:z59.string().optional(),startedAt:z59.string().optional(),exitCode:z59.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z59.object({processes:z59.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z59.object({processId:z59.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z59.object({success:z59.boolean(),message:z59.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z60}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common();init_attachments();init_env();init_realtime();init_references();init_content_fields();init_audit_log();init_ops();init_project_dto();init_project_env_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_activation_dto();init_agent_list_item_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_audit_log_dto();init_env_status_dto();init_env_diff_summary_dto();init_project_analytics_dto();init_project_access_dto();init_project_invite_dto();init_publication_dto();init_sandbox_dto();init_organization_dto();init_billing_dto();init_payment_method_dto();init_user_dto();init_content_dto();init_unique_conflict_dto();init_schema_transition_rejected_dto();init_cms_display_defaults_dto();init_asset_dto();init_translation_dto();init_document_dto();init_chat_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_webhook_dto();init_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,readFile5=defaultReadFile){try{return JSON.parse(readFile5(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&&params.set("against",against);for(let[k,v]of Object.entries(extras))params.set(k,v);return params.toString()}function throwUnauthorized(cfg,status){try{recordAuthFailure(cfg)}catch{}throw new UnauthorizedError(cfg.apiUrl,status)}async function throwPermissionDenied(cfg,response){let required=[];try{let body=await response.json();required=Array.isArray(body.required)?body.required:body.required?[body.required]:[]}catch{}throw new PermissionDeniedError(cfg.apiUrl,required)}async function fimoFetch(url,init){let headers=new Headers(init.headers);headers.delete(CLI_VERSION_HEADER),headers.delete(CLI_AUTO_UPGRADE_HEADER);let canAutoUpgrade=process.argv[2]!=="git-credential"&&autoUpgradeEnabled();canAutoUpgrade&&(headers.set(CLI_VERSION_HEADER,getCliVersion()),headers.set(CLI_AUTO_UPGRADE_HEADER,"1"));let response=await fetch(url,{...init,headers});if(canAutoUpgrade&&response.status===426){let latest=response.headers.get(CLI_LATEST_HEADER);if(latest){await autoUpgradeGlobal(latest)||ui.warn({command:process.argv[2]??"fimo",message:`Could not upgrade to ${latest}; continuing with the current command.`});let retryHeaders=new Headers(init.headers);return retryHeaders.delete(CLI_VERSION_HEADER),retryHeaders.delete(CLI_AUTO_UPGRADE_HEADER),fetch(url,{...init,headers:retryHeaders})}}return response}function formatZodIssues(parsed){if(!parsed||typeof parsed!="object")return null;let error=parsed.error,issues=error&&typeof error=="object"&&"issues"in error?error.issues:void 0;return!Array.isArray(issues)||issues.length===0?null:issues.map(issue=>{let{path:path47,message}=issue;return`${Array.isArray(path47)&&path47.length>0?`${path47.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}var ApiRequestError,UnauthorizedError,PermissionDeniedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_ENV_HEADER,FimoApiClient,init_api=__esm({"src/cli/api.ts"(){init_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,path47,status,detail,code2,body){super(`API ${method} ${path47} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path47,this.status=status,this.detail=detail,this.code=code2,this.body=body}},UnauthorizedError=class extends Error{static{__name(this,"UnauthorizedError")}apiUrl;status;constructor(apiUrl,status,message){super(message??`Session for ${apiUrl} expired or invalid (HTTP ${status}).`),this.name="UnauthorizedError",this.apiUrl=apiUrl,this.status=status}},PermissionDeniedError=class extends Error{static{__name(this,"PermissionDeniedError")}apiUrl;required;constructor(apiUrl,required=[],message){let detail=required.length?` Missing permission: ${required.join(", ")}.`:"";super(message??`You don't have permission to do this on ${apiUrl}.${detail}`),this.name="PermissionDeniedError",this.apiUrl=apiUrl,this.required=required}};__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");CLI_VERSION_HEADER="X-Fimo-CLI-Version",CLI_LATEST_HEADER="X-Fimo-CLI-Latest",CLI_AUTO_UPGRADE_HEADER="X-Fimo-CLI-Auto-Upgrade",FIMO_ENV_HEADER="X-Fimo-Env";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");FimoApiClient=class _FimoApiClient{constructor(cfg=loadConfig()){this.cfg=cfg}static{__name(this,"FimoApiClient")}env;withEnv(env){let next2=new _FimoApiClient(this.cfg);return next2.env=env,next2}formatError(status,text3,body){if(!text3)return String(status);if(body&&typeof body=="object"&&!Array.isArray(body)){let parsed=body;if(typeof parsed.message=="string"&&parsed.message.length>0){let partial=formatPartialResult(parsed);return partial?`${parsed.message} ${partial}`:parsed.message}if(typeof parsed.error=="string"&&parsed.error.length>0)return parsed.error;if(parsed.error&&typeof parsed.error=="object"&&"message"in parsed.error&&typeof parsed.error.message=="string")return parsed.error.message;let zodIssues=formatZodIssues(parsed);if(zodIssues)return zodIssues}return text3}async parseError(response){let text3=await response.text(),body;try{body=text3?JSON.parse(text3):void 0}catch{return{detail:this.formatError(response.status,text3)}}let code2=body&&typeof body=="object"&&!Array.isArray(body)&&typeof body.code=="string"?body.code:void 0;return{detail:this.formatError(response.status,text3,body),code:code2,body}}resolveAuthToken(){return process.env.FIMO_API_TOKEN?.trim()||requireToken(this.cfg)}async request(path47,init={},opts={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path47}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&!opts.allow403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new ApiRequestError(init.method??"GET",path47,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async rawRequest(path47,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path47}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new Error(`API ${init.method??"GET"} ${path47} failed: ${response.status} ${error.detail}`)}return response}tenantPath(projectId,route){if(!this.env)throw new Error("FimoApiClient: tenant-scoped call requires an env. Use `client.withEnv(env)` before calling tenant CRUD methods.");return`/api/tenant/${projectId}/envs/${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&&params.set("modality",query.modality);for(let t2 of query.tag??[])params.append("tag",t2);query.q&&params.set("q",query.q),query.category&&params.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&&params.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&&params.set("limit",String(query.limit)),query.cursor&&params.set("cursor",query.cursor),query.status&&params.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&&params.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&&params.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&&params.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&&params.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/status${qs?`?${qs}`:""}`)).data}async getCodeFileDiff(projectId,env,path47,opts={}){let qs=lazyFetchQs(opts.against,{path:path47});return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/code/file?${qs}`)).data}async getCodeConflictDetail(projectId,env,fromEnv,filePath){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflict/code?path=${encodeURIComponent(filePath)}`)).data}async getContentRowDiff(projectId,env,collection,rowId,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getSchemaTypeDiff(projectId,env,typeName,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getAssetDiff(projectId,env,assetId,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getTranslationRowDiff(projectId,env,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getFormSchemaDiff(projectId,env,formName,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getActivationDiff(projectId,env,agentName,triggerIndex,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/activations/${encodeURIComponent(agentName)}/${triggerIndex}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async mergeEnv(projectId,env,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge`,{method:"POST",body:JSON.stringify(body)})).data}async resolveMerge(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve`,{method:"POST",body:JSON.stringify(body)})).data}async cancelMerge(projectId,env,mergeId){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/cancel`,{method:"POST",body:JSON.stringify({mergeId})})).data}async getMergeConflicts(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflicts`)).data}async putResolveDraft(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"PUT",body:JSON.stringify(body)})).data}async deleteResolveDraft(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"DELETE"})).data}async publishRelease(projectId,body){return(await this.request(`/api/management/projects/${projectId}/releases`,{method:"POST",body:JSON.stringify(body)})).data}async activateAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/activations`,{method:"POST",body:JSON.stringify(body)})).data}async deactivateAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/activations`,{method:"DELETE",body:JSON.stringify(body)})).data}async runAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/run`,{method:"POST",body:JSON.stringify(body)})).data}async listAgentSessions(projectId,opts={}){let params=new URLSearchParams;opts.agentName&&params.set("agent_name",opts.agentName),opts.env&&params.set("env",opts.env),opts.status&&params.set("status",opts.status),opts.limit!==void 0&&params.set("limit",String(opts.limit));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/agents/sessions${qs?`?${qs}`:""}`)).data}async getAgentSession(projectId,sessionId){return(await this.request(`/api/management/projects/${projectId}/agents/sessions/${encodeURIComponent(sessionId)}`)).data.session}async getFeatures(){return this.request("/api/features")}async inviteProjectUser(input){return{id:(await this.request(`/api/management/projects/${input.projectId}/invites`,{method:"POST",body:JSON.stringify({email:input.email,roleKey:input.roleKey})})).data.id}}async updateProjectSettings(projectId,settings){return(await this.request(`/api/management/projects/${projectId}/settings`,{method:"PUT",body:JSON.stringify(settings)})).data}async deleteProject(projectId){await this.request(`/api/management/projects/${projectId}`,{method:"DELETE",body:JSON.stringify({})})}async getGitRemote(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-remote`,{},{allow403:!0})).data}async getGitCredential(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-credential`,{},{allow403:!0})).data}async getPreviewUrl(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sandbox`)).data}async sandboxPull(projectId,onProgress,env,options={}){let query=options.noRestart?"?noRestart=true":"",response=await this.rawRequest(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sandbox/pull${query}`,{method:"POST",headers:{Accept:"text/event-stream"}});if(!response.body)throw new Error("Sandbox pull failed: empty response stream");let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",errorMessage3=null,completed=!1;try{for(;;){let{value,done}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});let separatorIndex=buffer.indexOf(`
42
+ `)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();helpOption&&args.find(arg=>helpOption.is(arg))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;return(match=arg.match(/^(--inspect(-brk)?)$/))!==null?debugOption=match[1]:(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(debugOption=match[1],/^\d+$/.test(match[3])?debugPort=match[3]:debugHost=match[3]):(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match[1],debugHost=match[3],debugPort=match[4]),debugOption&&debugPort!=="0"?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}__name(incrementNodeInspectorPort,"incrementNodeInspectorPort");function useColor(){if(process8.env.NO_COLOR||process8.env.FORCE_COLOR==="0"||process8.env.FORCE_COLOR==="false")return!1;if(process8.env.FORCE_COLOR||process8.env.CLICOLOR_FORCE!==void 0)return!0}__name(useColor,"useColor");exports2.Command=Command2;exports2.useColor=useColor}});var require_commander=__commonJS({"../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js"(exports2){var{Argument:Argument2}=require_argument(),{Command:Command2}=require_command(),{CommanderError:CommanderError2,InvalidArgumentError:InvalidArgumentError2}=require_error(),{Help:Help2}=require_help(),{Option:Option2}=require_option();exports2.program=new Command2;exports2.createCommand=name=>new Command2(name);exports2.createOption=(flags,description)=>new Option2(flags,description);exports2.createArgument=(name,description)=>new Argument2(name,description);exports2.Command=Command2;exports2.Option=Option2;exports2.Argument=Argument2;exports2.Help=Help2;exports2.CommanderError=CommanderError2;exports2.InvalidArgumentError=InvalidArgumentError2;exports2.InvalidOptionArgumentError=InvalidArgumentError2}});import{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,RESERVED_CONTENT_FIELD_NAMES,CONTENT_TYPE_NAME_PATTERN,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION,CONTENT_FIELD_NAME_PATTERN,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION,init_common=__esm({"../../packages/api-contracts/dist/esm/types/common.js"(){"use strict";CommonSchemas={timestamp: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"]),RESERVED_CONTENT_FIELD_NAMES=["id","entryId","documentId","slug","locale","createdAt","updatedAt","__fimo"],CONTENT_TYPE_NAME_PATTERN=/^[A-Za-z]\w*$/,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter",CONTENT_FIELD_NAME_PATTERN=/^[A-Za-z_]\w*$/,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter or underscore"}});var ATTACHMENT_TYPES,ATTACHMENT_MIME_TYPES,ATTACHMENT_IMAGE_MIME_TYPES,ATTACHMENT_DOCUMENT_MIME_TYPES,ATTACHMENT_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image"},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image"},{mime:"image/webp",extensions:[".webp"],category:"image"},{mime:"image/avif",extensions:[".avif"],category:"image"},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:5242880},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:5242880},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:5242880}],ATTACHMENT_MIME_TYPES=ATTACHMENT_TYPES.map(t2=>t2.mime),ATTACHMENT_IMAGE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="image").map(t2=>t2.mime),ATTACHMENT_DOCUMENT_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="document").map(t2=>t2.mime),ATTACHMENT_ACCEPT_EXTENSIONS=ATTACHMENT_TYPES.flatMap(t2=>t2.extensions),ATTACHMENT_ACCEPT_STRING=[...ATTACHMENT_ACCEPT_EXTENSIONS,...ATTACHMENT_MIME_TYPES].join(","),ATTACHMENT_DROPZONE_ACCEPT=Object.fromEntries(ATTACHMENT_TYPES.map(t2=>[t2.mime,t2.extensions]))}});import{z as 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,path47){let conditionPath=[...path47,fieldName,condition.key],trigger=fields[clause.field];if(trigger===void 0)return[{path:conditionPath,message:`"${condition.key}" references unknown field "${clause.field}".`}];if(trigger.showIf!==void 0||trigger.showIfAny!==void 0)return[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is conditional too. Conditions are one level deep.`}];if(trigger.type!=="boolean"&&trigger.type!=="number"&&trigger.type!=="string")return[{path:conditionPath,message:`"${condition.key}" can only reference boolean, number, and string fields. "${clause.field}" is a ${trigger.type} field.`}];let triggerOptions=trigger.type==="string"?trigger.options:void 0;if(trigger.type==="string"&&triggerOptions===void 0)return[{path:conditionPath,message:`"${condition.key}" can only reference a string field that declares "options". Add options to "${clause.field}".`}];let values=getConditionValues(clause);if(values.some(value=>typeof value!==trigger.type))return[{path:conditionPath,message:`"${condition.key}" on "${clause.field}" expects a ${trigger.type} value.`}];if(triggerOptions!==void 0){let invalidValues=values.filter(value=>!triggerOptions.includes(value));if(invalidValues.length>0)return invalidValues.map(value=>({path:conditionPath,message:`"${value}" is not one of the options declared by "${clause.field}".`}))}return trigger.editable===!1?[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is not editable.`}]:[]}function collectConditionProblems(fields){let problems=[],walk=__name((currentFields,path47)=>{for(let[fieldName,field]of Object.entries(currentFields)){let condition=getConditionDefinition(field);if(condition!==void 0)for(let clause of condition.clauses)problems.push(...collectClauseProblems(fieldName,condition,clause,currentFields,path47));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path47,fieldName,variant.uid]);else walk(field.schema.fields,[...path47,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path47,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path47,fieldName];visit2({field,path:fieldPath,structuredDepth,insideStructuredContent});let nextDepth=structuredDepth+1;if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...fieldPath,variant.uid],nextDepth,!0);else walk(field.schema.fields,fieldPath,nextDepth,!0)}},"walk");walk(fields,[],0,!1)}var UNIQUE_FIELD_TYPES,utf8,MAX_STRUCTURED_CONTENT_DEPTH,MAX_BLOCK_VARIANTS,MAX_BLOCK_ITEMS,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES,showIfClauseSchema,commonFieldShape,FIELD_I18N_UNSUPPORTED_MESSAGE,uniqueFieldTypes,UNSUPPORTED_UNIQUE_MESSAGE,scalarFieldSchema,referenceFieldSchema,reservedStructuredContentNames,ContentFieldDefinitionSchema,blockFieldsSchema,blockVariantSchema,fixedBlocksSchema,blocksSchema,blocksFieldSchema,contentFieldDefinitionSchema,init_content_fields=__esm({"../../packages/api-contracts/dist/esm/types/content-fields.js"(){"use strict";init_common();UNIQUE_FIELD_TYPES=["string","text","number","boolean","date"],utf8=new TextEncoder,MAX_STRUCTURED_CONTENT_DEPTH=3,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],showIfClauseSchema=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"],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,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:sentry:read","ops:logs:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview","ops:notification:approve","ops:notification:send"],OpsPermissionSchema=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:investigations:read","ops:investigations:write","ops:known-issues:read","ops:validations:read","ops:notification:preview"],engineer:["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:sentry:read","ops:logs:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview"],full:[...OPS_PERMISSIONS]},OPS_SERVICE_PERMISSION_PRESETS={support:OPS_PERMISSION_PRESETS.support,engineer:OPS_PERMISSION_PRESETS.engineer,full:OPS_PERMISSION_PRESETS.full.filter(permission=>permission!=="ops:notification:approve")},OpsAccessGrantInputSchema=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)})}});import{z as z10}from"zod";var ProjectDTOSchema,ProjectDTO,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,QuestionAnswerMetadataSchema,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_common();init_create_dto();init_response();ProjectDTOSchema=BaseEntitySchema.extend({name:z10.string(),displayName:z10.string().nullable(),subdomain:z10.string().nullable().optional(),subdomainUpdatedAt:z10.date().nullable().optional(),organizationId:z10.string().nullable(),createdBy:z10.string().nullable(),visibility:ProjectVisibilitySchema,previewEnabled:z10.boolean().default(!0),status:ProjectStatusSchema,creationStatus:z10.string(),thumbnailUrl:z10.string().nullable(),publishedThumbnailUrl:z10.string().nullable(),category:z10.string().nullable(),appUrl:z10.string().nullable(),lastPublishedAt:z10.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z10.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z10.object({id:z10.uuid(),name:z10.string(),displayName:z10.string().nullable(),thumbnailUrl:z10.string().nullable(),visibility:ProjectVisibilitySchema,category:z10.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z10.object({id:z10.string(),name:z10.string(),avatar:z10.string().nullable(),color:z10.object({bg:z10.string(),text:z10.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z10.object({path:z10.string(),content:z10.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z10.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z10.object({id:z10.string(),messageId:z10.string(),versionId:z10.string().nullable(),role:ProjectChatMessageRole,parts:z10.array(z10.any()),createdAt:z10.coerce.date()}),MessageUserMetadataSchema=z10.object({id:z10.string(),name:z10.string().nullable().optional(),image:z10.string().nullable().optional()}).nullable().optional(),QuestionAnswerMetadataSchema=z10.object({shortTitle:z10.string().optional(),questions:z10.array(z10.object({header:z10.string(),question:z10.string(),answer:z10.string(),selectedLabels:z10.array(z10.string()),freeText:z10.string(),skipped:z10.boolean()}))}).optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z10.number(),metadata:z10.object({user:MessageUserMetadataSchema,changeManifest:z10.array(z10.any()).optional(),questionAnswer:QuestionAnswerMetadataSchema}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z10.object({versionId:z10.uuid(),commitHash:z10.string(),name:z10.string(),description:z10.string().nullable(),kind:z10.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z10.object({versionCount:z10.number().int().nonnegative(),snapshotBytes:z10.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z10.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z10.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z10.object({content:z10.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z10.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z10.object({success:z10.boolean(),message:z10.string().optional(),warning:z10.string().optional(),durationMs:z10.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z10.object({isPublished:z10.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z10.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublicationMutationDTOSchema=z10.object({success:z10.boolean(),message:z10.string().optional(),publishedAt:CommonSchemas.timestamp.optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z11}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=z11.enum(["provisioning","active","deleted"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z11.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,previewUrl:z11.string().nullable(),parentEnv:EnvSchema.nullable(),createdBy:z11.string().nullable(),deletedAt:z11.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),CreateProjectEnvRequestSchema=z11.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z11.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z11.array(ProjectEnvDTOSchema)),EnvSurfaceDiffSchema=z11.object({surface:z11.enum(["code","schemas","content","translations","assets","forms","activations"]),status:z11.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z11.number().int().nonnegative(),conflictCount:z11.number().int().nonnegative()}),EnvDiffResultSchema=z11.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z11.coerce.date(),surfaces:z11.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z12}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=z12.object({success:z12.literal(!0),downloadUrl:z12.string(),expiresAt:z12.string(),fileSize:z12.number(),duration:z12.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z12.object({success:z12.literal(!0),projectId:z12.string(),projectName:z12.string(),displayName:z12.string(),projectUrl:z12.string(),duration:z12.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z12.object({contentTypes:z12.number(),entries:z12.number(),assets:z12.number(),translations:z12.number(),forms:z12.number(),codeFiles:z12.number(),assetFiles:z12.number()}),ImportPreviewSurfaceDTOSchema=z12.object({name:z12.string(),included:z12.boolean(),count:z12.number().optional(),note:z12.string().optional()}),ImportPreviewDTOSchema=z12.object({projectName:z12.string(),displayName:z12.string().nullable(),visibility:z12.string().nullable(),category:z12.string().nullable(),exportedAt:z12.string(),version:z12.string(),envScope:z12.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z12.array(ImportPreviewSurfaceDTOSchema),fileSize:z12.number(),fileName:z12.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z12.object({success:z12.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z13}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=z13.enum(["manual","schedule","webhook"]),ManualTriggerSchema=z13.object({type:z13.literal("manual")}),ScheduleTriggerSchema=z13.object({type:z13.literal("schedule"),cron:z13.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:z13.string().optional()}),WebhookTriggerSchema=z13.object({type:z13.literal("webhook"),path:z13.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z13.discriminatedUnion("type",[ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema])}});import{z as z14}from"zod";var ActivateRequestSchema,DeactivateRequestSchema,AgentActivationDTOSchema,AgentActivationDTO,AgentActivationsListResponseSchema,AgentActivationResponseSchema,WebhookPathTakenErrorSchema,ManualRunRequestSchema,DispatchSkippedSchema,DispatchAcceptedSchema,ManualRunResponseSchema,init_agent_activation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-activation.dto.js"(){"use strict";init_env();init_create_dto();init_response();init_agent_trigger_dto();ActivateRequestSchema=z14.object({triggerIndices:z14.array(z14.number().int().nonnegative()).optional()}),DeactivateRequestSchema=z14.object({triggerIndices:z14.array(z14.number().int().nonnegative()).optional()}),AgentActivationDTOSchema=z14.object({projectId:z14.uuid(),env:EnvSchema,agentName:z14.string().min(1),triggerIndex:z14.number().int().nonnegative(),triggerKind:TriggerKindSchema,trigger:TriggerSchema,enabled:z14.boolean(),lastFiredAt:z14.coerce.date().nullable(),webhookPath:z14.string().nullable(),createdAt:z14.coerce.date(),updatedAt:z14.coerce.date()}),AgentActivationDTO=createDTO(AgentActivationDTOSchema),AgentActivationsListResponseSchema=createResponseSchema(z14.array(AgentActivationDTOSchema)),AgentActivationResponseSchema=createResponseSchema(AgentActivationDTOSchema),WebhookPathTakenErrorSchema=z14.object({error:z14.literal("webhook_path_taken"),conflictAgent:z14.string(),path:z14.string()}),ManualRunRequestSchema=z14.object({args:z14.unknown().optional(),requestId:z14.string().min(1).max(128).optional()}),DispatchSkippedSchema=z14.object({skipped:z14.enum(["duplicate","no-activation","agent-not-cloud","bundle-missing","trigger-stale"])}),DispatchAcceptedSchema=z14.object({sessionId:z14.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z14.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});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,AgentListItemActivationSchema,AgentListItemDTOSchema,AgentListItemDTO,AgentListResponseSchema,init_agent_list_item_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-list-item.dto.js"(){"use strict";init_create_dto();init_response();init_agent_install_summary_dto();init_agent_trigger_dto();AgentListItemTriggerSchema=z16.object({kind:TriggerKindSchema,summary:z16.string()}),AgentListItemActivationSchema=z16.object({triggerIndex:z16.number().int().nonnegative(),triggerKind:TriggerKindSchema,env:z16.string().min(1),active:z16.boolean()}),AgentListItemDTOSchema=z16.object({name:z16.string().min(1),description:z16.string().nullable(),goalFirstLine:z16.string().nullable(),declaredCapabilities:z16.array(CapabilitySummaryEntrySchema),triggers:z16.array(AgentListItemTriggerSchema),activations:z16.array(AgentListItemActivationSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z16.array(AgentListItemDTOSchema))}});import{z as z17}from"zod";var AgentSessionStatusSchema,SessionMetricsSchema,AgentSessionDTOSchema,AgentSessionDTO,AgentSessionCheckpointDTOSchema,AgentSessionCheckpointDTO,AgentSessionResponseSchema,AgentSessionsListResponseSchema,AgentSessionCheckpointsListResponseSchema,AgentSessionWithCheckpointsResponseSchema,SessionErrorCodeSchema,CancelSessionRequestSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_env();init_create_dto();init_response();init_agent_trigger_dto();AgentSessionStatusSchema=z17.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z17.object({cpuMs:z17.number().nonnegative().default(0),netBytes:z17.number().nonnegative().default(0),walltimeMs:z17.number().nonnegative().default(0),llmTokensIn:z17.number().nonnegative().optional(),llmTokensOut:z17.number().nonnegative().optional()}),AgentSessionDTOSchema=z17.object({id:z17.uuid(),projectId:z17.uuid(),env:EnvSchema,agentName:z17.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z17.unknown().optional(),capabilities:z17.array(z17.string()).optional(),dataSources:z17.array(z17.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z17.string().nullable(),startedAt:z17.coerce.date().nullable(),finishedAt:z17.coerce.date().nullable(),cancelledAt:z17.coerce.date().nullable(),costUsd:z17.number().nonnegative(),costCeilingUsd:z17.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z17.boolean(),lastCheckpointId:z17.uuid().nullable(),branchEnvId:z17.uuid().nullable(),parentSessionId:z17.uuid().nullable(),terminalReason:z17.string().nullable(),errorMessage:z17.string().nullable(),report:z17.string().nullable(),createdAt:z17.coerce.date(),updatedAt:z17.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z17.object({id:z17.uuid(),sessionId:z17.uuid(),checkpointIdx:z17.number().int().nonnegative(),payloadRef:z17.string(),payloadSizeBytes:z17.number().int().nonnegative(),checksum:z17.string().length(64),createdAt:z17.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z17.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z17.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z17.object({session:AgentSessionDTOSchema,checkpoints:z17.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z17.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","too_many_agent_envs","env_provisioning_failed"]),CancelSessionRequestSchema=z17.object({reason:z17.string().min(1).max(120).optional()})}});import{z as z18}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=z18.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z18.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z18.object({id:z18.uuid(),envId:z18.uuid(),sessionId:z18.uuid().nullable(),skillName:z18.string().min(1),classification:AgentBranchClassificationSchema,rationale:z18.string().nullable(),summary:z18.string().nullable(),surfaceDeltas:z18.record(z18.string(),z18.unknown()),createdAt:z18.coerce.date(),decidedAt:z18.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z18.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z18.object({path:z18.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z18.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z18.object({code:z18.literal("merge_conflict"),message:z18.string(),conflicts:z18.record(z18.string(),z18.number().int().nonnegative())})}});import{z as z19}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,SetProjectIntegrationCredentialRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,ConnectOrganizationIntegrationRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,BindProjectChannelRequestSchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolOptionsSchema,RunProjectIntegrationToolRequestSchema,ProjectIntegrationToolRunUsageSchema,ProjectIntegrationToolRunBillingSchema,FirecrawlScrapeToolOutputSchema,FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlMonitorScheduleOutputSchema,FirecrawlMonitorTargetOutputSchema,FirecrawlMonitorOutputSchema,FirecrawlMonitorCheckOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema,FirecrawlToolKeySchema,FirecrawlToolOutputSchema,ProjectIntegrationToolRunBaseSchema,ProjectIntegrationToolRunDTOSchema,ProjectIntegrationToolRunDTO,IntegrationsListResponseSchema,IntegrationInfoResponseSchema,ProjectIntegrationStatusResponseSchema,ProjectIntegrationInstallationResponseSchema,ProjectIntegrationToolRunResponseSchema,StartProjectIntegrationConnectResponseResponseSchema,OrganizationIntegrationConnectionResponseSchema,ProjectChannelBindingResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z19.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z19.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z19.enum(["secret_text"]),IntegrationCredentialUsageSchema=z19.enum(["http_bearer","api_key"]),ProjectIntegrationCredentialStatusSchema=z19.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z19.object({mode:IntegrationAuthModeSchema,label:z19.string().min(1),description:z19.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z19.object({id:z19.string().min(1),label:z19.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z19.boolean()}),IntegrationToolDefinitionDTOSchema=z19.object({key:z19.string().min(1),name:z19.string().min(1),description:z19.string().min(1)}),IntegrationRecipeDTOSchema=z19.object({title:z19.string().min(1),description:z19.string().min(1),command:z19.string().min(1).optional()}),IntegrationInfoDTOSchema=z19.object({key:z19.string().min(1),name:z19.string().min(1),summary:z19.string().min(1),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z19.array(IntegrationAuthModeDTOSchema),credentials:z19.array(IntegrationCredentialDefinitionDTOSchema),tools:z19.array(IntegrationToolDefinitionDTOSchema),recipes:z19.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z19.object({projectId:z19.uuid(),integrationKey:z19.string().min(1),installed:z19.boolean(),enabled:z19.boolean(),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z19.string().nullable(),connectionId:z19.uuid().nullable().optional(),connectionAlias:z19.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z19.array(z19.string()),installedAt:z19.coerce.date().nullable(),updatedAt:z19.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z19.object({id:z19.uuid(),projectId:z19.uuid(),integrationKey:z19.string().min(1),enabled:z19.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z19.string(),connectionId:z19.uuid().nullable().optional(),connectionAlias:z19.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z19.array(z19.string()),createdAt:z19.coerce.date(),updatedAt:z19.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z19.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z19.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z19.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z19.object({value:z19.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z19.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z19.object({id:z19.uuid(),organizationId:z19.string().min(1),integrationKey:z19.string().min(1),alias:z19.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z19.string().min(1),externalAccountName:z19.string().nullable(),externalBotUserId:z19.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z19.array(z19.string()),connectedAt:z19.coerce.date(),updatedAt:z19.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ConnectOrganizationIntegrationRequestSchema=z19.object({alias:z19.string().min(1).max(120).optional(),token:z19.string().min(1).optional()}),StartProjectIntegrationConnectResponseSchema=z19.object({integrationKey:z19.string().min(1),connectUrl:z19.string().url(),expiresAt:z19.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),BindProjectChannelRequestSchema=z19.object({ref:z19.string().min(1),connectionAlias:z19.string().min(1).optional(),agentName:z19.string().min(1).max(160).nullable().optional(),force:z19.boolean().optional()}),ProjectChannelBindingDTOSchema=z19.object({id:z19.uuid(),projectId:z19.uuid(),integrationKey:z19.string().min(1),connectionId:z19.uuid(),externalWorkspaceId:z19.string().min(1),externalChannelId:z19.string().min(1),externalChannelName:z19.string().nullable(),agentName:z19.string().nullable(),enabled:z19.boolean(),createdAt:z19.coerce.date(),updatedAt:z19.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),FirecrawlScrapeFormatsSchema=z19.object({markdown:z19.boolean().optional(),summary:z19.boolean().optional(),links:z19.boolean().optional(),images:z19.boolean().optional(),html:z19.union([z19.literal("cleaned"),z19.literal("raw"),z19.boolean()]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z19.object({url:z19.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z19.boolean().optional(),timeoutMs:z19.number().int().positive().max(12e4).optional(),waitForMs:z19.number().int().min(0).max(3e4).optional()}),FirecrawlSearchToolInputSchema=z19.object({query:z19.string().min(1),maxResults:z19.number().int().positive().max(20).optional(),sources:z19.array(z19.enum(["web","news","images"])).min(1).max(3).optional(),categories:z19.array(z19.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z19.array(z19.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z19.array(z19.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z19.enum(["hour","day","week","month","year"]).optional(),location:z19.string().min(1).max(160).optional(),country:z19.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z19.boolean().optional(),timeoutMs:z19.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlMapToolInputSchema=z19.object({url:z19.string().url(),search:z19.string().min(1).optional(),limit:z19.number().int().positive().max(200).optional(),includeSubdomains:z19.boolean().optional(),timeoutMs:z19.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z19.object({url:z19.string().url(),limit:z19.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z19.boolean().optional(),timeoutMs:z19.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z19.object({text:z19.string().min(1).max(200).optional(),cron:z19.string().min(1).max(120).optional(),timezone:z19.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorTargetInputSchema=z19.object({type:z19.enum(["scrape","crawl"]).default("scrape"),urls:z19.array(z19.string().url()).min(1).max(50),scrapeOptions:z19.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z19.boolean().optional(),timeoutMs:z19.number().int().positive().max(12e4).optional(),waitForMs:z19.number().int().min(0).max(3e4).optional()}).optional()}),FirecrawlMonitorCreateToolInputSchema=z19.object({name:z19.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z19.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z19.string().min(1).max(2e3).optional(),judgeEnabled:z19.boolean().optional(),retentionDays:z19.number().int().min(1).max(365).optional(),notification:z19.object({email:z19.object({enabled:z19.boolean().default(!0),recipients:z19.array(z19.string().email()).min(1).max(20),includeDiffs:z19.boolean().optional()}).optional()}).optional()}),FirecrawlMonitorIdToolInputSchema=z19.object({monitorId:z19.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z19.string().uuid()}),RunProjectIntegrationToolOptionsSchema=z19.object({connectionAlias:z19.string().min(1).optional()}),RunProjectIntegrationToolRequestSchema=z19.discriminatedUnion("tool",[RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("search"),input:FirecrawlSearchToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("scrape"),input:FirecrawlScrapeToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("map"),input:FirecrawlMapToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("crawl"),input:FirecrawlCrawlToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.create"),input:FirecrawlMonitorCreateToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.list"),input:z19.object({}).default({})}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.get"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.pause"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.resume"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.delete"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.run"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.checks"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.check"),input:FirecrawlMonitorCheckToolInputSchema})]),ProjectIntegrationToolRunUsageSchema=z19.object({provider:z19.string().min(1),providerCredits:z19.number().nonnegative().optional(),providerCostUsd:z19.number().nonnegative().optional(),requests:z19.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z19.object({credits:z19.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z19.object({url:z19.string(),provider:z19.literal("firecrawl"),title:z19.string().optional(),statusCode:z19.number().optional(),markdown:z19.string().optional(),summary:z19.string().optional(),links:z19.array(z19.string()).optional(),images:z19.array(z19.string()).optional(),html:z19.string().optional(),warning:z19.string().optional()}),FirecrawlSearchToolOutputSchema=z19.object({query:z19.string(),provider:z19.literal("firecrawl"),warning:z19.string().optional(),results:z19.array(z19.object({title:z19.string(),url:z19.string(),snippet:z19.string().optional(),content:z19.string().optional(),score:z19.number().optional(),publishedAt:z19.string().optional()}))}),FirecrawlMapToolOutputSchema=z19.object({url:z19.string(),provider:z19.literal("firecrawl"),count:z19.number(),links:z19.array(z19.object({url:z19.string(),title:z19.string().optional(),description:z19.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z19.object({url:z19.string(),provider:z19.literal("firecrawl"),total:z19.number(),pages:z19.array(z19.object({url:z19.string(),title:z19.string().optional(),statusCode:z19.number().optional(),markdown:z19.string().optional(),summary:z19.string().optional(),links:z19.array(z19.string()).optional(),images:z19.array(z19.string()).optional(),html:z19.string().optional(),warning:z19.string().optional()})),warning:z19.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z19.object({cron:z19.string().optional(),text:z19.string().optional(),timezone:z19.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z19.object({id:z19.string().optional(),urls:z19.array(z19.string()).optional(),scrapeOptions:z19.record(z19.string(),z19.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z19.object({id:z19.string(),name:z19.string(),status:z19.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z19.string().nullable().optional(),lastRunAt:z19.string().nullable().optional(),currentCheckId:z19.string().nullable().optional(),targets:z19.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z19.string().nullable().optional(),judgeEnabled:z19.boolean().optional(),estimatedCreditsPerMonth:z19.number().optional(),createdAt:z19.string().optional(),updatedAt:z19.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z19.object({id:z19.string(),monitorId:z19.string(),scheduledFor:z19.string().nullable().optional(),startedAt:z19.string().nullable().optional(),finishedAt:z19.string().nullable().optional(),estimatedCredits:z19.number().optional(),reservedCredits:z19.number().optional(),actualCredits:z19.number().optional(),billingStatus:z19.string().nullable().optional(),summary:z19.object({totalPages:z19.number().optional(),same:z19.number().optional(),changed:z19.number().optional(),new:z19.number().optional(),removed:z19.number().optional(),error:z19.number().optional()}).passthrough().optional(),error:z19.string().nullable().optional(),createdAt:z19.string().optional(),updatedAt:z19.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z19.object({provider:z19.literal("firecrawl"),monitors:z19.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z19.object({provider:z19.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z19.object({provider:z19.literal("firecrawl"),monitorId:z19.string(),deleted:z19.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z19.object({provider:z19.literal("firecrawl"),monitorId:z19.string(),checks:z19.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z19.object({provider:z19.literal("firecrawl"),monitorId:z19.string(),check:FirecrawlMonitorCheckOutputSchema,next:z19.string().optional()}),FirecrawlToolKeySchema=z19.enum(["search","scrape","map","crawl","monitor.create","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z19.union([FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z19.object({projectId:z19.uuid(),integrationKey:z19.string().min(1),tool:FirecrawlToolKeySchema,connectionAlias:z19.string().min(1).nullable().optional(),output:FirecrawlToolOutputSchema,executedAt:z19.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z19.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z19.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z19.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z19.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z19.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z19.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z19.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z19.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema)}});import{z as z20}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=z20.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=z20.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z20.uuid(),env:z20.string().min(1),name:z20.string().min(1),cron:z20.string().min(1),command:z20.string().min(1),secretKeys:z20.array(z20.string().min(1)),enabled:z20.boolean(),lastRunAt:z20.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z20.string().nullable()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z20.object({name:z20.string().min(1).max(120),cron:z20.string().min(1).max(120),command:z20.string().min(1).max(500),secretKeys:z20.array(ProjectSecretKeySchema).default([])}),UpdateProjectScheduleRequestSchema=z20.object({name:z20.string().min(1).max(120).optional(),cron:z20.string().min(1).max(120).optional(),command:z20.string().min(1).max(500).optional(),secretKeys:z20.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z20.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z20.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z20.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z20.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z20.object({maxRuns:z20.number().int().positive(),retentionDays:z20.number().int().positive().nullable(),outputRetentionDays:z20.number().int().positive(),maxOutputBytes:z20.number().int().positive()}),ProjectScheduleUsageSchema=z20.object({runCount:z20.number().int().nonnegative(),runsWithOutput:z20.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z20.object({id:z20.uuid(),scheduleId:z20.uuid(),projectId:z20.uuid(),env:z20.string().min(1),scheduleName:z20.string().min(1),command:z20.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z20.object({id:z20.string().min(1),name:z20.string().min(1)}).nullable(),queuedAt:z20.coerce.date(),startedAt:z20.coerce.date().nullable(),finishedAt:z20.coerce.date().nullable(),exitCode:z20.number().int().nullable(),errorCode:z20.string().nullable(),error:z20.string().nullable(),outputBytes:z20.number().int().nonnegative(),outputTruncated:z20.boolean(),outputExpiresAt:z20.coerce.date().nullable(),metadataExpiresAt:z20.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z20.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z20.coerce.date().nullable(),items:z20.array(z20.object({key:z20.string().min(1),updatedAt:z20.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z20.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z20.object({trigger:z20.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z20.object({limit:z20.coerce.number().int().min(1).max(100).default(25),cursor:z20.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z20.object({items:z20.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z20.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z20.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z20.object({items:z20.array(ProjectScheduleRunDTOSchema),nextCursor:z20.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z21}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=z21.object({id:z21.uuid(),occurredAt:z21.coerce.date(),projectId:z21.uuid().nullable(),env:z21.string().nullable(),actor:z21.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z21.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z21.unknown().optional(),ipAddress:z21.string().nullable().optional(),userAgent:z21.string().nullable().optional(),error:z21.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z21.object({rows:z21.array(AuditLogRowDTOSchema),nextCursor:z21.string().nullable()})),AuditLogQuerySchema=z21.object({env:z21.string().optional(),action:AuditActionSchema.optional(),actor:z21.string().optional(),from:z21.coerce.date().optional(),to:z21.coerce.date().optional(),limit:z21.coerce.number().int().min(1).max(200).optional(),cursor:z21.string().optional()})}});import{z as z22}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,ActivationSnapshotSchema,ActivationDiffSchema,ActivationDiffDTO,ActivationDiffResponseSchema,CONFLICT_KINDS,ConflictKindSchema,ConflictSchema,FieldPickSchema,ConflictResolutionSchema,MergeResultSchema,MergeResultDTO,MergeResultResponseSchema,EngineStrategySchema,VendorStrategySchema,MergeStrategySchema,ResolvedStrategySchema,MergeRequestSchema,MergeInitiateResultSchema,MergeInitiateResultDTO,MergeInitiateResponseSchema,MergeConflictsHydrationSchema,MergeConflictsHydrationDTO,MergeConflictsHydrationResponseSchema,MergeResolveDraftRequestSchema,MergeResolveDraftResultSchema,MergeResolveDraftResultDTO,MergeResolveRequestSchema,MergeCancelRequestSchema,PublishReleaseRequestSchema,PublishReleaseResultSchema,PublishReleaseResultDTO,PublishReleaseResponseSchema,init_env_status_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-status.dto.js"(){"use strict";init_env();init_create_dto();init_response();SurfaceNameSchema=z22.enum(["code","schemas","content","translations","assets","forms","activations"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms","activations"],SurfaceDeltaVerbSchema=z22.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z22.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z22.object({verb:SurfaceDeltaVerbSchema,key:z22.string(),detail:z22.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z22.record(z22.string(),z22.unknown()).optional()}),PerSurfaceDeltaSchema=z22.object({surface:SurfaceNameSchema,status:z22.enum(["ok","timed_out","failed","unchanged"]),durationMs:z22.number().int().nonnegative().optional(),changedCount:z22.number().int().nonnegative(),conflictCount:z22.number().int().nonnegative(),items:z22.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z22.boolean().optional(),error:z22.string().optional()}),CrossSurfaceFindingSchema=z22.object({id:z22.string(),kind:z22.string(),description:z22.string(),severity:z22.enum(["warning","error"]),source:z22.object({surface:SurfaceNameSchema,key:z22.string()}),target:z22.object({surface:SurfaceNameSchema,key:z22.string()}),actions:z22.array(z22.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z22.object({env:EnvSchema,vs:EnvSchema,syncState:z22.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z22.coerce.date(),surfaces:z22.array(PerSurfaceDeltaSchema),agents:z22.array(z22.object({id:z22.string(),name:z22.string(),status:z22.enum(["active","paused","failed"]),lastRunAt:z22.coerce.date().nullable()})).optional(),crossSurface:z22.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z22.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z22.coerce.date(),surfaces:z22.array(PerSurfaceDeltaSchema),crossSurface:z22.array(CrossSurfaceFindingSchema).optional(),fingerprint:z22.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z22.object({path:z22.string(),state:z22.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z22.string(),additions:z22.number().int().nonnegative(),deletions:z22.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z22.object({oid:z22.string().optional(),content:z22.string().optional(),truncated:z22.boolean(),binary:z22.boolean()}),CodeConflictDetailSchema=z22.object({path:z22.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z22.string(),targetTipSha:z22.string(),mergeBaseSha:z22.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z22.object({id:z22.string(),slug:z22.string(),contentType:z22.string(),data:z22.record(z22.string(),z22.unknown()),updatedAt:z22.coerce.date()}),ContentRowDiffSchema=z22.object({collection:z22.string(),rowId:z22.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z22.object({name:z22.string(),label:z22.string(),isSingleton:z22.boolean(),fields:z22.record(z22.string(),z22.unknown())}),SchemaTypeDiffSchema=z22.object({typeName:z22.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z22.object({id:z22.string(),name:z22.string(),type:z22.enum(["file","folder"]),mimeType:z22.string().nullable(),storageKey:z22.string().nullable(),url:z22.string().nullable(),fileSize:z22.number().nullable(),width:z22.number().nullable(),height:z22.number().nullable(),altText:z22.string().nullable(),caption:z22.string().nullable(),createdAt:z22.coerce.date(),updatedAt:z22.coerce.date()}),AssetDiffSchema=z22.object({assetId:z22.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z22.object({locale:z22.string(),key:z22.string(),parent:z22.string().nullable(),child:z22.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z22.object({formName:z22.string(),label:z22.string().nullable(),schemaFingerprint:z22.string(),fields:z22.record(z22.string(),z22.unknown()),settings:z22.record(z22.string(),z22.unknown()).optional()}),FormSchemaDiffSchema=z22.object({formName:z22.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),ActivationSnapshotSchema=z22.object({agentName:z22.string(),triggerIndex:z22.number().int().nonnegative(),triggerKind:z22.string(),triggerSpec:z22.record(z22.string(),z22.unknown()),enabled:z22.boolean(),emailRecipients:z22.array(z22.string()).nullable(),qstashScheduleId:z22.string().nullable()}),ActivationDiffSchema=z22.object({agentName:z22.string(),triggerIndex:z22.number().int().nonnegative(),parent:ActivationSnapshotSchema.nullable(),child:ActivationSnapshotSchema.nullable()}),ActivationDiffDTO=createDTO(ActivationDiffSchema),ActivationDiffResponseSchema=createResponseSchema(ActivationDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z22.enum(CONFLICT_KINDS),ConflictSchema=z22.object({surface:SurfaceNameSchema,key:z22.string(),kind:ConflictKindSchema.optional(),description:z22.string(),parentValue:z22.unknown().optional(),childValue:z22.unknown().optional(),conflictingFields:z22.array(z22.string()).optional(),code:z22.object({path:z22.string(),unresolvable:z22.boolean().optional(),reason:z22.string().optional()}).optional()}),FieldPickSchema=z22.object({field:z22.string(),choice:z22.enum(["parent","child","pick","ai-pick"]),pickedValue:z22.unknown().optional(),aiSessionId:z22.string().optional()}),ConflictResolutionSchema=z22.object({surface:SurfaceNameSchema,key:z22.string(),choice:z22.enum(["parent","child","pick"]),pickedValue:z22.unknown().optional(),fieldPicks:z22.array(FieldPickSchema).optional()}),MergeResultSchema=z22.object({ok:z22.boolean(),mergeId:z22.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z22.array(z22.object({surface:SurfaceNameSchema,count:z22.number().int().nonnegative()})),conflicts:z22.array(ConflictSchema).optional(),summary:z22.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z22.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z22.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z22.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z22.boolean().optional()}),ResolvedStrategySchema=z22.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z22.boolean()}),MergeRequestSchema=z22.object({from:EnvSchema,allowDirectMerge:z22.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z22.object({mergeId:z22.string().uuid(),streamUrl:z22.string(),strategy:ResolvedStrategySchema,acceptedAt:z22.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z22.object({mergeId:z22.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z22.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z22.array(ConflictSchema),draftResolutions:z22.array(ConflictResolutionSchema),lastEditedBy:z22.string().nullable(),lastEditedAt:z22.coerce.date().nullable(),initiator:z22.object({userId:z22.string().nullable(),role:z22.string().nullable(),agentName:z22.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z22.object({resolutions:z22.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z22.object({mergeId:z22.string().uuid(),draftResolutions:z22.array(ConflictResolutionSchema),lastEditedAt:z22.coerce.date(),lastEditedBy:z22.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z22.object({mergeId:z22.string().uuid(),resolutions:z22.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z22.object({mergeId:z22.string().uuid()}),PublishReleaseRequestSchema=z22.object({version:z22.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z22.string().max(2e4).optional()}),PublishReleaseResultSchema=z22.object({releaseTag:z22.string(),sha:z22.string(),publishedAt:z22.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z23}from"zod";var 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=z23.object({surface:SurfaceNameSchema,key:z23.string(),label:z23.string()}),InlineSchema=z23.object({text:z23.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z23.discriminatedUnion("type",[z23.object({type:z23.literal("paragraph"),content:z23.array(InlineSchema).max(24)}),z23.object({type:z23.literal("preview"),ref:DiffRefSchema,caption:z23.string().optional()}),z23.object({type:z23.literal("code"),code:z23.string(),lang:z23.string().optional(),caption:z23.string().optional()}),z23.object({type:z23.literal("risk"),level:z23.enum(["warning","error"]),content:z23.array(InlineSchema).max(24)}),z23.object({type:z23.literal("list"),items:z23.array(z23.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z23.object({headline:z23.string(),blocks:z23.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z23.object({summary:EnvDiffSummarySchema,fingerprint:z23.string(),generatedAt:z23.coerce.date(),cached:z23.boolean().optional(),credits:z23.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z24}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=z24.object({date:z24.string(),visitors:z24.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z24.object({key:z24.string(),visitors:z24.number().int().nonnegative(),pageviews:z24.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z24.object({path:z24.string(),pageName:z24.string().nullable().optional(),visitors:z24.number().int().nonnegative(),pageviews:z24.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z24.object({preset:z24.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z24.string(),requestedTo:z24.string(),effectiveFrom:z24.string(),effectiveTo:z24.string(),isRetentionLimited:z24.boolean(),groupBy:z24.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z24.object({date:z24.string(),content:z24.string(),updatedAt:z24.string(),updatedByUserId:z24.string()}),ProjectPageviewAnalyticsDTOSchema=z24.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z24.number().int().nonnegative(),pageviews:z24.number().int().nonnegative(),bounceRate:z24.number().min(0).max(100),viewsPerVisit:z24.number().nonnegative(),averageVisitDurationSeconds:z24.number().nonnegative(),visitorsSeries:z24.array(ProjectDailyVisitorsDTOSchema),topPages:z24.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z24.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z24.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z24.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z24.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z24.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z25}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=z25.object({id:z25.string(),email:z25.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z25.coerce.date(),createdAt:z25.coerce.date(),inviterUserId:z25.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z25.object({id:z25.string(),token:z25.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z25.object({success:z25.boolean(),projectId:z25.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z26}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=z26.object({id:z26.string(),name:z26.string(),image:z26.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z26.object({count:z26.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z26.object({counts:z26.object({signed_up:z26.int(),activated:z26.int()}),credits:z26.object({total:z26.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z26.email(),emailVerified:z26.boolean(),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z27}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,ProjectPermissionsDTOSchema,ProjectPermissionsDTO,ProjectAccessDTOSchema,ProjectAccessDTO,AccessMutationResponseSchema,InviteAcceptResponseSchema,init_project_access_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-access.dto.js"(){"use strict";init_common();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z27.object({id:z27.string(),principalType:ProjectPrincipalTypeSchema,principalId:z27.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z27.coerce.date(),expiresAt:z27.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),ProjectPermissionsDTOSchema=z27.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z27.record(z27.string(),z27.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z27.object({access:z27.array(ProjectAccessItemDTOSchema),invites:z27.array(ProjectInviteDTOSchema),organization:z27.object({name:z27.string().nullable(),logo:z27.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z27.object({success:z27.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z27.object({success:z27.boolean(),projectId:z27.uuid()}))}});import{z as z28}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=z28.object({publicationStatus:PublicationStatusSchema,appUrl:z28.string().nullable(),lastPublishedAt:z28.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z29}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=z29.object({url:z29.url(),expiresAt:z29.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema)}});import{z as z30}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:z30.string(),slug:z30.string().nullable(),logo:z30.string().nullable(),metadata:z30.record(z30.string(),z30.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z30.object({id:z30.string(),name:z30.string(),email:z30.email(),image:z30.string().nullable()}),OrganizationMemberDTOSchema=z30.object({id:z30.string(),userId:z30.string(),organizationId:z30.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z30.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z31}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=z31.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z31.object({reason:CancellationReasonCodeSchema,details:z31.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z31.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),AiCreditsEntitlementSchema=z31.object({included:z31.number().optional(),unitPrice:z31.number().optional(),dailyCap:z31.number().nullable().optional()}),EntitlementsDTOSchema=z31.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z31.object({retentionDays:z31.number().int().positive(),canUseExtendedDateRanges:z31.boolean()}).optional(),history:z31.object({retentionDays:z31.number().int().positive()}).optional(),members:z31.object({canInvite:z31.boolean(),maxMembers:z31.number().int().positive().nullable()}).optional(),projects:z31.object({canCreatePrivateProjects:z31.boolean(),maxPrivateProjects:z31.number().int().positive().nullable()}).optional(),domains:z31.object({canUseCustomDomains:z31.boolean(),maxDomains:z31.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z31.object({id:z31.string(),external_id:z31.string(),customerId:z31.string(),planId:z31.string(),planCode:TemplateCodeSchema,currentPeriod:z31.object({start:z31.string(),end:z31.string().nullable()}),cancelAt:z31.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z31.string(),nextPaymentAt:z31.string().nullable(),baseAmount:z31.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z31.object({totalCap:z31.number(),dailyCap:z31.number(),usedTotal:z31.number()}),CreditBalanceDTOSchema=z31.object({total:z31.number(),base:z31.number(),dailyBase:z31.number(),purchases:z31.number(),awards:z31.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z31.object({total:z31.number(),nearLimit:z31.boolean(),canChat:z31.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z31.object({dailyFreeAvailable:z31.number(),monthlyAvailable:z31.number(),purchasedAvailable:z31.number(),awardedAvailable:z31.number()}),ProjectDailyCreditAllowanceDTOSchema=z31.object({periodCap:z31.number(),dailyGrant:z31.number(),usedThisPeriod:z31.number(),remainingThisPeriod:z31.number()}),ProjectCreditBalanceDTOSchema=z31.object({projectId:z31.uuid(),organizationId:z31.string(),balance:z31.object({totalAvailable:z31.number(),nearLimit:z31.boolean(),canUseAi:z31.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z31.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),SuccessfulPurchaseDTOSchema=z31.object({invoiceId:z31.string(),newBalance:z31.int(),creditCount:z31.int(),amountUsd:z31.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z31.object({url:z31.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 z32}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=z32.object({brand:z32.string(),last4:z32.string(),exp:z32.string(),isDefault:z32.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z33}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=z33.string().superRefine((path47,ctx)=>{let segments=path47.split(".");(segments.length===0||segments.some(segment=>!CONTENT_FIELD_NAME_PATTERN.test(segment)))&&ctx.addIssue({code:"custom",message:"Field paths must use dot-separated field or block variant names."})}),SchemaMigrationOperationSchema=z33.object({type:z33.literal("renameField"),contentType:z33.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z33.object({enabled:z33.boolean()}).strict(),ContentTypeDTOSchema=z33.object({id:z33.string(),name:z33.string(),label:z33.string(),isSingleton:z33.boolean(),i18n:ContentTypeI18nSchema,fields:z33.record(z33.string(),FieldDefinitionSchema),createdAt:z33.string(),updatedAt:z33.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z33.object({contentTypes:z33.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z33.object({id:z33.string(),entryId:z33.string(),documentId:z33.string(),slug:z33.string(),locale:z33.string().optional(),createdAt:z33.string(),updatedAt:z33.string(),__fimo:z33.object({contentType:z33.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z33.object({data:z33.array(EntryDTOSchema),meta:z33.object({limit:z33.number(),offset:z33.number(),total:z33.number(),hasMore:z33.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z33.object({contentType:z33.string(),count:z33.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z33.object({counts:z33.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z33.object({count:z33.number().int().nonnegative(),sourceLocale:z33.string(),targetLocale:z33.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z33.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z33.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z33.union([z33.string(),z33.number(),z33.boolean(),z33.null()]),entryWhereOperatorSchema=z33.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z33.array(entryWhereScalarSchema).optional(),$nin:z33.array(entryWhereScalarSchema).optional(),$contains:z33.string().optional(),$startsWith:z33.string().optional(),$null:z33.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z33.record(z33.string(),z33.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z33.record(z33.string(),z33.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z33.object({data:z33.record(z33.string(),z33.unknown()),locale:z33.string().min(1).optional(),documentId:z33.uuid().optional()}),entryIdsSchema=z33.array(z33.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z33.object({sql:z33.string().min(1)}),BulkCreateEntriesRequestSchema=z33.object({entries:z33.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z33.union([z33.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z33.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z33.object({updates:z33.array(z33.object({id:z33.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z33.union([z33.object({ids:entryIdsSchema,locale:z33.string().min(1).optional()}),z33.object({where:EntryWhereSchema,locale:z33.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z33.object({data:z33.array(z33.record(z33.string(),z33.unknown())),meta:z33.object({rowCount:z33.number().int().nonnegative(),truncated:z33.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z33.object({data:z33.array(EntryDTOSchema),meta:z33.object({created:z33.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z33.object({data:z33.array(EntryDTOSchema),meta:z33.object({updated:z33.number().int().nonnegative(),missing:z33.array(z33.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z33.object({data:z33.array(EntryDTOSchema),meta:z33.object({deleted:z33.number().int().nonnegative(),missing:z33.array(z33.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z34}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z34.object({index:z34.number().int().nonnegative(),contentType:z34.string(),field:z34.string(),value:z34.string(),against:z34.enum(["stored","batch"]),ownerDocumentId:z34.uuid().optional(),ownerIndex:z34.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z34.object({code:z34.literal("unique_conflict"),message:z34.string(),conflicts:z34.array(UniqueConflictSchema),truncated:z34.boolean().optional()})}});import{z as z35}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=z35.object({kind:z35.literal("unique_conflict"),contentType:z35.string(),field:z35.string(),value:z35.string(),documentCount:z35.number().int().positive(),documentIds:z35.array(z35.uuid()),documentIdsTruncated:z35.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z35.object({code:z35.literal("schema_transition_rejected"),message:z35.string(),issues:z35.array(SchemaTransitionIssueSchema),truncated:z35.boolean().optional()})}});import{z as z36}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=z36.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z36.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z36.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z36.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z36.object({field:CmsFieldNameSchema,direction:z36.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z36.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z36.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z36.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z36.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z36.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z37}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=z37.object({id:z37.string(),name:z37.string()}),AssetDTOSchema=z37.object({id:z37.string(),name:z37.string(),type:AssetTypeSchema,originalFileName:z37.string().nullable(),parentId:z37.string().nullable(),mimeType:z37.string().nullable(),fileSize:z37.number().nullable(),url:z37.string().nullable(),storageKey:z37.string().nullable(),createdAt:z37.string(),updatedAt:z37.string(),altText:z37.string().nullable().optional(),caption:z37.string().nullable().optional(),aiCaption:z37.string().nullable().optional(),aiAltText:z37.string().nullable().optional(),aiTags:z37.array(z37.string()).nullable().optional(),aiPrimaryColor:z37.string().nullable().optional(),aiProcessingStatus:z37.string().nullable().optional(),width:z37.number().nullable().optional(),height:z37.number().nullable().optional(),path:z37.array(AssetPathItemSchema).optional(),hasChildren:z37.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z37.lazy(()=>z37.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z37.array(AssetDTOSchema))}});import{z as z38}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z38.object({key:z38.string(),value:z38.string().optional(),defaultValue:z38.string(),locale:z38.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z39}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=z39.object({id:z39.string(),name:z39.string(),type:z39.enum(["file","folder"]),path:z39.string(),children:z39.lazy(()=>z39.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z39.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z39.object({path:z39.string(),exists:z39.boolean(),type:z39.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z40}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatDeletionDTOSchema,ChatDeletionDTO,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,ChatDeletionResponseSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_create_dto();init_response();init_project_dto();ChatMessageListDTOSchema=z40.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z40.object({items:z40.array(ProjectMessagePublicDTOSchema),nextCursor:z40.string().nullable()}),ChatDeletionDTOSchema=z40.object({success:z40.boolean(),deletedCount:z40.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema)}});import{z as z41}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=z41.object({url:z41.string().url(),key:z41.string(),size:z41.number(),contentType:z41.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z42}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=z42.object({canAccess:z42.boolean(),permissions:z42.record(z42.string(),z42.boolean()),role:z42.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z43}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:z43.string().trim().default(""),sort:z43.enum(["recent","name","relevance"]).default("recent"),category:z43.string().optional(),visibility:z43.enum(["public","private"]).optional()})}});import{z as z44}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=z44.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z44.enum(["fimo","external"]),PaymentStatusSchema=z44.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z44.object({id:z44.string().uuid(),domain:z44.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z44.boolean(),price:z44.number().int().nullable(),renewalPrice:z44.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z44.string().nullable(),failureReason:z44.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z44.object({domain:z44.string(),available:z44.boolean(),premium:z44.boolean(),price:z44.number().nullable(),renewalPrice:z44.number().nullable(),purchaseType:z44.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z44.object({domain:z44.string(),price:z44.number().nullable(),renewalPrice:z44.number().nullable(),premium:z44.boolean(),allowedYears:z44.array(z44.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z44.object({firstName:z44.string().max(100),lastName:z44.string().max(100),companyName:z44.string().max(100).optional(),address1:z44.string().max(255),address2:z44.string().max(255).optional(),city:z44.string().max(100),state:z44.string().max(100),zip:z44.string().max(20),country:z44.string().max(2),phone:z44.string().max(30),email:z44.union([z44.string().email().max(255),z44.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z44.object({firstName:z44.string().min(1).max(100),lastName:z44.string().min(1).max(100),companyName:z44.string().max(100).optional(),address1:z44.string().min(1).max(255),address2:z44.string().max(255).optional(),city:z44.string().min(1).max(100),state:z44.string().min(1).max(100),zip:z44.string().min(1).max(20),country:z44.string().min(1).max(2),phone:z44.string().min(1).max(30),email:z44.string().email().max(255)}),SearchDomainsRequestSchema=z44.object({keyword:z44.string().min(1).max(100),tldFilter:z44.array(z44.string()).optional()}),CheckAvailabilityRequestSchema=z44.object({domains:z44.array(z44.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=z44.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z44.object({domain:DomainNameSchema,years:z44.number().int().min(1).max(10).optional().default(3),autoRenew:z44.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z44.object({autoRenew:z44.boolean().optional()}),RenewDomainRequestSchema=z44.object({years:z44.number().int().min(1).max(10).optional().default(1),autoRenew:z44.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z44.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z44.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z44.object({verified:z44.boolean(),email:z44.string().nullable(),verifyBy:z44.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z45}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=z45.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=z45.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=z45.object({txtName:z45.string().nullable().optional(),txtValue:z45.string().nullable().optional(),httpUrl:z45.string().nullable().optional(),httpBody:z45.string().nullable().optional(),cname:z45.string().nullable().optional(),cnameTarget:z45.string().nullable().optional()}),SSLValidationErrorSchema=z45.object({message:z45.string()}),OwnershipVerificationSchema=z45.object({type:z45.string(),name:z45.string(),value:z45.string()}),ProjectDomainSSLDTOSchema=z45.object({status:z45.string(),method:z45.string().nullable(),type:z45.string().nullable(),validationRecords:z45.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z45.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z45.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z45.enum(["subdomain","apex"]),RedirectConfigSchema=z45.object({type:z45.literal("apex_to_www"),linkedDomainId:z45.string()}).nullable().optional(),ProjectDomainDTOSchema=z45.object({id:z45.string(),hostname:z45.string(),status:z45.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z45.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z45.string(),scdCnameTarget:z45.string().optional(),apexTargets:z45.array(z45.string()),dnsAutoConfigured:z45.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z45.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z45.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z45.object({hostname:z45.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:z45.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z45.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z45.object({available:z45.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z45.object({success:z45.boolean(),hostname:z45.string()}))}});import{z as z46}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=z46.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z46.object({available:z46.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z46.object({slug:z46.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z46.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z46.object({subdomain:z46.string(),subdomainUpdatedAt:z46.coerce.date()})),SubdomainSuggestionsQuerySchema=z46.object({base:z46.string().max(100).optional(),max:z46.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z46.object({suggestions:z46.array(z46.string())}))}});import{z as z47}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=z47.object({translated:z47.number().int().nonnegative(),total:z47.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z47.object({locale:z47.string(),isDefault:z47.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z47.object({defaultLocale:z47.string(),routing:z47.object({strategy:z47.literal("path-prefix"),prefixDefaultLocale:z47.boolean()}),locales:z47.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z47.object({locale:z47.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z47.object({locale:z47.string().min(1).max(40)}),ProjectLocaleMutationSchema=z47.object({locale:z47.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z47.object({locale:z47.string(),entriesDeleted:z47.number().int().nonnegative(),labelsDeleted:z47.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z48}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=z48.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z48.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=z48.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z48.number(),credits:z48.number().optional(),billingMode:z48.enum(["fimo-credits","provider-account"]).optional(),confidence:z48.enum(["exact","estimated","metered"]),basis:z48.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z49}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=z49.object({options:z49.record(z49.string(),z49.unknown()),name:z49.string().optional(),parentId:z49.string().nullable().optional(),altText:z49.string().optional(),caption:z49.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z49.string().min(1).optional(),model:z49.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=z49.object({jobId:z49.string(),status:z49.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z49.string().nullable().optional(),credits:z49.number().optional(),costUsd:z49.number().optional(),billingMode:z49.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z49.object({error:z49.string(),code:z49.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:z49.array(GenerationTaskIdSchema).optional(),availableModels:z49.array(z49.string()).optional(),issues:z49.array(z49.unknown()).optional()})}});import{z as z50}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=z50.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z50.object({name:z50.string(),key:z50.string(),description:z50.string(),type:FlagTypeSchema,required:z50.boolean(),defaultValue:z50.unknown().optional(),enumValues:z50.array(z50.string()).optional(),isArray:z50.boolean()}),AssetModelPriceSchema=z50.object({unitPrice:z50.number(),unit:z50.string(),confidence:z50.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z50.object({id:z50.string(),shortName:z50.string(),provider:z50.string(),source:z50.string(),modality:z50.enum(["image","video","audio"]),tags:z50.array(z50.string()),displayName:z50.string(),description:z50.string(),flags:z50.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z50.object({model:z50.string(),costUsd:z50.number(),credits:z50.number(),billingMode:z50.enum(["fimo-credits","provider-account"]),confidence:z50.enum(["exact","estimated","metered"]),basis:z50.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z51}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=z51.object({tourId:z51.string(),version:z51.string(),status:z51.string(),completedAt:z51.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z51.array(UserTourDTOSchema))}});import{z as z52}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=z52.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z52.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z52.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z52.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z52.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z52.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z52.enum(["user","agent","system"]),SupportReportTagSchema=z52.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z52.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z52.object({organization:z52.object({id:z52.string().trim().min(1).max(255),name:z52.string().trim().max(240).optional()}),project:z52.object({id:z52.uuid(),name:z52.string().trim().max(240).optional(),createdAt:z52.coerce.date().optional()}).optional(),environment:z52.string().trim().max(255).optional(),clientVersion:z52.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z52.object({message:z52.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z52.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z52.string().trim().max(200).optional(),limit:z52.coerce.number().int().min(1).max(100).default(50),offset:z52.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z52.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z52.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z52.uuid().nullable().optional(),note:z52.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=z52.object({message:z52.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z52.object({kind:SupportReportLinkKindSchema,label:z52.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z52.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z52.object({kind:SupportReportActorKindSchema,id:z52.string().nullable(),name:z52.string().nullable()}),SupportReportLinkDTOSchema=z52.object({id:z52.uuid(),kind:SupportReportLinkKindSchema,label:z52.string(),url:SupportReportHttpUrlSchema,externalId:z52.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z52.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z52.object({id:z52.uuid(),kind:SupportReportEventKindSchema,body:z52.string().nullable(),metadata:z52.record(z52.string(),z52.unknown()),actor:SupportReportActorDTOSchema,createdAt:z52.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z52.object({id:z52.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z52.array(z52.string()),source:SupportReportSourceSchema,message:z52.string(),reporter:z52.object({id:z52.string().nullable(),name:z52.string().nullable(),email:z52.string().nullable()}),organization:z52.object({id:z52.string().nullable(),name:z52.string()}),project:z52.object({id:z52.uuid().nullable(),name:z52.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z52.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z52.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z52.string().nullable(),deliveredAt:z52.coerce.date().nullable()}).nullable(),duplicateOfReportId:z52.uuid().nullable(),resolvedAt:z52.coerce.date().nullable(),createdAt:z52.coerce.date(),updatedAt:z52.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z52.string().nullable(),clientVersion:z52.string().nullable(),links:z52.array(SupportReportLinkDTOSchema),events:z52.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z52.object({reports:z52.array(SupportReportSummaryDTOSchema),total:z52.number().int().nonnegative(),statusCounts:z52.object({new:z52.number().int().nonnegative(),in_progress:z52.number().int().nonnegative(),waiting:z52.number().int().nonnegative(),resolved:z52.number().int().nonnegative(),duplicate:z52.number().int().nonnegative(),irrelevant:z52.number().int().nonnegative(),ignored:z52.number().int().nonnegative()}),limit:z52.number().int().positive(),offset:z52.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z52.object({id:z52.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z52.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z53}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=z53.iso.datetime({offset:!0}).pipe(z53.coerce.date()),OpsRecentChatInputSchema=z53.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z53.string().trim().min(1).max(255).optional(),limit:z53.coerce.number().int().min(1).max(200).default(100),cursor:z53.string().trim().min(1).max(2e3).optional(),slim:z53.boolean().default(!0),reason:z53.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=z53.object({id:z53.string(),messageId:z53.string(),env:z53.string(),versionId:z53.string().nullable(),userId:z53.string().nullable(),role:z53.string(),parts:z53.array(z53.record(z53.string(),z53.unknown())),metadata:z53.object({status:z53.string().optional(),traceUrl:z53.string().optional(),externalFileChanges:z53.array(z53.unknown()).optional()}),stats:z53.object({toolCount:z53.number().int().nonnegative(),failedToolCount:z53.number().int().nonnegative()}),createdAt:z53.iso.datetime({offset:!0}),project:z53.object({id:z53.string(),name:z53.string(),displayName:z53.string().nullable(),organizationId:z53.string().nullable()})}),OpsRecentChatResponseSchema=z53.object({target:z53.object({backendProfile:OpsBackendProfileSchema,projectEnv:z53.string().nullable()}),window:z53.object({from:z53.iso.datetime({offset:!0}),to:z53.iso.datetime({offset:!0})}),messages:z53.object({items:z53.array(OpsRecentChatMessageSchema),nextCursor:z53.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z54}from"zod";function createAgentRunWebhookEventDataSchema(status){return z54.object({run:z54.object({id:z54.string(),agentName:z54.string(),trigger:z54.string(),status:z54.literal(status),startedAt:z54.string().nullable(),finishedAt:z54.string().nullable(),reason:z54.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=z54.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z54.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z54.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z54.enum(["main","all"]),WebhookEntryBatchWindowSecondsSchema=z54.union([z54.literal(0),z54.literal(5),z54.literal(30),z54.literal(60)]),EntryChangedWebhookEventDataSchema=z54.object({reason:WebhookEntryChangeReasonSchema,operationId:z54.string().optional(),batch:z54.object({index:z54.number().int().positive(),total:z54.number().int().positive()}).optional(),changes:z54.array(z54.object({action:WebhookEntryChangeActionSchema,contentType:z54.string(),id:z54.string(),documentId:z54.string(),locale:z54.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z54.object({form:z54.object({id:z54.string(),label:z54.string()}),submission:z54.object({id:z54.string(),data:z54.record(z54.string(),z54.unknown()),submittedAt:z54.string()})}),PublishStartedWebhookEventDataSchema=z54.object({publication:z54.object({status:z54.literal("publishing"),startedAt:z54.string()})}),PublishSucceededWebhookEventDataSchema=z54.object({publication:z54.object({status:z54.literal("published"),url:z54.string(),publishedAt:z54.string(),firstPublish:z54.boolean()})}),PublishFailedWebhookEventDataSchema=z54.object({publication:z54.object({status:z54.literal("failed"),reason:z54.string()})}),PublishUnpublishedWebhookEventDataSchema=z54.object({publication:z54.object({previousUrl:z54.string(),unpublishedAt:z54.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z54.object({review:z54.object({id:z54.string(),runId:z54.string(),agentName:z54.string(),classification:z54.string(),summary:z54.string(),reasons:z54.array(z54.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z54.object({review:z54.object({id:z54.string(),runId:z54.string(),agentName:z54.string(),resolution:z54.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z54.object({report:z54.object({weekStart:z54.string(),weekEnd:z54.string(),pageviews:z54.number(),visitors:z54.number(),previousPageviews:z54.number(),previousVisitors:z54.number()})}),MediaAssetWebhookEventDataSchema=z54.object({id:z54.string().nullable(),name:z54.string().nullable(),type:z54.string(),mimeType:z54.string().nullable(),fileSize:z54.number().nullable()}),MediaUploadedWebhookEventDataSchema=z54.object({asset:MediaAssetWebhookEventDataSchema,operation:z54.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z54.object({asset:MediaAssetWebhookEventDataSchema,operation:z54.enum(["updated","moved","analysis"]),analysis:z54.object({category:z54.string(),status:z54.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z54.object({asset:MediaAssetWebhookEventDataSchema,operation:z54.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z54.object({asset:MediaAssetWebhookEventDataSchema,operation:z54.literal("generated"),generation:z54.object({model:z54.string(),mode:z54.string()})}),MediaProcessingFailedWebhookEventDataSchema=z54.object({asset:MediaAssetWebhookEventDataSchema,operation:z54.enum(["analysis","generation"]),failure:z54.object({code:z54.string()})}),DomainCreatedWebhookEventDataSchema=z54.object({domain:z54.object({id:z54.string(),hostname:z54.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z54.object({domain:z54.object({id:z54.string(),hostname:z54.string()})}),LabelChangedWebhookEventDataSchema=z54.object({changes:z54.array(z54.object({action:z54.enum(["created","updated","deleted"]),key:z54.string(),locale:z54.string(),value:z54.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z54.object({locale:z54.object({code:z54.string(),isDefault:z54.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z54.object({locale:z54.object({code:z54.string(),previousCode:z54.string()})}),LocaleDeletedWebhookEventDataSchema=z54.object({locale:z54.object({code:z54.string(),entriesDeleted:z54.number().int().nonnegative(),labelsDeleted:z54.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z54.object({environment:z54.object({name:EnvSchema,parent:EnvSchema})}),EnvironmentDeletedWebhookEventDataSchema=z54.object({environment:z54.object({name:EnvSchema})}),EnvironmentMergedWebhookEventDataSchema=z54.object({merge:z54.object({id:z54.string(),from:EnvSchema,to:EnvSchema,applied:z54.array(z54.object({surface:SurfaceNameSchema,count:z54.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z54.object({environment:z54.object({name:EnvSchema}),version:z54.object({versionId:z54.uuid(),name:z54.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=z54.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z54.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z54.discriminatedUnion("source",[z54.object({source:z54.literal("literal"),value:z54.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z54.object({source:z54.literal("secret"),key:z54.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z54.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z54.object({name:z54.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z54.object({name:z54.string(),source:z54.enum(["literal","secret"]),secretKey:z54.string().nullable(),secretPrefix:z54.string().nullable(),configured:z54.literal(!0)}),WebhookFilterSchema=z54.object({environment:WebhookEnvironmentScopeSchema.optional(),formId:z54.string().min(1).max(255).optional(),agentName:z54.string().min(1).max(120).optional(),mediaType:z54.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z54.string().min(1).max(255).optional(),locale:z54.string().min(1).max(120).optional()}),JsonValueSchema=z54.lazy(()=>z54.union([z54.string(),z54.number(),z54.boolean(),z54.null(),z54.array(JsonValueSchema),z54.record(z54.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z54.object({name:z54.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z54.url(),enabled:z54.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z54.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z54.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z54.object({name:z54.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z54.url().optional(),enabled:z54.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z54.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z54.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z54.object({eventType:WebhookEventTypeSchema.optional(),data:z54.record(z54.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z54.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z54.uuid(),name:z54.string(),eventType:WebhookEventTypeSchema,enabled:z54.boolean(),destination:z54.object({host:z54.string(),maskedUrl:z54.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z54.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z54.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z54.coerce.date().nullable(),deliveryStats24h:z54.object({succeeded:z54.number().int().nonnegative(),failed:z54.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z54.uuid(),projectId:z54.uuid(),env:EnvSchema,eventId:z54.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z54.number().int().positive(),test:z54.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z54.number().int().nonnegative(),responseStatus:z54.number().int().nullable(),lastErrorCode:z54.string().nullable(),lastErrorMessage:z54.string().nullable(),payloadAvailable:z54.boolean(),destination:z54.object({host:z54.string(),maskedUrl:z54.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z54.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z54.string().nullable(),qstashMessageId:z54.string().nullable(),deliveredAt:z54.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z54.object({items:z54.array(WebhookDeliveryDTOSchema),pagination:z54.object({page:z54.number().int().positive(),limit:z54.number().int().positive(),total:z54.number().int().nonnegative(),totalPages:z54.number().int().positive(),hasMore:z54.boolean()}),stats:z54.object({total:z54.number().int().nonnegative(),succeeded:z54.number().int().nonnegative(),failed:z54.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z54.object({id:z54.uuid(),deliveryId:z54.uuid(),attempt:z54.number().int().positive(),status:z54.enum(["delivering","succeeded","failed"]),responseStatus:z54.number().int().nullable(),durationMs:z54.number().int().nonnegative(),responseExcerpt:z54.string().nullable(),errorCode:z54.string().nullable(),errorMessage:z54.string().nullable(),createdAt:z54.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z54.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z54.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z55}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=z55.object({key:z55.enum(previewFeatureKeys),enabled:z55.boolean(),dismissed:z55.boolean().default(!1),interacted:z55.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema),PreviewFeatureResponseSchema=createResponseSchema(PreviewFeatureDTOSchema),PreviewFeatureListResponseSchema=createResponseSchema(z55.array(PreviewFeatureDTOSchema))}});import{z as z56}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=z56.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z56.object({total:z56.number(),base:z56.number(),purchases:z56.number(),awards:z56.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z56.object({id:z56.string(),name:z56.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z56.object({type:z56.string(),brand:z56.string().nullable(),last4:z56.string().nullable(),expirationDate:z56.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z56.object({currency:z56.string(),nextPaymentAmount:z56.number().nullable(),nextPaymentAt:z56.string().nullable(),billingInterval:z56.string().nullable(),totalAmount:z56.number().nullable(),discountAmount:z56.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z56.object({id:z56.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z56.string().nullable(),currentPeriodEndsAt:z56.string().nullable(),renewsAt:z56.string().nullable(),cancelAt:z56.string().nullable(),renewAutomatically:z56.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z56.object({type:z56.enum(["low_balance","critical_balance","approaching_limit"]),message:z56.string(),estimatedPromptsRemaining:z56.number().nullable(),avgCostPerPrompt:z56.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z56.object({monthlyCredits:z56.number().nullable(),usedThisPeriod:z56.number(),remainingThisPeriod:z56.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z56.object({organizationId:z56.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z56.string().nullable(),tenureDays:z56.number().int().nonnegative(),capturedAt:z56.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z56.object({hasSubscription:z56.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z56.number().nullable(),alerts:z56.array(CreditAlertDTOSchema),portalUrl:z56.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z56.object({creditCount:z56.number().int().positive(),expiresAt:z56.string().datetime().nullable().optional(),message:z56.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z56.literal("free"),amountCents:z56.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z56.literal("purchase"),amountCents:z56.number().int().positive()}),CreditTopupRequestDTOSchema=z56.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z56.object({success:z56.boolean(),transactionId:z56.string().nullable(),newBalance:z56.number(),creditCount:z56.number(),type:z56.enum(["free","purchase"]),invoiceId:z56.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z57}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=z57.object({totalCredits:z57.number(),totalCostUsd:z57.number(),totalMessages:z57.number(),avgCostPerMessage:z57.number(),periodStart:z57.string().nullable(),periodEnd:z57.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z57.object({projectId:z57.string(),projectName:z57.string(),projectDisplayName:z57.string().nullable(),credits:z57.number(),costUsd:z57.number(),messages:z57.number(),percentage:z57.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z57.object({userId:z57.string(),userName:z57.string().nullable(),userEmail:z57.string().email().nullable(),credits:z57.number(),costUsd:z57.number(),messages:z57.number(),percentage:z57.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z57.object({date:z57.string(),credits:z57.number(),costUsd:z57.number(),messages:z57.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z57.object({userId:z57.string(),userName:z57.string().nullable(),userEmail:z57.string().email().nullable(),credits:z57.number(),costUsd:z57.number(),messages:z57.number(),percentage:z57.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z57.object({projectId:z57.string(),projectName:z57.string(),projectDisplayName:z57.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z57.array(UsageByUserForProjectDTOSchema),timeline:z57.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z57.object({summary:UsageSummaryDTOSchema,byProject:z57.array(UsageByProjectDTOSchema),byUser:z57.array(UsageByUserDTOSchema),timeline:z57.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z58}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=z58.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z58.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z58.object({startDate:z58.string().optional(),endDate:z58.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z58.coerce.number().int().positive().default(1),limit:z58.coerce.number().int().positive().max(100).default(20),sortBy:z58.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z58.string().optional()}),UsageOverviewSummaryDTOSchema=z58.object({totalCredits:z58.number(),totalCostUsd:z58.number(),totalMessages:z58.number(),avgCostPerMessage:z58.number(),avgCreditsPerMessage:z58.number(),periodStart:z58.string(),periodEnd:z58.string(),creditsChange:z58.number().nullable(),costChange:z58.number().nullable(),messagesChange:z58.number().nullable()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z58.object({date:z58.string(),credits:z58.number(),costUsd:z58.number(),messages:z58.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z58.object({organizationId:z58.string(),organizationName:z58.string(),credits:z58.number(),costUsd:z58.number(),messages:z58.number(),percentage:z58.number(),userCount:z58.number(),projectCount:z58.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z58.object({userId:z58.string(),userName:z58.string().nullable(),userEmail:z58.string().nullable(),userImage:z58.string().nullable(),organizationId:z58.string().nullable(),organizationName:z58.string().nullable(),credits:z58.number(),costUsd:z58.number(),messages:z58.number(),percentage:z58.number(),projectCount:z58.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z58.object({projectId:z58.string(),projectName:z58.string(),projectDisplayName:z58.string().nullable(),organizationId:z58.string(),organizationName:z58.string(),credits:z58.number(),costUsd:z58.number(),messages:z58.number(),percentage:z58.number(),userCount:z58.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z58.object({id:z58.string(),name:z58.string(),value:z58.number(),percentage:z58.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z58.object({day:z58.number(),hour:z58.number(),value:z58.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z58.object({summary:UsageOverviewSummaryDTOSchema,timeline:z58.array(UsageTimelinePointDTOSchema),topOrganizations:z58.array(OrganizationUsageRowDTOSchema),topUsers:z58.array(UserUsageRowDTOSchema),topProjects:z58.array(ProjectUsageRowDTOSchema),creditDistribution:z58.array(UsageDistributionItemDTOSchema),heatmap:z58.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z58.object({page:z58.number(),limit:z58.number(),totalItems:z58.number(),totalPages:z58.number(),hasMore:z58.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z58.object({organizations:z58.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z58.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z58.object({users:z58.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z58.string(),ownerName:z58.string().nullable(),ownerEmail:z58.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z58.object({projects:z58.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z58.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z58.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z58.object({credits:z58.number(),costUsd:z58.number(),messages:z58.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z58.object({id:z58.string(),name:z58.string(),createdAt:z58.string(),memberCount:z58.number(),projectCount:z58.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z58.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z58.object({id:z58.string(),name:z58.string().nullable(),email:z58.string(),image:z58.string().nullable(),createdAt:z58.string(),organizationCount:z58.number(),projectCount:z58.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z58.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z58.object({id:z58.string(),name:z58.string(),displayName:z58.string().nullable(),createdAt:z58.string(),organizationId:z58.string(),organizationName:z58.string(),ownerId:z58.string(),ownerName:z58.string().nullable(),ownerEmail:z58.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z58.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z59}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=z59.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z59.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z59.object({command:z59.string().min(1).max(1e4),cwd:z59.string().optional(),projectEnv:EnvSchema.optional(),env:z59.record(z59.string(),z59.string()).optional(),name:z59.string().optional(),waitForCompletion:z59.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z59.object({identifier:z59.string(),status:SandboxProcessStatusSchema,command:z59.string().optional(),startedAt:z59.string().optional(),exitCode:z59.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z59.object({processes:z59.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z59.object({processId:z59.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z59.object({success:z59.boolean(),message:z59.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z60}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common();init_attachments();init_env();init_realtime();init_references();init_content_fields();init_audit_log();init_ops();init_project_dto();init_project_env_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_activation_dto();init_agent_list_item_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_audit_log_dto();init_env_status_dto();init_env_diff_summary_dto();init_project_analytics_dto();init_project_access_dto();init_project_invite_dto();init_publication_dto();init_sandbox_dto();init_organization_dto();init_billing_dto();init_payment_method_dto();init_user_dto();init_content_dto();init_unique_conflict_dto();init_schema_transition_rejected_dto();init_cms_display_defaults_dto();init_asset_dto();init_translation_dto();init_document_dto();init_chat_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_webhook_dto();init_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,readFile5=defaultReadFile){try{return JSON.parse(readFile5(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&&params.set("against",against);for(let[k,v]of Object.entries(extras))params.set(k,v);return params.toString()}function throwUnauthorized(cfg,status){try{recordAuthFailure(cfg)}catch{}throw new UnauthorizedError(cfg.apiUrl,status)}async function throwPermissionDenied(cfg,response){let required=[];try{let body=await response.json();required=Array.isArray(body.required)?body.required:body.required?[body.required]:[]}catch{}throw new PermissionDeniedError(cfg.apiUrl,required)}async function fimoFetch(url,init){let headers=new Headers(init.headers);headers.delete(CLI_VERSION_HEADER),headers.delete(CLI_AUTO_UPGRADE_HEADER);let canAutoUpgrade=process.argv[2]!=="git-credential"&&autoUpgradeEnabled();canAutoUpgrade&&(headers.set(CLI_VERSION_HEADER,getCliVersion()),headers.set(CLI_AUTO_UPGRADE_HEADER,"1"));let response=await fetch(url,{...init,headers});if(canAutoUpgrade&&response.status===426){let latest=response.headers.get(CLI_LATEST_HEADER);if(latest){await autoUpgradeGlobal(latest)||ui.warn({command:process.argv[2]??"fimo",message:`Could not upgrade to ${latest}; continuing with the current command.`});let retryHeaders=new Headers(init.headers);return retryHeaders.delete(CLI_VERSION_HEADER),retryHeaders.delete(CLI_AUTO_UPGRADE_HEADER),fetch(url,{...init,headers:retryHeaders})}}return response}function formatZodIssues(parsed){if(!parsed||typeof parsed!="object")return null;let error=parsed.error,issues=error&&typeof error=="object"&&"issues"in error?error.issues:void 0;return!Array.isArray(issues)||issues.length===0?null:issues.map(issue=>{let{path:path47,message}=issue;return`${Array.isArray(path47)&&path47.length>0?`${path47.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}var ApiRequestError,UnauthorizedError,PermissionDeniedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_ENV_HEADER,FimoApiClient,init_api=__esm({"src/cli/api.ts"(){init_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,path47,status,detail,code2,body){super(`API ${method} ${path47} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path47,this.status=status,this.detail=detail,this.code=code2,this.body=body}},UnauthorizedError=class extends Error{static{__name(this,"UnauthorizedError")}apiUrl;status;constructor(apiUrl,status,message){super(message??`Session for ${apiUrl} expired or invalid (HTTP ${status}).`),this.name="UnauthorizedError",this.apiUrl=apiUrl,this.status=status}},PermissionDeniedError=class extends Error{static{__name(this,"PermissionDeniedError")}apiUrl;required;constructor(apiUrl,required=[],message){let detail=required.length?` Missing permission: ${required.join(", ")}.`:"";super(message??`You don't have permission to do this on ${apiUrl}.${detail}`),this.name="PermissionDeniedError",this.apiUrl=apiUrl,this.required=required}};__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");CLI_VERSION_HEADER="X-Fimo-CLI-Version",CLI_LATEST_HEADER="X-Fimo-CLI-Latest",CLI_AUTO_UPGRADE_HEADER="X-Fimo-CLI-Auto-Upgrade",FIMO_ENV_HEADER="X-Fimo-Env";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");FimoApiClient=class _FimoApiClient{constructor(cfg=loadConfig()){this.cfg=cfg}static{__name(this,"FimoApiClient")}env;withEnv(env){let next2=new _FimoApiClient(this.cfg);return next2.env=env,next2}formatError(status,text3,body){if(!text3)return String(status);if(body&&typeof body=="object"&&!Array.isArray(body)){let parsed=body;if(typeof parsed.message=="string"&&parsed.message.length>0){let partial=formatPartialResult(parsed);return partial?`${parsed.message} ${partial}`:parsed.message}if(typeof parsed.error=="string"&&parsed.error.length>0)return parsed.error;if(parsed.error&&typeof parsed.error=="object"&&"message"in parsed.error&&typeof parsed.error.message=="string")return parsed.error.message;let zodIssues=formatZodIssues(parsed);if(zodIssues)return zodIssues}return text3}async parseError(response){let text3=await response.text(),body;try{body=text3?JSON.parse(text3):void 0}catch{return{detail:this.formatError(response.status,text3)}}let code2=body&&typeof body=="object"&&!Array.isArray(body)&&typeof body.code=="string"?body.code:void 0;return{detail:this.formatError(response.status,text3,body),code:code2,body}}resolveAuthToken(){return process.env.FIMO_API_TOKEN?.trim()||requireToken(this.cfg)}async request(path47,init={},opts={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path47}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&!opts.allow403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new ApiRequestError(init.method??"GET",path47,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async rawRequest(path47,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path47}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new Error(`API ${init.method??"GET"} ${path47} failed: ${response.status} ${error.detail}`)}return response}tenantPath(projectId,route){if(!this.env)throw new Error("FimoApiClient: tenant-scoped call requires an env. Use `client.withEnv(env)` before calling tenant CRUD methods.");return`/api/tenant/${projectId}/envs/${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&&params.set("modality",query.modality);for(let t2 of query.tag??[])params.append("tag",t2);query.q&&params.set("q",query.q),query.category&&params.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&&params.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&&params.set("limit",String(query.limit)),query.cursor&&params.set("cursor",query.cursor),query.status&&params.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&&params.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&&params.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&&params.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&&params.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/status${qs?`?${qs}`:""}`)).data}async getCodeFileDiff(projectId,env,path47,opts={}){let qs=lazyFetchQs(opts.against,{path:path47});return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/code/file?${qs}`)).data}async getCodeConflictDetail(projectId,env,fromEnv,filePath){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflict/code?path=${encodeURIComponent(filePath)}`)).data}async getContentRowDiff(projectId,env,collection,rowId,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getSchemaTypeDiff(projectId,env,typeName,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getAssetDiff(projectId,env,assetId,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getTranslationRowDiff(projectId,env,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getFormSchemaDiff(projectId,env,formName,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getActivationDiff(projectId,env,agentName,triggerIndex,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/activations/${encodeURIComponent(agentName)}/${triggerIndex}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async mergeEnv(projectId,env,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge`,{method:"POST",body:JSON.stringify(body)})).data}async resolveMerge(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve`,{method:"POST",body:JSON.stringify(body)})).data}async cancelMerge(projectId,env,mergeId){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/cancel`,{method:"POST",body:JSON.stringify({mergeId})})).data}async getMergeConflicts(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflicts`)).data}async putResolveDraft(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"PUT",body:JSON.stringify(body)})).data}async deleteResolveDraft(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"DELETE"})).data}async publishRelease(projectId,body){return(await this.request(`/api/management/projects/${projectId}/releases`,{method:"POST",body:JSON.stringify(body)})).data}async activateAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/activations`,{method:"POST",body:JSON.stringify(body)})).data}async deactivateAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/activations`,{method:"DELETE",body:JSON.stringify(body)})).data}async runAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/run`,{method:"POST",body:JSON.stringify(body)})).data}async listAgentSessions(projectId,opts={}){let params=new URLSearchParams;opts.agentName&&params.set("agent_name",opts.agentName),opts.env&&params.set("env",opts.env),opts.status&&params.set("status",opts.status),opts.limit!==void 0&&params.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
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fimo",
3
- "version": "0.10.1-staging.2",
3
+ "version": "0.10.1-staging.4",
4
4
  "description": "Fimo CLI - create, deploy, and manage Fimo projects",
5
5
  "bin": {
6
6
  "fimo": "dist/cli/index.js"
@@ -21,7 +21,7 @@
21
21
  "cmdk": "^1.1.1",
22
22
  "date-fns": "^4.1.0",
23
23
  "embla-carousel-react": "^8.6.0",
24
- "fimo": "0.10.1-staging.2",
24
+ "fimo": "0.10.1-staging.4",
25
25
  "input-otp": "^1.4.2",
26
26
  "isbot": "^5",
27
27
  "lucide-react": "^0.577.0",