fimo 2.8.0-staging.15 → 2.8.0-staging.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/skills/fimo-cli/SKILL.md +2 -0
- package/assets/skills/fimo-studio/references/ai-chat.md +1 -1
- package/dist/cli/bundle.json +1 -1
- package/dist/cli/index.js +17 -15
- package/package.json +8 -8
- package/templates/astro/package.json +3 -3
- package/templates/nextjs/package.json +4 -4
- package/templates/react-router/package.json +5 -5
- package/templates/sveltekit/package.json +3 -3
- package/templates/vite/package.json +5 -5
package/dist/cli/index.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { createRequire as __fimoCreateRequire } from 'node:module';
|
|
3
3
|
const require = __fimoCreateRequire(import.meta.url);
|
|
4
4
|
var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropDesc=Object.getOwnPropertyDescriptor;var __getOwnPropNames=Object.getOwnPropertyNames;var __getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty;var __name=(target,value)=>__defProp(target,"name",{value,configurable:!0}),__require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(a,b)=>(typeof require<"u"?require:a)[b]}):x)(function(x){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var __esm=(fn,res)=>function(){return fn&&(res=(0,fn[__getOwnPropNames(fn)[0]])(fn=0)),res};var __commonJS=(cb,mod)=>function(){return mod||(0,cb[__getOwnPropNames(cb)[0]])((mod={exports:{}}).exports,mod),mod.exports};var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to};var __toESM=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod);import{z}from"zod";function filterUnknownProperties(data,schema){if(data==null)return data;if(schema instanceof z.ZodOptional||schema instanceof z.ZodNullable||schema instanceof z.ZodDefault)return filterUnknownProperties(data,schema.unwrap());if(schema instanceof z.ZodArray){if(!Array.isArray(data))return data;let itemSchema=schema.unwrap();return data.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z.ZodDiscriminatedUnion){if(typeof data!="object"||data===null)return data;let unionSchema=schema,discriminator=unionSchema.def.discriminator,discriminatorValue=data[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(data,matchingSchema):data}if(schema instanceof z.ZodObject){if(typeof data!="object")return data;let shape=schema.shape,result={};for(let key in shape)if(Object.prototype.hasOwnProperty.call(data,key)){let fieldSchema=shape[key],fieldValue2=data[key];result[key]=filterUnknownProperties(fieldValue2,fieldSchema)}if(schema.def.catchall instanceof z.ZodUnknown)for(let[key,value]of Object.entries(data))key in shape||(result[key]=value);return result}return data}function createObjectDTO(schema){return{schema,from(data){let filtered=filterUnknownProperties(data,schema);return schema.parse(filtered)},fromList(data){return data.map(item=>this.from(item))},safeParse(data){let filtered=filterUnknownProperties(data,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(data){let filtered=filterUnknownProperties(data,schema);return schema.parse(filtered)},fromList(data){return data.map(item=>this.from(item))},safeParse(data){let filtered=filterUnknownProperties(data,schema);return schema.safeParse(filtered)}}}function createDTO(schema){if(schema instanceof z.ZodObject)return createObjectDTO(schema);if(schema instanceof z.ZodDiscriminatedUnion)return createDiscriminatedUnionDTO(schema);throw new Error(`Unsupported schema type: ${schema.constructor.name}. createDTO supports ZodObject and ZodDiscriminatedUnion.`)}var init_create_dto=__esm({"../../packages/api-contracts/dist/esm/utils/create-dto.js"(){"use strict";__name(filterUnknownProperties,"filterUnknownProperties");__name(createObjectDTO,"createObjectDTO");__name(createDiscriminatedUnionDTO,"createDiscriminatedUnionDTO");__name(createDTO,"createDTO")}});import{z as z2}from"zod";function createCursorPageDataSchema(dataSchema){return z2.object({items:z2.array(dataSchema),nextCursor:z2.string().nullable()})}function createCursorPaginatedResponseSchema(dataSchema){return z2.object({data:createCursorPageDataSchema(dataSchema)})}var createResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema=__name(dataSchema=>z2.object({data:dataSchema}),"createResponseSchema");__name(createCursorPageDataSchema,"createCursorPageDataSchema");__name(createCursorPaginatedResponseSchema,"createCursorPaginatedResponseSchema")}});import{z as z3}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z3.object({page:z3.coerce.number().int().positive().default(1),limit:z3.coerce.number().int().positive().max(100).default(20)})}});import{z as z4}from"zod";var CommonSchemas,BaseEntitySchema,ProjectRoleKeySchema,ProjectRoleKeyWithSystemSchema,ProjectPrincipalTypeSchema,ProjectStatusSchema,ProjectInviteStatusSchema,PublicationStatusSchema,OrganizationRoleSchema,AssetTypeSchema,TemplateCodeSchema,FieldTypeSchema,CONTENT_INTERNAL_FIELD_NAMES,contentInternalFieldNames,RESERVED_CONTENT_FIELD_NAMES,contentReviewHiddenFieldNames,CONTENT_TYPE_NAME_PATTERN,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION,CONTENT_FIELD_NAME_PATTERN,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION,init_common=__esm({"../../packages/api-contracts/dist/esm/types/common.js"(){"use strict";CommonSchemas={timestamp:z4.coerce.date(),positiveInt:z4.number().int().positive(),nonNegativeInt:z4.number().int().nonnegative()},BaseEntitySchema=z4.object({id:z4.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z4.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z4.enum(["full","edit","comment","view","agent","schedule"]),ProjectPrincipalTypeSchema=z4.enum(["user","org","orgRole","public","email"]),ProjectStatusSchema=z4.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z4.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z4.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z4.enum(["owner","admin","member"]),AssetTypeSchema=z4.enum(["file","folder"]),TemplateCodeSchema=z4.enum(["Free","PAYG","Premium","Pro"]),FieldTypeSchema=z4.enum(["string","text","richtext","media","number","boolean","date","datetime","json","reference","blocks"]),CONTENT_INTERNAL_FIELD_NAMES=["id","entryId","documentId","locale","__fimo"],contentInternalFieldNames=new Set(CONTENT_INTERNAL_FIELD_NAMES),RESERVED_CONTENT_FIELD_NAMES=[...CONTENT_INTERNAL_FIELD_NAMES,"slug","createdAt","updatedAt"],contentReviewHiddenFieldNames=new Set(RESERVED_CONTENT_FIELD_NAMES),CONTENT_TYPE_NAME_PATTERN=/^[A-Za-z]\w*$/,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter",CONTENT_FIELD_NAME_PATTERN=/^[A-Za-z_]\w*$/,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter or underscore"}});import{z as z5}from"zod";var MB,MAX_UPLOAD_FILE_SIZE_BYTES,MAX_DOCUMENT_SIZE_BYTES,MAX_AUDIO_SIZE_BYTES,MAX_IMAGE_SIZE_BYTES,MAX_VIDEO_SIZE_BYTES,MAX_ARCHIVE_SIZE_BYTES,MAX_MODEL_SIZE_BYTES,MAX_ATTACHMENT_MESSAGE_SIZE_BYTES,MODEL_MEDIA_TYPE,AttachmentModelMediaTypeSchema,MODEL_MIME_TYPES,MODEL_RENDER_VIEW_ANGLES,AttachmentModelRenderRequestSchema,AttachmentModelRenderSuccessSchema,AttachmentModelRenderFailureSchema,AttachmentModelRenderResponseSchema,AttachmentModelRenderMeterSchema,ATTACHMENT_TYPES,ATTACHMENT_MIME_TYPES,ATTACHMENT_IMAGE_MIME_TYPES,ATTACHMENT_DOCUMENT_MIME_TYPES,ATTACHMENT_ARCHIVE_MIME_TYPES,ATTACHMENT_AUDIO_MIME_TYPES,ATTACHMENT_VIDEO_MIME_TYPES,ATTACHMENT_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,EXTENSION_MIME_TYPES,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";MB=1024*1024,MAX_UPLOAD_FILE_SIZE_BYTES=50*MB,MAX_DOCUMENT_SIZE_BYTES=5*MB,MAX_AUDIO_SIZE_BYTES=10*MB,MAX_IMAGE_SIZE_BYTES=20*MB,MAX_VIDEO_SIZE_BYTES=20*MB,MAX_ARCHIVE_SIZE_BYTES=20*MB,MAX_MODEL_SIZE_BYTES=20*MB,MAX_ATTACHMENT_MESSAGE_SIZE_BYTES=20*MB,MODEL_MEDIA_TYPE={GLB:"model/gltf-binary",GLTF:"model/gltf+json",FBX:"model/fbx",OBJ:"model/obj",STL:"model/stl",PLY:"model/ply"},AttachmentModelMediaTypeSchema=z5.enum(MODEL_MEDIA_TYPE),MODEL_MIME_TYPES=Object.values(MODEL_MEDIA_TYPE),MODEL_RENDER_VIEW_ANGLES=[35,125,215,305],AttachmentModelRenderRequestSchema=z5.object({renderId:z5.uuid(),filename:z5.string().min(1).max(255),mediaType:AttachmentModelMediaTypeSchema,modelUrl:z5.url()}),AttachmentModelRenderSuccessSchema=z5.object({status:z5.literal("succeeded"),views:z5.tuple([z5.object({angle:z5.literal(MODEL_RENDER_VIEW_ANGLES[0]),screenshotUrl:z5.url()}),z5.object({angle:z5.literal(MODEL_RENDER_VIEW_ANGLES[1]),screenshotUrl:z5.url()}),z5.object({angle:z5.literal(MODEL_RENDER_VIEW_ANGLES[2]),screenshotUrl:z5.url()}),z5.object({angle:z5.literal(MODEL_RENDER_VIEW_ANGLES[3]),screenshotUrl:z5.url()})]),elapsedMs:z5.number().nonnegative(),browserElapsedMs:z5.number().nonnegative(),diagnostics:z5.unknown().optional()}),AttachmentModelRenderFailureSchema=z5.object({status:z5.literal("failed"),error:z5.literal("render_failed"),message:z5.string(),elapsedMs:z5.number().nonnegative(),browserElapsedMs:z5.number().nonnegative()}),AttachmentModelRenderResponseSchema=z5.discriminatedUnion("status",[AttachmentModelRenderSuccessSchema,AttachmentModelRenderFailureSchema]),AttachmentModelRenderMeterSchema=z5.object({browserElapsedMs:z5.number().nonnegative()}),ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"image/webp",extensions:[".webp"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"image/avif",extensions:[".avif"],category:"image",maxSizeBytes:MAX_IMAGE_SIZE_BYTES},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/msword",extensions:[".doc"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",extensions:[".docx"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.ms-excel",extensions:[".xls"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",extensions:[".xlsx"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.ms-powerpoint",extensions:[".ppt"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation",extensions:[".pptx"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/epub+zip",extensions:[".epub"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.oasis.opendocument.text",extensions:[".odt"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.oasis.opendocument.spreadsheet",extensions:[".ods"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/vnd.oasis.opendocument.presentation",extensions:[".odp"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/rtf",extensions:[],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/rtf",extensions:[".rtf"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/html",extensions:[".html",".htm"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/markdown",extensions:[".md",".markdown"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/json",extensions:[".json"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:MAX_DOCUMENT_SIZE_BYTES},{mime:"application/zip",extensions:[".zip"],category:"archive",maxSizeBytes:MAX_ARCHIVE_SIZE_BYTES},{mime:"audio/mpeg",extensions:[".mp3"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/wav",extensions:[".wav"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/aiff",extensions:[".aiff",".aif"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/aac",extensions:[".aac"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/ogg",extensions:[".ogg"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"audio/flac",extensions:[".flac"],category:"audio",maxSizeBytes:MAX_AUDIO_SIZE_BYTES},{mime:"video/mp4",extensions:[".mp4"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/mpeg",extensions:[".mpeg",".mpg"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/mpg",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/quicktime",extensions:[".mov"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/mov",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/avi",extensions:[".avi"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/vnd.avi",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-msvideo",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-flv",extensions:[".flv"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/webm",extensions:[".webm"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/wmv",extensions:[".wmv"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-ms-wmv",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/x-ms-asf",extensions:[],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:"video/3gpp",extensions:[".3gp"],category:"video",maxSizeBytes:MAX_VIDEO_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.GLB,extensions:[".glb"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.GLTF,extensions:[".gltf"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.FBX,extensions:[".fbx"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.OBJ,extensions:[".obj"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.STL,extensions:[".stl"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES},{mime:MODEL_MEDIA_TYPE.PLY,extensions:[".ply"],category:"model",maxSizeBytes:MAX_MODEL_SIZE_BYTES}],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_ARCHIVE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="archive").map(t2=>t2.mime),ATTACHMENT_AUDIO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="audio").map(t2=>t2.mime),ATTACHMENT_VIDEO_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="video").map(t2=>t2.mime),ATTACHMENT_ACCEPT_EXTENSIONS=ATTACHMENT_TYPES.flatMap(t2=>t2.extensions),ATTACHMENT_ACCEPT_STRING=[...ATTACHMENT_ACCEPT_EXTENSIONS,...ATTACHMENT_MIME_TYPES].join(","),ATTACHMENT_DROPZONE_ACCEPT=Object.fromEntries(ATTACHMENT_TYPES.map(t2=>[t2.mime,t2.extensions])),EXTENSION_MIME_TYPES=Object.fromEntries(ATTACHMENT_TYPES.flatMap(t2=>t2.extensions.map(extension=>[extension,t2.mime])))}});import{z as z6}from"zod";var AssetReadRequestSchema,AssetDerivedFileSchema,AssetReadBaseSchema,AssetReadPageSchema,AssetReadQuerySchema,AssetReadResultSchema,init_asset_reading=__esm({"../../packages/api-contracts/dist/esm/types/asset-reading.js"(){"use strict";AssetReadRequestSchema=z6.object({cursor:z6.string().optional(),query:z6.string().trim().min(1).max(500).optional()}).strict().refine(input=>input.cursor===void 0||input.query===void 0,{message:"Use either cursor or query, not both."}),AssetDerivedFileSchema=z6.object({url:z6.url(),mediaType:z6.string(),filename:z6.string()}),AssetReadBaseSchema=z6.object({assetId:z6.uuid(),filename:z6.string(),mediaType:z6.string(),representation:z6.enum(["text","table","document","archive","image","transcript","video","model"]),content:z6.string(),derivedFiles:z6.array(AssetDerivedFileSchema).optional()}),AssetReadPageSchema=AssetReadBaseSchema.extend({mode:z6.literal("page"),start:z6.number().int().nonnegative(),end:z6.number().int().nonnegative(),total:z6.number().int().nonnegative(),nextCursor:z6.string().nullable(),complete:z6.boolean()}),AssetReadQuerySchema=AssetReadBaseSchema.extend({mode:z6.literal("query"),query:z6.string(),source:z6.enum(["original-file","canonical-text","derived-files"]),truncated:z6.boolean()}),AssetReadResultSchema=z6.discriminatedUnion("mode",[AssetReadPageSchema,AssetReadQuerySchema])}});import{z as z7}from"zod";function isValidBranch(branch){return typeof branch!="string"||branch.length===0||branch.length>MAX_BRANCH_LENGTH||branch.startsWith("-")||branch.startsWith(".")||branch.includes("//")||branch.includes("--")||branch.split("/").some(segment=>segment==="..")?!1:BRANCH_ID_REGEX.test(branch)}function encodeBranchPathSegment(branch){return branch.replace(/\//g,"--")}function isProductionBranch(branch){return branch===PRODUCTION_BRANCH}function fnv1a8(s){let h=2166136261;for(let i=0;i<s.length;i++)h^=s.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}function branchResourceKey(branch){let base=branch.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a8(branch);return base?`${base}-${hash}`:hash}function buildTenantApiUrl(projectId,branch,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${branchResourceKey(branch)}.${url.hostname}`,url.toString().replace(/\/$/,"")}var FIMO_CONTENT_API_ENV_KEYS,FIMO_ANALYTICS_ENV_KEYS,FIMO_PREVIEW_SCRIPT_ENV_KEYS,FIMO_MANAGED_PROJECT_ENV_KEYS,BRANCH_ID_REGEX,MAX_BRANCH_LENGTH,BranchSchema,DEFAULT_BRANCH,PRODUCTION_BRANCH,envResourceKey,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";FIMO_CONTENT_API_ENV_KEYS=["FIMO_CONTENT_API_URL","VITE_API_URL","NEXT_PUBLIC_FIMO_API_URL","NUXT_PUBLIC_FIMO_API_URL","PUBLIC_FIMO_API_URL"],FIMO_ANALYTICS_ENV_KEYS=["VITE_ENABLE_ANALYTICS","NEXT_PUBLIC_FIMO_ENABLE_ANALYTICS","NUXT_PUBLIC_FIMO_ENABLE_ANALYTICS","PUBLIC_FIMO_ENABLE_ANALYTICS"],FIMO_PREVIEW_SCRIPT_ENV_KEYS=["VITE_PREVIEW_SCRIPT_URL","VITE_FIMO_PREVIEW_SCRIPT_URL","NEXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","NUXT_PUBLIC_FIMO_PREVIEW_SCRIPT_URL","PUBLIC_FIMO_PREVIEW_SCRIPT_URL","FIMO_PREVIEW_SCRIPT_URL"],FIMO_MANAGED_PROJECT_ENV_KEYS=["FIMO_API_URL","FIMO_API_TOKEN","FIMO_PROJECT_ID","FIMO_ENV","NEXT_PUBLIC_FIMO_ENV","FIMO_AGENT_SESSION","FIMO_DATA_SOURCES",...FIMO_CONTENT_API_ENV_KEYS,...FIMO_PREVIEW_SCRIPT_ENV_KEYS,...FIMO_ANALYTICS_ENV_KEYS,"VITE_FIMO_BRANCH","VITE_FIMO_IMAGE_HOSTS"],BRANCH_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_BRANCH_LENGTH=255;__name(isValidBranch,"isValidBranch");__name(encodeBranchPathSegment,"encodeBranchPathSegment");BranchSchema=z7.string().min(1,"env must not be empty").max(MAX_BRANCH_LENGTH,`env must be at most ${MAX_BRANCH_LENGTH} characters`).refine(isValidBranch,{error:"env must match /^[a-zA-Z0-9._/-]+$/ and must not start with `-`"}),DEFAULT_BRANCH="main",PRODUCTION_BRANCH="prod";__name(isProductionBranch,"isProductionBranch");__name(fnv1a8,"fnv1a8");__name(branchResourceKey,"branchResourceKey");__name(buildTenantApiUrl,"buildTenantApiUrl");envResourceKey=branchResourceKey}});import{z as z8}from"zod";var PRODUCTION_ENVIRONMENT_KEY,PREVIEW_ENVIRONMENT_KEY,EnvironmentKeySchema,CustomEnvironmentSchema,ResolvedEnvironmentSchema,init_environment=__esm({"../../packages/api-contracts/dist/esm/types/environment.js"(){"use strict";init_env();PRODUCTION_ENVIRONMENT_KEY="production",PREVIEW_ENVIRONMENT_KEY="preview",EnvironmentKeySchema=z8.union([z8.literal(PRODUCTION_ENVIRONMENT_KEY),z8.literal(PREVIEW_ENVIRONMENT_KEY),z8.uuid()]),CustomEnvironmentSchema=z8.object({id:z8.uuid(),projectId:z8.uuid(),name:z8.string().trim().min(1).max(64),branchPatterns:z8.array(z8.string().min(1).max(255)).min(1),description:z8.string().max(255).nullable()}),ResolvedEnvironmentSchema=z8.object({branch:BranchSchema,environment:EnvironmentKeySchema})}});var init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict";init_env()}});var init_realtime_room=__esm({"../../packages/api-contracts/dist/esm/types/realtime-room.js"(){"use strict";init_env()}});import{z as z9}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=z9.preprocess(referenceValuePreprocess,z9.object({documentId:z9.uuid()})),ReferenceInputValueSchema=z9.preprocess(referenceValuePreprocess,z9.union([z9.object({documentId:z9.uuid()}),z9.object({slug:z9.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=z9.preprocess(polymorphicReferenceValuePreprocess,z9.object({contentType:z9.string().min(1),documentId:z9.uuid()})),PolymorphicReferenceInputValueSchema=z9.preprocess(polymorphicReferenceValuePreprocess,z9.union([z9.object({contentType:z9.string().min(1),documentId:z9.uuid()}),z9.object({contentType:z9.string().min(1),slug:z9.string().min(1)})]))}});import{z as z10}from"zod";function isDatetimeInstant(value){return typeof value=="string"&&DATETIME_INSTANT_PATTERN.test(value)&&!Number.isNaN(Date.parse(value))}function rejectLegacyLocaleSettings(field,ctx){"localized"in field&&ctx.addIssue({code:"custom",path:["localized"],message:'Field-level locale settings use "i18n".'})}function rejectFieldI18n(field,ctx){"i18n"in field&&ctx.addIssue({code:"custom",path:["i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}function refineConditions(field,ctx){if(field.showIf!==void 0&&field.showIfAny!==void 0&&ctx.addIssue({code:"custom",path:["showIfAny"],message:'A field declares "showIf" or "showIfAny", never both.'}),Array.isArray(field.showIf)){let fields=field.showIf.map(clause=>clause.field);new Set(fields).size!==fields.length&&ctx.addIssue({code:"custom",path:["showIf"],message:'"showIf" clauses must each name a different field. Use "in" for several values of one field.'})}}function rejectUnsupportedUnique(field,ctx,type){"unique"in field&&!uniqueFieldTypes.has(type)&&ctx.addIssue({code:"custom",path:["unique"],message:UNSUPPORTED_UNIQUE_MESSAGE})}function getConditionDefinition(field){if(field.showIfAny!==void 0)return{key:"showIfAny",clauses:field.showIfAny};if(field.showIf!==void 0)return{key:"showIf",clauses:Array.isArray(field.showIf)?field.showIf:[field.showIf]}}function getConditionValues(clause){return"equals"in clause?[clause.equals]:clause.in}function collectClauseProblems(fieldName,condition,clause,fields,path49){let conditionPath=[...path49,fieldName,condition.key],trigger=fields[clause.field];if(trigger===void 0)return[{path:conditionPath,message:`"${condition.key}" references unknown field "${clause.field}".`}];if(trigger.showIf!==void 0||trigger.showIfAny!==void 0)return[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is conditional too. Conditions are one level deep.`}];if(trigger.type!=="boolean"&&trigger.type!=="number"&&trigger.type!=="string")return[{path:conditionPath,message:`"${condition.key}" can only reference boolean, number, and string fields. "${clause.field}" is a ${trigger.type} field.`}];let triggerOptions=trigger.type==="string"?trigger.options:void 0;if(trigger.type==="string"&&triggerOptions===void 0)return[{path:conditionPath,message:`"${condition.key}" can only reference a string field that declares "options". Add options to "${clause.field}".`}];let values=getConditionValues(clause);if(values.some(value=>typeof value!==trigger.type))return[{path:conditionPath,message:`"${condition.key}" on "${clause.field}" expects a ${trigger.type} value.`}];if(triggerOptions!==void 0){let invalidValues=values.filter(value=>!triggerOptions.includes(value));if(invalidValues.length>0)return invalidValues.map(value=>({path:conditionPath,message:`"${value}" is not one of the options declared by "${clause.field}".`}))}return trigger.editable===!1?[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is not editable.`}]:[]}function collectConditionProblems(fields){let problems=[],walk=__name((currentFields,path49)=>{for(let[fieldName,field]of Object.entries(currentFields)){let condition=getConditionDefinition(field);if(condition!==void 0)for(let clause of condition.clauses)problems.push(...collectClauseProblems(fieldName,condition,clause,currentFields,path49));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path49,fieldName,variant.uid]);else walk(field.schema.fields,[...path49,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path49,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path49,fieldName];visit2({field,path:fieldPath,structuredDepth,insideStructuredContent});let nextDepth=structuredDepth+1;if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...fieldPath,variant.uid],nextDepth,!0);else walk(field.schema.fields,fieldPath,nextDepth,!0)}},"walk");walk(fields,[],0,!1)}var UNIQUE_FIELD_TYPES,DATETIME_INSTANT_PATTERN,DATETIME_INSTANT_MESSAGE,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"],DATETIME_INSTANT_PATTERN=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:\d{2})$/,DATETIME_INSTANT_MESSAGE="A datetime must be an ISO 8601 instant with a UTC offset, such as 2026-08-13T09:30:00Z.";__name(isDatetimeInstant,"isDatetimeInstant");utf8=new TextEncoder,MAX_STRUCTURED_CONTENT_DEPTH=7,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],showIfClauseSchema=z10.union([z10.object({field:z10.string().min(1),equals:z10.union([z10.string(),z10.number(),z10.boolean()])}).strict(),z10.object({field:z10.string().min(1),in:z10.array(z10.union([z10.string(),z10.number(),z10.boolean()])).min(1)}).strict()]),commonFieldShape={label:z10.string().min(1).optional(),description:z10.string().optional(),group:z10.union([z10.string().min(1),z10.array(z10.string().min(1)).min(1)]).optional(),editable:z10.boolean().optional(),required:z10.boolean().optional(),default:z10.unknown().optional(),showIf:z10.union([showIfClauseSchema,z10.array(showIfClauseSchema).min(1)]).optional(),showIfAny:z10.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=z10.object({...commonFieldShape,type:z10.enum(["string","text","richtext","media","number","boolean","date","datetime","json"]),min:z10.number().optional(),max:z10.number().optional(),minLength:z10.number().int().nonnegative().optional(),maxLength:z10.number().int().nonnegative().optional(),regex:z10.string().optional(),multiple:z10.boolean().optional(),allowedMimeTypes:z10.array(z10.string()).optional(),options:z10.array(z10.string().min(1)).min(1).optional(),unique:z10.boolean().optional(),i18n:z10.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==="datetime"&&field.default!==void 0&&!isDatetimeInstant(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:DATETIME_INSTANT_MESSAGE}),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=z10.object({...commonFieldShape,type:z10.literal("reference"),target:z10.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z10.array(z10.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z10.boolean().optional(),i18n:z10.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=z10.lazy(()=>contentFieldDefinitionSchema);__name(getConditionDefinition,"getConditionDefinition");__name(getConditionValues,"getConditionValues");__name(collectClauseProblems,"collectClauseProblems");__name(collectConditionProblems,"collectConditionProblems");blockFieldsSchema=z10.record(z10.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=z10.object({uid:z10.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z10.string().min(1),description:z10.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z10.object({fields:blockFieldsSchema}).strict(),blocksSchema=z10.object({oneOf:z10.array(blockVariantSchema).min(1).max(MAX_BLOCK_VARIANTS)}).strict().superRefine((schema,ctx)=>{let seen=new Set;for(let[index,variant]of schema.oneOf.entries())seen.has(variant.uid)&&ctx.addIssue({code:"custom",path:["oneOf",index,"uid"],message:"Variant UIDs must be unique."}),seen.add(variant.uid)}),blocksFieldSchema=z10.object({...commonFieldShape,type:z10.literal("blocks"),min:z10.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z10.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z10.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=z10.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z11}from"zod";var AUDIT_ACTIONS,AuditActionSchema,AUDIT_OUTCOMES,AuditOutcomeSchema,AUDIT_ACTOR_KINDS,AuditActorKindSchema,init_audit_log=__esm({"../../packages/api-contracts/dist/esm/types/audit-log.js"(){"use strict";AUDIT_ACTIONS=["env_create","env_delete","env_sync","capability_check","shell_exec","git_push","git_tag","git_merge","fimo_deploy","merge_decision","session_start","session_end","cost_breach","trigger_fire","schedule_notification_change","notification_preference_change","cutover_step","agent_delegate","version_restore","project_transfer","project_takedown","project_takedown_lift","organization_takedown","organization_takedown_lift","site_onboarding_refusal_lift","ops_access_change","ops_service_token_change","ops_project_search","ops_project_inspect","ops_project_chat_read","ops_recent_chat_read","ops_sentry_issue_change","ops_sentry_read","ops_logs_read","ops_trace_read","ops_posthog_milestones_read","ops_agent_trace_list","ops_agent_trace_read","ops_agent_trace_stats","ops_agent_health_read","ops_data_usage_read","ops_agent_provider_errors_read","ops_chat_history_health_read","ops_chat_history_calls_read","ops_chat_history_content_read","ops_chat_history_judge_calibration","ops_project_snapshot","ops_project_file_read","ops_project_file_write","ops_support_thread_read","ops_support_report_read","ops_support_intake_read","ops_pylon_queue_read","ops_support_report_change","ops_billing_read","ops_billing_agent_runtime_activate","ops_billing_entitlements_sync","ops_billing_cache_invalidate","ops_billing_dispatch_discard","ops_billing_legacy_premium_enroll","ops_organization_feature_set","ops_billing_plan_transition_notices","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send","ops_project_operation","ops_project_publish","ops_agent_branch_discard","admin_resource_read","merge_force"],AuditActionSchema=z11.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z11.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z11.enum(AUDIT_ACTOR_KINDS)}});import{z as z12}from"zod";function refineChatHistoryWindow(schema){return schema.refine(input=>input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>input.until.getTime()-input.since.getTime()<=OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,{path:["since"],message:"chat history windows cannot exceed 7 days"})}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,OpsPylonIssueIdSchema,OpsPylonReasonSchema,OpsPylonMessageSchema,OpsPylonMessageIdSchema,OpsPylonEmailListSchema,OpsPylonResolveInputSchema,OpsPylonNoteInputSchema,OpsPylonReplyPreviewInputSchema,OpsSentryIssueIdSchema,OpsSentryResolveInputSchema,OpsTraceIdSchema,OpsTraceReadInputSchema,OpsBraintrustSpanIdSchema,OpsAgentInvocationStatusSchema,OpsAgentTraceListInputSchema,OpsAgentTraceSpansInputSchema,OpsSpanBodyEdgeSchema,OpsAgentTraceSpanInputSchema,OpsAgentTraceMessagesInputSchema,OpsAgentHealthGroupBySchema,OpsAgentHealthInputSchema,OPS_DATA_USAGE_MAX_WINDOW_MS,OpsDataUsageGroupBySchema,OpsDataUsageInputSchema,OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,OpsContextHealthInputSchema,opsChatHistoryWindow,OpsChatHistoryHealthInputSchema,OpsChatHistoryCallsInputSchema,OpsChatHistoryJudgeInputSchema,OpsChatHistoryJudgeCalibrationInputSchema,OpsAgentTraceStatsGroupBySchema,OpsSpanTypeSchema,OpsAgentTraceStatsInputSchema,OpsAgentProviderErrorsInputSchema,OpsBillingCacheInvalidateInputSchema,OpsBillingEntitlementSyncInputSchema,OPS_PROJECT_OPERATIONS,OpsProjectOperationKindSchema,ExactVersionSchema,OpsProjectOperationPlanInputSchema,OPS_MIGRATIONS,OpsMigrationIdSchema,OPS_MIGRATION_PLAN_STATUSES,OpsMigrationPlanStatusSchema,OPS_MIGRATION_CHANGE_ACTIONS,OpsMigrationChangeActionSchema,OpsMigrationDryRunInputSchema,OpsProjectFilePathSchema,OpsProjectFileReasonSchema,OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES,OpsProjectPackageManagerInspectInputSchema,OpsProjectFileReadInputSchema,OpsProjectFileGlobInputSchema,OpsProjectFileGrepInputSchema,OpsProjectFileWritePlanInputSchema,OpsProjectFileWriteApplyInputSchema,OpsProjectOperationApplyInputSchema,OpsProjectPublishApplyInputSchema,OPS_POSTHOG_EVENTS,OPS_POSTHOG_QUESTION,OpsPosthogTimestampSchema,OpsPosthogMilestonesInputSchema,OpsPosthogFailureCodeSchema,OpsPosthogCoverageSchema,OpsPosthogCountsSchema,OpsPosthogMilestonesResponseSchema,OpsSessionHealthInputSchema,OpsProjectAnalyticsHealthInputSchema,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";init_env();OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z12.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:project:publish","ops:project:agents:write","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:posthog:read","ops:braintrust:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:organization:features: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=z12.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","ops:billing:read","ops:billing:write","ops:organization:features:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:validations:read","ops:notification:preview"],engineer:["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:project:operate","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:braintrust:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:billing:read","ops:billing:write","ops:organization:features: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=z12.object({permissions:z12.array(OpsPermissionSchema).min(1),backendProfiles:z12.array(OpsBackendProfileSchema).min(1),enabled:z12.boolean().default(!0)}),OpsServiceTokenInputSchema=z12.object({name:z12.string().trim().min(1).max(120),permissions:z12.array(OpsPermissionSchema).min(1),backendProfiles:z12.array(OpsBackendProfileSchema).min(1),expiresAt:z12.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=z12.object({importanceReason:z12.string().trim().min(1).max(1e3),ownerUserId:z12.string().trim().min(1).nullable().optional(),framework:z12.string().trim().max(120).nullable().optional(),packageManager:z12.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z12.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z12.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z12.object({projectId:z12.uuid(),title:z12.string().trim().min(1).max(240),userReport:z12.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z12.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z12.string().trim().max(1e4).nullable().optional(),outcome:z12.string().trim().max(1e4).nullable().optional(),evidence:z12.array(z12.record(z12.string(),z12.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=z12.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z12.object({fingerprint:z12.string().trim().min(1).max(240),title:z12.string().trim().min(1).max(240),description:z12.string().trim().min(1).max(1e4),affectedVersions:z12.array(z12.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z12.array(z12.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z12.string().trim().min(1).max(64).nullable().optional(),workaround:z12.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z12.array(z12.string().trim().min(1).max(120)).max(100),detectionQueries:z12.array(z12.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=z12.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z12.object({changeReference:z12.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z12.string().trim().min(1).max(1e4),evidence:z12.array(z12.record(z12.string(),z12.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z12.object({recipientEmail:z12.email().optional(),subject:z12.string().trim().min(1).max(200).default("An update from Fimo"),message:z12.string().trim().min(1).max(5e3),locale:z12.string().trim().min(2).max(20),reason:z12.string().trim().min(1).max(1e3),acknowledgePolicy:z12.literal(!0)}),OpsPylonIssueIdSchema=z12.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsPylonReasonSchema=z12.string().trim().min(1).max(1e3),OpsPylonMessageSchema=z12.string().trim().min(1).max(5e3),OpsPylonMessageIdSchema=z12.string().trim().min(1).max(255),OpsPylonEmailListSchema=z12.array(z12.email()).max(50).default([]),OpsPylonResolveInputSchema=z12.object({reason:OpsPylonReasonSchema}),OpsPylonNoteInputSchema=z12.object({message:OpsPylonMessageSchema,reason:OpsPylonReasonSchema}),OpsPylonReplyPreviewInputSchema=z12.object({messageId:OpsPylonMessageIdSchema,message:OpsPylonMessageSchema,toEmails:OpsPylonEmailListSchema,ccEmails:OpsPylonEmailListSchema,bccEmails:OpsPylonEmailListSchema,reason:OpsPylonReasonSchema,acknowledgePolicy:z12.literal(!0)}).refine(input=>input.toEmails.length+input.ccEmails.length+input.bccEmails.length<=50,{message:"At most 50 email recipients are allowed",path:["toEmails"]}),OpsSentryIssueIdSchema=z12.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsSentryResolveInputSchema=z12.object({reason:z12.string().trim().min(1).max(1e3)}),OpsTraceIdSchema=z12.string().trim().regex(/^[a-fA-F0-9]{32}$/).transform(value=>value.toLowerCase()),OpsTraceReadInputSchema=z12.object({projectId:z12.uuid(),from:z12.coerce.date(),to:z12.coerce.date(),reason:z12.string().trim().min(1).max(1e3)}).refine(input=>input.from<=input.to,{path:["from"],message:"from must be before or equal to to"}).refine(input=>input.to.getTime()-input.from.getTime()<=10080*60*1e3,{path:["from"],message:"trace windows cannot exceed 7 days"}),OpsBraintrustSpanIdSchema=z12.string().trim().regex(/^[A-Za-z0-9_-]{1,200}$/),OpsAgentInvocationStatusSchema=z12.enum(["planned","running","finished","cancelled","errored","refused"]),OpsAgentTraceListInputSchema=z12.object({projectId:z12.uuid().optional(),organizationId:z12.string().trim().min(1).max(255).optional(),agentKey:z12.string().trim().min(1).max(120).optional(),threadId:z12.uuid().optional(),status:OpsAgentInvocationStatusSchema.optional(),since:z12.coerce.date().optional(),minCostUsd:z12.coerce.number().min(0).optional(),tracedOnly:z12.coerce.boolean().default(!1),limit:z12.coerce.number().int().min(1).max(100).default(25),reason:z12.string().trim().min(1).max(1e3)}).refine(input=>!!(input.projectId||input.organizationId||input.threadId),{path:["projectId"],message:"one of projectId, organizationId, or threadId is required"}),OpsAgentTraceSpansInputSchema=z12.object({limit:z12.coerce.number().int().min(1).max(500).default(200),reason:z12.string().trim().min(1).max(1e3)}),OpsSpanBodyEdgeSchema=z12.enum(["start","end"]).default("start"),OpsAgentTraceSpanInputSchema=z12.object({maxChars:z12.coerce.number().int().min(500).max(2e5).default(2e4),edge:OpsSpanBodyEdgeSchema,reason:z12.string().trim().min(1).max(1e3)}),OpsAgentTraceMessagesInputSchema=z12.object({messageIndex:z12.coerce.number().int().min(0).optional(),maxChars:z12.coerce.number().int().min(500).max(2e5).default(2e4),reason:z12.string().trim().min(1).max(1e3)}),OpsAgentHealthGroupBySchema=z12.enum(["agent","status","branch","project","day"]),OpsAgentHealthInputSchema=z12.strictObject({projectId:z12.uuid().optional(),organizationId:z12.string().trim().min(1).max(255).optional(),branch:BranchSchema.optional(),agentKey:z12.string().trim().min(1).max(120).optional(),since:z12.coerce.date(),until:z12.coerce.date().optional(),groupBy:OpsAgentHealthGroupBySchema.default("agent"),includeChildren:z12.coerce.boolean().default(!1),limit:z12.coerce.number().int().min(1).max(200).default(50),reason:z12.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}),OPS_DATA_USAGE_MAX_WINDOW_MS=10080*60*1e3,OpsDataUsageGroupBySchema=z12.enum(["operation","provider","day","organization","agent"]),OpsDataUsageInputSchema=z12.strictObject({organizationId:z12.string().trim().min(1).max(255).optional(),since:z12.coerce.date(),until:z12.coerce.date().optional(),groupBy:OpsDataUsageGroupBySchema.default("operation"),limit:z12.coerce.number().int().min(1).max(200).default(50),reason:z12.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>(input.until??new Date).getTime()-input.since.getTime()<=OPS_DATA_USAGE_MAX_WINDOW_MS,{path:["since"],message:"data usage window cannot exceed 7 days"}),OPS_CONTEXT_HEALTH_MAX_WINDOW_MS=10080*60*1e3,OpsContextHealthInputSchema=z12.object({projectId:z12.uuid().optional(),since:z12.coerce.date(),until:z12.coerce.date().optional(),limit:z12.coerce.number().int().min(1).max(1e3).default(500),reason:z12.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>(input.until??new Date).getTime()-input.since.getTime()<=OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,{path:["since"],message:"context health window cannot exceed 7 days"}),opsChatHistoryWindow={projectId:z12.uuid().optional(),since:z12.coerce.date(),until:z12.coerce.date().default(()=>new Date),reason:z12.string().trim().min(1).max(1e3)};__name(refineChatHistoryWindow,"refineChatHistoryWindow");OpsChatHistoryHealthInputSchema=refineChatHistoryWindow(z12.strictObject(opsChatHistoryWindow)),OpsChatHistoryCallsInputSchema=refineChatHistoryWindow(z12.strictObject({...opsChatHistoryWindow,limit:z12.coerce.number().int().min(1).max(500).default(100)})),OpsChatHistoryJudgeInputSchema=refineChatHistoryWindow(z12.strictObject({...opsChatHistoryWindow,sample:z12.coerce.number().int().min(1).max(25).default(10)})),OpsChatHistoryJudgeCalibrationInputSchema=z12.strictObject({reason:z12.string().trim().min(1).max(1e3)}),OpsAgentTraceStatsGroupBySchema=z12.enum(["model","provider","span","type"]),OpsSpanTypeSchema=z12.enum(["llm","tool","function","task","score","eval"]),OpsAgentTraceStatsInputSchema=z12.object({since:z12.coerce.date(),until:z12.coerce.date().optional(),groupBy:OpsAgentTraceStatsGroupBySchema.default("model"),spanType:OpsSpanTypeSchema.optional(),slowerThanSeconds:z12.coerce.number().min(0).optional(),limit:z12.coerce.number().int().min(1).max(200).default(50),reason:z12.string().trim().min(1).max(1e3)}).refine(input=>!input.until||input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}),OpsAgentProviderErrorsInputSchema=z12.object({since:z12.coerce.date(),until:z12.coerce.date().default(()=>new Date),model:z12.string().trim().min(1).max(120).optional(),provider:z12.string().trim().min(1).max(120).optional(),spanType:OpsSpanTypeSchema.optional(),before:z12.coerce.date().optional(),limit:z12.coerce.number().int().min(1).max(1e3).default(500),sampleChars:z12.coerce.number().int().min(200).max(2e4).default(1200),correlateInvocations:z12.boolean().default(!1),correlationLimit:z12.coerce.number().int().min(1).max(100).default(25),reason:z12.string().trim().min(1).max(1e3)}).refine(input=>input.since<=input.until,{path:["since"],message:"since must be before or equal to until"}).refine(input=>input.until.getTime()-input.since.getTime()<=10080*60*1e3,{path:["since"],message:"provider error windows cannot exceed 7 days"}).refine(input=>!input.before||input.before>=input.since&&input.before<=input.until,{path:["before"],message:"before must be within the requested window"}),OpsBillingCacheInvalidateInputSchema=z12.object({reason:z12.string().trim().min(1).max(1e3)}),OpsBillingEntitlementSyncInputSchema=z12.object({reason:z12.string().trim().min(1).max(500),apply:z12.boolean().default(!1),confirmProduction:z12.boolean().default(!1),cursor:z12.string().min(1).optional(),batchSize:z12.number().int().min(1).max(100).default(50),concurrency:z12.number().int().min(1).max(10).default(2)}),OPS_PROJECT_OPERATIONS=["runtime.bump","preview.restart","production.publish"],OpsProjectOperationKindSchema=z12.enum(OPS_PROJECT_OPERATIONS),ExactVersionSchema=z12.string().trim().regex(/^\d+\.\d+\.\d+$/,"Expected an exact version such as 0.11.0"),OpsProjectOperationPlanInputSchema=z12.discriminatedUnion("kind",[z12.object({kind:z12.literal("runtime.bump"),targetVersion:ExactVersionSchema}),z12.object({kind:z12.literal("preview.restart")})]),OPS_MIGRATIONS=["project.v3-to-v4"],OpsMigrationIdSchema=z12.enum(OPS_MIGRATIONS),OPS_MIGRATION_PLAN_STATUSES=["applicable","not_applicable","unknown"],OpsMigrationPlanStatusSchema=z12.enum(OPS_MIGRATION_PLAN_STATUSES),OPS_MIGRATION_CHANGE_ACTIONS=["create","rewrite","delete"],OpsMigrationChangeActionSchema=z12.enum(OPS_MIGRATION_CHANGE_ACTIONS),OpsMigrationDryRunInputSchema=z12.object({migrationId:OpsMigrationIdSchema,projectEnv:z12.string().trim().min(1).max(255).default("main"),reason:z12.string().trim().min(1).max(1e3)}),OpsProjectFilePathSchema=z12.string().trim().min(1).max(1024),OpsProjectFileReasonSchema=z12.string().trim().min(1).max(1e3),OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES=["pnpm-lock.yaml","bun.lockb","bun.lock","yarn.lock","package-lock.json"],OpsProjectPackageManagerInspectInputSchema=z12.object({reason:OpsProjectFileReasonSchema}),OpsProjectFileReadInputSchema=z12.object({path:OpsProjectFilePathSchema,reason:OpsProjectFileReasonSchema}),OpsProjectFileGlobInputSchema=z12.object({pattern:z12.string().min(1).max(300).optional(),limit:z12.coerce.number().int().min(1).max(2e3).default(2e3),reason:OpsProjectFileReasonSchema}),OpsProjectFileGrepInputSchema=z12.object({pattern:z12.string().min(1).max(200),include:z12.string().min(1).max(300).optional(),caseInsensitive:z12.boolean().default(!1),maxMatches:z12.coerce.number().int().min(1).max(200).default(100),reason:OpsProjectFileReasonSchema}),OpsProjectFileWritePlanInputSchema=z12.object({path:OpsProjectFilePathSchema,content:z12.string().max(256*1024),overwrite:z12.boolean().default(!1),reason:OpsProjectFileReasonSchema}),OpsProjectFileWriteApplyInputSchema=OpsProjectFileWritePlanInputSchema.extend({planHash:z12.string().trim().length(64),consentReference:z12.string().trim().min(1).max(200).optional()}),OpsProjectOperationApplyInputSchema=z12.intersection(OpsProjectOperationPlanInputSchema,z12.object({planHash:z12.string().trim().length(64),reason:z12.string().trim().min(1).max(1e3),consentReference:z12.string().trim().min(1).max(200).optional()})),OpsProjectPublishApplyInputSchema=z12.object({planHash:z12.string().trim().length(64),reason:z12.string().trim().min(1).max(1e3),consentReference:z12.string({error:"Publishing on a customer's behalf requires a recorded consent reference"}).trim().min(1).max(200)}),OPS_POSTHOG_EVENTS=["didCreateProject","didInitiateProject","didDeploy","didDeployProject","didFirstPublish"],OPS_POSTHOG_QUESTION="project-milestone-counts-v1",OpsPosthogTimestampSchema=z12.iso.datetime({offset:!0}).refine(value=>Number.isFinite(Date.parse(value))&&!/\.\d{3}\d*[1-9]\d*(?:Z|[+-]\d{2}:\d{2})$/.test(value),"A finite timestamp with at most millisecond precision is required").transform(value=>new Date(value).toISOString()),OpsPosthogMilestonesInputSchema=z12.strictObject({projectId:z12.uuid().transform(value=>value.toLowerCase()),from:OpsPosthogTimestampSchema,to:OpsPosthogTimestampSchema,reason:z12.string().trim().min(1).max(1e3)}).refine(value=>{let duration=Date.parse(value.to)-Date.parse(value.from);return duration>0&&duration<=1440*60*1e3},{message:"Window must satisfy from < to and be at most 24 hours",path:["to"]}),OpsPosthogFailureCodeSchema=z12.enum(["not_configured","unauthenticated","forbidden","backend_mismatch","invalid_request","provider_auth_failed","provider_project_unavailable","rate_limited","timeout","provider_error","capability_unavailable","invalid_response","incomplete","pending","audit_unavailable"]),OpsPosthogCoverageSchema=z12.strictObject({completeAggregate:z12.boolean(),truncated:z12.boolean().nullable(),sampled:z12.boolean().nullable(),pagination:z12.enum(["not_applicable","unexpected","unknown"]),providerFreshnessKnown:z12.literal(!1),providerAsOf:z12.null(),projectFilter:z12.literal("exact properties.projectId equality"),environmentFilterSupported:z12.literal(!1),excludesMissingProjectId:z12.literal(!0),transport:z12.literal("server"),consentCoverage:z12.literal("server-policy-not-browser-consent"),operationDedupeAvailable:z12.literal(!1)}),OpsPosthogCountsSchema=z12.array(z12.strictObject({event:z12.enum(OPS_POSTHOG_EVENTS),captureCount:z12.number().int().min(0).max(Number.MAX_SAFE_INTEGER)})).length(5).refine(counts=>counts.every((entry,i)=>entry.event===OPS_POSTHOG_EVENTS[i])),OpsPosthogMilestonesResponseSchema=z12.strictObject({schemaVersion:z12.literal(1),questionId:z12.literal(OPS_POSTHOG_QUESTION),backendProfile:OpsBackendProfileSchema,projectId:z12.uuid().nullable(),projectEnvironment:z12.literal("mixed_or_unrecorded"),window:z12.strictObject({from:z12.iso.datetime(),to:z12.iso.datetime(),bounds:z12.literal("[from,to)")}).nullable(),source:z12.literal("posthog"),sourceStatus:z12.enum(["available","unavailable","forbidden"]),failureCode:OpsPosthogFailureCodeSchema.nullable(),queriedAt:z12.iso.datetime(),auditId:z12.uuid().nullable(),counts:OpsPosthogCountsSchema.nullable(),coverage:OpsPosthogCoverageSchema}).superRefine((value,ctx)=>{(value.sourceStatus==="available"?value.counts===null||value.failureCode!==null||value.auditId===null||value.projectId===null||value.window===null||!value.coverage.completeAggregate||value.coverage.sampled!==!1||value.coverage.truncated!==!1||value.coverage.pagination!=="not_applicable":value.counts!==null||value.failureCode===null||value.coverage.completeAggregate)&&ctx.addIssue({code:"custom",message:"Invalid aggregate availability"})}),OpsSessionHealthInputSchema=z12.object({reason:z12.string().trim().min(1).max(1e3),limit:z12.number().int().min(1).max(100).default(25),checkProvider:z12.boolean().default(!1)}),OpsProjectAnalyticsHealthInputSchema=z12.object({branch:z12.string().trim().min(1).max(255),canaryPath:z12.string().max(300).regex(/^\/[a-zA-Z0-9/_-]*\?fimo_monitor=[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/).optional(),since:z12.iso.datetime({offset:!0}),until:z12.iso.datetime({offset:!0}),reason:z12.string().trim().min(1).max(1e3)}).strict().refine(input=>Date.parse(input.since)<=Date.parse(input.until),{path:["since"],message:"since must be before or equal to until"}).refine(input=>Date.parse(input.until)-Date.parse(input.since)<=10080*60*1e3,{path:["since"],message:"analytics health window cannot exceed 7 days"}).refine(input=>Date.parse(input.until)<=Date.now(),{path:["until"],message:"until cannot be in the future"}).transform(({since,until,...input})=>({...input,since:new Date(since),until:new Date(until)}))}});import{z as z13}from"zod";function getChatFormOptionLabels(body){switch(body.type){case"choices":return body.actions.map(action=>action.label);case"cards":return body.items.map(item=>item.title);case"table":return body.rows.map(row2=>row2.cells[0]??"");case"assets":return body.items.map(item=>item.label??item.alt);case"capabilities":return body.items.map(item=>item.label);case"text":return[]}}var BlockSayActionSchema,BlockActionSchema,BlockAppActionSchema,BlockBaseSchema,ChoicesBlockSchema,TableRowTargetSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,ChatDisplayBlockSchema,TextBlockSchema,ChatFormStepIdSchema,CapabilityRequestSchema,CapabilitiesBlockSchema,ChatFormBodySchema,ChatFormStepSchema,FormBlockSchema,ChatBlockSchema,ChatBlockToolInputSchema,ChatFormAnswerItemSchema,ChatFormAnswerMetadataSchema,QUESTION_FORM_CONTRACT_VERSION,QuestionFormSnapshotSchema,QuestionFormAnswerSnapshotSchema,ChatFormResponseSchema,init_chat_block=__esm({"../../packages/api-contracts/dist/esm/types/chat-block.js"(){"use strict";BlockSayActionSchema=z13.object({kind:z13.literal("say"),label:z13.string().trim().min(1).max(40,"Button labels must be 40 characters or fewer."),description:z13.string().min(1).max(240).optional(),message:z13.string().trim().min(1,"Every say button needs the sentence the user is saying by clicking.").max(2e3),style:z13.enum(["primary","default","ghost"]).optional()}),BlockActionSchema=BlockSayActionSchema,BlockAppActionSchema=z13.discriminatedUnion("command",[z13.object({kind:z13.literal("app"),command:z13.literal("publish")}).strict(),z13.object({kind:z13.literal("app"),command:z13.literal("connect"),integrationKey:z13.string().trim().min(1).max(80)}).strict()]),BlockBaseSchema=z13.object({fallback:z13.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z13.string().min(1).max(80).optional()}),ChoicesBlockSchema=BlockBaseSchema.extend({type:z13.literal("choices"),text:z13.string().max(500).optional(),actions:z13.array(BlockActionSchema).min(2,"A choices block needs 2 to 4 buttons.").max(4,"A choices block needs 2 to 4 buttons.")}),TableRowTargetSchema=z13.discriminatedUnion("kind",[z13.object({kind:z13.literal("entry"),collection:z13.string().min(1).max(80),entryId:z13.string().min(1).max(120)}),z13.object({kind:z13.literal("asset"),assetId:z13.string().min(1).max(120)}),z13.object({kind:z13.literal("url"),url:z13.url({protocol:/^https$/}).max(2e3)})]),TableBlockSchema=BlockBaseSchema.extend({type:z13.literal("table"),columns:z13.array(z13.object({label:z13.string().min(1).max(24)})).min(2).max(4),rows:z13.array(z13.object({cells:z13.array(z13.string().max(80)).min(2).max(4),target:TableRowTargetSchema.optional()})).min(1).max(8)}).superRefine((table,ctx)=>{table.rows.forEach((row2,index)=>{row2.cells.length!==table.columns.length&&ctx.addIssue({code:"custom",path:["rows",index,"cells"],message:`Every table row needs exactly ${table.columns.length} cells, one for each column.`})})}),CardsBlockSchema=BlockBaseSchema.extend({type:z13.literal("cards"),layout:z13.enum(["rail","stack"]).optional(),items:z13.array(z13.object({title:z13.string().min(1).max(60),subtitle:z13.string().min(1).max(120).optional(),imageUrl:z13.url({protocol:/^https$/}).max(2e3).optional(),action:BlockSayActionSchema.optional()})).min(2).max(6)}),EntryBlockSchema=BlockBaseSchema.extend({type:z13.literal("entry"),label:z13.string().min(1).max(80),collection:z13.string().min(1).max(80),entryId:z13.string().min(1).max(120),path:z13.string().min(1).max(120).optional()}),AssetsBlockSchema=BlockBaseSchema.extend({type:z13.literal("assets"),items:z13.array(z13.object({url:z13.url({protocol:/^https$/}).max(2e3),alt:z13.string().min(1).max(120),label:z13.string().min(1).max(60).optional()})).min(1).max(6)}),CalloutBlockSchema=BlockBaseSchema.extend({type:z13.literal("callout"),title:z13.string().min(1).max(80),text:z13.string().min(1).max(240),action:BlockAppActionSchema}).strict(),StatBlockSchema=BlockBaseSchema.extend({type:z13.literal("stat"),items:z13.array(z13.object({label:z13.string().min(1).max(24),value:z13.string().min(1).max(16),delta:z13.string().min(1).max(12).optional(),tone:z13.enum(["up","down","flat"]).optional()})).min(1).max(4)}),ChartBlockSchema=BlockBaseSchema.extend({type:z13.literal("chart"),unit:z13.string().min(1).max(12).optional(),points:z13.array(z13.object({label:z13.string().min(1).max(12),value:z13.number().finite().min(0).max(1e9)})).min(2).max(12)}),ChatDisplayBlockSchema=z13.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema]),TextBlockSchema=BlockBaseSchema.extend({type:z13.literal("text"),placeholder:z13.string().min(1).max(120).optional(),multiline:z13.boolean().optional()}).strict(),ChatFormStepIdSchema=z13.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/,"Step ids are lowercase letters, digits, hyphen, or underscore (max 40)."),CapabilityRequestSchema=z13.object({id:ChatFormStepIdSchema,token:z13.string().regex(/^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?$/,"Capability tokens are verb:noun[:qualifier]."),label:z13.string().trim().min(1).max(60),reason:z13.string().trim().min(1).max(240)}).strict(),CapabilitiesBlockSchema=BlockBaseSchema.extend({type:z13.literal("capabilities"),items:z13.array(CapabilityRequestSchema).min(1).max(6)}).strict().superRefine((block,ctx)=>{let duplicate=__name(values=>new Set(values).size!==values.length,"duplicate");duplicate(block.items.map(item=>item.id))&&ctx.addIssue({code:"custom",path:["items"],message:"Every capability request needs its own id."}),duplicate(block.items.map(item=>item.token))&&ctx.addIssue({code:"custom",path:["items"],message:"Ask for each capability token once."}),duplicate(block.items.map(item=>item.label))&&ctx.addIssue({code:"custom",path:["items"],message:"Every capability request needs a distinct label."})}),ChatFormBodySchema=z13.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,AssetsBlockSchema,TextBlockSchema,CapabilitiesBlockSchema]);__name(getChatFormOptionLabels,"getChatFormOptionLabels");ChatFormStepSchema=z13.object({id:ChatFormStepIdSchema.optional(),question:z13.string().min(1).max(500),header:z13.string().min(1).max(25),body:ChatFormBodySchema,multiSelect:z13.boolean().optional(),recommended:z13.string().min(1).max(80).optional()}).superRefine((step,ctx)=>{let labels2=getChatFormOptionLabels(step.body);labels2.some(label=>!label.trim())&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a visible label."}),new Set(labels2).size!==labels2.length&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a unique label."}),step.recommended&&!labels2.includes(step.recommended)&&ctx.addIssue({code:"custom",path:["recommended"],message:"The recommended option must match a visible option label."}),step.body.type==="capabilities"&&step.multiSelect===!1&&ctx.addIssue({code:"custom",path:["multiSelect"],message:"A capabilities step is always multi-select: selected is approved, unselected is denied."})}).transform(step=>({...step,multiSelect:step.multiSelect??step.body.type==="capabilities"})),FormBlockSchema=BlockBaseSchema.extend({type:z13.literal("form"),steps:z13.array(ChatFormStepSchema).min(1).max(4)}),ChatBlockSchema=z13.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,FormBlockSchema]),ChatBlockToolInputSchema=z13.object({block:ChatBlockSchema}),ChatFormAnswerItemSchema=z13.object({stepId:ChatFormStepIdSchema.optional(),header:z13.string().min(1).max(25),question:z13.string().min(1).max(500),answer:z13.string().min(1),selectedLabels:z13.array(z13.string().min(1).max(120)).max(8),freeText:z13.string(),skipped:z13.boolean()}),ChatFormAnswerMetadataSchema=z13.object({toolCallId:z13.string().max(255).optional(),shortTitle:z13.string().max(80).optional(),questions:z13.array(ChatFormAnswerItemSchema).max(4)}),QUESTION_FORM_CONTRACT_VERSION=1,QuestionFormSnapshotSchema=z13.object({version:z13.literal(QUESTION_FORM_CONTRACT_VERSION),block:FormBlockSchema}).strict(),QuestionFormAnswerSnapshotSchema=z13.object({version:z13.literal(QUESTION_FORM_CONTRACT_VERSION),answer:ChatFormAnswerMetadataSchema}).strict(),ChatFormResponseSchema=ChatFormAnswerMetadataSchema.extend({toolCallId:z13.string().min(1).max(255),partial:z13.boolean().optional()})}});import{z as z14}from"zod";var CHAT_PORTRAIT_SHAPES,CHAT_PORTRAIT_EYES,CHAT_PORTRAIT_MOUTHS,CHAT_PORTRAIT_COLORS,ChatPortraitSchema,init_chat_portrait=__esm({"../../packages/api-contracts/dist/esm/types/chat-portrait.js"(){"use strict";CHAT_PORTRAIT_SHAPES=["pebble","bean","cloud","drop","potato","mochi","bun","pillow"],CHAT_PORTRAIT_EYES=["dot","caret","ring","shut","small","squint"],CHAT_PORTRAIT_MOUTHS=["smile","grin","o","w"],CHAT_PORTRAIT_COLORS=["red","orange","amber","lime","emerald","teal","sky","blue","indigo","violet","fuchsia","pink"],ChatPortraitSchema=z14.object({shape:z14.enum(CHAT_PORTRAIT_SHAPES),eyes:z14.enum(CHAT_PORTRAIT_EYES),mouth:z14.enum(CHAT_PORTRAIT_MOUTHS),color:z14.enum(CHAT_PORTRAIT_COLORS)})}});import{z as z15}from"zod";function normalizeStoredBlock(block){if(typeof block!="object"||block===null||Array.isArray(block))return block;let{type,...rest}=block;if(typeof type!="string")return block;let target=LEGACY_BLOCK_TYPES[type];return target?target==="viz"?{...rest,type:target,kind:"bar"}:{...rest,type:target}:block}function normalizeStoredBlocks(blocks){return Array.isArray(blocks)?blocks.map(normalizeStoredBlock):blocks}function normalizeStoredDocument(document){if(typeof document!="object"||document===null||Array.isArray(document))return document;let source=document;return{...source,brief:normalizeStoredBlocks(source.brief),details:normalizeStoredBlocks(source.details)}}function derivedBlockBody(block){let lines=[];switch(block.type){case"text":lines.push(block.text);break;case"metric":for(let item of block.items)lines.push([`${item.value}${item.unit??""}`,item.label].join(" \u2014 ")),item.note&&lines.push(item.note);break;case"viz":lines.push(block.points.map(point=>`${point.label}: ${formatReportValue(point.value,block.unit)}`).join(", ")),block.caption&&lines.push(block.caption);break;case"list":for(let item of block.items)lines.push([item.label,item.heading].filter(Boolean).join(" \u2014 ")),item.body&&lines.push(item.body),item.evidence&&lines.push(item.evidence);break;case"table":lines.push(block.columns.map(column=>column.label).join(" | "));for(let row2 of block.rows)lines.push(row2.cells.map(cell=>cell.text).join(" | "));block.caption&&lines.push(block.caption);break;case"media":lines.push(block.alt),block.caption&&lines.push(block.caption);break;case"links":for(let item of block.items)lines.push([`${item.label}: ${item.url}`,item.description].filter(Boolean).join(" \u2014 "));break;case"code":lines.push(block.code),block.caption&&lines.push(block.caption);break}return lines.join(`
|
|
5
|
-
`)}function reportSectionContentLength(blocks){return blocks.reduce((total,block)=>total+(block.title?.length??0)+derivedBlockBody(block).length+(block.fallback?.length??0),0)}function formatReportNumber(value){return Number.isInteger(value)?String(value):String(Number(value.toFixed(2)))}function formatReportValue(value,unit){let formatted=formatReportNumber(value);return unit?`${formatted}${new RegExp("^\\p{L}","u").test(unit)?" ":""}${unit}`:formatted}var REPORT_TITLE_MAX_CHARS,REPORT_BRIEF_MAX_BLOCKS,REPORT_DETAILS_MAX_BLOCKS,REPORT_BRIEF_MAX_CHARS,REPORT_DETAILS_MAX_CHARS,REPORT_TEXT_MAX_CHARS,REPORT_CODE_MAX_CHARS,REPORT_TONES,ReportToneSchema,blockCommon,ReportTextBlockSchema,ReportMetricBlockSchema,REPORT_VIZ_KINDS,ReportVizKindSchema,ReportVizBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema,ReportBlockSchema,ReportDocumentSchema,ReportBriefSchema,LEGACY_BLOCK_TYPES,StoredReportBriefSchema,StoredReportDocumentSchema,init_agent_report=__esm({"../../packages/api-contracts/dist/esm/types/agent-report.js"(){"use strict";REPORT_TITLE_MAX_CHARS=120,REPORT_BRIEF_MAX_BLOCKS=6,REPORT_DETAILS_MAX_BLOCKS=40,REPORT_BRIEF_MAX_CHARS=4e3,REPORT_DETAILS_MAX_CHARS=48e3,REPORT_TEXT_MAX_CHARS=4e3,REPORT_CODE_MAX_CHARS=8e3,REPORT_TONES=["critical","warning","info","neutral"],ReportToneSchema=z15.enum(REPORT_TONES),blockCommon={title:z15.string().trim().min(1).max(120).optional(),fallback:z15.string().trim().min(1).max(600).optional()},ReportTextBlockSchema=z15.object({type:z15.literal("text"),...blockCommon,text:z15.string().trim().min(1).max(REPORT_TEXT_MAX_CHARS)}).strict().describe("Short connective context or a conclusion with no better structure. Never a multi-item dump."),ReportMetricBlockSchema=z15.object({type:z15.literal("metric"),...blockCommon,items:z15.array(z15.object({value:z15.string().trim().min(1).max(24),unit:z15.string().trim().min(1).max(12).optional(),label:z15.string().trim().min(1).max(160),note:z15.string().trim().min(1).max(300).optional()}).strict()).min(1).max(3),spark:z15.array(z15.number().finite()).min(2).max(24).optional()}).strict().describe("1-3 numbers that materially communicate state, scale, or success. Do not promote incidental counts."),REPORT_VIZ_KINDS=["bar","line","area","composition"],ReportVizKindSchema=z15.enum(REPORT_VIZ_KINDS),ReportVizBlockSchema=z15.object({type:z15.literal("viz"),...blockCommon,kind:ReportVizKindSchema.describe("bar: compare named quantities. line/area: change across an ordered sequence. composition: parts of one whole."),unit:z15.string().trim().min(1).max(12).optional(),points:z15.array(z15.object({label:z15.string().trim().min(1).max(24),value:z15.number().finite(),highlight:z15.boolean().optional()}).strict()).min(2).max(24),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Only when comparison, relationship, distribution, persistence, or change over time is itself the point. Never decorative.").superRefine((block,ctx)=>{block.points.filter(point=>point.highlight).length>1&&ctx.addIssue({code:"custom",path:["points"],message:"Highlight at most one point."}),block.kind==="composition"&&block.points.forEach((point,index)=>{point.value<0&&ctx.addIssue({code:"custom",path:["points",index,"value"],message:"A composition holds parts of one whole, so every value must be zero or more."})})}),ReportListBlockSchema=z15.object({type:z15.literal("list"),...blockCommon,items:z15.array(z15.object({tone:ReportToneSchema.optional(),label:z15.string().trim().min(1).max(24).optional(),heading:z15.string().trim().min(1).max(160).describe("The human-visible result, action, or consequence, readable on its own."),body:z15.string().trim().min(1).max(1200).optional().describe("One short explanation of why it matters."),evidence:z15.string().trim().min(1).max(600).optional().describe("Exact supporting proof: paths, keys, literal values, compact measurements.")}).strict()).min(1).max(12)}).strict().describe("Ranked items sharing one hierarchy: findings, recommendations, steps, sources, or a single callout. heading = human consequence, body = why it matters, evidence = the technical proof. Do not repeat the report title."),ReportTableBlockSchema=z15.object({type:z15.literal("table"),...blockCommon,columns:z15.array(z15.object({label:z15.string().trim().min(1).max(32)}).strict()).min(1).max(6),rows:z15.array(z15.object({cells:z15.array(z15.object({text:z15.string().trim().max(160),tone:ReportToneSchema.optional()}).strict()).min(1).max(6)}).strict()).min(1).max(40),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Repeated entities sharing the same attributes. Use instead of parallel prose.").superRefine((block,ctx)=>{block.rows.forEach((row2,index)=>{row2.cells.length!==block.columns.length&&ctx.addIssue({code:"custom",path:["rows",index,"cells"],message:`Every row needs exactly ${block.columns.length} cells, one per column.`})})}),ReportMediaBlockSchema=z15.object({type:z15.literal("media"),...blockCommon,assetId:z15.uuid(),alt:z15.string().trim().min(1).max(300),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Only visual or recorded evidence, or a media deliverable: a before/after, a layout defect, a generated asset. Never decoration."),ReportLinksBlockSchema=z15.object({type:z15.literal("links"),...blockCommon,items:z15.array(z15.object({label:z15.string().trim().min(1).max(120),url:z15.url({protocol:/^https$/}).max(2e3),description:z15.string().trim().min(1).max(300).optional()}).strict()).min(1).max(8)}).strict().describe("A destination, evidence source, or next action worth opening."),ReportCodeBlockSchema=z15.object({type:z15.literal("code"),...blockCommon,language:z15.string().regex(/^[a-z0-9+#-]{1,20}$/,"A language is a short lowercase token, e.g. ts, json, bash.").optional(),code:z15.string().min(1).max(REPORT_CODE_MAX_CHARS),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("An exact snippet that is decisive evidence. Never a log dump."),ReportBlockSchema=z15.discriminatedUnion("type",[ReportTextBlockSchema,ReportMetricBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportVizBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema]),ReportDocumentSchema=z15.object({title:z15.string().trim().min(1).max(REPORT_TITLE_MAX_CHARS),brief:z15.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),details:z15.array(ReportBlockSchema).max(REPORT_DETAILS_MAX_BLOCKS)}).strict().superRefine((document,ctx)=>{let brief=reportSectionContentLength(document.brief);brief>REPORT_BRIEF_MAX_CHARS&&ctx.addIssue({code:"custom",path:["brief"],message:`The brief holds ${brief} characters of content; keep it under ${REPORT_BRIEF_MAX_CHARS}. Move evidence into details.`});let details=reportSectionContentLength(document.details);details>REPORT_DETAILS_MAX_CHARS&&ctx.addIssue({code:"custom",path:["details"],message:`The details hold ${details} characters of content; the limit is ${REPORT_DETAILS_MAX_CHARS}.`})}),ReportBriefSchema=z15.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),LEGACY_BLOCK_TYPES={findings:"list",series:"viz",image:"media"};__name(normalizeStoredBlock,"normalizeStoredBlock");__name(normalizeStoredBlocks,"normalizeStoredBlocks");__name(normalizeStoredDocument,"normalizeStoredDocument");StoredReportBriefSchema=z15.preprocess(normalizeStoredBlocks,ReportBriefSchema),StoredReportDocumentSchema=z15.preprocess(normalizeStoredDocument,ReportDocumentSchema);__name(derivedBlockBody,"derivedBlockBody");__name(reportSectionContentLength,"reportSectionContentLength");__name(formatReportNumber,"formatReportNumber");__name(formatReportValue,"formatReportValue")}});import{z as z16}from"zod";var FIMO_CONFIG_PATH,LEGACY_FIMO_CONFIG_PATHS,ALL_FIMO_CONFIG_PATHS,FimoFrameworkSchema,FimoRuntimeCommandsSchema,FimoRuntimeConfigSchema,FimoHostingConditionSchema,conditionFields,FimoHostingRewriteSchema,FimoHostingRedirectSchema,FimoHostingHeaderSchema,FimoHostingConfigSchema,FimoAppConfigSchema,init_fimo_config=__esm({"../../packages/api-contracts/dist/esm/types/fimo-config.js"(){"use strict";FIMO_CONFIG_PATH=".fimo/config.json",LEGACY_FIMO_CONFIG_PATHS=["fimo-config.json","fimo.config.json"],ALL_FIMO_CONFIG_PATHS=[FIMO_CONFIG_PATH,...LEGACY_FIMO_CONFIG_PATHS],FimoFrameworkSchema=z16.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z16.object({dev:z16.string().trim().min(1).optional(),build:z16.string().trim().min(1).optional(),install:z16.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z16.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z16.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z16.object({type:z16.enum(["header","cookie","query","host"]),key:z16.string().min(1).optional(),value:z16.string().min(1).optional()}).strict().superRefine((condition,context)=>{if(condition.type==="host"){condition.key!==void 0&&context.addIssue({code:"custom",path:["key"],message:"A host condition takes no key."}),condition.value===void 0&&context.addIssue({code:"custom",path:["value"],message:"A host condition needs a value."});return}condition.key===void 0&&context.addIssue({code:"custom",path:["key"],message:`A ${condition.type} condition needs the key it matches on.`})}),conditionFields={has:z16.array(FimoHostingConditionSchema).min(1).optional(),missing:z16.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z16.object({source:z16.string().min(1),destination:z16.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z16.object({source:z16.string().min(1),destination:z16.string().min(1),permanent:z16.boolean().optional(),statusCode:z16.union([z16.literal(301),z16.literal(302),z16.literal(307),z16.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z16.object({source:z16.string().min(1),headers:z16.array(z16.object({key:z16.string().min(1),value:z16.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z16.object({rewrites:z16.array(FimoHostingRewriteSchema).optional(),redirects:z16.array(FimoHostingRedirectSchema).optional(),headers:z16.array(FimoHostingHeaderSchema).optional(),cleanUrls:z16.boolean().optional(),trailingSlash:z16.boolean().optional()}).strict(),FimoAppConfigSchema=z16.object({runtime:FimoRuntimeConfigSchema.optional(),hosting:FimoHostingConfigSchema.optional()}).passthrough().superRefine((config,context)=>{Object.hasOwn(config,"framework")&&context.addIssue({code:"custom",path:["framework"],message:"Use runtime.framework instead of the top-level framework field."})})}});function isEntryParamBinding(binding){return binding!==void 0&&(binding.type??"entry")==="entry"}function pageRouteParamNames(path49){return[...path49.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path49,params){return pageRouteParamNames(path49).filter(param=>!LOCALE_PARAM_NAME.test(param)&¶ms?.[param]?.type!=="external")}function parsePageParamExpression(expression){let match=PARAM_EXPRESSION.exec(expression);return match?{param:match[1],field:match[2]}:null}function fieldValue(entry,fieldPath){let value=entry;for(let segment of fieldPath.split(".")){if(!value||typeof value!="object"||Array.isArray(value))return;value=value[segment]}return value}function queryValue(value){if(Array.isArray(value))return value.map(queryValue);if(value&&typeof value=="object"){let record=value;return typeof record.id=="string"?record.id:Object.fromEntries(Object.entries(record).map(([key,item])=>[key,queryValue(item)]))}return value===void 0?null:value}function resolveValue(value,params){if(typeof value=="string"&&value.startsWith("$params.")){let parsed=parsePageParamExpression(value);if(!parsed)return{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param:"",field:""}};let{param,field}=parsed,entry=params[param];if(!entry)return{ok:!1,error:{code:"PAGE_PARAM_NOT_SELECTED",expression:value,param,field}};let resolved=fieldValue(entry,field);return resolved==null||resolved===""?{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param,field}}:{ok:!0,value:queryValue(resolved)}}if(Array.isArray(value)){let resolved=[];for(let item of value){let result=resolveValue(item,params);if(!result.ok)return result;resolved.push(result.value)}return{ok:!0,value:resolved}}if(value&&typeof value=="object"){let resolved={};for(let[key,item]of Object.entries(value)){let result=resolveValue(item,params);if(!result.ok)return result;resolved[key]=result.value}return{ok:!0,value:resolved}}return{ok:!0,value}}function resolvePageSourceQuery(query={},params){let resolved=resolveValue(query,params);return resolved.ok?{ok:!0,query:resolved.value}:resolved}function pageSourceParamExpressions(value){return typeof value=="string"?value.startsWith("$params.")?[value]:[]:Array.isArray(value)?value.flatMap(pageSourceParamExpressions):value&&typeof value=="object"?Object.values(value).flatMap(pageSourceParamExpressions):[]}var LOCALE_PARAM_NAME,PARAM_EXPRESSION,init_page_sources=__esm({"../../packages/api-contracts/dist/esm/types/page-sources.js"(){"use strict";__name(isEntryParamBinding,"isEntryParamBinding");LOCALE_PARAM_NAME=/^(locale|lang|language)$/i;__name(pageRouteParamNames,"pageRouteParamNames");__name(pageContentParamNames,"pageContentParamNames");PARAM_EXPRESSION=/^\$params\.([A-Za-z_][\w-]*)\.([A-Za-z_][\w.-]*)$/;__name(parsePageParamExpression,"parsePageParamExpression");__name(fieldValue,"fieldValue");__name(queryValue,"queryValue");__name(resolveValue,"resolveValue");__name(resolvePageSourceQuery,"resolvePageSourceQuery");__name(pageSourceParamExpressions,"pageSourceParamExpressions")}});var init_project_files=__esm({"../../packages/api-contracts/dist/esm/types/project-files.js"(){"use strict"}});import{z as z17}from"zod";var PROJECT_CHAT_MANUAL_MODEL_IDS,ProjectChatManualModelIdSchema,ProjectDTOSchema,ProjectDTO,UpdateProjectSettingsRequestSchema,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectHistoryUsageDTOSchema,ProjectVersionPageDTOSchema,ProjectVersionPageDTO,ProjectHistorySummaryDTOSchema,ProjectHistorySummaryDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionResponseSchema,ProjectVersionPageResponseSchema,ProjectHistorySummaryResponseSchema,VersionMutationResponseSchema,PublishUpgradeRequiredSchema,ProjectLatestPublicationAttemptSchema,ProjectPublicationStateDTOSchema,ProjectPublicationStateDTO,PublishProjectRequestSchema,PublicationMutationDTOSchema,PublicationMutationDTO,ProjectPublicationStateResponseSchema,PublicationMutationResponseSchema,ProjectResponseSchema,ProjectWithPlanResponseSchema,init_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project.dto.js"(){"use strict";init_chat_block();init_common();init_env();init_create_dto();init_response();PROJECT_CHAT_MANUAL_MODEL_IDS=["anthropic/claude-opus-5.5","anthropic/claude-opus-5","anthropic/claude-sonnet-5","anthropic/claude-fable-5","anthropic/claude-haiku-5.5","openai/gpt-5.6-luna","openai/gpt-5.6-terra","openai/gpt-5.6-sol","openai/gpt-6-astra","openai/gpt-6.1-sol","openai/gpt-6-sol","openai/gpt-6-luna","xai/grok-4.6","google/gemini-3.1-pro-preview","google/gemini-3.8-flash","google/gemini-3.7-flash","google/gemini-3.6-flash","google/gemini-3.5-flash-lite","zai/glm-5.2","zai/glm-5.3-flash","deepseek/deepseek-v4-pro","minimax/minimax-m3","moonshotai/kimi-k3"],ProjectChatManualModelIdSchema=z17.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z17.string(),displayName:z17.string().nullable(),subdomain:z17.string().nullable().optional(),subdomainUpdatedAt:z17.date().nullable().optional(),organizationId:z17.string().nullable(),createdBy:z17.string().nullable(),defaultBranch:BranchSchema.default(DEFAULT_BRANCH),productionSourceBranch:BranchSchema.default(DEFAULT_BRANCH),enabledChatModels:z17.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z17.string(),thumbnailUrl:z17.string().nullable(),publishedThumbnailUrl:z17.string().nullable(),category:z17.string().nullable(),snapshotUrl:z17.string().startsWith("/").optional(),appUrl:z17.string().nullable(),lastPublishedAt:z17.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),UpdateProjectSettingsRequestSchema=z17.object({name:z17.string().optional(),enabledChatModels:z17.array(ProjectChatManualModelIdSchema).optional(),productionSourceBranch:BranchSchema.optional(),syncConfig:z17.boolean().optional()}).strict(),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z17.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z17.object({id:z17.uuid(),name:z17.string(),displayName:z17.string().nullable(),thumbnailUrl:z17.string().nullable(),category:z17.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z17.object({id:z17.string(),name:z17.string(),avatar:z17.string().nullable(),color:z17.object({bg:z17.string(),text:z17.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z17.object({path:z17.string(),content:z17.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z17.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z17.object({id:z17.string(),messageId:z17.string(),versionId:z17.string().nullable(),role:ProjectChatMessageRole,parts:z17.array(z17.any()),createdAt:z17.coerce.date()}),MessageUserMetadataSchema=z17.object({id:z17.string(),name:z17.string().nullable().optional(),image:z17.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z17.number(),metadata:z17.object({user:MessageUserMetadataSchema,changeManifest:z17.array(z17.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z17.object({versionId:z17.uuid(),commitHash:z17.string(),name:z17.string(),description:z17.string().nullable(),kind:z17.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z17.object({versionCount:z17.number().int().nonnegative(),snapshotBytes:z17.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z17.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z17.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z17.object({content:z17.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z17.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z17.object({success:z17.boolean(),message:z17.string().optional(),warning:z17.string().optional(),durationMs:z17.number().int().nonnegative().optional()})),PublishUpgradeRequiredSchema=z17.object({code:z17.literal("PUBLISH_UPGRADE_REQUIRED"),message:z17.string(),currentVersion:z17.number().int().positive(),targetVersion:z17.literal(4)}),ProjectLatestPublicationAttemptSchema=z17.object({publicationId:z17.uuid(),status:z17.enum(["queued","building","published","failed","canceled"]),failureCode:z17.string().nullable(),sourceBranch:z17.string(),createdAt:CommonSchemas.timestamp,finishedAt:CommonSchemas.timestamp.nullable()}),ProjectPublicationStateDTOSchema=z17.object({isPublished:z17.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z17.string().nullable(),upgradeRequired:PublishUpgradeRequiredSchema.nullish(),hasActiveRelease:z17.boolean().optional(),latestAttempt:ProjectLatestPublicationAttemptSchema.nullish()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z17.object({label:z17.string().trim().min(1).max(120).optional(),notes:z17.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z17.object({success:z17.boolean(),message:z17.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z17.boolean(),publicationId:z17.string().optional(),url:z17.string().nullable().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z18}from"zod";var ProjectBranchStatusSchema,ProjectBranchKindSchema,ProjectBranchDTOSchema,ProjectBranchDTO,ResolvedBranchEnvironmentDTOSchema,ProjectBranchListItemDTOSchema,ProjectBranchListItemDTO,CreateProjectBranchRequestInputSchema,CreateProjectBranchRequestSchema,SyncProjectBranchRequestSchema,ProjectBranchResponseSchema,ProjectBranchesListResponseSchema,BranchSurfaceDiffSchema,BranchDiffResultSchema,BranchDiffResultDTO,init_project_env_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-env.dto.js"(){"use strict";init_common();init_env();init_environment();init_create_dto();init_response();ProjectBranchStatusSchema=z18.enum(["provisioning","active","deleted"]),ProjectBranchKindSchema=z18.enum(["user","agent-session"]),ProjectBranchDTOSchema=BaseEntitySchema.extend({projectId:z18.uuid(),branch:BranchSchema.optional(),status:ProjectBranchStatusSchema,kind:ProjectBranchKindSchema,parentBranch:BranchSchema.nullable().optional(),createdBy:z18.string().nullable(),deletedAt:z18.coerce.date().nullable(),env:BranchSchema,parentEnv:BranchSchema.nullable()}),ProjectBranchDTO=createDTO(ProjectBranchDTOSchema),ResolvedBranchEnvironmentDTOSchema=z18.object({id:z18.union([z18.literal(PREVIEW_ENVIRONMENT_KEY),z18.uuid()]),name:z18.string()}),ProjectBranchListItemDTOSchema=ProjectBranchDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable(),workSession:z18.object({sessionId:z18.uuid(),name:z18.string()}).optional()}),ProjectBranchListItemDTO=createDTO(ProjectBranchListItemDTOSchema),CreateProjectBranchRequestInputSchema=z18.object({branch:BranchSchema.optional(),parentBranch:BranchSchema.optional(),env:BranchSchema.optional(),parentEnv:BranchSchema.optional()}),CreateProjectBranchRequestSchema=CreateProjectBranchRequestInputSchema.superRefine((body,ctx)=>{body.branch===void 0&&body.env===void 0&&ctx.addIssue({code:"custom",path:["branch"],message:"branch is required"}),body.branch!==void 0&&body.env!==void 0&&body.branch!==body.env&&ctx.addIssue({code:"custom",path:["branch"],message:`branch '${body.branch}' and the deprecated env '${body.env}' disagree \u2014 send one, or send both with the same value`}),body.parentBranch!==void 0&&body.parentEnv!==void 0&&body.parentBranch!==body.parentEnv&&ctx.addIssue({code:"custom",path:["parentBranch"],message:`parentBranch '${body.parentBranch}' and the deprecated parentEnv '${body.parentEnv}' disagree \u2014 send one, or send both with the same value`})}).transform(body=>({branch:body.branch??body.env,parentBranch:body.parentBranch??body.parentEnv})),SyncProjectBranchRequestSchema=z18.object({from:BranchSchema.optional()}),ProjectBranchResponseSchema=createResponseSchema(ProjectBranchDTOSchema),ProjectBranchesListResponseSchema=createResponseSchema(z18.array(ProjectBranchListItemDTOSchema)),BranchSurfaceDiffSchema=z18.object({surface:z18.enum(["code","schemas","content","translations","assets","forms"]),status:z18.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z18.number().int().nonnegative(),conflictCount:z18.number().int().nonnegative()}),BranchDiffResultSchema=z18.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),generatedAt:z18.coerce.date(),surfaces:z18.array(BranchSurfaceDiffSchema),fromEnv:BranchSchema,toEnv:BranchSchema}),BranchDiffResultDTO=createDTO(BranchDiffResultSchema)}});import{z as z19}from"zod";var ProjectEnvironmentBaseSchema,ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema,ProjectEnvironmentDTOSchema,ProjectEnvironmentDTO,CreateProjectEnvironmentRequestSchema,ProjectEnvironmentsListResponseSchema,ProjectEnvironmentResponseSchema,DeleteProjectEnvironmentResultSchema,DeleteProjectEnvironmentResponseSchema,init_project_environment_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-environment.dto.js"(){"use strict";init_env();init_environment();init_create_dto();init_response();ProjectEnvironmentBaseSchema=z19.object({projectId:z19.uuid(),name:z19.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z19.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z19.literal("production"),sourceBranch:BranchSchema,isPublished:z19.boolean(),url:z19.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z19.literal(PREVIEW_ENVIRONMENT_KEY),kind:z19.literal("preview"),matchedBranchCount:z19.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z19.literal("custom"),matchedBranchCount:z19.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z19.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z19.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema(z19.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z19.object({deletedId:z19.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema(DeleteProjectEnvironmentResultSchema)}});import{z as z20}from"zod";var ProjectSecretsListQuerySchema,ProjectSecretWriteRequestSchema,CreateProjectSecretRequestSchema,DeleteProjectSecretQuerySchema,ProjectSecretMetadataDTOSchema,ProjectSecretMetadataDTO,ProjectSecretsListResponseSchema,ProjectSecretResponseSchema,init_project_secret_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-secret.dto.js"(){"use strict";init_environment();init_create_dto();init_response();ProjectSecretsListQuerySchema=z20.object({kind:z20.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z20.object({kind:z20.enum(["variable","secret"]),value:z20.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z20.string().min(1).max(255)}),DeleteProjectSecretQuerySchema=z20.object({kind:z20.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z20.object({id:z20.uuid(),projectId:z20.uuid(),key:z20.string(),kind:z20.literal("secret"),exposure:z20.literal("private"),environment:EnvironmentKeySchema,maskedValue:z20.string().optional(),createdAt:z20.date().transform(value=>value.toISOString()),updatedAt:z20.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema(z20.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema(ProjectSecretMetadataDTOSchema)}});import{z as z21}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=z21.object({success:z21.literal(!0),downloadUrl:z21.string(),expiresAt:z21.string(),fileSize:z21.number(),duration:z21.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z21.object({success:z21.literal(!0),projectId:z21.string(),projectName:z21.string(),displayName:z21.string(),projectUrl:z21.string(),duration:z21.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z21.object({contentTypes:z21.number(),entries:z21.number(),assets:z21.number(),translations:z21.number(),forms:z21.number(),codeFiles:z21.number(),assetFiles:z21.number()}),ImportPreviewSurfaceDTOSchema=z21.object({name:z21.string(),included:z21.boolean(),count:z21.number().optional(),note:z21.string().optional()}),ImportPreviewDTOSchema=z21.object({projectName:z21.string(),displayName:z21.string().nullable(),category:z21.string().nullable(),exportedAt:z21.string(),version:z21.string(),envScope:z21.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z21.array(ImportPreviewSurfaceDTOSchema),fileSize:z21.number(),fileName:z21.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z21.object({success:z21.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z22}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,CONFLICT_KINDS,ConflictKindSchema,ConflictSchema,FieldPickSchema,ConflictResolutionSchema,MergeResultSchema,MergeResultDTO,MergeResultResponseSchema,EngineStrategySchema,VendorStrategySchema,MergeStrategySchema,ResolvedStrategySchema,MergeRequestSchema,MergeInitiateResultSchema,MergeInitiateResultDTO,MergeInitiateResponseSchema,MergeConflictsHydrationSchema,MergeConflictsHydrationDTO,MergeConflictsHydrationResponseSchema,MergeResolveDraftRequestSchema,MergeResolveDraftResultSchema,MergeResolveDraftResultDTO,MergeResolveRequestSchema,MergeCancelRequestSchema,PublishReleaseRequestSchema,PublishReleaseResultSchema,PublishReleaseResultDTO,PublishReleaseResponseSchema,init_env_status_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-status.dto.js"(){"use strict";init_env();init_create_dto();init_response();SurfaceNameSchema=z22.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z22.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z22.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z22.object({verb:SurfaceDeltaVerbSchema,key:z22.string(),detail:z22.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z22.record(z22.string(),z22.unknown()).optional()}),PerSurfaceDeltaSchema=z22.object({surface:SurfaceNameSchema,status:z22.enum(["ok","timed_out","failed","unchanged"]),durationMs:z22.number().int().nonnegative().optional(),changedCount:z22.number().int().nonnegative(),conflictCount:z22.number().int().nonnegative(),items:z22.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z22.boolean().optional(),error:z22.string().optional()}),CrossSurfaceFindingSchema=z22.object({id:z22.string(),kind:z22.string(),description:z22.string(),severity:z22.enum(["warning","error"]),source:z22.object({surface:SurfaceNameSchema,key:z22.string()}),target:z22.object({surface:SurfaceNameSchema,key:z22.string()}),actions:z22.array(z22.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z22.object({branch:BranchSchema.optional(),env:BranchSchema,vs:BranchSchema,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({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,generatedAt:z22.coerce.date(),surfaces:z22.array(PerSurfaceDeltaSchema),crossSurface:z22.array(CrossSurfaceFindingSchema).optional(),fingerprint:z22.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z22.object({path:z22.string(),state:z22.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z22.string(),additions:z22.number().int().nonnegative(),deletions:z22.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z22.object({oid:z22.string().optional(),content:z22.string().optional(),truncated:z22.boolean(),binary:z22.boolean()}),CodeConflictDetailSchema=z22.object({path:z22.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z22.string(),targetTipSha:z22.string(),mergeBaseSha:z22.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z22.object({id:z22.string(),slug:z22.string(),contentType:z22.string(),data:z22.record(z22.string(),z22.unknown()),updatedAt:z22.coerce.date()}),ContentRowDiffSchema=z22.object({collection:z22.string(),rowId:z22.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z22.object({name:z22.string(),label:z22.string(),isSingleton:z22.boolean(),fields:z22.record(z22.string(),z22.unknown())}),SchemaTypeDiffSchema=z22.object({typeName:z22.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z22.object({id:z22.string(),name:z22.string(),type:z22.enum(["file","folder"]),mimeType:z22.string().nullable(),storageKey:z22.string().nullable(),url:z22.string().nullable(),fileSize:z22.number().nullable(),width:z22.number().nullable(),height:z22.number().nullable(),altText:z22.string().nullable(),caption:z22.string().nullable(),createdAt:z22.coerce.date(),updatedAt:z22.coerce.date()}),AssetDiffSchema=z22.object({assetId:z22.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z22.object({locale:z22.string(),key:z22.string(),parent:z22.string().nullable(),child:z22.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z22.object({formName:z22.string(),label:z22.string().nullable(),schemaFingerprint:z22.string(),fields:z22.record(z22.string(),z22.unknown()),settings:z22.record(z22.string(),z22.unknown()).optional()}),FormSchemaDiffSchema=z22.object({formName:z22.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z22.enum(CONFLICT_KINDS),ConflictSchema=z22.object({surface:SurfaceNameSchema,key:z22.string(),kind:ConflictKindSchema.optional(),description:z22.string(),parentValue:z22.unknown().optional(),childValue:z22.unknown().optional(),conflictingFields:z22.array(z22.string()).optional(),code:z22.object({path:z22.string(),unresolvable:z22.boolean().optional(),reason:z22.string().optional()}).optional()}),FieldPickSchema=z22.object({field:z22.string(),choice:z22.enum(["parent","child","pick","ai-pick"]),pickedValue:z22.unknown().optional(),aiSessionId:z22.string().optional()}),ConflictResolutionSchema=z22.object({surface:SurfaceNameSchema,key:z22.string(),choice:z22.enum(["parent","child","pick"]),pickedValue:z22.unknown().optional(),fieldPicks:z22.array(FieldPickSchema).optional()}),MergeResultSchema=z22.object({ok:z22.boolean(),mergeId:z22.string().uuid(),fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,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:BranchSchema,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:BranchSchema,toEnv:BranchSchema,status:z22.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z22.array(ConflictSchema),draftResolutions:z22.array(ConflictResolutionSchema),lastEditedBy:z22.string().nullable(),lastEditedAt:z22.coerce.date().nullable(),initiator:z22.object({userId:z22.string().nullable(),role:z22.string().nullable(),agentName:z22.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z22.object({resolutions:z22.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z22.object({mergeId:z22.string().uuid(),draftResolutions:z22.array(ConflictResolutionSchema),lastEditedAt:z22.coerce.date(),lastEditedBy:z22.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z22.object({mergeId:z22.string().uuid(),resolutions:z22.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z22.object({mergeId:z22.string().uuid()}),PublishReleaseRequestSchema=z22.object({version:z22.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z22.string().max(2e4).optional()}),PublishReleaseResultSchema=z22.object({releaseTag:z22.string(),sha:z22.string(),publishedAt:z22.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z23}from"zod";var AgentSessionStatusSchema,AgentSessionReviewPublicationSchema,AgentSessionReviewSummarySchema,AgentSessionReviewSummaryDTO,AgentSessionReviewPayloadSchema,AgentSessionReviewPayloadDTO,AgentSessionReviewPayloadResponseSchema,SessionErrorCodeSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_create_dto();init_response();init_env_status_dto();AgentSessionStatusSchema=z23.enum(["planned","running","finished","cancelled","errored"]),AgentSessionReviewPublicationSchema=z23.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z23.object({capturedAt:z23.coerce.date(),fingerprint:z23.string().min(1).max(256),counts:z23.object({code:z23.number().int().nonnegative(),content:z23.number().int().nonnegative(),schemas:z23.number().int().nonnegative(),labels:z23.number().int().nonnegative(),assets:z23.number().int().nonnegative().optional()}),publication:AgentSessionReviewPublicationSchema,mergeId:z23.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z23.object({diff:DiffReportSchema,code:z23.array(CodeFileDiffSchema.extend({raw:z23.string().max(24576)})).max(200),schemas:z23.array(SchemaTypeDiffSchema).max(200),content:z23.array(z23.object({key:z23.string().min(1).max(512),collection:z23.string().min(1).max(256),slug:z23.string().max(512).optional(),verb:z23.enum(["added","modified","deleted"]),fields:z23.array(z23.object({name:z23.string().min(1).max(256),before:z23.unknown().optional(),after:z23.unknown().optional()})).max(20)})).max(200),labels:z23.array(z23.object({key:z23.string().min(1).max(512),locale:z23.string().min(1).max(64).optional(),before:z23.unknown().nullable(),after:z23.unknown().nullable()})).max(200),assets:z23.array(z23.object({key:z23.string().min(1).max(512),name:z23.string().min(1).max(512),verb:z23.enum(["added","modified","deleted"]),before:AssetSnapshotSchema.nullable(),after:AssetSnapshotSchema.nullable()})).max(200).default([])}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),SessionErrorCodeSchema=z23.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid"])}});import{z as z24}from"zod";var AgentBranchClassificationSchema,AgentBranchDecidedPathSchema,WorkSessionReviewSchema,RequestWorkSessionReviewSchema,WorkSessionReviewResultSchema,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();init_env_status_dto();AgentBranchClassificationSchema=z24.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z24.enum(["auto-merge","review-merged","review-discarded"]),WorkSessionReviewSchema=z24.object({sessionId:z24.uuid(),branch:z24.string().min(1),targetBranch:z24.string().min(1),revision:z24.string().min(1),fingerprint:z24.string().min(1),source:z24.enum(["studio","slack","mcp"]),threadId:z24.uuid().nullable(),invocationId:z24.uuid().nullable(),conversationBranch:z24.string().nullable(),capturedAt:z24.string(),surfaces:z24.array(PerSurfaceDeltaSchema).optional(),counts:z24.record(z24.string(),z24.number().int().nonnegative())}),RequestWorkSessionReviewSchema=z24.strictObject({sessionId:z24.uuid(),summary:z24.string().trim().min(1).max(240),targetBranch:z24.string().trim().min(1).optional()}),WorkSessionReviewResultSchema=z24.object({requested:z24.literal(!0),alreadyRequested:z24.boolean(),reviewId:z24.uuid(),reviewUrl:z24.url(),status:z24.literal("pending"),sessionId:z24.uuid(),branch:z24.string(),targetBranch:z24.string(),revision:z24.string(),savedRevision:z24.string(),fingerprint:z24.string(),visibility:z24.literal("user-visible"),retention:z24.literal("durable"),expiresAt:z24.null(),merged:z24.literal(!1),published:z24.literal(!1),links:z24.object({preview:z24.url(),changes:z24.url(),conversation:z24.url().nullable()})}),AgentBranchProposalDTOSchema=z24.object({id:z24.uuid(),envId:z24.uuid(),sessionId:z24.uuid().nullable(),skillName:z24.string().min(1),classification:AgentBranchClassificationSchema,rationale:z24.string().nullable(),summary:z24.string().nullable(),surfaceDeltas:z24.record(z24.string(),z24.unknown()),review:WorkSessionReviewSchema.optional(),createdAt:z24.coerce.date(),decidedAt:z24.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z24.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z24.object({path:z24.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z24.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z24.object({code:z24.literal("merge_conflict"),message:z24.string(),conflicts:z24.record(z24.string(),z24.number().int().nonnegative())})}});import{z as z25}from"zod";var AGENT_QUESTION_STATES,AgentQuestionStateSchema,AgentQuestionFormSchema,AgentQuestionAskSchema,AgentQuestionRequestSchema,AgentQuestionSchema,AgentQuestionResponseSchema,RunAgentQuestionResponseSchema,AgentQuestionAttentionSchema,OpenAgentQuestionsResponseSchema,AnswerAgentQuestionResultSchema,AnswerAgentQuestionResponseSchema,init_agent_question_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-question.dto.js"(){"use strict";init_chat_block();init_response();AGENT_QUESTION_STATES=["open","answered","expired","cancelled","superseded"],AgentQuestionStateSchema=z25.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z25.string().trim().min(1).max(80)}).superRefine((form,ctx)=>{(!form.steps.every(step=>step.id)||new Set(form.steps.map(step=>step.id)).size!==form.steps.length)&&ctx.addIssue({code:"custom",path:["steps"],message:"Every question step needs its own stable id."})}),AgentQuestionAskSchema=z25.object({description:z25.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z25.literal(QUESTION_FORM_CONTRACT_VERSION),sessionIds:z25.array(z25.uuid()).optional()}),AgentQuestionSchema=z25.object({id:z25.uuid(),projectId:z25.uuid(),threadId:z25.uuid(),invocationId:z25.uuid(),agentKey:z25.string().min(1).max(120),anchorEnv:z25.string().min(1).max(64),retainedEnv:z25.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z25.string().min(1).nullable(),continuationInvocationId:z25.uuid().nullable(),askedAt:z25.coerce.date(),expiresAt:z25.coerce.date(),closedAt:z25.coerce.date().nullable()}),AgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z25.object({questionId:z25.uuid(),invocationId:z25.uuid(),askedAt:z25.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema(z25.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z25.object({question:AgentQuestionSchema,continuationInvocationId:z25.uuid(),deduped:z25.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema(AnswerAgentQuestionResultSchema)}});import{z as z26}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,IntegrationToolEffectSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,ProjectIntegrationConnectionDTOSchema,ProjectIntegrationConnectionDTO,McpHeaderNameSchema,McpHeaderDefinitionSchema,McpSecretMapSchema,ConnectOrganizationIntegrationRequestSchema,ProjectIntegrationReturnPathSchema,IntegrationCustomIdentitySchema,ConnectProjectIntegrationRequestSchema,McpIntegrationAuthSchema,McpIntegrationSetupAuthSchema,AddProjectMcpIntegrationRequestSchema,AddProjectMcpIntegrationResponseBaseSchema,AddProjectMcpIntegrationResponseSchema,ReusableMcpServerAuthKindSchema,ReusableMcpServerDTOSchema,ReusableMcpServerDTO,SearchReusableMcpServersQuerySchema,ReuseProjectMcpIntegrationRequestSchema,LinearOAuthApplicationDistributionSchema,OrganizationLinearAppDTOSchema,OrganizationLinearAppDTO,CreateManagedLinearAppRequestSchema,UpdateManagedLinearAppRequestSchema,StartManagedLinearConnectRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,ProjectIntegrationConnectResponseSchema,BindProjectChannelRequestSchema,ListProjectChannelsQuerySchema,SearchProjectChannelsQuerySchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,ProjectChannelCandidateAvailabilitySchema,ProjectChannelCandidateDTOSchema,ProjectChannelCandidateDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlDeveloperSearchToolInputSchema,FirecrawlResearchSearchToolInputSchema,FirecrawlResearchPaperToolInputSchema,FirecrawlResearchRelatedToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorScrapeOptionsInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorUpdateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolRequestSchema,ProjectIntegrationToolRunUsageSchema,ProjectIntegrationToolRunBillingSchema,FirecrawlScrapeToolOutputSchema,FirecrawlSearchToolOutputSchema,FirecrawlResearchPaperSchema,FirecrawlResearchPassageSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlMonitorScheduleOutputSchema,FirecrawlMonitorTargetOutputSchema,FirecrawlMonitorOutputSchema,FirecrawlMonitorCheckOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema,FirecrawlToolKeySchema,FirecrawlToolOutputSchema,ProjectIntegrationToolRunBaseSchema,ProjectIntegrationToolRunDTOSchema,ProjectIntegrationToolRunDTO,IntegrationsListResponseSchema,IntegrationInfoResponseSchema,ProjectIntegrationStatusResponseSchema,ProjectIntegrationInstallationResponseSchema,ProjectIntegrationToolRunResponseSchema,StartProjectIntegrationConnectResponseResponseSchema,OrganizationIntegrationConnectionResponseSchema,ProjectIntegrationConnectionsResponseSchema,ProjectIntegrationConnectResponseResponseSchema,AddProjectMcpIntegrationResponseResponseSchema,ReusableMcpServersResponseSchema,ProjectChannelBindingResponseSchema,ProjectChannelBindingsResponseSchema,ProjectChannelCandidatesResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z26.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z26.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z26.enum(["secret_text"]),IntegrationCredentialUsageSchema=z26.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z26.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z26.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z26.object({mode:IntegrationAuthModeSchema,label:z26.string().min(1),description:z26.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z26.object({id:z26.string().min(1),label:z26.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z26.boolean()}),IntegrationToolDefinitionDTOSchema=z26.object({key:z26.string().min(1),name:z26.string().min(1),description:z26.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z26.object({title:z26.string().min(1),description:z26.string().min(1),command:z26.string().min(1).optional()}),IntegrationInfoDTOSchema=z26.object({key:z26.string().min(1),name:z26.string().min(1),summary:z26.string().min(1),type:z26.enum(["native","mcp"]).optional(),url:z26.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z26.array(IntegrationAuthModeDTOSchema),credentials:z26.array(IntegrationCredentialDefinitionDTOSchema),tools:z26.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z26.enum(["available","unavailable"]).optional(),connectionCapabilities:z26.object({customIdentityCreation:z26.boolean()}).optional(),recipes:z26.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z26.object({projectId:z26.uuid(),integrationKey:z26.string().min(1),name:z26.string().min(1),summary:z26.string().min(1),installed:z26.boolean(),enabled:z26.boolean(),setupState:z26.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z26.string().nullable(),connectionId:z26.uuid().nullable().optional(),connectionAlias:z26.string().min(1).nullable().optional(),connectionStatus:z26.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z26.array(z26.string()),installedAt:z26.coerce.date().nullable(),updatedAt:z26.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z26.object({id:z26.uuid(),projectId:z26.uuid(),integrationKey:z26.string().min(1),enabled:z26.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z26.string(),connectionId:z26.uuid().nullable().optional(),connectionAlias:z26.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z26.array(z26.string()),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z26.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z26.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z26.object({authMode:IntegrationAuthModeSchema}),OrganizationIntegrationConnectionStatusSchema=z26.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z26.object({id:z26.uuid(),organizationId:z26.string().min(1),integrationKey:z26.string().min(1),registrationId:z26.uuid().nullable(),alias:z26.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z26.string().min(1),externalAccountName:z26.string().nullable(),externalBotUserId:z26.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z26.array(z26.string()),connectedAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionDTOSchema=OrganizationIntegrationConnectionDTOSchema.extend({granted:z26.boolean(),isDefault:z26.boolean()}),ProjectIntegrationConnectionDTO=createDTO(ProjectIntegrationConnectionDTOSchema),McpHeaderNameSchema=z26.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z26.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z26.record(McpHeaderNameSchema,z26.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z26.object({alias:z26.string().min(1).max(120).optional(),token:z26.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z26.boolean().optional()}).superRefine((value,ctx)=>{value.token&&value.secrets&&ctx.addIssue({code:"custom",path:["token"],message:"Provide either one token or a complete MCP secret map."})}),ProjectIntegrationReturnPathSchema=z26.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),IntegrationCustomIdentitySchema=z26.object({displayName:z26.string().trim().min(1).max(35),backgroundColor:z26.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),iconUrl:z26.string().url().max(2048).optional()}),ConnectProjectIntegrationRequestSchema=z26.discriminatedUnion("mode",[z26.object({mode:z26.literal("personal"),alias:z26.string().min(1).max(120),token:z26.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z26.boolean().optional()}),z26.object({mode:z26.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z26.boolean().optional(),registrationId:z26.uuid().optional(),customIdentity:IntegrationCustomIdentitySchema.optional()})]).superRefine((value,ctx)=>{value.mode==="oauth"&&value.registrationId&&value.customIdentity&&ctx.addIssue({code:"custom",path:["registrationId"],message:"Choose an existing app identity or create a custom one, not both."}),value.mode==="personal"&&!!value.token==!!value.secrets&&ctx.addIssue({code:"custom",path:["token"],message:"Provide either one token or a complete MCP secret map."})}),McpIntegrationAuthSchema=z26.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z26.union([z26.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z26.object({type:z26.literal("mcp"),name:z26.string().trim().min(1).max(120),url:z26.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z26.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z26.string().min(1).optional()}).superRefine((value,ctx)=>{let protocol;try{protocol=new URL(value.url).protocol}catch{return}protocol!=="https:"&&ctx.addIssue({code:"custom",path:["url"],message:"MCP servers must use HTTPS."});let hasSingleHeader=!!(value.headerName||value.token),hasHeaderBundle=!!(value.headers||value.secrets);if(value.auth==="auto"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Automatic authentication does not accept manual credentials."}),value.auth==="none"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Public MCP servers cannot define credentials."}),value.auth==="bearer"&&(value.token||ctx.addIssue({code:"custom",path:["token"],message:"Bearer authentication requires a token."}),(value.headerName||value.headers||value.secrets)&&ctx.addIssue({code:"custom",path:["headers"],message:"Custom headers only apply to header authentication."})),value.auth!=="header")return;if(hasSingleHeader&&hasHeaderBundle){ctx.addIssue({code:"custom",path:["headers"],message:"Use either the single-header fields or headers with a complete secret map."});return}if(hasSingleHeader){value.headerName||ctx.addIssue({code:"custom",path:["headerName"],message:"Custom header authentication needs a header name."}),value.token||ctx.addIssue({code:"custom",path:["token"],message:"Header authentication requires a complete header value."});return}if(!value.headers){ctx.addIssue({code:"custom",path:["headers"],message:"Header authentication needs at least one header."});return}let normalizedNames=value.headers.map(header=>header.name.toLowerCase());if(new Set(normalizedNames).size!==normalizedNames.length&&ctx.addIssue({code:"custom",path:["headers"],message:"MCP header names must be unique."}),!value.secrets){ctx.addIssue({code:"custom",path:["secrets"],message:"Header authentication needs a complete secret map."});return}let secretNames=Object.keys(value.secrets).map(name=>name.toLowerCase());if(new Set(secretNames).size!==secretNames.length){ctx.addIssue({code:"custom",path:["secrets"],message:"MCP secret names must be unique."});return}let expected=new Set(normalizedNames),actual=new Set(secretNames);(expected.size!==actual.size||[...expected].some(name=>!actual.has(name)))&&ctx.addIssue({code:"custom",path:["secrets"],message:"The MCP secret map must exactly cover the configured headers."})}),AddProjectMcpIntegrationResponseBaseSchema=z26.object({integrationKey:z26.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z26.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z26.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z26.literal("oauth"),connectUrl:z26.string().url(),expiresAt:z26.coerce.date()})]),ReusableMcpServerAuthKindSchema=z26.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z26.object({id:z26.uuid(),name:z26.string().min(1),host:z26.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z26.string().min(1),availability:z26.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z26.object({query:z26.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z26.object({serverId:z26.uuid()}),LinearOAuthApplicationDistributionSchema=z26.enum(["private","public"]),OrganizationLinearAppDTOSchema=z26.object({id:z26.uuid(),displayName:z26.string().min(1),description:z26.string().nullable(),iconUrl:z26.string().nullable(),distribution:LinearOAuthApplicationDistributionSchema,status:z26.enum(["active","revoked"]),connectionIds:z26.array(z26.uuid()),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),OrganizationLinearAppDTO=createDTO(OrganizationLinearAppDTOSchema),CreateManagedLinearAppRequestSchema=z26.object({appName:z26.string().trim().min(2).max(80),description:z26.string().trim().max(1e3).optional(),iconUrl:z26.string().url().max(2048).optional()}),UpdateManagedLinearAppRequestSchema=CreateManagedLinearAppRequestSchema.partial().refine(input=>Object.keys(input).length>0,"At least one Linear app field is required."),StartManagedLinearConnectRequestSchema=z26.object({projectId:z26.uuid(),registrationId:z26.uuid(),returnTo:ProjectIntegrationReturnPathSchema.optional()}),StartProjectIntegrationConnectResponseSchema=z26.object({integrationKey:z26.string().min(1),connectUrl:z26.string().url(),expiresAt:z26.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z26.discriminatedUnion("mode",[z26.object({mode:z26.literal("personal"),integrationKey:z26.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z26.object({mode:z26.literal("oauth"),integrationKey:z26.string().min(1),connectUrl:z26.string().url(),expiresAt:z26.coerce.date()})]),BindProjectChannelRequestSchema=z26.object({ref:z26.string().min(1),connectionAlias:z26.string().min(1).optional(),agentName:z26.string().min(1).max(160).nullable().optional(),force:z26.boolean().optional()}),ListProjectChannelsQuerySchema=z26.object({integrationKey:z26.string().min(1)}),SearchProjectChannelsQuerySchema=z26.object({integrationKey:z26.string().min(1),connectionAlias:z26.string().min(1),query:z26.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z26.object({id:z26.uuid(),projectId:z26.uuid(),integrationKey:z26.string().min(1),connectionId:z26.uuid(),externalWorkspaceId:z26.string().min(1),externalChannelId:z26.string().min(1),externalChannelName:z26.string().nullable(),agentName:z26.string().nullable(),enabled:z26.boolean(),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z26.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z26.object({id:z26.string().min(1),name:z26.string().min(1),visibility:z26.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z26.string().min(1).nullable(),canMove:z26.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z26.object({markdown:z26.boolean().optional(),summary:z26.boolean().optional(),links:z26.boolean().optional(),branding:z26.boolean().optional(),images:z26.boolean().optional(),html:z26.union([z26.literal("cleaned"),z26.literal("raw"),z26.boolean()]).optional(),json:z26.union([z26.boolean(),z26.object({prompt:z26.string().min(1).max(1e4),schema:z26.record(z26.string(),z26.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z26.object({url:z26.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z26.boolean().optional(),timeoutMs:z26.number().int().positive().max(12e4).optional(),waitForMs:z26.number().int().min(0).max(3e4).optional(),maxAgeMs:z26.number().int().min(0).optional(),minAgeMs:z26.number().int().min(0).optional(),storeInCache:z26.boolean().optional(),proxy:z26.enum(["basic","enhanced","auto"]).optional(),mobile:z26.boolean().optional(),location:z26.object({country:z26.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z26.array(z26.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z26.object({query:z26.string().min(1),maxResults:z26.number().int().positive().max(20).optional(),sources:z26.array(z26.enum(["web","news","images"])).min(1).max(3).optional(),categories:z26.array(z26.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z26.array(z26.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z26.array(z26.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z26.enum(["hour","day","week","month","year"]).optional(),location:z26.string().min(1).max(160).optional(),country:z26.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z26.boolean().optional(),timeoutMs:z26.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z26.object({query:z26.string().min(1).max(500),maxResults:z26.number().int().min(1).max(100).optional(),types:z26.array(z26.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z26.array(z26.string().min(1).max(512)).min(1).max(20).optional(),sources:z26.array(z26.string().min(1).max(512)).min(1).max(20).optional(),passages:z26.number().int().min(1).max(5).optional(),skills:z26.literal("only").optional(),language:z26.string().min(1).optional(),topic:z26.string().min(1).optional(),license:z26.string().min(1).optional(),minStars:z26.number().int().min(0).optional(),maxStars:z26.number().int().min(0).optional(),archived:z26.boolean().optional(),fork:z26.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z26.object({query:z26.string().min(1).max(500),maxResults:z26.number().int().min(1).max(500).optional(),authors:z26.array(z26.string().min(1)).min(1).optional(),categories:z26.array(z26.string().min(1)).min(1).optional(),from:z26.iso.date().optional(),to:z26.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z26.object({paperId:z26.string().min(1).max(512),query:z26.string().min(1).max(500).optional(),maxPassages:z26.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z26.object({paperId:z26.string().min(1).max(512),intent:z26.string().min(1).max(500),mode:z26.enum(["similar","citers","references"]).optional(),maxResults:z26.number().int().min(1).max(500).optional(),rerank:z26.boolean().optional(),anchors:z26.array(z26.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z26.object({url:z26.string().url(),search:z26.string().min(1).optional(),limit:z26.number().int().positive().max(200).optional(),includeSubdomains:z26.boolean().optional(),timeoutMs:z26.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z26.object({url:z26.string().url(),limit:z26.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z26.boolean().optional(),timeoutMs:z26.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z26.object({text:z26.string().min(1).max(200).optional(),cron:z26.string().min(1).max(120).optional(),timezone:z26.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z26.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z26.boolean().optional(),timeoutMs:z26.number().int().positive().max(12e4).optional(),waitForMs:z26.number().int().min(0).max(3e4).optional(),maxAgeMs:z26.number().int().min(0).optional(),minAgeMs:z26.number().int().min(0).optional(),storeInCache:z26.boolean().optional(),proxy:z26.enum(["basic","enhanced","auto"]).optional(),mobile:z26.boolean().optional(),location:z26.object({country:z26.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z26.array(z26.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z26.union([z26.object({type:z26.enum(["scrape","crawl"]).default("scrape"),urls:z26.array(z26.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z26.object({type:z26.literal("search"),queries:z26.array(z26.string().min(1).max(256)).min(1).max(12),searchWindow:z26.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z26.number().int().min(1).max(50).optional(),includeDomains:z26.array(z26.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z26.array(z26.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z26.object({name:z26.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z26.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z26.string().min(1).max(2e3).optional(),judgeEnabled:z26.boolean().optional(),retentionDays:z26.number().int().min(1).max(365).optional(),notification:z26.object({email:z26.object({enabled:z26.boolean().default(!0),recipients:z26.array(z26.string().email()).min(1).max(20),includeDiffs:z26.boolean().optional()}).optional()}).optional()}).refine(value=>!value.targets.some(target=>target.type==="search")||value.judgeEnabled===!1||!!value.goal,{message:"Search monitor targets require goal unless judgeEnabled is false."}),FirecrawlMonitorUpdateToolInputSchema=z26.object({monitorId:z26.string().uuid(),name:z26.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z26.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z26.string().min(1).max(2e3).optional(),judgeEnabled:z26.boolean().optional(),retentionDays:z26.number().int().min(1).max(365).optional(),status:z26.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z26.object({monitorId:z26.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z26.string().uuid()}),RunProjectIntegrationToolRequestSchema=z26.object({tool:z26.string().min(1),input:z26.record(z26.string(),z26.unknown()),connectionAlias:z26.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z26.object({provider:z26.string().min(1),providerCredits:z26.number().nonnegative().optional(),providerCostUsd:z26.number().nonnegative().optional(),requests:z26.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z26.object({credits:z26.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z26.object({url:z26.string(),provider:z26.literal("firecrawl"),title:z26.string().optional(),statusCode:z26.number().optional(),markdown:z26.string().optional(),summary:z26.string().optional(),links:z26.array(z26.string()).optional(),images:z26.array(z26.string()).optional(),html:z26.string().optional(),json:z26.unknown().optional(),branding:z26.record(z26.string(),z26.unknown()).optional(),warning:z26.string().optional()}),FirecrawlSearchToolOutputSchema=z26.object({query:z26.string(),provider:z26.literal("firecrawl"),warning:z26.string().optional(),results:z26.array(z26.object({title:z26.string(),url:z26.string(),snippet:z26.string().optional(),content:z26.string().optional(),score:z26.number().optional(),publishedAt:z26.string().optional()}))}),FirecrawlResearchPaperSchema=z26.object({paperId:z26.string(),primaryId:z26.string().optional(),ids:z26.record(z26.string(),z26.array(z26.string())).optional(),title:z26.string().optional(),abstract:z26.string().optional(),score:z26.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z26.object({text:z26.string(),score:z26.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),results:z26.array(z26.object({id:z26.string(),type:z26.string().min(1).optional(),url:z26.string(),title:z26.string().optional(),passages:z26.array(z26.object({text:z26.string()}).passthrough())}).passthrough()),coverage:z26.record(z26.string(),z26.string()).optional(),reranked:z26.boolean().optional(),repos:z26.array(z26.record(z26.string(),z26.unknown())).optional(),sources:z26.array(z26.record(z26.string(),z26.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),results:z26.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),paper:z26.record(z26.string(),z26.unknown()),paperId:z26.string().optional(),query:z26.string().optional(),passages:z26.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),results:z26.array(FirecrawlResearchPaperSchema),poolSize:z26.number().int().nonnegative(),truncated:z26.boolean(),note:z26.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z26.object({url:z26.string(),provider:z26.literal("firecrawl"),count:z26.number(),links:z26.array(z26.object({url:z26.string(),title:z26.string().optional(),description:z26.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z26.object({url:z26.string(),provider:z26.literal("firecrawl"),total:z26.number(),pages:z26.array(z26.object({url:z26.string(),title:z26.string().optional(),statusCode:z26.number().optional(),markdown:z26.string().optional(),summary:z26.string().optional(),links:z26.array(z26.string()).optional(),images:z26.array(z26.string()).optional(),html:z26.string().optional(),warning:z26.string().optional()})),warning:z26.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z26.object({cron:z26.string().optional(),text:z26.string().optional(),timezone:z26.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z26.object({id:z26.string().optional(),type:z26.enum(["scrape","crawl","search"]).optional(),urls:z26.array(z26.string()).optional(),queries:z26.array(z26.string()).optional(),searchWindow:z26.string().optional(),maxResults:z26.number().optional(),includeDomains:z26.array(z26.string()).optional(),excludeDomains:z26.array(z26.string()).optional(),scrapeOptions:z26.record(z26.string(),z26.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z26.object({id:z26.string(),name:z26.string(),status:z26.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z26.string().nullable().optional(),lastRunAt:z26.string().nullable().optional(),currentCheckId:z26.string().nullable().optional(),targets:z26.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z26.string().nullable().optional(),judgeEnabled:z26.boolean().optional(),estimatedCreditsPerMonth:z26.number().optional(),createdAt:z26.string().optional(),updatedAt:z26.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z26.object({id:z26.string(),monitorId:z26.string(),scheduledFor:z26.string().nullable().optional(),startedAt:z26.string().nullable().optional(),finishedAt:z26.string().nullable().optional(),estimatedCredits:z26.number().nullable().optional(),reservedCredits:z26.number().nullable().optional(),actualCredits:z26.number().nullable().optional(),billingStatus:z26.string().nullable().optional(),summary:z26.object({totalPages:z26.number().optional(),same:z26.number().optional(),changed:z26.number().optional(),new:z26.number().optional(),removed:z26.number().optional(),error:z26.number().optional()}).passthrough().optional(),error:z26.string().nullable().optional(),createdAt:z26.string().optional(),updatedAt:z26.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),monitors:z26.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),monitorId:z26.string(),deleted:z26.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),monitorId:z26.string(),checks:z26.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),monitorId:z26.string(),check:FirecrawlMonitorCheckOutputSchema,next:z26.string().optional()}),FirecrawlToolKeySchema=z26.enum(["search","developer.search","research.search","research.paper","research.related","scrape","map","crawl","monitor.create","monitor.update","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z26.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z26.object({projectId:z26.uuid(),integrationKey:z26.string().min(1),tool:z26.string().min(1),connectionAlias:z26.string().min(1).nullable().optional(),output:z26.record(z26.string(),z26.unknown()),executedAt:z26.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z26.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z26.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z26.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z26.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z26.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z26.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z26.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z26.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z26.array(ProjectIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema(z26.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z26.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z26.array(ProjectChannelCandidateDTOSchema))}});import{z as z27}from"zod";var SCHEDULE_NOTIFICATION_TOPICS,ScheduleNotificationTopicSchema,USER_MANAGED_NOTIFICATION_TOPICS,UserManagedNotificationTopicSchema,MAX_SCHEDULE_SUBSCRIBERS,ScheduleSubscriberDeliveryStateSchema,ScheduleSubscriberCandidateSchema,ScheduleNotificationSettingsSchema,ScheduleNotificationSettingsResponseSchema,UpdateScheduleSubscribersRequestSchema,UserNotificationPreferenceSchema,SCHEDULE_OPT_OUT_LINK_ACTIONS,ScheduleOptOutLinkActionSchema,SCHEDULE_OPT_OUT_ACTIONS,ScheduleOptOutActionSchema,ScheduleOptOutStateSchema,ScheduleOptOutResponseSchema,FollowedScheduleSchema,FollowedSchedulesSchema,FollowedSchedulesResponseSchema,init_schedule_notifications_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule-notifications.dto.js"(){"use strict";init_response();SCHEDULE_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],ScheduleNotificationTopicSchema=z27.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],UserManagedNotificationTopicSchema=z27.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z27.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z27.object({userId:z27.string().min(1),name:z27.string(),email:z27.string().min(1),subscribed:z27.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z27.object({maxSubscribers:z27.number().int().positive(),subscriberCount:z27.number().int().nonnegative(),effectiveRecipientCount:z27.number().int().nonnegative(),currentUserSubscribed:z27.boolean(),candidates:z27.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z27.object({userIds:z27.array(z27.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z27.object({topic:UserManagedNotificationTopicSchema,enabled:z27.boolean(),source:z27.enum(["default","explicit"])}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z27.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z27.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z27.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z27.string().nullable(),maskedEmail:z27.string().min(1),applied:z27.boolean(),expiresAt:z27.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z27.object({scheduleId:z27.string().min(1),scheduleName:z27.string(),projectId:z27.string().min(1),projectName:z27.string(),env:z27.string().min(1)}),FollowedSchedulesSchema=z27.object({schedules:z27.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z28}from"zod";var PROJECT_SECRET_KEY_PATTERN,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN,RESERVED_PROJECT_SECRET_KEYS,ProjectSecretKeySchema,ProjectScheduleStatusSchema,ProjectScheduleDTOSchema,ProjectScheduleDTO,CreateProjectScheduleRequestSchema,UpdateProjectScheduleRequestSchema,ProjectScheduleRunStatusSchema,ProjectScheduleRunTriggerSchema,ProjectScheduleRunSecretSnapshotStateSchema,ProjectScheduleRunSecretResolutionSchema,ProjectSchedulePolicySchema,SchedulePolicyStateSchema,ProjectSchedulePlanSnapshotSchema,ProjectScheduleUsageSchema,ProjectScheduleRunDTOSchema,ProjectScheduleRunDTO,ProjectScheduleRunSecretSnapshotSchema,ProjectScheduleRunDetailDTOSchema,ProjectScheduleRunDetailDTO,RunProjectScheduleRequestSchema,ProjectScheduleRunsQuerySchema,ProjectScheduleResponseSchema,ProjectSchedulesListDataSchema,ProjectSchedulesListResponseSchema,ProjectSchedulesOverviewResponseSchema,ProjectScheduleDetailDataSchema,ProjectScheduleDetailResponseSchema,ProjectScheduleRunsPageSchema,ProjectScheduleRunsResponseSchema,ProjectScheduleRunResponseSchema,ProjectScheduleRunDetailResponseSchema,init_schedule_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();init_schedule_notifications_dto();PROJECT_SECRET_KEY_PATTERN=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN=/^(PUBLIC_|VITE_|NEXT_PUBLIC_|NUXT_PUBLIC_)/,RESERVED_PROJECT_SECRET_KEYS=new Set([...FIMO_MANAGED_PROJECT_ENV_KEYS,"FIMO_SCHEDULE_ID","FIMO_SCHEDULE_RUN_ID","FIMO_SCHEDULE_NAME"]),ProjectSecretKeySchema=z28.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=z28.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z28.uuid(),env:z28.string().min(1),name:z28.string().min(1),cron:z28.string().min(1),command:z28.string().min(1),secretKeys:z28.array(z28.string().min(1)),enabled:z28.boolean(),lastRunAt:z28.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z28.string().nullable(),suspendedAt:z28.coerce.date().nullable().optional(),suspensionReason:z28.string().nullable().optional(),overPolicyReasons:z28.array(z28.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z28.object({name:z28.string().min(1).max(120),cron:z28.string().min(1).max(120),command:z28.string().min(1).max(500),secretKeys:z28.array(ProjectSecretKeySchema).default([]),enabled:z28.boolean().optional()}),UpdateProjectScheduleRequestSchema=z28.object({name:z28.string().min(1).max(120).optional(),cron:z28.string().min(1).max(120).optional(),command:z28.string().min(1).max(500).optional(),secretKeys:z28.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z28.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z28.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z28.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z28.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z28.object({maxRuns:z28.number().int().positive(),retentionDays:z28.number().int().positive().nullable(),outputRetentionDays:z28.number().int().positive(),maxOutputBytes:z28.number().int().positive()}),SchedulePolicyStateSchema=z28.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z28.object({code:z28.enum(["Free","PAYG","Premium","Pro"]),source:z28.enum(["cached_subscription","free_fallback"]),activeSchedules:z28.object({used:z28.number().int().nonnegative(),limit:z28.number().int().nonnegative()}),minCadenceMinutes:z28.number().int().positive(),maxRunMs:z28.number().int().positive(),concurrency:z28.object({used:z28.number().int().nonnegative(),limit:z28.number().int().positive()}),compute:z28.object({settledMs:z28.number().int().nonnegative(),activeMs:z28.number().int().nonnegative(),reservedMs:z28.number().int().nonnegative().optional(),includedMs:z28.number().int().nonnegative(),remainingMs:z28.number().int().nonnegative(),resetsAt:z28.coerce.date()}),upgrade:z28.object({code:z28.literal("Pro"),activeSchedulesLimit:z28.number().int().positive(),minCadenceMinutes:z28.number().int().positive(),maxRunMs:z28.number().int().positive(),maxConcurrentRuns:z28.number().int().positive(),computeIncludedMs:z28.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z28.array(z28.string())}),ProjectScheduleUsageSchema=z28.object({runCount:z28.number().int().nonnegative(),runsWithOutput:z28.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z28.object({id:z28.uuid(),scheduleId:z28.uuid(),projectId:z28.uuid(),env:z28.string().min(1),scheduleName:z28.string().min(1),command:z28.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z28.object({id:z28.string().min(1),name:z28.string().min(1)}).nullable(),queuedAt:z28.coerce.date(),startedAt:z28.coerce.date().nullable(),finishedAt:z28.coerce.date().nullable(),exitCode:z28.number().int().nullable(),errorCode:z28.string().nullable(),error:z28.string().nullable(),outputBytes:z28.number().int().nonnegative(),outputTruncated:z28.boolean(),outputExpiresAt:z28.coerce.date().nullable(),metadataExpiresAt:z28.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z28.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z28.coerce.date().nullable(),items:z28.array(z28.object({key:z28.string().min(1),updatedAt:z28.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z28.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z28.object({trigger:z28.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z28.object({limit:z28.coerce.number().int().min(1).max(100).default(25),cursor:z28.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z28.object({items:z28.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z28.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z28.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z28.object({items:z28.array(ProjectScheduleRunDTOSchema),nextCursor:z28.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z29}from"zod";var WORK_NOTIFICATION_TOPICS,WorkNotificationTopicSchema,PUBLICATION_NOTIFICATION_TOPICS,NOTIFICATION_TOPICS,NotificationTopicSchema,NOTIFICATION_DELIVERY_CADENCES,NotificationDeliveryCadenceSchema,NOTIFICATION_CHANNELS,NotificationChannelSchema,NOTIFICATION_ACTOR_KINDS,NotificationActorKindSchema,NotificationActorSchema,NotificationSummarySchema,ReportBriefPayloadSchema,NotificationRunOutcomeSchema,NotificationRetainedReasonSchema,NotificationWorkSessionSchema,NotificationPayloadSchema,NotificationEnvelopeSchema,NotificationDeliveryStateSchema,NotificationDeliverySchema,NotificationPreferenceSchema,init_notification_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/notification.dto.js"(){"use strict";init_agent_report();WORK_NOTIFICATION_TOPICS=["agent_run_outcome","agent_retained_review","agent_conflict"],WorkNotificationTopicSchema=z29.enum(WORK_NOTIFICATION_TOPICS),PUBLICATION_NOTIFICATION_TOPICS=["publication_failed"],NOTIFICATION_TOPICS=[...WORK_NOTIFICATION_TOPICS,...PUBLICATION_NOTIFICATION_TOPICS],NotificationTopicSchema=z29.enum(NOTIFICATION_TOPICS),NOTIFICATION_DELIVERY_CADENCES=["immediate","daily","off"],NotificationDeliveryCadenceSchema=z29.enum(NOTIFICATION_DELIVERY_CADENCES),NOTIFICATION_CHANNELS=["email"],NotificationChannelSchema=z29.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z29.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z29.discriminatedUnion("kind",[z29.object({kind:z29.literal("user"),userId:z29.string().min(1)}).strict(),z29.object({kind:z29.literal("agent"),agentKey:z29.string().min(1).max(120),agentId:z29.uuid().optional()}).strict(),z29.object({kind:z29.literal("system")}).strict()]),NotificationSummarySchema=z29.string().trim().min(1).max(1200),ReportBriefPayloadSchema={title:z29.string().trim().min(1).max(120).optional(),brief:StoredReportBriefSchema.optional()},NotificationRunOutcomeSchema=z29.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z29.enum(["review","agent_requested","recovery"]),NotificationWorkSessionSchema=z29.object({sessionId:z29.uuid(),branch:z29.string().min(1),targetBranch:z29.string().min(1),revision:z29.string().min(1),fingerprint:z29.string().min(1)}),NotificationPayloadSchema=z29.discriminatedUnion("topic",[z29.object({topic:z29.literal("agent_run_outcome"),threadId:z29.uuid(),invocationId:z29.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z29.object({topic:z29.literal("agent_retained_review"),threadId:z29.uuid().optional(),invocationId:z29.uuid().optional(),proposalId:z29.uuid().optional(),workSession:NotificationWorkSessionSchema.optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z29.object({topic:z29.literal("agent_conflict"),mergeId:z29.uuid(),threadId:z29.uuid().optional(),invocationId:z29.uuid().optional(),summary:NotificationSummarySchema.optional(),...ReportBriefPayloadSchema}).strict(),z29.object({topic:z29.literal("publication_failed"),publicationId:z29.uuid(),sourceBranch:z29.string().trim().min(1).max(120),failureCode:z29.string().trim().min(1).max(64),failedAt:z29.iso.datetime(),firstPublication:z29.boolean()}).strict()]),NotificationEnvelopeSchema=z29.object({id:z29.uuid(),projectId:z29.uuid(),sourceKey:z29.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z29.literal(1),payload:NotificationPayloadSchema,createdAt:z29.coerce.date()}),NotificationDeliveryStateSchema=z29.enum(["pending","deferred","sent","suppressed","failed"]),NotificationDeliverySchema=z29.object({id:z29.uuid(),notificationRecipientId:z29.uuid(),projectId:z29.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z29.number().int().nonnegative(),nextAttemptAt:z29.coerce.date().nullable(),lastAttemptAt:z29.coerce.date().nullable(),sentAt:z29.coerce.date().nullable(),failureCode:z29.string().max(80).nullable(),createdAt:z29.coerce.date(),updatedAt:z29.coerce.date()}),NotificationPreferenceSchema=z29.object({topic:WorkNotificationTopicSchema,channel:z29.literal("email"),enabled:z29.boolean(),cadence:NotificationDeliveryCadenceSchema.exclude(["off"]),effectiveCadence:NotificationDeliveryCadenceSchema,source:z29.enum(["default","explicit"])})}});import{z as z30}from"zod";var NOTIFICATION_PREFERENCE_GROUPS,NotificationPreferenceGroupSchema,FIMO_TOGGLE_PREFERENCE_ENTRY_IDS,FimoTogglePreferenceEntryIdSchema,FIMO_DELIVERY_PREFERENCE_ENTRY_IDS,FimoDeliveryPreferenceEntryIdSchema,MARKETING_PREFERENCE_ENTRY_PREFIX,PreferenceSourceSchema,EmailNotificationProviderSyncSchema,EmailNotificationPreferenceSchema,PROVIDER_SUBSCRIPTION_PLACEMENTS,ProviderSubscriptionPlacementSchema,PROVIDER_SUBSCRIPTION_SEMANTIC_IDS,ProviderSubscriptionSemanticIdSchema,NotificationPreferenceEntrySchema,NotificationPreferenceCatalogSchema,NotificationPreferenceCatalogResponseSchema,NotificationPreferenceEntryResponseSchema,UpdateEmailNotificationPreferenceRequestSchema,EmailNotificationPreferenceResponseSchema,UpdateNotificationPreferenceEntryRequestSchema,init_notification_preference_catalog_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/notification-preference-catalog.dto.js"(){"use strict";init_response();init_notification_dto();NOTIFICATION_PREFERENCE_GROUPS=["work_review","publishing","schedule","marketing"],NotificationPreferenceGroupSchema=z30.enum(NOTIFICATION_PREFERENCE_GROUPS),FIMO_TOGGLE_PREFERENCE_ENTRY_IDS=["work_review.agent_conflict","publishing.publication_failed","schedule.schedule_health","schedule.schedule_compute_allowance"],FimoTogglePreferenceEntryIdSchema=z30.enum(FIMO_TOGGLE_PREFERENCE_ENTRY_IDS),FIMO_DELIVERY_PREFERENCE_ENTRY_IDS=["work_review.agent_retained_review","work_review.agent_run_outcome"],FimoDeliveryPreferenceEntryIdSchema=z30.enum(FIMO_DELIVERY_PREFERENCE_ENTRY_IDS),MARKETING_PREFERENCE_ENTRY_PREFIX="marketing.",PreferenceSourceSchema=z30.enum(["default","explicit"]),EmailNotificationProviderSyncSchema=z30.enum(["synced","pending","unavailable"]),EmailNotificationPreferenceSchema=z30.object({enabled:z30.boolean(),source:PreferenceSourceSchema,providerSync:EmailNotificationProviderSyncSchema}).strict(),PROVIDER_SUBSCRIPTION_PLACEMENTS=["reports","product_news"],ProviderSubscriptionPlacementSchema=z30.enum(PROVIDER_SUBSCRIPTION_PLACEMENTS),PROVIDER_SUBSCRIPTION_SEMANTIC_IDS=["weekly_analytics"],ProviderSubscriptionSemanticIdSchema=z30.enum(PROVIDER_SUBSCRIPTION_SEMANTIC_IDS),NotificationPreferenceEntrySchema=z30.discriminatedUnion("kind",[z30.object({kind:z30.literal("toggle"),id:FimoTogglePreferenceEntryIdSchema,group:z30.enum(["work_review","publishing","schedule"]),enabled:z30.boolean(),source:PreferenceSourceSchema}).strict(),z30.object({kind:z30.literal("delivery"),id:FimoDeliveryPreferenceEntryIdSchema,group:z30.literal("work_review"),cadence:NotificationDeliveryCadenceSchema,source:PreferenceSourceSchema}).strict(),z30.object({kind:z30.literal("provider_subscription"),id:z30.string().startsWith(MARKETING_PREFERENCE_ENTRY_PREFIX),group:z30.literal("marketing"),name:z30.string(),description:z30.string().nullable(),placement:ProviderSubscriptionPlacementSchema,semanticId:ProviderSubscriptionSemanticIdSchema.nullable(),enabled:z30.boolean(),source:PreferenceSourceSchema}).strict()]),NotificationPreferenceCatalogSchema=z30.object({email:EmailNotificationPreferenceSchema,entries:z30.array(NotificationPreferenceEntrySchema),unavailableGroups:z30.array(NotificationPreferenceGroupSchema)}),NotificationPreferenceCatalogResponseSchema=createResponseSchema(NotificationPreferenceCatalogSchema),NotificationPreferenceEntryResponseSchema=createResponseSchema(NotificationPreferenceEntrySchema),UpdateEmailNotificationPreferenceRequestSchema=z30.object({enabled:z30.boolean()}).strict(),EmailNotificationPreferenceResponseSchema=createResponseSchema(EmailNotificationPreferenceSchema),UpdateNotificationPreferenceEntryRequestSchema=z30.discriminatedUnion("kind",[z30.object({kind:z30.literal("toggle"),enabled:z30.boolean()}).strict(),z30.object({kind:z30.literal("delivery"),cadence:NotificationDeliveryCadenceSchema}).strict(),z30.object({kind:z30.literal("provider_subscription"),enabled:z30.boolean()}).strict()])}});import{z as z31}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=z31.object({surface:SurfaceNameSchema,key:z31.string(),label:z31.string()}),InlineSchema=z31.object({text:z31.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z31.discriminatedUnion("type",[z31.object({type:z31.literal("paragraph"),content:z31.array(InlineSchema).max(24)}),z31.object({type:z31.literal("preview"),ref:DiffRefSchema,caption:z31.string().optional()}),z31.object({type:z31.literal("code"),code:z31.string(),lang:z31.string().optional(),caption:z31.string().optional()}),z31.object({type:z31.literal("risk"),level:z31.enum(["warning","error"]),content:z31.array(InlineSchema).max(24)}),z31.object({type:z31.literal("list"),items:z31.array(z31.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z31.object({headline:z31.string(),blocks:z31.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z31.object({summary:EnvDiffSummarySchema,fingerprint:z31.string(),generatedAt:z31.coerce.date(),cached:z31.boolean().optional(),credits:z31.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z32}from"zod";var PROJECT_ANALYTICS_PRESETS,PROJECT_ANALYTICS_GROUP_BY_OPTIONS,ProjectDailyVisitorsDTOSchema,ProjectAnalyticsBreakdownItemDTOSchema,ProjectAnalyticsPageBreakdownItemDTOSchema,ProjectAnalyticsRangeDTOSchema,ProjectAnalyticsAnnotationDTOSchema,PROJECT_ANALYTICS_DEVICE_FILTERS,ProjectPageviewAnalyticsDTOSchema,PROJECT_ANALYTICS_TRACKING_STATES,ProjectAnalyticsTrackingStatusDTOSchema,ProjectPageviewAnalyticsDTO,ProjectAnalyticsTrackingStatusDTO,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=z32.object({date:z32.string(),visitors:z32.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z32.object({key:z32.string(),visitors:z32.number().int().nonnegative(),pageviews:z32.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z32.object({path:z32.string(),pageName:z32.string().nullable().optional(),visitors:z32.number().int().nonnegative(),pageviews:z32.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z32.object({preset:z32.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z32.string(),requestedTo:z32.string(),effectiveFrom:z32.string(),effectiveTo:z32.string(),isRetentionLimited:z32.boolean(),groupBy:z32.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z32.object({date:z32.string(),content:z32.string(),updatedAt:z32.string(),updatedByUserId:z32.string()}),PROJECT_ANALYTICS_DEVICE_FILTERS=["bot","desktop","mobile","tablet"],ProjectPageviewAnalyticsDTOSchema=z32.object({range:ProjectAnalyticsRangeDTOSchema,deviceFilter:z32.enum(PROJECT_ANALYTICS_DEVICE_FILTERS).nullable(),visitors:z32.number().int().nonnegative(),pageviews:z32.number().int().nonnegative(),botPageviews:z32.number().int().nonnegative(),botVisitors:z32.number().int().nonnegative(),bounceRate:z32.number().min(0).max(100),viewsPerVisit:z32.number().nonnegative(),averageVisitDurationSeconds:z32.number().nonnegative(),visitorsSeries:z32.array(ProjectDailyVisitorsDTOSchema),topPages:z32.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z32.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z32.array(ProjectAnalyticsBreakdownItemDTOSchema),topBots:z32.array(ProjectAnalyticsBreakdownItemDTOSchema),topAiAssistants:z32.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z32.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z32.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z32.array(ProjectAnalyticsAnnotationDTOSchema)}),PROJECT_ANALYTICS_TRACKING_STATES=["observed","waiting","unavailable"],ProjectAnalyticsTrackingStatusDTOSchema=z32.object({state:z32.enum(PROJECT_ANALYTICS_TRACKING_STATES),lastEventAt:z32.string().nullable()}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsTrackingStatusDTO=createDTO(ProjectAnalyticsTrackingStatusDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z33}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=z33.object({id:z33.string(),email:z33.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z33.coerce.date(),createdAt:z33.coerce.date(),inviterUserId:z33.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z33.object({id:z33.string(),token:z33.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z33.object({success:z33.boolean(),projectId:z33.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z34}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=z34.object({id:z34.string(),name:z34.string(),image:z34.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z34.object({count:z34.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z34.object({counts:z34.object({signed_up:z34.int(),activated:z34.int()}),credits:z34.object({total:z34.int(),earned:z34.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z34.email(),emailVerified:z34.boolean(),createdAt:z34.coerce.date(),updatedAt:z34.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z35}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,PROJECT_PERMISSION_KEYS,ProjectPermissionKeySchema,ProjectPermissionsDTOSchema,ProjectPermissionsDTO,ProjectAccessDTOSchema,ProjectAccessDTO,AccessMutationResponseSchema,InviteAcceptResponseSchema,init_project_access_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-access.dto.js"(){"use strict";init_common();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z35.object({id:z35.string(),principalType:ProjectPrincipalTypeSchema,principalId:z35.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z35.coerce.date(),expiresAt:z35.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),PROJECT_PERMISSION_KEYS=["project:read","project:manage","project:publish","project:unpublish","project:duplicate","project:export","project:import","project:transfer","project:delete","acl:read","acl:grant","member:read","member:change-role","invite:read","invite:send","invite:revoke","asset:read","asset:upload","asset:manage","asset:delete","asset:generate","code:view","code:edit","content:view","knowledge:view","knowledge:edit","content:edit","chat:read","chat:prompt","history:view","history:manage","comment:read","comment:create","comment:delete","branch:create","environment:create","integration:manage","integration:run","sync:github","webhook:read","webhook:manage","schedule:read","schedule:manage","preview:view","realtime:connect","analytics:view","logs:view","domain:manage","agent:run"],ProjectPermissionKeySchema=z35.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z35.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z35.record(z35.string(),z35.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z35.object({access:z35.array(ProjectAccessItemDTOSchema),invites:z35.array(ProjectInviteDTOSchema),organization:z35.object({name:z35.string().nullable(),logo:z35.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z35.object({success:z35.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z35.object({success:z35.boolean(),projectId:z35.uuid()}))}});import{z as z36}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=z36.object({publicationStatus:PublicationStatusSchema,appUrl:z36.string().nullable(),lastPublishedAt:z36.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z37}from"zod";var BranchHostedPreviewStatusSchema,BranchHostedPreviewSchema,init_hosted_preview_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/hosted-preview.dto.js"(){"use strict";init_env();BranchHostedPreviewStatusSchema=z37.enum(["queued","building","ready","failed"]),BranchHostedPreviewSchema=z37.object({branch:BranchSchema,revision:z37.string().min(1).max(64).nullable(),generation:z37.string().min(1).max(64),status:BranchHostedPreviewStatusSchema,url:z37.url().nullable()})}});import{z as z38}from"zod";var PreviewUpgradeRequiredSchema,PreviewBridgePackageSchema,PreviewBridgeCapabilitySchema,SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,PreviewInstallApprovalTargetSchema,PreviewInstallRepairSchema,SandboxSessionInstallPolicyErrorSchema,SandboxPullPhaseSchema,SandboxPullFailureCodeSchema,SandboxPullFailureSchema,PreviewInstallPolicyApprovalRequestSchema,PreviewInstallPolicyApprovalEventSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();PreviewUpgradeRequiredSchema=z38.object({code:z38.literal("PREVIEW_UPGRADE_REQUIRED"),message:z38.string(),currentVersion:z38.number().int().positive(),targetVersion:z38.literal(4)}),PreviewBridgePackageSchema=z38.object({name:z38.string().min(1),version:z38.string().min(1)}),PreviewBridgeCapabilitySchema=z38.object({integrated:z38.boolean(),packages:z38.array(PreviewBridgePackageSchema)}),SandboxSessionDTOSchema=z38.object({url:z38.url(),expiresAt:z38.iso.datetime().nullable(),source:z38.enum(["sandbox","hosted"]).optional(),previewBridge:PreviewBridgeCapabilitySchema.optional()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z38.object({name:z38.string().min(1),locator:z38.string().min(1).optional(),source:z38.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z38.object({kind:z38.literal("dependency_build_scripts_blocked"),packageManager:z38.enum(["pnpm","yarn","bun"]),packages:z38.array(z38.string()),targets:z38.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z38.string(),approvalKey:z38.string(),command:z38.string().optional(),approval:z38.object({id:z38.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z38.object({code:z38.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z38.string(),repair:PreviewInstallRepairSchema}),SandboxPullPhaseSchema=z38.enum(["acquire","pull","sync-env","install","restart","readiness"]),SandboxPullFailureCodeSchema=z38.enum(["sync_failed","readiness_failed","install_policy_blocked"]),SandboxPullFailureSchema=z38.object({message:z38.string(),code:SandboxPullFailureCodeSchema.optional().catch(void 0),phase:SandboxPullPhaseSchema.optional().catch(void 0),exitCode:z38.number().int().optional().catch(void 0),logTail:z38.array(z38.string()).optional().catch(void 0),logTailTruncated:z38.boolean().optional().catch(void 0),repair:PreviewInstallRepairSchema.optional().catch(void 0)}),PreviewInstallPolicyApprovalRequestSchema=z38.object({approvalId:z38.uuid()}),PreviewInstallPolicyApprovalEventSchema=z38.discriminatedUnion("type",[z38.object({type:z38.literal("progress"),step:z38.enum(["approval","install","restart","readiness"]),message:z38.string()}),z38.object({type:z38.literal("approved")}),z38.object({type:z38.literal("complete")}),z38.object({type:z38.literal("error"),code:z38.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z38.string()})])}});import{z as z39}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:z39.string(),slug:z39.string().nullable(),logo:z39.string().nullable(),metadata:z39.record(z39.string(),z39.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z39.object({id:z39.string(),name:z39.string(),email:z39.email(),image:z39.string().nullable()}),OrganizationMemberDTOSchema=z39.object({id:z39.string(),userId:z39.string(),organizationId:z39.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z39.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z40}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,PlanMigrationAcceptDTOSchema,PlanMigrationPreviewDTOSchema,PlanMigrationPreviewDTO,PlanMigrationStateSchema,PlanMigrationOfferDTOSchema,PlanMigrationOfferDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,MediaStorageUsageDTOSchema,MediaStorageUsageDTO,PendingPlanChangeDTOSchema,AutomaticSpendStopDTOSchema,HostingOverageStatusDTOSchema,HostingOverageStatusDTO,UpdateHostingOverageRequestSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,AutoRefillConfigDTOSchema,AutoRefillConfigDTO,UpdateAutoRefillDTOSchema,OptionalSpendRefusalSchema,CreditPurchasePricingDTOSchema,CreditPurchasePricingDTO,PurchaseCreditsDTOSchema,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,PaymentRecoveryInvoiceDTOSchema,PaymentRecoveryDTOSchema,PaymentRecoveryDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,AutoRefillConfigResponseSchema,CreditPurchasePricingResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,PaymentRecoveryResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common();init_create_dto();init_response();CancellationReasonCodeSchema=z40.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z40.object({reason:CancellationReasonCodeSchema,details:z40.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z40.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z40.object({offerVersion:z40.string().trim().min(1),unusedPremiumCreditAmount:z40.number().int().nonnegative(),amountDueNow:z40.number().int().nonnegative(),renewsOn:z40.string()}),PlanMigrationPreviewDTOSchema=z40.object({currency:z40.string().trim().min(1),unusedPremiumCreditAmount:z40.number().int().nonnegative(),amountDueNow:z40.number().int().nonnegative(),startsAt:z40.string(),renewsAt:z40.string(),nextRenewalAmount:z40.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z40.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z40.object({id:z40.string(),organizationId:z40.string(),legacySubscriptionId:z40.string(),offeredPlanCode:z40.string(),offeredPlanName:z40.string(),offeredPriceAmount:z40.number(),offeredCurrency:z40.string(),offerVersion:z40.string(),state:PlanMigrationStateSchema,checkoutToken:z40.string().nullable(),deadlineAt:z40.string(),transitions:z40.array(z40.object({event:z40.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z40.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z40.object({included:z40.number().optional(),unitPrice:z40.number().optional(),dailyCap:z40.number().nullable().optional()}),EntitlementsDTOSchema=z40.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z40.object({retentionDays:z40.number().int().positive(),canUseExtendedDateRanges:z40.boolean()}).optional(),history:z40.object({retentionDays:z40.number().int().positive()}).optional(),members:z40.object({canInvite:z40.boolean(),maxMembers:z40.number().int().positive().nullable()}).optional(),projects:z40.object({maxProjects:z40.number().int().positive().nullable()}).optional(),domains:z40.object({canUseCustomDomains:z40.boolean(),maxDomains:z40.number().int().nonnegative().nullable()}).optional(),media_storage:z40.object({limitBytes:z40.number().int().nonnegative()}).optional()}),MediaStorageUsageDTOSchema=z40.object({usedBytes:z40.number().int().nonnegative().nullable(),limitBytes:z40.number().int().nonnegative().nullable(),state:z40.enum(["ready","unavailable"]),measuredAt:z40.iso.datetime().nullable()}),MediaStorageUsageDTO=createDTO(MediaStorageUsageDTOSchema),PendingPlanChangeDTOSchema=z40.object({toPlanCode:TemplateCodeSchema,effectiveAt:z40.string(),scheduledAt:z40.string().nullable()}),AutomaticSpendStopDTOSchema=z40.object({fromPlanCode:TemplateCodeSchema,toPlanCode:TemplateCodeSchema,cutoffAt:z40.string(),spendStopped:z40.boolean(),settlementEndsAt:z40.string()}),HostingOverageStatusDTOSchema=z40.object({state:z40.enum(["ready","unavailable"]),planCode:z40.string(),overageAvailable:z40.boolean(),overageEnabled:z40.boolean(),monthlyCapUsd:z40.number().int().positive().nullable(),periodStart:z40.iso.datetime().nullable(),periodEnd:z40.iso.datetime().nullable(),usedBytes:z40.number().nonnegative().nullable(),includedBytes:z40.number().nonnegative().nullable(),overageBytes:z40.number().nonnegative(),currentOverageAmountMicros:z40.number().nonnegative().nullable(),totalExtraUsageAmountMicros:z40.number().nonnegative().nullable(),currency:z40.string().nullable(),status:z40.enum(["ok","near_limit","paused"])}),HostingOverageStatusDTO=createDTO(HostingOverageStatusDTOSchema),UpdateHostingOverageRequestSchema=z40.object({enabled:z40.boolean(),monthlyCapUsd:z40.number().int().positive().max(1e6).optional()}).refine(value=>!value.enabled||value.monthlyCapUsd!==void 0,{message:"Enabling extra usage requires a monthly budget"}),SubscriptionDTOSchema=z40.object({id:z40.string(),external_id:z40.string(),customerId:z40.string(),planId:z40.string(),planCode:z40.union([TemplateCodeSchema,z40.literal("Unknown")]),currentPeriod:z40.object({start:z40.string(),end:z40.string().nullable()}),cancelAt:z40.string().nullable(),pendingPlanChange:PendingPlanChangeDTOSchema.nullable(),automaticSpendStop:AutomaticSpendStopDTOSchema.nullable(),entitlements:EntitlementsDTOSchema,currency:z40.string(),nextPaymentAt:z40.string().nullable(),baseAmount:z40.number().nullable()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z40.object({totalCap:z40.number(),dailyCap:z40.number(),usedTotal:z40.number()}),CreditBalanceDTOSchema=z40.object({total:z40.number(),base:z40.number(),dailyBase:z40.number(),purchases:z40.number(),awards:z40.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z40.object({total:z40.number(),nearLimit:z40.boolean(),canChat:z40.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z40.object({dailyFreeAvailable:z40.number(),monthlyAvailable:z40.number(),purchasedAvailable:z40.number(),awardedAvailable:z40.number()}),ProjectDailyCreditAllowanceDTOSchema=z40.object({periodCap:z40.number(),dailyGrant:z40.number(),usedThisPeriod:z40.number(),remainingThisPeriod:z40.number()}),ProjectCreditBalanceDTOSchema=z40.object({projectId:z40.uuid(),organizationId:z40.string(),balance:z40.object({totalAvailable:z40.number(),nearLimit:z40.boolean(),canUseAi:z40.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z40.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AutoRefillConfigDTOSchema=z40.discriminatedUnion("enabled",[z40.object({enabled:z40.literal(!0),thresholdUsd:z40.number().nonnegative(),refillAmountUsd:z40.number().nonnegative()}),z40.object({enabled:z40.literal(!1),thresholdUsd:z40.number().nonnegative().nullable(),refillAmountUsd:z40.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z40.discriminatedUnion("enabled",[z40.object({enabled:z40.literal(!0),thresholdUsd:z40.number().min(.01).multipleOf(.01),refillAmountUsd:z40.number().min(.01).multipleOf(.01),expectedRateToken:z40.string().trim().min(1).max(40)}).strict(),z40.object({enabled:z40.literal(!1),thresholdUsd:z40.number().min(.01).multipleOf(.01),expectedRateToken:z40.string().trim().min(1).max(40).optional()}).strict()]),OptionalSpendRefusalSchema=z40.enum(["no_subscription","plan_cannot_fund","pending_plan_exit"]),CreditPurchasePricingDTOSchema=z40.object({planCode:z40.union([TemplateCodeSchema,z40.literal("Unknown")]).nullable(),canPurchase:z40.boolean(),refusalReason:OptionalSpendRefusalSchema.nullable(),creditsPerDollar:z40.number().int().positive(),minAmountUsd:z40.number().positive(),maxAmountUsd:z40.number().positive(),rateToken:z40.string().nullable()}),CreditPurchasePricingDTO=createDTO(CreditPurchasePricingDTOSchema),PurchaseCreditsDTOSchema=z40.object({amountUsd:z40.number(),idempotencyKey:z40.string().trim().min(8).max(120),expectedRateToken:z40.string().trim().min(1).max(40)}).strict(),SuccessfulPurchaseDTOSchema=z40.object({invoiceId:z40.string(),newBalance:z40.int(),creditCount:z40.int(),amountUsd:z40.number(),creditsPerDollar:z40.int()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z40.object({url:z40.string()}),PortalDTO=createDTO(PortalDTOSchema),PaymentRecoveryInvoiceDTOSchema=z40.object({id:z40.string(),number:z40.string().nullable(),status:z40.string(),amountDue:z40.int(),currency:z40.string(),issuedAt:z40.string().nullable(),hostedInvoiceUrl:z40.string().nullable()}),PaymentRecoveryDTOSchema=z40.discriminatedUnion("status",[z40.object({status:z40.literal("eligible"),checkedAt:z40.string()}),z40.object({status:z40.literal("recovery_required"),checkedAt:z40.string(),invoice:PaymentRecoveryInvoiceDTOSchema,outstandingCount:z40.int().min(1)}),z40.object({status:z40.literal("unavailable"),checkedAt:z40.string(),reason:z40.enum(["provider_error","truncated","unattempted","foreign_invoice","unknown_status"])})]),PaymentRecoveryDTO=createDTO(PaymentRecoveryDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),AutoRefillConfigResponseSchema=createResponseSchema(AutoRefillConfigDTOSchema),CreditPurchasePricingResponseSchema=createResponseSchema(CreditPurchasePricingDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema),PaymentRecoveryResponseSchema=createResponseSchema(PaymentRecoveryDTOSchema)}});import{z as z41}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=z41.object({brand:z41.string(),last4:z41.string(),exp:z41.string(),isDefault:z41.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z42}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentFieldGroupSchema,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=z42.string().superRefine((path49,ctx)=>{let segments=path49.split(".");(segments.length===0||segments.some(segment=>!CONTENT_FIELD_NAME_PATTERN.test(segment)))&&ctx.addIssue({code:"custom",message:"Field paths must use dot-separated field or block variant names."})}),SchemaMigrationOperationSchema=z42.object({type:z42.literal("renameField"),contentType:z42.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z42.object({enabled:z42.boolean()}).strict(),ContentFieldGroupSchema=z42.object({id:z42.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z42.string().min(1).max(255),default:z42.boolean().optional()}).strict(),ContentTypeDTOSchema=z42.object({id:z42.string(),name:z42.string(),label:z42.string(),isSingleton:z42.boolean(),i18n:ContentTypeI18nSchema,groups:z42.array(ContentFieldGroupSchema).default([]),fields:z42.record(z42.string(),FieldDefinitionSchema),createdAt:z42.string(),updatedAt:z42.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z42.object({contentTypes:z42.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z42.object({id:z42.string(),entryId:z42.string(),documentId:z42.string(),slug:z42.string(),locale:z42.string().optional(),createdAt:z42.string(),updatedAt:z42.string(),__fimo:z42.object({contentType:z42.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z42.object({data:z42.array(EntryDTOSchema),meta:z42.object({limit:z42.number(),offset:z42.number(),total:z42.number(),hasMore:z42.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z42.object({contentType:z42.string(),count:z42.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z42.object({counts:z42.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z42.object({count:z42.number().int().nonnegative(),sourceLocale:z42.string(),targetLocale:z42.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z42.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z42.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z42.union([z42.string(),z42.number(),z42.boolean(),z42.null()]),entryWhereOperatorSchema=z42.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z42.array(entryWhereScalarSchema).optional(),$nin:z42.array(entryWhereScalarSchema).optional(),$contains:z42.string().optional(),$startsWith:z42.string().optional(),$null:z42.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z42.record(z42.string(),z42.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z42.record(z42.string(),z42.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z42.object({data:z42.record(z42.string(),z42.unknown()),locale:z42.string().min(1).optional(),documentId:z42.uuid().optional()}),entryIdsSchema=z42.array(z42.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z42.object({sql:z42.string().min(1)}),BulkCreateEntriesRequestSchema=z42.object({entries:z42.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z42.union([z42.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z42.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z42.object({updates:z42.array(z42.object({id:z42.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z42.union([z42.object({ids:entryIdsSchema,locale:z42.string().min(1).optional()}),z42.object({where:EntryWhereSchema,locale:z42.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z42.object({data:z42.array(z42.record(z42.string(),z42.unknown())),meta:z42.object({rowCount:z42.number().int().nonnegative(),truncated:z42.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z42.object({data:z42.array(EntryDTOSchema),meta:z42.object({created:z42.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z42.object({data:z42.array(EntryDTOSchema),meta:z42.object({updated:z42.number().int().nonnegative(),missing:z42.array(z42.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z42.object({data:z42.array(EntryDTOSchema),meta:z42.object({deleted:z42.number().int().nonnegative(),missing:z42.array(z42.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z43}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z43.object({index:z43.number().int().nonnegative(),contentType:z43.string(),field:z43.string(),value:z43.string(),against:z43.enum(["stored","batch"]),ownerDocumentId:z43.uuid().optional(),ownerIndex:z43.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z43.object({code:z43.literal("unique_conflict"),message:z43.string(),conflicts:z43.array(UniqueConflictSchema),truncated:z43.boolean().optional()})}});import{z as z44}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=z44.object({kind:z44.literal("unique_conflict"),contentType:z44.string(),field:z44.string(),value:z44.string(),documentCount:z44.number().int().positive(),documentIds:z44.array(z44.uuid()),documentIdsTruncated:z44.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z44.object({code:z44.literal("schema_transition_rejected"),message:z44.string(),issues:z44.array(SchemaTransitionIssueSchema),truncated:z44.boolean().optional()})}});import{z as z45}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=z45.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z45.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z45.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z45.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z45.object({field:CmsFieldNameSchema,direction:z45.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z45.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z45.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z45.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z45.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z45.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z46}from"zod";var MIGRATION_SOURCE_PLATFORMS,MigrationSourcePlatformSchema,init_project_migration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-migration.dto.js"(){"use strict";MIGRATION_SOURCE_PLATFORMS=["webflow","framer","squarespace","wix","carrd","wordpress","nextjs","astro","react-router","other","unknown"],MigrationSourcePlatformSchema=z46.enum(MIGRATION_SOURCE_PLATFORMS)}});import{z as z47}from"zod";var CLIENT_TRACKED_EVENTS,ClientTrackedEventSchema,TrackProjectEventRequestSchema,init_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/analytics.dto.js"(){"use strict";CLIENT_TRACKED_EVENTS=["didStartMigration","didEndMigration"],ClientTrackedEventSchema=z47.enum(CLIENT_TRACKED_EVENTS),TrackProjectEventRequestSchema=z47.object({event:ClientTrackedEventSchema,properties:z47.record(z47.string(),z47.unknown()).default({})})}});import{z as z48}from"zod";var AssetPathItemSchema,AssetDTOSchema,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema,AssetListResponseSchema,MediaStorageLimitErrorSchema,AssetReferenceScopeSchema,ASSET_REFERENCE_IMPACT_FILE_LIMIT,AssetReferenceImpactRequestSchema,AssetReferenceImpactSelectionDTOSchema,AssetReferenceFindingDTOSchema,AssetReferenceScopeResultDTOSchema,AssetReferenceScopeResultDTO,AssetReferenceImpactEventDTOSchema,AssetReferenceImpactEventDTO,AssetReferenceReplacementRequestSchema,AssetReferenceReplacementResultSchema,AssetReferenceReplacementResponseSchema,AssetReferenceReplacementPreviewResponseSchema,AssetCodeReferenceReplacementResultSchema,AssetReferenceReplacementErrorCodeSchema,AssetReferenceReplacementErrorSchema,ASSET_REMOVAL_ASSET_LIMIT,AssetRemovalIntentSchema,ASSET_REPLACING_REMOVAL_INTENTS,isReplacingIntent,AssetRemovalRequestSchema,AssetRemovalOperationDTOSchema,AssetRemovalOperationDTO,AssetRemovalScheduleResultDTOSchema,AssetRemovalScheduleResultDTO,AssetRemovalErrorCodeSchema,AssetRemovalErrorSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common();init_create_dto();init_response();AssetPathItemSchema=z48.object({id:z48.string(),name:z48.string()}),AssetDTOSchema=z48.object({id:z48.string(),name:z48.string(),type:AssetTypeSchema,originalFileName:z48.string().nullable(),parentId:z48.string().nullable(),mimeType:z48.string().nullable(),fileSize:z48.number().nullable(),url:z48.string().nullable(),storageKey:z48.string().nullable(),createdAt:z48.string(),updatedAt:z48.string(),altText:z48.string().nullable().optional(),caption:z48.string().nullable().optional(),aiCaption:z48.string().nullable().optional(),aiAltText:z48.string().nullable().optional(),aiTags:z48.array(z48.string()).nullable().optional(),aiPrimaryColor:z48.string().nullable().optional(),aiProcessingStatus:z48.string().nullable().optional(),width:z48.number().nullable().optional(),height:z48.number().nullable().optional(),path:z48.array(AssetPathItemSchema).optional(),hasChildren:z48.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z48.lazy(()=>z48.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z48.array(AssetDTOSchema)),MediaStorageLimitErrorSchema=z48.object({error:z48.string(),code:z48.literal("media_storage_limit_exceeded"),usedBytes:z48.number().int().nonnegative(),limitBytes:z48.number().int().positive(),incomingBytes:z48.number().int().nonnegative()}),AssetReferenceScopeSchema=z48.enum(["current","main","live"]),ASSET_REFERENCE_IMPACT_FILE_LIMIT=50,AssetReferenceImpactRequestSchema=z48.object({assetIds:z48.array(z48.uuid()).min(1).max(ASSET_REFERENCE_IMPACT_FILE_LIMIT),scopes:z48.array(AssetReferenceScopeSchema).min(1).optional()}),AssetReferenceImpactSelectionDTOSchema=z48.object({totalFiles:z48.number().int().nonnegative(),checkedFiles:z48.number().int().nonnegative(),limit:z48.number().int().positive()}),AssetReferenceFindingDTOSchema=z48.object({assetId:z48.uuid(),entryId:z48.string(),documentId:z48.string(),contentType:z48.string(),locale:z48.string().nullable(),slug:z48.string(),fieldPath:z48.string()}),AssetReferenceScopeResultDTOSchema=z48.object({scope:AssetReferenceScopeSchema,label:z48.string(),state:z48.enum(["available","not-published","failed"]),coverage:z48.enum(["complete","partial","failed"]),referenceCount:z48.number().int().nonnegative().optional(),codeReferenceCount:z48.number().int().nonnegative().optional(),referencedAssetIds:z48.array(z48.uuid()).optional(),references:z48.array(AssetReferenceFindingDTOSchema),reason:z48.enum(["timeout","unavailable"]).optional()}),AssetReferenceScopeResultDTO=createDTO(AssetReferenceScopeResultDTOSchema),AssetReferenceImpactEventDTOSchema=z48.discriminatedUnion("type",[z48.object({type:z48.literal("selection"),data:AssetReferenceImpactSelectionDTOSchema}),z48.object({type:z48.literal("scope"),data:AssetReferenceScopeResultDTOSchema}),z48.object({type:z48.literal("complete")})]),AssetReferenceImpactEventDTO=createDTO(AssetReferenceImpactEventDTOSchema),AssetReferenceReplacementRequestSchema=z48.object({replacementAssetId:z48.uuid()}),AssetReferenceReplacementResultSchema=z48.object({referencesReplaced:z48.number().int().nonnegative(),entriesChanged:z48.number().int().nonnegative()}),AssetReferenceReplacementResponseSchema=createResponseSchema(AssetReferenceReplacementResultSchema),AssetReferenceReplacementPreviewResponseSchema=createResponseSchema(AssetReferenceReplacementResultSchema),AssetCodeReferenceReplacementResultSchema=z48.object({referencesReplaced:z48.number().int().nonnegative(),filesChanged:z48.number().int().nonnegative(),commitSha:z48.string().nullable()}),AssetReferenceReplacementErrorCodeSchema=z48.enum(["asset_replacement.self","asset_replacement.source_not_found","asset_replacement.replacement_not_found","asset_replacement.incompatible_media","asset_replacement.target_unavailable","asset_replacement.code_not_editable","asset_replacement.code_unavailable","asset_replacement.code_conflict","asset_replacement.code_too_many_files"]),AssetReferenceReplacementErrorSchema=z48.object({error:z48.string(),code:AssetReferenceReplacementErrorCodeSchema}),ASSET_REMOVAL_ASSET_LIMIT=200,AssetRemovalIntentSchema=z48.enum(["remove-from-branch","delete-from-project","replace-and-remove","replace-and-delete"]),ASSET_REPLACING_REMOVAL_INTENTS=["replace-and-remove","replace-and-delete"],isReplacingIntent=__name(intent=>ASSET_REPLACING_REMOVAL_INTENTS.includes(intent),"isReplacingIntent"),AssetRemovalRequestSchema=z48.object({intent:AssetRemovalIntentSchema,assetIds:z48.array(z48.uuid()).min(1).max(ASSET_REMOVAL_ASSET_LIMIT),replacementAssetId:z48.uuid().optional()}).refine(request=>isReplacingIntent(request.intent)===(request.replacementAssetId!==void 0),{message:"A replacement is required by the replace intents and rejected by the others",path:["replacementAssetId"]}).refine(request=>!isReplacingIntent(request.intent)||request.assetIds.length===1,{message:"A replacement applies to exactly one asset",path:["assetIds"]}),AssetRemovalOperationDTOSchema=z48.object({id:z48.uuid(),intent:AssetRemovalIntentSchema,assetIds:z48.array(z48.uuid()),replacementAssetId:z48.uuid().nullable(),expiresAt:z48.iso.datetime(),undoable:z48.boolean(),requestedByMe:z48.boolean()}),AssetRemovalOperationDTO=createDTO(AssetRemovalOperationDTOSchema),AssetRemovalScheduleResultDTOSchema=AssetRemovalOperationDTOSchema.extend({codeReplacement:AssetCodeReferenceReplacementResultSchema.optional()}),AssetRemovalScheduleResultDTO=createDTO(AssetRemovalScheduleResultDTOSchema),AssetRemovalErrorCodeSchema=z48.enum(["asset_removal.asset_not_found","asset_removal.replacement_not_found","asset_removal.already_finalized"]),AssetRemovalErrorSchema=z48.object({error:z48.string(),code:AssetRemovalErrorCodeSchema})}});import{z as z49}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z49.object({key:z49.string(),value:z49.string().optional(),defaultValue:z49.string(),locale:z49.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z50}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=z50.object({id:z50.string(),name:z50.string(),type:z50.enum(["file","folder"]),path:z50.string(),children:z50.lazy(()=>z50.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z50.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z50.object({path:z50.string(),exists:z50.boolean(),type:z50.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z51}from"zod";var FormFieldTypeSchema,FormFieldValidationSchema,FormFieldSchema,FormFieldsSchema,FormContentSchema,FormUpdateSchema,init_form_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/form.dto.js"(){"use strict";FormFieldTypeSchema=z51.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),FormFieldValidationSchema=z51.object({minLength:z51.number().optional(),maxLength:z51.number().optional(),min:z51.number().optional(),max:z51.number().optional(),pattern:z51.string().optional(),maxFileSize:z51.number().optional(),accept:z51.array(z51.string()).optional()}),FormFieldSchema=z51.object({type:FormFieldTypeSchema,label:z51.string(),placeholder:z51.string().optional(),required:z51.boolean().optional(),defaultValue:z51.string().optional(),options:z51.array(z51.string()).optional(),validation:FormFieldValidationSchema.optional()}),FormFieldsSchema=z51.record(z51.string(),FormFieldSchema),FormContentSchema=z51.object({name:z51.string().min(1).max(255),label:z51.string().min(1).max(255),fields:FormFieldsSchema}).strict(),FormUpdateSchema=FormContentSchema.partial().refine(update=>update.name!==void 0||update.label!==void 0||update.fields!==void 0,{message:"Pass at least one of name, label, or fields."})}});import{z as z52}from"zod";function isIanaTimezone(value){try{return new Intl.DateTimeFormat("en-US",{timeZone:value}),!0}catch{return!1}}var ChatRoutineCronSchema,ChatRoutineTimezoneSchema,ChatRoutineScheduleSchema,ChatRoutineNameSchema,ChatRoutineInstructionsSchema,ChatRoutineModelSchema,ChatRoutineEventTriggerDTOSchema,ChatRoutineEventTriggerInputSchema,ChatRoutineTriggersDTOSchema,ChatRoutineRunOutcomeSchema,ChatRoutineReportSchema,ChatRoutineDTOSchema,ChatRoutineListDTOSchema,ChatRoutineCreateSchema,ChatRoutineUpdateSchema,ChatRoutineRefusalReasonSchema,ChatRoutineRefusalDTOSchema,ChatRoutineRunStatusSchema,ChatRoutineRunTriggerSchema,ChatRoutineRunStartedBySchema,ChatRoutineRunDTOSchema,ChatRoutineRunListDTOSchema,ChatRoutineRunRequestSchema,ChatRoutineRunOutcomeDTOSchema,init_chat_routine_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat-routine.dto.js"(){"use strict";ChatRoutineCronSchema=z52.string().trim().max(64).regex(/^\S+(?: \S+){4}$/,"A schedule is a five-field cron expression");__name(isIanaTimezone,"isIanaTimezone");ChatRoutineTimezoneSchema=z52.string().trim().min(1).max(64).refine(isIanaTimezone,"Unknown timezone"),ChatRoutineScheduleSchema=z52.object({cron:ChatRoutineCronSchema,timezone:ChatRoutineTimezoneSchema}),ChatRoutineNameSchema=z52.string().trim().min(1).max(120),ChatRoutineInstructionsSchema=z52.string().trim().min(1).max(2e4),ChatRoutineModelSchema=z52.string().trim().min(1).max(120),ChatRoutineEventTriggerDTOSchema=z52.object({text:z52.string(),title:z52.string(),explanation:z52.string()}),ChatRoutineEventTriggerInputSchema=z52.object({text:z52.string().trim().min(1).max(500)}),ChatRoutineTriggersDTOSchema=z52.object({manual:z52.literal(!0),schedule:ChatRoutineScheduleSchema.nullable(),event:ChatRoutineEventTriggerDTOSchema.nullable()}),ChatRoutineRunOutcomeSchema=z52.enum(["quiet","reported","decision","incomplete","failed","running"]),ChatRoutineReportSchema=z52.object({message:z52.string().trim().min(1).max(2e4),decision:z52.boolean().optional(),incomplete:z52.boolean().optional()}).refine(report=>!(report.decision===!0&&report.incomplete===!0),{message:"A run that could not check asks for no decision: set incomplete or decision, not both."}),ChatRoutineDTOSchema=z52.object({id:z52.string().uuid(),threadId:z52.string().uuid(),runThreadId:z52.string().uuid(),name:z52.string(),instructions:z52.string(),triggers:ChatRoutineTriggersDTOSchema,model:z52.string(),modelIsDefault:z52.boolean(),paused:z52.boolean(),nextRunAt:z52.string().nullable(),lastRunAt:z52.string().nullable(),lastOutcome:ChatRoutineRunOutcomeSchema.nullable(),createdAt:z52.string(),updatedAt:z52.string()}),ChatRoutineListDTOSchema=z52.object({routines:z52.array(ChatRoutineDTOSchema)}),ChatRoutineCreateSchema=z52.object({name:ChatRoutineNameSchema,instructions:ChatRoutineInstructionsSchema,schedule:ChatRoutineScheduleSchema.nullable().optional(),event:ChatRoutineEventTriggerInputSchema.nullable().optional(),model:ChatRoutineModelSchema.nullable().optional()}),ChatRoutineUpdateSchema=z52.object({name:ChatRoutineNameSchema,instructions:ChatRoutineInstructionsSchema,schedule:ChatRoutineScheduleSchema.nullable(),event:ChatRoutineEventTriggerInputSchema.nullable(),model:ChatRoutineModelSchema.nullable(),paused:z52.boolean()}).partial().refine(update=>Object.values(update).some(value=>value!==void 0),"Change at least one field"),ChatRoutineRefusalReasonSchema=z52.enum(["routine_cadence_too_frequent","routine_schedule_invalid","routine_owner_not_agent","routine_trigger_unsupported","routine_model_unknown"]),ChatRoutineRefusalDTOSchema=z52.object({message:z52.string(),reason:ChatRoutineRefusalReasonSchema}),ChatRoutineRunStatusSchema=z52.enum(["queued","running","finished","failed","cancelled"]),ChatRoutineRunTriggerSchema=z52.enum(["schedule","hand","event"]),ChatRoutineRunStartedBySchema=z52.object({kind:z52.enum(["person","agent"]),name:z52.string().nullable()}),ChatRoutineRunDTOSchema=z52.object({messageId:z52.string().uuid(),invocationId:z52.string().uuid().nullable(),startedAt:z52.string(),trigger:ChatRoutineRunTriggerSchema,startedBy:ChatRoutineRunStartedBySchema.nullable(),status:ChatRoutineRunStatusSchema,outcome:ChatRoutineRunOutcomeSchema.nullable(),summary:z52.string().nullable(),events:z52.number().int().min(1)}),ChatRoutineRunListDTOSchema=z52.object({runs:z52.array(ChatRoutineRunDTOSchema)}),ChatRoutineRunRequestSchema=z52.object({message:z52.string().trim().min(1).max(2e4).optional()}),ChatRoutineRunOutcomeDTOSchema=z52.object({kind:z52.enum(["published","queued","replay","streaming","busy","refused"]),messageId:z52.string().uuid().nullable()})}});import{z as z53}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatLiveTurnStateDTOSchema,ChatLiveTurnStateDTO,ChatMessageAuthorDTOSchema,ChatThreadMessageDTOSchema,ChatQueuedMessageDTOSchema,ChatAttentionDTOSchema,ChatThreadMessagesPageDTOSchema,ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema,ChatNonStreamingOutcomeDTOSchema,ProjectChatKindSchema,ProjectChatCreatableKindSchema,ProjectChatRoutinesDTOSchema,ProjectChatDescriptionSchema,ProjectChatDTOSchema,ProjectChatListDTOSchema,ProjectChatCreatedDTOSchema,ProjectChatTitleSchema,ProjectChatCreateSchema,ProjectChatUpdateSchema,ChatTemplateRoutineScheduleDTOSchema,ChatTemplateRoutineDTOSchema,ChatTemplateDTOSchema,ChatTemplateListDTOSchema,ProjectChatStateSchema,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_chat_portrait();init_create_dto();init_response();init_chat_routine_dto();init_project_dto();ChatMessageListDTOSchema=z53.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z53.object({items:z53.array(ProjectMessagePublicDTOSchema),nextCursor:z53.string().nullable()}),ChatLiveTurnDTOSchema=z53.object({invocationId:z53.string(),step:z53.enum(["preparing","working","compacting","merging"]),startedAt:z53.string(),continuesInvocationId:z53.string().nullable().optional()}),ChatLiveTurnStateDTOSchema=z53.object({threadId:z53.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatMessageAuthorDTOSchema=z53.object({kind:z53.enum(["person","agent","routine","system"]),id:z53.string().nullable()}),ChatThreadMessageDTOSchema=z53.object({id:z53.string(),role:z53.enum(["user","assistant"]),parts:z53.array(z53.unknown()),metadata:z53.record(z53.string(),z53.unknown()).nullable(),versionId:z53.string().nullable().optional(),createdAt:z53.date().transform(value=>value.toISOString()),providerMessageId:z53.string().nullable().optional(),author:ChatMessageAuthorDTOSchema,invocationId:z53.string().nullable().optional(),invocationStatus:z53.string().nullable().optional(),invocationTerminalReason:z53.string().nullable().optional()}),ChatQueuedMessageDTOSchema=z53.object({id:z53.string(),parts:z53.array(z53.unknown()),metadata:z53.record(z53.string(),z53.unknown()).nullable(),providerMessageId:z53.string().nullable().optional(),author:ChatMessageAuthorDTOSchema,failed:z53.boolean(),queuedAt:z53.date().transform(value=>value.toISOString())}),ChatAttentionDTOSchema=z53.object({type:z53.literal("merge_conflict"),merge:z53.object({mergeId:z53.string().uuid(),projectId:z53.string(),fromBranch:z53.string(),toBranch:z53.string()}),publishAfterMerge:z53.boolean()}),ChatThreadMessagesPageDTOSchema=z53.object({threadId:z53.string().nullable(),title:z53.string().nullable(),messages:z53.array(ChatThreadMessageDTOSchema),nextCursor:z53.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional(),queue:z53.array(ChatQueuedMessageDTOSchema).optional(),queuePaused:z53.boolean().optional(),queueWaitUntil:z53.string().nullable().optional()}),ChatReplayOutcomeDTOSchema=z53.object({kind:z53.literal("replay"),threadId:z53.string(),userMessageId:z53.string()}),ChatQueuedOutcomeDTOSchema=z53.object({kind:z53.literal("queued"),threadId:z53.string(),userMessageId:z53.string(),blockingRootId:z53.string().optional()}),ChatBusyOutcomeDTOSchema=z53.object({kind:z53.literal("busy"),threadId:z53.string(),userMessageId:z53.string(),blockingRootId:z53.string().optional()}),ChatRefusedOutcomeDTOSchema=z53.object({kind:z53.literal("refused"),threadId:z53.string(),userMessageId:z53.string(),refusedInvocationId:z53.string(),terminalReason:z53.string()}),ChatNonStreamingOutcomeDTOSchema=z53.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ProjectChatKindSchema=z53.enum(["chat","agent","routine"]),ProjectChatCreatableKindSchema=z53.enum(["chat","agent"]),ProjectChatRoutinesDTOSchema=z53.object({quietRuns:z53.number().int().nonnegative(),since:z53.string().nullable(),lastOutcome:ChatRoutineRunOutcomeSchema.nullable(),lastRunAt:z53.string().nullable(),nextRunAt:z53.string().nullable()}),ProjectChatDescriptionSchema=z53.string().trim().max(2e3),ProjectChatDTOSchema=z53.object({id:z53.string().uuid(),kind:ProjectChatKindSchema,title:z53.string().nullable(),description:z53.string().nullable(),template:z53.string().nullable(),parentThreadId:z53.string().uuid().nullable(),routines:ProjectChatRoutinesDTOSchema.nullable(),createdAt:z53.string(),lastMessageAt:z53.string().nullable(),preview:z53.string().nullable(),running:z53.boolean(),awaitingAnswer:z53.boolean(),unread:z53.boolean(),pinned:z53.boolean(),archived:z53.boolean(),muted:z53.boolean(),portrait:ChatPortraitSchema.nullable()}),ProjectChatListDTOSchema=z53.object({chats:z53.array(ProjectChatDTOSchema)}),ProjectChatCreatedDTOSchema=z53.object({id:z53.string().uuid()}),ProjectChatTitleSchema=z53.string().trim().min(1).max(120),ProjectChatCreateSchema=z53.object({id:z53.string().uuid(),portrait:ChatPortraitSchema,kind:ProjectChatCreatableKindSchema,title:ProjectChatTitleSchema,description:ProjectChatDescriptionSchema,template:z53.string().min(1).max(64),timezone:ChatRoutineTimezoneSchema}).partial().refine(create=>create.template===void 0||create.kind===void 0&&create.title===void 0&&create.description===void 0,"A template brings its own kind, title and description"),ProjectChatUpdateSchema=z53.object({title:ProjectChatTitleSchema,description:ProjectChatDescriptionSchema,portrait:ChatPortraitSchema}).partial().refine(update=>update.title!==void 0||update.description!==void 0||update.portrait!==void 0,"Set a title, a description or a portrait"),ChatTemplateRoutineScheduleDTOSchema=z53.object({cron:z53.string()}),ChatTemplateRoutineDTOSchema=z53.object({name:z53.string(),instructions:z53.string(),schedule:ChatTemplateRoutineScheduleDTOSchema.nullable()}),ChatTemplateDTOSchema=z53.object({id:z53.string(),name:z53.string(),summary:z53.string(),description:z53.string(),portrait:ChatPortraitSchema,routines:z53.array(ChatTemplateRoutineDTOSchema)}),ChatTemplateListDTOSchema=z53.object({templates:z53.array(ChatTemplateDTOSchema)}),ProjectChatStateSchema=z53.object({read:z53.boolean(),pinned:z53.boolean(),archived:z53.boolean(),muted:z53.boolean()}).partial().refine(state=>Object.keys(state).length>0,"Set at least one of read, pinned, archived or muted"),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema)}});import{z as z54}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=z54.object({url:z54.string().url(),key:z54.string(),size:z54.number(),contentType:z54.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z55}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=z55.object({canAccess:z55.boolean(),permissions:z55.record(z55.string(),z55.boolean()),role:z55.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z56}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:z56.string().trim().default(""),sort:z56.enum(["recent","name","relevance"]).default("recent"),category:z56.string().optional()})}});import{z as z57}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=z57.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z57.enum(["fimo","external"]),PaymentStatusSchema=z57.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z57.object({id:z57.string().uuid(),domain:z57.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z57.boolean(),price:z57.number().int().nullable(),renewalPrice:z57.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z57.string().nullable(),failureReason:z57.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z57.object({domain:z57.string(),available:z57.boolean(),premium:z57.boolean(),price:z57.number().nullable(),renewalPrice:z57.number().nullable(),purchaseType:z57.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z57.object({domain:z57.string(),price:z57.number().nullable(),renewalPrice:z57.number().nullable(),premium:z57.boolean(),allowedYears:z57.array(z57.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z57.object({firstName:z57.string().max(100),lastName:z57.string().max(100),companyName:z57.string().max(100).optional(),address1:z57.string().max(255),address2:z57.string().max(255).optional(),city:z57.string().max(100),state:z57.string().max(100),zip:z57.string().max(20),country:z57.string().max(2),phone:z57.string().max(30),email:z57.union([z57.string().email().max(255),z57.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z57.object({firstName:z57.string().min(1).max(100),lastName:z57.string().min(1).max(100),companyName:z57.string().max(100).optional(),address1:z57.string().min(1).max(255),address2:z57.string().max(255).optional(),city:z57.string().min(1).max(100),state:z57.string().min(1).max(100),zip:z57.string().min(1).max(20),country:z57.string().min(1).max(2),phone:z57.string().min(1).max(30),email:z57.string().email().max(255)}),SearchDomainsRequestSchema=z57.object({keyword:z57.string().min(1).max(100),tldFilter:z57.array(z57.string()).optional()}),CheckAvailabilityRequestSchema=z57.object({domains:z57.array(z57.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=z57.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z57.object({domain:DomainNameSchema,years:z57.number().int().min(1).max(10).optional().default(3),autoRenew:z57.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z57.object({autoRenew:z57.boolean().optional()}),RenewDomainRequestSchema=z57.object({years:z57.number().int().min(1).max(10).optional().default(1),autoRenew:z57.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z57.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z57.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z57.object({verified:z57.boolean(),email:z57.string().nullable(),verifyBy:z57.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z58}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=z58.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=z58.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=z58.object({txtName:z58.string().nullable().optional(),txtValue:z58.string().nullable().optional(),httpUrl:z58.string().nullable().optional(),httpBody:z58.string().nullable().optional(),cname:z58.string().nullable().optional(),cnameTarget:z58.string().nullable().optional()}),SSLValidationErrorSchema=z58.object({message:z58.string()}),OwnershipVerificationSchema=z58.object({type:z58.string(),name:z58.string(),value:z58.string()}),ProjectDomainSSLDTOSchema=z58.object({status:z58.string(),method:z58.string().nullable(),type:z58.string().nullable(),validationRecords:z58.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z58.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z58.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z58.enum(["subdomain","apex"]),RedirectConfigSchema=z58.object({type:z58.enum(["apex_to_www","www_to_apex"]),linkedDomainId:z58.string()}).nullable().optional(),ProjectDomainDTOSchema=z58.object({id:z58.string(),hostname:z58.string(),status:z58.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z58.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z58.string(),scdCnameTarget:z58.string().optional(),apexTargets:z58.array(z58.string()),dnsAutoConfigured:z58.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z58.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z58.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z58.object({hostname:z58.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:z58.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z58.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z58.object({available:z58.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z58.object({success:z58.boolean(),hostname:z58.string()}))}});import{z as z59}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=z59.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z59.object({available:z59.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z59.object({slug:z59.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z59.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z59.object({subdomain:z59.string(),subdomainUpdatedAt:z59.coerce.date()})),SubdomainSuggestionsQuerySchema=z59.object({base:z59.string().max(100).optional(),max:z59.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z59.object({suggestions:z59.array(z59.string())}))}});import{z as z60}from"zod";var PROJECT_TRANSFER_BLOCKER_CODES,ProjectTransferBlockerCodeSchema,ProjectTransferBlockerDTO,TransferProjectRequestSchema,ProjectTransferResultDTO,init_project_transfer_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-transfer.dto.js"(){"use strict";init_create_dto();PROJECT_TRANSFER_BLOCKER_CODES=["same_organization","concurrent_transfer","agent_work_in_flight","unsettled_agent_holds","unsettled_usage_ledger","project_integrations_present","source_registered_domain"],ProjectTransferBlockerCodeSchema=z60.enum(PROJECT_TRANSFER_BLOCKER_CODES),ProjectTransferBlockerDTO=createDTO(z60.object({code:ProjectTransferBlockerCodeSchema,message:z60.string(),count:z60.number().int().nonnegative().optional()})),TransferProjectRequestSchema=z60.object({targetOrganizationId:z60.string().min(1)}),ProjectTransferResultDTO=createDTO(z60.object({projectId:z60.string(),sourceOrganizationId:z60.string(),targetOrganizationId:z60.string(),movedThreads:z60.number().int().nonnegative(),revokedInvites:z60.number().int().nonnegative(),revokedGrants:z60.number().int().nonnegative(),preservedGrants:z60.number().int().nonnegative(),warnings:z60.array(z60.string())}))}});import{z as z61}from"zod";var PROJECT_TOKEN_PREFIX,MB2,UNCLAIMED_PLAN,UnclaimedLockedFeatureSchema,UNCLAIMED_CLAIM_STATES,UnclaimedClaimStateSchema,UNCLAIMED_PROJECT_ERROR_CODES,UnclaimedProjectErrorCodeSchema,ProvisionUnclaimedProjectRequestSchema,UnclaimedProjectLimitsSchema,UnclaimedProjectClaimSchema,ProvisionUnclaimedProjectResponseDTO,UnclaimedClaimStatusDTO,UnclaimedClaimSecretSchema,UnclaimedClaimStatusRequestSchema,UnclaimedClaimStatesRequestSchema,UnclaimedClaimStatesResponseDTO,ClaimUnclaimedProjectRequestSchema,ClaimUnclaimedProjectResultDTO,ProjectTokenSelfDTO,init_unclaimed_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unclaimed-project.dto.js"(){"use strict";init_create_dto();init_project_dto();PROJECT_TOKEN_PREFIX="fimo_pt_",MB2=1e6,UNCLAIMED_PLAN={ttlHours:72,tokenTtlAfterClaimHours:24,media:{totalBytes:50*MB2,fileBytes:5*MB2,maxFiles:100,mimeTypes:["image/jpeg","image/png","image/webp","image/avif","image/gif"]},database:{storageBytes:100*MB2,computeSeconds:600*60,maxComputeUnits:.5},locked:{publish:"Publishing",subdomain:"A fimo.site address",custom_domains:"Custom domains",branches:"Extra Branches",environments:"Extra environments",asset_generation:"Generating images and videos",integrations:"Connecting integrations",invites:"Inviting people",schedules:"Schedules",agents:"Fimo agents",ai_credits:"AI features"}},UnclaimedLockedFeatureSchema=z61.enum(Object.keys(UNCLAIMED_PLAN.locked)),UNCLAIMED_CLAIM_STATES=["claimable","claimed","expired"],UnclaimedClaimStateSchema=z61.enum(UNCLAIMED_CLAIM_STATES),UNCLAIMED_PROJECT_ERROR_CODES=["project_unclaimed","unclaimed_projects_disabled","unclaimed_limit_reached","claim_not_claimable","claim_project_limit_reached","claim_target_organization_not_found","claim_target_organization_forbidden","claim_target_subscription_inactive","claim_blocked","project_token_required","unclaimed_media_limit"],UnclaimedProjectErrorCodeSchema=z61.enum(UNCLAIMED_PROJECT_ERROR_CODES),ProvisionUnclaimedProjectRequestSchema=z61.object({displayName:z61.string().trim().min(1).max(80),machineId:z61.string().trim().min(1).max(128).optional(),cliVersion:z61.string().trim().max(64).optional()}),UnclaimedProjectLimitsSchema=z61.object({ttlHours:z61.number().int().positive(),lockedFeatures:z61.array(UnclaimedLockedFeatureSchema),media:z61.object({totalBytes:z61.number().int().nonnegative(),fileBytes:z61.number().int().positive(),maxFiles:z61.number().int().nonnegative(),mimeTypes:z61.array(z61.string())}),database:z61.object({storageBytes:z61.number().int().positive(),computeSeconds:z61.number().int().positive(),maxComputeUnits:z61.number().positive()})}),UnclaimedProjectClaimSchema=z61.object({url:z61.string().url(),expiresAt:z61.coerce.date()}),ProvisionUnclaimedProjectResponseDTO=createDTO(z61.object({project:ProjectDTOSchema,token:z61.string(),claim:UnclaimedProjectClaimSchema,limits:UnclaimedProjectLimitsSchema})),UnclaimedClaimStatusDTO=createDTO(z61.object({state:UnclaimedClaimStateSchema,displayName:z61.string().nullable(),expiresAt:z61.coerce.date().nullable(),projectId:z61.string().nullable()})),UnclaimedClaimSecretSchema=z61.string().min(1).max(256),UnclaimedClaimStatusRequestSchema=z61.object({secret:UnclaimedClaimSecretSchema}),UnclaimedClaimStatesRequestSchema=z61.object({secrets:z61.array(UnclaimedClaimSecretSchema).min(1).max(20)}),UnclaimedClaimStatesResponseDTO=createDTO(z61.object({claims:z61.array(z61.object({state:UnclaimedClaimStateSchema,expiresAt:z61.coerce.date().nullable()}))})),ClaimUnclaimedProjectRequestSchema=z61.object({secret:UnclaimedClaimSecretSchema,organizationId:z61.string().min(1)}),ClaimUnclaimedProjectResultDTO=createDTO(z61.object({projectId:z61.string(),organizationId:z61.string()})),ProjectTokenSelfDTO=createDTO(z61.object({kind:z61.literal("project_token"),projectId:z61.string(),projectName:z61.string(),displayName:z61.string().nullable(),organizationId:z61.string().nullable(),organizationName:z61.string().nullable(),claimState:UnclaimedClaimStateSchema,expiresAt:z61.coerce.date().nullable(),tokenExpiresAt:z61.coerce.date().nullable()}))}});import{z as z62}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=z62.object({translated:z62.number().int().nonnegative(),total:z62.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z62.object({locale:z62.string(),isDefault:z62.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z62.object({defaultLocale:z62.string(),locales:z62.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z62.object({locale:z62.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z62.object({locale:z62.string().min(1).max(40)}),ProjectLocaleMutationSchema=z62.object({locale:z62.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z62.object({locale:z62.string(),entriesDeleted:z62.number().int().nonnegative(),labelsDeleted:z62.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z63}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=z63.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z63.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=z63.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z63.number(),credits:z63.number().optional(),billingMode:z63.enum(["fimo-credits","provider-account"]).optional(),confidence:z63.enum(["exact","estimated","metered"]),basis:z63.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z64}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=z64.object({options:z64.record(z64.string(),z64.unknown()),name:z64.string().optional(),parentId:z64.string().nullable().optional(),altText:z64.string().optional(),caption:z64.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z64.string().min(1).optional(),model:z64.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=z64.object({jobId:z64.string(),status:z64.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z64.string().nullable().optional(),credits:z64.number().optional(),costUsd:z64.number().optional(),billingMode:z64.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z64.object({error:z64.string(),code:z64.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:z64.array(GenerationTaskIdSchema).optional(),availableModels:z64.array(z64.string()).optional(),issues:z64.array(z64.unknown()).optional()})}});import{z as z65}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=z65.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z65.object({name:z65.string(),key:z65.string(),description:z65.string(),type:FlagTypeSchema,required:z65.boolean(),defaultValue:z65.unknown().optional(),enumValues:z65.array(z65.string()).optional(),isArray:z65.boolean()}),AssetModelPriceSchema=z65.object({unitPrice:z65.number(),unit:z65.string(),confidence:z65.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z65.object({id:z65.string(),shortName:z65.string(),provider:z65.string(),source:z65.string(),modality:z65.enum(["image","video","audio"]),tags:z65.array(z65.string()),displayName:z65.string(),description:z65.string(),flags:z65.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z65.object({model:z65.string(),costUsd:z65.number(),credits:z65.number(),billingMode:z65.enum(["fimo-credits","provider-account"]),confidence:z65.enum(["exact","estimated","metered"]),basis:z65.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z66}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=z66.object({tourId:z66.string(),version:z66.string(),status:z66.string(),completedAt:z66.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z66.array(UserTourDTOSchema))}});import{z as z67}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=z67.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z67.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z67.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z67.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z67.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z67.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z67.enum(["user","agent","system"]),SupportReportTagSchema=z67.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z67.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z67.object({organization:z67.object({id:z67.string().trim().min(1).max(255),name:z67.string().trim().max(240).optional()}),project:z67.object({id:z67.uuid(),name:z67.string().trim().max(240).optional(),createdAt:z67.coerce.date().optional()}).optional(),environment:z67.string().trim().max(255).optional(),clientVersion:z67.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z67.object({message:z67.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("cli"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z67.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z67.string().trim().max(200).optional(),limit:z67.coerce.number().int().min(1).max(100).default(50),offset:z67.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z67.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z67.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z67.uuid().nullable().optional(),note:z67.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=z67.object({message:z67.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z67.object({kind:SupportReportLinkKindSchema,label:z67.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z67.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z67.object({kind:SupportReportActorKindSchema,id:z67.string().nullable(),name:z67.string().nullable()}),SupportReportLinkDTOSchema=z67.object({id:z67.uuid(),kind:SupportReportLinkKindSchema,label:z67.string(),url:SupportReportHttpUrlSchema,externalId:z67.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z67.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z67.object({id:z67.uuid(),kind:SupportReportEventKindSchema,body:z67.string().nullable(),metadata:z67.record(z67.string(),z67.unknown()),actor:SupportReportActorDTOSchema,createdAt:z67.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z67.object({id:z67.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z67.array(z67.string()),source:SupportReportSourceSchema,message:z67.string(),reporter:z67.object({id:z67.string().nullable(),name:z67.string().nullable(),email:z67.string().nullable()}),organization:z67.object({id:z67.string().nullable(),name:z67.string()}),project:z67.object({id:z67.uuid().nullable(),name:z67.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z67.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z67.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z67.string().nullable(),deliveredAt:z67.coerce.date().nullable()}).nullable(),duplicateOfReportId:z67.uuid().nullable(),resolvedAt:z67.coerce.date().nullable(),createdAt:z67.coerce.date(),updatedAt:z67.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z67.string().nullable(),clientVersion:z67.string().nullable(),links:z67.array(SupportReportLinkDTOSchema),events:z67.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z67.object({reports:z67.array(SupportReportSummaryDTOSchema),total:z67.number().int().nonnegative(),statusCounts:z67.object({new:z67.number().int().nonnegative(),in_progress:z67.number().int().nonnegative(),waiting:z67.number().int().nonnegative(),resolved:z67.number().int().nonnegative(),duplicate:z67.number().int().nonnegative(),irrelevant:z67.number().int().nonnegative(),ignored:z67.number().int().nonnegative()}),limit:z67.number().int().positive(),offset:z67.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z67.object({id:z67.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z67.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z68}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=z68.iso.datetime({offset:!0}).pipe(z68.coerce.date()),OpsRecentChatInputSchema=z68.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z68.string().trim().min(1).max(255).optional(),limit:z68.coerce.number().int().min(1).max(200).default(100),cursor:z68.string().trim().min(1).max(2e3).optional(),slim:z68.boolean().default(!0),reason:z68.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=z68.object({id:z68.string(),threadId:z68.string(),providerMessageId:z68.string().nullable(),invocationId:z68.string().nullable(),env:z68.string().nullable(),role:z68.string(),parts:z68.array(z68.record(z68.string(),z68.unknown())),metadata:z68.object({status:z68.string().optional(),traceUrl:z68.string().optional(),externalFileChanges:z68.array(z68.unknown()).optional()}),stats:z68.object({toolCount:z68.number().int().nonnegative(),failedToolCount:z68.number().int().nonnegative()}),createdAt:z68.iso.datetime({offset:!0}),project:z68.object({id:z68.string(),name:z68.string(),displayName:z68.string().nullable(),organizationId:z68.string().nullable()})}),OpsRecentChatResponseSchema=z68.object({target:z68.object({backendProfile:OpsBackendProfileSchema,projectEnv:z68.string().nullable()}),window:z68.object({from:z68.iso.datetime({offset:!0}),to:z68.iso.datetime({offset:!0})}),messages:z68.object({items:z68.array(OpsRecentChatMessageSchema),nextCursor:z68.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z69}from"zod";var OpsSentryIssueResolutionResponseSchema,OpsSentryIssueResolutionResponseDTO,OpsSentryIssueResolutionErrorResponseSchema,OpsSentryIssueResolutionErrorResponseDTO,init_ops_sentry_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-sentry.dto.js"(){"use strict";init_ops();init_create_dto();OpsSentryIssueResolutionResponseSchema=z69.object({backendProfile:OpsBackendProfileSchema,provider:z69.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z69.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z69.object({backendProfile:OpsBackendProfileSchema,provider:z69.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z69.literal(!1),reason:z69.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z70}from"zod";var OpsProjectPackageManagerSummarySchema,OpsProjectPackageManagerSchema,OpsProjectPackageManagerDTO,init_ops_project_files_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-project-files.dto.js"(){"use strict";init_ops();init_create_dto();OpsProjectPackageManagerSummarySchema=z70.object({packageManager:z70.string().trim().min(1).max(200).nullable(),trackedLockfiles:z70.array(z70.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z70.string().trim().min(1)}),OpsProjectPackageManagerSchema=z70.object({target:z70.object({backendProfile:OpsBackendProfileSchema,projectId:z70.uuid(),projectEnv:z70.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z71}from"zod";function uniqueRoutineNames(spec){let names=(spec.routines??[]).map(routine=>routine.name);return new Set(names).size===names.length}var OpsAgentChatRoutineSpecSchema,OpsAgentChatAgentSpecSchema,OpsAgentChatSpecObjectSchema,UNIQUE_ROUTINE_NAMES,OpsAgentChatSpecSchema,OpsAgentChatCreateInputSchema,OpsAgentChatOutcomeSchema,OpsAgentChatRoutineResultSchema,OpsAgentChatCreateResultSchema,init_ops_agent_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-agent-chat.dto.js"(){"use strict";init_ops();init_chat_routine_dto();OpsAgentChatRoutineSpecSchema=ChatRoutineCreateSchema.extend({schedule:ChatRoutineScheduleSchema.nullable(),paused:z71.boolean().optional()}).strict(),OpsAgentChatAgentSpecSchema=z71.union([z71.object({name:z71.string().trim().min(1).max(120),description:z71.string().trim().min(1).max(2e3)}).strict(),z71.object({template:z71.string().trim().min(1).max(64)}).strict()]),OpsAgentChatSpecObjectSchema=z71.object({agent:OpsAgentChatAgentSpecSchema,routines:z71.array(OpsAgentChatRoutineSpecSchema).max(50).optional()}).strict();__name(uniqueRoutineNames,"uniqueRoutineNames");UNIQUE_ROUTINE_NAMES={path:["routines"],message:"Routine names must be unique within one agent"},OpsAgentChatSpecSchema=OpsAgentChatSpecObjectSchema.refine(uniqueRoutineNames,UNIQUE_ROUTINE_NAMES),OpsAgentChatCreateInputSchema=OpsAgentChatSpecObjectSchema.extend({reason:z71.string().trim().min(1).max(1e3),dryRun:z71.boolean().optional()}).refine(uniqueRoutineNames,UNIQUE_ROUTINE_NAMES),OpsAgentChatOutcomeSchema=z71.enum(["created","existing","would_create"]),OpsAgentChatRoutineResultSchema=z71.object({id:z71.string().uuid().nullable(),name:z71.string(),schedule:ChatRoutineScheduleSchema.nullable(),nextRunAt:z71.string().nullable(),paused:z71.boolean(),outcome:z71.enum(["created","would_create"]),source:z71.enum(["spec","template"])}),OpsAgentChatCreateResultSchema=z71.object({target:z71.object({backendProfile:OpsBackendProfileSchema,projectId:z71.string().uuid()}),dryRun:z71.boolean(),applied:z71.boolean(),createdBy:z71.object({userId:z71.string()}),agent:z71.object({id:z71.string().uuid().nullable(),title:z71.string(),template:z71.string().nullable(),outcome:OpsAgentChatOutcomeSchema}),routines:z71.array(OpsAgentChatRoutineResultSchema),skipped:z71.array(z71.object({name:z71.string(),reason:z71.literal("routine_exists")})),refused:z71.array(z71.object({name:z71.string(),reason:ChatRoutineRefusalReasonSchema}))})}});import{z as z72}from"zod";var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEnvironmentSelectorSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,DomainCreatedWebhookEventDataSchema,DomainDeletedWebhookEventDataSchema,LabelChangedWebhookEventDataSchema,LocaleCreatedWebhookEventDataSchema,LocaleDefaultChangedWebhookEventDataSchema,LocaleDeletedWebhookEventDataSchema,EnvironmentCreatedWebhookEventDataSchema,EnvironmentDeletedWebhookEventDataSchema,EnvironmentMergedWebhookEventDataSchema,BranchRestoredWebhookEventDataSchema,WebhookEventFamilySchema,WebhookDestinationKindSchema,WebhookHeaderValueInputSchema,WebhookHeaderInputSchema,WebhookHeaderDTOSchema,WebhookFilterSchema,JsonValueSchema,CreateProjectWebhookRequestSchema,UpdateProjectWebhookRequestSchema,TestProjectWebhookRequestSchema,WebhookDeliveryStatusSchema,ProjectWebhookDTOSchema,ProjectWebhookDTO,WebhookDeliveryDTOSchema,WebhookDeliveryDTO,WebhookDeliveriesPageSchema,WebhookDeliveryAttemptDTOSchema,WebhookDeliveryAttemptDTO,ProjectWebhookResponseSchema,ProjectWebhooksListResponseSchema,WebhookDeliveriesListResponseSchema,WebhookDeliveryAttemptsListResponseSchema,init_webhook_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/webhook.dto.js"(){"use strict";init_common();init_env();init_environment();init_create_dto();init_response();init_env_status_dto();init_project_domain_dto();WEBHOOK_EVENT_TYPES=["entry.changed","form.submitted","publish.started","publish.succeeded","publish.failed","publish.unpublished","analytics.report_ready","media.uploaded","media.updated","media.deleted","domain.created","domain.deleted","label.changed","locale.created","locale.default_changed","locale.deleted","environment.created","environment.deleted","environment.merged","branch.restored"],WebhookEventTypeSchema=z72.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z72.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z72.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z72.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z72.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),EntryChangedWebhookEventDataSchema=z72.object({reason:WebhookEntryChangeReasonSchema,operationId:z72.string().optional(),batch:z72.object({index:z72.number().int().positive(),total:z72.number().int().positive()}).optional(),changes:z72.array(z72.object({action:WebhookEntryChangeActionSchema,contentType:z72.string(),id:z72.string(),documentId:z72.string(),locale:z72.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z72.object({form:z72.object({id:z72.string(),label:z72.string()}),submission:z72.object({id:z72.string(),data:z72.record(z72.string(),z72.unknown()),submittedAt:z72.string()})}),PublishStartedWebhookEventDataSchema=z72.object({publication:z72.object({status:z72.literal("publishing"),startedAt:z72.string()})}),PublishSucceededWebhookEventDataSchema=z72.object({publication:z72.object({status:z72.literal("published"),url:z72.string(),publishedAt:z72.string(),firstPublish:z72.boolean()})}),PublishFailedWebhookEventDataSchema=z72.object({publication:z72.object({status:z72.literal("failed"),reason:z72.string()})}),PublishUnpublishedWebhookEventDataSchema=z72.object({publication:z72.object({previousUrl:z72.string(),unpublishedAt:z72.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z72.object({report:z72.object({weekStart:z72.string(),weekEnd:z72.string(),pageviews:z72.number(),visitors:z72.number(),previousPageviews:z72.number(),previousVisitors:z72.number()})}),MediaAssetWebhookEventDataSchema=z72.object({id:z72.string().nullable(),name:z72.string().nullable(),type:z72.string(),mimeType:z72.string().nullable(),fileSize:z72.number().nullable()}),MediaUploadedWebhookEventDataSchema=z72.object({asset:MediaAssetWebhookEventDataSchema,operation:z72.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z72.object({asset:MediaAssetWebhookEventDataSchema,operation:z72.literal("updated")}),MediaDeletedWebhookEventDataSchema=z72.object({asset:MediaAssetWebhookEventDataSchema,operation:z72.literal("deleted")}),DomainCreatedWebhookEventDataSchema=z72.object({domain:z72.object({id:z72.string(),hostname:z72.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z72.object({domain:z72.object({id:z72.string(),hostname:z72.string()})}),LabelChangedWebhookEventDataSchema=z72.object({changes:z72.array(z72.object({action:z72.enum(["created","updated","deleted"]),key:z72.string(),locale:z72.string(),value:z72.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z72.object({locale:z72.object({code:z72.string(),isDefault:z72.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z72.object({locale:z72.object({code:z72.string(),previousCode:z72.string()})}),LocaleDeletedWebhookEventDataSchema=z72.object({locale:z72.object({code:z72.string(),entriesDeleted:z72.number().int().nonnegative(),labelsDeleted:z72.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z72.object({environment:z72.object({name:BranchSchema,parent:BranchSchema})}),EnvironmentDeletedWebhookEventDataSchema=z72.object({environment:z72.object({name:BranchSchema})}),EnvironmentMergedWebhookEventDataSchema=z72.object({merge:z72.object({id:z72.string(),from:BranchSchema,to:BranchSchema,applied:z72.array(z72.object({surface:SurfaceNameSchema,count:z72.number().int().nonnegative()}))})}),BranchRestoredWebhookEventDataSchema=z72.object({branch:z72.object({name:BranchSchema}),version:z72.object({versionId:z72.uuid(),name:z72.string()})}),WebhookEventFamilySchema=z72.enum(["entries","forms","publish","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z72.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z72.discriminatedUnion("source",[z72.object({source:z72.literal("literal"),value:z72.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z72.object({source:z72.literal("secret"),key:z72.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z72.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z72.object({name:z72.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z72.object({name:z72.string(),source:z72.enum(["literal","secret"]),secretKey:z72.string().nullable(),secretPrefix:z72.string().nullable(),configured:z72.literal(!0)}),WebhookFilterSchema=z72.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z72.string().min(1).max(255).optional(),mediaType:z72.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z72.string().min(1).max(255).optional(),locale:z72.string().min(1).max(120).optional()}),JsonValueSchema=z72.lazy(()=>z72.union([z72.string(),z72.number(),z72.boolean(),z72.null(),z72.array(JsonValueSchema),z72.record(z72.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z72.object({name:z72.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z72.url(),enabled:z72.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z72.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z72.boolean().optional().default(!0)}),UpdateProjectWebhookRequestSchema=z72.object({name:z72.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z72.url().optional(),enabled:z72.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z72.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z72.boolean().optional()}),TestProjectWebhookRequestSchema=z72.object({eventType:WebhookEventTypeSchema.optional(),data:z72.record(z72.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z72.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z72.uuid(),name:z72.string(),eventType:WebhookEventTypeSchema,enabled:z72.boolean(),destination:z72.object({host:z72.string(),maskedUrl:z72.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z72.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z72.boolean(),lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z72.coerce.date().nullable(),deliveryStats24h:z72.object({succeeded:z72.number().int().nonnegative(),failed:z72.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z72.uuid(),projectId:z72.uuid(),env:BranchSchema,environment:EnvironmentKeySchema,branch:BranchSchema,eventId:z72.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z72.number().int().positive(),test:z72.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z72.number().int().nonnegative(),responseStatus:z72.number().int().nullable(),lastErrorCode:z72.string().nullable(),lastErrorMessage:z72.string().nullable(),payloadAvailable:z72.boolean(),destination:z72.object({host:z72.string(),maskedUrl:z72.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z72.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z72.string().nullable(),qstashMessageId:z72.string().nullable(),deliveredAt:z72.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z72.object({items:z72.array(WebhookDeliveryDTOSchema),pagination:z72.object({page:z72.number().int().positive(),limit:z72.number().int().positive(),total:z72.number().int().nonnegative(),totalPages:z72.number().int().positive(),hasMore:z72.boolean()}),stats:z72.object({total:z72.number().int().nonnegative(),succeeded:z72.number().int().nonnegative(),failed:z72.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z72.object({id:z72.uuid(),deliveryId:z72.uuid(),attempt:z72.number().int().positive(),status:z72.enum(["delivering","succeeded","failed"]),responseStatus:z72.number().int().nullable(),durationMs:z72.number().int().nonnegative(),responseExcerpt:z72.string().nullable(),errorCode:z72.string().nullable(),errorMessage:z72.string().nullable(),createdAt:z72.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z72.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z72.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z73}from"zod";var PreviewFeatureDTOSchema,PreviewFeatureDTO,init_preview_feature_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/preview-feature.dto.js"(){"use strict";init_create_dto();PreviewFeatureDTOSchema=z73.object({key:z73.literal("fimo-2"),enabled:z73.boolean(),dismissed:z73.boolean().default(!1),interacted:z73.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z74}from"zod";var SiteOnboardingStageSchema,SiteScanStatusSchema,SiteCloneStatusSchema,SiteRefusalCodeSchema,SiteRefusalSchema,SiteCheckGroupSchema,SiteScoreSchema,SITE_CHECKS,SiteCheckIdSchema,SiteCheckStatusSchema,SiteCheckEvidenceSchema,SiteCheckResultSchema,SiteReportGroupSchema,SiteReportSchema,SitePriceTierSchema,SiteTypeSchema,SiteTermsCategorySchema,SITE_QUESTION,SITE_QUESTIONS,SiteUnderstandingSchema,SiteSuggestionSchema,SiteInterviewSuggestionsSchema,SiteInterviewAnswerSchema,SiteInterviewSchema,AnswerSiteInterviewRequestSchema,SiteFixesReportSchema,SiteOnboardingResultSchema,StartSiteOnboardingRequestSchema,StartSiteOnboardingResponseSchema,SiteOnboardingRefusedResponseSchema,SiteOnboardingStateSchema,SiteOnboardingStateDTO,SiteOnboardingStateResponseSchema,RetrySiteOnboardingRequestSchema,SiteOnboardingOutcomeSchema,AdminSiteOnboardingsQuerySchema,AdminSiteOnboardingDTOSchema,AdminSiteOnboardingDTO,AdminSiteOnboardingsResponseSchema,AdminSiteOnboardingStatsSchema,AdminSiteOnboardingStatsResponseSchema,AdminSiteOnboardingDetailSchema,AdminSiteOnboardingDetailDTO,AdminSiteOnboardingDetailResponseSchema,init_site_onboarding_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/site-onboarding.dto.js"(){"use strict";init_create_dto();init_response();SiteOnboardingStageSchema=z74.enum(["scanning","interviewing","reporting","open","expired","refused"]),SiteScanStatusSchema=z74.enum(["running","done","failed"]),SiteCloneStatusSchema=z74.enum(["not_started","running","paused","finished","failed"]),SiteRefusalCodeSchema=z74.enum(["invalid","private","not_found","tls","unreachable","redirect","error_page","bot_wall"]),SiteRefusalSchema=z74.object({code:SiteRefusalCodeSchema,suggestedUrl:z74.string().nullable()}),SiteCheckGroupSchema=z74.enum(["discovery","indexing","ai_crawlers","rendering","metadata","content","speed"]),SiteScoreSchema=z74.enum(["seo","geo"]),SITE_CHECKS=[{id:"robots_txt",group:"discovery",scores:["seo","geo"],weight:2},{id:"sitemap",group:"discovery",scores:["seo","geo"],weight:2},{id:"sitemap_lastmod",group:"discovery",scores:["seo","geo"],weight:1},{id:"broken_links",group:"discovery",scores:["seo"],weight:2},{id:"internal_nofollow",group:"discovery",scores:["seo"],weight:1},{id:"blocked_from_crawling",group:"discovery",scores:["seo","geo"],weight:3,cap:{seo:20,geo:20}},{id:"status_4xx",group:"indexing",scores:["seo","geo"],weight:2,cap:{seo:10,geo:10}},{id:"status_5xx",group:"indexing",scores:["seo","geo"],weight:3,cap:{seo:10,geo:10}},{id:"https_to_http",group:"indexing",scores:["seo"],weight:1,cap:{seo:50}},{id:"canonical",group:"indexing",scores:["seo"],weight:1},{id:"noindex",group:"indexing",scores:["seo","geo"],weight:3,cap:{seo:20,geo:20}},{id:"hreflang",group:"indexing",scores:["seo"],weight:1},{id:"missing_page",group:"indexing",scores:["seo","geo"],weight:1,cap:{seo:80,geo:80}},{id:"ai_bots_robots",group:"ai_crawlers",scores:["geo"],weight:3,cap:{geo:30}},{id:"ai_bot_access",group:"ai_crawlers",scores:["geo"],weight:2,cap:{geo:40}},{id:"llms_txt",group:"ai_crawlers",scores:["geo"],weight:1},{id:"server_rendering",group:"rendering",scores:["geo"],weight:3},{id:"semantic_html",group:"rendering",scores:["seo","geo"],weight:2},{id:"markdown_pages",group:"rendering",scores:["geo"],weight:1},{id:"markdown_alternate",group:"rendering",scores:["geo"],weight:.5},{id:"markdown_index",group:"rendering",scores:["geo"],weight:.5},{id:"meta_title",group:"metadata",scores:["seo"],weight:2},{id:"meta_description",group:"metadata",scores:["seo"],weight:2},{id:"structured_data",group:"metadata",scores:["seo","geo"],weight:2},{id:"organization_schema",group:"metadata",scores:["geo"],weight:2},{id:"entity_links",group:"metadata",scores:["geo"],weight:1},{id:"metadata_completeness",group:"metadata",scores:["seo","geo"],weight:2},{id:"trust_pages",group:"metadata",scores:["geo"],weight:2},{id:"word_count",group:"content",scores:["seo","geo"],weight:2},{id:"text_ratio",group:"content",scores:["seo"],weight:1},{id:"h1",group:"content",scores:["seo"],weight:2},{id:"image_alt",group:"content",scores:["seo","geo"],weight:1},{id:"broken_images",group:"content",scores:["seo"],weight:1},{id:"empty_link_text",group:"content",scores:["seo","geo"],weight:1},{id:"page_load",group:"speed",scores:["seo"],weight:3},{id:"unminified_assets",group:"speed",scores:["seo"],weight:1}],SiteCheckIdSchema=z74.enum(SITE_CHECKS.map(check=>check.id)),SiteCheckStatusSchema=z74.enum(["pass","partial","fail","not_scored"]),SiteCheckEvidenceSchema=z74.record(z74.string(),z74.union([z74.string(),z74.number(),z74.boolean(),z74.array(z74.string())])),SiteCheckResultSchema=z74.object({id:SiteCheckIdSchema,status:SiteCheckStatusSchema,evidence:SiteCheckEvidenceSchema}),SiteReportGroupSchema=z74.object({id:SiteCheckGroupSchema,score:z74.number().int().min(0).max(100).nullable()}),SiteReportSchema=z74.object({siteUrl:z74.string(),scannedAt:z74.coerce.date(),seoScore:z74.number().int().min(0).max(100).nullable(),geoScore:z74.number().int().min(0).max(100).nullable(),groups:z74.array(SiteReportGroupSchema),checks:z74.array(SiteCheckResultSchema),blockers:z74.array(SiteCheckIdSchema).default([])}),SitePriceTierSchema=z74.enum(["budget","standard","premium","luxury"]),SiteTypeSchema=z74.enum(["business","non_profit","portfolio","hobby","personal"]),SiteTermsCategorySchema=z74.enum(["violence","child_harm","harassment","hate","self_harm","adult","deception","scam"]),SITE_QUESTION={id:"site",kind:"confirm"},SITE_QUESTIONS={business:[SITE_QUESTION,{id:"competitors",kind:"form",inputs:[{id:"names",kind:"choices",multiple:!0,allowOther:!0,options:"competitors"}]},{id:"positioning",kind:"form",inputs:[{id:"positioning",kind:"text",max:2e3}]},{id:"priceTier",kind:"form",inputs:[{id:"priceTier",kind:"choices",multiple:!1,allowOther:!1,options:SitePriceTierSchema.options}]}],non_profit:[SITE_QUESTION,{id:"action",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!1,allowOther:!0,options:["volunteer","donate","join","next_event"]}]},{id:"searches",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!0,allowOther:!0,options:"model"}]}],portfolio:[SITE_QUESTION,{id:"work",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!0,allowOther:!0,options:"model"}]},{id:"action",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!1,allowOther:!0,options:["book_call","request_quote","email","follow"]}]}],hobby:[SITE_QUESTION,{id:"return",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!0,allowOther:!0,options:["creations","tutorials","progress","tips"]}]},{id:"tone",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!1,allowOther:!1,options:["warm","expert","playful","calm"]}]}],personal:[SITE_QUESTION,{id:"remember",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!1,allowOther:!0,options:"model"}]},{id:"action",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!1,allowOther:!0,options:["read","contact","hire","follow"]}]}]},SiteUnderstandingSchema=z74.object({name:z74.string(),summary:z74.string(),audience:z74.string(),positioning:z74.string(),priceTier:SitePriceTierSchema,homepage:z74.string()}),SiteSuggestionSchema=z74.object({label:z74.string(),url:z74.string().nullable()}),SiteInterviewSuggestionsSchema=z74.record(z74.string(),z74.record(z74.string(),z74.array(SiteSuggestionSchema))),SiteInterviewAnswerSchema=z74.record(z74.string().max(50),z74.union([z74.string().trim().max(2e3),z74.array(z74.string().trim().min(1).max(200)).max(10)])),SiteInterviewSchema=z74.object({status:z74.enum(["waiting","drafting","ready","failed"]),siteType:SiteTypeSchema.nullable(),site:SiteUnderstandingSchema.nullable(),suggestions:SiteInterviewSuggestionsSchema,answers:z74.record(z74.string(),SiteInterviewAnswerSchema)}),AnswerSiteInterviewRequestSchema=z74.object({questionId:z74.string().min(1).max(50),answer:SiteInterviewAnswerSchema}),SiteFixesReportSchema=z74.object({fixes:z74.array(z74.object({checkId:SiteCheckIdSchema,status:z74.enum(["fixed","not_fixed","not_applicable"]),note:z74.string().trim().min(1).max(300)})).min(1).max(40)}),SiteOnboardingResultSchema=z74.object({fixes:SiteFixesReportSchema.nullable(),summary:z74.string().nullable()}),StartSiteOnboardingRequestSchema=z74.object({organizationId:z74.string().min(1),url:z74.string().trim().min(1).max(2048),locale:z74.string().trim().min(2).max(16).default("en")}),StartSiteOnboardingResponseSchema=createResponseSchema(z74.object({projectId:z74.string()})),SiteOnboardingRefusedResponseSchema=z74.object({error:z74.literal("site_refused"),refusal:SiteRefusalSchema}),SiteOnboardingStateSchema=z74.object({projectId:z74.string(),siteUrl:z74.string(),stage:SiteOnboardingStageSchema,scanStatus:SiteScanStatusSchema,cloneStatus:SiteCloneStatusSchema,cloneRetryAvailable:z74.boolean(),budgetExhausted:z74.boolean(),sponsored:z74.boolean(),cloneOutOfCredits:z74.boolean(),interview:SiteInterviewSchema.nullable(),cloneThreadId:z74.string().nullable(),welcomeThreadId:z74.string().nullable(),competitors:z74.array(z74.string()),report:SiteReportSchema.nullable(),reportExpiresAt:z74.coerce.date(),openedAt:z74.coerce.date().nullable(),bannerDismissed:z74.boolean()}),SiteOnboardingStateDTO=createDTO(SiteOnboardingStateSchema),SiteOnboardingStateResponseSchema=createResponseSchema(SiteOnboardingStateSchema.nullable()),RetrySiteOnboardingRequestSchema=z74.object({task:z74.enum(["interview","scan","clone"])}),SiteOnboardingOutcomeSchema=z74.enum(["finished","rebuilding","paused","failed","scan_failed","scanning","expired","refused","not_started"]),AdminSiteOnboardingsQuerySchema=z74.object({search:z74.string().trim().max(200).optional(),organizationId:z74.string().trim().min(1).max(200).optional(),startDate:z74.coerce.date().optional(),endDate:z74.coerce.date().optional(),outcomes:z74.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z74.array(SiteOnboardingOutcomeSchema).optional()),siteTypes:z74.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z74.array(SiteTypeSchema).optional()),page:z74.coerce.number().int().min(1).default(1),pageSize:z74.coerce.number().int().min(1).max(100).default(25)}),AdminSiteOnboardingDTOSchema=z74.object({projectId:z74.string(),projectName:z74.string(),organizationId:z74.string(),organizationName:z74.string().nullable(),ownerEmail:z74.string().nullable(),ownerName:z74.string().nullable(),siteUrl:z74.string(),stage:SiteOnboardingStageSchema,scanStatus:SiteScanStatusSchema,cloneStatus:SiteCloneStatusSchema,outcome:SiteOnboardingOutcomeSchema,sponsored:z74.boolean(),cloneRetries:z74.number(),siteType:SiteTypeSchema.nullable(),refusalCategory:SiteTermsCategorySchema.nullable(),interviewAnswers:z74.number(),interviewQuestions:z74.number().nullable(),seoScore:z74.number().nullable(),geoScore:z74.number().nullable(),spentUsd:z74.number(),budgetCapUsd:z74.number(),capReached:z74.boolean(),cloneSeconds:z74.number().nullable(),createdAt:z74.coerce.date(),openedAt:z74.coerce.date().nullable()}),AdminSiteOnboardingDTO=createDTO(AdminSiteOnboardingDTOSchema),AdminSiteOnboardingsResponseSchema=createResponseSchema(z74.object({onboardings:z74.array(AdminSiteOnboardingDTOSchema),page:z74.number(),limit:z74.number(),total:z74.number(),totalPages:z74.number()})),AdminSiteOnboardingStatsSchema=z74.object({total:z74.number(),outcomes:z74.record(SiteOnboardingOutcomeSchema,z74.number()),funnel:z74.object({started:z74.number(),confirmed:z74.number(),finished:z74.number(),opened:z74.number()}),bySiteType:z74.array(z74.object({siteType:SiteTypeSchema,total:z74.number(),finished:z74.number(),opened:z74.number()})),granularity:z74.enum(["hour","day"]),series:z74.array(z74.object({at:z74.coerce.date(),outcomes:z74.record(SiteOnboardingOutcomeSchema,z74.number())})),spentUsd:z74.object({total:z74.number(),average:z74.number().nullable()}),sponsored:z74.number(),paidByOrganization:z74.object({usd:z74.number(),credits:z74.number()}),capReached:z74.number(),cloneSeconds:z74.object({median:z74.number().nullable(),average:z74.number().nullable()})}),AdminSiteOnboardingStatsResponseSchema=createResponseSchema(AdminSiteOnboardingStatsSchema),AdminSiteOnboardingDetailSchema=z74.object({onboarding:AdminSiteOnboardingDTOSchema.extend({locale:z74.string(),cloneThreadId:z74.string().nullable(),paidByOrganizationUsd:z74.number()}),interview:SiteInterviewSchema.extend({invocationIds:z74.array(z74.string())}).nullable(),knowledgeWritten:z74.string().nullable(),knowledgeNow:z74.object({content:z74.string(),updatedAt:z74.coerce.date().nullable(),updatedBy:z74.string().nullable()}),report:SiteReportSchema.nullable()}),AdminSiteOnboardingDetailDTO=createDTO(AdminSiteOnboardingDetailSchema),AdminSiteOnboardingDetailResponseSchema=createResponseSchema(AdminSiteOnboardingDetailSchema)}});import{z as z75}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=z75.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z75.object({total:z75.number(),base:z75.number(),purchases:z75.number(),awards:z75.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z75.object({id:z75.string(),name:z75.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z75.object({type:z75.string(),brand:z75.string().nullable(),last4:z75.string().nullable(),expirationDate:z75.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z75.object({currency:z75.string(),nextPaymentAmount:z75.number().nullable(),nextPaymentAt:z75.string().nullable(),billingInterval:z75.string().nullable(),totalAmount:z75.number().nullable(),discountAmount:z75.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z75.object({id:z75.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z75.string().nullable(),currentPeriodEndsAt:z75.string().nullable(),renewsAt:z75.string().nullable(),cancelAt:z75.string().nullable(),renewAutomatically:z75.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z75.object({type:z75.enum(["low_balance","critical_balance","approaching_limit"]),message:z75.string(),estimatedPromptsRemaining:z75.number().nullable(),avgCostPerPrompt:z75.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z75.object({monthlyCredits:z75.number().nullable(),usedThisPeriod:z75.number(),remainingThisPeriod:z75.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z75.object({organizationId:z75.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z75.string().nullable(),tenureDays:z75.number().int().nonnegative(),capturedAt:z75.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z75.object({hasSubscription:z75.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z75.number().nullable(),alerts:z75.array(CreditAlertDTOSchema),portalUrl:z75.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z75.object({creditCount:z75.number().int().positive(),expiresAt:z75.string().datetime().nullable().optional(),message:z75.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z75.literal("free"),amountCents:z75.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z75.literal("purchase"),amountCents:z75.number().int().positive()}),CreditTopupRequestDTOSchema=z75.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z75.object({success:z75.boolean(),transactionId:z75.string().nullable(),newBalance:z75.number(),creditCount:z75.number(),type:z75.enum(["free","purchase"]),invoiceId:z75.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z76}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=z76.object({totalCredits:z76.number(),totalCostUsd:z76.number(),totalMessages:z76.number(),avgCostPerMessage:z76.number(),periodStart:z76.string().nullable(),periodEnd:z76.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z76.object({projectId:z76.string(),projectName:z76.string(),projectDisplayName:z76.string().nullable(),credits:z76.number(),costUsd:z76.number(),messages:z76.number(),percentage:z76.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z76.object({userId:z76.string(),userName:z76.string().nullable(),userEmail:z76.string().email().nullable(),credits:z76.number(),costUsd:z76.number(),messages:z76.number(),percentage:z76.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z76.object({date:z76.string(),credits:z76.number(),costUsd:z76.number(),messages:z76.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z76.object({userId:z76.string(),userName:z76.string().nullable(),userEmail:z76.string().email().nullable(),credits:z76.number(),costUsd:z76.number(),messages:z76.number(),percentage:z76.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z76.object({projectId:z76.string(),projectName:z76.string(),projectDisplayName:z76.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z76.array(UsageByUserForProjectDTOSchema),timeline:z76.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z76.object({summary:UsageSummaryDTOSchema,byProject:z76.array(UsageByProjectDTOSchema),byUser:z76.array(UsageByUserDTOSchema),timeline:z76.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z77}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=z77.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z77.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z77.object({startDate:z77.string().optional(),endDate:z77.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z77.coerce.number().int().positive().default(1),limit:z77.coerce.number().int().positive().max(100).default(20),sortBy:z77.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z77.string().optional(),activeOnly:z77.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z77.object({totalCredits:z77.number(),totalCostUsd:z77.number(),totalMessages:z77.number(),avgCostPerMessage:z77.number(),avgCreditsPerMessage:z77.number(),periodStart:z77.string(),periodEnd:z77.string(),creditsChange:z77.number().nullable(),costChange:z77.number().nullable(),messagesChange:z77.number().nullable(),unattributedCredits:z77.number(),unattributedCostUsd:z77.number(),unattributedMessages:z77.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z77.object({date:z77.string(),credits:z77.number(),costUsd:z77.number(),messages:z77.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z77.object({organizationId:z77.string(),organizationName:z77.string(),credits:z77.number(),costUsd:z77.number(),messages:z77.number(),percentage:z77.number(),userCount:z77.number(),projectCount:z77.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z77.object({userId:z77.string(),userName:z77.string().nullable(),userEmail:z77.string().nullable(),userImage:z77.string().nullable(),organizationId:z77.string().nullable(),organizationName:z77.string().nullable(),credits:z77.number(),costUsd:z77.number(),messages:z77.number(),percentage:z77.number(),projectCount:z77.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z77.object({projectId:z77.string(),projectName:z77.string(),projectDisplayName:z77.string().nullable(),organizationId:z77.string(),organizationName:z77.string(),credits:z77.number(),costUsd:z77.number(),messages:z77.number(),percentage:z77.number(),userCount:z77.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z77.object({id:z77.string(),name:z77.string(),value:z77.number(),percentage:z77.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z77.object({day:z77.number(),hour:z77.number(),value:z77.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z77.object({summary:UsageOverviewSummaryDTOSchema,timeline:z77.array(UsageTimelinePointDTOSchema),topOrganizations:z77.array(OrganizationUsageRowDTOSchema),topUsers:z77.array(UserUsageRowDTOSchema),topProjects:z77.array(ProjectUsageRowDTOSchema),creditDistribution:z77.array(UsageDistributionItemDTOSchema),userDistribution:z77.array(UsageDistributionItemDTOSchema),heatmap:z77.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z77.object({page:z77.number(),limit:z77.number(),totalItems:z77.number(),totalPages:z77.number(),hasMore:z77.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z77.object({organizations:z77.array(OrganizationUsageRowDTOSchema),top:z77.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z77.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z77.object({users:z77.array(ExtendedUserUsageRowDTOSchema),top:z77.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z77.string(),ownerName:z77.string().nullable(),ownerEmail:z77.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z77.object({projects:z77.array(ExtendedProjectUsageRowDTOSchema),top:z77.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z77.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z77.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z77.object({credits:z77.number(),costUsd:z77.number(),messages:z77.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z77.object({id:z77.string(),name:z77.string(),createdAt:z77.string(),memberCount:z77.number(),projectCount:z77.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z77.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z77.object({id:z77.string(),name:z77.string().nullable(),email:z77.string(),image:z77.string().nullable(),createdAt:z77.string(),organizationCount:z77.number(),projectCount:z77.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z77.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z77.object({id:z77.string(),name:z77.string(),displayName:z77.string().nullable(),createdAt:z77.string(),organizationId:z77.string(),organizationName:z77.string(),ownerId:z77.string(),ownerName:z77.string().nullable(),ownerEmail:z77.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z77.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z78}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=z78.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z78.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z78.object({command:z78.string().min(1).max(1e4),cwd:z78.string().optional(),projectBranch:BranchSchema.optional(),projectEnv:BranchSchema.optional(),env:z78.record(z78.string(),z78.string()).optional(),name:z78.string().optional(),waitForCompletion:z78.boolean().optional().default(!1)}).superRefine((value,ctx)=>{value.projectBranch!==void 0&&value.projectEnv!==void 0&&value.projectBranch!==value.projectEnv&&ctx.addIssue({code:"custom",path:["projectBranch"],message:"`projectBranch` and deprecated `projectEnv` must match when both are supplied"})}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z78.object({identifier:z78.string(),status:SandboxProcessStatusSchema,command:z78.string().optional(),startedAt:z78.string().optional(),exitCode:z78.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z78.object({processes:z78.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z78.object({processId:z78.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z78.object({success:z78.boolean(),message:z78.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z79}from"zod";var WorkSessionVisibilitySchema,SessionSetRetentionSchema,init_work_sessions=__esm({"../../packages/api-contracts/dist/esm/work-sessions.js"(){"use strict";WorkSessionVisibilitySchema=z79.enum(["internal","user-visible"]),SessionSetRetentionSchema=z79.object({additionalDays:z79.number().int().min(1).max(30)}).strict()}});import{z as z80}from"zod";var PROJECT_KNOWLEDGE_MAX_CHARACTERS,ProjectKnowledgeContentSchema,ProjectKnowledgeDTOSchema,ProjectKnowledgeUpdateSchema,ProjectKnowledgeResponseSchema,ProjectKnowledgeDraftDTOSchema,ProjectKnowledgeDraftResponseSchema,ProjectKnowledgeDraftStartSchema,init_project_knowledge_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-knowledge.dto.js"(){"use strict";init_response();PROJECT_KNOWLEDGE_MAX_CHARACTERS=1e4,ProjectKnowledgeContentSchema=z80.string().refine(value=>[...value].length<=PROJECT_KNOWLEDGE_MAX_CHARACTERS&&new TextEncoder().encode(value).length<=4e4,"Knowledge must contain at most 10,000 characters and 40 KB of UTF-8 text"),ProjectKnowledgeDTOSchema=z80.object({content:ProjectKnowledgeContentSchema,updatedAt:z80.string().nullable(),updatedBy:z80.string().nullable()}),ProjectKnowledgeUpdateSchema=z80.object({content:ProjectKnowledgeContentSchema}),ProjectKnowledgeResponseSchema=createResponseSchema(ProjectKnowledgeDTOSchema),ProjectKnowledgeDraftDTOSchema=z80.object({id:z80.uuid(),status:z80.enum(["queued","running","ready","failed"]),content:ProjectKnowledgeContentSchema.nullable(),error:z80.string().nullable()}),ProjectKnowledgeDraftResponseSchema=createResponseSchema(ProjectKnowledgeDraftDTOSchema.nullable()),ProjectKnowledgeDraftStartSchema=z80.object({idempotencyKey:z80.uuid()})}});import{z as z81}from"zod";var ORGANIZATION_FEATURES,OrganizationFeatureSchema,OrganizationFeaturesDTOSchema,OrganizationFeaturesDTO,OrganizationFeatureStateDTOSchema,OrganizationFeatureSetSchema,init_organization_features_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization-features.dto.js"(){"use strict";init_create_dto();ORGANIZATION_FEATURES=["agents"],OrganizationFeatureSchema=z81.enum(ORGANIZATION_FEATURES),OrganizationFeaturesDTOSchema=z81.object({features:z81.record(OrganizationFeatureSchema,z81.boolean())}),OrganizationFeaturesDTO=createDTO(OrganizationFeaturesDTOSchema),OrganizationFeatureStateDTOSchema=z81.object({feature:OrganizationFeatureSchema,enabled:z81.boolean(),default:z81.boolean(),override:z81.boolean().nullable(),reason:z81.string().nullable(),updatedBy:z81.string().nullable(),updatedAt:z81.string().datetime().nullable()}),OrganizationFeatureSetSchema=z81.object({state:z81.enum(["on","off","default"]),reason:z81.string().trim().min(1).max(500),apply:z81.boolean().default(!1),confirmProduction:z81.boolean().default(!1)})}});import{z as z82}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_asset_reading();init_env();init_environment();init_realtime();init_realtime_room();init_references();init_content_fields();init_audit_log();init_ops();init_chat_block();init_chat_portrait();init_agent_report();init_fimo_config();init_page_sources();init_project_files();init_project_dto();init_project_env_dto();init_project_environment_dto();init_project_secret_dto();init_project_import_export_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_question_dto();init_integration_dto();init_schedule_dto();init_schedule_notifications_dto();init_notification_dto();init_notification_preference_catalog_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_hosted_preview_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_project_migration_dto();init_analytics_dto();init_asset_dto();init_translation_dto();init_document_dto();init_form_dto();init_chat_dto();init_chat_routine_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_transfer_dto();init_unclaimed_project_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_ops_sentry_dto();init_ops_project_files_dto();init_ops_agent_chat_dto();init_webhook_dto();init_preview_feature_dto();init_site_onboarding_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto();init_work_sessions();init_project_knowledge_dto();init_organization_features_dto()}});var require_picocolors=__commonJS({"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports2,module2){var p2=process||{},argv=p2.argv||[],env=p2.env||{},isColorSupported=!(env.NO_COLOR||argv.includes("--no-color"))&&(!!env.FORCE_COLOR||argv.includes("--color")||p2.platform==="win32"||(p2.stdout||{}).isTTY&&env.TERM!=="dumb"||!!env.CI),formatter=__name((open2,close,replace=open2)=>input=>{let string=""+input,index=string.indexOf(close,open2.length);return~index?open2+replaceClose(string,close,replace,index)+close:open2+string+close},"formatter"),replaceClose=__name((string,close,replace,index)=>{let result="",cursor=0;do result+=string.substring(cursor,index)+replace,cursor=index+close.length,index=string.indexOf(close,cursor);while(~index);return result+string.substring(cursor)},"replaceClose"),createColors=__name((enabled=isColorSupported)=>{let f=enabled?formatter:()=>String;return{isColorSupported:enabled,reset:f("\x1B[0m","\x1B[0m"),bold:f("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:f("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:f("\x1B[3m","\x1B[23m"),underline:f("\x1B[4m","\x1B[24m"),inverse:f("\x1B[7m","\x1B[27m"),hidden:f("\x1B[8m","\x1B[28m"),strikethrough:f("\x1B[9m","\x1B[29m"),black:f("\x1B[30m","\x1B[39m"),red:f("\x1B[31m","\x1B[39m"),green:f("\x1B[32m","\x1B[39m"),yellow:f("\x1B[33m","\x1B[39m"),blue:f("\x1B[34m","\x1B[39m"),magenta:f("\x1B[35m","\x1B[39m"),cyan:f("\x1B[36m","\x1B[39m"),white:f("\x1B[37m","\x1B[39m"),gray:f("\x1B[90m","\x1B[39m"),bgBlack:f("\x1B[40m","\x1B[49m"),bgRed:f("\x1B[41m","\x1B[49m"),bgGreen:f("\x1B[42m","\x1B[49m"),bgYellow:f("\x1B[43m","\x1B[49m"),bgBlue:f("\x1B[44m","\x1B[49m"),bgMagenta:f("\x1B[45m","\x1B[49m"),bgCyan:f("\x1B[46m","\x1B[49m"),bgWhite:f("\x1B[47m","\x1B[49m"),blackBright:f("\x1B[90m","\x1B[39m"),redBright:f("\x1B[91m","\x1B[39m"),greenBright:f("\x1B[92m","\x1B[39m"),yellowBright:f("\x1B[93m","\x1B[39m"),blueBright:f("\x1B[94m","\x1B[39m"),magentaBright:f("\x1B[95m","\x1B[39m"),cyanBright:f("\x1B[96m","\x1B[39m"),whiteBright:f("\x1B[97m","\x1B[39m"),bgBlackBright:f("\x1B[100m","\x1B[49m"),bgRedBright:f("\x1B[101m","\x1B[49m"),bgGreenBright:f("\x1B[102m","\x1B[49m"),bgYellowBright:f("\x1B[103m","\x1B[49m"),bgBlueBright:f("\x1B[104m","\x1B[49m"),bgMagentaBright:f("\x1B[105m","\x1B[49m"),bgCyanBright:f("\x1B[106m","\x1B[49m"),bgWhiteBright:f("\x1B[107m","\x1B[49m")}},"createColors");module2.exports=createColors();module2.exports.createColors=createColors}});function makePalette(enabled){return enabled?{success:import_picocolors.default.green,warn:import_picocolors.default.yellow,error:import_picocolors.default.red,hint:import_picocolors.default.cyan,dim:import_picocolors.default.dim,accent:import_picocolors.default.bold}:{success:identity,warn:identity,error:identity,hint:identity,dim:identity,accent:identity}}var import_picocolors,identity,init_colors=__esm({"../../packages/cli-kit/dist/colors.js"(){"use strict";import_picocolors=__toESM(require_picocolors(),1),identity=__name(s=>s,"identity");__name(makePalette,"makePalette")}});var SCHEMA_VERSION,init_types=__esm({"../../packages/cli-kit/dist/types.js"(){"use strict";SCHEMA_VERSION=1}});function makeJsonRenderer(opts){let{stdout,stderr}=opts,pendingWarnings=[];function emit(stream,envelope){let warnings=[...pendingWarnings,...envelope.warnings??[]].filter((warning,index,all)=>all.indexOf(warning)===index);pendingWarnings=[],stream.write(`${JSON.stringify(warnings.length>0?{...envelope,warnings}:envelope)}
|
|
5
|
+
`)}function reportSectionContentLength(blocks){return blocks.reduce((total,block)=>total+(block.title?.length??0)+derivedBlockBody(block).length+(block.fallback?.length??0),0)}function formatReportNumber(value){return Number.isInteger(value)?String(value):String(Number(value.toFixed(2)))}function formatReportValue(value,unit){let formatted=formatReportNumber(value);return unit?`${formatted}${new RegExp("^\\p{L}","u").test(unit)?" ":""}${unit}`:formatted}var REPORT_TITLE_MAX_CHARS,REPORT_BRIEF_MAX_BLOCKS,REPORT_DETAILS_MAX_BLOCKS,REPORT_BRIEF_MAX_CHARS,REPORT_DETAILS_MAX_CHARS,REPORT_TEXT_MAX_CHARS,REPORT_CODE_MAX_CHARS,REPORT_TONES,ReportToneSchema,blockCommon,ReportTextBlockSchema,ReportMetricBlockSchema,REPORT_VIZ_KINDS,ReportVizKindSchema,ReportVizBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema,ReportBlockSchema,ReportDocumentSchema,ReportBriefSchema,LEGACY_BLOCK_TYPES,StoredReportBriefSchema,StoredReportDocumentSchema,init_agent_report=__esm({"../../packages/api-contracts/dist/esm/types/agent-report.js"(){"use strict";REPORT_TITLE_MAX_CHARS=120,REPORT_BRIEF_MAX_BLOCKS=6,REPORT_DETAILS_MAX_BLOCKS=40,REPORT_BRIEF_MAX_CHARS=4e3,REPORT_DETAILS_MAX_CHARS=48e3,REPORT_TEXT_MAX_CHARS=4e3,REPORT_CODE_MAX_CHARS=8e3,REPORT_TONES=["critical","warning","info","neutral"],ReportToneSchema=z15.enum(REPORT_TONES),blockCommon={title:z15.string().trim().min(1).max(120).optional(),fallback:z15.string().trim().min(1).max(600).optional()},ReportTextBlockSchema=z15.object({type:z15.literal("text"),...blockCommon,text:z15.string().trim().min(1).max(REPORT_TEXT_MAX_CHARS)}).strict().describe("Short connective context or a conclusion with no better structure. Never a multi-item dump."),ReportMetricBlockSchema=z15.object({type:z15.literal("metric"),...blockCommon,items:z15.array(z15.object({value:z15.string().trim().min(1).max(24),unit:z15.string().trim().min(1).max(12).optional(),label:z15.string().trim().min(1).max(160),note:z15.string().trim().min(1).max(300).optional()}).strict()).min(1).max(3),spark:z15.array(z15.number().finite()).min(2).max(24).optional()}).strict().describe("1-3 numbers that materially communicate state, scale, or success. Do not promote incidental counts."),REPORT_VIZ_KINDS=["bar","line","area","composition"],ReportVizKindSchema=z15.enum(REPORT_VIZ_KINDS),ReportVizBlockSchema=z15.object({type:z15.literal("viz"),...blockCommon,kind:ReportVizKindSchema.describe("bar: compare named quantities. line/area: change across an ordered sequence. composition: parts of one whole."),unit:z15.string().trim().min(1).max(12).optional(),points:z15.array(z15.object({label:z15.string().trim().min(1).max(24),value:z15.number().finite(),highlight:z15.boolean().optional()}).strict()).min(2).max(24),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Only when comparison, relationship, distribution, persistence, or change over time is itself the point. Never decorative.").superRefine((block,ctx)=>{block.points.filter(point=>point.highlight).length>1&&ctx.addIssue({code:"custom",path:["points"],message:"Highlight at most one point."}),block.kind==="composition"&&block.points.forEach((point,index)=>{point.value<0&&ctx.addIssue({code:"custom",path:["points",index,"value"],message:"A composition holds parts of one whole, so every value must be zero or more."})})}),ReportListBlockSchema=z15.object({type:z15.literal("list"),...blockCommon,items:z15.array(z15.object({tone:ReportToneSchema.optional(),label:z15.string().trim().min(1).max(24).optional(),heading:z15.string().trim().min(1).max(160).describe("The human-visible result, action, or consequence, readable on its own."),body:z15.string().trim().min(1).max(1200).optional().describe("One short explanation of why it matters."),evidence:z15.string().trim().min(1).max(600).optional().describe("Exact supporting proof: paths, keys, literal values, compact measurements.")}).strict()).min(1).max(12)}).strict().describe("Ranked items sharing one hierarchy: findings, recommendations, steps, sources, or a single callout. heading = human consequence, body = why it matters, evidence = the technical proof. Do not repeat the report title."),ReportTableBlockSchema=z15.object({type:z15.literal("table"),...blockCommon,columns:z15.array(z15.object({label:z15.string().trim().min(1).max(32)}).strict()).min(1).max(6),rows:z15.array(z15.object({cells:z15.array(z15.object({text:z15.string().trim().max(160),tone:ReportToneSchema.optional()}).strict()).min(1).max(6)}).strict()).min(1).max(40),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Repeated entities sharing the same attributes. Use instead of parallel prose.").superRefine((block,ctx)=>{block.rows.forEach((row2,index)=>{row2.cells.length!==block.columns.length&&ctx.addIssue({code:"custom",path:["rows",index,"cells"],message:`Every row needs exactly ${block.columns.length} cells, one per column.`})})}),ReportMediaBlockSchema=z15.object({type:z15.literal("media"),...blockCommon,assetId:z15.uuid(),alt:z15.string().trim().min(1).max(300),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("Only visual or recorded evidence, or a media deliverable: a before/after, a layout defect, a generated asset. Never decoration."),ReportLinksBlockSchema=z15.object({type:z15.literal("links"),...blockCommon,items:z15.array(z15.object({label:z15.string().trim().min(1).max(120),url:z15.url({protocol:/^https$/}).max(2e3),description:z15.string().trim().min(1).max(300).optional()}).strict()).min(1).max(8)}).strict().describe("A destination, evidence source, or next action worth opening."),ReportCodeBlockSchema=z15.object({type:z15.literal("code"),...blockCommon,language:z15.string().regex(/^[a-z0-9+#-]{1,20}$/,"A language is a short lowercase token, e.g. ts, json, bash.").optional(),code:z15.string().min(1).max(REPORT_CODE_MAX_CHARS),caption:z15.string().trim().min(1).max(600).optional()}).strict().describe("An exact snippet that is decisive evidence. Never a log dump."),ReportBlockSchema=z15.discriminatedUnion("type",[ReportTextBlockSchema,ReportMetricBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportVizBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema]),ReportDocumentSchema=z15.object({title:z15.string().trim().min(1).max(REPORT_TITLE_MAX_CHARS),brief:z15.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),details:z15.array(ReportBlockSchema).max(REPORT_DETAILS_MAX_BLOCKS)}).strict().superRefine((document,ctx)=>{let brief=reportSectionContentLength(document.brief);brief>REPORT_BRIEF_MAX_CHARS&&ctx.addIssue({code:"custom",path:["brief"],message:`The brief holds ${brief} characters of content; keep it under ${REPORT_BRIEF_MAX_CHARS}. Move evidence into details.`});let details=reportSectionContentLength(document.details);details>REPORT_DETAILS_MAX_CHARS&&ctx.addIssue({code:"custom",path:["details"],message:`The details hold ${details} characters of content; the limit is ${REPORT_DETAILS_MAX_CHARS}.`})}),ReportBriefSchema=z15.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),LEGACY_BLOCK_TYPES={findings:"list",series:"viz",image:"media"};__name(normalizeStoredBlock,"normalizeStoredBlock");__name(normalizeStoredBlocks,"normalizeStoredBlocks");__name(normalizeStoredDocument,"normalizeStoredDocument");StoredReportBriefSchema=z15.preprocess(normalizeStoredBlocks,ReportBriefSchema),StoredReportDocumentSchema=z15.preprocess(normalizeStoredDocument,ReportDocumentSchema);__name(derivedBlockBody,"derivedBlockBody");__name(reportSectionContentLength,"reportSectionContentLength");__name(formatReportNumber,"formatReportNumber");__name(formatReportValue,"formatReportValue")}});import{z as z16}from"zod";var FIMO_CONFIG_PATH,LEGACY_FIMO_CONFIG_PATHS,ALL_FIMO_CONFIG_PATHS,FimoFrameworkSchema,FimoRuntimeCommandsSchema,FimoRuntimeConfigSchema,FimoHostingConditionSchema,conditionFields,FimoHostingRewriteSchema,FimoHostingRedirectSchema,FimoHostingHeaderSchema,FimoHostingConfigSchema,FimoAppConfigSchema,init_fimo_config=__esm({"../../packages/api-contracts/dist/esm/types/fimo-config.js"(){"use strict";FIMO_CONFIG_PATH=".fimo/config.json",LEGACY_FIMO_CONFIG_PATHS=["fimo-config.json","fimo.config.json"],ALL_FIMO_CONFIG_PATHS=[FIMO_CONFIG_PATH,...LEGACY_FIMO_CONFIG_PATHS],FimoFrameworkSchema=z16.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z16.object({dev:z16.string().trim().min(1).optional(),build:z16.string().trim().min(1).optional(),install:z16.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z16.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z16.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z16.object({type:z16.enum(["header","cookie","query","host"]),key:z16.string().min(1).optional(),value:z16.string().min(1).optional()}).strict().superRefine((condition,context)=>{if(condition.type==="host"){condition.key!==void 0&&context.addIssue({code:"custom",path:["key"],message:"A host condition takes no key."}),condition.value===void 0&&context.addIssue({code:"custom",path:["value"],message:"A host condition needs a value."});return}condition.key===void 0&&context.addIssue({code:"custom",path:["key"],message:`A ${condition.type} condition needs the key it matches on.`})}),conditionFields={has:z16.array(FimoHostingConditionSchema).min(1).optional(),missing:z16.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z16.object({source:z16.string().min(1),destination:z16.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z16.object({source:z16.string().min(1),destination:z16.string().min(1),permanent:z16.boolean().optional(),statusCode:z16.union([z16.literal(301),z16.literal(302),z16.literal(307),z16.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z16.object({source:z16.string().min(1),headers:z16.array(z16.object({key:z16.string().min(1),value:z16.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z16.object({rewrites:z16.array(FimoHostingRewriteSchema).optional(),redirects:z16.array(FimoHostingRedirectSchema).optional(),headers:z16.array(FimoHostingHeaderSchema).optional(),cleanUrls:z16.boolean().optional(),trailingSlash:z16.boolean().optional()}).strict(),FimoAppConfigSchema=z16.object({runtime:FimoRuntimeConfigSchema.optional(),hosting:FimoHostingConfigSchema.optional()}).passthrough().superRefine((config,context)=>{Object.hasOwn(config,"framework")&&context.addIssue({code:"custom",path:["framework"],message:"Use runtime.framework instead of the top-level framework field."})})}});function isEntryParamBinding(binding){return binding!==void 0&&(binding.type??"entry")==="entry"}function pageRouteParamNames(path49){return[...path49.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path49,params){return pageRouteParamNames(path49).filter(param=>!LOCALE_PARAM_NAME.test(param)&¶ms?.[param]?.type!=="external")}function parsePageParamExpression(expression){let match=PARAM_EXPRESSION.exec(expression);return match?{param:match[1],field:match[2]}:null}function fieldValue(entry,fieldPath){let value=entry;for(let segment of fieldPath.split(".")){if(!value||typeof value!="object"||Array.isArray(value))return;value=value[segment]}return value}function queryValue(value){if(Array.isArray(value))return value.map(queryValue);if(value&&typeof value=="object"){let record=value;return typeof record.id=="string"?record.id:Object.fromEntries(Object.entries(record).map(([key,item])=>[key,queryValue(item)]))}return value===void 0?null:value}function resolveValue(value,params){if(typeof value=="string"&&value.startsWith("$params.")){let parsed=parsePageParamExpression(value);if(!parsed)return{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param:"",field:""}};let{param,field}=parsed,entry=params[param];if(!entry)return{ok:!1,error:{code:"PAGE_PARAM_NOT_SELECTED",expression:value,param,field}};let resolved=fieldValue(entry,field);return resolved==null||resolved===""?{ok:!1,error:{code:"PAGE_PARAM_FIELD_EMPTY",expression:value,param,field}}:{ok:!0,value:queryValue(resolved)}}if(Array.isArray(value)){let resolved=[];for(let item of value){let result=resolveValue(item,params);if(!result.ok)return result;resolved.push(result.value)}return{ok:!0,value:resolved}}if(value&&typeof value=="object"){let resolved={};for(let[key,item]of Object.entries(value)){let result=resolveValue(item,params);if(!result.ok)return result;resolved[key]=result.value}return{ok:!0,value:resolved}}return{ok:!0,value}}function resolvePageSourceQuery(query={},params){let resolved=resolveValue(query,params);return resolved.ok?{ok:!0,query:resolved.value}:resolved}function pageSourceParamExpressions(value){return typeof value=="string"?value.startsWith("$params.")?[value]:[]:Array.isArray(value)?value.flatMap(pageSourceParamExpressions):value&&typeof value=="object"?Object.values(value).flatMap(pageSourceParamExpressions):[]}var LOCALE_PARAM_NAME,PARAM_EXPRESSION,init_page_sources=__esm({"../../packages/api-contracts/dist/esm/types/page-sources.js"(){"use strict";__name(isEntryParamBinding,"isEntryParamBinding");LOCALE_PARAM_NAME=/^(locale|lang|language)$/i;__name(pageRouteParamNames,"pageRouteParamNames");__name(pageContentParamNames,"pageContentParamNames");PARAM_EXPRESSION=/^\$params\.([A-Za-z_][\w-]*)\.([A-Za-z_][\w.-]*)$/;__name(parsePageParamExpression,"parsePageParamExpression");__name(fieldValue,"fieldValue");__name(queryValue,"queryValue");__name(resolveValue,"resolveValue");__name(resolvePageSourceQuery,"resolvePageSourceQuery");__name(pageSourceParamExpressions,"pageSourceParamExpressions")}});var init_project_files=__esm({"../../packages/api-contracts/dist/esm/types/project-files.js"(){"use strict"}});import{z as z17}from"zod";var PROJECT_CHAT_MANUAL_MODEL_IDS,ProjectChatManualModelIdSchema,ProjectDTOSchema,ProjectDTO,UpdateProjectSettingsRequestSchema,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectHistoryUsageDTOSchema,ProjectVersionPageDTOSchema,ProjectVersionPageDTO,ProjectHistorySummaryDTOSchema,ProjectHistorySummaryDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionResponseSchema,ProjectVersionPageResponseSchema,ProjectHistorySummaryResponseSchema,VersionMutationResponseSchema,PublishUpgradeRequiredSchema,ProjectLatestPublicationAttemptSchema,ProjectPublicationStateDTOSchema,ProjectPublicationStateDTO,PublishProjectRequestSchema,PublicationMutationDTOSchema,PublicationMutationDTO,ProjectPublicationStateResponseSchema,PublicationMutationResponseSchema,ProjectResponseSchema,ProjectWithPlanResponseSchema,init_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project.dto.js"(){"use strict";init_chat_block();init_common();init_env();init_create_dto();init_response();PROJECT_CHAT_MANUAL_MODEL_IDS=["anthropic/claude-opus-5.5","anthropic/claude-opus-5","anthropic/claude-sonnet-5","anthropic/claude-fable-5","anthropic/claude-haiku-5.5","openai/gpt-5.6-luna","openai/gpt-5.6-terra","openai/gpt-5.6-sol","openai/gpt-6-astra","openai/gpt-6.1-sol","openai/gpt-6-sol","openai/gpt-6-luna","xai/grok-4.6","google/gemini-3.1-pro-preview","google/gemini-3.8-flash","google/gemini-3.7-flash","google/gemini-3.6-flash","google/gemini-3.5-flash-lite","zai/glm-5.2","zai/glm-5.3-flash","deepseek/deepseek-v4-pro","minimax/minimax-m3","moonshotai/kimi-k3"],ProjectChatManualModelIdSchema=z17.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z17.string(),displayName:z17.string().nullable(),subdomain:z17.string().nullable().optional(),subdomainUpdatedAt:z17.date().nullable().optional(),organizationId:z17.string().nullable(),createdBy:z17.string().nullable(),defaultBranch:BranchSchema.default(DEFAULT_BRANCH),productionSourceBranch:BranchSchema.default(DEFAULT_BRANCH),enabledChatModels:z17.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z17.string(),thumbnailUrl:z17.string().nullable(),publishedThumbnailUrl:z17.string().nullable(),category:z17.string().nullable(),snapshotUrl:z17.string().startsWith("/").optional(),appUrl:z17.string().nullable(),lastPublishedAt:z17.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),UpdateProjectSettingsRequestSchema=z17.object({name:z17.string().optional(),enabledChatModels:z17.array(ProjectChatManualModelIdSchema).optional(),productionSourceBranch:BranchSchema.optional(),syncConfig:z17.boolean().optional()}).strict(),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z17.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z17.object({id:z17.uuid(),name:z17.string(),displayName:z17.string().nullable(),thumbnailUrl:z17.string().nullable(),category:z17.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z17.object({id:z17.string(),name:z17.string(),avatar:z17.string().nullable(),color:z17.object({bg:z17.string(),text:z17.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z17.object({path:z17.string(),content:z17.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z17.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z17.object({id:z17.string(),messageId:z17.string(),versionId:z17.string().nullable(),role:ProjectChatMessageRole,parts:z17.array(z17.any()),createdAt:z17.coerce.date()}),MessageUserMetadataSchema=z17.object({id:z17.string(),name:z17.string().nullable().optional(),image:z17.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z17.number(),metadata:z17.object({user:MessageUserMetadataSchema,changeManifest:z17.array(z17.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z17.object({versionId:z17.uuid(),commitHash:z17.string(),name:z17.string(),description:z17.string().nullable(),kind:z17.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z17.object({versionCount:z17.number().int().nonnegative(),snapshotBytes:z17.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z17.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z17.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z17.object({content:z17.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z17.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z17.object({success:z17.boolean(),message:z17.string().optional(),warning:z17.string().optional(),durationMs:z17.number().int().nonnegative().optional()})),PublishUpgradeRequiredSchema=z17.object({code:z17.literal("PUBLISH_UPGRADE_REQUIRED"),message:z17.string(),currentVersion:z17.number().int().positive(),targetVersion:z17.literal(4)}),ProjectLatestPublicationAttemptSchema=z17.object({publicationId:z17.uuid(),status:z17.enum(["queued","building","published","failed","canceled"]),failureCode:z17.string().nullable(),sourceBranch:z17.string(),createdAt:CommonSchemas.timestamp,finishedAt:CommonSchemas.timestamp.nullable()}),ProjectPublicationStateDTOSchema=z17.object({isPublished:z17.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z17.string().nullable(),upgradeRequired:PublishUpgradeRequiredSchema.nullish(),hasActiveRelease:z17.boolean().optional(),latestAttempt:ProjectLatestPublicationAttemptSchema.nullish()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z17.object({label:z17.string().trim().min(1).max(120).optional(),notes:z17.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z17.object({success:z17.boolean(),message:z17.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z17.boolean(),publicationId:z17.string().optional(),url:z17.string().nullable().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z18}from"zod";var ProjectBranchStatusSchema,ProjectBranchKindSchema,ProjectBranchDTOSchema,ProjectBranchDTO,ResolvedBranchEnvironmentDTOSchema,ProjectBranchListItemDTOSchema,ProjectBranchListItemDTO,CreateProjectBranchRequestInputSchema,CreateProjectBranchRequestSchema,SyncProjectBranchRequestSchema,ProjectBranchResponseSchema,ProjectBranchesListResponseSchema,BranchSurfaceDiffSchema,BranchDiffResultSchema,BranchDiffResultDTO,init_project_env_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-env.dto.js"(){"use strict";init_common();init_env();init_environment();init_create_dto();init_response();ProjectBranchStatusSchema=z18.enum(["provisioning","active","deleted"]),ProjectBranchKindSchema=z18.enum(["user","agent-session"]),ProjectBranchDTOSchema=BaseEntitySchema.extend({projectId:z18.uuid(),branch:BranchSchema.optional(),status:ProjectBranchStatusSchema,kind:ProjectBranchKindSchema,parentBranch:BranchSchema.nullable().optional(),createdBy:z18.string().nullable(),deletedAt:z18.coerce.date().nullable(),env:BranchSchema,parentEnv:BranchSchema.nullable()}),ProjectBranchDTO=createDTO(ProjectBranchDTOSchema),ResolvedBranchEnvironmentDTOSchema=z18.object({id:z18.union([z18.literal(PREVIEW_ENVIRONMENT_KEY),z18.uuid()]),name:z18.string()}),ProjectBranchListItemDTOSchema=ProjectBranchDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable(),workSession:z18.object({sessionId:z18.uuid(),name:z18.string()}).optional()}),ProjectBranchListItemDTO=createDTO(ProjectBranchListItemDTOSchema),CreateProjectBranchRequestInputSchema=z18.object({branch:BranchSchema.optional(),parentBranch:BranchSchema.optional(),env:BranchSchema.optional(),parentEnv:BranchSchema.optional()}),CreateProjectBranchRequestSchema=CreateProjectBranchRequestInputSchema.superRefine((body,ctx)=>{body.branch===void 0&&body.env===void 0&&ctx.addIssue({code:"custom",path:["branch"],message:"branch is required"}),body.branch!==void 0&&body.env!==void 0&&body.branch!==body.env&&ctx.addIssue({code:"custom",path:["branch"],message:`branch '${body.branch}' and the deprecated env '${body.env}' disagree \u2014 send one, or send both with the same value`}),body.parentBranch!==void 0&&body.parentEnv!==void 0&&body.parentBranch!==body.parentEnv&&ctx.addIssue({code:"custom",path:["parentBranch"],message:`parentBranch '${body.parentBranch}' and the deprecated parentEnv '${body.parentEnv}' disagree \u2014 send one, or send both with the same value`})}).transform(body=>({branch:body.branch??body.env,parentBranch:body.parentBranch??body.parentEnv})),SyncProjectBranchRequestSchema=z18.object({from:BranchSchema.optional()}),ProjectBranchResponseSchema=createResponseSchema(ProjectBranchDTOSchema),ProjectBranchesListResponseSchema=createResponseSchema(z18.array(ProjectBranchListItemDTOSchema)),BranchSurfaceDiffSchema=z18.object({surface:z18.enum(["code","schemas","content","translations","assets","forms"]),status:z18.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z18.number().int().nonnegative(),conflictCount:z18.number().int().nonnegative()}),BranchDiffResultSchema=z18.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),generatedAt:z18.coerce.date(),surfaces:z18.array(BranchSurfaceDiffSchema),fromEnv:BranchSchema,toEnv:BranchSchema}),BranchDiffResultDTO=createDTO(BranchDiffResultSchema)}});import{z as z19}from"zod";var ProjectEnvironmentBaseSchema,ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema,ProjectEnvironmentDTOSchema,ProjectEnvironmentDTO,CreateProjectEnvironmentRequestSchema,ProjectEnvironmentsListResponseSchema,ProjectEnvironmentResponseSchema,DeleteProjectEnvironmentResultSchema,DeleteProjectEnvironmentResponseSchema,init_project_environment_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-environment.dto.js"(){"use strict";init_env();init_environment();init_create_dto();init_response();ProjectEnvironmentBaseSchema=z19.object({projectId:z19.uuid(),name:z19.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z19.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z19.literal("production"),sourceBranch:BranchSchema,isPublished:z19.boolean(),url:z19.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z19.literal(PREVIEW_ENVIRONMENT_KEY),kind:z19.literal("preview"),matchedBranchCount:z19.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z19.literal("custom"),matchedBranchCount:z19.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z19.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z19.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema(z19.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z19.object({deletedId:z19.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema(DeleteProjectEnvironmentResultSchema)}});import{z as z20}from"zod";var ProjectSecretsListQuerySchema,ProjectSecretWriteRequestSchema,CreateProjectSecretRequestSchema,DeleteProjectSecretQuerySchema,ProjectSecretMetadataDTOSchema,ProjectSecretMetadataDTO,ProjectSecretsListResponseSchema,ProjectSecretResponseSchema,init_project_secret_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-secret.dto.js"(){"use strict";init_environment();init_create_dto();init_response();ProjectSecretsListQuerySchema=z20.object({kind:z20.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z20.object({kind:z20.enum(["variable","secret"]),value:z20.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z20.string().min(1).max(255)}),DeleteProjectSecretQuerySchema=z20.object({kind:z20.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z20.object({id:z20.uuid(),projectId:z20.uuid(),key:z20.string(),kind:z20.literal("secret"),exposure:z20.literal("private"),environment:EnvironmentKeySchema,maskedValue:z20.string().optional(),createdAt:z20.date().transform(value=>value.toISOString()),updatedAt:z20.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema(z20.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema(ProjectSecretMetadataDTOSchema)}});import{z as z21}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=z21.object({success:z21.literal(!0),downloadUrl:z21.string(),expiresAt:z21.string(),fileSize:z21.number(),duration:z21.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z21.object({success:z21.literal(!0),projectId:z21.string(),projectName:z21.string(),displayName:z21.string(),projectUrl:z21.string(),duration:z21.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z21.object({contentTypes:z21.number(),entries:z21.number(),assets:z21.number(),translations:z21.number(),forms:z21.number(),codeFiles:z21.number(),assetFiles:z21.number()}),ImportPreviewSurfaceDTOSchema=z21.object({name:z21.string(),included:z21.boolean(),count:z21.number().optional(),note:z21.string().optional()}),ImportPreviewDTOSchema=z21.object({projectName:z21.string(),displayName:z21.string().nullable(),category:z21.string().nullable(),exportedAt:z21.string(),version:z21.string(),envScope:z21.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z21.array(ImportPreviewSurfaceDTOSchema),fileSize:z21.number(),fileName:z21.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z21.object({success:z21.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z22}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,CONFLICT_KINDS,ConflictKindSchema,ConflictSchema,FieldPickSchema,ConflictResolutionSchema,MergeResultSchema,MergeResultDTO,MergeResultResponseSchema,EngineStrategySchema,VendorStrategySchema,MergeStrategySchema,ResolvedStrategySchema,MergeRequestSchema,MergeInitiateResultSchema,MergeInitiateResultDTO,MergeInitiateResponseSchema,MergeConflictsHydrationSchema,MergeConflictsHydrationDTO,MergeConflictsHydrationResponseSchema,MergeResolveDraftRequestSchema,MergeResolveDraftResultSchema,MergeResolveDraftResultDTO,MergeResolveRequestSchema,MergeCancelRequestSchema,PublishReleaseRequestSchema,PublishReleaseResultSchema,PublishReleaseResultDTO,PublishReleaseResponseSchema,init_env_status_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-status.dto.js"(){"use strict";init_env();init_create_dto();init_response();SurfaceNameSchema=z22.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z22.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z22.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z22.object({verb:SurfaceDeltaVerbSchema,key:z22.string(),detail:z22.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z22.record(z22.string(),z22.unknown()).optional()}),PerSurfaceDeltaSchema=z22.object({surface:SurfaceNameSchema,status:z22.enum(["ok","timed_out","failed","unchanged"]),durationMs:z22.number().int().nonnegative().optional(),changedCount:z22.number().int().nonnegative(),conflictCount:z22.number().int().nonnegative(),items:z22.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z22.boolean().optional(),error:z22.string().optional()}),CrossSurfaceFindingSchema=z22.object({id:z22.string(),kind:z22.string(),description:z22.string(),severity:z22.enum(["warning","error"]),source:z22.object({surface:SurfaceNameSchema,key:z22.string()}),target:z22.object({surface:SurfaceNameSchema,key:z22.string()}),actions:z22.array(z22.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z22.object({branch:BranchSchema.optional(),env:BranchSchema,vs:BranchSchema,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({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,generatedAt:z22.coerce.date(),surfaces:z22.array(PerSurfaceDeltaSchema),crossSurface:z22.array(CrossSurfaceFindingSchema).optional(),fingerprint:z22.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z22.object({path:z22.string(),state:z22.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z22.string(),additions:z22.number().int().nonnegative(),deletions:z22.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z22.object({oid:z22.string().optional(),content:z22.string().optional(),truncated:z22.boolean(),binary:z22.boolean()}),CodeConflictDetailSchema=z22.object({path:z22.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z22.string(),targetTipSha:z22.string(),mergeBaseSha:z22.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z22.object({id:z22.string(),slug:z22.string(),contentType:z22.string(),data:z22.record(z22.string(),z22.unknown()),updatedAt:z22.coerce.date()}),ContentRowDiffSchema=z22.object({collection:z22.string(),rowId:z22.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z22.object({name:z22.string(),label:z22.string(),isSingleton:z22.boolean(),fields:z22.record(z22.string(),z22.unknown())}),SchemaTypeDiffSchema=z22.object({typeName:z22.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z22.object({id:z22.string(),name:z22.string(),type:z22.enum(["file","folder"]),mimeType:z22.string().nullable(),storageKey:z22.string().nullable(),url:z22.string().nullable(),fileSize:z22.number().nullable(),width:z22.number().nullable(),height:z22.number().nullable(),altText:z22.string().nullable(),caption:z22.string().nullable(),createdAt:z22.coerce.date(),updatedAt:z22.coerce.date()}),AssetDiffSchema=z22.object({assetId:z22.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z22.object({locale:z22.string(),key:z22.string(),parent:z22.string().nullable(),child:z22.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z22.object({formName:z22.string(),label:z22.string().nullable(),schemaFingerprint:z22.string(),fields:z22.record(z22.string(),z22.unknown()),settings:z22.record(z22.string(),z22.unknown()).optional()}),FormSchemaDiffSchema=z22.object({formName:z22.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z22.enum(CONFLICT_KINDS),ConflictSchema=z22.object({surface:SurfaceNameSchema,key:z22.string(),kind:ConflictKindSchema.optional(),description:z22.string(),parentValue:z22.unknown().optional(),childValue:z22.unknown().optional(),conflictingFields:z22.array(z22.string()).optional(),code:z22.object({path:z22.string(),unresolvable:z22.boolean().optional(),reason:z22.string().optional()}).optional()}),FieldPickSchema=z22.object({field:z22.string(),choice:z22.enum(["parent","child","pick","ai-pick"]),pickedValue:z22.unknown().optional(),aiSessionId:z22.string().optional()}),ConflictResolutionSchema=z22.object({surface:SurfaceNameSchema,key:z22.string(),choice:z22.enum(["parent","child","pick"]),pickedValue:z22.unknown().optional(),fieldPicks:z22.array(FieldPickSchema).optional()}),MergeResultSchema=z22.object({ok:z22.boolean(),mergeId:z22.string().uuid(),fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,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:BranchSchema,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:BranchSchema,toEnv:BranchSchema,status:z22.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z22.array(ConflictSchema),draftResolutions:z22.array(ConflictResolutionSchema),lastEditedBy:z22.string().nullable(),lastEditedAt:z22.coerce.date().nullable(),initiator:z22.object({userId:z22.string().nullable(),role:z22.string().nullable(),agentName:z22.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z22.object({resolutions:z22.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z22.object({mergeId:z22.string().uuid(),draftResolutions:z22.array(ConflictResolutionSchema),lastEditedAt:z22.coerce.date(),lastEditedBy:z22.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z22.object({mergeId:z22.string().uuid(),resolutions:z22.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z22.object({mergeId:z22.string().uuid()}),PublishReleaseRequestSchema=z22.object({version:z22.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z22.string().max(2e4).optional()}),PublishReleaseResultSchema=z22.object({releaseTag:z22.string(),sha:z22.string(),publishedAt:z22.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z23}from"zod";var AgentSessionStatusSchema,AgentSessionReviewPublicationSchema,AgentSessionReviewSummarySchema,AgentSessionReviewSummaryDTO,AgentSessionReviewPayloadSchema,AgentSessionReviewPayloadDTO,AgentSessionReviewPayloadResponseSchema,SessionErrorCodeSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_create_dto();init_response();init_env_status_dto();AgentSessionStatusSchema=z23.enum(["planned","running","finished","cancelled","errored"]),AgentSessionReviewPublicationSchema=z23.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z23.object({capturedAt:z23.coerce.date(),fingerprint:z23.string().min(1).max(256),counts:z23.object({code:z23.number().int().nonnegative(),content:z23.number().int().nonnegative(),schemas:z23.number().int().nonnegative(),labels:z23.number().int().nonnegative(),assets:z23.number().int().nonnegative().optional()}),publication:AgentSessionReviewPublicationSchema,mergeId:z23.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z23.object({diff:DiffReportSchema,code:z23.array(CodeFileDiffSchema.extend({raw:z23.string().max(24576)})).max(200),schemas:z23.array(SchemaTypeDiffSchema).max(200),content:z23.array(z23.object({key:z23.string().min(1).max(512),collection:z23.string().min(1).max(256),slug:z23.string().max(512).optional(),verb:z23.enum(["added","modified","deleted"]),fields:z23.array(z23.object({name:z23.string().min(1).max(256),before:z23.unknown().optional(),after:z23.unknown().optional()})).max(20)})).max(200),labels:z23.array(z23.object({key:z23.string().min(1).max(512),locale:z23.string().min(1).max(64).optional(),before:z23.unknown().nullable(),after:z23.unknown().nullable()})).max(200),assets:z23.array(z23.object({key:z23.string().min(1).max(512),name:z23.string().min(1).max(512),verb:z23.enum(["added","modified","deleted"]),before:AssetSnapshotSchema.nullable(),after:AssetSnapshotSchema.nullable()})).max(200).default([])}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),SessionErrorCodeSchema=z23.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid"])}});import{z as z24}from"zod";var AgentBranchClassificationSchema,AgentBranchDecidedPathSchema,WorkSessionReviewSchema,RequestWorkSessionReviewSchema,WorkSessionReviewResultSchema,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();init_env_status_dto();AgentBranchClassificationSchema=z24.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z24.enum(["auto-merge","review-merged","review-discarded"]),WorkSessionReviewSchema=z24.object({sessionId:z24.uuid(),branch:z24.string().min(1),targetBranch:z24.string().min(1),revision:z24.string().min(1),fingerprint:z24.string().min(1),source:z24.enum(["studio","slack","mcp"]),threadId:z24.uuid().nullable(),invocationId:z24.uuid().nullable(),conversationBranch:z24.string().nullable(),capturedAt:z24.string(),surfaces:z24.array(PerSurfaceDeltaSchema).optional(),counts:z24.record(z24.string(),z24.number().int().nonnegative())}),RequestWorkSessionReviewSchema=z24.strictObject({sessionId:z24.uuid(),summary:z24.string().trim().min(1).max(240),targetBranch:z24.string().trim().min(1).optional()}),WorkSessionReviewResultSchema=z24.object({requested:z24.literal(!0),alreadyRequested:z24.boolean(),reviewId:z24.uuid(),reviewUrl:z24.url(),status:z24.literal("pending"),sessionId:z24.uuid(),branch:z24.string(),targetBranch:z24.string(),revision:z24.string(),savedRevision:z24.string(),fingerprint:z24.string(),visibility:z24.literal("user-visible"),retention:z24.literal("durable"),expiresAt:z24.null(),merged:z24.literal(!1),published:z24.literal(!1),links:z24.object({preview:z24.url(),changes:z24.url(),conversation:z24.url().nullable()})}),AgentBranchProposalDTOSchema=z24.object({id:z24.uuid(),envId:z24.uuid(),sessionId:z24.uuid().nullable(),skillName:z24.string().min(1),classification:AgentBranchClassificationSchema,rationale:z24.string().nullable(),summary:z24.string().nullable(),surfaceDeltas:z24.record(z24.string(),z24.unknown()),review:WorkSessionReviewSchema.optional(),createdAt:z24.coerce.date(),decidedAt:z24.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z24.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z24.object({path:z24.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z24.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z24.object({code:z24.literal("merge_conflict"),message:z24.string(),conflicts:z24.record(z24.string(),z24.number().int().nonnegative())})}});import{z as z25}from"zod";var AGENT_QUESTION_STATES,AgentQuestionStateSchema,AgentQuestionFormSchema,AgentQuestionAskSchema,AgentQuestionRequestSchema,AgentQuestionSchema,AgentQuestionResponseSchema,RunAgentQuestionResponseSchema,AgentQuestionAttentionSchema,OpenAgentQuestionsResponseSchema,AnswerAgentQuestionResultSchema,AnswerAgentQuestionResponseSchema,init_agent_question_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-question.dto.js"(){"use strict";init_chat_block();init_response();AGENT_QUESTION_STATES=["open","answered","expired","cancelled","superseded"],AgentQuestionStateSchema=z25.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z25.string().trim().min(1).max(80)}).superRefine((form,ctx)=>{(!form.steps.every(step=>step.id)||new Set(form.steps.map(step=>step.id)).size!==form.steps.length)&&ctx.addIssue({code:"custom",path:["steps"],message:"Every question step needs its own stable id."})}),AgentQuestionAskSchema=z25.object({description:z25.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z25.literal(QUESTION_FORM_CONTRACT_VERSION),sessionIds:z25.array(z25.uuid()).optional()}),AgentQuestionSchema=z25.object({id:z25.uuid(),projectId:z25.uuid(),threadId:z25.uuid(),invocationId:z25.uuid(),agentKey:z25.string().min(1).max(120),anchorEnv:z25.string().min(1).max(64),retainedEnv:z25.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z25.string().min(1).nullable(),continuationInvocationId:z25.uuid().nullable(),askedAt:z25.coerce.date(),expiresAt:z25.coerce.date(),closedAt:z25.coerce.date().nullable()}),AgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z25.object({questionId:z25.uuid(),invocationId:z25.uuid(),askedAt:z25.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema(z25.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z25.object({question:AgentQuestionSchema,continuationInvocationId:z25.uuid(),deduped:z25.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema(AnswerAgentQuestionResultSchema)}});import{z as z26}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,IntegrationToolEffectSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,ProjectIntegrationConnectionDTOSchema,ProjectIntegrationConnectionDTO,McpHeaderNameSchema,McpHeaderDefinitionSchema,McpSecretMapSchema,ConnectOrganizationIntegrationRequestSchema,ProjectIntegrationReturnPathSchema,IntegrationCustomIdentitySchema,ConnectProjectIntegrationRequestSchema,McpIntegrationAuthSchema,McpIntegrationSetupAuthSchema,AddProjectMcpIntegrationRequestSchema,AddProjectMcpIntegrationResponseBaseSchema,AddProjectMcpIntegrationResponseSchema,ReusableMcpServerAuthKindSchema,ReusableMcpServerDTOSchema,ReusableMcpServerDTO,SearchReusableMcpServersQuerySchema,ReuseProjectMcpIntegrationRequestSchema,LinearOAuthApplicationDistributionSchema,OrganizationLinearAppDTOSchema,OrganizationLinearAppDTO,CreateManagedLinearAppRequestSchema,UpdateManagedLinearAppRequestSchema,StartManagedLinearConnectRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,ProjectIntegrationConnectResponseSchema,BindProjectChannelRequestSchema,ListProjectChannelsQuerySchema,SearchProjectChannelsQuerySchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,ProjectChannelCandidateAvailabilitySchema,ProjectChannelCandidateDTOSchema,ProjectChannelCandidateDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlDeveloperSearchToolInputSchema,FirecrawlResearchSearchToolInputSchema,FirecrawlResearchPaperToolInputSchema,FirecrawlResearchRelatedToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorScrapeOptionsInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorUpdateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolRequestSchema,ProjectIntegrationToolRunUsageSchema,ProjectIntegrationToolRunBillingSchema,FirecrawlScrapeToolOutputSchema,FirecrawlSearchToolOutputSchema,FirecrawlResearchPaperSchema,FirecrawlResearchPassageSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlMonitorScheduleOutputSchema,FirecrawlMonitorTargetOutputSchema,FirecrawlMonitorOutputSchema,FirecrawlMonitorCheckOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema,FirecrawlToolKeySchema,FirecrawlToolOutputSchema,ProjectIntegrationToolRunBaseSchema,ProjectIntegrationToolRunDTOSchema,ProjectIntegrationToolRunDTO,IntegrationsListResponseSchema,IntegrationInfoResponseSchema,ProjectIntegrationStatusResponseSchema,ProjectIntegrationInstallationResponseSchema,ProjectIntegrationToolRunResponseSchema,StartProjectIntegrationConnectResponseResponseSchema,OrganizationIntegrationConnectionResponseSchema,ProjectIntegrationConnectionsResponseSchema,ProjectIntegrationConnectResponseResponseSchema,AddProjectMcpIntegrationResponseResponseSchema,ReusableMcpServersResponseSchema,ProjectChannelBindingResponseSchema,ProjectChannelBindingsResponseSchema,ProjectChannelCandidatesResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z26.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z26.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z26.enum(["secret_text"]),IntegrationCredentialUsageSchema=z26.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z26.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z26.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z26.object({mode:IntegrationAuthModeSchema,label:z26.string().min(1),description:z26.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z26.object({id:z26.string().min(1),label:z26.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z26.boolean()}),IntegrationToolDefinitionDTOSchema=z26.object({key:z26.string().min(1),name:z26.string().min(1),description:z26.string().min(1),effect:IntegrationToolEffectSchema}),IntegrationRecipeDTOSchema=z26.object({title:z26.string().min(1),description:z26.string().min(1),command:z26.string().min(1).optional()}),IntegrationInfoDTOSchema=z26.object({key:z26.string().min(1),name:z26.string().min(1),summary:z26.string().min(1),type:z26.enum(["native","mcp"]).optional(),url:z26.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z26.array(IntegrationAuthModeDTOSchema),credentials:z26.array(IntegrationCredentialDefinitionDTOSchema),tools:z26.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z26.enum(["available","unavailable"]).optional(),connectionCapabilities:z26.object({customIdentityCreation:z26.boolean()}).optional(),recipes:z26.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z26.object({projectId:z26.uuid(),integrationKey:z26.string().min(1),name:z26.string().min(1),summary:z26.string().min(1),installed:z26.boolean(),enabled:z26.boolean(),setupState:z26.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z26.string().nullable(),connectionId:z26.uuid().nullable().optional(),connectionAlias:z26.string().min(1).nullable().optional(),connectionStatus:z26.enum(["active","revoked"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z26.array(z26.string()),installedAt:z26.coerce.date().nullable(),updatedAt:z26.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z26.object({id:z26.uuid(),projectId:z26.uuid(),integrationKey:z26.string().min(1),enabled:z26.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z26.string(),connectionId:z26.uuid().nullable().optional(),connectionAlias:z26.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z26.array(z26.string()),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z26.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z26.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z26.object({authMode:IntegrationAuthModeSchema}),OrganizationIntegrationConnectionStatusSchema=z26.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z26.object({id:z26.uuid(),organizationId:z26.string().min(1),integrationKey:z26.string().min(1),registrationId:z26.uuid().nullable(),alias:z26.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z26.string().min(1),externalAccountName:z26.string().nullable(),externalBotUserId:z26.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z26.array(z26.string()),connectedAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionDTOSchema=OrganizationIntegrationConnectionDTOSchema.extend({granted:z26.boolean(),isDefault:z26.boolean()}),ProjectIntegrationConnectionDTO=createDTO(ProjectIntegrationConnectionDTOSchema),McpHeaderNameSchema=z26.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z26.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z26.record(McpHeaderNameSchema,z26.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z26.object({alias:z26.string().min(1).max(120).optional(),token:z26.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z26.boolean().optional()}).superRefine((value,ctx)=>{value.token&&value.secrets&&ctx.addIssue({code:"custom",path:["token"],message:"Provide either one token or a complete MCP secret map."})}),ProjectIntegrationReturnPathSchema=z26.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),IntegrationCustomIdentitySchema=z26.object({displayName:z26.string().trim().min(1).max(35),backgroundColor:z26.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),iconUrl:z26.string().url().max(2048).optional()}),ConnectProjectIntegrationRequestSchema=z26.discriminatedUnion("mode",[z26.object({mode:z26.literal("personal"),alias:z26.string().min(1).max(120),token:z26.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z26.boolean().optional()}),z26.object({mode:z26.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z26.boolean().optional(),registrationId:z26.uuid().optional(),customIdentity:IntegrationCustomIdentitySchema.optional()})]).superRefine((value,ctx)=>{value.mode==="oauth"&&value.registrationId&&value.customIdentity&&ctx.addIssue({code:"custom",path:["registrationId"],message:"Choose an existing app identity or create a custom one, not both."}),value.mode==="personal"&&!!value.token==!!value.secrets&&ctx.addIssue({code:"custom",path:["token"],message:"Provide either one token or a complete MCP secret map."})}),McpIntegrationAuthSchema=z26.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z26.union([z26.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z26.object({type:z26.literal("mcp"),name:z26.string().trim().min(1).max(120),url:z26.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z26.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z26.string().min(1).optional()}).superRefine((value,ctx)=>{let protocol;try{protocol=new URL(value.url).protocol}catch{return}protocol!=="https:"&&ctx.addIssue({code:"custom",path:["url"],message:"MCP servers must use HTTPS."});let hasSingleHeader=!!(value.headerName||value.token),hasHeaderBundle=!!(value.headers||value.secrets);if(value.auth==="auto"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Automatic authentication does not accept manual credentials."}),value.auth==="none"&&(hasSingleHeader||hasHeaderBundle)&&ctx.addIssue({code:"custom",path:["auth"],message:"Public MCP servers cannot define credentials."}),value.auth==="bearer"&&(value.token||ctx.addIssue({code:"custom",path:["token"],message:"Bearer authentication requires a token."}),(value.headerName||value.headers||value.secrets)&&ctx.addIssue({code:"custom",path:["headers"],message:"Custom headers only apply to header authentication."})),value.auth!=="header")return;if(hasSingleHeader&&hasHeaderBundle){ctx.addIssue({code:"custom",path:["headers"],message:"Use either the single-header fields or headers with a complete secret map."});return}if(hasSingleHeader){value.headerName||ctx.addIssue({code:"custom",path:["headerName"],message:"Custom header authentication needs a header name."}),value.token||ctx.addIssue({code:"custom",path:["token"],message:"Header authentication requires a complete header value."});return}if(!value.headers){ctx.addIssue({code:"custom",path:["headers"],message:"Header authentication needs at least one header."});return}let normalizedNames=value.headers.map(header=>header.name.toLowerCase());if(new Set(normalizedNames).size!==normalizedNames.length&&ctx.addIssue({code:"custom",path:["headers"],message:"MCP header names must be unique."}),!value.secrets){ctx.addIssue({code:"custom",path:["secrets"],message:"Header authentication needs a complete secret map."});return}let secretNames=Object.keys(value.secrets).map(name=>name.toLowerCase());if(new Set(secretNames).size!==secretNames.length){ctx.addIssue({code:"custom",path:["secrets"],message:"MCP secret names must be unique."});return}let expected=new Set(normalizedNames),actual=new Set(secretNames);(expected.size!==actual.size||[...expected].some(name=>!actual.has(name)))&&ctx.addIssue({code:"custom",path:["secrets"],message:"The MCP secret map must exactly cover the configured headers."})}),AddProjectMcpIntegrationResponseBaseSchema=z26.object({integrationKey:z26.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z26.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z26.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z26.literal("oauth"),connectUrl:z26.string().url(),expiresAt:z26.coerce.date()})]),ReusableMcpServerAuthKindSchema=z26.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z26.object({id:z26.uuid(),name:z26.string().min(1),host:z26.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z26.string().min(1),availability:z26.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z26.object({query:z26.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z26.object({serverId:z26.uuid()}),LinearOAuthApplicationDistributionSchema=z26.enum(["private","public"]),OrganizationLinearAppDTOSchema=z26.object({id:z26.uuid(),displayName:z26.string().min(1),description:z26.string().nullable(),iconUrl:z26.string().nullable(),distribution:LinearOAuthApplicationDistributionSchema,status:z26.enum(["active","revoked"]),connectionIds:z26.array(z26.uuid()),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),OrganizationLinearAppDTO=createDTO(OrganizationLinearAppDTOSchema),CreateManagedLinearAppRequestSchema=z26.object({appName:z26.string().trim().min(2).max(80),description:z26.string().trim().max(1e3).optional(),iconUrl:z26.string().url().max(2048).optional()}),UpdateManagedLinearAppRequestSchema=CreateManagedLinearAppRequestSchema.partial().refine(input=>Object.keys(input).length>0,"At least one Linear app field is required."),StartManagedLinearConnectRequestSchema=z26.object({projectId:z26.uuid(),registrationId:z26.uuid(),returnTo:ProjectIntegrationReturnPathSchema.optional()}),StartProjectIntegrationConnectResponseSchema=z26.object({integrationKey:z26.string().min(1),connectUrl:z26.string().url(),expiresAt:z26.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z26.discriminatedUnion("mode",[z26.object({mode:z26.literal("personal"),integrationKey:z26.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z26.object({mode:z26.literal("oauth"),integrationKey:z26.string().min(1),connectUrl:z26.string().url(),expiresAt:z26.coerce.date()})]),BindProjectChannelRequestSchema=z26.object({ref:z26.string().min(1),connectionAlias:z26.string().min(1).optional(),agentName:z26.string().min(1).max(160).nullable().optional(),force:z26.boolean().optional()}),ListProjectChannelsQuerySchema=z26.object({integrationKey:z26.string().min(1)}),SearchProjectChannelsQuerySchema=z26.object({integrationKey:z26.string().min(1),connectionAlias:z26.string().min(1),query:z26.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z26.object({id:z26.uuid(),projectId:z26.uuid(),integrationKey:z26.string().min(1),connectionId:z26.uuid(),externalWorkspaceId:z26.string().min(1),externalChannelId:z26.string().min(1),externalChannelName:z26.string().nullable(),agentName:z26.string().nullable(),enabled:z26.boolean(),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z26.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z26.object({id:z26.string().min(1),name:z26.string().min(1),visibility:z26.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z26.string().min(1).nullable(),canMove:z26.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z26.object({markdown:z26.boolean().optional(),summary:z26.boolean().optional(),links:z26.boolean().optional(),branding:z26.boolean().optional(),images:z26.boolean().optional(),html:z26.union([z26.literal("cleaned"),z26.literal("raw"),z26.boolean()]).optional(),json:z26.union([z26.boolean(),z26.object({prompt:z26.string().min(1).max(1e4),schema:z26.record(z26.string(),z26.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z26.object({url:z26.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z26.boolean().optional(),timeoutMs:z26.number().int().positive().max(12e4).optional(),waitForMs:z26.number().int().min(0).max(3e4).optional(),maxAgeMs:z26.number().int().min(0).optional(),minAgeMs:z26.number().int().min(0).optional(),storeInCache:z26.boolean().optional(),proxy:z26.enum(["basic","enhanced","auto"]).optional(),mobile:z26.boolean().optional(),location:z26.object({country:z26.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z26.array(z26.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z26.object({query:z26.string().min(1),maxResults:z26.number().int().positive().max(20).optional(),sources:z26.array(z26.enum(["web","news","images"])).min(1).max(3).optional(),categories:z26.array(z26.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z26.array(z26.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z26.array(z26.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z26.enum(["hour","day","week","month","year"]).optional(),location:z26.string().min(1).max(160).optional(),country:z26.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z26.boolean().optional(),timeoutMs:z26.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z26.object({query:z26.string().min(1).max(500),maxResults:z26.number().int().min(1).max(100).optional(),types:z26.array(z26.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z26.array(z26.string().min(1).max(512)).min(1).max(20).optional(),sources:z26.array(z26.string().min(1).max(512)).min(1).max(20).optional(),passages:z26.number().int().min(1).max(5).optional(),skills:z26.literal("only").optional(),language:z26.string().min(1).optional(),topic:z26.string().min(1).optional(),license:z26.string().min(1).optional(),minStars:z26.number().int().min(0).optional(),maxStars:z26.number().int().min(0).optional(),archived:z26.boolean().optional(),fork:z26.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z26.object({query:z26.string().min(1).max(500),maxResults:z26.number().int().min(1).max(500).optional(),authors:z26.array(z26.string().min(1)).min(1).optional(),categories:z26.array(z26.string().min(1)).min(1).optional(),from:z26.iso.date().optional(),to:z26.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z26.object({paperId:z26.string().min(1).max(512),query:z26.string().min(1).max(500).optional(),maxPassages:z26.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z26.object({paperId:z26.string().min(1).max(512),intent:z26.string().min(1).max(500),mode:z26.enum(["similar","citers","references"]).optional(),maxResults:z26.number().int().min(1).max(500).optional(),rerank:z26.boolean().optional(),anchors:z26.array(z26.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z26.object({url:z26.string().url(),search:z26.string().min(1).optional(),limit:z26.number().int().positive().max(200).optional(),includeSubdomains:z26.boolean().optional(),timeoutMs:z26.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z26.object({url:z26.string().url(),limit:z26.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z26.boolean().optional(),timeoutMs:z26.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z26.object({text:z26.string().min(1).max(200).optional(),cron:z26.string().min(1).max(120).optional(),timezone:z26.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z26.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z26.boolean().optional(),timeoutMs:z26.number().int().positive().max(12e4).optional(),waitForMs:z26.number().int().min(0).max(3e4).optional(),maxAgeMs:z26.number().int().min(0).optional(),minAgeMs:z26.number().int().min(0).optional(),storeInCache:z26.boolean().optional(),proxy:z26.enum(["basic","enhanced","auto"]).optional(),mobile:z26.boolean().optional(),location:z26.object({country:z26.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z26.array(z26.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z26.union([z26.object({type:z26.enum(["scrape","crawl"]).default("scrape"),urls:z26.array(z26.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z26.object({type:z26.literal("search"),queries:z26.array(z26.string().min(1).max(256)).min(1).max(12),searchWindow:z26.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z26.number().int().min(1).max(50).optional(),includeDomains:z26.array(z26.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z26.array(z26.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z26.object({name:z26.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z26.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z26.string().min(1).max(2e3).optional(),judgeEnabled:z26.boolean().optional(),retentionDays:z26.number().int().min(1).max(365).optional(),notification:z26.object({email:z26.object({enabled:z26.boolean().default(!0),recipients:z26.array(z26.string().email()).min(1).max(20),includeDiffs:z26.boolean().optional()}).optional()}).optional()}).refine(value=>!value.targets.some(target=>target.type==="search")||value.judgeEnabled===!1||!!value.goal,{message:"Search monitor targets require goal unless judgeEnabled is false."}),FirecrawlMonitorUpdateToolInputSchema=z26.object({monitorId:z26.string().uuid(),name:z26.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z26.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z26.string().min(1).max(2e3).optional(),judgeEnabled:z26.boolean().optional(),retentionDays:z26.number().int().min(1).max(365).optional(),status:z26.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z26.object({monitorId:z26.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z26.string().uuid()}),RunProjectIntegrationToolRequestSchema=z26.object({tool:z26.string().min(1),input:z26.record(z26.string(),z26.unknown()),connectionAlias:z26.string().min(1).optional()}),ProjectIntegrationToolRunUsageSchema=z26.object({provider:z26.string().min(1),providerCredits:z26.number().nonnegative().optional(),providerCostUsd:z26.number().nonnegative().optional(),requests:z26.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z26.object({credits:z26.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z26.object({url:z26.string(),provider:z26.literal("firecrawl"),title:z26.string().optional(),statusCode:z26.number().optional(),markdown:z26.string().optional(),summary:z26.string().optional(),links:z26.array(z26.string()).optional(),images:z26.array(z26.string()).optional(),html:z26.string().optional(),json:z26.unknown().optional(),branding:z26.record(z26.string(),z26.unknown()).optional(),warning:z26.string().optional()}),FirecrawlSearchToolOutputSchema=z26.object({query:z26.string(),provider:z26.literal("firecrawl"),warning:z26.string().optional(),results:z26.array(z26.object({title:z26.string(),url:z26.string(),snippet:z26.string().optional(),content:z26.string().optional(),score:z26.number().optional(),publishedAt:z26.string().optional()}))}),FirecrawlResearchPaperSchema=z26.object({paperId:z26.string(),primaryId:z26.string().optional(),ids:z26.record(z26.string(),z26.array(z26.string())).optional(),title:z26.string().optional(),abstract:z26.string().optional(),score:z26.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z26.object({text:z26.string(),score:z26.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),results:z26.array(z26.object({id:z26.string(),type:z26.string().min(1).optional(),url:z26.string(),title:z26.string().optional(),passages:z26.array(z26.object({text:z26.string()}).passthrough())}).passthrough()),coverage:z26.record(z26.string(),z26.string()).optional(),reranked:z26.boolean().optional(),repos:z26.array(z26.record(z26.string(),z26.unknown())).optional(),sources:z26.array(z26.record(z26.string(),z26.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),results:z26.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),paper:z26.record(z26.string(),z26.unknown()),paperId:z26.string().optional(),query:z26.string().optional(),passages:z26.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),results:z26.array(FirecrawlResearchPaperSchema),poolSize:z26.number().int().nonnegative(),truncated:z26.boolean(),note:z26.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z26.object({url:z26.string(),provider:z26.literal("firecrawl"),count:z26.number(),links:z26.array(z26.object({url:z26.string(),title:z26.string().optional(),description:z26.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z26.object({url:z26.string(),provider:z26.literal("firecrawl"),total:z26.number(),pages:z26.array(z26.object({url:z26.string(),title:z26.string().optional(),statusCode:z26.number().optional(),markdown:z26.string().optional(),summary:z26.string().optional(),links:z26.array(z26.string()).optional(),images:z26.array(z26.string()).optional(),html:z26.string().optional(),warning:z26.string().optional()})),warning:z26.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z26.object({cron:z26.string().optional(),text:z26.string().optional(),timezone:z26.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z26.object({id:z26.string().optional(),type:z26.enum(["scrape","crawl","search"]).optional(),urls:z26.array(z26.string()).optional(),queries:z26.array(z26.string()).optional(),searchWindow:z26.string().optional(),maxResults:z26.number().optional(),includeDomains:z26.array(z26.string()).optional(),excludeDomains:z26.array(z26.string()).optional(),scrapeOptions:z26.record(z26.string(),z26.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z26.object({id:z26.string(),name:z26.string(),status:z26.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z26.string().nullable().optional(),lastRunAt:z26.string().nullable().optional(),currentCheckId:z26.string().nullable().optional(),targets:z26.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z26.string().nullable().optional(),judgeEnabled:z26.boolean().optional(),estimatedCreditsPerMonth:z26.number().optional(),createdAt:z26.string().optional(),updatedAt:z26.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z26.object({id:z26.string(),monitorId:z26.string(),scheduledFor:z26.string().nullable().optional(),startedAt:z26.string().nullable().optional(),finishedAt:z26.string().nullable().optional(),estimatedCredits:z26.number().nullable().optional(),reservedCredits:z26.number().nullable().optional(),actualCredits:z26.number().nullable().optional(),billingStatus:z26.string().nullable().optional(),summary:z26.object({totalPages:z26.number().optional(),same:z26.number().optional(),changed:z26.number().optional(),new:z26.number().optional(),removed:z26.number().optional(),error:z26.number().optional()}).passthrough().optional(),error:z26.string().nullable().optional(),createdAt:z26.string().optional(),updatedAt:z26.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),monitors:z26.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),monitorId:z26.string(),deleted:z26.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),monitorId:z26.string(),checks:z26.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z26.object({provider:z26.literal("firecrawl"),monitorId:z26.string(),check:FirecrawlMonitorCheckOutputSchema,next:z26.string().optional()}),FirecrawlToolKeySchema=z26.enum(["search","developer.search","research.search","research.paper","research.related","scrape","map","crawl","monitor.create","monitor.update","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z26.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z26.object({projectId:z26.uuid(),integrationKey:z26.string().min(1),tool:z26.string().min(1),connectionAlias:z26.string().min(1).nullable().optional(),output:z26.record(z26.string(),z26.unknown()),executedAt:z26.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z26.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z26.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z26.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z26.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z26.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z26.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z26.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z26.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z26.array(ProjectIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema(z26.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z26.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z26.array(ProjectChannelCandidateDTOSchema))}});import{z as z27}from"zod";var SCHEDULE_NOTIFICATION_TOPICS,ScheduleNotificationTopicSchema,USER_MANAGED_NOTIFICATION_TOPICS,UserManagedNotificationTopicSchema,MAX_SCHEDULE_SUBSCRIBERS,ScheduleSubscriberDeliveryStateSchema,ScheduleSubscriberCandidateSchema,ScheduleNotificationSettingsSchema,ScheduleNotificationSettingsResponseSchema,UpdateScheduleSubscribersRequestSchema,UserNotificationPreferenceSchema,SCHEDULE_OPT_OUT_LINK_ACTIONS,ScheduleOptOutLinkActionSchema,SCHEDULE_OPT_OUT_ACTIONS,ScheduleOptOutActionSchema,ScheduleOptOutStateSchema,ScheduleOptOutResponseSchema,FollowedScheduleSchema,FollowedSchedulesSchema,FollowedSchedulesResponseSchema,init_schedule_notifications_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule-notifications.dto.js"(){"use strict";init_response();SCHEDULE_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],ScheduleNotificationTopicSchema=z27.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance"],UserManagedNotificationTopicSchema=z27.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z27.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z27.object({userId:z27.string().min(1),name:z27.string(),email:z27.string().min(1),subscribed:z27.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z27.object({maxSubscribers:z27.number().int().positive(),subscriberCount:z27.number().int().nonnegative(),effectiveRecipientCount:z27.number().int().nonnegative(),currentUserSubscribed:z27.boolean(),candidates:z27.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z27.object({userIds:z27.array(z27.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z27.object({topic:UserManagedNotificationTopicSchema,enabled:z27.boolean(),source:z27.enum(["default","explicit"])}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z27.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z27.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z27.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z27.string().nullable(),maskedEmail:z27.string().min(1),applied:z27.boolean(),expiresAt:z27.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z27.object({scheduleId:z27.string().min(1),scheduleName:z27.string(),projectId:z27.string().min(1),projectName:z27.string(),env:z27.string().min(1)}),FollowedSchedulesSchema=z27.object({schedules:z27.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z28}from"zod";var PROJECT_SECRET_KEY_PATTERN,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN,RESERVED_PROJECT_SECRET_KEYS,ProjectSecretKeySchema,ProjectScheduleStatusSchema,ProjectScheduleDTOSchema,ProjectScheduleDTO,CreateProjectScheduleRequestSchema,UpdateProjectScheduleRequestSchema,ProjectScheduleRunStatusSchema,ProjectScheduleRunTriggerSchema,ProjectScheduleRunSecretSnapshotStateSchema,ProjectScheduleRunSecretResolutionSchema,ProjectSchedulePolicySchema,SchedulePolicyStateSchema,ProjectSchedulePlanSnapshotSchema,ProjectScheduleUsageSchema,ProjectScheduleRunDTOSchema,ProjectScheduleRunDTO,ProjectScheduleRunSecretSnapshotSchema,ProjectScheduleRunDetailDTOSchema,ProjectScheduleRunDetailDTO,RunProjectScheduleRequestSchema,ProjectScheduleRunsQuerySchema,ProjectScheduleResponseSchema,ProjectSchedulesListDataSchema,ProjectSchedulesListResponseSchema,ProjectSchedulesOverviewResponseSchema,ProjectScheduleDetailDataSchema,ProjectScheduleDetailResponseSchema,ProjectScheduleRunsPageSchema,ProjectScheduleRunsResponseSchema,ProjectScheduleRunResponseSchema,ProjectScheduleRunDetailResponseSchema,init_schedule_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();init_schedule_notifications_dto();PROJECT_SECRET_KEY_PATTERN=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN=/^(PUBLIC_|VITE_|NEXT_PUBLIC_|NUXT_PUBLIC_)/,RESERVED_PROJECT_SECRET_KEYS=new Set([...FIMO_MANAGED_PROJECT_ENV_KEYS,"FIMO_SCHEDULE_ID","FIMO_SCHEDULE_RUN_ID","FIMO_SCHEDULE_NAME"]),ProjectSecretKeySchema=z28.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=z28.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z28.uuid(),env:z28.string().min(1),name:z28.string().min(1),cron:z28.string().min(1),command:z28.string().min(1),secretKeys:z28.array(z28.string().min(1)),enabled:z28.boolean(),lastRunAt:z28.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z28.string().nullable(),suspendedAt:z28.coerce.date().nullable().optional(),suspensionReason:z28.string().nullable().optional(),overPolicyReasons:z28.array(z28.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z28.object({name:z28.string().min(1).max(120),cron:z28.string().min(1).max(120),command:z28.string().min(1).max(500),secretKeys:z28.array(ProjectSecretKeySchema).default([]),enabled:z28.boolean().optional()}),UpdateProjectScheduleRequestSchema=z28.object({name:z28.string().min(1).max(120).optional(),cron:z28.string().min(1).max(120).optional(),command:z28.string().min(1).max(500).optional(),secretKeys:z28.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z28.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z28.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z28.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z28.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z28.object({maxRuns:z28.number().int().positive(),retentionDays:z28.number().int().positive().nullable(),outputRetentionDays:z28.number().int().positive(),maxOutputBytes:z28.number().int().positive()}),SchedulePolicyStateSchema=z28.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z28.object({code:z28.enum(["Free","PAYG","Premium","Pro"]),source:z28.enum(["cached_subscription","free_fallback"]),activeSchedules:z28.object({used:z28.number().int().nonnegative(),limit:z28.number().int().nonnegative()}),minCadenceMinutes:z28.number().int().positive(),maxRunMs:z28.number().int().positive(),concurrency:z28.object({used:z28.number().int().nonnegative(),limit:z28.number().int().positive()}),compute:z28.object({settledMs:z28.number().int().nonnegative(),activeMs:z28.number().int().nonnegative(),reservedMs:z28.number().int().nonnegative().optional(),includedMs:z28.number().int().nonnegative(),remainingMs:z28.number().int().nonnegative(),resetsAt:z28.coerce.date()}),upgrade:z28.object({code:z28.literal("Pro"),activeSchedulesLimit:z28.number().int().positive(),minCadenceMinutes:z28.number().int().positive(),maxRunMs:z28.number().int().positive(),maxConcurrentRuns:z28.number().int().positive(),computeIncludedMs:z28.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z28.array(z28.string())}),ProjectScheduleUsageSchema=z28.object({runCount:z28.number().int().nonnegative(),runsWithOutput:z28.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z28.object({id:z28.uuid(),scheduleId:z28.uuid(),projectId:z28.uuid(),env:z28.string().min(1),scheduleName:z28.string().min(1),command:z28.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z28.object({id:z28.string().min(1),name:z28.string().min(1)}).nullable(),queuedAt:z28.coerce.date(),startedAt:z28.coerce.date().nullable(),finishedAt:z28.coerce.date().nullable(),exitCode:z28.number().int().nullable(),errorCode:z28.string().nullable(),error:z28.string().nullable(),outputBytes:z28.number().int().nonnegative(),outputTruncated:z28.boolean(),outputExpiresAt:z28.coerce.date().nullable(),metadataExpiresAt:z28.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z28.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z28.coerce.date().nullable(),items:z28.array(z28.object({key:z28.string().min(1),updatedAt:z28.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z28.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z28.object({trigger:z28.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z28.object({limit:z28.coerce.number().int().min(1).max(100).default(25),cursor:z28.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z28.object({items:z28.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z28.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z28.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z28.object({items:z28.array(ProjectScheduleRunDTOSchema),nextCursor:z28.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z29}from"zod";var WORK_NOTIFICATION_TOPICS,WorkNotificationTopicSchema,PUBLICATION_NOTIFICATION_TOPICS,NOTIFICATION_TOPICS,NotificationTopicSchema,NOTIFICATION_DELIVERY_CADENCES,NotificationDeliveryCadenceSchema,NOTIFICATION_CHANNELS,NotificationChannelSchema,NOTIFICATION_ACTOR_KINDS,NotificationActorKindSchema,NotificationActorSchema,NotificationSummarySchema,ReportBriefPayloadSchema,NotificationRunOutcomeSchema,NotificationRetainedReasonSchema,NotificationWorkSessionSchema,NotificationPayloadSchema,NotificationEnvelopeSchema,NotificationDeliveryStateSchema,NotificationDeliverySchema,NotificationPreferenceSchema,init_notification_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/notification.dto.js"(){"use strict";init_agent_report();WORK_NOTIFICATION_TOPICS=["agent_run_outcome","agent_retained_review","agent_conflict"],WorkNotificationTopicSchema=z29.enum(WORK_NOTIFICATION_TOPICS),PUBLICATION_NOTIFICATION_TOPICS=["publication_failed"],NOTIFICATION_TOPICS=[...WORK_NOTIFICATION_TOPICS,...PUBLICATION_NOTIFICATION_TOPICS],NotificationTopicSchema=z29.enum(NOTIFICATION_TOPICS),NOTIFICATION_DELIVERY_CADENCES=["immediate","daily","off"],NotificationDeliveryCadenceSchema=z29.enum(NOTIFICATION_DELIVERY_CADENCES),NOTIFICATION_CHANNELS=["email"],NotificationChannelSchema=z29.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z29.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z29.discriminatedUnion("kind",[z29.object({kind:z29.literal("user"),userId:z29.string().min(1)}).strict(),z29.object({kind:z29.literal("agent"),agentKey:z29.string().min(1).max(120),agentId:z29.uuid().optional()}).strict(),z29.object({kind:z29.literal("system")}).strict()]),NotificationSummarySchema=z29.string().trim().min(1).max(1200),ReportBriefPayloadSchema={title:z29.string().trim().min(1).max(120).optional(),brief:StoredReportBriefSchema.optional()},NotificationRunOutcomeSchema=z29.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z29.enum(["review","agent_requested","recovery"]),NotificationWorkSessionSchema=z29.object({sessionId:z29.uuid(),branch:z29.string().min(1),targetBranch:z29.string().min(1),revision:z29.string().min(1),fingerprint:z29.string().min(1)}),NotificationPayloadSchema=z29.discriminatedUnion("topic",[z29.object({topic:z29.literal("agent_run_outcome"),threadId:z29.uuid(),invocationId:z29.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z29.object({topic:z29.literal("agent_retained_review"),threadId:z29.uuid().optional(),invocationId:z29.uuid().optional(),proposalId:z29.uuid().optional(),workSession:NotificationWorkSessionSchema.optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z29.object({topic:z29.literal("agent_conflict"),mergeId:z29.uuid(),threadId:z29.uuid().optional(),invocationId:z29.uuid().optional(),summary:NotificationSummarySchema.optional(),...ReportBriefPayloadSchema}).strict(),z29.object({topic:z29.literal("publication_failed"),publicationId:z29.uuid(),sourceBranch:z29.string().trim().min(1).max(120),failureCode:z29.string().trim().min(1).max(64),failedAt:z29.iso.datetime(),firstPublication:z29.boolean()}).strict()]),NotificationEnvelopeSchema=z29.object({id:z29.uuid(),projectId:z29.uuid(),sourceKey:z29.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z29.literal(1),payload:NotificationPayloadSchema,createdAt:z29.coerce.date()}),NotificationDeliveryStateSchema=z29.enum(["pending","deferred","sent","suppressed","failed"]),NotificationDeliverySchema=z29.object({id:z29.uuid(),notificationRecipientId:z29.uuid(),projectId:z29.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z29.number().int().nonnegative(),nextAttemptAt:z29.coerce.date().nullable(),lastAttemptAt:z29.coerce.date().nullable(),sentAt:z29.coerce.date().nullable(),failureCode:z29.string().max(80).nullable(),createdAt:z29.coerce.date(),updatedAt:z29.coerce.date()}),NotificationPreferenceSchema=z29.object({topic:WorkNotificationTopicSchema,channel:z29.literal("email"),enabled:z29.boolean(),cadence:NotificationDeliveryCadenceSchema.exclude(["off"]),effectiveCadence:NotificationDeliveryCadenceSchema,source:z29.enum(["default","explicit"])})}});import{z as z30}from"zod";var NOTIFICATION_PREFERENCE_GROUPS,NotificationPreferenceGroupSchema,FIMO_TOGGLE_PREFERENCE_ENTRY_IDS,FimoTogglePreferenceEntryIdSchema,FIMO_DELIVERY_PREFERENCE_ENTRY_IDS,FimoDeliveryPreferenceEntryIdSchema,MARKETING_PREFERENCE_ENTRY_PREFIX,PreferenceSourceSchema,EmailNotificationProviderSyncSchema,EmailNotificationPreferenceSchema,PROVIDER_SUBSCRIPTION_PLACEMENTS,ProviderSubscriptionPlacementSchema,PROVIDER_SUBSCRIPTION_SEMANTIC_IDS,ProviderSubscriptionSemanticIdSchema,NotificationPreferenceEntrySchema,NotificationPreferenceCatalogSchema,NotificationPreferenceCatalogResponseSchema,NotificationPreferenceEntryResponseSchema,UpdateEmailNotificationPreferenceRequestSchema,EmailNotificationPreferenceResponseSchema,UpdateNotificationPreferenceEntryRequestSchema,init_notification_preference_catalog_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/notification-preference-catalog.dto.js"(){"use strict";init_response();init_notification_dto();NOTIFICATION_PREFERENCE_GROUPS=["work_review","publishing","schedule","marketing"],NotificationPreferenceGroupSchema=z30.enum(NOTIFICATION_PREFERENCE_GROUPS),FIMO_TOGGLE_PREFERENCE_ENTRY_IDS=["work_review.agent_conflict","publishing.publication_failed","schedule.schedule_health","schedule.schedule_compute_allowance"],FimoTogglePreferenceEntryIdSchema=z30.enum(FIMO_TOGGLE_PREFERENCE_ENTRY_IDS),FIMO_DELIVERY_PREFERENCE_ENTRY_IDS=["work_review.agent_retained_review","work_review.agent_run_outcome"],FimoDeliveryPreferenceEntryIdSchema=z30.enum(FIMO_DELIVERY_PREFERENCE_ENTRY_IDS),MARKETING_PREFERENCE_ENTRY_PREFIX="marketing.",PreferenceSourceSchema=z30.enum(["default","explicit"]),EmailNotificationProviderSyncSchema=z30.enum(["synced","pending","unavailable"]),EmailNotificationPreferenceSchema=z30.object({enabled:z30.boolean(),source:PreferenceSourceSchema,providerSync:EmailNotificationProviderSyncSchema}).strict(),PROVIDER_SUBSCRIPTION_PLACEMENTS=["reports","product_news"],ProviderSubscriptionPlacementSchema=z30.enum(PROVIDER_SUBSCRIPTION_PLACEMENTS),PROVIDER_SUBSCRIPTION_SEMANTIC_IDS=["weekly_analytics"],ProviderSubscriptionSemanticIdSchema=z30.enum(PROVIDER_SUBSCRIPTION_SEMANTIC_IDS),NotificationPreferenceEntrySchema=z30.discriminatedUnion("kind",[z30.object({kind:z30.literal("toggle"),id:FimoTogglePreferenceEntryIdSchema,group:z30.enum(["work_review","publishing","schedule"]),enabled:z30.boolean(),source:PreferenceSourceSchema}).strict(),z30.object({kind:z30.literal("delivery"),id:FimoDeliveryPreferenceEntryIdSchema,group:z30.literal("work_review"),cadence:NotificationDeliveryCadenceSchema,source:PreferenceSourceSchema}).strict(),z30.object({kind:z30.literal("provider_subscription"),id:z30.string().startsWith(MARKETING_PREFERENCE_ENTRY_PREFIX),group:z30.literal("marketing"),name:z30.string(),description:z30.string().nullable(),placement:ProviderSubscriptionPlacementSchema,semanticId:ProviderSubscriptionSemanticIdSchema.nullable(),enabled:z30.boolean(),source:PreferenceSourceSchema}).strict()]),NotificationPreferenceCatalogSchema=z30.object({email:EmailNotificationPreferenceSchema,entries:z30.array(NotificationPreferenceEntrySchema),unavailableGroups:z30.array(NotificationPreferenceGroupSchema)}),NotificationPreferenceCatalogResponseSchema=createResponseSchema(NotificationPreferenceCatalogSchema),NotificationPreferenceEntryResponseSchema=createResponseSchema(NotificationPreferenceEntrySchema),UpdateEmailNotificationPreferenceRequestSchema=z30.object({enabled:z30.boolean()}).strict(),EmailNotificationPreferenceResponseSchema=createResponseSchema(EmailNotificationPreferenceSchema),UpdateNotificationPreferenceEntryRequestSchema=z30.discriminatedUnion("kind",[z30.object({kind:z30.literal("toggle"),enabled:z30.boolean()}).strict(),z30.object({kind:z30.literal("delivery"),cadence:NotificationDeliveryCadenceSchema}).strict(),z30.object({kind:z30.literal("provider_subscription"),enabled:z30.boolean()}).strict()])}});import{z as z31}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=z31.object({surface:SurfaceNameSchema,key:z31.string(),label:z31.string()}),InlineSchema=z31.object({text:z31.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z31.discriminatedUnion("type",[z31.object({type:z31.literal("paragraph"),content:z31.array(InlineSchema).max(24)}),z31.object({type:z31.literal("preview"),ref:DiffRefSchema,caption:z31.string().optional()}),z31.object({type:z31.literal("code"),code:z31.string(),lang:z31.string().optional(),caption:z31.string().optional()}),z31.object({type:z31.literal("risk"),level:z31.enum(["warning","error"]),content:z31.array(InlineSchema).max(24)}),z31.object({type:z31.literal("list"),items:z31.array(z31.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z31.object({headline:z31.string(),blocks:z31.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z31.object({summary:EnvDiffSummarySchema,fingerprint:z31.string(),generatedAt:z31.coerce.date(),cached:z31.boolean().optional(),credits:z31.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z32}from"zod";var PROJECT_ANALYTICS_PRESETS,PROJECT_ANALYTICS_GROUP_BY_OPTIONS,ProjectDailyVisitorsDTOSchema,ProjectAnalyticsBreakdownItemDTOSchema,ProjectAnalyticsPageBreakdownItemDTOSchema,ProjectAnalyticsRangeDTOSchema,ProjectAnalyticsAnnotationDTOSchema,PROJECT_ANALYTICS_DEVICE_FILTERS,ProjectPageviewAnalyticsDTOSchema,PROJECT_ANALYTICS_TRACKING_STATES,ProjectAnalyticsTrackingStatusDTOSchema,ProjectPageviewAnalyticsDTO,ProjectAnalyticsTrackingStatusDTO,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=z32.object({date:z32.string(),visitors:z32.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z32.object({key:z32.string(),visitors:z32.number().int().nonnegative(),pageviews:z32.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z32.object({path:z32.string(),pageName:z32.string().nullable().optional(),visitors:z32.number().int().nonnegative(),pageviews:z32.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z32.object({preset:z32.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z32.string(),requestedTo:z32.string(),effectiveFrom:z32.string(),effectiveTo:z32.string(),isRetentionLimited:z32.boolean(),groupBy:z32.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z32.object({date:z32.string(),content:z32.string(),updatedAt:z32.string(),updatedByUserId:z32.string()}),PROJECT_ANALYTICS_DEVICE_FILTERS=["bot","desktop","mobile","tablet"],ProjectPageviewAnalyticsDTOSchema=z32.object({range:ProjectAnalyticsRangeDTOSchema,deviceFilter:z32.enum(PROJECT_ANALYTICS_DEVICE_FILTERS).nullable(),visitors:z32.number().int().nonnegative(),pageviews:z32.number().int().nonnegative(),botPageviews:z32.number().int().nonnegative(),botVisitors:z32.number().int().nonnegative(),bounceRate:z32.number().min(0).max(100),viewsPerVisit:z32.number().nonnegative(),averageVisitDurationSeconds:z32.number().nonnegative(),visitorsSeries:z32.array(ProjectDailyVisitorsDTOSchema),topPages:z32.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z32.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z32.array(ProjectAnalyticsBreakdownItemDTOSchema),topBots:z32.array(ProjectAnalyticsBreakdownItemDTOSchema),topAiAssistants:z32.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z32.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z32.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z32.array(ProjectAnalyticsAnnotationDTOSchema)}),PROJECT_ANALYTICS_TRACKING_STATES=["observed","waiting","unavailable"],ProjectAnalyticsTrackingStatusDTOSchema=z32.object({state:z32.enum(PROJECT_ANALYTICS_TRACKING_STATES),lastEventAt:z32.string().nullable()}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsTrackingStatusDTO=createDTO(ProjectAnalyticsTrackingStatusDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z33}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=z33.object({id:z33.string(),email:z33.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z33.coerce.date(),createdAt:z33.coerce.date(),inviterUserId:z33.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z33.object({id:z33.string(),token:z33.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z33.object({success:z33.boolean(),projectId:z33.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z34}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=z34.object({id:z34.string(),name:z34.string(),image:z34.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z34.object({count:z34.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z34.object({counts:z34.object({signed_up:z34.int(),activated:z34.int()}),credits:z34.object({total:z34.int(),earned:z34.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z34.email(),emailVerified:z34.boolean(),createdAt:z34.coerce.date(),updatedAt:z34.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z35}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,PROJECT_PERMISSION_KEYS,ProjectPermissionKeySchema,ProjectPermissionsDTOSchema,ProjectPermissionsDTO,ProjectAccessDTOSchema,ProjectAccessDTO,AccessMutationResponseSchema,InviteAcceptResponseSchema,init_project_access_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-access.dto.js"(){"use strict";init_common();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z35.object({id:z35.string(),principalType:ProjectPrincipalTypeSchema,principalId:z35.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z35.coerce.date(),expiresAt:z35.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),PROJECT_PERMISSION_KEYS=["project:read","project:manage","project:publish","project:unpublish","project:duplicate","project:export","project:import","project:transfer","project:delete","acl:read","acl:grant","member:read","member:change-role","invite:read","invite:send","invite:revoke","asset:read","asset:upload","asset:manage","asset:delete","asset:generate","code:view","code:edit","content:view","knowledge:view","knowledge:edit","content:edit","chat:read","chat:prompt","history:view","history:manage","comment:read","comment:create","comment:delete","branch:create","environment:create","integration:manage","integration:run","sync:github","webhook:read","webhook:manage","schedule:read","schedule:manage","preview:view","realtime:connect","analytics:view","logs:view","domain:manage","agent:run"],ProjectPermissionKeySchema=z35.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z35.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z35.record(z35.string(),z35.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z35.object({access:z35.array(ProjectAccessItemDTOSchema),invites:z35.array(ProjectInviteDTOSchema),organization:z35.object({name:z35.string().nullable(),logo:z35.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z35.object({success:z35.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z35.object({success:z35.boolean(),projectId:z35.uuid()}))}});import{z as z36}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=z36.object({publicationStatus:PublicationStatusSchema,appUrl:z36.string().nullable(),lastPublishedAt:z36.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z37}from"zod";var BranchHostedPreviewStatusSchema,BranchHostedPreviewSchema,init_hosted_preview_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/hosted-preview.dto.js"(){"use strict";init_env();BranchHostedPreviewStatusSchema=z37.enum(["queued","building","ready","failed"]),BranchHostedPreviewSchema=z37.object({branch:BranchSchema,revision:z37.string().min(1).max(64).nullable(),generation:z37.string().min(1).max(64),status:BranchHostedPreviewStatusSchema,url:z37.url().nullable()})}});import{z as z38}from"zod";var PreviewUpgradeRequiredSchema,PreviewBridgePackageSchema,PreviewBridgeCapabilitySchema,SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,PreviewInstallApprovalTargetSchema,PreviewInstallRepairSchema,SandboxSessionInstallPolicyErrorSchema,SandboxPullPhaseSchema,SandboxPullFailureCodeSchema,SandboxPullFailureSchema,PreviewInstallPolicyApprovalRequestSchema,PreviewInstallPolicyApprovalEventSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();PreviewUpgradeRequiredSchema=z38.object({code:z38.literal("PREVIEW_UPGRADE_REQUIRED"),message:z38.string(),currentVersion:z38.number().int().positive(),targetVersion:z38.literal(4)}),PreviewBridgePackageSchema=z38.object({name:z38.string().min(1),version:z38.string().min(1)}),PreviewBridgeCapabilitySchema=z38.object({integrated:z38.boolean(),packages:z38.array(PreviewBridgePackageSchema)}),SandboxSessionDTOSchema=z38.object({url:z38.url(),expiresAt:z38.iso.datetime().nullable(),source:z38.enum(["sandbox","hosted"]).optional(),previewBridge:PreviewBridgeCapabilitySchema.optional()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z38.object({name:z38.string().min(1),locator:z38.string().min(1).optional(),source:z38.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z38.object({kind:z38.literal("dependency_build_scripts_blocked"),packageManager:z38.enum(["pnpm","yarn","bun"]),packages:z38.array(z38.string()),targets:z38.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z38.string(),approvalKey:z38.string(),command:z38.string().optional(),approval:z38.object({id:z38.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z38.object({code:z38.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z38.string(),repair:PreviewInstallRepairSchema}),SandboxPullPhaseSchema=z38.enum(["acquire","pull","sync-env","install","restart","readiness"]),SandboxPullFailureCodeSchema=z38.enum(["sync_failed","readiness_failed","install_policy_blocked"]),SandboxPullFailureSchema=z38.object({message:z38.string(),code:SandboxPullFailureCodeSchema.optional().catch(void 0),phase:SandboxPullPhaseSchema.optional().catch(void 0),exitCode:z38.number().int().optional().catch(void 0),logTail:z38.array(z38.string()).optional().catch(void 0),logTailTruncated:z38.boolean().optional().catch(void 0),repair:PreviewInstallRepairSchema.optional().catch(void 0)}),PreviewInstallPolicyApprovalRequestSchema=z38.object({approvalId:z38.uuid()}),PreviewInstallPolicyApprovalEventSchema=z38.discriminatedUnion("type",[z38.object({type:z38.literal("progress"),step:z38.enum(["approval","install","restart","readiness"]),message:z38.string()}),z38.object({type:z38.literal("approved")}),z38.object({type:z38.literal("complete")}),z38.object({type:z38.literal("error"),code:z38.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z38.string()})])}});import{z as z39}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:z39.string(),slug:z39.string().nullable(),logo:z39.string().nullable(),metadata:z39.record(z39.string(),z39.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z39.object({id:z39.string(),name:z39.string(),email:z39.email(),image:z39.string().nullable()}),OrganizationMemberDTOSchema=z39.object({id:z39.string(),userId:z39.string(),organizationId:z39.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z39.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z40}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,PlanMigrationAcceptDTOSchema,PlanMigrationPreviewDTOSchema,PlanMigrationPreviewDTO,PlanMigrationStateSchema,PlanMigrationOfferDTOSchema,PlanMigrationOfferDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,MediaStorageUsageDTOSchema,MediaStorageUsageDTO,PendingPlanChangeDTOSchema,AutomaticSpendStopDTOSchema,HostingOverageStatusDTOSchema,HostingOverageStatusDTO,UpdateHostingOverageRequestSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,AutoRefillConfigDTOSchema,AutoRefillConfigDTO,UpdateAutoRefillDTOSchema,OptionalSpendRefusalSchema,CreditPurchasePricingDTOSchema,CreditPurchasePricingDTO,PurchaseCreditsDTOSchema,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,PaymentRecoveryInvoiceDTOSchema,PaymentRecoveryDTOSchema,PaymentRecoveryDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,AutoRefillConfigResponseSchema,CreditPurchasePricingResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,PaymentRecoveryResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common();init_create_dto();init_response();CancellationReasonCodeSchema=z40.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z40.object({reason:CancellationReasonCodeSchema,details:z40.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z40.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z40.object({offerVersion:z40.string().trim().min(1),unusedPremiumCreditAmount:z40.number().int().nonnegative(),amountDueNow:z40.number().int().nonnegative(),renewsOn:z40.string()}),PlanMigrationPreviewDTOSchema=z40.object({currency:z40.string().trim().min(1),unusedPremiumCreditAmount:z40.number().int().nonnegative(),amountDueNow:z40.number().int().nonnegative(),startsAt:z40.string(),renewsAt:z40.string(),nextRenewalAmount:z40.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z40.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z40.object({id:z40.string(),organizationId:z40.string(),legacySubscriptionId:z40.string(),offeredPlanCode:z40.string(),offeredPlanName:z40.string(),offeredPriceAmount:z40.number(),offeredCurrency:z40.string(),offerVersion:z40.string(),state:PlanMigrationStateSchema,checkoutToken:z40.string().nullable(),deadlineAt:z40.string(),transitions:z40.array(z40.object({event:z40.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z40.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z40.object({included:z40.number().optional(),unitPrice:z40.number().optional(),dailyCap:z40.number().nullable().optional()}),EntitlementsDTOSchema=z40.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z40.object({retentionDays:z40.number().int().positive(),canUseExtendedDateRanges:z40.boolean()}).optional(),history:z40.object({retentionDays:z40.number().int().positive()}).optional(),members:z40.object({canInvite:z40.boolean(),maxMembers:z40.number().int().positive().nullable()}).optional(),projects:z40.object({maxProjects:z40.number().int().positive().nullable()}).optional(),domains:z40.object({canUseCustomDomains:z40.boolean(),maxDomains:z40.number().int().nonnegative().nullable()}).optional(),media_storage:z40.object({limitBytes:z40.number().int().nonnegative()}).optional()}),MediaStorageUsageDTOSchema=z40.object({usedBytes:z40.number().int().nonnegative().nullable(),limitBytes:z40.number().int().nonnegative().nullable(),state:z40.enum(["ready","unavailable"]),measuredAt:z40.iso.datetime().nullable()}),MediaStorageUsageDTO=createDTO(MediaStorageUsageDTOSchema),PendingPlanChangeDTOSchema=z40.object({toPlanCode:TemplateCodeSchema,effectiveAt:z40.string(),scheduledAt:z40.string().nullable()}),AutomaticSpendStopDTOSchema=z40.object({fromPlanCode:TemplateCodeSchema,toPlanCode:TemplateCodeSchema,cutoffAt:z40.string(),spendStopped:z40.boolean(),settlementEndsAt:z40.string()}),HostingOverageStatusDTOSchema=z40.object({state:z40.enum(["ready","unavailable"]),planCode:z40.string(),overageAvailable:z40.boolean(),overageEnabled:z40.boolean(),monthlyCapUsd:z40.number().int().positive().nullable(),periodStart:z40.iso.datetime().nullable(),periodEnd:z40.iso.datetime().nullable(),usedBytes:z40.number().nonnegative().nullable(),includedBytes:z40.number().nonnegative().nullable(),overageBytes:z40.number().nonnegative(),currentOverageAmountMicros:z40.number().nonnegative().nullable(),totalExtraUsageAmountMicros:z40.number().nonnegative().nullable(),currency:z40.string().nullable(),status:z40.enum(["ok","near_limit","paused"])}),HostingOverageStatusDTO=createDTO(HostingOverageStatusDTOSchema),UpdateHostingOverageRequestSchema=z40.object({enabled:z40.boolean(),monthlyCapUsd:z40.number().int().positive().max(1e6).optional()}).refine(value=>!value.enabled||value.monthlyCapUsd!==void 0,{message:"Enabling extra usage requires a monthly budget"}),SubscriptionDTOSchema=z40.object({id:z40.string(),external_id:z40.string(),customerId:z40.string(),planId:z40.string(),planCode:z40.union([TemplateCodeSchema,z40.literal("Unknown")]),currentPeriod:z40.object({start:z40.string(),end:z40.string().nullable()}),cancelAt:z40.string().nullable(),pendingPlanChange:PendingPlanChangeDTOSchema.nullable(),automaticSpendStop:AutomaticSpendStopDTOSchema.nullable(),entitlements:EntitlementsDTOSchema,currency:z40.string(),nextPaymentAt:z40.string().nullable(),baseAmount:z40.number().nullable()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z40.object({totalCap:z40.number(),dailyCap:z40.number(),usedTotal:z40.number()}),CreditBalanceDTOSchema=z40.object({total:z40.number(),base:z40.number(),dailyBase:z40.number(),purchases:z40.number(),awards:z40.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z40.object({total:z40.number(),nearLimit:z40.boolean(),canChat:z40.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z40.object({dailyFreeAvailable:z40.number(),monthlyAvailable:z40.number(),purchasedAvailable:z40.number(),awardedAvailable:z40.number()}),ProjectDailyCreditAllowanceDTOSchema=z40.object({periodCap:z40.number(),dailyGrant:z40.number(),usedThisPeriod:z40.number(),remainingThisPeriod:z40.number()}),ProjectCreditBalanceDTOSchema=z40.object({projectId:z40.uuid(),organizationId:z40.string(),balance:z40.object({totalAvailable:z40.number(),nearLimit:z40.boolean(),canUseAi:z40.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z40.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AutoRefillConfigDTOSchema=z40.discriminatedUnion("enabled",[z40.object({enabled:z40.literal(!0),thresholdUsd:z40.number().nonnegative(),refillAmountUsd:z40.number().nonnegative()}),z40.object({enabled:z40.literal(!1),thresholdUsd:z40.number().nonnegative().nullable(),refillAmountUsd:z40.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z40.discriminatedUnion("enabled",[z40.object({enabled:z40.literal(!0),thresholdUsd:z40.number().min(.01).multipleOf(.01),refillAmountUsd:z40.number().min(.01).multipleOf(.01),expectedRateToken:z40.string().trim().min(1).max(40)}).strict(),z40.object({enabled:z40.literal(!1),thresholdUsd:z40.number().min(.01).multipleOf(.01),expectedRateToken:z40.string().trim().min(1).max(40).optional()}).strict()]),OptionalSpendRefusalSchema=z40.enum(["no_subscription","plan_cannot_fund","pending_plan_exit"]),CreditPurchasePricingDTOSchema=z40.object({planCode:z40.union([TemplateCodeSchema,z40.literal("Unknown")]).nullable(),canPurchase:z40.boolean(),refusalReason:OptionalSpendRefusalSchema.nullable(),creditsPerDollar:z40.number().int().positive(),minAmountUsd:z40.number().positive(),maxAmountUsd:z40.number().positive(),rateToken:z40.string().nullable()}),CreditPurchasePricingDTO=createDTO(CreditPurchasePricingDTOSchema),PurchaseCreditsDTOSchema=z40.object({amountUsd:z40.number(),idempotencyKey:z40.string().trim().min(8).max(120),expectedRateToken:z40.string().trim().min(1).max(40)}).strict(),SuccessfulPurchaseDTOSchema=z40.object({invoiceId:z40.string(),newBalance:z40.int(),creditCount:z40.int(),amountUsd:z40.number(),creditsPerDollar:z40.int()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z40.object({url:z40.string()}),PortalDTO=createDTO(PortalDTOSchema),PaymentRecoveryInvoiceDTOSchema=z40.object({id:z40.string(),number:z40.string().nullable(),status:z40.string(),amountDue:z40.int(),currency:z40.string(),issuedAt:z40.string().nullable(),hostedInvoiceUrl:z40.string().nullable()}),PaymentRecoveryDTOSchema=z40.discriminatedUnion("status",[z40.object({status:z40.literal("eligible"),checkedAt:z40.string()}),z40.object({status:z40.literal("recovery_required"),checkedAt:z40.string(),invoice:PaymentRecoveryInvoiceDTOSchema,outstandingCount:z40.int().min(1)}),z40.object({status:z40.literal("unavailable"),checkedAt:z40.string(),reason:z40.enum(["provider_error","truncated","unattempted","foreign_invoice","unknown_status"])})]),PaymentRecoveryDTO=createDTO(PaymentRecoveryDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),AutoRefillConfigResponseSchema=createResponseSchema(AutoRefillConfigDTOSchema),CreditPurchasePricingResponseSchema=createResponseSchema(CreditPurchasePricingDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema),PaymentRecoveryResponseSchema=createResponseSchema(PaymentRecoveryDTOSchema)}});import{z as z41}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=z41.object({brand:z41.string(),last4:z41.string(),exp:z41.string(),isDefault:z41.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z42}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentFieldGroupSchema,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=z42.string().superRefine((path49,ctx)=>{let segments=path49.split(".");(segments.length===0||segments.some(segment=>!CONTENT_FIELD_NAME_PATTERN.test(segment)))&&ctx.addIssue({code:"custom",message:"Field paths must use dot-separated field or block variant names."})}),SchemaMigrationOperationSchema=z42.object({type:z42.literal("renameField"),contentType:z42.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z42.object({enabled:z42.boolean()}).strict(),ContentFieldGroupSchema=z42.object({id:z42.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z42.string().min(1).max(255),default:z42.boolean().optional()}).strict(),ContentTypeDTOSchema=z42.object({id:z42.string(),name:z42.string(),label:z42.string(),isSingleton:z42.boolean(),i18n:ContentTypeI18nSchema,groups:z42.array(ContentFieldGroupSchema).default([]),fields:z42.record(z42.string(),FieldDefinitionSchema),createdAt:z42.string(),updatedAt:z42.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z42.object({contentTypes:z42.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z42.object({id:z42.string(),entryId:z42.string(),documentId:z42.string(),slug:z42.string(),locale:z42.string().optional(),createdAt:z42.string(),updatedAt:z42.string(),__fimo:z42.object({contentType:z42.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z42.object({data:z42.array(EntryDTOSchema),meta:z42.object({limit:z42.number(),offset:z42.number(),total:z42.number(),hasMore:z42.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z42.object({contentType:z42.string(),count:z42.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z42.object({counts:z42.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z42.object({count:z42.number().int().nonnegative(),sourceLocale:z42.string(),targetLocale:z42.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z42.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z42.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z42.union([z42.string(),z42.number(),z42.boolean(),z42.null()]),entryWhereOperatorSchema=z42.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z42.array(entryWhereScalarSchema).optional(),$nin:z42.array(entryWhereScalarSchema).optional(),$contains:z42.string().optional(),$startsWith:z42.string().optional(),$null:z42.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z42.record(z42.string(),z42.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z42.record(z42.string(),z42.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z42.object({data:z42.record(z42.string(),z42.unknown()),locale:z42.string().min(1).optional(),documentId:z42.uuid().optional()}),entryIdsSchema=z42.array(z42.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z42.object({sql:z42.string().min(1)}),BulkCreateEntriesRequestSchema=z42.object({entries:z42.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z42.union([z42.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z42.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z42.object({updates:z42.array(z42.object({id:z42.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z42.union([z42.object({ids:entryIdsSchema,locale:z42.string().min(1).optional()}),z42.object({where:EntryWhereSchema,locale:z42.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z42.object({data:z42.array(z42.record(z42.string(),z42.unknown())),meta:z42.object({rowCount:z42.number().int().nonnegative(),truncated:z42.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z42.object({data:z42.array(EntryDTOSchema),meta:z42.object({created:z42.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z42.object({data:z42.array(EntryDTOSchema),meta:z42.object({updated:z42.number().int().nonnegative(),missing:z42.array(z42.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z42.object({data:z42.array(EntryDTOSchema),meta:z42.object({deleted:z42.number().int().nonnegative(),missing:z42.array(z42.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z43}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z43.object({index:z43.number().int().nonnegative(),contentType:z43.string(),field:z43.string(),value:z43.string(),against:z43.enum(["stored","batch"]),ownerDocumentId:z43.uuid().optional(),ownerIndex:z43.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z43.object({code:z43.literal("unique_conflict"),message:z43.string(),conflicts:z43.array(UniqueConflictSchema),truncated:z43.boolean().optional()})}});import{z as z44}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=z44.object({kind:z44.literal("unique_conflict"),contentType:z44.string(),field:z44.string(),value:z44.string(),documentCount:z44.number().int().positive(),documentIds:z44.array(z44.uuid()),documentIdsTruncated:z44.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z44.object({code:z44.literal("schema_transition_rejected"),message:z44.string(),issues:z44.array(SchemaTransitionIssueSchema),truncated:z44.boolean().optional()})}});import{z as z45}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=z45.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z45.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z45.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z45.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z45.object({field:CmsFieldNameSchema,direction:z45.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z45.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z45.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z45.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z45.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z45.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z46}from"zod";var MIGRATION_SOURCE_PLATFORMS,MigrationSourcePlatformSchema,init_project_migration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-migration.dto.js"(){"use strict";MIGRATION_SOURCE_PLATFORMS=["webflow","framer","squarespace","wix","carrd","wordpress","nextjs","astro","react-router","other","unknown"],MigrationSourcePlatformSchema=z46.enum(MIGRATION_SOURCE_PLATFORMS)}});import{z as z47}from"zod";var CLIENT_TRACKED_EVENTS,ClientTrackedEventSchema,TrackProjectEventRequestSchema,init_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/analytics.dto.js"(){"use strict";CLIENT_TRACKED_EVENTS=["didStartMigration","didEndMigration"],ClientTrackedEventSchema=z47.enum(CLIENT_TRACKED_EVENTS),TrackProjectEventRequestSchema=z47.object({event:ClientTrackedEventSchema,properties:z47.record(z47.string(),z47.unknown()).default({})})}});import{z as z48}from"zod";var AssetPathItemSchema,AssetDTOSchema,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema,AssetListResponseSchema,MediaStorageLimitErrorSchema,AssetReferenceScopeSchema,ASSET_REFERENCE_IMPACT_FILE_LIMIT,AssetReferenceImpactRequestSchema,AssetReferenceImpactSelectionDTOSchema,AssetReferenceFindingDTOSchema,AssetReferenceScopeResultDTOSchema,AssetReferenceScopeResultDTO,AssetReferenceImpactEventDTOSchema,AssetReferenceImpactEventDTO,AssetReferenceReplacementRequestSchema,AssetReferenceReplacementResultSchema,AssetReferenceReplacementResponseSchema,AssetReferenceReplacementPreviewResponseSchema,AssetCodeReferenceReplacementResultSchema,AssetReferenceReplacementErrorCodeSchema,AssetReferenceReplacementErrorSchema,ASSET_REMOVAL_ASSET_LIMIT,AssetRemovalIntentSchema,ASSET_REPLACING_REMOVAL_INTENTS,isReplacingIntent,AssetRemovalRequestSchema,AssetRemovalOperationDTOSchema,AssetRemovalOperationDTO,AssetRemovalScheduleResultDTOSchema,AssetRemovalScheduleResultDTO,AssetRemovalErrorCodeSchema,AssetRemovalErrorSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common();init_create_dto();init_response();AssetPathItemSchema=z48.object({id:z48.string(),name:z48.string()}),AssetDTOSchema=z48.object({id:z48.string(),name:z48.string(),type:AssetTypeSchema,originalFileName:z48.string().nullable(),parentId:z48.string().nullable(),mimeType:z48.string().nullable(),fileSize:z48.number().nullable(),url:z48.string().nullable(),storageKey:z48.string().nullable(),createdAt:z48.string(),updatedAt:z48.string(),altText:z48.string().nullable().optional(),caption:z48.string().nullable().optional(),aiCaption:z48.string().nullable().optional(),aiAltText:z48.string().nullable().optional(),aiTags:z48.array(z48.string()).nullable().optional(),aiPrimaryColor:z48.string().nullable().optional(),aiProcessingStatus:z48.string().nullable().optional(),width:z48.number().nullable().optional(),height:z48.number().nullable().optional(),path:z48.array(AssetPathItemSchema).optional(),hasChildren:z48.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z48.lazy(()=>z48.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z48.array(AssetDTOSchema)),MediaStorageLimitErrorSchema=z48.object({error:z48.string(),code:z48.literal("media_storage_limit_exceeded"),usedBytes:z48.number().int().nonnegative(),limitBytes:z48.number().int().positive(),incomingBytes:z48.number().int().nonnegative()}),AssetReferenceScopeSchema=z48.enum(["current","main","live"]),ASSET_REFERENCE_IMPACT_FILE_LIMIT=50,AssetReferenceImpactRequestSchema=z48.object({assetIds:z48.array(z48.uuid()).min(1).max(ASSET_REFERENCE_IMPACT_FILE_LIMIT),scopes:z48.array(AssetReferenceScopeSchema).min(1).optional()}),AssetReferenceImpactSelectionDTOSchema=z48.object({totalFiles:z48.number().int().nonnegative(),checkedFiles:z48.number().int().nonnegative(),limit:z48.number().int().positive()}),AssetReferenceFindingDTOSchema=z48.object({assetId:z48.uuid(),entryId:z48.string(),documentId:z48.string(),contentType:z48.string(),locale:z48.string().nullable(),slug:z48.string(),fieldPath:z48.string()}),AssetReferenceScopeResultDTOSchema=z48.object({scope:AssetReferenceScopeSchema,label:z48.string(),state:z48.enum(["available","not-published","failed"]),coverage:z48.enum(["complete","partial","failed"]),referenceCount:z48.number().int().nonnegative().optional(),codeReferenceCount:z48.number().int().nonnegative().optional(),referencedAssetIds:z48.array(z48.uuid()).optional(),references:z48.array(AssetReferenceFindingDTOSchema),reason:z48.enum(["timeout","unavailable"]).optional()}),AssetReferenceScopeResultDTO=createDTO(AssetReferenceScopeResultDTOSchema),AssetReferenceImpactEventDTOSchema=z48.discriminatedUnion("type",[z48.object({type:z48.literal("selection"),data:AssetReferenceImpactSelectionDTOSchema}),z48.object({type:z48.literal("scope"),data:AssetReferenceScopeResultDTOSchema}),z48.object({type:z48.literal("complete")})]),AssetReferenceImpactEventDTO=createDTO(AssetReferenceImpactEventDTOSchema),AssetReferenceReplacementRequestSchema=z48.object({replacementAssetId:z48.uuid()}),AssetReferenceReplacementResultSchema=z48.object({referencesReplaced:z48.number().int().nonnegative(),entriesChanged:z48.number().int().nonnegative()}),AssetReferenceReplacementResponseSchema=createResponseSchema(AssetReferenceReplacementResultSchema),AssetReferenceReplacementPreviewResponseSchema=createResponseSchema(AssetReferenceReplacementResultSchema),AssetCodeReferenceReplacementResultSchema=z48.object({referencesReplaced:z48.number().int().nonnegative(),filesChanged:z48.number().int().nonnegative(),commitSha:z48.string().nullable()}),AssetReferenceReplacementErrorCodeSchema=z48.enum(["asset_replacement.self","asset_replacement.source_not_found","asset_replacement.replacement_not_found","asset_replacement.incompatible_media","asset_replacement.target_unavailable","asset_replacement.code_not_editable","asset_replacement.code_unavailable","asset_replacement.code_conflict","asset_replacement.code_too_many_files"]),AssetReferenceReplacementErrorSchema=z48.object({error:z48.string(),code:AssetReferenceReplacementErrorCodeSchema}),ASSET_REMOVAL_ASSET_LIMIT=200,AssetRemovalIntentSchema=z48.enum(["remove-from-branch","delete-from-project","replace-and-remove","replace-and-delete"]),ASSET_REPLACING_REMOVAL_INTENTS=["replace-and-remove","replace-and-delete"],isReplacingIntent=__name(intent=>ASSET_REPLACING_REMOVAL_INTENTS.includes(intent),"isReplacingIntent"),AssetRemovalRequestSchema=z48.object({intent:AssetRemovalIntentSchema,assetIds:z48.array(z48.uuid()).min(1).max(ASSET_REMOVAL_ASSET_LIMIT),replacementAssetId:z48.uuid().optional()}).refine(request=>isReplacingIntent(request.intent)===(request.replacementAssetId!==void 0),{message:"A replacement is required by the replace intents and rejected by the others",path:["replacementAssetId"]}).refine(request=>!isReplacingIntent(request.intent)||request.assetIds.length===1,{message:"A replacement applies to exactly one asset",path:["assetIds"]}),AssetRemovalOperationDTOSchema=z48.object({id:z48.uuid(),intent:AssetRemovalIntentSchema,assetIds:z48.array(z48.uuid()),replacementAssetId:z48.uuid().nullable(),expiresAt:z48.iso.datetime(),undoable:z48.boolean(),requestedByMe:z48.boolean()}),AssetRemovalOperationDTO=createDTO(AssetRemovalOperationDTOSchema),AssetRemovalScheduleResultDTOSchema=AssetRemovalOperationDTOSchema.extend({codeReplacement:AssetCodeReferenceReplacementResultSchema.optional()}),AssetRemovalScheduleResultDTO=createDTO(AssetRemovalScheduleResultDTOSchema),AssetRemovalErrorCodeSchema=z48.enum(["asset_removal.asset_not_found","asset_removal.replacement_not_found","asset_removal.already_finalized"]),AssetRemovalErrorSchema=z48.object({error:z48.string(),code:AssetRemovalErrorCodeSchema})}});import{z as z49}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z49.object({key:z49.string(),value:z49.string().optional(),defaultValue:z49.string(),locale:z49.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z50}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=z50.object({id:z50.string(),name:z50.string(),type:z50.enum(["file","folder"]),path:z50.string(),children:z50.lazy(()=>z50.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z50.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z50.object({path:z50.string(),exists:z50.boolean(),type:z50.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z51}from"zod";var FormFieldTypeSchema,FormFieldValidationSchema,FormFieldSchema,FormFieldsSchema,FormContentSchema,FormUpdateSchema,init_form_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/form.dto.js"(){"use strict";FormFieldTypeSchema=z51.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),FormFieldValidationSchema=z51.object({minLength:z51.number().optional(),maxLength:z51.number().optional(),min:z51.number().optional(),max:z51.number().optional(),pattern:z51.string().optional(),maxFileSize:z51.number().optional(),accept:z51.array(z51.string()).optional()}),FormFieldSchema=z51.object({type:FormFieldTypeSchema,label:z51.string(),placeholder:z51.string().optional(),required:z51.boolean().optional(),defaultValue:z51.string().optional(),options:z51.array(z51.string()).optional(),validation:FormFieldValidationSchema.optional()}),FormFieldsSchema=z51.record(z51.string(),FormFieldSchema),FormContentSchema=z51.object({name:z51.string().min(1).max(255),label:z51.string().min(1).max(255),fields:FormFieldsSchema}).strict(),FormUpdateSchema=FormContentSchema.partial().refine(update=>update.name!==void 0||update.label!==void 0||update.fields!==void 0,{message:"Pass at least one of name, label, or fields."})}});import{z as z52}from"zod";function isIanaTimezone(value){try{return new Intl.DateTimeFormat("en-US",{timeZone:value}),!0}catch{return!1}}var ChatRoutineCronSchema,ChatRoutineTimezoneSchema,ChatRoutineScheduleSchema,ChatRoutineNameSchema,ChatRoutineInstructionsSchema,ChatRoutineModelSchema,ChatRoutineEventTriggerDTOSchema,ChatRoutineEventTriggerInputSchema,ChatRoutineTriggersDTOSchema,ChatRoutineRunOutcomeSchema,ChatRoutineReportSchema,ChatRoutineDTOSchema,ChatRoutineListDTOSchema,ChatRoutineCreateSchema,ChatRoutineUpdateSchema,ChatRoutineRefusalReasonSchema,ChatRoutineRefusalDTOSchema,ChatRoutineRunStatusSchema,ChatRoutineRunTriggerSchema,ChatRoutineRunStartedBySchema,ChatRoutineRunDTOSchema,ChatRoutineRunListDTOSchema,ChatRoutineRunRequestSchema,ChatRoutineRunOutcomeDTOSchema,init_chat_routine_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat-routine.dto.js"(){"use strict";ChatRoutineCronSchema=z52.string().trim().max(64).regex(/^\S+(?: \S+){4}$/,"A schedule is a five-field cron expression");__name(isIanaTimezone,"isIanaTimezone");ChatRoutineTimezoneSchema=z52.string().trim().min(1).max(64).refine(isIanaTimezone,"Unknown timezone"),ChatRoutineScheduleSchema=z52.object({cron:ChatRoutineCronSchema,timezone:ChatRoutineTimezoneSchema}),ChatRoutineNameSchema=z52.string().trim().min(1).max(120),ChatRoutineInstructionsSchema=z52.string().trim().min(1).max(2e4),ChatRoutineModelSchema=z52.string().trim().min(1).max(120),ChatRoutineEventTriggerDTOSchema=z52.object({text:z52.string(),title:z52.string(),explanation:z52.string()}),ChatRoutineEventTriggerInputSchema=z52.object({text:z52.string().trim().min(1).max(500)}),ChatRoutineTriggersDTOSchema=z52.object({manual:z52.literal(!0),schedule:ChatRoutineScheduleSchema.nullable(),event:ChatRoutineEventTriggerDTOSchema.nullable()}),ChatRoutineRunOutcomeSchema=z52.enum(["quiet","reported","decision","incomplete","failed","running"]),ChatRoutineReportSchema=z52.object({message:z52.string().trim().min(1).max(2e4),decision:z52.boolean().optional(),incomplete:z52.boolean().optional()}).refine(report=>!(report.decision===!0&&report.incomplete===!0),{message:"A run that could not check asks for no decision: set incomplete or decision, not both."}),ChatRoutineDTOSchema=z52.object({id:z52.string().uuid(),threadId:z52.string().uuid(),runThreadId:z52.string().uuid(),name:z52.string(),instructions:z52.string(),triggers:ChatRoutineTriggersDTOSchema,model:z52.string(),modelIsDefault:z52.boolean(),paused:z52.boolean(),nextRunAt:z52.string().nullable(),lastRunAt:z52.string().nullable(),lastOutcome:ChatRoutineRunOutcomeSchema.nullable(),createdAt:z52.string(),updatedAt:z52.string()}),ChatRoutineListDTOSchema=z52.object({routines:z52.array(ChatRoutineDTOSchema)}),ChatRoutineCreateSchema=z52.object({name:ChatRoutineNameSchema,instructions:ChatRoutineInstructionsSchema,schedule:ChatRoutineScheduleSchema.nullable().optional(),event:ChatRoutineEventTriggerInputSchema.nullable().optional(),model:ChatRoutineModelSchema.nullable().optional()}),ChatRoutineUpdateSchema=z52.object({name:ChatRoutineNameSchema,instructions:ChatRoutineInstructionsSchema,schedule:ChatRoutineScheduleSchema.nullable(),event:ChatRoutineEventTriggerInputSchema.nullable(),model:ChatRoutineModelSchema.nullable(),paused:z52.boolean()}).partial().refine(update=>Object.values(update).some(value=>value!==void 0),"Change at least one field"),ChatRoutineRefusalReasonSchema=z52.enum(["routine_cadence_too_frequent","routine_schedule_invalid","routine_owner_not_agent","routine_trigger_unsupported","routine_model_unknown"]),ChatRoutineRefusalDTOSchema=z52.object({message:z52.string(),reason:ChatRoutineRefusalReasonSchema}),ChatRoutineRunStatusSchema=z52.enum(["queued","running","finished","failed","cancelled"]),ChatRoutineRunTriggerSchema=z52.enum(["schedule","hand","event"]),ChatRoutineRunStartedBySchema=z52.object({kind:z52.enum(["person","agent"]),name:z52.string().nullable()}),ChatRoutineRunDTOSchema=z52.object({messageId:z52.string().uuid(),invocationId:z52.string().uuid().nullable(),startedAt:z52.string(),trigger:ChatRoutineRunTriggerSchema,startedBy:ChatRoutineRunStartedBySchema.nullable(),status:ChatRoutineRunStatusSchema,outcome:ChatRoutineRunOutcomeSchema.nullable(),summary:z52.string().nullable(),events:z52.number().int().min(1)}),ChatRoutineRunListDTOSchema=z52.object({runs:z52.array(ChatRoutineRunDTOSchema)}),ChatRoutineRunRequestSchema=z52.object({message:z52.string().trim().min(1).max(2e4).optional()}),ChatRoutineRunOutcomeDTOSchema=z52.object({kind:z52.enum(["published","queued","replay","streaming","busy","refused"]),messageId:z52.string().uuid().nullable()})}});import{z as z53}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatLiveTurnStateDTOSchema,ChatLiveTurnStateDTO,ChatMessageAuthorDTOSchema,ChatThreadMessageDTOSchema,ChatQueuedMessageDTOSchema,ChatAttentionDTOSchema,ChatThreadMessagesPageDTOSchema,ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema,ChatNonStreamingOutcomeDTOSchema,ProjectChatKindSchema,ProjectChatCreatableKindSchema,ProjectChatRoutinesDTOSchema,ProjectChatDescriptionSchema,ProjectChatDTOSchema,ProjectChatListDTOSchema,ProjectChatCreatedDTOSchema,ProjectChatTitleSchema,ProjectChatCreateSchema,ProjectChatUpdateSchema,ChatTemplateRoutineScheduleDTOSchema,ChatTemplateRoutineDTOSchema,ChatTemplateDTOSchema,ChatTemplateListDTOSchema,ProjectChatStateSchema,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_chat_portrait();init_create_dto();init_response();init_chat_routine_dto();init_project_dto();ChatMessageListDTOSchema=z53.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z53.object({items:z53.array(ProjectMessagePublicDTOSchema),nextCursor:z53.string().nullable()}),ChatLiveTurnDTOSchema=z53.object({invocationId:z53.string(),step:z53.enum(["preparing","working","compacting","merging"]),startedAt:z53.string(),continuesInvocationId:z53.string().nullable().optional()}),ChatLiveTurnStateDTOSchema=z53.object({threadId:z53.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatMessageAuthorDTOSchema=z53.object({kind:z53.enum(["person","agent","routine","system"]),id:z53.string().nullable()}),ChatThreadMessageDTOSchema=z53.object({id:z53.string(),role:z53.enum(["user","assistant"]),parts:z53.array(z53.unknown()),metadata:z53.record(z53.string(),z53.unknown()).nullable(),versionId:z53.string().nullable().optional(),createdAt:z53.date().transform(value=>value.toISOString()),providerMessageId:z53.string().nullable().optional(),author:ChatMessageAuthorDTOSchema,invocationId:z53.string().nullable().optional(),invocationStatus:z53.string().nullable().optional(),invocationTerminalReason:z53.string().nullable().optional()}),ChatQueuedMessageDTOSchema=z53.object({id:z53.string(),parts:z53.array(z53.unknown()),metadata:z53.record(z53.string(),z53.unknown()).nullable(),providerMessageId:z53.string().nullable().optional(),author:ChatMessageAuthorDTOSchema,failed:z53.boolean(),queuedAt:z53.date().transform(value=>value.toISOString())}),ChatAttentionDTOSchema=z53.object({type:z53.literal("merge_conflict"),merge:z53.object({mergeId:z53.string().uuid(),projectId:z53.string(),fromBranch:z53.string(),toBranch:z53.string()}),publishAfterMerge:z53.boolean()}),ChatThreadMessagesPageDTOSchema=z53.object({threadId:z53.string().nullable(),title:z53.string().nullable(),messages:z53.array(ChatThreadMessageDTOSchema),nextCursor:z53.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional(),queue:z53.array(ChatQueuedMessageDTOSchema).optional(),queuePaused:z53.boolean().optional(),queueWaitUntil:z53.string().nullable().optional()}),ChatReplayOutcomeDTOSchema=z53.object({kind:z53.literal("replay"),threadId:z53.string(),userMessageId:z53.string()}),ChatQueuedOutcomeDTOSchema=z53.object({kind:z53.literal("queued"),threadId:z53.string(),userMessageId:z53.string(),blockingRootId:z53.string().optional()}),ChatBusyOutcomeDTOSchema=z53.object({kind:z53.literal("busy"),threadId:z53.string(),userMessageId:z53.string(),blockingRootId:z53.string().optional()}),ChatRefusedOutcomeDTOSchema=z53.object({kind:z53.literal("refused"),threadId:z53.string(),userMessageId:z53.string(),refusedInvocationId:z53.string(),terminalReason:z53.string()}),ChatNonStreamingOutcomeDTOSchema=z53.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ProjectChatKindSchema=z53.enum(["chat","agent","routine"]),ProjectChatCreatableKindSchema=z53.enum(["chat","agent"]),ProjectChatRoutinesDTOSchema=z53.object({quietRuns:z53.number().int().nonnegative(),since:z53.string().nullable(),lastOutcome:ChatRoutineRunOutcomeSchema.nullable(),lastRunAt:z53.string().nullable(),nextRunAt:z53.string().nullable()}),ProjectChatDescriptionSchema=z53.string().trim().max(2e3),ProjectChatDTOSchema=z53.object({id:z53.string().uuid(),kind:ProjectChatKindSchema,title:z53.string().nullable(),description:z53.string().nullable(),template:z53.string().nullable(),parentThreadId:z53.string().uuid().nullable(),routines:ProjectChatRoutinesDTOSchema.nullable(),createdAt:z53.string(),lastMessageAt:z53.string().nullable(),preview:z53.string().nullable(),running:z53.boolean(),awaitingAnswer:z53.boolean(),unread:z53.boolean(),pinned:z53.boolean(),archived:z53.boolean(),muted:z53.boolean(),portrait:ChatPortraitSchema.nullable()}),ProjectChatListDTOSchema=z53.object({chats:z53.array(ProjectChatDTOSchema)}),ProjectChatCreatedDTOSchema=z53.object({id:z53.string().uuid()}),ProjectChatTitleSchema=z53.string().trim().min(1).max(120),ProjectChatCreateSchema=z53.object({id:z53.string().uuid(),portrait:ChatPortraitSchema,kind:ProjectChatCreatableKindSchema,title:ProjectChatTitleSchema,description:ProjectChatDescriptionSchema,template:z53.string().min(1).max(64),timezone:ChatRoutineTimezoneSchema}).partial().refine(create=>create.template===void 0||create.kind===void 0&&create.title===void 0&&create.description===void 0,"A template brings its own kind, title and description"),ProjectChatUpdateSchema=z53.object({title:ProjectChatTitleSchema,description:ProjectChatDescriptionSchema,portrait:ChatPortraitSchema}).partial().refine(update=>update.title!==void 0||update.description!==void 0||update.portrait!==void 0,"Set a title, a description or a portrait"),ChatTemplateRoutineScheduleDTOSchema=z53.object({cron:z53.string()}),ChatTemplateRoutineDTOSchema=z53.object({name:z53.string(),instructions:z53.string(),schedule:ChatTemplateRoutineScheduleDTOSchema.nullable()}),ChatTemplateDTOSchema=z53.object({id:z53.string(),name:z53.string(),summary:z53.string(),description:z53.string(),portrait:ChatPortraitSchema,routines:z53.array(ChatTemplateRoutineDTOSchema)}),ChatTemplateListDTOSchema=z53.object({templates:z53.array(ChatTemplateDTOSchema)}),ProjectChatStateSchema=z53.object({read:z53.boolean(),pinned:z53.boolean(),archived:z53.boolean(),muted:z53.boolean()}).partial().refine(state=>Object.keys(state).length>0,"Set at least one of read, pinned, archived or muted"),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema)}});import{z as z54}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=z54.object({url:z54.string().url(),key:z54.string(),size:z54.number(),contentType:z54.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z55}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=z55.object({canAccess:z55.boolean(),permissions:z55.record(z55.string(),z55.boolean()),role:z55.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z56}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:z56.string().trim().default(""),sort:z56.enum(["recent","name","relevance"]).default("recent"),category:z56.string().optional()})}});import{z as z57}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=z57.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z57.enum(["fimo","external"]),PaymentStatusSchema=z57.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z57.object({id:z57.string().uuid(),domain:z57.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z57.boolean(),price:z57.number().int().nullable(),renewalPrice:z57.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z57.string().nullable(),failureReason:z57.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z57.object({domain:z57.string(),available:z57.boolean(),premium:z57.boolean(),price:z57.number().nullable(),renewalPrice:z57.number().nullable(),purchaseType:z57.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z57.object({domain:z57.string(),price:z57.number().nullable(),renewalPrice:z57.number().nullable(),premium:z57.boolean(),allowedYears:z57.array(z57.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z57.object({firstName:z57.string().max(100),lastName:z57.string().max(100),companyName:z57.string().max(100).optional(),address1:z57.string().max(255),address2:z57.string().max(255).optional(),city:z57.string().max(100),state:z57.string().max(100),zip:z57.string().max(20),country:z57.string().max(2),phone:z57.string().max(30),email:z57.union([z57.string().email().max(255),z57.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z57.object({firstName:z57.string().min(1).max(100),lastName:z57.string().min(1).max(100),companyName:z57.string().max(100).optional(),address1:z57.string().min(1).max(255),address2:z57.string().max(255).optional(),city:z57.string().min(1).max(100),state:z57.string().min(1).max(100),zip:z57.string().min(1).max(20),country:z57.string().min(1).max(2),phone:z57.string().min(1).max(30),email:z57.string().email().max(255)}),SearchDomainsRequestSchema=z57.object({keyword:z57.string().min(1).max(100),tldFilter:z57.array(z57.string()).optional()}),CheckAvailabilityRequestSchema=z57.object({domains:z57.array(z57.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=z57.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z57.object({domain:DomainNameSchema,years:z57.number().int().min(1).max(10).optional().default(3),autoRenew:z57.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z57.object({autoRenew:z57.boolean().optional()}),RenewDomainRequestSchema=z57.object({years:z57.number().int().min(1).max(10).optional().default(1),autoRenew:z57.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z57.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z57.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z57.object({verified:z57.boolean(),email:z57.string().nullable(),verifyBy:z57.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z58}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=z58.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=z58.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=z58.object({txtName:z58.string().nullable().optional(),txtValue:z58.string().nullable().optional(),httpUrl:z58.string().nullable().optional(),httpBody:z58.string().nullable().optional(),cname:z58.string().nullable().optional(),cnameTarget:z58.string().nullable().optional()}),SSLValidationErrorSchema=z58.object({message:z58.string()}),OwnershipVerificationSchema=z58.object({type:z58.string(),name:z58.string(),value:z58.string()}),ProjectDomainSSLDTOSchema=z58.object({status:z58.string(),method:z58.string().nullable(),type:z58.string().nullable(),validationRecords:z58.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z58.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z58.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z58.enum(["subdomain","apex"]),RedirectConfigSchema=z58.object({type:z58.enum(["apex_to_www","www_to_apex"]),linkedDomainId:z58.string()}).nullable().optional(),ProjectDomainDTOSchema=z58.object({id:z58.string(),hostname:z58.string(),status:z58.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z58.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z58.string(),scdCnameTarget:z58.string().optional(),apexTargets:z58.array(z58.string()),dnsAutoConfigured:z58.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z58.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z58.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z58.object({hostname:z58.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:z58.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z58.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z58.object({available:z58.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z58.object({success:z58.boolean(),hostname:z58.string()}))}});import{z as z59}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=z59.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z59.object({available:z59.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z59.object({slug:z59.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z59.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z59.object({subdomain:z59.string(),subdomainUpdatedAt:z59.coerce.date()})),SubdomainSuggestionsQuerySchema=z59.object({base:z59.string().max(100).optional(),max:z59.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z59.object({suggestions:z59.array(z59.string())}))}});import{z as z60}from"zod";var PROJECT_TRANSFER_BLOCKER_CODES,ProjectTransferBlockerCodeSchema,ProjectTransferBlockerDTO,TransferProjectRequestSchema,ProjectTransferResultDTO,init_project_transfer_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-transfer.dto.js"(){"use strict";init_create_dto();PROJECT_TRANSFER_BLOCKER_CODES=["same_organization","concurrent_transfer","agent_work_in_flight","unsettled_agent_holds","unsettled_usage_ledger","project_integrations_present","source_registered_domain"],ProjectTransferBlockerCodeSchema=z60.enum(PROJECT_TRANSFER_BLOCKER_CODES),ProjectTransferBlockerDTO=createDTO(z60.object({code:ProjectTransferBlockerCodeSchema,message:z60.string(),count:z60.number().int().nonnegative().optional()})),TransferProjectRequestSchema=z60.object({targetOrganizationId:z60.string().min(1)}),ProjectTransferResultDTO=createDTO(z60.object({projectId:z60.string(),sourceOrganizationId:z60.string(),targetOrganizationId:z60.string(),movedThreads:z60.number().int().nonnegative(),revokedInvites:z60.number().int().nonnegative(),revokedGrants:z60.number().int().nonnegative(),preservedGrants:z60.number().int().nonnegative(),warnings:z60.array(z60.string())}))}});import{z as z61}from"zod";var PROJECT_TOKEN_PREFIX,MB2,UNCLAIMED_PLAN,UnclaimedLockedFeatureSchema,UNCLAIMED_CLAIM_STATES,UnclaimedClaimStateSchema,UNCLAIMED_PROJECT_ERROR_CODES,UnclaimedProjectErrorCodeSchema,ProvisionUnclaimedProjectRequestSchema,UnclaimedProjectLimitsSchema,UnclaimedProjectClaimSchema,ProvisionUnclaimedProjectResponseDTO,UnclaimedClaimStatusDTO,UnclaimedClaimSecretSchema,UnclaimedClaimStatusRequestSchema,UnclaimedClaimStatesRequestSchema,UnclaimedClaimStatesResponseDTO,ClaimUnclaimedProjectRequestSchema,ClaimUnclaimedProjectResultDTO,ProjectTokenSelfDTO,init_unclaimed_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unclaimed-project.dto.js"(){"use strict";init_create_dto();init_project_dto();PROJECT_TOKEN_PREFIX="fimo_pt_",MB2=1e6,UNCLAIMED_PLAN={ttlHours:72,tokenTtlAfterClaimHours:24,media:{totalBytes:50*MB2,fileBytes:5*MB2,maxFiles:100,mimeTypes:["image/jpeg","image/png","image/webp","image/avif","image/gif"]},database:{storageBytes:100*MB2,computeSeconds:600*60,maxComputeUnits:.5},locked:{publish:"Publishing",subdomain:"A fimo.site address",custom_domains:"Custom domains",branches:"Extra Branches",environments:"Extra environments",asset_generation:"Generating images and videos",integrations:"Connecting integrations",invites:"Inviting people",schedules:"Schedules",agents:"Fimo agents",ai_credits:"AI features"}},UnclaimedLockedFeatureSchema=z61.enum(Object.keys(UNCLAIMED_PLAN.locked)),UNCLAIMED_CLAIM_STATES=["claimable","claimed","expired"],UnclaimedClaimStateSchema=z61.enum(UNCLAIMED_CLAIM_STATES),UNCLAIMED_PROJECT_ERROR_CODES=["project_unclaimed","unclaimed_limit_reached","claim_not_claimable","claim_project_limit_reached","claim_target_organization_not_found","claim_target_organization_forbidden","claim_target_subscription_inactive","claim_blocked","project_token_required","unclaimed_media_limit"],UnclaimedProjectErrorCodeSchema=z61.enum(UNCLAIMED_PROJECT_ERROR_CODES),ProvisionUnclaimedProjectRequestSchema=z61.object({displayName:z61.string().trim().min(1).max(80),machineId:z61.string().trim().min(1).max(128).optional(),cliVersion:z61.string().trim().max(64).optional()}),UnclaimedProjectLimitsSchema=z61.object({ttlHours:z61.number().int().positive(),lockedFeatures:z61.array(UnclaimedLockedFeatureSchema),media:z61.object({totalBytes:z61.number().int().nonnegative(),fileBytes:z61.number().int().positive(),maxFiles:z61.number().int().nonnegative(),mimeTypes:z61.array(z61.string())}),database:z61.object({storageBytes:z61.number().int().positive(),computeSeconds:z61.number().int().positive(),maxComputeUnits:z61.number().positive()})}),UnclaimedProjectClaimSchema=z61.object({url:z61.string().url(),expiresAt:z61.coerce.date()}),ProvisionUnclaimedProjectResponseDTO=createDTO(z61.object({project:ProjectDTOSchema,token:z61.string(),claim:UnclaimedProjectClaimSchema,limits:UnclaimedProjectLimitsSchema})),UnclaimedClaimStatusDTO=createDTO(z61.object({state:UnclaimedClaimStateSchema,displayName:z61.string().nullable(),expiresAt:z61.coerce.date().nullable(),projectId:z61.string().nullable()})),UnclaimedClaimSecretSchema=z61.string().min(1).max(256),UnclaimedClaimStatusRequestSchema=z61.object({secret:UnclaimedClaimSecretSchema}),UnclaimedClaimStatesRequestSchema=z61.object({secrets:z61.array(UnclaimedClaimSecretSchema).min(1).max(20)}),UnclaimedClaimStatesResponseDTO=createDTO(z61.object({claims:z61.array(z61.object({state:UnclaimedClaimStateSchema,expiresAt:z61.coerce.date().nullable()}))})),ClaimUnclaimedProjectRequestSchema=z61.object({secret:UnclaimedClaimSecretSchema,organizationId:z61.string().min(1)}),ClaimUnclaimedProjectResultDTO=createDTO(z61.object({projectId:z61.string(),organizationId:z61.string()})),ProjectTokenSelfDTO=createDTO(z61.object({kind:z61.literal("project_token"),projectId:z61.string(),projectName:z61.string(),displayName:z61.string().nullable(),organizationId:z61.string().nullable(),organizationName:z61.string().nullable(),claimState:UnclaimedClaimStateSchema,expiresAt:z61.coerce.date().nullable(),tokenExpiresAt:z61.coerce.date().nullable()}))}});import{z as z62}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=z62.object({translated:z62.number().int().nonnegative(),total:z62.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z62.object({locale:z62.string(),isDefault:z62.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z62.object({defaultLocale:z62.string(),locales:z62.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z62.object({locale:z62.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z62.object({locale:z62.string().min(1).max(40)}),ProjectLocaleMutationSchema=z62.object({locale:z62.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z62.object({locale:z62.string(),entriesDeleted:z62.number().int().nonnegative(),labelsDeleted:z62.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z63}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=z63.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z63.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=z63.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z63.number(),credits:z63.number().optional(),billingMode:z63.enum(["fimo-credits","provider-account"]).optional(),confidence:z63.enum(["exact","estimated","metered"]),basis:z63.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z64}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=z64.object({options:z64.record(z64.string(),z64.unknown()),name:z64.string().optional(),parentId:z64.string().nullable().optional(),altText:z64.string().optional(),caption:z64.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z64.string().min(1).optional(),model:z64.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=z64.object({jobId:z64.string(),status:z64.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z64.string().nullable().optional(),credits:z64.number().optional(),costUsd:z64.number().optional(),billingMode:z64.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z64.object({error:z64.string(),code:z64.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:z64.array(GenerationTaskIdSchema).optional(),availableModels:z64.array(z64.string()).optional(),issues:z64.array(z64.unknown()).optional()})}});import{z as z65}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=z65.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z65.object({name:z65.string(),key:z65.string(),description:z65.string(),type:FlagTypeSchema,required:z65.boolean(),defaultValue:z65.unknown().optional(),enumValues:z65.array(z65.string()).optional(),isArray:z65.boolean()}),AssetModelPriceSchema=z65.object({unitPrice:z65.number(),unit:z65.string(),confidence:z65.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z65.object({id:z65.string(),shortName:z65.string(),provider:z65.string(),source:z65.string(),modality:z65.enum(["image","video","audio"]),tags:z65.array(z65.string()),displayName:z65.string(),description:z65.string(),flags:z65.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z65.object({model:z65.string(),costUsd:z65.number(),credits:z65.number(),billingMode:z65.enum(["fimo-credits","provider-account"]),confidence:z65.enum(["exact","estimated","metered"]),basis:z65.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z66}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=z66.object({tourId:z66.string(),version:z66.string(),status:z66.string(),completedAt:z66.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z66.array(UserTourDTOSchema))}});import{z as z67}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=z67.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z67.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z67.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z67.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z67.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z67.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z67.enum(["user","agent","system"]),SupportReportTagSchema=z67.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z67.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z67.object({organization:z67.object({id:z67.string().trim().min(1).max(255),name:z67.string().trim().max(240).optional()}),project:z67.object({id:z67.uuid(),name:z67.string().trim().max(240).optional(),createdAt:z67.coerce.date().optional()}).optional(),environment:z67.string().trim().max(255).optional(),clientVersion:z67.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z67.object({message:z67.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("cli"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z67.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z67.string().trim().max(200).optional(),limit:z67.coerce.number().int().min(1).max(100).default(50),offset:z67.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z67.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z67.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z67.uuid().nullable().optional(),note:z67.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=z67.object({message:z67.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z67.object({kind:SupportReportLinkKindSchema,label:z67.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z67.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z67.object({kind:SupportReportActorKindSchema,id:z67.string().nullable(),name:z67.string().nullable()}),SupportReportLinkDTOSchema=z67.object({id:z67.uuid(),kind:SupportReportLinkKindSchema,label:z67.string(),url:SupportReportHttpUrlSchema,externalId:z67.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z67.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z67.object({id:z67.uuid(),kind:SupportReportEventKindSchema,body:z67.string().nullable(),metadata:z67.record(z67.string(),z67.unknown()),actor:SupportReportActorDTOSchema,createdAt:z67.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z67.object({id:z67.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z67.array(z67.string()),source:SupportReportSourceSchema,message:z67.string(),reporter:z67.object({id:z67.string().nullable(),name:z67.string().nullable(),email:z67.string().nullable()}),organization:z67.object({id:z67.string().nullable(),name:z67.string()}),project:z67.object({id:z67.uuid().nullable(),name:z67.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z67.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z67.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z67.string().nullable(),deliveredAt:z67.coerce.date().nullable()}).nullable(),duplicateOfReportId:z67.uuid().nullable(),resolvedAt:z67.coerce.date().nullable(),createdAt:z67.coerce.date(),updatedAt:z67.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z67.string().nullable(),clientVersion:z67.string().nullable(),links:z67.array(SupportReportLinkDTOSchema),events:z67.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z67.object({reports:z67.array(SupportReportSummaryDTOSchema),total:z67.number().int().nonnegative(),statusCounts:z67.object({new:z67.number().int().nonnegative(),in_progress:z67.number().int().nonnegative(),waiting:z67.number().int().nonnegative(),resolved:z67.number().int().nonnegative(),duplicate:z67.number().int().nonnegative(),irrelevant:z67.number().int().nonnegative(),ignored:z67.number().int().nonnegative()}),limit:z67.number().int().positive(),offset:z67.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z67.object({id:z67.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z67.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z68}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=z68.iso.datetime({offset:!0}).pipe(z68.coerce.date()),OpsRecentChatInputSchema=z68.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z68.string().trim().min(1).max(255).optional(),limit:z68.coerce.number().int().min(1).max(200).default(100),cursor:z68.string().trim().min(1).max(2e3).optional(),slim:z68.boolean().default(!0),reason:z68.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=z68.object({id:z68.string(),threadId:z68.string(),providerMessageId:z68.string().nullable(),invocationId:z68.string().nullable(),env:z68.string().nullable(),role:z68.string(),parts:z68.array(z68.record(z68.string(),z68.unknown())),metadata:z68.object({status:z68.string().optional(),traceUrl:z68.string().optional(),externalFileChanges:z68.array(z68.unknown()).optional()}),stats:z68.object({toolCount:z68.number().int().nonnegative(),failedToolCount:z68.number().int().nonnegative()}),createdAt:z68.iso.datetime({offset:!0}),project:z68.object({id:z68.string(),name:z68.string(),displayName:z68.string().nullable(),organizationId:z68.string().nullable()})}),OpsRecentChatResponseSchema=z68.object({target:z68.object({backendProfile:OpsBackendProfileSchema,projectEnv:z68.string().nullable()}),window:z68.object({from:z68.iso.datetime({offset:!0}),to:z68.iso.datetime({offset:!0})}),messages:z68.object({items:z68.array(OpsRecentChatMessageSchema),nextCursor:z68.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z69}from"zod";var OpsSentryIssueResolutionResponseSchema,OpsSentryIssueResolutionResponseDTO,OpsSentryIssueResolutionErrorResponseSchema,OpsSentryIssueResolutionErrorResponseDTO,init_ops_sentry_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-sentry.dto.js"(){"use strict";init_ops();init_create_dto();OpsSentryIssueResolutionResponseSchema=z69.object({backendProfile:OpsBackendProfileSchema,provider:z69.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z69.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z69.object({backendProfile:OpsBackendProfileSchema,provider:z69.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z69.literal(!1),reason:z69.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z70}from"zod";var OpsProjectPackageManagerSummarySchema,OpsProjectPackageManagerSchema,OpsProjectPackageManagerDTO,init_ops_project_files_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-project-files.dto.js"(){"use strict";init_ops();init_create_dto();OpsProjectPackageManagerSummarySchema=z70.object({packageManager:z70.string().trim().min(1).max(200).nullable(),trackedLockfiles:z70.array(z70.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z70.string().trim().min(1)}),OpsProjectPackageManagerSchema=z70.object({target:z70.object({backendProfile:OpsBackendProfileSchema,projectId:z70.uuid(),projectEnv:z70.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z71}from"zod";function uniqueRoutineNames(spec){let names=(spec.routines??[]).map(routine=>routine.name);return new Set(names).size===names.length}var OpsAgentChatRoutineSpecSchema,OpsAgentChatAgentSpecSchema,OpsAgentChatSpecObjectSchema,UNIQUE_ROUTINE_NAMES,OpsAgentChatSpecSchema,OpsAgentChatCreateInputSchema,OpsAgentChatOutcomeSchema,OpsAgentChatRoutineResultSchema,OpsAgentChatCreateResultSchema,init_ops_agent_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-agent-chat.dto.js"(){"use strict";init_ops();init_chat_routine_dto();OpsAgentChatRoutineSpecSchema=ChatRoutineCreateSchema.extend({schedule:ChatRoutineScheduleSchema.nullable(),paused:z71.boolean().optional()}).strict(),OpsAgentChatAgentSpecSchema=z71.union([z71.object({name:z71.string().trim().min(1).max(120),description:z71.string().trim().min(1).max(2e3)}).strict(),z71.object({template:z71.string().trim().min(1).max(64)}).strict()]),OpsAgentChatSpecObjectSchema=z71.object({agent:OpsAgentChatAgentSpecSchema,routines:z71.array(OpsAgentChatRoutineSpecSchema).max(50).optional()}).strict();__name(uniqueRoutineNames,"uniqueRoutineNames");UNIQUE_ROUTINE_NAMES={path:["routines"],message:"Routine names must be unique within one agent"},OpsAgentChatSpecSchema=OpsAgentChatSpecObjectSchema.refine(uniqueRoutineNames,UNIQUE_ROUTINE_NAMES),OpsAgentChatCreateInputSchema=OpsAgentChatSpecObjectSchema.extend({reason:z71.string().trim().min(1).max(1e3),dryRun:z71.boolean().optional()}).refine(uniqueRoutineNames,UNIQUE_ROUTINE_NAMES),OpsAgentChatOutcomeSchema=z71.enum(["created","existing","would_create"]),OpsAgentChatRoutineResultSchema=z71.object({id:z71.string().uuid().nullable(),name:z71.string(),schedule:ChatRoutineScheduleSchema.nullable(),nextRunAt:z71.string().nullable(),paused:z71.boolean(),outcome:z71.enum(["created","would_create"]),source:z71.enum(["spec","template"])}),OpsAgentChatCreateResultSchema=z71.object({target:z71.object({backendProfile:OpsBackendProfileSchema,projectId:z71.string().uuid()}),dryRun:z71.boolean(),applied:z71.boolean(),createdBy:z71.object({userId:z71.string()}),agent:z71.object({id:z71.string().uuid().nullable(),title:z71.string(),template:z71.string().nullable(),outcome:OpsAgentChatOutcomeSchema}),routines:z71.array(OpsAgentChatRoutineResultSchema),skipped:z71.array(z71.object({name:z71.string(),reason:z71.literal("routine_exists")})),refused:z71.array(z71.object({name:z71.string(),reason:ChatRoutineRefusalReasonSchema}))})}});import{z as z72}from"zod";var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEnvironmentSelectorSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,DomainCreatedWebhookEventDataSchema,DomainDeletedWebhookEventDataSchema,LabelChangedWebhookEventDataSchema,LocaleCreatedWebhookEventDataSchema,LocaleDefaultChangedWebhookEventDataSchema,LocaleDeletedWebhookEventDataSchema,EnvironmentCreatedWebhookEventDataSchema,EnvironmentDeletedWebhookEventDataSchema,EnvironmentMergedWebhookEventDataSchema,BranchRestoredWebhookEventDataSchema,WebhookEventFamilySchema,WebhookDestinationKindSchema,WebhookHeaderValueInputSchema,WebhookHeaderInputSchema,WebhookHeaderDTOSchema,WebhookFilterSchema,JsonValueSchema,CreateProjectWebhookRequestSchema,UpdateProjectWebhookRequestSchema,TestProjectWebhookRequestSchema,WebhookDeliveryStatusSchema,ProjectWebhookDTOSchema,ProjectWebhookDTO,WebhookDeliveryDTOSchema,WebhookDeliveryDTO,WebhookDeliveriesPageSchema,WebhookDeliveryAttemptDTOSchema,WebhookDeliveryAttemptDTO,ProjectWebhookResponseSchema,ProjectWebhooksListResponseSchema,WebhookDeliveriesListResponseSchema,WebhookDeliveryAttemptsListResponseSchema,init_webhook_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/webhook.dto.js"(){"use strict";init_common();init_env();init_environment();init_create_dto();init_response();init_env_status_dto();init_project_domain_dto();WEBHOOK_EVENT_TYPES=["entry.changed","form.submitted","publish.started","publish.succeeded","publish.failed","publish.unpublished","analytics.report_ready","media.uploaded","media.updated","media.deleted","domain.created","domain.deleted","label.changed","locale.created","locale.default_changed","locale.deleted","environment.created","environment.deleted","environment.merged","branch.restored"],WebhookEventTypeSchema=z72.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z72.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z72.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z72.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z72.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),EntryChangedWebhookEventDataSchema=z72.object({reason:WebhookEntryChangeReasonSchema,operationId:z72.string().optional(),batch:z72.object({index:z72.number().int().positive(),total:z72.number().int().positive()}).optional(),changes:z72.array(z72.object({action:WebhookEntryChangeActionSchema,contentType:z72.string(),id:z72.string(),documentId:z72.string(),locale:z72.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z72.object({form:z72.object({id:z72.string(),label:z72.string()}),submission:z72.object({id:z72.string(),data:z72.record(z72.string(),z72.unknown()),submittedAt:z72.string()})}),PublishStartedWebhookEventDataSchema=z72.object({publication:z72.object({status:z72.literal("publishing"),startedAt:z72.string()})}),PublishSucceededWebhookEventDataSchema=z72.object({publication:z72.object({status:z72.literal("published"),url:z72.string(),publishedAt:z72.string(),firstPublish:z72.boolean()})}),PublishFailedWebhookEventDataSchema=z72.object({publication:z72.object({status:z72.literal("failed"),reason:z72.string()})}),PublishUnpublishedWebhookEventDataSchema=z72.object({publication:z72.object({previousUrl:z72.string(),unpublishedAt:z72.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z72.object({report:z72.object({weekStart:z72.string(),weekEnd:z72.string(),pageviews:z72.number(),visitors:z72.number(),previousPageviews:z72.number(),previousVisitors:z72.number()})}),MediaAssetWebhookEventDataSchema=z72.object({id:z72.string().nullable(),name:z72.string().nullable(),type:z72.string(),mimeType:z72.string().nullable(),fileSize:z72.number().nullable()}),MediaUploadedWebhookEventDataSchema=z72.object({asset:MediaAssetWebhookEventDataSchema,operation:z72.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z72.object({asset:MediaAssetWebhookEventDataSchema,operation:z72.literal("updated")}),MediaDeletedWebhookEventDataSchema=z72.object({asset:MediaAssetWebhookEventDataSchema,operation:z72.literal("deleted")}),DomainCreatedWebhookEventDataSchema=z72.object({domain:z72.object({id:z72.string(),hostname:z72.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z72.object({domain:z72.object({id:z72.string(),hostname:z72.string()})}),LabelChangedWebhookEventDataSchema=z72.object({changes:z72.array(z72.object({action:z72.enum(["created","updated","deleted"]),key:z72.string(),locale:z72.string(),value:z72.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z72.object({locale:z72.object({code:z72.string(),isDefault:z72.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z72.object({locale:z72.object({code:z72.string(),previousCode:z72.string()})}),LocaleDeletedWebhookEventDataSchema=z72.object({locale:z72.object({code:z72.string(),entriesDeleted:z72.number().int().nonnegative(),labelsDeleted:z72.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z72.object({environment:z72.object({name:BranchSchema,parent:BranchSchema})}),EnvironmentDeletedWebhookEventDataSchema=z72.object({environment:z72.object({name:BranchSchema})}),EnvironmentMergedWebhookEventDataSchema=z72.object({merge:z72.object({id:z72.string(),from:BranchSchema,to:BranchSchema,applied:z72.array(z72.object({surface:SurfaceNameSchema,count:z72.number().int().nonnegative()}))})}),BranchRestoredWebhookEventDataSchema=z72.object({branch:z72.object({name:BranchSchema}),version:z72.object({versionId:z72.uuid(),name:z72.string()})}),WebhookEventFamilySchema=z72.enum(["entries","forms","publish","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z72.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z72.discriminatedUnion("source",[z72.object({source:z72.literal("literal"),value:z72.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z72.object({source:z72.literal("secret"),key:z72.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z72.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z72.object({name:z72.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z72.object({name:z72.string(),source:z72.enum(["literal","secret"]),secretKey:z72.string().nullable(),secretPrefix:z72.string().nullable(),configured:z72.literal(!0)}),WebhookFilterSchema=z72.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z72.string().min(1).max(255).optional(),mediaType:z72.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z72.string().min(1).max(255).optional(),locale:z72.string().min(1).max(120).optional()}),JsonValueSchema=z72.lazy(()=>z72.union([z72.string(),z72.number(),z72.boolean(),z72.null(),z72.array(JsonValueSchema),z72.record(z72.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z72.object({name:z72.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z72.url(),enabled:z72.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z72.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z72.boolean().optional().default(!0)}),UpdateProjectWebhookRequestSchema=z72.object({name:z72.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z72.url().optional(),enabled:z72.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z72.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z72.boolean().optional()}),TestProjectWebhookRequestSchema=z72.object({eventType:WebhookEventTypeSchema.optional(),data:z72.record(z72.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z72.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z72.uuid(),name:z72.string(),eventType:WebhookEventTypeSchema,enabled:z72.boolean(),destination:z72.object({host:z72.string(),maskedUrl:z72.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z72.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z72.boolean(),lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z72.coerce.date().nullable(),deliveryStats24h:z72.object({succeeded:z72.number().int().nonnegative(),failed:z72.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z72.uuid(),projectId:z72.uuid(),env:BranchSchema,environment:EnvironmentKeySchema,branch:BranchSchema,eventId:z72.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z72.number().int().positive(),test:z72.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z72.number().int().nonnegative(),responseStatus:z72.number().int().nullable(),lastErrorCode:z72.string().nullable(),lastErrorMessage:z72.string().nullable(),payloadAvailable:z72.boolean(),destination:z72.object({host:z72.string(),maskedUrl:z72.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z72.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z72.string().nullable(),qstashMessageId:z72.string().nullable(),deliveredAt:z72.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z72.object({items:z72.array(WebhookDeliveryDTOSchema),pagination:z72.object({page:z72.number().int().positive(),limit:z72.number().int().positive(),total:z72.number().int().nonnegative(),totalPages:z72.number().int().positive(),hasMore:z72.boolean()}),stats:z72.object({total:z72.number().int().nonnegative(),succeeded:z72.number().int().nonnegative(),failed:z72.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z72.object({id:z72.uuid(),deliveryId:z72.uuid(),attempt:z72.number().int().positive(),status:z72.enum(["delivering","succeeded","failed"]),responseStatus:z72.number().int().nullable(),durationMs:z72.number().int().nonnegative(),responseExcerpt:z72.string().nullable(),errorCode:z72.string().nullable(),errorMessage:z72.string().nullable(),createdAt:z72.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z72.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z72.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z73}from"zod";var PreviewFeatureDTOSchema,PreviewFeatureDTO,init_preview_feature_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/preview-feature.dto.js"(){"use strict";init_create_dto();PreviewFeatureDTOSchema=z73.object({key:z73.literal("fimo-2"),enabled:z73.boolean(),dismissed:z73.boolean().default(!1),interacted:z73.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z74}from"zod";var SiteOnboardingStageSchema,SiteScanStatusSchema,SiteCloneStatusSchema,SiteRefusalCodeSchema,SiteRefusalSchema,SiteCheckGroupSchema,SiteScoreSchema,SITE_CHECKS,SiteCheckIdSchema,SiteCheckStatusSchema,SiteCheckEvidenceSchema,SiteCheckResultSchema,SiteReportGroupSchema,SiteReportSchema,SitePriceTierSchema,SiteTypeSchema,SiteTermsCategorySchema,SITE_QUESTION,SITE_QUESTIONS,SiteUnderstandingSchema,SiteSuggestionSchema,SiteInterviewSuggestionsSchema,SiteInterviewAnswerSchema,SiteInterviewSchema,AnswerSiteInterviewRequestSchema,SiteFixesReportSchema,SiteOnboardingResultSchema,StartSiteOnboardingRequestSchema,StartSiteOnboardingResponseSchema,SiteOnboardingRefusedResponseSchema,SiteOnboardingStateSchema,SiteOnboardingStateDTO,SiteOnboardingStateResponseSchema,RetrySiteOnboardingRequestSchema,SiteOnboardingOutcomeSchema,AdminSiteOnboardingsQuerySchema,AdminSiteOnboardingDTOSchema,AdminSiteOnboardingDTO,AdminSiteOnboardingsResponseSchema,AdminSiteOnboardingStatsSchema,AdminSiteOnboardingStatsResponseSchema,AdminSiteOnboardingDetailSchema,AdminSiteOnboardingDetailDTO,AdminSiteOnboardingDetailResponseSchema,init_site_onboarding_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/site-onboarding.dto.js"(){"use strict";init_create_dto();init_response();SiteOnboardingStageSchema=z74.enum(["scanning","interviewing","reporting","open","expired","refused"]),SiteScanStatusSchema=z74.enum(["running","done","failed"]),SiteCloneStatusSchema=z74.enum(["not_started","running","paused","finished","failed"]),SiteRefusalCodeSchema=z74.enum(["invalid","private","not_found","tls","unreachable","redirect","error_page","bot_wall"]),SiteRefusalSchema=z74.object({code:SiteRefusalCodeSchema,suggestedUrl:z74.string().nullable()}),SiteCheckGroupSchema=z74.enum(["discovery","indexing","ai_crawlers","rendering","metadata","content","speed"]),SiteScoreSchema=z74.enum(["seo","geo"]),SITE_CHECKS=[{id:"robots_txt",group:"discovery",scores:["seo","geo"],weight:2},{id:"sitemap",group:"discovery",scores:["seo","geo"],weight:2},{id:"sitemap_lastmod",group:"discovery",scores:["seo","geo"],weight:1},{id:"broken_links",group:"discovery",scores:["seo"],weight:2},{id:"internal_nofollow",group:"discovery",scores:["seo"],weight:1},{id:"blocked_from_crawling",group:"discovery",scores:["seo","geo"],weight:3,cap:{seo:20,geo:20}},{id:"status_4xx",group:"indexing",scores:["seo","geo"],weight:2,cap:{seo:10,geo:10}},{id:"status_5xx",group:"indexing",scores:["seo","geo"],weight:3,cap:{seo:10,geo:10}},{id:"https_to_http",group:"indexing",scores:["seo"],weight:1,cap:{seo:50}},{id:"canonical",group:"indexing",scores:["seo"],weight:1},{id:"noindex",group:"indexing",scores:["seo","geo"],weight:3,cap:{seo:20,geo:20}},{id:"hreflang",group:"indexing",scores:["seo"],weight:1},{id:"missing_page",group:"indexing",scores:["seo","geo"],weight:1,cap:{seo:80,geo:80}},{id:"ai_bots_robots",group:"ai_crawlers",scores:["geo"],weight:3,cap:{geo:30}},{id:"ai_bot_access",group:"ai_crawlers",scores:["geo"],weight:2,cap:{geo:40}},{id:"llms_txt",group:"ai_crawlers",scores:["geo"],weight:1},{id:"server_rendering",group:"rendering",scores:["geo"],weight:3},{id:"semantic_html",group:"rendering",scores:["seo","geo"],weight:2},{id:"markdown_pages",group:"rendering",scores:["geo"],weight:1},{id:"markdown_alternate",group:"rendering",scores:["geo"],weight:.5},{id:"markdown_index",group:"rendering",scores:["geo"],weight:.5},{id:"meta_title",group:"metadata",scores:["seo"],weight:2},{id:"meta_description",group:"metadata",scores:["seo"],weight:2},{id:"structured_data",group:"metadata",scores:["seo","geo"],weight:2},{id:"organization_schema",group:"metadata",scores:["geo"],weight:2},{id:"entity_links",group:"metadata",scores:["geo"],weight:1},{id:"metadata_completeness",group:"metadata",scores:["seo","geo"],weight:2},{id:"trust_pages",group:"metadata",scores:["geo"],weight:2},{id:"word_count",group:"content",scores:["seo","geo"],weight:2},{id:"text_ratio",group:"content",scores:["seo"],weight:1},{id:"h1",group:"content",scores:["seo"],weight:2},{id:"image_alt",group:"content",scores:["seo","geo"],weight:1},{id:"broken_images",group:"content",scores:["seo"],weight:1},{id:"empty_link_text",group:"content",scores:["seo","geo"],weight:1},{id:"page_load",group:"speed",scores:["seo"],weight:3},{id:"unminified_assets",group:"speed",scores:["seo"],weight:1}],SiteCheckIdSchema=z74.enum(SITE_CHECKS.map(check=>check.id)),SiteCheckStatusSchema=z74.enum(["pass","partial","fail","not_scored"]),SiteCheckEvidenceSchema=z74.record(z74.string(),z74.union([z74.string(),z74.number(),z74.boolean(),z74.array(z74.string())])),SiteCheckResultSchema=z74.object({id:SiteCheckIdSchema,status:SiteCheckStatusSchema,evidence:SiteCheckEvidenceSchema}),SiteReportGroupSchema=z74.object({id:SiteCheckGroupSchema,score:z74.number().int().min(0).max(100).nullable()}),SiteReportSchema=z74.object({siteUrl:z74.string(),scannedAt:z74.coerce.date(),seoScore:z74.number().int().min(0).max(100).nullable(),geoScore:z74.number().int().min(0).max(100).nullable(),groups:z74.array(SiteReportGroupSchema),checks:z74.array(SiteCheckResultSchema),blockers:z74.array(SiteCheckIdSchema).default([])}),SitePriceTierSchema=z74.enum(["budget","standard","premium","luxury"]),SiteTypeSchema=z74.enum(["business","non_profit","portfolio","hobby","personal"]),SiteTermsCategorySchema=z74.enum(["violence","child_harm","harassment","hate","self_harm","adult","deception","scam"]),SITE_QUESTION={id:"site",kind:"confirm"},SITE_QUESTIONS={business:[SITE_QUESTION,{id:"competitors",kind:"form",inputs:[{id:"names",kind:"choices",multiple:!0,allowOther:!0,options:"competitors"}]},{id:"positioning",kind:"form",inputs:[{id:"positioning",kind:"text",max:2e3}]},{id:"priceTier",kind:"form",inputs:[{id:"priceTier",kind:"choices",multiple:!1,allowOther:!1,options:SitePriceTierSchema.options}]}],non_profit:[SITE_QUESTION,{id:"action",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!1,allowOther:!0,options:["volunteer","donate","join","next_event"]}]},{id:"searches",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!0,allowOther:!0,options:"model"}]}],portfolio:[SITE_QUESTION,{id:"work",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!0,allowOther:!0,options:"model"}]},{id:"action",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!1,allowOther:!0,options:["book_call","request_quote","email","follow"]}]}],hobby:[SITE_QUESTION,{id:"return",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!0,allowOther:!0,options:["creations","tutorials","progress","tips"]}]},{id:"tone",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!1,allowOther:!1,options:["warm","expert","playful","calm"]}]}],personal:[SITE_QUESTION,{id:"remember",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!1,allowOther:!0,options:"model"}]},{id:"action",kind:"form",inputs:[{id:"picks",kind:"choices",multiple:!1,allowOther:!0,options:["read","contact","hire","follow"]}]}]},SiteUnderstandingSchema=z74.object({name:z74.string(),summary:z74.string(),audience:z74.string(),positioning:z74.string(),priceTier:SitePriceTierSchema,homepage:z74.string()}),SiteSuggestionSchema=z74.object({label:z74.string(),url:z74.string().nullable()}),SiteInterviewSuggestionsSchema=z74.record(z74.string(),z74.record(z74.string(),z74.array(SiteSuggestionSchema))),SiteInterviewAnswerSchema=z74.record(z74.string().max(50),z74.union([z74.string().trim().max(2e3),z74.array(z74.string().trim().min(1).max(200)).max(10)])),SiteInterviewSchema=z74.object({status:z74.enum(["waiting","drafting","ready","failed"]),siteType:SiteTypeSchema.nullable(),site:SiteUnderstandingSchema.nullable(),suggestions:SiteInterviewSuggestionsSchema,answers:z74.record(z74.string(),SiteInterviewAnswerSchema)}),AnswerSiteInterviewRequestSchema=z74.object({questionId:z74.string().min(1).max(50),answer:SiteInterviewAnswerSchema}),SiteFixesReportSchema=z74.object({fixes:z74.array(z74.object({checkId:SiteCheckIdSchema,status:z74.enum(["fixed","not_fixed","not_applicable"]),note:z74.string().trim().min(1).max(300)})).min(1).max(40)}),SiteOnboardingResultSchema=z74.object({fixes:SiteFixesReportSchema.nullable(),summary:z74.string().nullable()}),StartSiteOnboardingRequestSchema=z74.object({organizationId:z74.string().min(1),url:z74.string().trim().min(1).max(2048),locale:z74.string().trim().min(2).max(16).default("en")}),StartSiteOnboardingResponseSchema=createResponseSchema(z74.object({projectId:z74.string()})),SiteOnboardingRefusedResponseSchema=z74.object({error:z74.literal("site_refused"),refusal:SiteRefusalSchema}),SiteOnboardingStateSchema=z74.object({projectId:z74.string(),siteUrl:z74.string(),stage:SiteOnboardingStageSchema,scanStatus:SiteScanStatusSchema,cloneStatus:SiteCloneStatusSchema,cloneRetryAvailable:z74.boolean(),budgetExhausted:z74.boolean(),sponsored:z74.boolean(),cloneOutOfCredits:z74.boolean(),interview:SiteInterviewSchema.nullable(),cloneThreadId:z74.string().nullable(),welcomeThreadId:z74.string().nullable(),competitors:z74.array(z74.string()),report:SiteReportSchema.nullable(),reportExpiresAt:z74.coerce.date(),openedAt:z74.coerce.date().nullable(),bannerDismissed:z74.boolean()}),SiteOnboardingStateDTO=createDTO(SiteOnboardingStateSchema),SiteOnboardingStateResponseSchema=createResponseSchema(SiteOnboardingStateSchema.nullable()),RetrySiteOnboardingRequestSchema=z74.object({task:z74.enum(["interview","scan","clone"])}),SiteOnboardingOutcomeSchema=z74.enum(["finished","rebuilding","paused","failed","scan_failed","scanning","expired","refused","not_started"]),AdminSiteOnboardingsQuerySchema=z74.object({search:z74.string().trim().max(200).optional(),organizationId:z74.string().trim().min(1).max(200).optional(),startDate:z74.coerce.date().optional(),endDate:z74.coerce.date().optional(),outcomes:z74.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z74.array(SiteOnboardingOutcomeSchema).optional()),siteTypes:z74.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z74.array(SiteTypeSchema).optional()),page:z74.coerce.number().int().min(1).default(1),pageSize:z74.coerce.number().int().min(1).max(100).default(25)}),AdminSiteOnboardingDTOSchema=z74.object({projectId:z74.string(),projectName:z74.string(),organizationId:z74.string(),organizationName:z74.string().nullable(),ownerEmail:z74.string().nullable(),ownerName:z74.string().nullable(),siteUrl:z74.string(),stage:SiteOnboardingStageSchema,scanStatus:SiteScanStatusSchema,cloneStatus:SiteCloneStatusSchema,outcome:SiteOnboardingOutcomeSchema,sponsored:z74.boolean(),cloneRetries:z74.number(),siteType:SiteTypeSchema.nullable(),refusalCategory:SiteTermsCategorySchema.nullable(),interviewAnswers:z74.number(),interviewQuestions:z74.number().nullable(),seoScore:z74.number().nullable(),geoScore:z74.number().nullable(),spentUsd:z74.number(),budgetCapUsd:z74.number(),capReached:z74.boolean(),cloneSeconds:z74.number().nullable(),createdAt:z74.coerce.date(),openedAt:z74.coerce.date().nullable()}),AdminSiteOnboardingDTO=createDTO(AdminSiteOnboardingDTOSchema),AdminSiteOnboardingsResponseSchema=createResponseSchema(z74.object({onboardings:z74.array(AdminSiteOnboardingDTOSchema),page:z74.number(),limit:z74.number(),total:z74.number(),totalPages:z74.number()})),AdminSiteOnboardingStatsSchema=z74.object({total:z74.number(),outcomes:z74.record(SiteOnboardingOutcomeSchema,z74.number()),funnel:z74.object({started:z74.number(),confirmed:z74.number(),finished:z74.number(),opened:z74.number()}),bySiteType:z74.array(z74.object({siteType:SiteTypeSchema,total:z74.number(),finished:z74.number(),opened:z74.number()})),granularity:z74.enum(["hour","day"]),series:z74.array(z74.object({at:z74.coerce.date(),outcomes:z74.record(SiteOnboardingOutcomeSchema,z74.number())})),spentUsd:z74.object({total:z74.number(),average:z74.number().nullable()}),sponsored:z74.number(),paidByOrganization:z74.object({usd:z74.number(),credits:z74.number()}),capReached:z74.number(),cloneSeconds:z74.object({median:z74.number().nullable(),average:z74.number().nullable()})}),AdminSiteOnboardingStatsResponseSchema=createResponseSchema(AdminSiteOnboardingStatsSchema),AdminSiteOnboardingDetailSchema=z74.object({onboarding:AdminSiteOnboardingDTOSchema.extend({locale:z74.string(),cloneThreadId:z74.string().nullable(),paidByOrganizationUsd:z74.number()}),interview:SiteInterviewSchema.extend({invocationIds:z74.array(z74.string())}).nullable(),knowledgeWritten:z74.string().nullable(),knowledgeNow:z74.object({content:z74.string(),updatedAt:z74.coerce.date().nullable(),updatedBy:z74.string().nullable()}),report:SiteReportSchema.nullable()}),AdminSiteOnboardingDetailDTO=createDTO(AdminSiteOnboardingDetailSchema),AdminSiteOnboardingDetailResponseSchema=createResponseSchema(AdminSiteOnboardingDetailSchema)}});import{z as z75}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=z75.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z75.object({total:z75.number(),base:z75.number(),purchases:z75.number(),awards:z75.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z75.object({id:z75.string(),name:z75.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z75.object({type:z75.string(),brand:z75.string().nullable(),last4:z75.string().nullable(),expirationDate:z75.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z75.object({currency:z75.string(),nextPaymentAmount:z75.number().nullable(),nextPaymentAt:z75.string().nullable(),billingInterval:z75.string().nullable(),totalAmount:z75.number().nullable(),discountAmount:z75.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z75.object({id:z75.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z75.string().nullable(),currentPeriodEndsAt:z75.string().nullable(),renewsAt:z75.string().nullable(),cancelAt:z75.string().nullable(),renewAutomatically:z75.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z75.object({type:z75.enum(["low_balance","critical_balance","approaching_limit"]),message:z75.string(),estimatedPromptsRemaining:z75.number().nullable(),avgCostPerPrompt:z75.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z75.object({monthlyCredits:z75.number().nullable(),usedThisPeriod:z75.number(),remainingThisPeriod:z75.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z75.object({organizationId:z75.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z75.string().nullable(),tenureDays:z75.number().int().nonnegative(),capturedAt:z75.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z75.object({hasSubscription:z75.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z75.number().nullable(),alerts:z75.array(CreditAlertDTOSchema),portalUrl:z75.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z75.object({creditCount:z75.number().int().positive(),expiresAt:z75.string().datetime().nullable().optional(),message:z75.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z75.literal("free"),amountCents:z75.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z75.literal("purchase"),amountCents:z75.number().int().positive()}),CreditTopupRequestDTOSchema=z75.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z75.object({success:z75.boolean(),transactionId:z75.string().nullable(),newBalance:z75.number(),creditCount:z75.number(),type:z75.enum(["free","purchase"]),invoiceId:z75.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z76}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=z76.object({totalCredits:z76.number(),totalCostUsd:z76.number(),totalMessages:z76.number(),avgCostPerMessage:z76.number(),periodStart:z76.string().nullable(),periodEnd:z76.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z76.object({projectId:z76.string(),projectName:z76.string(),projectDisplayName:z76.string().nullable(),credits:z76.number(),costUsd:z76.number(),messages:z76.number(),percentage:z76.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z76.object({userId:z76.string(),userName:z76.string().nullable(),userEmail:z76.string().email().nullable(),credits:z76.number(),costUsd:z76.number(),messages:z76.number(),percentage:z76.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z76.object({date:z76.string(),credits:z76.number(),costUsd:z76.number(),messages:z76.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z76.object({userId:z76.string(),userName:z76.string().nullable(),userEmail:z76.string().email().nullable(),credits:z76.number(),costUsd:z76.number(),messages:z76.number(),percentage:z76.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z76.object({projectId:z76.string(),projectName:z76.string(),projectDisplayName:z76.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z76.array(UsageByUserForProjectDTOSchema),timeline:z76.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z76.object({summary:UsageSummaryDTOSchema,byProject:z76.array(UsageByProjectDTOSchema),byUser:z76.array(UsageByUserDTOSchema),timeline:z76.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z77}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=z77.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z77.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z77.object({startDate:z77.string().optional(),endDate:z77.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z77.coerce.number().int().positive().default(1),limit:z77.coerce.number().int().positive().max(100).default(20),sortBy:z77.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z77.string().optional(),activeOnly:z77.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z77.object({totalCredits:z77.number(),totalCostUsd:z77.number(),totalMessages:z77.number(),avgCostPerMessage:z77.number(),avgCreditsPerMessage:z77.number(),periodStart:z77.string(),periodEnd:z77.string(),creditsChange:z77.number().nullable(),costChange:z77.number().nullable(),messagesChange:z77.number().nullable(),unattributedCredits:z77.number(),unattributedCostUsd:z77.number(),unattributedMessages:z77.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z77.object({date:z77.string(),credits:z77.number(),costUsd:z77.number(),messages:z77.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z77.object({organizationId:z77.string(),organizationName:z77.string(),credits:z77.number(),costUsd:z77.number(),messages:z77.number(),percentage:z77.number(),userCount:z77.number(),projectCount:z77.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z77.object({userId:z77.string(),userName:z77.string().nullable(),userEmail:z77.string().nullable(),userImage:z77.string().nullable(),organizationId:z77.string().nullable(),organizationName:z77.string().nullable(),credits:z77.number(),costUsd:z77.number(),messages:z77.number(),percentage:z77.number(),projectCount:z77.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z77.object({projectId:z77.string(),projectName:z77.string(),projectDisplayName:z77.string().nullable(),organizationId:z77.string(),organizationName:z77.string(),credits:z77.number(),costUsd:z77.number(),messages:z77.number(),percentage:z77.number(),userCount:z77.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z77.object({id:z77.string(),name:z77.string(),value:z77.number(),percentage:z77.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z77.object({day:z77.number(),hour:z77.number(),value:z77.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z77.object({summary:UsageOverviewSummaryDTOSchema,timeline:z77.array(UsageTimelinePointDTOSchema),topOrganizations:z77.array(OrganizationUsageRowDTOSchema),topUsers:z77.array(UserUsageRowDTOSchema),topProjects:z77.array(ProjectUsageRowDTOSchema),creditDistribution:z77.array(UsageDistributionItemDTOSchema),userDistribution:z77.array(UsageDistributionItemDTOSchema),heatmap:z77.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z77.object({page:z77.number(),limit:z77.number(),totalItems:z77.number(),totalPages:z77.number(),hasMore:z77.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z77.object({organizations:z77.array(OrganizationUsageRowDTOSchema),top:z77.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z77.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z77.object({users:z77.array(ExtendedUserUsageRowDTOSchema),top:z77.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z77.string(),ownerName:z77.string().nullable(),ownerEmail:z77.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z77.object({projects:z77.array(ExtendedProjectUsageRowDTOSchema),top:z77.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z77.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z77.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z77.object({credits:z77.number(),costUsd:z77.number(),messages:z77.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z77.object({id:z77.string(),name:z77.string(),createdAt:z77.string(),memberCount:z77.number(),projectCount:z77.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z77.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z77.object({id:z77.string(),name:z77.string().nullable(),email:z77.string(),image:z77.string().nullable(),createdAt:z77.string(),organizationCount:z77.number(),projectCount:z77.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z77.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z77.object({id:z77.string(),name:z77.string(),displayName:z77.string().nullable(),createdAt:z77.string(),organizationId:z77.string(),organizationName:z77.string(),ownerId:z77.string(),ownerName:z77.string().nullable(),ownerEmail:z77.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z77.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z78}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=z78.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z78.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z78.object({command:z78.string().min(1).max(1e4),cwd:z78.string().optional(),projectBranch:BranchSchema.optional(),projectEnv:BranchSchema.optional(),env:z78.record(z78.string(),z78.string()).optional(),name:z78.string().optional(),waitForCompletion:z78.boolean().optional().default(!1)}).superRefine((value,ctx)=>{value.projectBranch!==void 0&&value.projectEnv!==void 0&&value.projectBranch!==value.projectEnv&&ctx.addIssue({code:"custom",path:["projectBranch"],message:"`projectBranch` and deprecated `projectEnv` must match when both are supplied"})}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z78.object({identifier:z78.string(),status:SandboxProcessStatusSchema,command:z78.string().optional(),startedAt:z78.string().optional(),exitCode:z78.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z78.object({processes:z78.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z78.object({processId:z78.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z78.object({success:z78.boolean(),message:z78.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z79}from"zod";var ADMIN_UNCLAIMED_STATES,AdminUnclaimedStateSchema,AdminUnclaimedProjectsQuerySchema,AdminUnclaimedProjectDTOSchema,AdminUnclaimedProjectDTO,AdminUnclaimedProjectsResponseSchema,ClaimOutcomesSchema,AdminUnclaimedProjectStatsSchema,AdminUnclaimedProjectStatsResponseSchema,init_unclaimed_projects_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/unclaimed-projects.dto.js"(){"use strict";init_create_dto();init_response();ADMIN_UNCLAIMED_STATES=["waiting","claiming","claimed","overdue","archived"],AdminUnclaimedStateSchema=z79.enum(ADMIN_UNCLAIMED_STATES),AdminUnclaimedProjectsQuerySchema=z79.object({search:z79.string().trim().max(200).optional(),startDate:z79.coerce.date().optional(),endDate:z79.coerce.date().optional(),states:z79.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z79.array(AdminUnclaimedStateSchema).optional()),cliVersions:z79.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z79.array(z79.string().max(64)).optional()),page:z79.coerce.number().int().min(1).default(1),pageSize:z79.coerce.number().int().min(1).max(100).default(25)}),AdminUnclaimedProjectDTOSchema=z79.object({projectId:z79.string(),displayName:z79.string().nullable(),state:AdminUnclaimedStateSchema,cliVersion:z79.string().nullable(),createdAt:z79.coerce.date(),expiresAt:z79.coerce.date(),claimedAt:z79.coerce.date().nullable(),claimedOrganizationId:z79.string().nullable(),claimedOrganizationName:z79.string().nullable(),claimedByEmail:z79.string().nullable(),projectExists:z79.boolean(),previewUrl:z79.string().nullable(),hostingCostUsd:z79.number().nullable()}),AdminUnclaimedProjectDTO=createDTO(AdminUnclaimedProjectDTOSchema),AdminUnclaimedProjectsResponseSchema=createResponseSchema(z79.object({projects:z79.array(AdminUnclaimedProjectDTOSchema),page:z79.number(),limit:z79.number(),total:z79.number(),totalPages:z79.number()})),ClaimOutcomesSchema=z79.object({total:z79.number(),claimed:z79.number(),archived:z79.number(),claimRate:z79.number().nullable(),medianTimeToClaimSeconds:z79.number().nullable()}),AdminUnclaimedProjectStatsSchema=ClaimOutcomesSchema.extend({states:z79.record(AdminUnclaimedStateSchema,z79.number()),averageTimeToClaimSeconds:z79.number().nullable(),byCliVersion:z79.array(ClaimOutcomesSchema.extend({cliVersion:z79.string().nullable()})),granularity:z79.enum(["hour","day"]),series:z79.array(z79.object({at:z79.coerce.date(),states:z79.record(AdminUnclaimedStateSchema,z79.number()),alive:z79.number(),hostingCostUsd:z79.number()})),hostingCostUsd:z79.number(),costPerProjectUsd:z79.number().nullable(),leftovers:z79.object({overdue:z79.number(),claiming:z79.number(),archivedNotDeleted:z79.number()})}),AdminUnclaimedProjectStatsResponseSchema=createResponseSchema(AdminUnclaimedProjectStatsSchema)}});import{z as z80}from"zod";var WorkSessionVisibilitySchema,SessionSetRetentionSchema,init_work_sessions=__esm({"../../packages/api-contracts/dist/esm/work-sessions.js"(){"use strict";WorkSessionVisibilitySchema=z80.enum(["internal","user-visible"]),SessionSetRetentionSchema=z80.object({additionalDays:z80.number().int().min(1).max(30)}).strict()}});import{z as z81}from"zod";var PROJECT_KNOWLEDGE_MAX_CHARACTERS,ProjectKnowledgeContentSchema,ProjectKnowledgeDTOSchema,ProjectKnowledgeUpdateSchema,ProjectKnowledgeResponseSchema,ProjectKnowledgeDraftDTOSchema,ProjectKnowledgeDraftResponseSchema,ProjectKnowledgeDraftStartSchema,init_project_knowledge_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-knowledge.dto.js"(){"use strict";init_response();PROJECT_KNOWLEDGE_MAX_CHARACTERS=1e4,ProjectKnowledgeContentSchema=z81.string().refine(value=>[...value].length<=PROJECT_KNOWLEDGE_MAX_CHARACTERS&&new TextEncoder().encode(value).length<=4e4,"Knowledge must contain at most 10,000 characters and 40 KB of UTF-8 text"),ProjectKnowledgeDTOSchema=z81.object({content:ProjectKnowledgeContentSchema,updatedAt:z81.string().nullable(),updatedBy:z81.string().nullable()}),ProjectKnowledgeUpdateSchema=z81.object({content:ProjectKnowledgeContentSchema}),ProjectKnowledgeResponseSchema=createResponseSchema(ProjectKnowledgeDTOSchema),ProjectKnowledgeDraftDTOSchema=z81.object({id:z81.uuid(),status:z81.enum(["queued","running","ready","failed"]),content:ProjectKnowledgeContentSchema.nullable(),error:z81.string().nullable()}),ProjectKnowledgeDraftResponseSchema=createResponseSchema(ProjectKnowledgeDraftDTOSchema.nullable()),ProjectKnowledgeDraftStartSchema=z81.object({idempotencyKey:z81.uuid()})}});import{z as z82}from"zod";var ORGANIZATION_FEATURES,OrganizationFeatureSchema,OrganizationFeaturesDTOSchema,OrganizationFeaturesDTO,OrganizationFeatureStateDTOSchema,OrganizationFeatureSetSchema,init_organization_features_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization-features.dto.js"(){"use strict";init_create_dto();ORGANIZATION_FEATURES=["agents"],OrganizationFeatureSchema=z82.enum(ORGANIZATION_FEATURES),OrganizationFeaturesDTOSchema=z82.object({features:z82.record(OrganizationFeatureSchema,z82.boolean())}),OrganizationFeaturesDTO=createDTO(OrganizationFeaturesDTOSchema),OrganizationFeatureStateDTOSchema=z82.object({feature:OrganizationFeatureSchema,enabled:z82.boolean(),default:z82.boolean(),override:z82.boolean().nullable(),reason:z82.string().nullable(),updatedBy:z82.string().nullable(),updatedAt:z82.string().datetime().nullable()}),OrganizationFeatureSetSchema=z82.object({state:z82.enum(["on","off","default"]),reason:z82.string().trim().min(1).max(500),apply:z82.boolean().default(!1),confirmProduction:z82.boolean().default(!1)})}});import{z as z83}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_asset_reading();init_env();init_environment();init_realtime();init_realtime_room();init_references();init_content_fields();init_audit_log();init_ops();init_chat_block();init_chat_portrait();init_agent_report();init_fimo_config();init_page_sources();init_project_files();init_project_dto();init_project_env_dto();init_project_environment_dto();init_project_secret_dto();init_project_import_export_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_question_dto();init_integration_dto();init_schedule_dto();init_schedule_notifications_dto();init_notification_dto();init_notification_preference_catalog_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_hosted_preview_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_project_migration_dto();init_analytics_dto();init_asset_dto();init_translation_dto();init_document_dto();init_form_dto();init_chat_dto();init_chat_routine_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_transfer_dto();init_unclaimed_project_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_ops_sentry_dto();init_ops_project_files_dto();init_ops_agent_chat_dto();init_webhook_dto();init_preview_feature_dto();init_site_onboarding_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto();init_unclaimed_projects_dto();init_work_sessions();init_project_knowledge_dto();init_organization_features_dto()}});var require_picocolors=__commonJS({"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js"(exports2,module2){var p2=process||{},argv=p2.argv||[],env=p2.env||{},isColorSupported=!(env.NO_COLOR||argv.includes("--no-color"))&&(!!env.FORCE_COLOR||argv.includes("--color")||p2.platform==="win32"||(p2.stdout||{}).isTTY&&env.TERM!=="dumb"||!!env.CI),formatter=__name((open2,close,replace=open2)=>input=>{let string=""+input,index=string.indexOf(close,open2.length);return~index?open2+replaceClose(string,close,replace,index)+close:open2+string+close},"formatter"),replaceClose=__name((string,close,replace,index)=>{let result="",cursor=0;do result+=string.substring(cursor,index)+replace,cursor=index+close.length,index=string.indexOf(close,cursor);while(~index);return result+string.substring(cursor)},"replaceClose"),createColors=__name((enabled=isColorSupported)=>{let f=enabled?formatter:()=>String;return{isColorSupported:enabled,reset:f("\x1B[0m","\x1B[0m"),bold:f("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:f("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:f("\x1B[3m","\x1B[23m"),underline:f("\x1B[4m","\x1B[24m"),inverse:f("\x1B[7m","\x1B[27m"),hidden:f("\x1B[8m","\x1B[28m"),strikethrough:f("\x1B[9m","\x1B[29m"),black:f("\x1B[30m","\x1B[39m"),red:f("\x1B[31m","\x1B[39m"),green:f("\x1B[32m","\x1B[39m"),yellow:f("\x1B[33m","\x1B[39m"),blue:f("\x1B[34m","\x1B[39m"),magenta:f("\x1B[35m","\x1B[39m"),cyan:f("\x1B[36m","\x1B[39m"),white:f("\x1B[37m","\x1B[39m"),gray:f("\x1B[90m","\x1B[39m"),bgBlack:f("\x1B[40m","\x1B[49m"),bgRed:f("\x1B[41m","\x1B[49m"),bgGreen:f("\x1B[42m","\x1B[49m"),bgYellow:f("\x1B[43m","\x1B[49m"),bgBlue:f("\x1B[44m","\x1B[49m"),bgMagenta:f("\x1B[45m","\x1B[49m"),bgCyan:f("\x1B[46m","\x1B[49m"),bgWhite:f("\x1B[47m","\x1B[49m"),blackBright:f("\x1B[90m","\x1B[39m"),redBright:f("\x1B[91m","\x1B[39m"),greenBright:f("\x1B[92m","\x1B[39m"),yellowBright:f("\x1B[93m","\x1B[39m"),blueBright:f("\x1B[94m","\x1B[39m"),magentaBright:f("\x1B[95m","\x1B[39m"),cyanBright:f("\x1B[96m","\x1B[39m"),whiteBright:f("\x1B[97m","\x1B[39m"),bgBlackBright:f("\x1B[100m","\x1B[49m"),bgRedBright:f("\x1B[101m","\x1B[49m"),bgGreenBright:f("\x1B[102m","\x1B[49m"),bgYellowBright:f("\x1B[103m","\x1B[49m"),bgBlueBright:f("\x1B[104m","\x1B[49m"),bgMagentaBright:f("\x1B[105m","\x1B[49m"),bgCyanBright:f("\x1B[106m","\x1B[49m"),bgWhiteBright:f("\x1B[107m","\x1B[49m")}},"createColors");module2.exports=createColors();module2.exports.createColors=createColors}});function makePalette(enabled){return enabled?{success:import_picocolors.default.green,warn:import_picocolors.default.yellow,error:import_picocolors.default.red,hint:import_picocolors.default.cyan,dim:import_picocolors.default.dim,accent:import_picocolors.default.bold}:{success:identity,warn:identity,error:identity,hint:identity,dim:identity,accent:identity}}var import_picocolors,identity,init_colors=__esm({"../../packages/cli-kit/dist/colors.js"(){"use strict";import_picocolors=__toESM(require_picocolors(),1),identity=__name(s=>s,"identity");__name(makePalette,"makePalette")}});var SCHEMA_VERSION,init_types=__esm({"../../packages/cli-kit/dist/types.js"(){"use strict";SCHEMA_VERSION=1}});function makeJsonRenderer(opts){let{stdout,stderr}=opts,pendingWarnings=[];function emit(stream,envelope){let warnings=[...pendingWarnings,...envelope.warnings??[]].filter((warning,index,all)=>all.indexOf(warning)===index);pendingWarnings=[],stream.write(`${JSON.stringify(warnings.length>0?{...envelope,warnings}:envelope)}
|
|
6
6
|
`)}__name(emit,"emit");function okEnvelope(event){let base={status:"ok",command:event.command,schema_version:1};switch(event.kind){case"message":{let data={headline:event.headline};return event.details&&(data.details=event.details),base.data=data,event.hint&&(base.hint=event.hint),event.warnings&&event.warnings.length>0&&(base.warnings=event.warnings),base}case"table":{let rows=event.rows.map(row2=>{let out={};for(let col of event.columns)out[col.key]=row2[col.key];return event.isActive?.(row2)===!0&&(out.__active=!0),out}),data={...event.jsonData,columns:event.columns.map(c2=>c2.key),rows};return event.headline&&(data.headline=event.headline),base.data=data,event.hint&&(base.hint=event.hint),base}case"kv":{let data={fields:event.fields};return event.headline&&(data.headline=event.headline),base.data=data,event.hint&&(base.hint=event.hint),base}case"script":return base.data={shell:event.shell,script:event.script},base;case"raw":{let field=event.field??"value";return base.data={[field]:event.value},base}case"result":return base.data=event.data,event.hint&&(base.hint=event.hint),event.warnings&&event.warnings.length>0&&(base.warnings=event.warnings),base}}return __name(okEnvelope,"okEnvelope"),{ok(event){emit(stdout,okEnvelope(event))},error(event){emit(stderr,{status:"error",command:event.command,schema_version:1,error:{code:event.code,message:event.message,...event.details?{details:event.details}:{},...event.hint?{hint:event.hint}:{}}})},warn(event){pendingWarnings.push(event.message)},info(event){let env={status:"ok",command:event.command,schema_version:1,data:{...event.jsonData,message:event.message}};event.hint&&(env.hint=event.hint),emit(stdout,env)}}}var init_renderer_json=__esm({"../../packages/cli-kit/dist/renderer-json.js"(){"use strict";__name(makeJsonRenderer,"makeJsonRenderer")}});function stripAnsi(input){return input.replace(OSC_PATTERN,"").replace(CSI_PATTERN,"")}function displayWidth(input){return stripAnsi(input).length}function padToWidth(input,target){let visible=displayWidth(input);return visible>=target?input:input+" ".repeat(target-visible)}var CSI_PATTERN,OSC_PATTERN,init_width=__esm({"../../packages/cli-kit/dist/width.js"(){"use strict";CSI_PATTERN=/\x1B\[[0-9;]*[A-Za-z]/g,OSC_PATTERN=/\x1B\][\s\S]*?(?:\x07|\x1B\\)/g;__name(stripAnsi,"stripAnsi");__name(displayWidth,"displayWidth");__name(padToWidth,"padToWidth")}});function makePrettyRenderer(opts){let{palette:palette2,symbols,context,stdout,stderr}=opts;function write(stream,line){stream.write(`${line}
|
|
7
7
|
`)}__name(write,"write");function renderMessage(event){if(write(stdout,`${palette2.success(symbols.ok)} ${event.headline}`),event.details&&renderAlignedFields(event.details," "),event.warnings)for(let w3 of event.warnings)write(stdout,` ${palette2.warn(symbols.warn)} ${w3}`);maybeHint(event.hint)}__name(renderMessage,"renderMessage");function renderAlignedFields(fields,indent){let keys=Object.keys(fields),longest=keys.reduce((m,k)=>Math.max(m,k.length),0);for(let k of keys){let value=fields[k];value!=null&&write(stdout,`${indent}${palette2.dim(`${k}:`.padEnd(longest+2))}${formatScalar(value)}`)}}__name(renderAlignedFields,"renderAlignedFields");function renderTable2(event){event.headline&&write(stdout,`${palette2.success(symbols.ok)} ${event.headline}`);let{columns,rows}=event;if(rows.length===0){write(stdout,palette2.dim(" (no rows)")),maybeHint(event.hint);return}let widths=columns.map(c2=>Math.max(displayWidth(c2.label),...rows.map(r=>displayWidth(String(r[c2.key]??""))))),header=columns.map((c2,i)=>padToWidth(c2.label,widths[i])).join(" ");write(stdout,` ${palette2.dim(header)}`);for(let row2 of rows){let active=event.isActive?.(row2)===!0,cells=columns.map((c2,i)=>{let raw=String(row2[c2.key]??""),padded=padToWidth(raw,widths[i]),role=event.cellStyle?.(row2,c2.key);return role?paintCell(padded,role):active?palette2.accent(padded):padded}),marker=active?palette2.success(symbols.active):" ";write(stdout,`${marker} ${cells.join(" ")}`)}maybeHint(event.hint)}__name(renderTable2,"renderTable");function paintCell(cell,role){switch(role){case"success":return palette2.success(cell);case"warn":return palette2.warn(cell);case"error":return palette2.error(cell);case"dim":return palette2.dim(cell);case"accent":return palette2.accent(cell)}}__name(paintCell,"paintCell");function renderKv(event){event.headline&&write(stdout,`${palette2.success(symbols.ok)} ${event.headline}`),renderAlignedFields(event.fields,""),maybeHint(event.hint)}__name(renderKv,"renderKv");function renderScript(event){stdout.write(event.script.endsWith(`
|
|
8
8
|
`)?event.script:`${event.script}
|
|
@@ -41,7 +41,7 @@ Expecting one of '${allowedValues.join("', '")}'`);return this._lifeCycleHooks[e
|
|
|
41
41
|
`),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(aliases){return aliases===void 0?this._aliases:(aliases.forEach(alias=>this.alias(alias)),this)}usage(str){if(str===void 0){if(this._usage)return this._usage;let args=this.registeredArguments.map(arg=>humanReadableArgName(arg));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?args:[]).join(" ")}return this._usage=str,this}name(str){return str===void 0?this._name:(this._name=str,this)}nameFromFilename(filename){return this._name=path49.basename(filename,path49.extname(filename)),this}executableDir(path50){return path50===void 0?this._executableDir:(this._executableDir=path50,this)}helpInformation(contextOptions){let helper=this.createHelp(),context=this._getOutputContext(contextOptions);helper.prepareContext({error:context.error,helpWidth:context.helpWidth,outputHasColors:context.hasColors});let text=helper.formatHelp(this,helper);return context.hasColors?text:this._outputConfiguration.stripColor(text)}_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,text){let allowedValues=["beforeAll","before","after","afterAll"];if(!allowedValues.includes(position))throw new Error(`Unexpected value for position to addHelpText.
|
|
42
42
|
Expecting one of '${allowedValues.join("', '")}'`);let helpEvent=`${position}Help`;return this.on(helpEvent,context=>{let helpStr;typeof text=="function"?helpStr=text({error:context.error,command:context.command}):helpStr=text,helpStr&&context.write(`${helpStr}
|
|
43
43
|
`)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();helpOption&&args.find(arg=>helpOption.is(arg))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;return(match=arg.match(/^(--inspect(-brk)?)$/))!==null?debugOption=match[1]:(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(debugOption=match[1],/^\d+$/.test(match[3])?debugPort=match[3]:debugHost=match[3]):(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match[1],debugHost=match[3],debugPort=match[4]),debugOption&&debugPort!=="0"?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}__name(incrementNodeInspectorPort,"incrementNodeInspectorPort");function useColor(){if(process8.env.NO_COLOR||process8.env.FORCE_COLOR==="0"||process8.env.FORCE_COLOR==="false")return!1;if(process8.env.FORCE_COLOR||process8.env.CLICOLOR_FORCE!==void 0)return!0}__name(useColor,"useColor");exports2.Command=Command2;exports2.useColor=useColor}});var require_commander=__commonJS({"../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js"(exports2){var{Argument:Argument2}=require_argument(),{Command:Command2}=require_command(),{CommanderError:CommanderError2,InvalidArgumentError:InvalidArgumentError2}=require_error(),{Help:Help2}=require_help(),{Option:Option2}=require_option();exports2.program=new Command2;exports2.createCommand=name=>new Command2(name);exports2.createOption=(flags,description)=>new Option2(flags,description);exports2.createArgument=(name,description)=>new Argument2(name,description);exports2.Command=Command2;exports2.Option=Option2;exports2.Argument=Argument2;exports2.Help=Help2;exports2.CommanderError=CommanderError2;exports2.InvalidArgumentError=InvalidArgumentError2;exports2.InvalidOptionArgumentError=InvalidArgumentError2}});import{createHash}from"node:crypto";function normalizeApiUrl(input){let trimmed=input.trim();try{let url=new URL(trimmed),pathname=url.pathname.replace(/\/+$/,"");return`${url.protocol}//${url.host}${pathname}`}catch{return trimmed.replace(/\/+$/,"")}}function hashApiUrl(input){return createHash("sha256").update(normalizeApiUrl(input)).digest("hex").slice(0,6)}function safeHostLabel(host){return host.replace(/:/g,"-").replace(/[^a-zA-Z0-9.-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").toLowerCase()}function credentialsFilename(apiUrl){let normalized=normalizeApiUrl(apiUrl),hostLabel="unknown";try{hostLabel=safeHostLabel(new URL(normalized).host)}catch{}return hostLabel.length===0&&(hostLabel="unknown"),`${hostLabel}-${hashApiUrl(apiUrl)}.json`}var init_credentials_path=__esm({"src/cli/utils/credentials-path.ts"(){__name(normalizeApiUrl,"normalizeApiUrl");__name(hashApiUrl,"hashApiUrl");__name(safeHostLabel,"safeHostLabel");__name(credentialsFilename,"credentialsFilename")}});import fs from"node:fs";import{homedir}from"node:os";import path,{join}from"node:path";import{fileURLToPath}from"node:url";function readReleaseManifest(){try{let raw=fs.readFileSync(RELEASE_FILE,"utf8"),parsed=JSON.parse(raw),manifest={};return typeof parsed.apiUrl=="string"&&parsed.apiUrl.length>0&&(manifest.apiUrl=parsed.apiUrl),typeof parsed.webUrl=="string"&&parsed.webUrl.length>0&&(manifest.webUrl=parsed.webUrl),manifest}catch{return{}}}function loadConfig(){let baked=readReleaseManifest(),apiUrl=process.env.FIMO_API_URL?.trim()||baked.apiUrl||DEFAULT_API_URL,webUrl=process.env.FIMO_WEB_URL?.trim()||baked.webUrl||DEFAULT_WEB_URL,configDir=join(process.env.XDG_CONFIG_HOME||join(homedir(),".config"),"fimo"),credentialsDir=join(configDir,"credentials");return{apiUrl,webUrl,configDir,credentialsDir,credentialsFile:join(credentialsDir,credentialsFilename(apiUrl))}}var DEFAULT_API_URL,DEFAULT_WEB_URL,THIS_FILE,CLI_ROOT,RELEASE_FILE,init_config=__esm({"src/cli/config.ts"(){init_credentials_path();DEFAULT_API_URL="http://localhost:3000",DEFAULT_WEB_URL="http://localhost:5173",THIS_FILE=fileURLToPath(import.meta.url),CLI_ROOT=path.resolve(path.dirname(THIS_FILE),"..",".."),RELEASE_FILE=path.resolve(CLI_ROOT,"release.json");__name(readReleaseManifest,"readReleaseManifest");__name(loadConfig,"loadConfig")}});import fs2 from"node:fs";import path2 from"node:path";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 findProjectToken(cfg=loadConfig(),start=process.cwd()){let dir=path2.resolve(start);for(;;){let candidate=path2.join(dir,PROJECT_TOKEN_FILE);if(fs2.existsSync(candidate)){let file=JSON.parse(fs2.readFileSync(candidate,"utf-8"));return normalizeApiUrl(file.apiUrl)===normalizeApiUrl(cfg.apiUrl)?{root:dir,file}:null}let parent=path2.dirname(dir);if(parent===dir)return null;dir=parent}}function writeProjectToken(root,file){let target=path2.join(root,PROJECT_TOKEN_FILE);fs2.mkdirSync(path2.dirname(target),{recursive:!0}),fs2.writeFileSync(target,`${JSON.stringify(file,null,2)}
|
|
44
|
-
`,{mode:384})}function resolveAuth(cfg=loadConfig()){let bearer=cfg.token||process.env.FIMO_API_TOKEN?.trim();if(bearer)return bearer.startsWith(PROJECT_TOKEN_PREFIX)?{kind:"project",token:bearer,tokenFile:null}:{kind:"bearer",token:bearer};let tokenFile=findProjectToken(cfg);if(tokenFile)return{kind:"project",token:tokenFile.file.token,tokenFile};let credentials=readCredentials(cfg);return credentials?.access_token?{kind:"session",token:credentials.access_token,credentials}:null}function requireAuth(cfg=loadConfig()){let auth=resolveAuth(cfg);if(!auth)throw new NotAuthenticatedError(cfg.apiUrl);return auth}function requireToken(cfg=loadConfig()){return requireAuth(cfg).token}function requireAccountCredentials(cfg=loadConfig()){if(resolveAuth(cfg)?.kind==="project")throw new AccountRequiredError(cfg.apiUrl);return requireCredentials(cfg)}function requireCredentials(cfg=loadConfig()){let creds=readCredentials(cfg);if(!creds?.access_token)throw new NotAuthenticatedError(cfg.apiUrl);return creds}var PROJECT_TOKEN_FILE,NotAuthenticatedError,AccountRequiredError,init_auth=__esm({"src/cli/auth.ts"(){init_esm();init_config();init_credentials_path();PROJECT_TOKEN_FILE=path2.join(".fimo","credentials.local.json"),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}},AccountRequiredError=class extends NotAuthenticatedError{static{__name(this,"AccountRequiredError")}constructor(apiUrl){super(apiUrl,"This command needs a Fimo account, but this directory uses the project token of an unclaimed site."),this.name="AccountRequiredError"}};__name(ensureCredentialsDir,"ensureCredentialsDir");__name(readCredentials,"readCredentials");__name(writeCredentials,"writeCredentials");__name(clearCredentials,"clearCredentials");__name(setActiveOrganization,"setActiveOrganization");__name(recordAuthFailure,"recordAuthFailure");__name(findProjectToken,"findProjectToken");__name(writeProjectToken,"writeProjectToken");__name(resolveAuth,"resolveAuth");__name(requireAuth,"requireAuth");__name(requireToken,"requireToken");__name(requireAccountCredentials,"requireAccountCredentials");__name(requireCredentials,"requireCredentials")}});function detectProjectLayout(paths){let hasCurrentProject=!1,hasLegacyProject=!1,hasCurrentMarker=!1,hasLegacyMarker=!1;for(let input of paths){let file=input.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/$/,"");hasCurrentProject||=file===CURRENT_PROJECT_LAYOUT.project,hasLegacyProject||=file===LEGACY_PROJECT_LAYOUT.project,hasCurrentMarker||=file===CURRENT_PROJECT_LAYOUT.config,hasLegacyMarker||=file===LEGACY_PROJECT_LAYOUT.config||file===LEGACY_AGENT_POLICY_PATH}return hasCurrentProject?"current":hasLegacyProject?"legacy":hasCurrentMarker?"current":hasLegacyMarker?"legacy":null}function getProjectLayoutPaths(layout){return layout==="current"?CURRENT_PROJECT_LAYOUT:LEGACY_PROJECT_LAYOUT}function selectProjectConfigPath(paths,layout){let files=new Set(Array.from(paths,file=>file.replace(/\\/g,"/").replace(/^\.\//,"")));return(layout??detectProjectLayout(files)??"current")==="current"?CURRENT_PROJECT_LAYOUT.config:files.has(LEGACY_AGENT_POLICY_PATH)&&!files.has(LEGACY_PROJECT_LAYOUT.config)?LEGACY_AGENT_POLICY_PATH:LEGACY_PROJECT_LAYOUT.config}var CURRENT_PROJECT_LAYOUT,LEGACY_PROJECT_LAYOUT,LEGACY_AGENT_POLICY_PATH,init_project_layout=__esm({"src/runtime/project-layout.ts"(){CURRENT_PROJECT_LAYOUT={project:".fimo/project.json",config:".fimo/config.json"},LEGACY_PROJECT_LAYOUT={project:".fimo.settings.json",config:"fimo-config.json"},LEGACY_AGENT_POLICY_PATH="fimo.config.json";__name(detectProjectLayout,"detectProjectLayout");__name(getProjectLayoutPaths,"getProjectLayoutPaths");__name(selectProjectConfigPath,"selectProjectConfigPath")}});function isValidBranch2(branch){return typeof branch!="string"||branch.length===0||branch.length>255||branch.startsWith("-")||branch.startsWith(".")||branch.includes("//")||branch.includes("--")||branch.split("/").some(segment=>segment==="..")?!1:BRANCH_ID_REGEX2.test(branch)}function fnv1a82(s){let h=2166136261;for(let i=0;i<s.length;i++)h^=s.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}function envResourceKey2(branch){let base=branch.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a82(branch);return base?`${base}-${hash}`:hash}function buildTenantApiUrl2(projectId,branch,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${envResourceKey2(branch)}.${url.hostname}`,url.toString().replace(/\/$/,"")}function buildLocalRuntimeEnv(options){return{...Object.fromEntries(LOCAL_CONTENT_API_ENV_KEYS.map(key=>[key,options.tenantApiUrl])),...Object.fromEntries(LOCAL_ENV_SELECTOR_KEYS.map(key=>[key,options.branch]))}}var BRANCH_ID_REGEX2,LOCAL_CONTENT_API_ENV_KEYS,LOCAL_ENV_SELECTOR_KEYS,init_branch_identity=__esm({"src/runtime/shared/branch-identity.ts"(){BRANCH_ID_REGEX2=/^[a-zA-Z0-9._/-]+$/;__name(isValidBranch2,"isValidBranch");__name(fnv1a82,"fnv1a8");__name(envResourceKey2,"envResourceKey");__name(buildTenantApiUrl2,"buildTenantApiUrl");LOCAL_CONTENT_API_ENV_KEYS=["FIMO_CONTENT_API_URL","VITE_API_URL","NEXT_PUBLIC_FIMO_API_URL","PUBLIC_FIMO_API_URL"],LOCAL_ENV_SELECTOR_KEYS=["FIMO_ENV","NEXT_PUBLIC_FIMO_ENV"];__name(buildLocalRuntimeEnv,"buildLocalRuntimeEnv")}});import{execFileSync}from"node:child_process";import fs3 from"node:fs";import path3 from"node:path";import{parseEnv}from"node:util";function resolveLocalRuntimeEnv(options){let root=findProjectRoot(options.cwd),link=root?readProjectLink(root):null;if(!root||!link)return null;let branch=currentBranch(root);if(!branch)return null;let tenantApiUrl=buildTenantApiUrl2(link.projectId,branch,link.tenantApiBaseUrl);return{env:branch,tenantApiUrl,source:"branch",values:buildLocalRuntimeEnv({tenantApiUrl,branch}),link}}function findStaleFimoOverride(explicit,derived){for(let key of LOCAL_CONTENT_API_ENV_KEYS){let value=explicit[key];if(value&&value!==derived.tenantApiUrl&&isFimoMintedTenantUrl(value,derived.link))return{key,explicit:value,derived:derived.tenantApiUrl}}return null}function staleOverrideMessage(stale){return`[fimo] An env file pins the app to ${stale.explicit} (seeded by an older CLI), so it will NOT follow the git branch (${stale.derived}). Run \`fimo link\` to remove that line, or delete it yourself.`}function isFimoMintedTenantUrl(value,link){try{let candidate=new URL(value),base=new URL(link.tenantApiBaseUrl);return candidate.protocol===base.protocol&&candidate.port===base.port&&candidate.hostname.startsWith(`${link.projectId}-`)&&candidate.hostname.endsWith(`.${base.hostname}`)}catch{return!1}}function readLocalEnvFiles(cwd){let root=findProjectRoot(cwd)??cwd,values={};for(let file of[".env",".env.local"]){let filePath=path3.join(root,file);fs3.existsSync(filePath)&&Object.assign(values,parseEnv(fs3.readFileSync(filePath,"utf-8")))}return values}function currentBranch(root){try{let branch=execFileSync("git",["symbolic-ref","--short","-q","HEAD"],{cwd:root,stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim();return branch&&isValidBranch2(branch)?branch:null}catch{return null}}function findProjectRoot(start){let dir=path3.resolve(start);for(;;){if(fs3.existsSync(path3.join(dir,CURRENT_PROJECT_LAYOUT.project))||fs3.existsSync(path3.join(dir,LEGACY_PROJECT_LAYOUT.project)))return dir;let parent=path3.dirname(dir);if(parent===dir)return null;dir=parent}}function readProjectLink(root){for(let layout of[CURRENT_PROJECT_LAYOUT,LEGACY_PROJECT_LAYOUT]){let file=path3.join(root,layout.project);if(fs3.existsSync(file))try{let parsed=JSON.parse(fs3.readFileSync(file,"utf-8"));if(typeof parsed.projectId=="string"&&parsed.projectId.length>0&&typeof parsed.tenantApiBaseUrl=="string"&&parsed.tenantApiBaseUrl.length>0)return{projectId:parsed.projectId,tenantApiBaseUrl:parsed.tenantApiBaseUrl}}catch{return null}}return null}var init_local_runtime_env=__esm({"src/runtime/shared/local-runtime-env.ts"(){init_project_layout();init_branch_identity();__name(resolveLocalRuntimeEnv,"resolveLocalRuntimeEnv");__name(findStaleFimoOverride,"findStaleFimoOverride");__name(staleOverrideMessage,"staleOverrideMessage");__name(isFimoMintedTenantUrl,"isFimoMintedTenantUrl");__name(readLocalEnvFiles,"readLocalEnvFiles");__name(currentBranch,"currentBranch");__name(findProjectRoot,"findProjectRoot");__name(readProjectLink,"readProjectLink")}});import{z as z83}from"zod";function createResponseSchema2(dataSchema){return z83.object({data:dataSchema})}function encodeBranchPathSegment2(branch){return encodeURIComponent(branch.replaceAll("/","--"))}function managementProjectPath(projectId,suffix){return`/management/projects/${encodeURIComponent(projectId)}${suffix}`}function managementBranchPath(projectId,branch,suffix){return managementProjectPath(projectId,`/branches/${encodeBranchPathSegment2(branch)}${suffix}`)}function tenantPath(projectId,branch,suffix){return`/tenant/${encodeURIComponent(projectId)}/branches/${encodeBranchPathSegment2(branch)}${suffix}`}function addQuery(path49,query){let params=new URLSearchParams;for(let[key,value]of Object.entries(query))value!=null&&(Array.isArray(value)?value.length>0&¶ms.set(key,value.join(",")):params.set(key,String(value)));let queryString=params.toString();return queryString?`${path49}?${queryString}`:path49}function withoutUndefined(values){return Object.fromEntries(Object.entries(values).filter(([,value])=>value!==void 0))}function utf8Text(maxBytes,message){return z83.string().refine(value=>new TextEncoder().encode(value).byteLength<=maxBytes,message)}function responseData(body){if(!body||typeof body!="object"||!("data"in body))throw new Error("Expected a Fimo API response envelope.");return body.data}function publicSurface(surface){return surface==="translations"?"labels":surface}function backendSurfaces(surfaces){return surfaces?.map(surface=>surface==="labels"?"translations":surface)}function recordValue(value,message){if(!value||typeof value!="object"||Array.isArray(value))throw new Error(message);return value}function paginationRefinement(input,context){if(input.cursor!=null&&input.offset!==void 0){context.addIssue({code:"custom",message:"Use either cursor or offset, not both.",path:["cursor"]});return}if(input.cursor!=null)try{decodePaginationCursor(input.cursor)}catch(error){context.addIssue({code:"custom",message:error instanceof Error?error.message:"Invalid pagination cursor.",path:["cursor"]})}}function encodePaginationCursor(offset){return btoa(JSON.stringify({v:1,offset})).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function decodePaginationCursor(cursor){try{if(!/^[A-Za-z0-9_-]+$/.test(cursor))throw new Error("Invalid pagination cursor.");let base64=cursor.replaceAll("-","+").replaceAll("_","/"),value=JSON.parse(atob(base64.padEnd(Math.ceil(base64.length/4)*4,"=")));if(!value||typeof value!="object"||value.v!==1||!Number.isSafeInteger(value.offset)||value.offset<0)throw new Error("Invalid pagination cursor.");return value.offset}catch{throw new Error("Invalid pagination cursor.")}}function paginationOffset(input){return input.cursor==null?input.offset:decodePaginationCursor(input.cursor)}function numberedPaginationRefinement(input,context){input.cursor!=null&&input.page!==void 0&&context.addIssue({code:"custom",message:"Use either cursor or page, not both.",path:["cursor"]})}function paginationPage(input){return input.cursor==null?input.page:Number(input.cursor)}function pageSchema(itemSchema){return z83.object({items:z83.array(itemSchema),nextCursor:z83.string().nullable(),total:z83.number().int().nonnegative().optional()})}function projectOffsetPage(body){let{data,meta}=rawOffsetPageSchema.parse(body);return{items:data,nextCursor:meta.hasMore?encodePaginationCursor(meta.offset+meta.limit):null,total:meta.total}}function projectDetail(schema){return body=>{let projected=schema.safeParse(body);return projected.success?projected.data:schema.parse(responseData(body))}}function requiredBranch(branch){if(!branch)throw new Error("A Branch is required when sessionId is absent.");return branch}function projectFilesPath(projectId,branch,sessionId,suffix){return sessionId?managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files${suffix}`):managementBranchPath(projectId,requiredBranch(branch),`/files${suffix}`)}var uuidSchema,sessionStatusSchema,surfaceNameSchema,branchSurfaceSchema,backendSurfaceSchema,branchNameSchema,PROJECT_FILE_WRITE_LIMIT_BYTES2,PROJECT_FILE_WRITE_MANY_MAX_FILES,PROJECT_FILE_WRITE_MANY_LIMIT_BYTES,sessionEnvelopeSchema,paginationShape,numberedPaginationShape,rawOffsetPageSchema,init_common2=__esm({"../../packages/sdk/dist/operations/common.js"(){"use strict";__name(createResponseSchema2,"createResponseSchema");uuidSchema=z83.uuid(),sessionStatusSchema=z83.enum(["provisioning","ready","closing","merged","discarded","expired","failed"]),surfaceNameSchema=z83.enum(["code","schemas","content","labels","assets","forms"]),branchSurfaceSchema=z83.enum(["code","schemas","content","labels","assets","forms"]),backendSurfaceSchema=z83.enum(["code","schemas","content","translations","assets","forms"]),branchNameSchema=z83.string().trim().min(1).max(255).regex(/^[a-zA-Z0-9._/-]+$/).refine(branch=>!branch.startsWith("-")&&!branch.startsWith(".")&&!branch.includes("//")&&!branch.includes("--")&&!branch.split("/").some(segment=>segment===".."),"Invalid Branch name.");__name(encodeBranchPathSegment2,"encodeBranchPathSegment");__name(managementProjectPath,"managementProjectPath");__name(managementBranchPath,"managementBranchPath");__name(tenantPath,"tenantPath");__name(addQuery,"addQuery");__name(withoutUndefined,"withoutUndefined");PROJECT_FILE_WRITE_LIMIT_BYTES2=256*1024,PROJECT_FILE_WRITE_MANY_MAX_FILES=100,PROJECT_FILE_WRITE_MANY_LIMIT_BYTES=1024*1024;__name(utf8Text,"utf8Text");__name(responseData,"responseData");__name(publicSurface,"publicSurface");__name(backendSurfaces,"backendSurfaces");__name(recordValue,"recordValue");sessionEnvelopeSchema=z83.object({sessionId:uuidSchema,projectId:uuidSchema,status:sessionStatusSchema,name:z83.string().nullable().optional(),goal:z83.string().nullable().optional(),provenance:z83.object({source:z83.enum(["studio","slack","mcp"]),creator:z83.object({kind:z83.enum(["user","slack","agent","oauth","conversation"]),id:z83.string()}),conversationId:z83.string().nullable(),runId:z83.string().nullable()}).nullable().optional(),createdBy:z83.string().optional(),createdAt:z83.iso.datetime().optional(),savedRevision:z83.string().nullable().optional(),targetBranch:z83.object({id:uuidSchema.nullable(),name:branchNameSchema,sha:z83.string().min(1)}),workingBranch:z83.object({id:uuidSchema,name:branchNameSchema}).nullable(),preview:z83.url().nullable(),lastActivityAt:z83.iso.datetime(),expiresAt:z83.iso.datetime().nullable(),retention:z83.enum(["temporary","durable"]).optional(),visibility:z83.enum(["internal","user-visible"]).optional(),onExpire:z83.enum(["discard","keep"]),nextOperations:z83.array(z83.string())}),paginationShape={limit:z83.number().int().min(1).max(100).optional(),cursor:z83.string().min(1).nullable().optional().describe("Opaque nextCursor from the previous page. Omit or use null for the first page."),offset:z83.number().int().min(0).optional()};__name(paginationRefinement,"paginationRefinement");__name(encodePaginationCursor,"encodePaginationCursor");__name(decodePaginationCursor,"decodePaginationCursor");__name(paginationOffset,"paginationOffset");numberedPaginationShape={page:z83.number().int().positive().optional(),cursor:paginationShape.cursor.refine(cursor=>cursor==null||/^[1-9]\d*$/.test(cursor)&&Number.isSafeInteger(Number(cursor)),"Invalid pagination cursor.")};__name(numberedPaginationRefinement,"numberedPaginationRefinement");__name(paginationPage,"paginationPage");__name(pageSchema,"pageSchema");rawOffsetPageSchema=z83.object({data:z83.array(z83.unknown()),meta:z83.object({limit:z83.number().int().positive(),offset:z83.number().int().nonnegative(),total:z83.number().int().nonnegative(),hasMore:z83.boolean()})});__name(projectOffsetPage,"projectOffsetPage");__name(projectDetail,"projectDetail");__name(requiredBranch,"requiredBranch");__name(projectFilesPath,"projectFilesPath")}});import{z as z84}from"zod";function projectAnalyticsTop(body,input){let analytics2=analyticsApiResponseSchema.parse(body).data,field={pages:"topPages",browsers:"topBrowsers",devices:"topDevices",countries:"topCountries",sources:"topSources"}[input.dimension];return analyticsTopOutputSchema.parse({branch:input.branch,dimension:input.dimension,items:input.limit===void 0?analytics2[field]:analytics2[field].slice(0,input.limit)})}function projectAnalyticsAnnotations(body,input){let analytics2=analyticsApiResponseSchema.parse(body).data;return analyticsAnnotationsOutputSchema.parse({branch:input.branch,annotations:analytics2.annotations})}function projectAnalyticsAnnotation(body){return body===void 0?null:analyticsAnnotationResponseSchema.parse(body)}var analyticsReadBranchSchema,analyticsPresetSchema,analyticsGroupBySchema,analyticsDeviceSchema,analyticsRangeShape,analyticsRangeRefinement,analyticsAnnotationSchema,analyticsBreakdownSchema,analyticsPageBreakdownSchema,analyticsPageviewsSchema,analyticsApiResponseSchema,analyticsPageviewsResponseSchema,analyticsDimensionSchema,analyticsTopOutputSchema,analyticsAnnotationsOutputSchema,analyticsAnnotationResponseSchema,analyticsOperations,init_analytics=__esm({"../../packages/sdk/dist/operations/analytics.js"(){"use strict";init_common2();analyticsReadBranchSchema=branchNameSchema.default("prod"),analyticsPresetSchema=z84.enum(["today","yesterday","this_week","this_month","last_7_days","last_30_days","last_90_days","last_week","last_month","last_quarter","last_year","custom"]),analyticsGroupBySchema=z84.enum(["day","week","month","quarter"]),analyticsDeviceSchema=z84.enum(["bot","desktop","mobile","tablet"]),analyticsRangeShape={preset:analyticsPresetSchema.optional(),device:analyticsDeviceSchema.optional(),groupBy:analyticsGroupBySchema.optional(),from:z84.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),to:z84.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),days:z84.union([z84.literal(7),z84.literal(30),z84.literal(90)]).optional()},analyticsRangeRefinement=__name((input,context)=>{input.preset==="custom"&&input.from===void 0&&context.addIssue({code:"custom",message:"from is required for custom preset",path:["from"]}),input.preset==="custom"&&input.to===void 0&&context.addIssue({code:"custom",message:"to is required for custom preset",path:["to"]})},"analyticsRangeRefinement"),analyticsAnnotationSchema=z84.object({date:z84.string(),content:z84.string(),updatedAt:z84.string(),updatedByUserId:z84.string()}),analyticsBreakdownSchema=z84.object({key:z84.string(),visitors:z84.number().int().nonnegative(),pageviews:z84.number().int().nonnegative()}),analyticsPageBreakdownSchema=z84.object({path:z84.string(),pageName:z84.string().nullable().optional(),visitors:z84.number().int().nonnegative(),pageviews:z84.number().int().nonnegative()}),analyticsPageviewsSchema=z84.object({range:z84.object({preset:analyticsPresetSchema,requestedFrom:z84.string(),requestedTo:z84.string(),effectiveFrom:z84.string(),effectiveTo:z84.string(),isRetentionLimited:z84.boolean(),groupBy:analyticsGroupBySchema}),deviceFilter:analyticsDeviceSchema.nullable().default(null),visitors:z84.number().int().nonnegative(),pageviews:z84.number().int().nonnegative(),botPageviews:z84.number().int().nonnegative().default(0),botVisitors:z84.number().int().nonnegative().default(0),bounceRate:z84.number().min(0).max(100),viewsPerVisit:z84.number().nonnegative(),averageVisitDurationSeconds:z84.number().nonnegative(),visitorsSeries:z84.array(z84.object({date:z84.string(),visitors:z84.number().int().nonnegative()})),topPages:z84.array(analyticsPageBreakdownSchema),topBrowsers:z84.array(analyticsBreakdownSchema),topDevices:z84.array(analyticsBreakdownSchema),topBots:z84.array(analyticsBreakdownSchema).default([]),topAiAssistants:z84.array(analyticsBreakdownSchema).default([]),topCountries:z84.array(analyticsBreakdownSchema),topSources:z84.array(analyticsBreakdownSchema),annotations:z84.array(analyticsAnnotationSchema)}),analyticsApiResponseSchema=createResponseSchema2(analyticsPageviewsSchema),analyticsPageviewsResponseSchema=createResponseSchema2(analyticsPageviewsSchema.extend({branch:branchNameSchema})),analyticsDimensionSchema=z84.enum(["pages","browsers","devices","countries","sources"]),analyticsTopOutputSchema=z84.object({branch:branchNameSchema,dimension:analyticsDimensionSchema,items:z84.array(z84.union([analyticsPageBreakdownSchema,analyticsBreakdownSchema]))}),analyticsAnnotationsOutputSchema=z84.object({branch:branchNameSchema,annotations:z84.array(analyticsAnnotationSchema)}),analyticsAnnotationResponseSchema=createResponseSchema2(analyticsAnnotationSchema);__name(projectAnalyticsTop,"projectAnalyticsTop");__name(projectAnalyticsAnnotations,"projectAnalyticsAnnotations");__name(projectAnalyticsAnnotation,"projectAnalyticsAnnotation");analyticsOperations={"analytics.pageviews":{domain:"analytics",summary:"Read published-site pageviews, visitors, range, breakdowns, and annotations. Branch defaults to prod; explicit branches are honored. Preview traffic is not collected; a non-prod zero is not evidence of no published traffic.",accessScope:"read",effect:"read",inputSchema:z84.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsPageviewsResponseSchema,projectOutput:__name((body,input)=>{let response=analyticsApiResponseSchema.parse(body);return{...response,data:{...response.data,branch:input.branch}}},"projectOutput"),buildRequest:__name(({projectId,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/analytics"),{preset,groupBy,from,to,days,device})}),"buildRequest")},"analytics.top":{domain:"analytics",summary:"Read a ranked published-site analytics breakdown. Branch defaults to prod; explicit branches are honored. Preview traffic is not collected.",accessScope:"read",effect:"read",inputSchema:z84.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,dimension:analyticsDimensionSchema,limit:z84.number().int().min(1).max(100).optional(),...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsTopOutputSchema,buildRequest:__name(({projectId,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/analytics"),{preset,groupBy,from,to,days,device})}),"buildRequest"),projectOutput:projectAnalyticsTop},"analytics.annotationsList":{domain:"analytics",summary:"List analytics annotations in the selected range. Branch defaults to prod; explicit branches are honored. Writes still require their own Branch scope.",accessScope:"read",effect:"read",inputSchema:z84.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsAnnotationsOutputSchema,buildRequest:__name(({projectId,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/analytics"),{preset,groupBy,from,to,days,device})}),"buildRequest"),projectOutput:projectAnalyticsAnnotations},"analytics.annotationsSet":{domain:"analytics",summary:"Set an analytics annotation for one site date.",accessScope:"write",effect:"mutation",inputSchema:z84.object({projectId:uuidSchema,branch:branchNameSchema,date:z84.string().regex(/^\d{4}-\d{2}-\d{2}$/),content:z84.string().max(500)}).strict(),outputSchema:z84.union([analyticsAnnotationResponseSchema,z84.null()]),buildRequest:__name(({projectId,branch,date,content:content2})=>({method:"PUT",path:managementBranchPath(projectId,branch,`/analytics/annotations/${encodeURIComponent(date)}`),body:{content:content2}}),"buildRequest"),projectOutput:projectAnalyticsAnnotation},"analytics.annotationsDelete":{domain:"analytics",summary:"Delete an analytics annotation for one site date.",accessScope:"write",effect:"mutation",inputSchema:z84.object({projectId:uuidSchema,branch:branchNameSchema,date:z84.string().regex(/^\d{4}-\d{2}-\d{2}$/)}).strict(),outputSchema:z84.null(),buildRequest:__name(({projectId,branch,date})=>({method:"PUT",path:managementBranchPath(projectId,branch,`/analytics/annotations/${encodeURIComponent(date)}`),body:{content:""}}),"buildRequest"),projectOutput:__name(()=>null,"projectOutput")}}}});import{z as z85}from"zod";var assetPathItemSchema,AssetDTOSchema2,AssetResponseSchema2,AssetReadRequestSchema2,assetDerivedFileSchema,assetReadBaseSchema,AssetReadResultSchema2,GenerateResponseSchema2,assetPageSchema,successMessageResponseSchema,assetGenerationInputSchema,assetUploadInputSchema,assetsOperations,init_assets=__esm({"../../packages/sdk/dist/operations/assets.js"(){"use strict";init_common2();assetPathItemSchema=z85.object({id:z85.string(),name:z85.string()}),AssetDTOSchema2=z85.object({id:z85.string(),name:z85.string(),type:z85.enum(["file","folder"]),originalFileName:z85.string().nullable(),parentId:z85.string().nullable(),mimeType:z85.string().nullable(),fileSize:z85.number().nullable(),url:z85.string().nullable(),storageKey:z85.string().nullable(),slug:z85.string(),tags:z85.array(z85.string()).nullable().optional(),createdAt:z85.string().nullable(),updatedAt:z85.string().nullable(),altText:z85.string().nullable().optional(),caption:z85.string().nullable().optional(),aiCaption:z85.string().nullable().optional(),aiAltText:z85.string().nullable().optional(),aiTags:z85.array(z85.string()).nullable().optional(),aiPrimaryColor:z85.string().nullable().optional(),aiProcessingStatus:z85.string().nullable().optional(),width:z85.number().nullable().optional(),height:z85.number().nullable().optional(),path:z85.array(assetPathItemSchema).optional(),hasChildren:z85.boolean().optional()}),AssetResponseSchema2=createResponseSchema2(AssetDTOSchema2),AssetReadRequestSchema2=z85.object({cursor:z85.string().nullable().optional(),query:z85.string().trim().min(1).max(500).optional()}).strict().refine(input=>input.cursor==null||input.query===void 0,{message:"Use either cursor or query, not both."}),assetDerivedFileSchema=z85.object({url:z85.url(),mediaType:z85.string(),filename:z85.string()}),assetReadBaseSchema=z85.object({assetId:z85.uuid(),filename:z85.string(),mediaType:z85.string(),representation:z85.enum(["text","table","document","archive","image","transcript","video","model"]),content:z85.string(),derivedFiles:z85.array(assetDerivedFileSchema).optional()}),AssetReadResultSchema2=z85.discriminatedUnion("mode",[assetReadBaseSchema.extend({mode:z85.literal("page"),start:z85.number().int().nonnegative(),end:z85.number().int().nonnegative(),total:z85.number().int().nonnegative(),nextCursor:z85.string().nullable(),complete:z85.boolean()}),assetReadBaseSchema.extend({mode:z85.literal("query"),query:z85.string(),source:z85.enum(["original-file","canonical-text","derived-files"]),truncated:z85.boolean()})]),GenerateResponseSchema2=createResponseSchema2(z85.object({jobId:z85.string(),status:z85.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema2.optional(),error:z85.string().nullable().optional(),credits:z85.number().optional(),costUsd:z85.number().optional(),billingMode:z85.enum(["fimo-credits","provider-account"]).optional(),task:z85.enum(["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"]).optional(),quality:z85.enum(["draft","standard","premium"]).optional()})),assetPageSchema=pageSchema(AssetDTOSchema2),successMessageResponseSchema=z85.object({data:z85.object({message:z85.literal("success")})}),assetGenerationInputSchema=z85.object({projectId:uuidSchema,branch:branchNameSchema,task:z85.string().min(1).optional(),model:z85.string().min(1).optional(),options:z85.record(z85.string(),z85.unknown()),name:z85.string().min(1).max(255).optional(),parentId:uuidSchema.nullable().optional(),altText:z85.string().max(2e3).optional(),caption:z85.string().max(2e3).optional()}).strict().superRefine((input,context)=>{!!input.task==!!input.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model.",path:["task"]})}),assetUploadInputSchema=z85.object({projectId:uuidSchema,sessionId:uuidSchema,url:z85.url().max(4096).refine(url=>url.startsWith("https://")||url.startsWith("http://"),"URL must use HTTP or HTTPS"),filename:z85.string().trim().min(1).max(255).refine(filename=>!filename.includes("/")&&!filename.includes("\\"),"Filename must not contain a path").optional(),name:z85.string().trim().min(1).max(255).optional(),parentId:uuidSchema.nullable().optional(),folderPath:z85.string().max(1024).refine(path49=>path49.split("/").some(segment=>segment.trim()),"Folder path must contain a folder name").refine(path49=>path49.split("/").every(segment=>![".",".."].includes(segment.trim())),"Folder path cannot contain . or .. segments").optional(),altText:z85.string().max(2e3).optional(),caption:z85.string().max(5e3).optional()}).refine(({parentId,folderPath})=>!(parentId&&folderPath),{message:"Use either parentId or folderPath, not both."}),assetsOperations={"assets.list":{domain:"assets",summary:"List media assets and folders on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z85.object({projectId:uuidSchema,branch:branchNameSchema,parentId:uuidSchema.optional(),search:z85.string().max(200).optional(),type:z85.enum(["file","folder"]).optional(),mimePrefix:z85.string().max(50).optional(),sortBy:z85.enum(["name","createdAt","updatedAt","fileSize","type"]).optional(),sortDirection:z85.enum(["asc","desc"]).optional(),includePath:z85.boolean().optional(),excludeHidden:z85.boolean().optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:assetPageSchema,buildRequest:__name(({projectId,branch,parentId,search,type,mimePrefix,sortBy,sortDirection,includePath,excludeHidden,limit,cursor,offset})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,"/assets"),{parentId,search,type,mimePrefix,sortBy,sortDirection,includePath:includePath||void 0,excludeHidden:excludeHidden||void 0,limit,offset:paginationOffset({cursor,offset})})}),"buildRequest"),projectOutput:projectOffsetPage},"assets.get":{domain:"assets",summary:"Read one media asset or folder from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z85.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:AssetResponseSchema2,buildRequest:__name(({projectId,branch,id})=>({method:"GET",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}`)}),"buildRequest")},"assets.read":{domain:"assets",summary:"Read bounded canonical content from one media asset or ask one targeted question.",accessScope:"read",effect:"read",inputSchema:z85.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,...AssetReadRequestSchema2.shape}).strict().refine(input=>input.cursor==null||input.query===void 0,{message:"Use either cursor or query, not both."}),outputSchema:createResponseSchema2(AssetReadResultSchema2),buildRequest:__name(({projectId,branch,id,cursor,query})=>({method:"POST",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}/read`),body:{cursor:cursor??void 0,query}}),"buildRequest")},"assets.generate":{domain:"assets",summary:"Generate an image or video asset and save it to the media library.",accessScope:"write",effect:"mutation",inputSchema:assetGenerationInputSchema,outputSchema:GenerateResponseSchema2,buildRequest:__name(({projectId,branch,task,model,options,name,parentId,altText,caption})=>({method:"POST",path:tenantPath(projectId,branch,"/assets/generate"),body:{...task?{task}:{model},options,name,parentId,altText,caption}}),"buildRequest")},"assets.uploadFromUrl":{domain:"assets",summary:"Import a public URL into a media library through an owned work session.",accessScope:"code",effect:"mutation",inputSchema:assetUploadInputSchema,outputSchema:sessionEnvelopeSchema.extend({asset:AssetDTOSchema2}),buildRequest:__name(({projectId,sessionId,...upload})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/assets/upload-from-url`),body:withoutUndefined(upload)}),"buildRequest")},"assets.createFolder":{domain:"assets",summary:"Create a media-library folder on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z85.object({projectId:uuidSchema,branch:branchNameSchema,name:z85.string().min(1).max(255),parentId:uuidSchema.nullable().optional()}).strict(),outputSchema:AssetResponseSchema2,buildRequest:__name(({projectId,branch,name,parentId})=>({method:"POST",path:tenantPath(projectId,branch,"/assets/folders"),body:{name,parentId}}),"buildRequest")},"assets.replaceReferences":{domain:"assets",summary:"Replace every Branch reference to one asset with another asset.",accessScope:"write",effect:"mutation",inputSchema:z85.object({projectId:uuidSchema,branch:branchNameSchema,sourceAssetId:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z85.record(z85.string(),z85.unknown()),buildRequest:__name(({projectId,branch,sourceAssetId,replacementAssetId})=>({method:"POST",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(sourceAssetId)}/replace-references`),body:{replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z85.object({data:z85.record(z85.string(),z85.unknown())}).parse(body).data,"projectOutput")},"assets.replaceAndRemove":{domain:"assets",summary:"Replace Branch references to an asset and schedule that asset for removal.",accessScope:"write",effect:"mutation",inputSchema:z85.object({projectId:uuidSchema,branch:branchNameSchema,sourceAssetId:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z85.record(z85.string(),z85.unknown()),buildRequest:__name(({projectId,branch,sourceAssetId,replacementAssetId})=>({method:"POST",path:tenantPath(projectId,branch,"/assets/removals"),body:{intent:"replace-and-remove",assetIds:[sourceAssetId],replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z85.object({data:z85.record(z85.string(),z85.unknown())}).parse(body).data,"projectOutput")},"assets.destroy":{domain:"assets",summary:"Permanently destroy an asset on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z85.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:z85.unknown(),buildRequest:__name(({projectId,branch,id})=>({method:"DELETE",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}/permanent`)}),"buildRequest"),projectOutput:__name(body=>z85.object({data:z85.unknown()}).parse(body).data,"projectOutput")},"assets.replaceAndDestroy":{domain:"assets",summary:"Replace every Branch reference to an asset, then permanently destroy it.",accessScope:"write",effect:"mutation",inputSchema:z85.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z85.record(z85.string(),z85.unknown()),buildRequest:__name(({projectId,branch,id,replacementAssetId})=>({method:"POST",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}/replace-and-destroy`),body:{replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z85.object({data:z85.record(z85.string(),z85.unknown())}).parse(body).data,"projectOutput")},"assets.move":{domain:"assets",summary:"Move a media asset or folder on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z85.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,parentId:uuidSchema.nullable()}).strict(),outputSchema:AssetResponseSchema2,buildRequest:__name(({projectId,branch,id,parentId})=>({method:"POST",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}/move`),body:{parentId}}),"buildRequest")},"assets.delete":{domain:"assets",summary:"Delete a media asset or folder from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z85.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:successMessageResponseSchema,buildRequest:__name(({projectId,branch,id})=>({method:"DELETE",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}`)}),"buildRequest")}}}});import{z as z86}from"zod";var creditBalanceOutputSchema,billingOperations,init_billing=__esm({"../../packages/sdk/dist/operations/billing.js"(){"use strict";init_common2();creditBalanceOutputSchema=z86.object({projectId:uuidSchema,organizationId:z86.string(),balance:z86.object({totalAvailable:z86.number(),nearLimit:z86.boolean(),canUseAi:z86.boolean(),buckets:z86.object({dailyFreeAvailable:z86.number(),monthlyAvailable:z86.number(),purchasedAvailable:z86.number(),awardedAvailable:z86.number()})}),allowances:z86.object({dailyCredits:z86.object({periodCap:z86.number(),dailyGrant:z86.number(),usedThisPeriod:z86.number(),remainingThisPeriod:z86.number()}).nullable()})}),billingOperations={"billing.credits":{domain:"billing",summary:"Read the AI credit balance and daily allowance that apply to one project. The daily allowance is a cap, not extra balance.",accessScope:"read",effect:"read",inputSchema:z86.object({projectId:uuidSchema}).strict(),outputSchema:creditBalanceOutputSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/billing/credits")}),"buildRequest"),projectOutput:__name(body=>creditBalanceOutputSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z87}from"zod";function projectConflict(value){let conflict=backendConflictSchema.parse(value);return conflictSchema.parse({...conflict,surface:publicSurface(conflict.surface)})}function backendResolution(resolution){return{...resolution,surface:backendSurfaces([resolution.surface])?.[0]}}function projectMergeResult(body){let result=z87.object({ok:z87.boolean(),mergeId:uuidSchema,fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),fromEnv:branchNameSchema,toEnv:branchNameSchema,applied:z87.array(z87.object({surface:backendSurfaceSchema,count:z87.number().int().nonnegative()})),conflicts:z87.array(backendConflictSchema).optional(),summary:z87.string().optional()}).parse(responseData(body));return mergeResultSchema.parse({...result,fromBranch:result.fromBranch??result.fromEnv,toBranch:result.toBranch??result.toEnv,applied:result.applied.map(item=>({...item,surface:publicSurface(item.surface)})),conflicts:result.conflicts?.map(projectConflict)})}function projectMergeHydration(body){let value=z87.object({mergeId:uuidSchema,conflicts:z87.array(backendConflictSchema),draftResolutions:z87.array(conflictResolutionSchema.extend({surface:backendSurfaceSchema})),status:z87.string()}).passthrough().parse(responseData(body));return mergeHydrationSchema.parse({...value,conflicts:value.conflicts.map(projectConflict),draftResolutions:value.draftResolutions.map(resolution=>({...resolution,surface:publicSurface(resolution.surface)}))})}function projectCrossSurfaceFinding(finding){return{...finding,source:{...finding.source,surface:publicSurface(finding.source.surface)},target:{...finding.target,surface:publicSurface(finding.target.surface)}}}function projectBranchRecord(body){let record=responseData(body),{env:_env,parentEnv:_parentEnv,...branch}=record;return branchResponseSchema.parse({data:branch})}function projectBranchList(body){if(!body||typeof body!="object"||!Array.isArray(body.data))throw new Error("Expected a Branch list response.");let data=body.data.map(({env:_env,parentEnv:_parentEnv,...branch})=>branch);return z87.object({data:z87.array(branchSchema)}).parse({data})}function projectBranchStatus(body){if(branchStatusOutputSchema.safeParse(body).success)return branchStatusOutputSchema.parse(body);let report=z87.object({branch:branchNameSchema.optional(),env:branchNameSchema,vs:branchNameSchema,syncState:z87.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:isoTimestampSchema,surfaces:z87.array(backendSurfaceDeltaSchema).max(6),crossSurface:z87.array(backendCrossSurfaceFindingSchema).max(1e3).optional()}).parse(responseData(body));return branchStatusOutputSchema.parse(withoutUndefined({branch:report.branch??report.env,against:report.vs,state:report.syncState==="in-sync"?"clean":"changed",syncState:report.syncState,generatedAt:report.generatedAt,surfaces:report.surfaces.map(({surface,status,changedCount,conflictCount,items,truncated,error})=>withoutUndefined({surface:publicSurface(surface),status,changedCount,conflictCount,items,truncated,error})),crossSurface:report.crossSurface?.map(projectCrossSurfaceFinding)}))}function projectBranchDiff(body){if(branchDiffOutputSchema.safeParse(body).success)return branchDiffOutputSchema.parse(body);let report=z87.object({fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),fromEnv:branchNameSchema,toEnv:branchNameSchema,generatedAt:isoTimestampSchema,fingerprint:z87.string().min(1),surfaces:z87.array(backendSurfaceDeltaSchema).max(6),crossSurface:z87.array(backendCrossSurfaceFindingSchema).max(1e3).optional()}).parse(responseData(body));return branchDiffOutputSchema.parse({branch:report.fromBranch??report.fromEnv,against:report.toBranch??report.toEnv,generatedAt:report.generatedAt,fingerprint:report.fingerprint,surfaces:report.surfaces.map(({surface,status,changedCount,conflictCount,truncated,items,error})=>({...withoutUndefined({surface:publicSurface(surface),status,changedCount,conflictCount,error}),truncated:truncated??!1,items:(items??[]).map(({origin:_origin,...item})=>item)})),crossSurface:report.crossSurface?.map(projectCrossSurfaceFinding)})}var branchSchema,branchResponseSchema,branchSurfaceStatusSchema,branchDeltaVerbSchema,isoTimestampSchema,backendCrossSurfaceFindingSchema,crossSurfaceFindingSchema,backendSurfaceDeltaSchema,branchSurfaceSummarySchema,branchStatusOutputSchema,branchDiffItemSchema,branchDiffOutputSchema,codeFileDiffOutputSchema,contentSnapshotSchema,contentEntryDiffOutputSchema,schemaSnapshotSchema,schemaDiffOutputSchema,assetSnapshotSchema,assetDiffOutputSchema,labelDiffOutputSchema,formSnapshotSchema,formDiffOutputSchema,backendConflictSchema,conflictSchema,fieldPickSchema,conflictResolutionSchema,mergeResultSchema,mergeHydrationSchema,codeConflictBlobSchema,codeConflictDetailOutputSchema,branchesOperations,init_branches=__esm({"../../packages/sdk/dist/operations/branches.js"(){"use strict";init_common2();branchSchema=z87.object({id:uuidSchema,projectId:uuidSchema,branch:branchNameSchema,parentBranch:branchNameSchema.nullable().optional(),status:z87.enum(["provisioning","active","deleted"]),kind:z87.enum(["user","agent-session"]),createdAt:z87.string().optional(),updatedAt:z87.string().optional(),createdBy:z87.string().nullable().optional(),deletedAt:z87.string().nullable().optional()}).passthrough(),branchResponseSchema=z87.object({data:branchSchema}),branchSurfaceStatusSchema=z87.enum(["ok","timed_out","failed","unchanged"]),branchDeltaVerbSchema=z87.enum(["added","removed","changed","conflict"]),isoTimestampSchema=z87.iso.datetime(),backendCrossSurfaceFindingSchema=z87.object({id:z87.string(),kind:z87.string(),description:z87.string(),severity:z87.enum(["warning","error"]),source:z87.object({surface:backendSurfaceSchema,key:z87.string()}),target:z87.object({surface:backendSurfaceSchema,key:z87.string()}),actions:z87.array(z87.enum(["restore-target","fix-source","ignore"])).min(1)}),crossSurfaceFindingSchema=backendCrossSurfaceFindingSchema.extend({source:backendCrossSurfaceFindingSchema.shape.source.extend({surface:branchSurfaceSchema}),target:backendCrossSurfaceFindingSchema.shape.target.extend({surface:branchSurfaceSchema})}),backendSurfaceDeltaSchema=z87.object({surface:backendSurfaceSchema,status:branchSurfaceStatusSchema,changedCount:z87.number().int().nonnegative(),conflictCount:z87.number().int().nonnegative(),items:z87.array(z87.object({verb:branchDeltaVerbSchema,key:z87.string(),detail:z87.string().optional(),origin:z87.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z87.record(z87.string(),z87.unknown()).optional()})).max(1e3).optional(),truncated:z87.boolean().optional(),error:z87.string().optional()}),branchSurfaceSummarySchema=z87.object({surface:branchSurfaceSchema,status:branchSurfaceStatusSchema,changedCount:z87.number().int().nonnegative(),conflictCount:z87.number().int().nonnegative(),error:z87.string().optional(),items:z87.array(z87.object({verb:branchDeltaVerbSchema,key:z87.string(),detail:z87.string().optional(),origin:z87.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z87.record(z87.string(),z87.unknown()).optional()})).optional(),truncated:z87.boolean().optional()}),branchStatusOutputSchema=z87.object({branch:branchNameSchema,against:branchNameSchema,state:z87.enum(["clean","changed"]),syncState:z87.enum(["in-sync","ahead","behind","diverged","unknown"]).optional(),generatedAt:isoTimestampSchema,surfaces:z87.array(branchSurfaceSummarySchema).max(6),crossSurface:z87.array(crossSurfaceFindingSchema).max(1e3).optional()}),branchDiffItemSchema=z87.object({verb:branchDeltaVerbSchema,key:z87.string(),detail:z87.string().optional(),meta:z87.record(z87.string(),z87.unknown()).optional()}),branchDiffOutputSchema=branchStatusOutputSchema.omit({state:!0}).extend({fingerprint:z87.string().min(1),surfaces:z87.array(branchSurfaceSummarySchema.extend({truncated:z87.boolean(),items:z87.array(branchDiffItemSchema).max(1e3)})).max(6)}),codeFileDiffOutputSchema=z87.object({path:z87.string(),state:z87.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z87.string(),additions:z87.number().int().nonnegative(),deletions:z87.number().int().nonnegative()}),contentSnapshotSchema=z87.object({id:z87.string(),slug:z87.string(),contentType:z87.string(),data:z87.record(z87.string(),z87.unknown()),updatedAt:isoTimestampSchema}),contentEntryDiffOutputSchema=z87.object({collection:z87.string(),rowId:z87.string(),parent:contentSnapshotSchema.nullable(),child:contentSnapshotSchema.nullable()}),schemaSnapshotSchema=z87.object({name:z87.string(),label:z87.string(),isSingleton:z87.boolean(),fields:z87.record(z87.string(),z87.unknown())}),schemaDiffOutputSchema=z87.object({typeName:z87.string(),parent:schemaSnapshotSchema.nullable(),child:schemaSnapshotSchema.nullable()}),assetSnapshotSchema=z87.object({id:z87.string(),name:z87.string(),type:z87.enum(["file","folder"]),mimeType:z87.string().nullable(),storageKey:z87.string().nullable(),url:z87.string().nullable(),fileSize:z87.number().nullable(),width:z87.number().nullable(),height:z87.number().nullable(),altText:z87.string().nullable(),caption:z87.string().nullable(),createdAt:isoTimestampSchema,updatedAt:isoTimestampSchema}),assetDiffOutputSchema=z87.object({assetId:z87.string(),parent:assetSnapshotSchema.nullable(),child:assetSnapshotSchema.nullable()}),labelDiffOutputSchema=z87.object({locale:z87.string(),key:z87.string(),parent:z87.string().nullable(),child:z87.string().nullable()}),formSnapshotSchema=z87.object({formName:z87.string(),label:z87.string().nullable(),schemaFingerprint:z87.string(),fields:z87.record(z87.string(),z87.unknown())}),formDiffOutputSchema=z87.object({formName:z87.string(),parent:formSnapshotSchema.nullable(),child:formSnapshotSchema.nullable()}),backendConflictSchema=z87.object({surface:backendSurfaceSchema,key:z87.string(),kind:z87.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"]).optional(),description:z87.string(),parentValue:z87.unknown().optional(),childValue:z87.unknown().optional(),conflictingFields:z87.array(z87.string()).optional(),code:z87.object({path:z87.string(),unresolvable:z87.boolean().optional(),reason:z87.string().optional()}).optional()}),conflictSchema=backendConflictSchema.extend({surface:branchSurfaceSchema}),fieldPickSchema=z87.object({field:z87.string(),choice:z87.enum(["parent","child","pick","ai-pick"]),pickedValue:z87.unknown().optional(),aiSessionId:z87.string().optional()}),conflictResolutionSchema=z87.object({surface:branchSurfaceSchema,key:z87.string(),choice:z87.enum(["parent","child","pick"]),pickedValue:z87.unknown().optional(),fieldPicks:z87.array(fieldPickSchema).optional()}),mergeResultSchema=z87.object({ok:z87.boolean(),mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,applied:z87.array(z87.object({surface:branchSurfaceSchema,count:z87.number().int().nonnegative()})),conflicts:z87.array(conflictSchema).optional(),summary:z87.string().optional()}),mergeHydrationSchema=z87.object({mergeId:uuidSchema,conflicts:z87.array(conflictSchema),draftResolutions:z87.array(conflictResolutionSchema),status:z87.string()}).passthrough();__name(projectConflict,"projectConflict");__name(backendResolution,"backendResolution");__name(projectMergeResult,"projectMergeResult");__name(projectMergeHydration,"projectMergeHydration");codeConflictBlobSchema=z87.object({content:z87.string(),sha:z87.string().nullable().optional()}).passthrough(),codeConflictDetailOutputSchema=z87.object({path:z87.string(),base:codeConflictBlobSchema.nullable(),ours:codeConflictBlobSchema.nullable(),theirs:codeConflictBlobSchema.nullable(),result:codeConflictBlobSchema}).passthrough();__name(projectCrossSurfaceFinding,"projectCrossSurfaceFinding");__name(projectBranchRecord,"projectBranchRecord");__name(projectBranchList,"projectBranchList");__name(projectBranchStatus,"projectBranchStatus");__name(projectBranchDiff,"projectBranchDiff");branchesOperations={"branches.list":{domain:"branches",summary:"List the durable Branches of a site.",accessScope:"read",effect:"read",inputSchema:z87.object({projectId:uuidSchema,includeDeleted:z87.boolean().optional(),includeAgentBranches:z87.boolean().optional()}).strict(),outputSchema:z87.object({data:z87.array(branchSchema)}),buildRequest:__name(({projectId,includeDeleted,includeAgentBranches})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/branches"),{includeDeleted:includeDeleted?!0:void 0,includeAgentEnvs:includeAgentBranches?!0:void 0})}),"buildRequest"),projectOutput:projectBranchList},"branches.create":{domain:"branches",summary:"Create a deliberate durable Branch for lasting parallel work.",accessScope:"code",effect:"mutation",inputSchema:z87.object({projectId:uuidSchema,from:branchNameSchema.optional(),name:branchNameSchema}).strict(),outputSchema:branchResponseSchema,buildRequest:__name(({projectId,from,name})=>({method:"POST",path:managementProjectPath(projectId,"/branches"),body:from===void 0?{branch:name}:{branch:name,parentBranch:from}}),"buildRequest"),projectOutput:projectBranchRecord},"branches.get":{domain:"branches",summary:"Read one durable site Branch.",accessScope:"read",effect:"read",inputSchema:z87.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:branchSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"")}),"buildRequest"),projectOutput:__name(body=>branchResponseSchema.parse(projectBranchRecord(body)).data,"projectOutput")},"branches.sync":{domain:"branches",summary:"Sync one durable Branch from its parent or another Branch.",accessScope:"code",effect:"mutation",inputSchema:z87.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema.optional()}).strict(),outputSchema:z87.object({branch:branchSchema,conflicts:z87.number().int().nonnegative()}),buildRequest:__name(({projectId,branch,from})=>({method:"POST",path:managementBranchPath(projectId,branch,"/sync"),body:withoutUndefined({from})}),"buildRequest"),projectOutput:__name(body=>{let data=z87.object({branch:branchSchema.optional(),env:branchSchema.optional(),conflicts:z87.number().int().nonnegative()}).parse(responseData(body)),branch=data.branch??data.env;if(!branch)throw new Error("Expected a synced Branch.");return{branch,conflicts:data.conflicts}},"projectOutput")},"branches.delete":{domain:"branches",summary:"Delete one durable site Branch.",accessScope:"code",effect:"mutation",inputSchema:z87.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:z87.unknown(),buildRequest:__name(({projectId,branch})=>({method:"DELETE",path:managementBranchPath(projectId,branch,"")}),"buildRequest")},"branches.status":{domain:"branches",summary:"Summarize bounded differences between two durable Branches.",accessScope:"read",effect:"read",inputSchema:z87.object({projectId:uuidSchema,branch:branchNameSchema,against:branchNameSchema.optional(),surfaces:z87.array(branchSurfaceSchema).min(1).max(6).optional()}).strict(),outputSchema:branchStatusOutputSchema,buildRequest:__name(({projectId,branch,against,surfaces})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/status"),{against,surfaces:backendSurfaces(surfaces)?.join(",")})}),"buildRequest"),projectOutput:projectBranchStatus},"branches.diff":{domain:"branches",summary:"List a bounded index of changes between two durable Branches.",accessScope:"read",effect:"read",inputSchema:z87.object({projectId:uuidSchema,branch:branchNameSchema,against:branchNameSchema.optional(),surfaces:z87.array(branchSurfaceSchema).min(1).max(6).optional()}).strict(),outputSchema:branchDiffOutputSchema,buildRequest:__name(({projectId,branch,against,surfaces})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/diff"),{against,surfaces:backendSurfaces(surfaces)?.join(",")})}),"buildRequest"),projectOutput:projectBranchDiff},"branches.diffCodeFile":{domain:"branches",summary:"Read the unified patch for one changed code file between durable Branches.",accessScope:"read",effect:"read",inputSchema:z87.object({projectId:uuidSchema,branch:branchNameSchema,path:z87.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:codeFileDiffOutputSchema,buildRequest:__name(({projectId,branch,path:path49,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/diff/code/file"),{path:path49,against})}),"buildRequest"),projectOutput:projectDetail(codeFileDiffOutputSchema)},"branches.diffContentEntry":{domain:"branches",summary:"Read both sides of one changed content entry between durable Branches.",accessScope:"read",effect:"read",inputSchema:z87.object({projectId:uuidSchema,branch:branchNameSchema,collection:z87.string().min(1),rowId:z87.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:contentEntryDiffOutputSchema,buildRequest:__name(({projectId,branch,collection,rowId,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`),{against})}),"buildRequest"),projectOutput:projectDetail(contentEntryDiffOutputSchema)},"branches.diffSchema":{domain:"branches",summary:"Read both sides of one changed content schema between durable Branches.",accessScope:"read",effect:"read",inputSchema:z87.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z87.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:schemaDiffOutputSchema,buildRequest:__name(({projectId,branch,typeName,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/schemas/${encodeURIComponent(typeName)}`),{against})}),"buildRequest"),projectOutput:projectDetail(schemaDiffOutputSchema)},"branches.diffAsset":{domain:"branches",summary:"Read both sides of one changed media asset between durable Branches.",accessScope:"read",effect:"read",inputSchema:z87.object({projectId:uuidSchema,branch:branchNameSchema,assetId:z87.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:assetDiffOutputSchema,buildRequest:__name(({projectId,branch,assetId,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/assets/${encodeURIComponent(assetId)}`),{against})}),"buildRequest"),projectOutput:projectDetail(assetDiffOutputSchema)},"branches.diffLabel":{domain:"branches",summary:"Read both sides of one changed localized label between durable Branches.",accessScope:"read",effect:"read",inputSchema:z87.object({projectId:uuidSchema,branch:branchNameSchema,locale:z87.string().min(1),key:z87.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:labelDiffOutputSchema,buildRequest:__name(({projectId,branch,locale,key,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`),{against})}),"buildRequest"),projectOutput:projectDetail(labelDiffOutputSchema)},"branches.diffForm":{domain:"branches",summary:"Read safe form definition fields from both sides of a durable Branch diff.",accessScope:"read",effect:"read",inputSchema:z87.object({projectId:uuidSchema,branch:branchNameSchema,formName:z87.string().min(1).max(255),against:branchNameSchema.optional()}).strict(),outputSchema:formDiffOutputSchema,buildRequest:__name(({projectId,branch,formName,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/forms/${encodeURIComponent(formName)}`),{against})}),"buildRequest"),projectOutput:projectDetail(formDiffOutputSchema)},"branches.merge":{domain:"branches",summary:"Merge one durable Branch into another.",accessScope:"code",effect:"mutation",inputSchema:z87.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,allowDirectMerge:z87.boolean().optional()}).strict(),outputSchema:mergeResultSchema,buildRequest:__name(({projectId,branch,from,allowDirectMerge})=>({method:"POST",path:managementBranchPath(projectId,branch,"/merge"),body:withoutUndefined({from,allowDirectMerge})}),"buildRequest"),projectOutput:projectMergeResult},"branches.resolveMerge":{domain:"branches",summary:"Resume a parked durable Branch merge with operator resolutions.",accessScope:"code",effect:"mutation",inputSchema:z87.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,mergeId:uuidSchema,resolutions:z87.array(conflictResolutionSchema)}).strict(),outputSchema:mergeResultSchema,buildRequest:__name(({projectId,branch,from,mergeId,resolutions})=>({method:"POST",path:managementBranchPath(projectId,branch,`/merge/${encodeURIComponent(from)}/resolve`),body:{mergeId,resolutions:resolutions.map(backendResolution)}}),"buildRequest"),projectOutput:projectMergeResult},"branches.cancelMerge":{domain:"branches",summary:"Cancel a parked durable Branch merge.",accessScope:"code",effect:"mutation",inputSchema:z87.object({projectId:uuidSchema,branch:branchNameSchema,mergeId:uuidSchema}).strict(),outputSchema:z87.object({ok:z87.boolean()}),buildRequest:__name(({projectId,branch,mergeId})=>({method:"POST",path:managementBranchPath(projectId,branch,"/merge/cancel"),body:{mergeId}}),"buildRequest"),projectOutput:__name(body=>z87.object({ok:z87.boolean()}).parse(responseData(body)),"projectOutput")},"branches.mergeConflicts":{domain:"branches",summary:"Read conflicts and saved resolutions for a parked durable Branch merge.",accessScope:"read",effect:"read",inputSchema:z87.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema}).strict(),outputSchema:mergeHydrationSchema,buildRequest:__name(({projectId,branch,from})=>({method:"GET",path:managementBranchPath(projectId,branch,`/merge/${encodeURIComponent(from)}/conflicts`)}),"buildRequest"),projectOutput:projectMergeHydration},"branches.saveMergeDraft":{domain:"branches",summary:"Save in-progress resolutions for a parked durable Branch merge.",accessScope:"code",effect:"mutation",inputSchema:z87.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,mergeId:uuidSchema,resolutions:z87.array(conflictResolutionSchema)}).strict(),outputSchema:z87.object({mergeId:uuidSchema,lastEditedAt:z87.string()}),buildRequest:__name(({projectId,branch,from,mergeId,resolutions})=>({method:"PUT",path:managementBranchPath(projectId,branch,`/merge/${encodeURIComponent(from)}/resolve/draft`),body:{mergeId,resolutions:resolutions.map(backendResolution)}}),"buildRequest"),projectOutput:__name(body=>z87.object({mergeId:uuidSchema,lastEditedAt:z87.string()}).parse(responseData(body)),"projectOutput")},"branches.codeConflict":{domain:"branches",summary:"Read three-way code detail for one conflicted merge path.",accessScope:"read",effect:"read",inputSchema:z87.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,path:z87.string().min(1)}).strict(),outputSchema:codeConflictDetailOutputSchema,buildRequest:__name(({projectId,branch,from,path:path49})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/merge/${encodeURIComponent(from)}/conflict/code`),{path:path49})}),"buildRequest"),projectOutput:projectDetail(codeConflictDetailOutputSchema)}}}});import{z as z88}from"zod";var projectDomainSchema,registeredDomainSchema,domainSearchResultSchema,domainPricingSchema,projectPath,forbidden,domainsOperations,init_domains=__esm({"../../packages/sdk/dist/operations/domains.js"(){"use strict";init_common2();projectDomainSchema=z88.object({id:z88.string(),hostname:z88.string(),status:z88.string(),ssl:z88.record(z88.string(),z88.unknown()),cnameTarget:z88.string(),apexTargets:z88.array(z88.string()),dnsAutoConfigured:z88.boolean(),createdAt:z88.unknown(),provider:z88.enum(["cloudflare","saas_custom_domains"]),domainType:z88.enum(["subdomain","apex"])}).passthrough(),registeredDomainSchema=z88.object({id:uuidSchema,domain:z88.string(),status:z88.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),source:z88.enum(["fimo","external"]),autoRenew:z88.boolean(),paymentStatus:z88.enum(["pending","paid","failed","refunded"]).nullable(),checkoutUrl:z88.string().nullable()}).passthrough(),domainSearchResultSchema=z88.object({domain:z88.string(),available:z88.boolean(),premium:z88.boolean(),price:z88.number().nullable(),renewalPrice:z88.number().nullable(),purchaseType:z88.string().nullable()}).passthrough(),domainPricingSchema=z88.object({domain:z88.string(),price:z88.number().nullable(),renewalPrice:z88.number().nullable(),premium:z88.boolean(),allowedYears:z88.array(z88.number().int().positive())}).passthrough(),projectPath=__name((projectId,suffix)=>`/management/projects/${encodeURIComponent(projectId)}${suffix}`,"projectPath"),forbidden={preserveForbidden:!0},domainsOperations={"domains.features":{domain:"domains",summary:"Read domain-purchasing feature availability and the publication domain.",accessScope:"read",effect:"read",inputSchema:z88.object({}).strict(),outputSchema:z88.object({domainPurchaseEnabled:z88.boolean(),publicationDomain:z88.string()}),buildRequest:__name(()=>({method:"GET",path:"/features"}),"buildRequest")},"domains.renameSubdomain":{domain:"domains",summary:"Change the built-in subdomain for a site.",accessScope:"write",effect:"mutation",inputSchema:z88.object({projectId:uuidSchema,slug:z88.string().min(1).max(63)}).strict(),outputSchema:z88.object({subdomain:z88.string(),subdomainUpdatedAt:z88.string()}),buildRequest:__name(({projectId,slug})=>({method:"PATCH",path:projectPath(projectId,"/subdomain"),body:{slug}}),"buildRequest"),projectOutput:responseData},"domains.suggestSubdomains":{domain:"domains",summary:"Suggest available built-in subdomains for a site.",accessScope:"read",effect:"read",inputSchema:z88.object({projectId:uuidSchema,base:z88.string().min(1).max(63).optional(),max:z88.number().int().positive().optional()}).strict(),outputSchema:z88.array(z88.string()),buildRequest:__name(({projectId,base,max})=>({method:"GET",path:addQuery(projectPath(projectId,"/subdomain/suggestions"),{base,max})}),"buildRequest"),projectOutput:__name(body=>z88.object({data:z88.object({suggestions:z88.array(z88.string())})}).parse(body).data.suggestions,"projectOutput")},"domains.list":{domain:"domains",summary:"List custom domains attached to a site.",accessScope:"read",effect:"read",inputSchema:z88.object({projectId:uuidSchema}).strict(),outputSchema:z88.array(projectDomainSchema),buildRequest:__name(({projectId})=>({method:"GET",path:projectPath(projectId,"/domains"),...forbidden}),"buildRequest"),projectOutput:responseData},"domains.add":{domain:"domains",summary:"Attach a custom domain to a site.",accessScope:"write",effect:"mutation",inputSchema:z88.object({projectId:uuidSchema,hostname:z88.string().min(1).max(255),redirectToWww:z88.boolean().optional()}).strict(),outputSchema:projectDomainSchema,buildRequest:__name(({projectId,hostname,redirectToWww})=>({method:"POST",path:projectPath(projectId,"/domains"),body:{hostname,redirectToWww},...forbidden}),"buildRequest"),projectOutput:responseData},"domains.refresh":{domain:"domains",summary:"Refresh custom-domain verification state.",accessScope:"write",effect:"mutation",inputSchema:z88.object({projectId:uuidSchema,domainId:z88.string().min(1)}).strict(),outputSchema:projectDomainSchema,buildRequest:__name(({projectId,domainId})=>({method:"POST",path:projectPath(projectId,`/domains/${encodeURIComponent(domainId)}/refresh`),...forbidden}),"buildRequest"),projectOutput:responseData},"domains.remove":{domain:"domains",summary:"Detach a custom domain from a site.",accessScope:"write",effect:"mutation",inputSchema:z88.object({projectId:uuidSchema,domainId:z88.string().min(1)}).strict(),outputSchema:z88.unknown(),buildRequest:__name(({projectId,domainId})=>({method:"DELETE",path:projectPath(projectId,`/domains/${encodeURIComponent(domainId)}`),...forbidden}),"buildRequest")},"registeredDomains.search":{domain:"domains",summary:"Search domain-registration availability.",accessScope:"read",effect:"read",inputSchema:z88.object({keyword:z88.string().min(1).max(100),tldFilter:z88.array(z88.string().min(1)).optional()}).strict(),outputSchema:z88.array(domainSearchResultSchema),buildRequest:__name(({keyword,tldFilter})=>({method:"POST",path:"/domains/search",body:{keyword,tldFilter},...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.pricing":{domain:"domains",summary:"Read registration pricing for a domain.",accessScope:"read",effect:"read",inputSchema:z88.object({domain:z88.string().min(1).max(255)}).strict(),outputSchema:domainPricingSchema,buildRequest:__name(({domain})=>({method:"GET",path:`/domains/pricing/${encodeURIComponent(domain)}`,...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.list":{domain:"domains",summary:"List domains owned by an organization.",accessScope:"read",effect:"read",inputSchema:z88.object({organizationId:z88.string().min(1)}).strict(),outputSchema:z88.array(registeredDomainSchema),buildRequest:__name(({organizationId})=>({method:"GET",path:`/domains/${encodeURIComponent(organizationId)}`,...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.purchase":{domain:"domains",summary:"Purchase and register a domain for an organization.",accessScope:"write",effect:"mutation",inputSchema:z88.object({organizationId:z88.string().min(1),domain:z88.string().min(1).max(255),years:z88.number().int().min(1).max(10).optional(),autoRenew:z88.boolean().optional()}).strict(),outputSchema:registeredDomainSchema,buildRequest:__name(({organizationId,domain,years,autoRenew})=>({method:"POST",path:`/domains/${encodeURIComponent(organizationId)}/purchase`,body:{domain,years,autoRenew},...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.refreshPayment":{domain:"domains",summary:"Refresh the payment state of a registered-domain purchase.",accessScope:"write",effect:"mutation",inputSchema:z88.object({organizationId:z88.string().min(1),domainId:uuidSchema}).strict(),outputSchema:registeredDomainSchema,buildRequest:__name(({organizationId,domainId})=>({method:"POST",path:`/domains/${encodeURIComponent(organizationId)}/${encodeURIComponent(domainId)}/refresh-payment`,...forbidden}),"buildRequest"),projectOutput:responseData}}}});import{z as z89}from"zod";function projectEntriesPage(body){return projectOffsetPage(PaginatedEntriesDTOSchema2.parse(body))}var EntryDTOSchema2,PaginatedEntriesDTOSchema2,EntryResponseSchema2,MAX_BULK_ENTRIES2,entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2,EntryWhereSchema2,EntryMutationBodySchema2,BulkCreateEntriesResponseSchema2,BulkUpdateEntriesResponseSchema2,BulkDeleteEntriesResponseSchema2,entriesPageSchema,typeNameSchema,localeSchema,populateSchema,entryDataSchema,entryResponseSchema,entriesOperations,init_entries=__esm({"../../packages/sdk/dist/operations/entries.js"(){"use strict";init_common2();EntryDTOSchema2=z89.object({id:z89.string(),entryId:z89.string(),documentId:z89.string(),slug:z89.string(),locale:z89.string().optional(),createdAt:z89.string(),updatedAt:z89.string(),__fimo:z89.object({contentType:z89.string()})}).passthrough(),PaginatedEntriesDTOSchema2=z89.object({data:z89.array(EntryDTOSchema2),meta:z89.object({limit:z89.number(),offset:z89.number(),total:z89.number(),hasMore:z89.boolean()})}),EntryResponseSchema2=createResponseSchema2(EntryDTOSchema2),MAX_BULK_ENTRIES2=1e3,entryWhereScalarSchema2=z89.union([z89.string(),z89.number(),z89.boolean(),z89.null()]),entryWhereOperatorSchema2=z89.object({$eq:entryWhereScalarSchema2.optional(),$ne:entryWhereScalarSchema2.optional(),$gt:entryWhereScalarSchema2.optional(),$gte:entryWhereScalarSchema2.optional(),$lt:entryWhereScalarSchema2.optional(),$lte:entryWhereScalarSchema2.optional(),$in:z89.array(entryWhereScalarSchema2).optional(),$nin:z89.array(entryWhereScalarSchema2).optional(),$contains:z89.string().optional(),$startsWith:z89.string().optional(),$null:z89.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema2=z89.record(z89.string(),z89.union([entryWhereScalarSchema2,entryWhereOperatorSchema2])),EntryWhereSchema2=z89.record(z89.string(),z89.union([entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2])),EntryMutationBodySchema2=z89.object({data:z89.record(z89.string(),z89.unknown()),locale:z89.string().min(1).optional(),documentId:z89.uuid().optional()}),BulkCreateEntriesResponseSchema2=z89.object({data:z89.array(EntryDTOSchema2),meta:z89.object({created:z89.number().int().nonnegative()})}),BulkUpdateEntriesResponseSchema2=z89.object({data:z89.array(EntryDTOSchema2),meta:z89.object({updated:z89.number().int().nonnegative(),missing:z89.array(z89.string())})}),BulkDeleteEntriesResponseSchema2=z89.object({data:z89.array(EntryDTOSchema2),meta:z89.object({deleted:z89.number().int().nonnegative(),missing:z89.array(z89.string())})});__name(projectEntriesPage,"projectEntriesPage");entriesPageSchema=pageSchema(EntryDTOSchema2),typeNameSchema=z89.string().min(1).max(255),localeSchema=z89.string().min(1),populateSchema=z89.array(z89.string().min(1)).max(50).optional(),entryDataSchema=EntryMutationBodySchema2.shape.data,entryResponseSchema=EntryResponseSchema2,entriesOperations={"entries.list":{domain:"entries",summary:"List entries for one content type on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z89.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,locale:localeSchema.optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:entriesPageSchema,buildRequest:__name(({projectId,branch,typeName,locale,limit,cursor,offset})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}`),{locale,limit,offset:paginationOffset({cursor,offset})})}),"buildRequest"),projectOutput:projectEntriesPage},"entries.get":{domain:"entries",summary:"Read one entry by ID from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z89.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional(),populate:populateSchema,localeFallbacks:z89.boolean().optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,id,locale,populate,localeFallbacks})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale,populate,localeFallbacks})}),"buildRequest")},"entries.search":{domain:"entries",summary:"Search entries across content types on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z89.object({projectId:uuidSchema,branch:branchNameSchema,search:z89.string().min(1).optional(),locale:localeSchema.optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:entriesPageSchema,buildRequest:__name(({projectId,branch,search,locale,limit,cursor,offset})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,"/entries"),{search,locale,limit,offset:paginationOffset({cursor,offset})})}),"buildRequest"),projectOutput:projectEntriesPage},"entries.create":{domain:"entries",summary:"Create one entry of a content type on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z89.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z89.string().min(1).max(255),data:entryDataSchema,locale:z89.string().min(1).optional(),documentId:z89.string().min(1).optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,data,locale,documentId})=>({method:"POST",path:tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}`),body:{data,locale,documentId}}),"buildRequest")},"entries.update":{domain:"entries",summary:"Update one entry of a content type on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z89.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z89.string().min(1).max(255),id:uuidSchema,data:entryDataSchema,locale:z89.string().min(1).optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,id,data,locale})=>({method:"PUT",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale}),body:{data}}),"buildRequest")},"entries.updateFields":{domain:"entries",summary:"Update entry fields using the direct Branch entry payload.",accessScope:"write",effect:"mutation",inputSchema:z89.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional(),fields:z89.record(z89.string(),z89.unknown())}).strict(),outputSchema:z89.unknown(),buildRequest:__name(({projectId,branch,typeName,id,locale,fields})=>({method:"PUT",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale}),body:fields}),"buildRequest"),projectOutput:__name(body=>z89.object({data:z89.unknown()}).parse(body).data,"projectOutput")},"entries.querySql":{domain:"entries",summary:"Run a read-only SQL query against Branch content.",accessScope:"read",effect:"read",inputSchema:z89.object({projectId:uuidSchema,branch:branchNameSchema,sql:z89.string().min(1)}).strict(),outputSchema:z89.object({data:z89.array(z89.record(z89.string(),z89.unknown())),meta:z89.object({rowCount:z89.number().int().nonnegative(),truncated:z89.boolean()})}),buildRequest:__name(({projectId,branch,sql})=>({method:"POST",path:tenantPath(projectId,branch,"/entries/query"),body:{sql}}),"buildRequest")},"entries.delete":{domain:"entries",summary:"Delete one entry by ID from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z89.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,id,locale})=>({method:"DELETE",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale})}),"buildRequest")},"entries.bulkCreate":{domain:"entries",summary:`Create up to ${MAX_BULK_ENTRIES2} entries of one content type on a Fimo Branch.`,accessScope:"write",effect:"mutation",inputSchema:z89.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,entries:z89.array(z89.unknown()).max(MAX_BULK_ENTRIES2)}).strict(),outputSchema:BulkCreateEntriesResponseSchema2,buildRequest:__name(({projectId,branch,typeName,entries:entries2})=>({method:"POST",path:tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/bulk-create`),body:{entries:entries2}}),"buildRequest")},"entries.bulkUpdate":{domain:"entries",summary:`Update up to ${MAX_BULK_ENTRIES2} entries by IDs, a bounded filter, or per-entry updates.`,accessScope:"write",effect:"mutation",inputSchema:z89.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,selection:z89.union([z89.object({ids:z89.array(uuidSchema).min(1).max(MAX_BULK_ENTRIES2)}),z89.object({where:EntryWhereSchema2}),z89.object({updates:z89.array(z89.object({id:uuidSchema,body:EntryMutationBodySchema2})).min(1).max(MAX_BULK_ENTRIES2)})]),body:EntryMutationBodySchema2.optional()}).strict().superRefine((input,context)=>{let perEntry="updates"in input.selection;perEntry&&input.body!==void 0&&context.addIssue({code:"custom",message:"Do not pass body with per-entry updates.",path:["body"]}),!perEntry&&input.body===void 0&&context.addIssue({code:"custom",message:"Pass body with ids or where selections.",path:["body"]})}),outputSchema:BulkUpdateEntriesResponseSchema2,buildRequest:__name(({projectId,branch,typeName,selection,body})=>({method:"POST",path:tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/bulk-update`),body:"updates"in selection?selection:{...selection,body}}),"buildRequest")},"entries.bulkDelete":{domain:"entries",summary:`Delete up to ${MAX_BULK_ENTRIES2} entries by IDs or a bounded filter.`,accessScope:"write",effect:"mutation",inputSchema:z89.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,selection:z89.union([z89.object({ids:z89.array(uuidSchema).min(1).max(MAX_BULK_ENTRIES2)}),z89.object({where:EntryWhereSchema2})]),locale:localeSchema.optional()}).strict(),outputSchema:BulkDeleteEntriesResponseSchema2,buildRequest:__name(({projectId,branch,typeName,selection,locale})=>({method:"POST",path:tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/bulk-delete`),body:{...selection,locale}}),"buildRequest")}}}});import{z as z90}from"zod";var productionEnvironmentSchema,previewEnvironmentSchema,customEnvironmentSchema,environmentSchema,environmentWriteShape,environmentsOperations,init_environments=__esm({"../../packages/sdk/dist/operations/environments.js"(){"use strict";init_common2();productionEnvironmentSchema=z90.object({id:z90.literal("production"),projectId:uuidSchema,name:z90.string(),kind:z90.literal("production"),sourceBranch:z90.string().min(1),isPublished:z90.boolean(),url:z90.string().nullable()}),previewEnvironmentSchema=z90.object({id:z90.literal("preview"),projectId:uuidSchema,name:z90.string(),kind:z90.literal("preview"),matchedBranchCount:z90.number().int().nonnegative()}),customEnvironmentSchema=z90.object({id:uuidSchema,projectId:uuidSchema,name:z90.string().min(1).max(64),branchPatterns:z90.array(z90.string().min(1).max(255)).min(1),description:z90.string().max(255).nullable(),kind:z90.literal("custom"),matchedBranchCount:z90.number().int().nonnegative()}),environmentSchema=z90.discriminatedUnion("kind",[productionEnvironmentSchema,previewEnvironmentSchema,customEnvironmentSchema]),environmentWriteShape={name:z90.string().trim().min(1).max(64),branchPatterns:z90.array(z90.string().min(1).max(255)).min(1),description:z90.string().trim().max(255).nullable().optional()},environmentsOperations={"environments.list":{domain:"environments",summary:"List the compatibility Environments configured for one site.",accessScope:"read",effect:"read",inputSchema:z90.object({projectId:uuidSchema}).strict(),outputSchema:z90.array(environmentSchema),buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/environments")}),"buildRequest"),projectOutput:__name(body=>z90.array(environmentSchema).parse(responseData(body)),"projectOutput")},"environments.create":{domain:"environments",summary:"Create a custom compatibility Environment for one site.",accessScope:"write",effect:"mutation",inputSchema:z90.object({projectId:uuidSchema,...environmentWriteShape}).strict(),outputSchema:environmentSchema,buildRequest:__name(({projectId,...body})=>({method:"POST",path:managementProjectPath(projectId,"/environments"),body,preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>environmentSchema.parse(responseData(body)),"projectOutput")},"environments.update":{domain:"environments",summary:"Update one custom compatibility Environment.",accessScope:"write",effect:"mutation",inputSchema:z90.object({projectId:uuidSchema,environmentId:z90.string().min(1),...environmentWriteShape}).strict(),outputSchema:environmentSchema,buildRequest:__name(({projectId,environmentId,...body})=>({method:"PATCH",path:managementProjectPath(projectId,`/environments/${encodeURIComponent(environmentId)}`),body,preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>environmentSchema.parse(responseData(body)),"projectOutput")},"environments.delete":{domain:"environments",summary:"Delete one custom compatibility Environment.",accessScope:"write",effect:"mutation",inputSchema:z90.object({projectId:uuidSchema,environmentId:z90.string().min(1)}).strict(),outputSchema:z90.object({deletedId:uuidSchema}),buildRequest:__name(({projectId,environmentId})=>({method:"DELETE",path:managementProjectPath(projectId,`/environments/${encodeURIComponent(environmentId)}`),preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>z90.object({deletedId:uuidSchema}).parse(responseData(body)),"projectOutput")}}}});import{z as z91}from"zod";function requireBranchOrSession(input,context){!input.branch&&!input.sessionId&&context.addIssue({code:"custom",message:"Pass branch or sessionId.",path:["branch"]}),input.branch&&input.sessionId&&context.addIssue({code:"custom",message:"Pass branch or sessionId, not both.",path:["branch"]})}var fileReadOutputSchema,fileGlobOutputSchema,fileGrepOutputSchema,fileWriteInputSchema,fileEditInputSchema,fileWriteOutputSchema,fileWriteManyInputSchema,fileWriteManyOutputSchema,fileEditOutputSchema,fileDeleteOutputSchema,fileSearchInputShape,fileReadInputSchema,filesOperations,init_files=__esm({"../../packages/sdk/dist/operations/files.js"(){"use strict";init_common2();fileReadOutputSchema=z91.object({data:z91.object({path:z91.string(),content:z91.string(),totalLines:z91.number().int().nonnegative()}).passthrough()}),fileGlobOutputSchema=z91.object({data:z91.object({paths:z91.array(z91.string().min(1)).max(2e3),truncated:z91.boolean()})}),fileGrepOutputSchema=z91.object({data:z91.object({matches:z91.array(z91.object({path:z91.string().min(1),line:z91.number().int().positive(),text:z91.string()})).max(200),truncated:z91.boolean()})}),fileWriteInputSchema=z91.object({projectId:uuidSchema,sessionId:uuidSchema,path:z91.string().min(1).max(1024),content:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES2,`Content exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES2}-byte write limit.`),overwrite:z91.boolean().optional()}).strict(),fileEditInputSchema=z91.object({projectId:uuidSchema,sessionId:uuidSchema,path:z91.string().min(1).max(1024),oldString:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES2,`Text exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES2}-byte edit limit.`).min(1),newString:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES2,`Text exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES2}-byte edit limit.`),replaceAll:z91.boolean().optional()}).strict(),fileWriteOutputSchema=sessionEnvelopeSchema.extend({file:z91.object({path:z91.string(),created:z91.boolean(),tip:z91.string().min(1)}).passthrough()}),fileWriteManyInputSchema=z91.object({projectId:uuidSchema,sessionId:uuidSchema,files:z91.array(z91.object({path:z91.string().min(1).max(1024),content:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES2,`Content exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES2}-byte write limit.`)}).strict()).min(1).max(PROJECT_FILE_WRITE_MANY_MAX_FILES).refine(files=>files.reduce((total,file)=>total+new TextEncoder().encode(file.content).byteLength,0)<=PROJECT_FILE_WRITE_MANY_LIMIT_BYTES,`Files exceed the ${PROJECT_FILE_WRITE_MANY_LIMIT_BYTES}-byte total write limit.`)}).strict(),fileWriteManyOutputSchema=sessionEnvelopeSchema.extend({files:z91.array(z91.object({path:z91.string(),created:z91.boolean()}).passthrough()),tip:z91.string().min(1)}),fileEditOutputSchema=sessionEnvelopeSchema.extend({file:z91.object({path:z91.string(),replacements:z91.number().int().nonnegative(),tip:z91.string().min(1)}).passthrough()}),fileDeleteOutputSchema=sessionEnvelopeSchema.extend({file:z91.object({path:z91.string(),deleted:z91.literal(!0),tip:z91.string().min(1)})}),fileSearchInputShape={projectId:uuidSchema,branch:branchNameSchema.optional(),sessionId:uuidSchema.optional()};__name(requireBranchOrSession,"requireBranchOrSession");fileReadInputSchema=z91.object({projectId:uuidSchema,branch:branchNameSchema.optional(),sessionId:uuidSchema.optional(),path:z91.string().min(1).max(1024)}).superRefine(requireBranchOrSession),filesOperations={"files.read":{domain:"files",summary:"Read one safe text file from a Branch or owned work session.",accessScope:"read",effect:"read",inputSchema:fileReadInputSchema,outputSchema:fileReadOutputSchema,buildRequest:__name(({projectId,branch,sessionId,path:path49})=>({method:"GET",path:addQuery(projectFilesPath(projectId,branch,sessionId,"/file"),{path:path49})}),"buildRequest")},"files.glob":{domain:"files",summary:"List bounded safe site file paths from a Branch or owned work session.",accessScope:"read",effect:"read",inputSchema:z91.object({...fileSearchInputShape,pattern:z91.string().min(1).max(300).optional(),limit:z91.number().int().min(1).max(2e3).optional()}).strict().superRefine(requireBranchOrSession),outputSchema:fileGlobOutputSchema,buildRequest:__name(({projectId,branch,sessionId,pattern,limit})=>({method:"GET",path:addQuery(projectFilesPath(projectId,branch,sessionId,"/paths"),{pattern,limit})}),"buildRequest")},"files.grep":{domain:"files",summary:"Search bounded safe site file contents on a Branch or owned work session.",accessScope:"read",effect:"read",inputSchema:z91.object({...fileSearchInputShape,pattern:z91.string().min(1).max(200),include:z91.string().min(1).max(300).optional(),caseInsensitive:z91.boolean().optional(),maxMatches:z91.number().int().min(1).max(200).optional()}).strict().superRefine(requireBranchOrSession),outputSchema:fileGrepOutputSchema,buildRequest:__name(({projectId,branch,sessionId,pattern,include,caseInsensitive,maxMatches})=>({method:"GET",path:addQuery(projectFilesPath(projectId,branch,sessionId,"/grep"),{pattern,include,caseInsensitive,maxMatches})}),"buildRequest")},"files.write":{domain:"files",summary:"Create or overwrite one safe text file in an owned work session.",accessScope:"code",effect:"mutation",inputSchema:fileWriteInputSchema,outputSchema:fileWriteOutputSchema,buildRequest:__name(({projectId,sessionId,path:path49,content:content2,overwrite})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/write`),body:withoutUndefined({path:path49,content:content2,overwrite})}),"buildRequest")},"files.writeMany":{domain:"files",summary:"Create or overwrite several safe text files in an owned work session as one saved change.",accessScope:"code",effect:"mutation",inputSchema:fileWriteManyInputSchema,outputSchema:fileWriteManyOutputSchema,buildRequest:__name(({projectId,sessionId,files})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/write-many`),body:{files}}),"buildRequest")},"files.edit":{domain:"files",summary:"Replace exact text in one safe file in an owned work session.",accessScope:"code",effect:"mutation",inputSchema:fileEditInputSchema,outputSchema:fileEditOutputSchema,buildRequest:__name(({projectId,sessionId,path:path49,oldString,newString,replaceAll})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/edit`),body:withoutUndefined({path:path49,oldString,newString,replaceAll})}),"buildRequest")},"files.delete":{domain:"files",summary:"Delete one safe site file in an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z91.object({projectId:uuidSchema,sessionId:uuidSchema,path:z91.string().min(1).max(1024)}).strict(),outputSchema:fileDeleteOutputSchema,buildRequest:__name(({projectId,sessionId,path:path49})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/delete`),body:{path:path49}}),"buildRequest")}}}});import{z as z92}from"zod";function projectFormResponse(body){return formResponseSchema.parse(body)}function projectFormDetail(body){return formResponseSchema.parse(body).data}function projectFormList(body){return z92.object({data:z92.array(formSchema)}).parse(body).data}function projectFormSubmissionsPage(body,input){let page=z92.object({data:z92.array(formSubmissionSchema),total:z92.number().int().nonnegative()}).parse(body),offset=paginationOffset(input)??0;if(page.data.length===0&&offset<page.total)throw new Error("Expected a page that advances the cursor.");return{items:page.data,nextCursor:offset+page.data.length<page.total?encodePaginationCursor(offset+page.data.length):null,total:page.total}}var formFieldSchema,FormContentSchema2,FormUpdateSchema2,rawFormSchema,formSchema,formResponseSchema,formSubmissionSchema,formSubmissionResponseSchema,formSubmissionsPageSchema,formSubmissionStatsResponseSchema,formsOperations,init_forms=__esm({"../../packages/sdk/dist/operations/forms.js"(){"use strict";init_common2();formFieldSchema=z92.object({type:z92.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),label:z92.string(),placeholder:z92.string().optional(),required:z92.boolean().optional(),defaultValue:z92.string().optional(),options:z92.array(z92.string()).optional(),validation:z92.object({minLength:z92.number().optional(),maxLength:z92.number().optional(),min:z92.number().optional(),max:z92.number().optional(),pattern:z92.string().optional(),maxFileSize:z92.number().optional(),accept:z92.array(z92.string()).optional()}).optional()}),FormContentSchema2=z92.object({name:z92.string().min(1).max(255),label:z92.string().min(1).max(255),fields:z92.record(z92.string(),formFieldSchema)}).strict(),FormUpdateSchema2=FormContentSchema2.partial().refine(update=>update.name!==void 0||update.label!==void 0||update.fields!==void 0,{message:"Pass at least one of name, label, or fields."}),rawFormSchema=z92.object({id:uuidSchema,name:FormContentSchema2.shape.name,label:FormContentSchema2.shape.label,fields:FormContentSchema2.shape.fields,settings:z92.record(z92.string(),z92.unknown()).nullable().optional(),createdAt:z92.string(),updatedAt:z92.string()}).passthrough(),formSchema=rawFormSchema,formResponseSchema=z92.object({data:formSchema}),formSubmissionSchema=z92.object({id:uuidSchema,formId:uuidSchema,projectId:uuidSchema,branch:branchNameSchema,data:z92.record(z92.string(),z92.unknown()),submittedAt:z92.string()}),formSubmissionResponseSchema=z92.object({data:formSubmissionSchema}),formSubmissionsPageSchema=pageSchema(formSubmissionSchema),formSubmissionStatsResponseSchema=z92.object({data:z92.object({total:z92.number().int().nonnegative(),dailyCounts:z92.array(z92.object({date:z92.string(),count:z92.number().int().nonnegative()}))})});__name(projectFormResponse,"projectFormResponse");__name(projectFormDetail,"projectFormDetail");__name(projectFormList,"projectFormList");__name(projectFormSubmissionsPage,"projectFormSubmissionsPage");formsOperations={"forms.list":{domain:"forms",summary:"List form definitions on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z92.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:z92.array(formSchema),buildRequest:__name(({projectId,branch})=>({method:"GET",path:tenantPath(projectId,branch,"/forms")}),"buildRequest"),projectOutput:projectFormList},"forms.get":{domain:"forms",summary:"Read one form definition from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z92.object({projectId:uuidSchema,branch:branchNameSchema,id:z92.string().min(1).max(255)}).strict(),outputSchema:formSchema,buildRequest:__name(({projectId,branch,id})=>({method:"GET",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}`)}),"buildRequest"),projectOutput:projectFormDetail},"forms.create":{domain:"forms",summary:"Create a form definition on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z92.object({projectId:uuidSchema,branch:branchNameSchema,...FormContentSchema2.shape}).strict(),outputSchema:formResponseSchema,buildRequest:__name(({projectId,branch,name,label,fields})=>({method:"POST",path:tenantPath(projectId,branch,"/forms"),body:{name,label,fields}}),"buildRequest"),projectOutput:projectFormResponse},"forms.update":{domain:"forms",summary:"Update the name, label, or fields of one form definition.",accessScope:"write",effect:"mutation",inputSchema:z92.object({projectId:uuidSchema,branch:branchNameSchema,id:z92.string().min(1).max(255),...FormContentSchema2.partial().shape}).strict().superRefine((input,context)=>{let update=FormUpdateSchema2.safeParse({name:input.name,label:input.label,fields:input.fields});if(!update.success)for(let issue of update.error.issues)context.addIssue({...issue,path:issue.path})}),outputSchema:formResponseSchema,buildRequest:__name(({projectId,branch,id,name,label,fields})=>({method:"PUT",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}`),body:{name,label,fields}}),"buildRequest"),projectOutput:projectFormResponse},"forms.delete":{domain:"forms",summary:"Delete one form definition from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z92.object({projectId:uuidSchema,branch:branchNameSchema,id:z92.string().min(1).max(255)}).strict(),outputSchema:formResponseSchema,buildRequest:__name(({projectId,branch,id})=>({method:"DELETE",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}`)}),"buildRequest"),projectOutput:projectFormResponse},"forms.listSubmissions":{domain:"forms",summary:"List submissions for one form with cursor pagination.",accessScope:"read",effect:"read",inputSchema:z92.object({projectId:uuidSchema,branch:branchNameSchema,id:z92.string().min(1).max(255),...paginationShape,searchQuery:z92.string().max(200).optional(),sortDirection:z92.enum(["asc","desc"]).optional()}).strict().superRefine(paginationRefinement),outputSchema:formSubmissionsPageSchema,buildRequest:__name(({projectId,branch,id,limit,cursor,offset,searchQuery,sortDirection})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}/submissions`),{limit,offset:paginationOffset({cursor,offset}),searchQuery,sortDirection})}),"buildRequest"),projectOutput:projectFormSubmissionsPage},"forms.getSubmission":{domain:"forms",summary:"Read one submission for a form.",accessScope:"read",effect:"read",inputSchema:z92.object({projectId:uuidSchema,branch:branchNameSchema,id:z92.string().min(1).max(255),submissionId:z92.string().min(1).max(255)}).strict(),outputSchema:formSubmissionSchema,buildRequest:__name(({projectId,branch,id,submissionId})=>({method:"GET",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}/submissions/${encodeURIComponent(submissionId)}`)}),"buildRequest"),projectOutput:__name(body=>formSubmissionResponseSchema.parse(body).data,"projectOutput")},"forms.submissionStats":{domain:"forms",summary:"Read aggregate submission statistics for one form.",accessScope:"read",effect:"read",inputSchema:z92.object({projectId:uuidSchema,branch:branchNameSchema,id:z92.string().min(1).max(255)}).strict(),outputSchema:formSubmissionStatsResponseSchema.shape.data,buildRequest:__name(({projectId,branch,id})=>({method:"GET",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}/submissions/stats`)}),"buildRequest"),projectOutput:__name(body=>formSubmissionStatsResponseSchema.parse(body).data,"projectOutput")},"forms.deleteSubmission":{domain:"forms",summary:"Permanently delete one submission for a form. This cannot be undone.",accessScope:"write",effect:"mutation",inputSchema:z92.object({projectId:uuidSchema,branch:branchNameSchema,id:z92.string().min(1).max(255),submissionId:z92.string().min(1).max(255)}).strict(),outputSchema:formSubmissionSchema,buildRequest:__name(({projectId,branch,id,submissionId})=>({method:"DELETE",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}/submissions/${encodeURIComponent(submissionId)}`)}),"buildRequest"),projectOutput:__name(body=>formSubmissionResponseSchema.parse(body).data,"projectOutput")}}}});import{z as z93}from"zod";var estimateSchema,generationOperations,init_generation=__esm({"../../packages/sdk/dist/operations/generation.js"(){"use strict";init_common2();estimateSchema=z93.object({costUsd:z93.number(),credits:z93.number().optional(),billingMode:z93.enum(["fimo-credits","provider-account"]).optional(),confidence:z93.enum(["exact","estimated","metered"]),basis:z93.string()}).passthrough(),generationOperations={"generation.estimateModel":{domain:"generation",summary:"Estimate one generation request against an enabled provider model.",accessScope:"read",effect:"read",inputSchema:z93.object({projectId:uuidSchema,model:z93.string().min(1),options:z93.record(z93.string(),z93.unknown())}).strict(),outputSchema:estimateSchema,buildRequest:__name(({projectId,model,options})=>({method:"POST",path:`/management/projects/${encodeURIComponent(projectId)}/integrations/fal/models/estimate`,body:{model,options}}),"buildRequest"),projectOutput:responseData},"generation.estimateTask":{domain:"generation",summary:"Estimate one built-in media generation task on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z93.object({projectId:uuidSchema,branch:branchNameSchema,task:z93.string().min(1),options:z93.record(z93.string(),z93.unknown())}).strict(),outputSchema:estimateSchema,buildRequest:__name(({projectId,branch,task,options})=>({method:"POST",path:tenantPath(projectId,branch,"/assets/generate/estimate"),body:{task,options}}),"buildRequest"),projectOutput:responseData}}}});import{z as z94}from"zod";var historyKindSchema,projectVersionSchema,projectVersionPageSchema,historySummarySchema,restoreResultSchema,historyOperations,init_history=__esm({"../../packages/sdk/dist/operations/history.js"(){"use strict";init_common2();historyKindSchema=z94.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),projectVersionSchema=z94.object({versionId:uuidSchema,commitHash:z94.string(),name:z94.string(),description:z94.string().nullable(),kind:historyKindSchema,createdAt:z94.iso.datetime(),expiresAt:z94.iso.datetime()}),projectVersionPageSchema=z94.object({items:z94.array(projectVersionSchema),nextCursor:z94.string().nullable()}),historySummarySchema=z94.object({usage:z94.object({versionCount:z94.number().int().nonnegative(),snapshotBytes:z94.number().int().nonnegative()}),retentionDays:z94.number().int().positive()}),restoreResultSchema=z94.object({durationMs:z94.number().nonnegative().optional(),warning:z94.string().optional()}),historyOperations={"history.list":{domain:"history",summary:"List restore points for one Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z94.object({projectId:uuidSchema,branch:branchNameSchema,limit:z94.number().int().min(1).max(100),cursor:paginationShape.cursor}).strict(),outputSchema:projectVersionPageSchema,buildRequest:__name(({projectId,branch,limit,cursor})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/versions"),{limit,cursor})}),"buildRequest"),projectOutput:__name(body=>projectVersionPageSchema.parse(responseData(body)),"projectOutput")},"history.summary":{domain:"history",summary:"Read restore-point usage and retention for one Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z94.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:historySummarySchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"/versions/summary")}),"buildRequest"),projectOutput:__name(body=>historySummarySchema.parse(responseData(body)),"projectOutput")},"history.get":{domain:"history",summary:"Read one restore point from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z94.object({projectId:uuidSchema,branch:branchNameSchema,versionId:uuidSchema}).strict(),outputSchema:projectVersionSchema,buildRequest:__name(({projectId,branch,versionId})=>({method:"GET",path:managementBranchPath(projectId,branch,`/versions/${encodeURIComponent(versionId)}`)}),"buildRequest"),projectOutput:__name(body=>projectVersionSchema.parse(responseData(body)),"projectOutput")},"history.create":{domain:"history",summary:"Create a restore point for one Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z94.object({projectId:uuidSchema,branch:branchNameSchema,name:z94.string().min(1),description:z94.string().optional()}).strict(),outputSchema:projectVersionSchema,buildRequest:__name(({projectId,branch,name,description})=>({method:"POST",path:managementBranchPath(projectId,branch,"/versions"),body:withoutUndefined({name,description})}),"buildRequest"),projectOutput:__name(body=>projectVersionSchema.parse(responseData(body)),"projectOutput")},"history.restore":{domain:"history",summary:"Restore code and content from one Fimo Branch restore point.",accessScope:"write",effect:"mutation",inputSchema:z94.object({projectId:uuidSchema,branch:branchNameSchema,versionId:uuidSchema}).strict(),outputSchema:restoreResultSchema,buildRequest:__name(({projectId,branch,versionId})=>({method:"POST",path:managementBranchPath(projectId,branch,`/versions/${encodeURIComponent(versionId)}/restore`)}),"buildRequest"),projectOutput:__name(body=>restoreResultSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z95}from"zod";function publicationRecord(value){let publication=recordValue(value,"Expected a publication record."),source=recordValue(publication.source,"Expected a publication source."),{env,targetEnv,...publicSource}=source;return{...publication,source:{...publicSource,branch:publicSource.branch??env,targetBranch:publicSource.targetBranch??targetEnv}}}function projectPublication(body){return publicationOutputSchema.parse(publicationRecord(responseData(body)))}function projectPublicationsPage(body){let page=recordValue(responseData(body),"Expected a publication history page.");if(!Array.isArray(page.items))throw new Error("Expected publication history items.");return publicationsPageOutputSchema.parse({items:page.items.map(publicationRecord),nextCursor:page.nextCursor,retention:page.retention})}function projectPublicationLogs(body){let result=recordValue(responseData(body),"Expected publication logs.");return publicationLogsOutputSchema.parse({status:result.status,publicationId:result.publicationId,reason:result.reason??null,message:result.message??null,items:result.events??[]})}function projectSandboxLogs(body){let result=recordValue(responseData(body),"Expected sandbox logs.");return sandboxLogsOutputSchema.parse({status:result.status,reason:result.reason??null,message:result.message??null,items:result.events??[],nextCursor:result.previousCursor??null,retention:result.retention??null})}var LOG_TAIL_MAX_LIMIT,logTailLimitSchema,publicationStateOutputSchema,publicationOutputSchema,publicationsPageOutputSchema,publicationLogsOutputSchema,sandboxLogsOutputSchema,previewLocationOutputSchema,previewOpenOutputSchema,publishOutputSchema,hostingOperations,init_hosting=__esm({"../../packages/sdk/dist/operations/hosting.js"(){"use strict";init_common2();LOG_TAIL_MAX_LIMIT=1e3,logTailLimitSchema=z95.number().int().min(1).max(LOG_TAIL_MAX_LIMIT).optional(),publicationStateOutputSchema=z95.object({isPublished:z95.boolean(),publishedAt:z95.iso.datetime().nullable(),publishedVersion:z95.string().nullable()}),publicationOutputSchema=z95.object({id:uuidSchema,status:z95.enum(["queued","building","published","failed","canceled"]),label:z95.string().nullable(),notes:z95.string().nullable(),source:z95.object({branch:branchNameSchema,targetBranch:branchNameSchema,configVersion:z95.string().nullable(),framework:z95.string().nullable(),commit:z95.string().nullable()}),createdAt:z95.iso.datetime(),finishedAt:z95.iso.datetime().nullable(),url:z95.string().nullable(),failureCode:z95.string().nullable()}),publicationsPageOutputSchema=z95.object({items:z95.array(publicationOutputSchema),nextCursor:z95.string().nullable(),retention:z95.object({scope:z95.literal("publication_attempt_record"),records:z95.literal("project_lifetime")})}),publicationLogsOutputSchema=z95.object({status:z95.enum(["ok","unavailable"]),publicationId:uuidSchema,reason:z95.enum(["pending","no_deployment","provider_unavailable"]).nullable(),message:z95.string().nullable(),items:z95.array(z95.object({timestamp:z95.iso.datetime(),phase:z95.enum(["build","deploy"]),stream:z95.enum(["command","stdout","stderr","status","error"]),message:z95.string()}))}),sandboxLogsOutputSchema=z95.object({status:z95.enum(["ok","unavailable"]),reason:z95.enum(["no_sandbox","sandbox_expired","provider_unsupported"]).nullable(),message:z95.string().nullable(),items:z95.array(z95.object({id:z95.string(),timestamp:z95.iso.datetime().nullable(),source:z95.enum(["install","dev-server"]),phase:z95.string(),stream:z95.enum(["combined","stdout","stderr"]),message:z95.string()})),nextCursor:z95.string().nullable(),retention:z95.object({scope:z95.literal("sandbox_process_snapshot"),timestamps:z95.literal("process_start"),droppedOldest:z95.boolean(),phases:z95.array(z95.object({phase:z95.string(),source:z95.enum(["install","dev-server"]),status:z95.string(),startedAt:z95.iso.datetime().nullable(),exitCode:z95.number().int().nullable(),events:z95.number().int().nonnegative()}))}).nullable()}),previewLocationOutputSchema=z95.object({url:z95.string(),branch:branchNameSchema}),previewOpenOutputSchema=z95.object({url:z95.url(),expiresAt:z95.iso.datetime().nullable()}),publishOutputSchema=z95.object({success:z95.boolean(),message:z95.string().optional(),firstPublish:z95.boolean(),publicationId:z95.string().optional(),url:z95.string().nullable().optional()});__name(publicationRecord,"publicationRecord");__name(projectPublication,"projectPublication");__name(projectPublicationsPage,"projectPublicationsPage");__name(projectPublicationLogs,"projectPublicationLogs");__name(projectSandboxLogs,"projectSandboxLogs");hostingOperations={"publications.state":{domain:"publications",summary:"Read whether a site has a live published site.",accessScope:"read",effect:"read",inputSchema:z95.object({projectId:uuidSchema}).strict(),outputSchema:publicationStateOutputSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/publication-state")}),"buildRequest"),projectOutput:__name(body=>publicationStateOutputSchema.parse(responseData(body)),"projectOutput")},"publications.list":{domain:"publications",summary:"List durable publication attempts, newest first.",accessScope:"read",effect:"read",inputSchema:z95.object({projectId:uuidSchema,limit:z95.number().int().min(1).max(100).optional(),cursor:paginationShape.cursor}).strict(),outputSchema:publicationsPageOutputSchema,buildRequest:__name(({projectId,limit,cursor})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/publications"),{limit,before:cursor})}),"buildRequest"),projectOutput:projectPublicationsPage},"publications.get":{domain:"publications",summary:"Read one durable publication attempt.",accessScope:"read",effect:"read",inputSchema:z95.object({projectId:uuidSchema,publicationId:z95.string().min(1)}).strict(),outputSchema:publicationOutputSchema,buildRequest:__name(({projectId,publicationId})=>({method:"GET",path:managementProjectPath(projectId,`/publications/${encodeURIComponent(publicationId)}`)}),"buildRequest"),projectOutput:projectPublication},"publications.publish":{domain:"publications",summary:"Publish the production source Branch and wait until the site is live; returns the live URL. Building can take a few minutes; if the call fails or times out, list the publications until the newest attempt is published or failed.",accessScope:"write",effect:"mutation",inputSchema:z95.object({projectId:uuidSchema,label:z95.string().trim().min(1).max(120).optional(),notes:z95.string().max(2e4).optional()}).strict(),outputSchema:publishOutputSchema,buildRequest:__name(({projectId,label,notes})=>({method:"POST",path:managementProjectPath(projectId,"/publish"),body:withoutUndefined({label,notes})}),"buildRequest"),projectOutput:__name(body=>publishOutputSchema.parse(responseData(body)),"projectOutput")},"publications.logs":{domain:"publications",summary:"Read a bounded sanitized build-log tail for one publication.",accessScope:"read",effect:"read",inputSchema:z95.object({projectId:uuidSchema,publicationId:z95.string().min(1),limit:logTailLimitSchema}).strict(),outputSchema:publicationLogsOutputSchema,buildRequest:__name(({projectId,publicationId,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId,`/publications/${encodeURIComponent(publicationId)}/logs`),{limit})}),"buildRequest"),projectOutput:projectPublicationLogs},"sandbox.logs":{domain:"sandbox",summary:"Read existing install and dev-server logs without creating or extending a sandbox.",accessScope:"read",effect:"read",inputSchema:z95.object({projectId:uuidSchema,branch:branchNameSchema,limit:logTailLimitSchema,cursor:paginationShape.cursor}).strict(),outputSchema:sandboxLogsOutputSchema,buildRequest:__name(({projectId,branch,limit,cursor})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/sandbox/logs"),{limit,before:cursor})}),"buildRequest"),projectOutput:projectSandboxLogs},"preview.location":{domain:"preview",summary:"Return the Studio Preview location for one Branch without provisioning it.",accessScope:"read",effect:"read",inputSchema:z95.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:previewLocationOutputSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"/preview-location")}),"buildRequest"),projectOutput:__name(body=>previewLocationOutputSchema.parse(responseData(body)),"projectOutput")},"preview.open":{domain:"preview",summary:"Start or reuse one Branch's preview sandbox and return its signed live URL. Pass a work session's workingBranch name to preview unmerged changes; the URL expires at expiresAt.",accessScope:"read",effect:"mutation",inputSchema:z95.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:previewOpenOutputSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"/sandbox")}),"buildRequest"),projectOutput:__name(body=>previewOpenOutputSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z96}from"zod";var knowledgeSchema,knowledgeOperations,init_knowledge=__esm({"../../packages/sdk/dist/operations/knowledge.js"(){"use strict";init_common2();knowledgeSchema=z96.object({content:z96.string(),updatedAt:z96.string().nullable(),updatedBy:z96.string().nullable()}),knowledgeOperations={"knowledge.get":{domain:"knowledge",summary:"Read shared site goals, brand guidance and rules before planning, recommendations, design, copy or coding.",accessScope:"read",effect:"read",inputSchema:z96.object({projectId:uuidSchema}).strict(),outputSchema:knowledgeSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/knowledge")}),"buildRequest"),projectOutput:__name(body=>knowledgeSchema.parse(responseData(body)),"projectOutput")},"knowledge.update":{domain:"knowledge",summary:"Replace shared site knowledge only when explicitly asked and authorized. Read first to preserve unrelated guidance.",accessScope:"write",effect:"mutation",inputSchema:z96.object({projectId:uuidSchema,content:z96.string()}).strict(),outputSchema:knowledgeSchema,buildRequest:__name(({projectId,content:content2})=>({method:"PUT",path:managementProjectPath(projectId,"/knowledge"),body:{content:content2}}),"buildRequest"),projectOutput:__name(body=>knowledgeSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z97}from"zod";function responseValue(schema,body){return schema.parse(responseData(body))}var TranslationDTOSchema2,labelResponseSchema,labelListOutputSchema,labelUpsertOutputSchema,labelDeleteOutputSchema,labelsOperations,init_labels=__esm({"../../packages/sdk/dist/operations/labels.js"(){"use strict";init_common2();init_entries();TranslationDTOSchema2=z97.object({key:z97.string(),value:z97.string().optional(),defaultValue:z97.string(),locale:z97.string()}),labelResponseSchema=createResponseSchema2(TranslationDTOSchema2),labelListOutputSchema=z97.object({data:z97.array(z97.union([TranslationDTOSchema2,z97.object({key:z97.string(),values:z97.record(z97.string(),z97.string())})]))}),labelUpsertOutputSchema=z97.object({created:z97.number().int().nonnegative(),updated:z97.number().int().nonnegative(),deleted:z97.number().int().nonnegative(),defaultLocale:z97.string(),locales:z97.array(z97.string())}),labelDeleteOutputSchema=z97.object({key:z97.string(),locale:z97.string()});__name(responseValue,"responseValue");labelsOperations={"labels.list":{domain:"labels",summary:"List localized labels on a Fimo Branch, optionally grouped across locales.",accessScope:"read",effect:"read",inputSchema:z97.object({projectId:uuidSchema,branch:branchNameSchema,locale:localeSchema.optional()}).strict(),outputSchema:labelListOutputSchema,buildRequest:__name(({projectId,branch,locale})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,"/labels"),{locale})}),"buildRequest")},"labels.get":{domain:"labels",summary:"Read one localized label by locale and key.",accessScope:"read",effect:"read",inputSchema:z97.object({projectId:uuidSchema,branch:branchNameSchema,locale:localeSchema,key:z97.string().min(1).max(255)}).strict(),outputSchema:labelResponseSchema,buildRequest:__name(({projectId,branch,locale,key})=>({method:"GET",path:tenantPath(projectId,branch,`/labels/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`)}),"buildRequest")},"labels.set":{domain:"labels",summary:"Create or set one localized label.",accessScope:"write",effect:"mutation",inputSchema:z97.object({projectId:uuidSchema,branch:branchNameSchema,key:z97.string(),value:z97.string(),locale:z97.string().optional()}).strict(),outputSchema:TranslationDTOSchema2,buildRequest:__name(({projectId,branch,key,value,locale})=>({method:"POST",path:tenantPath(projectId,branch,"/labels"),body:{key,value,locale}}),"buildRequest"),projectOutput:__name(body=>responseValue(TranslationDTOSchema2,body),"projectOutput")},"labels.setMany":{domain:"labels",summary:"Create or overwrite localized labels in one request.",accessScope:"write",effect:"mutation",inputSchema:z97.object({projectId:uuidSchema,branch:branchNameSchema,records:z97.array(z97.object({key:z97.string(),value:z97.string(),locale:z97.string().optional()}))}).strict(),outputSchema:labelUpsertOutputSchema,buildRequest:__name(({projectId,branch,records})=>({method:"POST",path:tenantPath(projectId,branch,"/labels/sync"),body:{created:records,updated:[],deleted:[]}}),"buildRequest"),projectOutput:__name(body=>responseValue(labelUpsertOutputSchema,body),"projectOutput")},"labels.delete":{domain:"labels",summary:"Delete one localized label.",accessScope:"write",effect:"mutation",inputSchema:z97.object({projectId:uuidSchema,branch:branchNameSchema,locale:z97.string().optional(),key:z97.string()}).strict(),outputSchema:labelDeleteOutputSchema,buildRequest:__name(({projectId,branch,locale,key})=>({method:"DELETE",path:tenantPath(projectId,branch,locale?`/labels/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`:`/labels/${encodeURIComponent(key)}`)}),"buildRequest"),projectOutput:__name(body=>responseValue(labelDeleteOutputSchema,body),"projectOutput")}}}});import{z as z98}from"zod";var projectLocaleCoverageSchema,ProjectLocaleStatsResponseSchema2,projectLocaleInputSchema,ProjectLocaleMutationResponseSchema2,RemoveProjectLocaleResponseSchema2,localesOperations,init_locales=__esm({"../../packages/sdk/dist/operations/locales.js"(){"use strict";init_common2();projectLocaleCoverageSchema=z98.object({translated:z98.number().int().nonnegative(),total:z98.number().int().nonnegative()}),ProjectLocaleStatsResponseSchema2=createResponseSchema2(z98.object({defaultLocale:z98.string(),locales:z98.array(z98.object({locale:z98.string(),isDefault:z98.boolean(),entries:projectLocaleCoverageSchema,labels:projectLocaleCoverageSchema}))})),projectLocaleInputSchema=z98.string().min(1).max(40),ProjectLocaleMutationResponseSchema2=createResponseSchema2(z98.object({locale:z98.string()})),RemoveProjectLocaleResponseSchema2=createResponseSchema2(z98.object({locale:z98.string(),entriesDeleted:z98.number().int().nonnegative(),labelsDeleted:z98.number().int().nonnegative()})),localesOperations={"locales.list":{domain:"locales",summary:"List configured locales and content coverage on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z98.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:ProjectLocaleStatsResponseSchema2,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"/locales/stats")}),"buildRequest")},"locales.add":{domain:"locales",summary:"Add a configured locale to a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z98.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:ProjectLocaleMutationResponseSchema2,buildRequest:__name(({projectId,branch,locale})=>({method:"POST",path:managementBranchPath(projectId,branch,"/locales"),body:{locale}}),"buildRequest")},"locales.setDefault":{domain:"locales",summary:"Set the default configured locale on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z98.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:ProjectLocaleMutationResponseSchema2,buildRequest:__name(({projectId,branch,locale})=>({method:"PUT",path:managementBranchPath(projectId,branch,"/locales/default"),body:{locale}}),"buildRequest")},"locales.delete":{domain:"locales",summary:"Delete a non-default locale and its localized content from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z98.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:RemoveProjectLocaleResponseSchema2,buildRequest:__name(({projectId,branch,locale})=>({method:"DELETE",path:managementBranchPath(projectId,branch,`/locales/${encodeURIComponent(locale)}`)}),"buildRequest")}}}});import{z as z99}from"zod";var organizationSchema,organizationMemberSchema,organizationInvitationSchema,referralSummarySchema,organizationsOperations,init_organizations=__esm({"../../packages/sdk/dist/operations/organizations.js"(){"use strict";init_common2();organizationSchema=z99.object({id:z99.string().min(1),name:z99.string(),slug:z99.string()}),organizationMemberSchema=z99.object({id:z99.string().min(1),role:z99.string(),createdAt:z99.string().optional(),user:z99.object({id:z99.string().min(1),name:z99.string().nullable().optional(),email:z99.string().nullable().optional()}).optional()}),organizationInvitationSchema=z99.object({id:z99.string().min(1),email:z99.email(),role:z99.string(),organizationId:z99.string().min(1),inviterId:z99.string().min(1),status:z99.string(),expiresAt:z99.string(),createdAt:z99.string()}).passthrough(),referralSummarySchema=z99.object({counts:z99.object({signed_up:z99.number().int(),activated:z99.number().int()}),credits:z99.object({total:z99.number().int(),earned:z99.number().int().optional()})}),organizationsOperations={"organizations.list":{domain:"organizations",summary:"List organizations the authenticated user belongs to.",accessScope:"read",effect:"read",inputSchema:z99.object({}).strict(),outputSchema:createResponseSchema2(z99.array(organizationSchema)),buildRequest:__name(()=>({method:"GET",path:"/management/organizations"}),"buildRequest")},"organizations.members":{domain:"organizations",summary:"List members of one organization.",accessScope:"read",effect:"read",inputSchema:z99.object({organizationId:z99.string().min(1)}).strict(),outputSchema:z99.array(organizationMemberSchema),buildRequest:__name(({organizationId})=>({method:"GET",path:`/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`}),"buildRequest"),projectOutput:__name(body=>z99.object({members:z99.array(organizationMemberSchema)}).nullable().parse(body)?.members??[],"projectOutput")},"organizations.invite":{domain:"organizations",summary:"Invite a user to an organization.",accessScope:"write",effect:"mutation",inputSchema:z99.object({organizationId:z99.string().min(1),email:z99.email(),role:z99.enum(["owner","admin","member"]),resend:z99.boolean().optional()}).strict(),outputSchema:organizationInvitationSchema,buildRequest:__name(input=>({method:"POST",path:"/auth/organization/invite-member",body:input}),"buildRequest")},"referrals.summary":{domain:"referrals",summary:"Read the referral summary for the authenticated user.",accessScope:"read",effect:"read",inputSchema:z99.object({userId:z99.string().min(1)}).strict(),outputSchema:referralSummarySchema,buildRequest:__name(({userId})=>({method:"GET",path:`/users/${encodeURIComponent(userId)}/referrals/summary`}),"buildRequest"),projectOutput:__name(body=>referralSummarySchema.parse(responseData(body)),"projectOutput")}}}});import{z as z100}from"zod";var projectSchema,projectResponseSchema,transferResultSchema,projectsOperations,init_projects=__esm({"../../packages/sdk/dist/operations/projects.js"(){"use strict";init_common2();projectSchema=z100.object({id:uuidSchema,name:z100.string(),displayName:z100.string().nullable(),organizationId:z100.string().nullable(),defaultBranch:branchNameSchema.optional(),productionSourceBranch:branchNameSchema.optional(),status:z100.string().optional(),appUrl:z100.string().nullable().optional()}).passthrough(),projectResponseSchema=z100.object({data:projectSchema}),transferResultSchema=z100.object({projectId:z100.string(),sourceOrganizationId:z100.string(),targetOrganizationId:z100.string(),movedThreads:z100.number().int().nonnegative(),revokedInvites:z100.number().int().nonnegative(),revokedGrants:z100.number().int().nonnegative(),preservedGrants:z100.number().int().nonnegative(),warnings:z100.array(z100.string())}),projectsOperations={"projects.list":{domain:"projects",summary:"List the Fimo sites the authenticated user can access.",accessScope:"read",effect:"read",inputSchema:z100.object({organizationId:z100.string().min(1).optional()}).strict(),outputSchema:z100.object({data:z100.array(projectSchema)}),buildRequest:__name(({organizationId})=>({method:"GET",path:organizationId?`/management/organizations/${encodeURIComponent(organizationId)}/projects`:"/management/projects"}),"buildRequest")},"projects.get":{domain:"projects",summary:"Read one Fimo site the authenticated user can access.",accessScope:"read",effect:"read",inputSchema:z100.object({projectId:uuidSchema}).strict(),outputSchema:projectResponseSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"")}),"buildRequest")},"projects.create":{domain:"projects",summary:"Create a Fimo site in an organization. Pass starter to commit a runnable Fimo site template so sessions, preview and publish work immediately; use nextjs unless the user asks for another framework.",accessScope:"write",effect:"mutation",inputSchema:z100.object({organizationId:z100.string().min(1),displayName:z100.string().min(1).optional(),origin:z100.enum(["scratch","migration"]).optional(),starter:z100.enum(["nextjs","astro","react-router","vite","sveltekit"]).optional()}).strict(),outputSchema:projectResponseSchema,buildRequest:__name(({organizationId,displayName,origin,starter})=>({method:"POST",path:"/management/projects",body:withoutUndefined({organizationId,displayName,origin,starter,source:"cli"})}),"buildRequest")},"projects.transfer":{domain:"projects",summary:"Transfer one Fimo site to another organization.",accessScope:"write",effect:"mutation",inputSchema:z100.object({projectId:uuidSchema,targetOrganizationId:z100.string().min(1)}).strict(),outputSchema:transferResultSchema,buildRequest:__name(({projectId,targetOrganizationId})=>({method:"POST",path:managementProjectPath(projectId,"/transfer"),body:{targetOrganizationId},preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>transferResultSchema.parse(responseData(body)),"projectOutput")},"projects.invite":{domain:"projects",summary:"Invite someone by email to collaborate on a Fimo site with full, edit, comment or view access. They receive an email and join the site's members when they accept.",accessScope:"write",effect:"mutation",inputSchema:z100.object({projectId:uuidSchema,email:z100.email(),role:z100.enum(["full","edit","comment","view"])}).strict(),outputSchema:z100.object({id:z100.string().min(1)}),buildRequest:__name(({projectId,email,role})=>({method:"POST",path:managementProjectPath(projectId,"/invites"),body:{email,roleKey:role}}),"buildRequest"),projectOutput:__name(body=>({id:z100.object({id:z100.string().min(1)}).parse(responseData(body)).id}),"projectOutput")},"projects.delete":{domain:"projects",summary:"Permanently delete a Fimo site.",accessScope:"write",effect:"mutation",inputSchema:z100.object({projectId:uuidSchema}).strict(),outputSchema:z100.unknown(),buildRequest:__name(({projectId})=>({method:"DELETE",path:managementProjectPath(projectId,""),body:{}}),"buildRequest")}}}});import{z as z101}from"zod";function projectBranchRecord2(value){let{env,...record}=value;return{...record,branch:env}}function projectSchedule(body){return scheduleSchema.parse(projectBranchRecord2(responseData(body)))}function projectRun(body){return runSchema.parse(projectBranchRecord2(responseData(body)))}function projectOverview(body){let value=responseData(body);return overviewSchema.parse({...value,items:value.items.map(projectBranchRecord2)})}function projectDetail2(body){let value=responseData(body);return detailSchema.parse({...value,schedule:projectBranchRecord2(value.schedule)})}function projectRunsPage(body){let value=responseData(body);return runsPageSchema.parse({...value,items:value.items.map(projectBranchRecord2)})}function projectRunDetail(body){return runDetailSchema.parse(projectBranchRecord2(responseData(body)))}var dateSchema,scheduleStatusSchema,runStatusSchema,scheduleSchema,usageSchema,policySchema,planSchema,runSchema,runDetailSchema,overviewSchema,detailSchema,runsPageSchema,scheduleWriteShape,scheduleContextShape,schedulesOperations,init_schedules=__esm({"../../packages/sdk/dist/operations/schedules.js"(){"use strict";init_common2();dateSchema=z101.iso.datetime(),scheduleStatusSchema=z101.enum(["ok","failed"]),runStatusSchema=z101.enum(["queued","running","succeeded","failed","skipped"]),scheduleSchema=z101.object({id:uuidSchema,createdAt:dateSchema,updatedAt:dateSchema,projectId:uuidSchema,branch:z101.string().min(1),name:z101.string().min(1),cron:z101.string().min(1),command:z101.string().min(1),secretKeys:z101.array(z101.string().min(1)),enabled:z101.boolean(),lastRunAt:dateSchema.nullable(),lastStatus:scheduleStatusSchema.nullable(),lastError:z101.string().nullable(),overPolicyReasons:z101.array(z101.string()).optional()}).passthrough(),usageSchema=z101.object({runCount:z101.number().int().nonnegative(),runsWithOutput:z101.number().int().nonnegative()}),policySchema=z101.object({maxRuns:z101.number().int().positive(),retentionDays:z101.number().int().positive().nullable(),outputRetentionDays:z101.number().int().positive(),maxOutputBytes:z101.number().int().positive()}).passthrough(),planSchema=z101.object({code:z101.enum(["Free","PAYG","Premium","Pro"]),source:z101.enum(["cached_subscription","free_fallback"]),activeSchedules:z101.object({used:z101.number().int().nonnegative(),limit:z101.number().int().positive()}),minCadenceMinutes:z101.number().int().positive(),maxRunMs:z101.number().int().positive(),concurrency:z101.object({used:z101.number().int().nonnegative(),limit:z101.number().int().positive()}),compute:z101.object({settledMs:z101.number().int().nonnegative(),activeMs:z101.number().int().nonnegative(),reservedMs:z101.number().int().nonnegative().optional(),includedMs:z101.number().int().positive(),remainingMs:z101.number().int().nonnegative(),resetsAt:dateSchema}),state:z101.enum(["ok","near_limit","exhausted","over_policy"]),overPolicyReasons:z101.array(z101.string())}).passthrough(),runSchema=z101.object({id:uuidSchema,scheduleId:uuidSchema,projectId:uuidSchema,branch:z101.string().min(1),scheduleName:z101.string().min(1),command:z101.string().min(1),status:runStatusSchema,trigger:z101.enum(["cron","ui","cli"]),triggeredBy:z101.object({id:z101.string().min(1),name:z101.string().min(1)}).nullable(),queuedAt:dateSchema,startedAt:dateSchema.nullable(),finishedAt:dateSchema.nullable(),exitCode:z101.number().int().nullable(),errorCode:z101.string().nullable(),error:z101.string().nullable(),outputBytes:z101.number().int().nonnegative(),outputTruncated:z101.boolean(),outputExpiresAt:dateSchema.nullable(),metadataExpiresAt:dateSchema.nullable()}).passthrough(),runDetailSchema=runSchema.extend({output:z101.string().nullable(),secretSnapshot:z101.object({state:z101.enum(["pending","resolved","failed"]),capturedAt:dateSchema.nullable(),items:z101.array(z101.object({key:z101.string().min(1),updatedAt:dateSchema.nullable(),resolution:z101.enum(["resolved","missing","deleted","recreated","rotated"])}))})}),overviewSchema=z101.object({items:z101.array(scheduleSchema),usage:usageSchema,policy:policySchema,plan:planSchema}),detailSchema=z101.object({schedule:scheduleSchema,usage:usageSchema,policy:policySchema,plan:planSchema}).passthrough(),runsPageSchema=z101.object({items:z101.array(runSchema),nextCursor:z101.string().nullable(),usage:usageSchema,policy:policySchema,plan:planSchema});__name(projectBranchRecord2,"projectBranchRecord");__name(projectSchedule,"projectSchedule");__name(projectRun,"projectRun");__name(projectOverview,"projectOverview");__name(projectDetail2,"projectDetail");__name(projectRunsPage,"projectRunsPage");__name(projectRunDetail,"projectRunDetail");scheduleWriteShape={name:z101.string().min(1).max(120),cron:z101.string().min(1).max(120),command:z101.string().min(1).max(500),secretKeys:z101.array(z101.string().min(1))},scheduleContextShape={projectId:uuidSchema,branch:branchNameSchema.optional()},schedulesOperations={"schedules.list":{domain:"schedules",summary:"List schedule records for one site Branch.",accessScope:"read",effect:"read",inputSchema:z101.object({...scheduleContextShape}).strict(),outputSchema:z101.array(scheduleSchema),buildRequest:__name(({projectId,branch})=>({method:"GET",context:{branch},path:managementProjectPath(projectId,"/schedules")}),"buildRequest"),projectOutput:__name(body=>z101.array(scheduleSchema).parse(responseData(body).map(projectBranchRecord2)),"projectOutput")},"schedules.overview":{domain:"schedules",summary:"Read schedules with usage and plan limits for one site Branch.",accessScope:"read",effect:"read",inputSchema:z101.object({...scheduleContextShape}).strict(),outputSchema:overviewSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",context:{branch},path:managementProjectPath(projectId,"/schedules/overview")}),"buildRequest"),projectOutput:projectOverview},"schedules.get":{domain:"schedules",summary:"Read one schedule with usage and plan limits.",accessScope:"read",effect:"read",inputSchema:z101.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:detailSchema,buildRequest:__name(({projectId,branch,scheduleId})=>({method:"GET",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}`)}),"buildRequest"),projectOutput:projectDetail2},"schedules.create":{domain:"schedules",summary:"Create a recurring command schedule for one site Branch.",accessScope:"agents",effect:"mutation",inputSchema:z101.object({...scheduleContextShape,...scheduleWriteShape,enabled:z101.boolean().optional()}).strict(),outputSchema:scheduleSchema,buildRequest:__name(({projectId,branch,...body})=>({method:"POST",context:{branch},path:managementProjectPath(projectId,"/schedules"),body}),"buildRequest"),projectOutput:projectSchedule},"schedules.update":{domain:"schedules",summary:"Update a recurring command schedule.",accessScope:"agents",effect:"mutation",inputSchema:z101.object({...scheduleContextShape,scheduleId:uuidSchema,name:scheduleWriteShape.name.optional(),cron:scheduleWriteShape.cron.optional(),command:scheduleWriteShape.command.optional(),secretKeys:scheduleWriteShape.secretKeys.optional()}).strict().refine(({projectId:_projectId,branch:_branch,scheduleId:_scheduleId,...update})=>Object.values(update).some(value=>value!==void 0),{message:"Pass at least one schedule field to update."}),outputSchema:scheduleSchema,buildRequest:__name(({projectId,branch,scheduleId,...update})=>({method:"PATCH",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}`),body:withoutUndefined(update)}),"buildRequest"),projectOutput:projectSchedule},"schedules.setEnabled":{domain:"schedules",summary:"Pause or resume a recurring command schedule.",accessScope:"agents",effect:"mutation",inputSchema:z101.object({...scheduleContextShape,scheduleId:uuidSchema,enabled:z101.boolean()}).strict(),outputSchema:scheduleSchema,buildRequest:__name(({projectId,branch,scheduleId,enabled})=>({method:"POST",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}/${enabled?"resume":"pause"}`)}),"buildRequest"),projectOutput:projectSchedule},"schedules.run":{domain:"schedules",summary:"Queue an immediate run of a site schedule.",accessScope:"agents",effect:"mutation",inputSchema:z101.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:runSchema,buildRequest:__name(({projectId,branch,scheduleId})=>({method:"POST",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}/run`),body:{trigger:"cli"}}),"buildRequest"),projectOutput:projectRun},"schedules.listRuns":{domain:"schedules",summary:"List runs of one site schedule with cursor pagination.",accessScope:"read",effect:"read",inputSchema:z101.object({...scheduleContextShape,scheduleId:uuidSchema,limit:z101.number().int().min(1).max(100).optional(),cursor:paginationShape.cursor,status:runStatusSchema.optional()}).strict(),outputSchema:runsPageSchema,buildRequest:__name(({projectId,branch,scheduleId,limit,cursor,status})=>({method:"GET",context:{branch},path:addQuery(managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}/runs`),{limit,cursor,status})}),"buildRequest"),projectOutput:projectRunsPage},"schedules.getRun":{domain:"schedules",summary:"Read one schedule run and its captured output.",accessScope:"read",effect:"read",inputSchema:z101.object({...scheduleContextShape,runId:uuidSchema}).strict(),outputSchema:runDetailSchema,buildRequest:__name(({projectId,branch,runId})=>({method:"GET",context:{branch},path:managementProjectPath(projectId,`/schedules/runs/${encodeURIComponent(runId)}`)}),"buildRequest"),projectOutput:projectRunDetail},"schedules.delete":{domain:"schedules",summary:"Delete one site schedule.",accessScope:"agents",effect:"mutation",inputSchema:z101.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:z101.object({ok:z101.literal(!0)}),buildRequest:__name(({projectId,branch,scheduleId})=>({method:"DELETE",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}`)}),"buildRequest"),projectOutput:__name(body=>z101.object({ok:z101.literal(!0)}).parse(responseData(body)),"projectOutput")}}}});import{z as z102}from"zod";function projectSchemaDefinition(body){return z102.object({data:contentTypeSchema}).parse(body).data}var contentTypeSchema,schemaListOutputSchema,schemaMutationOutputSchema,schemaDefinitionInputSchema,schemasOperations,init_schemas=__esm({"../../packages/sdk/dist/operations/schemas.js"(){"use strict";init_common2();contentTypeSchema=z102.object({id:z102.string(),name:z102.string(),label:z102.string(),isSingleton:z102.boolean(),slugUnique:z102.boolean(),i18n:z102.record(z102.string(),z102.unknown()),groups:z102.array(z102.record(z102.string(),z102.unknown())),fields:z102.record(z102.string(),z102.unknown()),createdAt:z102.string(),updatedAt:z102.string()}).passthrough(),schemaListOutputSchema=z102.object({contentTypes:z102.array(contentTypeSchema)}),schemaMutationOutputSchema=sessionEnvelopeSchema.extend({schema:z102.object({typeName:z102.string().min(1).max(255),generatedPaths:z102.array(z102.string().min(1)).max(1e3),tip:z102.string().min(1)})}),schemaDefinitionInputSchema=z102.record(z102.string(),z102.unknown());__name(projectSchemaDefinition,"projectSchemaDefinition");schemasOperations={"schemas.list":{domain:"schemas",summary:"List content schemas on a durable Branch.",accessScope:"read",effect:"read",inputSchema:z102.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:schemaListOutputSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:tenantPath(projectId,branch,"/schema")}),"buildRequest")},"schemas.get":{domain:"schemas",summary:"Get one complete content schema from a durable Branch.",accessScope:"read",effect:"read",inputSchema:z102.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z102.string().min(1).max(255)}).strict(),outputSchema:contentTypeSchema,buildRequest:__name(({projectId,branch,typeName})=>({method:"GET",path:tenantPath(projectId,branch,`/schema/types/${encodeURIComponent(typeName)}`)}),"buildRequest"),projectOutput:projectSchemaDefinition},"schemas.upsertBatch":{domain:"schemas",summary:"Atomically create or update a batch of content schemas on a Fimo Branch.",accessScope:"code",effect:"mutation",inputSchema:z102.object({projectId:uuidSchema,branch:branchNameSchema,contentTypes:z102.array(schemaDefinitionInputSchema).min(1).max(100),operations:z102.array(z102.record(z102.string(),z102.unknown())).optional()}).strict(),outputSchema:z102.array(z102.unknown()),buildRequest:__name(({projectId,branch,contentTypes,operations})=>({method:"POST",path:tenantPath(projectId,branch,"/schema/batch"),body:withoutUndefined({contentTypes,operations:operations?.length?operations:void 0})}),"buildRequest"),projectOutput:__name(body=>z102.object({data:z102.array(z102.unknown())}).parse(body).data,"projectOutput")},"schemas.deleteFromBranch":{domain:"schemas",summary:"Delete a content schema directly from a Fimo Branch.",accessScope:"code",effect:"mutation",inputSchema:z102.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z102.string().min(1).max(255)}).strict(),outputSchema:z102.unknown(),buildRequest:__name(({projectId,branch,typeName})=>({method:"DELETE",path:tenantPath(projectId,branch,`/schema/types/${encodeURIComponent(typeName)}`)}),"buildRequest"),projectOutput:__name(body=>z102.object({data:z102.unknown()}).parse(body).data,"projectOutput")},"schemas.create":{domain:"schemas",summary:"Create a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z102.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z102.string().min(1).max(255),definition:schemaDefinitionInputSchema}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId,sessionId,typeName,definition})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/schema`),body:{kind:"create",typeName,definition}}),"buildRequest")},"schemas.update":{domain:"schemas",summary:"Update a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z102.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z102.string().min(1).max(255),definition:schemaDefinitionInputSchema,renameFrom:z102.string().max(255).optional()}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId,sessionId,typeName,definition,renameFrom})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/schema`),body:withoutUndefined({kind:"update",typeName,definition,renameFrom})}),"buildRequest")},"schemas.delete":{domain:"schemas",summary:"Delete a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z102.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z102.string().min(1).max(255)}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId,sessionId,typeName})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/schema`),body:{kind:"delete",typeName}}),"buildRequest")}}}});import{z as z103}from"zod";var environmentSchema2,secretKindSchema,projectSecretSchema,secretWriteInputSchema,secretsOperations,init_secrets=__esm({"../../packages/sdk/dist/operations/secrets.js"(){"use strict";init_common2();environmentSchema2=z103.union([z103.literal("production"),z103.literal("preview"),uuidSchema]),secretKindSchema=z103.enum(["variable","secret"]),projectSecretSchema=z103.object({id:z103.string().min(1),projectId:z103.string().min(1),key:z103.string().min(1),kind:secretKindSchema,exposure:z103.enum(["public","private"]),environment:environmentSchema2,value:z103.string().optional(),maskedValue:z103.string().optional(),createdAt:z103.string(),updatedAt:z103.string()}),secretWriteInputSchema=z103.object({projectId:uuidSchema,key:z103.string().min(1).max(255),kind:secretKindSchema,value:z103.string(),environment:environmentSchema2}),secretsOperations={"secrets.list":{domain:"secrets",summary:"List public variables or masked secrets for one site Environment.",accessScope:"read",effect:"read",inputSchema:z103.object({projectId:uuidSchema,environment:environmentSchema2,kind:secretKindSchema.optional()}).strict(),outputSchema:z103.array(projectSecretSchema),buildRequest:__name(({projectId,environment,kind})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/secrets"),{environment,kind})}),"buildRequest"),projectOutput:__name(body=>z103.array(projectSecretSchema).parse(responseData(body)),"projectOutput")},"secrets.create":{domain:"secrets",summary:"Create a public variable or secret for one site Environment.",accessScope:"write",effect:"mutation",inputSchema:secretWriteInputSchema.strict(),outputSchema:projectSecretSchema,buildRequest:__name(({projectId,...body})=>({method:"POST",path:managementProjectPath(projectId,"/secrets"),body}),"buildRequest"),projectOutput:__name(body=>projectSecretSchema.parse(responseData(body)),"projectOutput")},"secrets.update":{domain:"secrets",summary:"Update a public variable or secret for one site Environment.",accessScope:"write",effect:"mutation",inputSchema:secretWriteInputSchema.strict(),outputSchema:projectSecretSchema,buildRequest:__name(({projectId,key,...body})=>({method:"PATCH",path:managementProjectPath(projectId,`/secrets/${encodeURIComponent(key)}`),body}),"buildRequest"),projectOutput:__name(body=>projectSecretSchema.parse(responseData(body)),"projectOutput")},"secrets.delete":{domain:"secrets",summary:"Delete a public variable or secret from one site Environment.",accessScope:"write",effect:"mutation",inputSchema:z103.object({projectId:uuidSchema,key:z103.string().min(1),kind:secretKindSchema,environment:environmentSchema2}).strict(),outputSchema:z103.unknown(),buildRequest:__name(({projectId,key,kind,environment})=>({method:"DELETE",path:addQuery(managementProjectPath(projectId,`/secrets/${encodeURIComponent(key)}`),{kind,environment})}),"buildRequest")},"environments.resolve":{domain:"environments",summary:"Resolve which compatibility Environment receives one site Branch.",accessScope:"read",effect:"read",inputSchema:z103.object({projectId:uuidSchema,branch:z103.string().min(1)}).strict(),outputSchema:z103.object({branch:z103.string().min(1),environment:environmentSchema2}),buildRequest:__name(({projectId})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/branches"),{includeAgentEnvs:!0})}),"buildRequest"),projectOutput:__name((body,input)=>{let branches=z103.array(z103.object({branch:z103.string().optional(),env:z103.string().optional(),parentBranch:z103.string().nullable().optional(),parentEnv:z103.string().nullable().optional(),resolvedEnvironment:z103.object({id:environmentSchema2}).nullable().optional()}).passthrough()).parse(responseData(body)),current=branches.find(candidate=>(candidate.branch??candidate.env)===input.branch),visited=new Set;for(;current;){let name=current.branch??current.env;if(!name||visited.has(name))break;if(visited.add(name),current.resolvedEnvironment)return{branch:input.branch,environment:current.resolvedEnvironment.id};let parent=current.parentBranch??current.parentEnv;current=parent?branches.find(candidate=>(candidate.branch??candidate.env)===parent):void 0}return{branch:input.branch,environment:"preview"}},"projectOutput")}}}});import{z as z104}from"zod";function projectConflictSurface(conflict){let value=recordValue(conflict,"Expected a session conflict object.");return{...value,surface:value.surface==="translations"?"labels":value.surface}}function projectSessionChanges(body){let value=recordValue(body,"Expected a session changes response."),changes=recordValue(value.changes,"Expected session changes.");if(!Array.isArray(changes.surfaces))throw new Error("Expected session change surfaces.");return{...value,changes:{...changes,surfaces:changes.surfaces.map(projectConflictSurface),...Array.isArray(changes.crossSurface)?{crossSurface:changes.crossSurface.map(finding=>{let parsed=backendCrossSurfaceFindingSchema.parse(finding);return projectCrossSurfaceFinding(parsed)})}:{}}}}function projectSessionConflicts(body){let value=recordValue(body,"Expected a session conflict response.");return Array.isArray(value.conflicts)?{...value,conflicts:value.conflicts.map(projectConflictSurface)}:value}function backendConflictResolutions(resolutions){return resolutions.map(resolution=>({...resolution,surface:resolution.surface==="labels"?"translations":resolution.surface}))}var sessionValidationSchema,sessionConflictSummarySchema,surfaceDeltaItemSchema,perSurfaceDeltaSchema,sessionChangesSchema,projectScriptStatusSchema,sessionOperationResultSchema,conflictSchema2,codeConflictBlobSchema2,codeConflictDetailSchema,resolutionChoiceSchema,conflictResolutionSchema2,resolvedMergeStrategySchema,sessionsOperations,init_sessions=__esm({"../../packages/sdk/dist/operations/sessions.js"(){"use strict";init_branches();init_common2();__name(projectConflictSurface,"projectConflictSurface");__name(projectSessionChanges,"projectSessionChanges");__name(projectSessionConflicts,"projectSessionConflicts");__name(backendConflictResolutions,"backendConflictResolutions");sessionValidationSchema=z104.object({status:z104.literal("passed")}).passthrough(),sessionConflictSummarySchema=z104.object({surface:surfaceNameSchema,key:z104.string().min(1),kind:z104.string().optional(),description:z104.string(),path:z104.string().optional()}).passthrough(),surfaceDeltaItemSchema=z104.object({verb:z104.enum(["added","removed","changed","conflict"]),key:z104.string(),detail:z104.string().optional(),origin:z104.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z104.record(z104.string(),z104.unknown()).optional()}).passthrough(),perSurfaceDeltaSchema=z104.object({surface:surfaceNameSchema,status:z104.enum(["ok","timed_out","failed","unchanged"]),durationMs:z104.number().int().nonnegative().optional(),changedCount:z104.number().int().nonnegative(),conflictCount:z104.number().int().nonnegative(),items:z104.array(surfaceDeltaItemSchema).max(1e3).optional(),truncated:z104.boolean().optional(),error:z104.string().optional()}).passthrough(),sessionChangesSchema=z104.object({fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),generatedAt:z104.iso.datetime(),surfaces:z104.array(perSurfaceDeltaSchema),crossSurface:z104.array(crossSurfaceFindingSchema).optional(),fingerprint:z104.string()}).passthrough(),projectScriptStatusSchema=z104.enum(["passed","failed","unavailable"]),sessionOperationResultSchema=z104.discriminatedUnion("operation",[z104.object({operation:z104.literal("dependencies_install"),repairedInstallPolicy:z104.boolean(),tip:z104.string()}),z104.object({operation:z104.literal("schemas_sync"),tip:z104.string()}),z104.object({operation:z104.literal("typecheck"),status:projectScriptStatusSchema,output:z104.string()}),z104.object({operation:z104.literal("lint"),status:projectScriptStatusSchema,output:z104.string()})]),conflictSchema2=z104.object({surface:surfaceNameSchema,key:z104.string(),kind:z104.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"]).optional(),description:z104.string(),parentValue:z104.unknown().optional(),childValue:z104.unknown().optional(),conflictingFields:z104.array(z104.string()).optional(),code:z104.object({path:z104.string(),unresolvable:z104.boolean().optional(),reason:z104.string().optional()}).optional()}).passthrough(),codeConflictBlobSchema2=z104.object({oid:z104.string().optional(),content:z104.string().optional(),truncated:z104.boolean(),binary:z104.boolean()}),codeConflictDetailSchema=z104.object({path:z104.string(),base:codeConflictBlobSchema2,ours:codeConflictBlobSchema2,theirs:codeConflictBlobSchema2,result:codeConflictBlobSchema2,sourceTipSha:z104.string(),targetTipSha:z104.string(),mergeBaseSha:z104.string().optional()}),resolutionChoiceSchema=z104.enum(["parent","child","pick"]),conflictResolutionSchema2=z104.object({surface:surfaceNameSchema,key:z104.string().min(1),choice:resolutionChoiceSchema,pickedValue:z104.unknown().optional(),fieldPicks:z104.array(z104.object({field:z104.string().min(1),choice:resolutionChoiceSchema,pickedValue:z104.unknown().optional()})).optional()}).superRefine((resolution,context)=>{resolution.choice==="pick"&&resolution.pickedValue===void 0&&!resolution.fieldPicks?.length&&context.addIssue({code:"custom",message:"Pass pickedValue when choice is 'pick'.",path:["pickedValue"]}),resolution.fieldPicks?.forEach((fieldPick,index)=>{fieldPick.choice==="pick"&&fieldPick.pickedValue===void 0&&context.addIssue({code:"custom",message:"Pass pickedValue when choice is 'pick'.",path:["fieldPicks",index,"pickedValue"]})})}),resolvedMergeStrategySchema=z104.object({engine:z104.enum(["ff-only","auto","theirs","ours","manual"]),vendor:z104.enum(["ff_only","ff_prefer","merge"]),squash:z104.boolean()}),sessionsOperations={"sessions.start":{domain:"sessions",summary:"Start an isolated work session. At capacity, Fimo cleans expired/leaked work, then the oldest inactive temporary work before refusing. Temporary expiry is a maximum lifetime, not guaranteed retention. Inspect your sessions and close unused work; durable work and active operations are not pressure-reclaimed.",accessScope:"code",effect:"mutation",inputSchema:z104.object({projectId:uuidSchema,targetBranch:branchNameSchema.optional(),name:z104.string().trim().min(1).max(120).optional(),goal:z104.string().trim().min(1).max(500).optional()}).strict(),outputSchema:z104.object({session:sessionEnvelopeSchema,adopted:z104.boolean()}),buildRequest:__name(({projectId,targetBranch,name,goal})=>({method:"POST",path:managementProjectPath(projectId,"/sessions"),body:withoutUndefined({targetBranch,name,goal})}),"buildRequest")},"sessions.get":{domain:"sessions",summary:"Get one owned Fimo work session for lifecycle recovery.",accessScope:"code",effect:"read",inputSchema:z104.object({projectId:uuidSchema,sessionId:uuidSchema}).strict(),outputSchema:sessionEnvelopeSchema,buildRequest:__name(({projectId,sessionId})=>({method:"GET",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}`)}),"buildRequest")},"sessions.list":{domain:"sessions",summary:"Discover work sessions. Defaults to mine; project lists authorized work within the connection's client boundary.",accessScope:"code",effect:"read",inputSchema:z104.object({projectId:uuidSchema,status:sessionStatusSchema.optional(),scope:z104.enum(["mine","project"]).optional(),cursor:paginationShape.cursor,limit:z104.number().int().min(1).max(100).optional()}).strict(),outputSchema:z104.object({items:z104.array(sessionEnvelopeSchema),nextCursor:z104.string().nullable()}),buildRequest:__name(({projectId,status,cursor,limit,scope:scope2})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/sessions"),{status,cursor,limit,scope:scope2})}),"buildRequest")},"sessions.changes":{domain:"sessions",summary:"Review bounded changes in an owned work session before closing it.",accessScope:"code",effect:"read",inputSchema:z104.object({projectId:uuidSchema,sessionId:uuidSchema,detail:z104.boolean().optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({changes:sessionChangesSchema}),buildRequest:__name(({projectId,sessionId,detail})=>({method:"GET",path:addQuery(managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/changes`),{detail})}),"buildRequest"),projectOutput:projectSessionChanges},"sessions.requestReview":{domain:"sessions",summary:"Save current work in one owned session and request human review. Keeps that same session visible and durable, with no expiry. Returns the saved revision and secure review URL. Does not merge, publish or finish a run. Retry unchanged work to reuse its review.",accessScope:"code",effect:"mutation",inputSchema:z104.object({projectId:uuidSchema,sessionId:uuidSchema,summary:z104.string().trim().min(1).max(240),targetBranch:branchNameSchema.optional()}).strict(),outputSchema:z104.object({requested:z104.literal(!0),alreadyRequested:z104.boolean(),reviewId:uuidSchema,reviewUrl:z104.url(),status:z104.literal("pending"),sessionId:uuidSchema,branch:branchNameSchema,targetBranch:branchNameSchema,revision:z104.string().min(1),savedRevision:z104.string().min(1),fingerprint:z104.string().min(1),visibility:z104.literal("user-visible"),retention:z104.literal("durable"),expiresAt:z104.null(),merged:z104.literal(!1),published:z104.literal(!1),links:z104.object({preview:z104.url(),changes:z104.url(),conversation:z104.url().nullable()})}),buildRequest:__name(({projectId,sessionId,summary:summary2,targetBranch})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/review`),body:withoutUndefined({summary:summary2,targetBranch})}),"buildRequest")},"sessions.setRetention":{domain:"sessions",summary:"Add exactly 1\u201330 whole days to the current expiry of temporary work. Repeat for more time; each request is bounded to that range, not the total. Returns actual expiry. Rejects unchanged with invalid_session_retention when the work is not temporary or has no deadline. Does not save, show, merge or publish; eligible early capacity cleanup still applies.",accessScope:"code",effect:"mutation",inputSchema:z104.object({projectId:uuidSchema,sessionId:uuidSchema,additionalDays:z104.number().int().min(1).max(30)}).strict(),outputSchema:sessionEnvelopeSchema.extend({retention:z104.literal("temporary"),visibility:z104.enum(["internal","user-visible"]),expiresAt:z104.iso.datetime()}),buildRequest:__name(({projectId,sessionId,additionalDays})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/retention`),body:{additionalDays}}),"buildRequest")},"sessions.validate":{domain:"sessions",summary:"Run site validation inside an owned Fimo work session and wait for its terminal result.",accessScope:"code",effect:"mutation",inputSchema:z104.object({projectId:uuidSchema,sessionId:uuidSchema}).strict(),outputSchema:sessionEnvelopeSchema.extend({validation:sessionValidationSchema}),buildRequest:__name(({projectId,sessionId})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/validate`)}),"buildRequest")},"sessions.runOperation":{domain:"sessions",summary:"Run an approved sandbox operation in an owned work session: 'dependencies_install', 'schemas_sync', or the project's own 'typecheck' or 'lint' script, which report their output without saving.",accessScope:"code",effect:"mutation",inputSchema:z104.object({projectId:uuidSchema,sessionId:uuidSchema,operation:z104.string().min(1).max(100),args:z104.record(z104.string(),z104.unknown()).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({operation:sessionOperationResultSchema}),buildRequest:__name(({projectId,sessionId,operation,args})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/operations`),body:args===void 0?{operation}:{operation,args}}),"buildRequest")},"sessions.close":{domain:"sessions",summary:"Merge or discard an owned Fimo work session.",accessScope:"code",effect:"mutation",inputSchema:z104.object({projectId:uuidSchema,sessionId:uuidSchema,action:z104.enum(["merge","discard"]),message:z104.string().max(1e3).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({outcome:z104.enum(["merged","no_changes","discarded","conflicts","failed"]),closed:z104.boolean(),mergeId:uuidSchema.optional(),conflictCount:z104.number().int().nonnegative().optional(),conflicts:z104.array(sessionConflictSummarySchema).optional(),parentAdvanced:z104.boolean().optional(),code:z104.string().optional(),summary:z104.string().nullable().optional()}),buildRequest:__name(({projectId,sessionId,action,message})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/close`),body:withoutUndefined({action,message})}),"buildRequest"),projectOutput:projectSessionConflicts},"sessions.conflicts":{domain:"sessions",summary:"Inspect one cursor-paginated parked session merge and optionally hydrate one code conflict.",accessScope:"code",effect:"read",inputSchema:z104.object({projectId:uuidSchema,sessionId:uuidSchema,mergeId:uuidSchema.optional(),cursor:paginationShape.cursor,limit:z104.number().int().min(1).max(100).optional(),codePath:z104.string().min(1).max(1024).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({merge:z104.object({mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,status:z104.enum(["in_progress","complete","failed","rolled_back","conflicts"]),conflictCount:z104.number().int().nonnegative(),error:z104.string().nullable()}),conflicts:z104.array(conflictSchema2).max(100),nextCursor:z104.string().nullable(),codeDetail:codeConflictDetailSchema.nullable().optional()}),buildRequest:__name(({projectId,sessionId,mergeId,cursor,limit,codePath})=>({method:"GET",path:addQuery(managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/conflicts`),{mergeId,cursor,limit,codePath})}),"buildRequest"),projectOutput:projectSessionConflicts},"sessions.resolve":{domain:"sessions",summary:"Resolve a parked session merge and start its successor merge.",accessScope:"code",effect:"mutation",inputSchema:z104.object({projectId:uuidSchema,sessionId:uuidSchema,mergeId:uuidSchema,resolutions:z104.array(conflictResolutionSchema2).min(1).max(500)}).strict(),outputSchema:sessionEnvelopeSchema.extend({outcome:z104.literal("resolving"),mergeId:uuidSchema,supersededMergeId:uuidSchema,strategy:resolvedMergeStrategySchema,acceptedAt:z104.iso.datetime()}),buildRequest:__name(({projectId,sessionId,mergeId,resolutions})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/resolve`),body:{mergeId,resolutions:backendConflictResolutions(resolutions)}}),"buildRequest")}}}});import{z as z105}from"zod";var singlesOperations,init_singles=__esm({"../../packages/sdk/dist/operations/singles.js"(){"use strict";init_common2();init_entries();singlesOperations={"singles.get":{domain:"singles",summary:"Read the document-scoped value of a Single content type.",accessScope:"read",effect:"read",inputSchema:z105.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,locale:localeSchema.optional(),populate:populateSchema}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,locale,populate})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,`/documents/${encodeURIComponent(typeName)}`),{locale,populate})}),"buildRequest")},"singles.update":{domain:"singles",summary:"Update the document-scoped value of a Single content type.",accessScope:"write",effect:"mutation",inputSchema:z105.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,data:entryDataSchema,locale:localeSchema.optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,data,locale})=>({method:"PUT",path:addQuery(tenantPath(projectId,branch,`/documents/${encodeURIComponent(typeName)}`),{locale}),body:{data}}),"buildRequest")}}}});import{z as z106}from"zod";var supportReportInputSchema,supportReportResultSchema,supportOperations,init_support=__esm({"../../packages/sdk/dist/operations/support.js"(){"use strict";init_common2();supportReportInputSchema=z106.object({message:z106.string().trim().min(1).max(2e4),projectId:uuidSchema.optional(),branch:branchNameSchema.optional()}).strict().superRefine((input,context)=>{input.branch!==void 0&&input.projectId===void 0&&context.addIssue({code:"custom",message:"Pass projectId when providing branch.",path:["projectId"]})}),supportReportResultSchema=z106.object({id:uuidSchema,deliveryStatus:z106.enum(["pending","delivered","failed"]),message:z106.string()}),supportOperations={"support.report":{domain:"support",summary:"Submit an approved report to Fimo support immediately. Call only when the user explicitly asks to contact support or approves the exact report.",accessScope:"write",effect:"mutation",inputSchema:supportReportInputSchema,outputSchema:z106.object({data:supportReportResultSchema}),buildRequest:__name(({message,projectId,branch})=>({method:"POST",path:"/support/issues/agent",body:withoutUndefined({message,projectId,branch})}),"buildRequest")}}}});import{z as z107}from"zod";var jsonObjectSchema,deliveryStatusSchema,webhookSchema,deliverySchema,attemptSchema,deliveriesPageSchema,eventSchema,webhookWriteSchema,webhooksOperations,init_webhooks=__esm({"../../packages/sdk/dist/operations/webhooks.js"(){"use strict";init_common2();jsonObjectSchema=z107.record(z107.string(),z107.unknown()),deliveryStatusSchema=z107.enum(["pending","delivering","retrying","succeeded","failed"]),webhookSchema=z107.object({id:uuidSchema,projectId:uuidSchema,name:z107.string(),eventType:z107.string().min(1),enabled:z107.boolean(),destination:z107.object({host:z107.string(),maskedUrl:z107.string(),kind:z107.string()}),filter:jsonObjectSchema,headers:z107.array(jsonObjectSchema),bodyTemplate:z107.unknown().nullable(),signingEnabled:z107.boolean(),lastDeliveryStatus:deliveryStatusSchema.nullable()}).passthrough(),deliverySchema=z107.object({id:uuidSchema,webhookId:uuidSchema,projectId:uuidSchema,eventType:z107.string().min(1),status:deliveryStatusSchema,attemptCount:z107.number().int().nonnegative(),responseStatus:z107.number().int().nullable(),createdAt:z107.iso.datetime()}).passthrough(),attemptSchema=z107.object({id:uuidSchema,deliveryId:uuidSchema,attempt:z107.number().int().positive(),status:z107.enum(["delivering","succeeded","failed"]),createdAt:z107.iso.datetime()}).passthrough(),deliveriesPageSchema=z107.object({items:z107.array(deliverySchema),pagination:z107.object({page:z107.number().int().positive(),limit:z107.number().int().positive(),total:z107.number().int().nonnegative(),totalPages:z107.number().int().positive(),hasMore:z107.boolean()}),stats:z107.object({total:z107.number().int().nonnegative(),succeeded:z107.number().int().nonnegative(),failed:z107.number().int().nonnegative()})}),eventSchema=z107.object({type:z107.string().min(1),family:z107.string(),description:z107.string(),variables:z107.array(z107.string()),data:z107.unknown().optional()}).passthrough(),webhookWriteSchema=jsonObjectSchema,webhooksOperations={"webhooks.events":{domain:"webhooks",summary:"List the webhook event catalog available to one site.",accessScope:"read",effect:"read",inputSchema:z107.object({projectId:uuidSchema}).strict(),outputSchema:z107.array(eventSchema),buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/webhooks/events")}),"buildRequest"),projectOutput:__name(body=>z107.array(eventSchema).parse(responseData(body)),"projectOutput")},"webhooks.list":{domain:"webhooks",summary:"List outbound webhooks configured for one site.",accessScope:"read",effect:"read",inputSchema:z107.object({projectId:uuidSchema}).strict(),outputSchema:z107.array(webhookSchema),buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/webhooks")}),"buildRequest"),projectOutput:__name(body=>z107.array(webhookSchema).parse(responseData(body)),"projectOutput")},"webhooks.get":{domain:"webhooks",summary:"Read one outbound site webhook.",accessScope:"read",effect:"read",inputSchema:z107.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:webhookSchema,buildRequest:__name(({projectId,webhookId})=>({method:"GET",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}`)}),"buildRequest"),projectOutput:__name(body=>webhookSchema.parse(responseData(body)),"projectOutput")},"webhooks.create":{domain:"webhooks",summary:"Create an outbound site webhook.",accessScope:"write",effect:"mutation",inputSchema:z107.object({projectId:uuidSchema,webhook:webhookWriteSchema}).strict(),outputSchema:z107.object({webhook:webhookSchema,signingSecret:z107.string().min(1)}),buildRequest:__name(({projectId,webhook})=>({method:"POST",path:managementProjectPath(projectId,"/webhooks"),body:webhook}),"buildRequest"),projectOutput:__name(body=>z107.object({webhook:webhookSchema,signingSecret:z107.string().min(1)}).parse(responseData(body)),"projectOutput")},"webhooks.update":{domain:"webhooks",summary:"Update one outbound site webhook.",accessScope:"write",effect:"mutation",inputSchema:z107.object({projectId:uuidSchema,webhookId:uuidSchema,webhook:webhookWriteSchema}).strict(),outputSchema:webhookSchema,buildRequest:__name(({projectId,webhookId,webhook})=>({method:"PATCH",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}`),body:webhook}),"buildRequest"),projectOutput:__name(body=>webhookSchema.parse(responseData(body)),"projectOutput")},"webhooks.delete":{domain:"webhooks",summary:"Delete one outbound site webhook.",accessScope:"write",effect:"mutation",inputSchema:z107.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:z107.unknown(),buildRequest:__name(({projectId,webhookId})=>({method:"DELETE",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}`)}),"buildRequest")},"webhooks.rotateSecret":{domain:"webhooks",summary:"Rotate and reveal the signing secret for one site webhook.",accessScope:"write",effect:"mutation",inputSchema:z107.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:z107.string().min(1),buildRequest:__name(({projectId,webhookId})=>({method:"POST",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/rotate-signing-secret`)}),"buildRequest"),projectOutput:__name(body=>z107.object({signingSecret:z107.string().min(1)}).parse(responseData(body)).signingSecret,"projectOutput")},"webhooks.test":{domain:"webhooks",summary:"Queue a test delivery for one site webhook.",accessScope:"write",effect:"mutation",inputSchema:z107.object({projectId:uuidSchema,webhookId:uuidSchema,data:jsonObjectSchema.optional()}).strict(),outputSchema:deliverySchema,buildRequest:__name(({projectId,webhookId,data})=>({method:"POST",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/test`),body:data===void 0?{}:{data}}),"buildRequest"),projectOutput:__name(body=>deliverySchema.parse(responseData(body)),"projectOutput")},"webhooks.listDeliveries":{domain:"webhooks",summary:"List webhook delivery history with cursor pagination; legacy page input remains supported.",accessScope:"read",effect:"read",inputSchema:z107.object({projectId:uuidSchema,webhookId:uuidSchema,...numberedPaginationShape,limit:z107.number().int().min(1).max(100).optional()}).strict().superRefine(numberedPaginationRefinement),outputSchema:deliveriesPageSchema.extend({nextCursor:z107.string().nullable()}),buildRequest:__name(({projectId,webhookId,page,cursor,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/deliveries`),{page:paginationPage({page,cursor}),limit})}),"buildRequest"),projectOutput:__name(body=>{let result=deliveriesPageSchema.parse(responseData(body));return{...result,nextCursor:result.pagination.hasMore?String(result.pagination.page+1):null}},"projectOutput")},"webhooks.getDelivery":{domain:"webhooks",summary:"Read one webhook delivery and all of its attempts.",accessScope:"read",effect:"read",inputSchema:z107.object({projectId:uuidSchema,webhookId:uuidSchema,deliveryId:uuidSchema}).strict(),outputSchema:z107.object({delivery:deliverySchema,attempts:z107.array(attemptSchema)}),buildRequest:__name(({projectId,webhookId,deliveryId})=>({method:"GET",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/deliveries/${encodeURIComponent(deliveryId)}`)}),"buildRequest"),projectOutput:__name(body=>z107.object({delivery:deliverySchema,attempts:z107.array(attemptSchema)}).parse(responseData(body)),"projectOutput")},"webhooks.retryDelivery":{domain:"webhooks",summary:"Retry one failed webhook delivery.",accessScope:"write",effect:"mutation",inputSchema:z107.object({projectId:uuidSchema,webhookId:uuidSchema,deliveryId:uuidSchema}).strict(),outputSchema:deliverySchema,buildRequest:__name(({projectId,webhookId,deliveryId})=>({method:"POST",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/deliveries/${encodeURIComponent(deliveryId)}/retry`)}),"buildRequest"),projectOutput:__name(body=>deliverySchema.parse(responseData(body)),"projectOutput")}}}});import{z as z108}from"zod";var fimoOperations,fimoOperationManifestEntrySchema,fimoOperationManifestSchema,fimoOperationManifest,init_operations=__esm({"../../packages/sdk/dist/operations.js"(){"use strict";init_analytics();init_assets();init_billing();init_branches();init_domains();init_entries();init_environments();init_files();init_forms();init_generation();init_history();init_hosting();init_knowledge();init_labels();init_locales();init_organizations();init_projects();init_schedules();init_schemas();init_secrets();init_sessions();init_singles();init_support();init_webhooks();fimoOperations={...projectsOperations,...organizationsOperations,...domainsOperations,...generationOperations,...historyOperations,...environmentsOperations,...secretsOperations,...schedulesOperations,...webhooksOperations,...branchesOperations,...schemasOperations,...supportOperations,...sessionsOperations,...entriesOperations,...singlesOperations,...knowledgeOperations,...labelsOperations,...localesOperations,...assetsOperations,...formsOperations,...hostingOperations,...analyticsOperations,...filesOperations,...billingOperations},fimoOperationManifestEntrySchema=z108.object({id:z108.string().regex(/^[a-zA-Z_$][\w$]*\.[a-zA-Z_$][\w$]*$/),domain:z108.string().min(1),summary:z108.string().min(1),accessScope:z108.enum(["read","write","code","agents"]),effect:z108.enum(["read","mutation"]),inputJsonSchema:z108.record(z108.string(),z108.unknown()),outputJsonSchema:z108.record(z108.string(),z108.unknown())}).strict(),fimoOperationManifestSchema=z108.array(fimoOperationManifestEntrySchema),fimoOperationManifest=Object.entries(fimoOperations).map(([id,operation])=>({id,domain:operation.domain,summary:operation.summary,accessScope:operation.accessScope,effect:operation.effect,inputJsonSchema:z108.toJSONSchema(operation.inputSchema,{target:"draft-7",io:"input"}),outputJsonSchema:z108.toJSONSchema(operation.outputSchema,{target:"draft-7"})}))}});function createFimoClient(input){return{async execute(operationId,operationInput){let operation=fimoOperations[operationId],parsedInput=operation.inputSchema.parse(operationInput),response=await input.transport.execute(operation.buildRequest(parsedInput)),output=operation.projectOutput?operation.projectOutput(response,parsedInput):response;return operation.outputSchema.parse(output)}}}var init_client=__esm({"../../packages/sdk/dist/client.js"(){"use strict";init_operations();__name(createFimoClient,"createFimoClient")}});var init_dist2=__esm({"../../packages/sdk/dist/index.js"(){"use strict";init_client()}});import{spawnSync}from"node:child_process";import fs4 from"node:fs";import path4 from"node:path";import{setTimeout as sleep}from"node:timers/promises";function isPublishedInstall(cliRoot=CLI_ROOT){return fs4.existsSync(path4.join(cliRoot,"release.json"))}function buildSkipsVersionCheck(cliRoot=CLI_ROOT,readFile6=defaultReadFile){try{return JSON.parse(readFile6(path4.join(cliRoot,"release.json"))).skipVersionCheck===!0}catch{return!1}}function defaultReadFile(file){return fs4.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:path4.resolve(result.stdout.trim(),"fimo")}function normalizedPath(input){try{return fs4.realpathSync(input)}catch{return path4.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{fs4.mkdirSync(lockDir);return}catch(error){if(error.code!=="EEXIST")throw error}let stale=!1;try{stale=Date.now()-fs4.statSync(lockDir).mtimeMs>LOCK_STALE_MS}catch{continue}if(stale){try{fs4.rmdirSync(lockDir)}catch{}continue}if(Date.now()>=deadline)throw new Error("auto-upgrade lock timeout");await sleep(LOCK_POLL_MS)}}function readGlobalFimoVersion(){let root=resolveGlobalFimoRoot();if(!root)return null;try{let pkg=JSON.parse(fs4.readFileSync(path4.join(root,"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=path4.join(loadConfig().configDir,"auto-upgrade.lock");try{fs4.mkdirSync(path4.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{fs4.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 fs5 from"node:fs";import path5 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";function getCliVersion(){try{let raw=fs5.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=path5.resolve(path5.dirname(THIS_FILE2),"..",".."),PACKAGE_JSON_PATH=path5.join(CLI_ROOT2,"package.json");__name(getCliVersion,"getCliVersion")}});function branchNameOf(row2){return row2.branch??row2.env}function parentBranchOf(row2){return row2.parentBranch??row2.parentEnv}function projectUnclaimedError(cfg,body){let{feature,message}=body&&typeof body=="object"?body:{};return new ProjectUnclaimedError(cfg.apiUrl,typeof feature=="string"?feature:null,findProjectToken(cfg)?.file.claimUrl??null,typeof message=="string"&&message?message:void 0)}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,container=error&&typeof error=="object"?error:parsed,issues="issues"in container?container.issues:void 0;return!Array.isArray(issues)||issues.length===0?null:issues.map(issue=>{let{path:path49,message}=issue;return`${Array.isArray(path49)&&path49.length>0?`${path49.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}function formatError(status,text,body){if(!text)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 text}async function parseError(response){let text=await response.text(),body;try{body=text?JSON.parse(text):void 0}catch{return{detail:formatError(response.status,text)}}let code2=body&&typeof body=="object"&&!Array.isArray(body)&&typeof body.code=="string"?body.code:void 0;return{detail:formatError(response.status,text,body),code:code2,body}}function throwUnauthorized(cfg,status){if(resolveAuth(cfg)?.kind==="project")throw new ProjectTokenRejectedError(cfg.apiUrl,status);try{recordAuthFailure(cfg)}catch{}throw new UnauthorizedError(cfg.apiUrl,status)}async function throwPermissionDenied(cfg,response){let required=[],server={},body;try{body=await response.json(),required=Array.isArray(body.required)?body.required:body.required?[body.required]:[],typeof body.code=="string"&&body.code&&(server.code=body.code),typeof body.message=="string"&&body.message&&(server.detail=body.message)}catch{}throw server.code==="project_unclaimed"?projectUnclaimedError(cfg,body):new PermissionDeniedError(cfg.apiUrl,required,void 0,server)}function createCliHttpTransport(cfg=loadConfig(),branch){let authHeaders=__name((init,defaultJsonContentType)=>{let headers=new Headers(init.headers),token=requireToken(cfg);return headers.set("Authorization",`Bearer ${token}`),defaultJsonContentType&&init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),branch&&!headers.has(FIMO_BRANCH_HEADER)&&headers.set(FIMO_BRANCH_HEADER,branch),headers},"authHeaders"),send=__name(async(path49,init={},defaultJsonContentType=!0)=>fimoFetch(`${cfg.apiUrl}${path49}`,{...init,headers:authHeaders(init,defaultJsonContentType)}),"send");return{async request(path49,init={},options={}){let response=await send(path49,init);if(response.status===401&&throwUnauthorized(cfg,response.status),response.status===403&&!options.preserveForbidden&&await throwPermissionDenied(cfg,response),!response.ok){let error=await parseError(response);throw error.code==="project_unclaimed"?projectUnclaimedError(cfg,error.body):new ApiRequestError(init.method??"GET",path49,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()},async response(path49,init={}){let response=await send(path49,init,!1);if(response.status===401&&throwUnauthorized(cfg,response.status),response.status===403&&await throwPermissionDenied(cfg,response),!response.ok){let error=await parseError(response);throw new ApiRequestError(init.method??"GET",path49,response.status,error.detail,error.code,error.body)}return response}}}function createCliFimoClient(cfg=loadConfig(),branch){let transport=createCliHttpTransport(cfg,branch);return createFimoClient({transport:{execute:__name(request=>transport.request(`/api${request.path}`,{method:request.method,headers:!branch&&request.context?.branch!==void 0?{[FIMO_BRANCH_HEADER]:request.context.branch}:void 0,body:request.body===void 0?void 0:JSON.stringify(request.body)},{preserveForbidden:request.preserveForbidden}),"execute")}})}function requiredPermissions(body){let required=typeof body=="object"&&body!==null?body.required:void 0;return Array.isArray(required)?required.filter(value=>typeof value=="string"):typeof required=="string"?[required]:[]}var ApiRequestError,UnauthorizedError,ProjectTokenRejectedError,PermissionDeniedError,ProjectUnclaimedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_BRANCH_HEADER,init_sdk_transport=__esm({"src/cli/sdk-transport.ts"(){init_esm();init_dist();init_dist2();init_auth();init_auto_upgrade();init_config();init_version();__name(branchNameOf,"branchNameOf");__name(parentBranchOf,"parentBranchOf");ApiRequestError=class extends Error{static{__name(this,"ApiRequestError")}status;method;path;detail;code;body;constructor(method,path49,status,detail,code2,body){super(`API ${method} ${path49} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path49,this.status=status,this.detail=detail,this.code=code2,this.body=body}},UnauthorizedError=class extends Error{static{__name(this,"UnauthorizedError")}apiUrl;status;constructor(apiUrl,status,message){super(message??`Session for ${apiUrl} expired or invalid (HTTP ${status}).`),this.name="UnauthorizedError",this.apiUrl=apiUrl,this.status=status}},ProjectTokenRejectedError=class extends UnauthorizedError{static{__name(this,"ProjectTokenRejectedError")}constructor(apiUrl,status){super(apiUrl,status,"The project token in this directory no longer works."),this.name="ProjectTokenRejectedError"}},PermissionDeniedError=class extends Error{static{__name(this,"PermissionDeniedError")}apiUrl;required;code;detail;constructor(apiUrl,required=[],message,server={}){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,this.code=server.code,this.detail=server.detail}},ProjectUnclaimedError=class extends PermissionDeniedError{static{__name(this,"ProjectUnclaimedError")}feature;claimUrl;constructor(apiUrl,feature,claimUrl,detail){let label=feature?UNCLAIMED_PLAN.locked[feature]:void 0,message=label?`${label} unlocks once a person claims this site.`:detail??"This action unlocks once a person claims this site.";super(apiUrl,[],message,{code:"project_unclaimed",detail}),this.name="ProjectUnclaimedError",this.feature=feature,this.claimUrl=claimUrl}};__name(projectUnclaimedError,"projectUnclaimedError");CLI_VERSION_HEADER="X-Fimo-CLI-Version",CLI_LATEST_HEADER="X-Fimo-CLI-Latest",CLI_AUTO_UPGRADE_HEADER="X-Fimo-CLI-Auto-Upgrade",FIMO_BRANCH_HEADER="X-Fimo-Branch";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");__name(formatError,"formatError");__name(parseError,"parseError");__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");__name(createCliHttpTransport,"createCliHttpTransport");__name(createCliFimoClient,"createCliFimoClient");__name(requiredPermissions,"requiredPermissions")}});import{execFile}from"node:child_process";import{promisify}from"node:util";async function runGit(args,cwd){let{stdout}=await execFileAsync("git",args,{cwd});return stdout.trim()}async function isGitRepo(cwd){try{return await runGit(["rev-parse","--is-inside-work-tree"],cwd),!0}catch{return!1}}async function hasUncommittedChanges(cwd){return(await runGit(["status","--porcelain"],cwd)).length>0}async function cloneRepo(args){await execFileAsync("git",["clone","--branch",args.branch,"--single-branch",args.url,args.targetDir])}function isMissingRemoteBranch(error){let stderr=extractStderr(error).toLowerCase();return stderr.includes("remote branch")&&stderr.includes("not found")}async function remoteHasBranch(remoteUrl,branch){let{stdout}=await execFileAsync("git",["ls-remote","--heads",remoteUrl,branch]);return stdout.trim().length>0}async function currentBranch2(cwd){return runGit(["symbolic-ref","--short","-q","HEAD"],cwd)}async function commitSubjectOrNull(cwd,sha){try{return await runGit(["log","-1","--format=%s",sha,"--"],cwd)}catch{return null}}async function currentTagOrNull(cwd){try{return await runGit(["describe","--tags","--exact-match","HEAD"],cwd)||null}catch{return null}}function isReleaseTag(tag){return tag?/^release\/.+/.test(tag):!1}function classifyPushError(error){let stderr=extractStderr(error),lower=stderr.toLowerCase();return lower.includes("invalid or expired token")||lower.includes("expired token")||lower.includes("invalid token")||lower.includes("could not obtain git credentials")||lower.includes("not signed in")?{kind:"auth",stderr}:lower.includes("remote rejected")||lower.includes("protected")||lower.includes("no-push")||lower.includes("push declined")||lower.includes("not allowed to push")||lower.includes("permission to push")||lower.includes("forbidden")||lower.includes("403")?{kind:"protected",stderr}:lower.includes("non-fast-forward")||lower.includes("rejected")||lower.includes("fetch first")||lower.includes("updates were rejected")?{kind:"non-fast-forward",stderr}:lower.includes("authentication")||lower.includes("permission denied")?{kind:"auth",stderr}:lower.includes("could not resolve host")||lower.includes("timed out")||lower.includes("connection")?{kind:"network",stderr}:{kind:"unknown",stderr}}function gitErrorSummary(error){let lines=extractStderr(error).split(`
|
|
44
|
+
`,{mode:384})}function resolveAuth(cfg=loadConfig()){let bearer=cfg.token||process.env.FIMO_API_TOKEN?.trim();if(bearer)return bearer.startsWith(PROJECT_TOKEN_PREFIX)?{kind:"project",token:bearer,tokenFile:null}:{kind:"bearer",token:bearer};let tokenFile=findProjectToken(cfg);if(tokenFile)return{kind:"project",token:tokenFile.file.token,tokenFile};let credentials=readCredentials(cfg);return credentials?.access_token?{kind:"session",token:credentials.access_token,credentials}:null}function requireAuth(cfg=loadConfig()){let auth=resolveAuth(cfg);if(!auth)throw new NotAuthenticatedError(cfg.apiUrl);return auth}function requireToken(cfg=loadConfig()){return requireAuth(cfg).token}function requireAccountCredentials(cfg=loadConfig()){if(resolveAuth(cfg)?.kind==="project")throw new AccountRequiredError(cfg.apiUrl);return requireCredentials(cfg)}function requireCredentials(cfg=loadConfig()){let creds=readCredentials(cfg);if(!creds?.access_token)throw new NotAuthenticatedError(cfg.apiUrl);return creds}var PROJECT_TOKEN_FILE,NotAuthenticatedError,AccountRequiredError,init_auth=__esm({"src/cli/auth.ts"(){init_esm();init_config();init_credentials_path();PROJECT_TOKEN_FILE=path2.join(".fimo","credentials.local.json"),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}},AccountRequiredError=class extends NotAuthenticatedError{static{__name(this,"AccountRequiredError")}constructor(apiUrl){super(apiUrl,"This command needs a Fimo account, but this directory uses the project token of an unclaimed site."),this.name="AccountRequiredError"}};__name(ensureCredentialsDir,"ensureCredentialsDir");__name(readCredentials,"readCredentials");__name(writeCredentials,"writeCredentials");__name(clearCredentials,"clearCredentials");__name(setActiveOrganization,"setActiveOrganization");__name(recordAuthFailure,"recordAuthFailure");__name(findProjectToken,"findProjectToken");__name(writeProjectToken,"writeProjectToken");__name(resolveAuth,"resolveAuth");__name(requireAuth,"requireAuth");__name(requireToken,"requireToken");__name(requireAccountCredentials,"requireAccountCredentials");__name(requireCredentials,"requireCredentials")}});function detectProjectLayout(paths){let hasCurrentProject=!1,hasLegacyProject=!1,hasCurrentMarker=!1,hasLegacyMarker=!1;for(let input of paths){let file=input.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/$/,"");hasCurrentProject||=file===CURRENT_PROJECT_LAYOUT.project,hasLegacyProject||=file===LEGACY_PROJECT_LAYOUT.project,hasCurrentMarker||=file===CURRENT_PROJECT_LAYOUT.config,hasLegacyMarker||=file===LEGACY_PROJECT_LAYOUT.config||file===LEGACY_AGENT_POLICY_PATH}return hasCurrentProject?"current":hasLegacyProject?"legacy":hasCurrentMarker?"current":hasLegacyMarker?"legacy":null}function getProjectLayoutPaths(layout){return layout==="current"?CURRENT_PROJECT_LAYOUT:LEGACY_PROJECT_LAYOUT}function selectProjectConfigPath(paths,layout){let files=new Set(Array.from(paths,file=>file.replace(/\\/g,"/").replace(/^\.\//,"")));return(layout??detectProjectLayout(files)??"current")==="current"?CURRENT_PROJECT_LAYOUT.config:files.has(LEGACY_AGENT_POLICY_PATH)&&!files.has(LEGACY_PROJECT_LAYOUT.config)?LEGACY_AGENT_POLICY_PATH:LEGACY_PROJECT_LAYOUT.config}var CURRENT_PROJECT_LAYOUT,LEGACY_PROJECT_LAYOUT,LEGACY_AGENT_POLICY_PATH,init_project_layout=__esm({"src/runtime/project-layout.ts"(){CURRENT_PROJECT_LAYOUT={project:".fimo/project.json",config:".fimo/config.json"},LEGACY_PROJECT_LAYOUT={project:".fimo.settings.json",config:"fimo-config.json"},LEGACY_AGENT_POLICY_PATH="fimo.config.json";__name(detectProjectLayout,"detectProjectLayout");__name(getProjectLayoutPaths,"getProjectLayoutPaths");__name(selectProjectConfigPath,"selectProjectConfigPath")}});function isValidBranch2(branch){return typeof branch!="string"||branch.length===0||branch.length>255||branch.startsWith("-")||branch.startsWith(".")||branch.includes("//")||branch.includes("--")||branch.split("/").some(segment=>segment==="..")?!1:BRANCH_ID_REGEX2.test(branch)}function fnv1a82(s){let h=2166136261;for(let i=0;i<s.length;i++)h^=s.charCodeAt(i),h=Math.imul(h,16777619);return(h>>>0).toString(16).padStart(8,"0")}function envResourceKey2(branch){let base=branch.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,15),hash=fnv1a82(branch);return base?`${base}-${hash}`:hash}function buildTenantApiUrl2(projectId,branch,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId}-${envResourceKey2(branch)}.${url.hostname}`,url.toString().replace(/\/$/,"")}function buildLocalRuntimeEnv(options){return{...Object.fromEntries(LOCAL_CONTENT_API_ENV_KEYS.map(key=>[key,options.tenantApiUrl])),...Object.fromEntries(LOCAL_ENV_SELECTOR_KEYS.map(key=>[key,options.branch]))}}var BRANCH_ID_REGEX2,LOCAL_CONTENT_API_ENV_KEYS,LOCAL_ENV_SELECTOR_KEYS,init_branch_identity=__esm({"src/runtime/shared/branch-identity.ts"(){BRANCH_ID_REGEX2=/^[a-zA-Z0-9._/-]+$/;__name(isValidBranch2,"isValidBranch");__name(fnv1a82,"fnv1a8");__name(envResourceKey2,"envResourceKey");__name(buildTenantApiUrl2,"buildTenantApiUrl");LOCAL_CONTENT_API_ENV_KEYS=["FIMO_CONTENT_API_URL","VITE_API_URL","NEXT_PUBLIC_FIMO_API_URL","PUBLIC_FIMO_API_URL"],LOCAL_ENV_SELECTOR_KEYS=["FIMO_ENV","NEXT_PUBLIC_FIMO_ENV"];__name(buildLocalRuntimeEnv,"buildLocalRuntimeEnv")}});import{execFileSync}from"node:child_process";import fs3 from"node:fs";import path3 from"node:path";import{parseEnv}from"node:util";function resolveLocalRuntimeEnv(options){let root=findProjectRoot(options.cwd),link=root?readProjectLink(root):null;if(!root||!link)return null;let branch=currentBranch(root);if(!branch)return null;let tenantApiUrl=buildTenantApiUrl2(link.projectId,branch,link.tenantApiBaseUrl);return{env:branch,tenantApiUrl,source:"branch",values:buildLocalRuntimeEnv({tenantApiUrl,branch}),link}}function findStaleFimoOverride(explicit,derived){for(let key of LOCAL_CONTENT_API_ENV_KEYS){let value=explicit[key];if(value&&value!==derived.tenantApiUrl&&isFimoMintedTenantUrl(value,derived.link))return{key,explicit:value,derived:derived.tenantApiUrl}}return null}function staleOverrideMessage(stale){return`[fimo] An env file pins the app to ${stale.explicit} (seeded by an older CLI), so it will NOT follow the git branch (${stale.derived}). Run \`fimo link\` to remove that line, or delete it yourself.`}function isFimoMintedTenantUrl(value,link){try{let candidate=new URL(value),base=new URL(link.tenantApiBaseUrl);return candidate.protocol===base.protocol&&candidate.port===base.port&&candidate.hostname.startsWith(`${link.projectId}-`)&&candidate.hostname.endsWith(`.${base.hostname}`)}catch{return!1}}function readLocalEnvFiles(cwd){let root=findProjectRoot(cwd)??cwd,values={};for(let file of[".env",".env.local"]){let filePath=path3.join(root,file);fs3.existsSync(filePath)&&Object.assign(values,parseEnv(fs3.readFileSync(filePath,"utf-8")))}return values}function currentBranch(root){try{let branch=execFileSync("git",["symbolic-ref","--short","-q","HEAD"],{cwd:root,stdio:["ignore","pipe","ignore"],encoding:"utf-8"}).trim();return branch&&isValidBranch2(branch)?branch:null}catch{return null}}function findProjectRoot(start){let dir=path3.resolve(start);for(;;){if(fs3.existsSync(path3.join(dir,CURRENT_PROJECT_LAYOUT.project))||fs3.existsSync(path3.join(dir,LEGACY_PROJECT_LAYOUT.project)))return dir;let parent=path3.dirname(dir);if(parent===dir)return null;dir=parent}}function readProjectLink(root){for(let layout of[CURRENT_PROJECT_LAYOUT,LEGACY_PROJECT_LAYOUT]){let file=path3.join(root,layout.project);if(fs3.existsSync(file))try{let parsed=JSON.parse(fs3.readFileSync(file,"utf-8"));if(typeof parsed.projectId=="string"&&parsed.projectId.length>0&&typeof parsed.tenantApiBaseUrl=="string"&&parsed.tenantApiBaseUrl.length>0)return{projectId:parsed.projectId,tenantApiBaseUrl:parsed.tenantApiBaseUrl}}catch{return null}}return null}var init_local_runtime_env=__esm({"src/runtime/shared/local-runtime-env.ts"(){init_project_layout();init_branch_identity();__name(resolveLocalRuntimeEnv,"resolveLocalRuntimeEnv");__name(findStaleFimoOverride,"findStaleFimoOverride");__name(staleOverrideMessage,"staleOverrideMessage");__name(isFimoMintedTenantUrl,"isFimoMintedTenantUrl");__name(readLocalEnvFiles,"readLocalEnvFiles");__name(currentBranch,"currentBranch");__name(findProjectRoot,"findProjectRoot");__name(readProjectLink,"readProjectLink")}});import{z as z84}from"zod";function createResponseSchema2(dataSchema){return z84.object({data:dataSchema})}function encodeBranchPathSegment2(branch){return encodeURIComponent(branch.replaceAll("/","--"))}function managementProjectPath(projectId,suffix){return`/management/projects/${encodeURIComponent(projectId)}${suffix}`}function managementBranchPath(projectId,branch,suffix){return managementProjectPath(projectId,`/branches/${encodeBranchPathSegment2(branch)}${suffix}`)}function tenantPath(projectId,branch,suffix){return`/tenant/${encodeURIComponent(projectId)}/branches/${encodeBranchPathSegment2(branch)}${suffix}`}function addQuery(path49,query){let params=new URLSearchParams;for(let[key,value]of Object.entries(query))value!=null&&(Array.isArray(value)?value.length>0&¶ms.set(key,value.join(",")):params.set(key,String(value)));let queryString=params.toString();return queryString?`${path49}?${queryString}`:path49}function withoutUndefined(values){return Object.fromEntries(Object.entries(values).filter(([,value])=>value!==void 0))}function utf8Text(maxBytes,message){return z84.string().refine(value=>new TextEncoder().encode(value).byteLength<=maxBytes,message)}function responseData(body){if(!body||typeof body!="object"||!("data"in body))throw new Error("Expected a Fimo API response envelope.");return body.data}function publicSurface(surface){return surface==="translations"?"labels":surface}function backendSurfaces(surfaces){return surfaces?.map(surface=>surface==="labels"?"translations":surface)}function recordValue(value,message){if(!value||typeof value!="object"||Array.isArray(value))throw new Error(message);return value}function paginationRefinement(input,context){if(input.cursor!=null&&input.offset!==void 0){context.addIssue({code:"custom",message:"Use either cursor or offset, not both.",path:["cursor"]});return}if(input.cursor!=null)try{decodePaginationCursor(input.cursor)}catch(error){context.addIssue({code:"custom",message:error instanceof Error?error.message:"Invalid pagination cursor.",path:["cursor"]})}}function encodePaginationCursor(offset){return btoa(JSON.stringify({v:1,offset})).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function decodePaginationCursor(cursor){try{if(!/^[A-Za-z0-9_-]+$/.test(cursor))throw new Error("Invalid pagination cursor.");let base64=cursor.replaceAll("-","+").replaceAll("_","/"),value=JSON.parse(atob(base64.padEnd(Math.ceil(base64.length/4)*4,"=")));if(!value||typeof value!="object"||value.v!==1||!Number.isSafeInteger(value.offset)||value.offset<0)throw new Error("Invalid pagination cursor.");return value.offset}catch{throw new Error("Invalid pagination cursor.")}}function paginationOffset(input){return input.cursor==null?input.offset:decodePaginationCursor(input.cursor)}function numberedPaginationRefinement(input,context){input.cursor!=null&&input.page!==void 0&&context.addIssue({code:"custom",message:"Use either cursor or page, not both.",path:["cursor"]})}function paginationPage(input){return input.cursor==null?input.page:Number(input.cursor)}function pageSchema(itemSchema){return z84.object({items:z84.array(itemSchema),nextCursor:z84.string().nullable(),total:z84.number().int().nonnegative().optional()})}function projectOffsetPage(body){let{data,meta}=rawOffsetPageSchema.parse(body);return{items:data,nextCursor:meta.hasMore?encodePaginationCursor(meta.offset+meta.limit):null,total:meta.total}}function projectDetail(schema){return body=>{let projected=schema.safeParse(body);return projected.success?projected.data:schema.parse(responseData(body))}}function requiredBranch(branch){if(!branch)throw new Error("A Branch is required when sessionId is absent.");return branch}function projectFilesPath(projectId,branch,sessionId,suffix){return sessionId?managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files${suffix}`):managementBranchPath(projectId,requiredBranch(branch),`/files${suffix}`)}var uuidSchema,sessionStatusSchema,surfaceNameSchema,branchSurfaceSchema,backendSurfaceSchema,branchNameSchema,PROJECT_FILE_WRITE_LIMIT_BYTES2,PROJECT_FILE_WRITE_MANY_MAX_FILES,PROJECT_FILE_WRITE_MANY_LIMIT_BYTES,sessionEnvelopeSchema,paginationShape,numberedPaginationShape,rawOffsetPageSchema,init_common2=__esm({"../../packages/sdk/dist/operations/common.js"(){"use strict";__name(createResponseSchema2,"createResponseSchema");uuidSchema=z84.uuid(),sessionStatusSchema=z84.enum(["provisioning","ready","closing","merged","discarded","expired","failed"]),surfaceNameSchema=z84.enum(["code","schemas","content","labels","assets","forms"]),branchSurfaceSchema=z84.enum(["code","schemas","content","labels","assets","forms"]),backendSurfaceSchema=z84.enum(["code","schemas","content","translations","assets","forms"]),branchNameSchema=z84.string().trim().min(1).max(255).regex(/^[a-zA-Z0-9._/-]+$/).refine(branch=>!branch.startsWith("-")&&!branch.startsWith(".")&&!branch.includes("//")&&!branch.includes("--")&&!branch.split("/").some(segment=>segment===".."),"Invalid Branch name.");__name(encodeBranchPathSegment2,"encodeBranchPathSegment");__name(managementProjectPath,"managementProjectPath");__name(managementBranchPath,"managementBranchPath");__name(tenantPath,"tenantPath");__name(addQuery,"addQuery");__name(withoutUndefined,"withoutUndefined");PROJECT_FILE_WRITE_LIMIT_BYTES2=256*1024,PROJECT_FILE_WRITE_MANY_MAX_FILES=100,PROJECT_FILE_WRITE_MANY_LIMIT_BYTES=1024*1024;__name(utf8Text,"utf8Text");__name(responseData,"responseData");__name(publicSurface,"publicSurface");__name(backendSurfaces,"backendSurfaces");__name(recordValue,"recordValue");sessionEnvelopeSchema=z84.object({sessionId:uuidSchema,projectId:uuidSchema,status:sessionStatusSchema,name:z84.string().nullable().optional(),goal:z84.string().nullable().optional(),provenance:z84.object({source:z84.enum(["studio","slack","mcp"]),creator:z84.object({kind:z84.enum(["user","slack","agent","oauth","conversation"]),id:z84.string()}),conversationId:z84.string().nullable(),runId:z84.string().nullable()}).nullable().optional(),createdBy:z84.string().optional(),createdAt:z84.iso.datetime().optional(),savedRevision:z84.string().nullable().optional(),targetBranch:z84.object({id:uuidSchema.nullable(),name:branchNameSchema,sha:z84.string().min(1)}),workingBranch:z84.object({id:uuidSchema,name:branchNameSchema}).nullable(),preview:z84.url().nullable(),lastActivityAt:z84.iso.datetime(),expiresAt:z84.iso.datetime().nullable(),retention:z84.enum(["temporary","durable"]).optional(),visibility:z84.enum(["internal","user-visible"]).optional(),onExpire:z84.enum(["discard","keep"]),nextOperations:z84.array(z84.string())}),paginationShape={limit:z84.number().int().min(1).max(100).optional(),cursor:z84.string().min(1).nullable().optional().describe("Opaque nextCursor from the previous page. Omit or use null for the first page."),offset:z84.number().int().min(0).optional()};__name(paginationRefinement,"paginationRefinement");__name(encodePaginationCursor,"encodePaginationCursor");__name(decodePaginationCursor,"decodePaginationCursor");__name(paginationOffset,"paginationOffset");numberedPaginationShape={page:z84.number().int().positive().optional(),cursor:paginationShape.cursor.refine(cursor=>cursor==null||/^[1-9]\d*$/.test(cursor)&&Number.isSafeInteger(Number(cursor)),"Invalid pagination cursor.")};__name(numberedPaginationRefinement,"numberedPaginationRefinement");__name(paginationPage,"paginationPage");__name(pageSchema,"pageSchema");rawOffsetPageSchema=z84.object({data:z84.array(z84.unknown()),meta:z84.object({limit:z84.number().int().positive(),offset:z84.number().int().nonnegative(),total:z84.number().int().nonnegative(),hasMore:z84.boolean()})});__name(projectOffsetPage,"projectOffsetPage");__name(projectDetail,"projectDetail");__name(requiredBranch,"requiredBranch");__name(projectFilesPath,"projectFilesPath")}});import{z as z85}from"zod";function projectAnalyticsTop(body,input){let analytics2=analyticsApiResponseSchema.parse(body).data,field={pages:"topPages",browsers:"topBrowsers",devices:"topDevices",countries:"topCountries",sources:"topSources"}[input.dimension];return analyticsTopOutputSchema.parse({branch:input.branch,dimension:input.dimension,items:input.limit===void 0?analytics2[field]:analytics2[field].slice(0,input.limit)})}function projectAnalyticsAnnotations(body,input){let analytics2=analyticsApiResponseSchema.parse(body).data;return analyticsAnnotationsOutputSchema.parse({branch:input.branch,annotations:analytics2.annotations})}function projectAnalyticsAnnotation(body){return body===void 0?null:analyticsAnnotationResponseSchema.parse(body)}var analyticsReadBranchSchema,analyticsPresetSchema,analyticsGroupBySchema,analyticsDeviceSchema,analyticsRangeShape,analyticsRangeRefinement,analyticsAnnotationSchema,analyticsBreakdownSchema,analyticsPageBreakdownSchema,analyticsPageviewsSchema,analyticsApiResponseSchema,analyticsPageviewsResponseSchema,analyticsDimensionSchema,analyticsTopOutputSchema,analyticsAnnotationsOutputSchema,analyticsAnnotationResponseSchema,analyticsOperations,init_analytics=__esm({"../../packages/sdk/dist/operations/analytics.js"(){"use strict";init_common2();analyticsReadBranchSchema=branchNameSchema.default("prod"),analyticsPresetSchema=z85.enum(["today","yesterday","this_week","this_month","last_7_days","last_30_days","last_90_days","last_week","last_month","last_quarter","last_year","custom"]),analyticsGroupBySchema=z85.enum(["day","week","month","quarter"]),analyticsDeviceSchema=z85.enum(["bot","desktop","mobile","tablet"]),analyticsRangeShape={preset:analyticsPresetSchema.optional(),device:analyticsDeviceSchema.optional(),groupBy:analyticsGroupBySchema.optional(),from:z85.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),to:z85.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),days:z85.union([z85.literal(7),z85.literal(30),z85.literal(90)]).optional()},analyticsRangeRefinement=__name((input,context)=>{input.preset==="custom"&&input.from===void 0&&context.addIssue({code:"custom",message:"from is required for custom preset",path:["from"]}),input.preset==="custom"&&input.to===void 0&&context.addIssue({code:"custom",message:"to is required for custom preset",path:["to"]})},"analyticsRangeRefinement"),analyticsAnnotationSchema=z85.object({date:z85.string(),content:z85.string(),updatedAt:z85.string(),updatedByUserId:z85.string()}),analyticsBreakdownSchema=z85.object({key:z85.string(),visitors:z85.number().int().nonnegative(),pageviews:z85.number().int().nonnegative()}),analyticsPageBreakdownSchema=z85.object({path:z85.string(),pageName:z85.string().nullable().optional(),visitors:z85.number().int().nonnegative(),pageviews:z85.number().int().nonnegative()}),analyticsPageviewsSchema=z85.object({range:z85.object({preset:analyticsPresetSchema,requestedFrom:z85.string(),requestedTo:z85.string(),effectiveFrom:z85.string(),effectiveTo:z85.string(),isRetentionLimited:z85.boolean(),groupBy:analyticsGroupBySchema}),deviceFilter:analyticsDeviceSchema.nullable().default(null),visitors:z85.number().int().nonnegative(),pageviews:z85.number().int().nonnegative(),botPageviews:z85.number().int().nonnegative().default(0),botVisitors:z85.number().int().nonnegative().default(0),bounceRate:z85.number().min(0).max(100),viewsPerVisit:z85.number().nonnegative(),averageVisitDurationSeconds:z85.number().nonnegative(),visitorsSeries:z85.array(z85.object({date:z85.string(),visitors:z85.number().int().nonnegative()})),topPages:z85.array(analyticsPageBreakdownSchema),topBrowsers:z85.array(analyticsBreakdownSchema),topDevices:z85.array(analyticsBreakdownSchema),topBots:z85.array(analyticsBreakdownSchema).default([]),topAiAssistants:z85.array(analyticsBreakdownSchema).default([]),topCountries:z85.array(analyticsBreakdownSchema),topSources:z85.array(analyticsBreakdownSchema),annotations:z85.array(analyticsAnnotationSchema)}),analyticsApiResponseSchema=createResponseSchema2(analyticsPageviewsSchema),analyticsPageviewsResponseSchema=createResponseSchema2(analyticsPageviewsSchema.extend({branch:branchNameSchema})),analyticsDimensionSchema=z85.enum(["pages","browsers","devices","countries","sources"]),analyticsTopOutputSchema=z85.object({branch:branchNameSchema,dimension:analyticsDimensionSchema,items:z85.array(z85.union([analyticsPageBreakdownSchema,analyticsBreakdownSchema]))}),analyticsAnnotationsOutputSchema=z85.object({branch:branchNameSchema,annotations:z85.array(analyticsAnnotationSchema)}),analyticsAnnotationResponseSchema=createResponseSchema2(analyticsAnnotationSchema);__name(projectAnalyticsTop,"projectAnalyticsTop");__name(projectAnalyticsAnnotations,"projectAnalyticsAnnotations");__name(projectAnalyticsAnnotation,"projectAnalyticsAnnotation");analyticsOperations={"analytics.pageviews":{domain:"analytics",summary:"Read published-site pageviews, visitors, range, breakdowns, and annotations. Branch defaults to prod; explicit branches are honored. Preview traffic is not collected; a non-prod zero is not evidence of no published traffic.",accessScope:"read",effect:"read",inputSchema:z85.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsPageviewsResponseSchema,projectOutput:__name((body,input)=>{let response=analyticsApiResponseSchema.parse(body);return{...response,data:{...response.data,branch:input.branch}}},"projectOutput"),buildRequest:__name(({projectId,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/analytics"),{preset,groupBy,from,to,days,device})}),"buildRequest")},"analytics.top":{domain:"analytics",summary:"Read a ranked published-site analytics breakdown. Branch defaults to prod; explicit branches are honored. Preview traffic is not collected.",accessScope:"read",effect:"read",inputSchema:z85.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,dimension:analyticsDimensionSchema,limit:z85.number().int().min(1).max(100).optional(),...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsTopOutputSchema,buildRequest:__name(({projectId,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/analytics"),{preset,groupBy,from,to,days,device})}),"buildRequest"),projectOutput:projectAnalyticsTop},"analytics.annotationsList":{domain:"analytics",summary:"List analytics annotations in the selected range. Branch defaults to prod; explicit branches are honored. Writes still require their own Branch scope.",accessScope:"read",effect:"read",inputSchema:z85.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsAnnotationsOutputSchema,buildRequest:__name(({projectId,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/analytics"),{preset,groupBy,from,to,days,device})}),"buildRequest"),projectOutput:projectAnalyticsAnnotations},"analytics.annotationsSet":{domain:"analytics",summary:"Set an analytics annotation for one site date.",accessScope:"write",effect:"mutation",inputSchema:z85.object({projectId:uuidSchema,branch:branchNameSchema,date:z85.string().regex(/^\d{4}-\d{2}-\d{2}$/),content:z85.string().max(500)}).strict(),outputSchema:z85.union([analyticsAnnotationResponseSchema,z85.null()]),buildRequest:__name(({projectId,branch,date,content:content2})=>({method:"PUT",path:managementBranchPath(projectId,branch,`/analytics/annotations/${encodeURIComponent(date)}`),body:{content:content2}}),"buildRequest"),projectOutput:projectAnalyticsAnnotation},"analytics.annotationsDelete":{domain:"analytics",summary:"Delete an analytics annotation for one site date.",accessScope:"write",effect:"mutation",inputSchema:z85.object({projectId:uuidSchema,branch:branchNameSchema,date:z85.string().regex(/^\d{4}-\d{2}-\d{2}$/)}).strict(),outputSchema:z85.null(),buildRequest:__name(({projectId,branch,date})=>({method:"PUT",path:managementBranchPath(projectId,branch,`/analytics/annotations/${encodeURIComponent(date)}`),body:{content:""}}),"buildRequest"),projectOutput:__name(()=>null,"projectOutput")}}}});import{z as z86}from"zod";var assetPathItemSchema,AssetDTOSchema2,AssetResponseSchema2,AssetReadRequestSchema2,assetDerivedFileSchema,assetReadBaseSchema,AssetReadResultSchema2,GenerateResponseSchema2,assetPageSchema,successMessageResponseSchema,assetGenerationInputSchema,assetUploadInputSchema,assetsOperations,init_assets=__esm({"../../packages/sdk/dist/operations/assets.js"(){"use strict";init_common2();assetPathItemSchema=z86.object({id:z86.string(),name:z86.string()}),AssetDTOSchema2=z86.object({id:z86.string(),name:z86.string(),type:z86.enum(["file","folder"]),originalFileName:z86.string().nullable(),parentId:z86.string().nullable(),mimeType:z86.string().nullable(),fileSize:z86.number().nullable(),url:z86.string().nullable(),storageKey:z86.string().nullable(),slug:z86.string(),tags:z86.array(z86.string()).nullable().optional(),createdAt:z86.string().nullable(),updatedAt:z86.string().nullable(),altText:z86.string().nullable().optional(),caption:z86.string().nullable().optional(),aiCaption:z86.string().nullable().optional(),aiAltText:z86.string().nullable().optional(),aiTags:z86.array(z86.string()).nullable().optional(),aiPrimaryColor:z86.string().nullable().optional(),aiProcessingStatus:z86.string().nullable().optional(),width:z86.number().nullable().optional(),height:z86.number().nullable().optional(),path:z86.array(assetPathItemSchema).optional(),hasChildren:z86.boolean().optional()}),AssetResponseSchema2=createResponseSchema2(AssetDTOSchema2),AssetReadRequestSchema2=z86.object({cursor:z86.string().nullable().optional(),query:z86.string().trim().min(1).max(500).optional()}).strict().refine(input=>input.cursor==null||input.query===void 0,{message:"Use either cursor or query, not both."}),assetDerivedFileSchema=z86.object({url:z86.url(),mediaType:z86.string(),filename:z86.string()}),assetReadBaseSchema=z86.object({assetId:z86.uuid(),filename:z86.string(),mediaType:z86.string(),representation:z86.enum(["text","table","document","archive","image","transcript","video","model"]),content:z86.string(),derivedFiles:z86.array(assetDerivedFileSchema).optional()}),AssetReadResultSchema2=z86.discriminatedUnion("mode",[assetReadBaseSchema.extend({mode:z86.literal("page"),start:z86.number().int().nonnegative(),end:z86.number().int().nonnegative(),total:z86.number().int().nonnegative(),nextCursor:z86.string().nullable(),complete:z86.boolean()}),assetReadBaseSchema.extend({mode:z86.literal("query"),query:z86.string(),source:z86.enum(["original-file","canonical-text","derived-files"]),truncated:z86.boolean()})]),GenerateResponseSchema2=createResponseSchema2(z86.object({jobId:z86.string(),status:z86.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema2.optional(),error:z86.string().nullable().optional(),credits:z86.number().optional(),costUsd:z86.number().optional(),billingMode:z86.enum(["fimo-credits","provider-account"]).optional(),task:z86.enum(["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"]).optional(),quality:z86.enum(["draft","standard","premium"]).optional()})),assetPageSchema=pageSchema(AssetDTOSchema2),successMessageResponseSchema=z86.object({data:z86.object({message:z86.literal("success")})}),assetGenerationInputSchema=z86.object({projectId:uuidSchema,branch:branchNameSchema,task:z86.string().min(1).optional(),model:z86.string().min(1).optional(),options:z86.record(z86.string(),z86.unknown()),name:z86.string().min(1).max(255).optional(),parentId:uuidSchema.nullable().optional(),altText:z86.string().max(2e3).optional(),caption:z86.string().max(2e3).optional()}).strict().superRefine((input,context)=>{!!input.task==!!input.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model.",path:["task"]})}),assetUploadInputSchema=z86.object({projectId:uuidSchema,sessionId:uuidSchema,url:z86.url().max(4096).refine(url=>url.startsWith("https://")||url.startsWith("http://"),"URL must use HTTP or HTTPS"),filename:z86.string().trim().min(1).max(255).refine(filename=>!filename.includes("/")&&!filename.includes("\\"),"Filename must not contain a path").optional(),name:z86.string().trim().min(1).max(255).optional(),parentId:uuidSchema.nullable().optional(),folderPath:z86.string().max(1024).refine(path49=>path49.split("/").some(segment=>segment.trim()),"Folder path must contain a folder name").refine(path49=>path49.split("/").every(segment=>![".",".."].includes(segment.trim())),"Folder path cannot contain . or .. segments").optional(),altText:z86.string().max(2e3).optional(),caption:z86.string().max(5e3).optional()}).refine(({parentId,folderPath})=>!(parentId&&folderPath),{message:"Use either parentId or folderPath, not both."}),assetsOperations={"assets.list":{domain:"assets",summary:"List media assets and folders on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z86.object({projectId:uuidSchema,branch:branchNameSchema,parentId:uuidSchema.optional(),search:z86.string().max(200).optional(),type:z86.enum(["file","folder"]).optional(),mimePrefix:z86.string().max(50).optional(),sortBy:z86.enum(["name","createdAt","updatedAt","fileSize","type"]).optional(),sortDirection:z86.enum(["asc","desc"]).optional(),includePath:z86.boolean().optional(),excludeHidden:z86.boolean().optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:assetPageSchema,buildRequest:__name(({projectId,branch,parentId,search,type,mimePrefix,sortBy,sortDirection,includePath,excludeHidden,limit,cursor,offset})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,"/assets"),{parentId,search,type,mimePrefix,sortBy,sortDirection,includePath:includePath||void 0,excludeHidden:excludeHidden||void 0,limit,offset:paginationOffset({cursor,offset})})}),"buildRequest"),projectOutput:projectOffsetPage},"assets.get":{domain:"assets",summary:"Read one media asset or folder from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z86.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:AssetResponseSchema2,buildRequest:__name(({projectId,branch,id})=>({method:"GET",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}`)}),"buildRequest")},"assets.read":{domain:"assets",summary:"Read bounded canonical content from one media asset or ask one targeted question.",accessScope:"read",effect:"read",inputSchema:z86.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,...AssetReadRequestSchema2.shape}).strict().refine(input=>input.cursor==null||input.query===void 0,{message:"Use either cursor or query, not both."}),outputSchema:createResponseSchema2(AssetReadResultSchema2),buildRequest:__name(({projectId,branch,id,cursor,query})=>({method:"POST",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}/read`),body:{cursor:cursor??void 0,query}}),"buildRequest")},"assets.generate":{domain:"assets",summary:"Generate an image or video asset and save it to the media library.",accessScope:"write",effect:"mutation",inputSchema:assetGenerationInputSchema,outputSchema:GenerateResponseSchema2,buildRequest:__name(({projectId,branch,task,model,options,name,parentId,altText,caption})=>({method:"POST",path:tenantPath(projectId,branch,"/assets/generate"),body:{...task?{task}:{model},options,name,parentId,altText,caption}}),"buildRequest")},"assets.uploadFromUrl":{domain:"assets",summary:"Import a public URL into a media library through an owned work session.",accessScope:"code",effect:"mutation",inputSchema:assetUploadInputSchema,outputSchema:sessionEnvelopeSchema.extend({asset:AssetDTOSchema2}),buildRequest:__name(({projectId,sessionId,...upload})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/assets/upload-from-url`),body:withoutUndefined(upload)}),"buildRequest")},"assets.createFolder":{domain:"assets",summary:"Create a media-library folder on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z86.object({projectId:uuidSchema,branch:branchNameSchema,name:z86.string().min(1).max(255),parentId:uuidSchema.nullable().optional()}).strict(),outputSchema:AssetResponseSchema2,buildRequest:__name(({projectId,branch,name,parentId})=>({method:"POST",path:tenantPath(projectId,branch,"/assets/folders"),body:{name,parentId}}),"buildRequest")},"assets.replaceReferences":{domain:"assets",summary:"Replace every Branch reference to one asset with another asset.",accessScope:"write",effect:"mutation",inputSchema:z86.object({projectId:uuidSchema,branch:branchNameSchema,sourceAssetId:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z86.record(z86.string(),z86.unknown()),buildRequest:__name(({projectId,branch,sourceAssetId,replacementAssetId})=>({method:"POST",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(sourceAssetId)}/replace-references`),body:{replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z86.object({data:z86.record(z86.string(),z86.unknown())}).parse(body).data,"projectOutput")},"assets.replaceAndRemove":{domain:"assets",summary:"Replace Branch references to an asset and schedule that asset for removal.",accessScope:"write",effect:"mutation",inputSchema:z86.object({projectId:uuidSchema,branch:branchNameSchema,sourceAssetId:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z86.record(z86.string(),z86.unknown()),buildRequest:__name(({projectId,branch,sourceAssetId,replacementAssetId})=>({method:"POST",path:tenantPath(projectId,branch,"/assets/removals"),body:{intent:"replace-and-remove",assetIds:[sourceAssetId],replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z86.object({data:z86.record(z86.string(),z86.unknown())}).parse(body).data,"projectOutput")},"assets.destroy":{domain:"assets",summary:"Permanently destroy an asset on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z86.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:z86.unknown(),buildRequest:__name(({projectId,branch,id})=>({method:"DELETE",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}/permanent`)}),"buildRequest"),projectOutput:__name(body=>z86.object({data:z86.unknown()}).parse(body).data,"projectOutput")},"assets.replaceAndDestroy":{domain:"assets",summary:"Replace every Branch reference to an asset, then permanently destroy it.",accessScope:"write",effect:"mutation",inputSchema:z86.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z86.record(z86.string(),z86.unknown()),buildRequest:__name(({projectId,branch,id,replacementAssetId})=>({method:"POST",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}/replace-and-destroy`),body:{replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z86.object({data:z86.record(z86.string(),z86.unknown())}).parse(body).data,"projectOutput")},"assets.move":{domain:"assets",summary:"Move a media asset or folder on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z86.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,parentId:uuidSchema.nullable()}).strict(),outputSchema:AssetResponseSchema2,buildRequest:__name(({projectId,branch,id,parentId})=>({method:"POST",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}/move`),body:{parentId}}),"buildRequest")},"assets.delete":{domain:"assets",summary:"Delete a media asset or folder from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z86.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:successMessageResponseSchema,buildRequest:__name(({projectId,branch,id})=>({method:"DELETE",path:tenantPath(projectId,branch,`/assets/${encodeURIComponent(id)}`)}),"buildRequest")}}}});import{z as z87}from"zod";var creditBalanceOutputSchema,billingOperations,init_billing=__esm({"../../packages/sdk/dist/operations/billing.js"(){"use strict";init_common2();creditBalanceOutputSchema=z87.object({projectId:uuidSchema,organizationId:z87.string(),balance:z87.object({totalAvailable:z87.number(),nearLimit:z87.boolean(),canUseAi:z87.boolean(),buckets:z87.object({dailyFreeAvailable:z87.number(),monthlyAvailable:z87.number(),purchasedAvailable:z87.number(),awardedAvailable:z87.number()})}),allowances:z87.object({dailyCredits:z87.object({periodCap:z87.number(),dailyGrant:z87.number(),usedThisPeriod:z87.number(),remainingThisPeriod:z87.number()}).nullable()})}),billingOperations={"billing.credits":{domain:"billing",summary:"Read the AI credit balance and daily allowance that apply to one project. The daily allowance is a cap, not extra balance.",accessScope:"read",effect:"read",inputSchema:z87.object({projectId:uuidSchema}).strict(),outputSchema:creditBalanceOutputSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/billing/credits")}),"buildRequest"),projectOutput:__name(body=>creditBalanceOutputSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z88}from"zod";function projectConflict(value){let conflict=backendConflictSchema.parse(value);return conflictSchema.parse({...conflict,surface:publicSurface(conflict.surface)})}function backendResolution(resolution){return{...resolution,surface:backendSurfaces([resolution.surface])?.[0]}}function projectMergeResult(body){let result=z88.object({ok:z88.boolean(),mergeId:uuidSchema,fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),fromEnv:branchNameSchema,toEnv:branchNameSchema,applied:z88.array(z88.object({surface:backendSurfaceSchema,count:z88.number().int().nonnegative()})),conflicts:z88.array(backendConflictSchema).optional(),summary:z88.string().optional()}).parse(responseData(body));return mergeResultSchema.parse({...result,fromBranch:result.fromBranch??result.fromEnv,toBranch:result.toBranch??result.toEnv,applied:result.applied.map(item=>({...item,surface:publicSurface(item.surface)})),conflicts:result.conflicts?.map(projectConflict)})}function projectMergeHydration(body){let value=z88.object({mergeId:uuidSchema,conflicts:z88.array(backendConflictSchema),draftResolutions:z88.array(conflictResolutionSchema.extend({surface:backendSurfaceSchema})),status:z88.string()}).passthrough().parse(responseData(body));return mergeHydrationSchema.parse({...value,conflicts:value.conflicts.map(projectConflict),draftResolutions:value.draftResolutions.map(resolution=>({...resolution,surface:publicSurface(resolution.surface)}))})}function projectCrossSurfaceFinding(finding){return{...finding,source:{...finding.source,surface:publicSurface(finding.source.surface)},target:{...finding.target,surface:publicSurface(finding.target.surface)}}}function projectBranchRecord(body){let record=responseData(body),{env:_env,parentEnv:_parentEnv,...branch}=record;return branchResponseSchema.parse({data:branch})}function projectBranchList(body){if(!body||typeof body!="object"||!Array.isArray(body.data))throw new Error("Expected a Branch list response.");let data=body.data.map(({env:_env,parentEnv:_parentEnv,...branch})=>branch);return z88.object({data:z88.array(branchSchema)}).parse({data})}function projectBranchStatus(body){if(branchStatusOutputSchema.safeParse(body).success)return branchStatusOutputSchema.parse(body);let report=z88.object({branch:branchNameSchema.optional(),env:branchNameSchema,vs:branchNameSchema,syncState:z88.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:isoTimestampSchema,surfaces:z88.array(backendSurfaceDeltaSchema).max(6),crossSurface:z88.array(backendCrossSurfaceFindingSchema).max(1e3).optional()}).parse(responseData(body));return branchStatusOutputSchema.parse(withoutUndefined({branch:report.branch??report.env,against:report.vs,state:report.syncState==="in-sync"?"clean":"changed",syncState:report.syncState,generatedAt:report.generatedAt,surfaces:report.surfaces.map(({surface,status,changedCount,conflictCount,items,truncated,error})=>withoutUndefined({surface:publicSurface(surface),status,changedCount,conflictCount,items,truncated,error})),crossSurface:report.crossSurface?.map(projectCrossSurfaceFinding)}))}function projectBranchDiff(body){if(branchDiffOutputSchema.safeParse(body).success)return branchDiffOutputSchema.parse(body);let report=z88.object({fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),fromEnv:branchNameSchema,toEnv:branchNameSchema,generatedAt:isoTimestampSchema,fingerprint:z88.string().min(1),surfaces:z88.array(backendSurfaceDeltaSchema).max(6),crossSurface:z88.array(backendCrossSurfaceFindingSchema).max(1e3).optional()}).parse(responseData(body));return branchDiffOutputSchema.parse({branch:report.fromBranch??report.fromEnv,against:report.toBranch??report.toEnv,generatedAt:report.generatedAt,fingerprint:report.fingerprint,surfaces:report.surfaces.map(({surface,status,changedCount,conflictCount,truncated,items,error})=>({...withoutUndefined({surface:publicSurface(surface),status,changedCount,conflictCount,error}),truncated:truncated??!1,items:(items??[]).map(({origin:_origin,...item})=>item)})),crossSurface:report.crossSurface?.map(projectCrossSurfaceFinding)})}var branchSchema,branchResponseSchema,branchSurfaceStatusSchema,branchDeltaVerbSchema,isoTimestampSchema,backendCrossSurfaceFindingSchema,crossSurfaceFindingSchema,backendSurfaceDeltaSchema,branchSurfaceSummarySchema,branchStatusOutputSchema,branchDiffItemSchema,branchDiffOutputSchema,codeFileDiffOutputSchema,contentSnapshotSchema,contentEntryDiffOutputSchema,schemaSnapshotSchema,schemaDiffOutputSchema,assetSnapshotSchema,assetDiffOutputSchema,labelDiffOutputSchema,formSnapshotSchema,formDiffOutputSchema,backendConflictSchema,conflictSchema,fieldPickSchema,conflictResolutionSchema,mergeResultSchema,mergeHydrationSchema,codeConflictBlobSchema,codeConflictDetailOutputSchema,branchesOperations,init_branches=__esm({"../../packages/sdk/dist/operations/branches.js"(){"use strict";init_common2();branchSchema=z88.object({id:uuidSchema,projectId:uuidSchema,branch:branchNameSchema,parentBranch:branchNameSchema.nullable().optional(),status:z88.enum(["provisioning","active","deleted"]),kind:z88.enum(["user","agent-session"]),createdAt:z88.string().optional(),updatedAt:z88.string().optional(),createdBy:z88.string().nullable().optional(),deletedAt:z88.string().nullable().optional()}).passthrough(),branchResponseSchema=z88.object({data:branchSchema}),branchSurfaceStatusSchema=z88.enum(["ok","timed_out","failed","unchanged"]),branchDeltaVerbSchema=z88.enum(["added","removed","changed","conflict"]),isoTimestampSchema=z88.iso.datetime(),backendCrossSurfaceFindingSchema=z88.object({id:z88.string(),kind:z88.string(),description:z88.string(),severity:z88.enum(["warning","error"]),source:z88.object({surface:backendSurfaceSchema,key:z88.string()}),target:z88.object({surface:backendSurfaceSchema,key:z88.string()}),actions:z88.array(z88.enum(["restore-target","fix-source","ignore"])).min(1)}),crossSurfaceFindingSchema=backendCrossSurfaceFindingSchema.extend({source:backendCrossSurfaceFindingSchema.shape.source.extend({surface:branchSurfaceSchema}),target:backendCrossSurfaceFindingSchema.shape.target.extend({surface:branchSurfaceSchema})}),backendSurfaceDeltaSchema=z88.object({surface:backendSurfaceSchema,status:branchSurfaceStatusSchema,changedCount:z88.number().int().nonnegative(),conflictCount:z88.number().int().nonnegative(),items:z88.array(z88.object({verb:branchDeltaVerbSchema,key:z88.string(),detail:z88.string().optional(),origin:z88.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z88.record(z88.string(),z88.unknown()).optional()})).max(1e3).optional(),truncated:z88.boolean().optional(),error:z88.string().optional()}),branchSurfaceSummarySchema=z88.object({surface:branchSurfaceSchema,status:branchSurfaceStatusSchema,changedCount:z88.number().int().nonnegative(),conflictCount:z88.number().int().nonnegative(),error:z88.string().optional(),items:z88.array(z88.object({verb:branchDeltaVerbSchema,key:z88.string(),detail:z88.string().optional(),origin:z88.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z88.record(z88.string(),z88.unknown()).optional()})).optional(),truncated:z88.boolean().optional()}),branchStatusOutputSchema=z88.object({branch:branchNameSchema,against:branchNameSchema,state:z88.enum(["clean","changed"]),syncState:z88.enum(["in-sync","ahead","behind","diverged","unknown"]).optional(),generatedAt:isoTimestampSchema,surfaces:z88.array(branchSurfaceSummarySchema).max(6),crossSurface:z88.array(crossSurfaceFindingSchema).max(1e3).optional()}),branchDiffItemSchema=z88.object({verb:branchDeltaVerbSchema,key:z88.string(),detail:z88.string().optional(),meta:z88.record(z88.string(),z88.unknown()).optional()}),branchDiffOutputSchema=branchStatusOutputSchema.omit({state:!0}).extend({fingerprint:z88.string().min(1),surfaces:z88.array(branchSurfaceSummarySchema.extend({truncated:z88.boolean(),items:z88.array(branchDiffItemSchema).max(1e3)})).max(6)}),codeFileDiffOutputSchema=z88.object({path:z88.string(),state:z88.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z88.string(),additions:z88.number().int().nonnegative(),deletions:z88.number().int().nonnegative()}),contentSnapshotSchema=z88.object({id:z88.string(),slug:z88.string(),contentType:z88.string(),data:z88.record(z88.string(),z88.unknown()),updatedAt:isoTimestampSchema}),contentEntryDiffOutputSchema=z88.object({collection:z88.string(),rowId:z88.string(),parent:contentSnapshotSchema.nullable(),child:contentSnapshotSchema.nullable()}),schemaSnapshotSchema=z88.object({name:z88.string(),label:z88.string(),isSingleton:z88.boolean(),fields:z88.record(z88.string(),z88.unknown())}),schemaDiffOutputSchema=z88.object({typeName:z88.string(),parent:schemaSnapshotSchema.nullable(),child:schemaSnapshotSchema.nullable()}),assetSnapshotSchema=z88.object({id:z88.string(),name:z88.string(),type:z88.enum(["file","folder"]),mimeType:z88.string().nullable(),storageKey:z88.string().nullable(),url:z88.string().nullable(),fileSize:z88.number().nullable(),width:z88.number().nullable(),height:z88.number().nullable(),altText:z88.string().nullable(),caption:z88.string().nullable(),createdAt:isoTimestampSchema,updatedAt:isoTimestampSchema}),assetDiffOutputSchema=z88.object({assetId:z88.string(),parent:assetSnapshotSchema.nullable(),child:assetSnapshotSchema.nullable()}),labelDiffOutputSchema=z88.object({locale:z88.string(),key:z88.string(),parent:z88.string().nullable(),child:z88.string().nullable()}),formSnapshotSchema=z88.object({formName:z88.string(),label:z88.string().nullable(),schemaFingerprint:z88.string(),fields:z88.record(z88.string(),z88.unknown())}),formDiffOutputSchema=z88.object({formName:z88.string(),parent:formSnapshotSchema.nullable(),child:formSnapshotSchema.nullable()}),backendConflictSchema=z88.object({surface:backendSurfaceSchema,key:z88.string(),kind:z88.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"]).optional(),description:z88.string(),parentValue:z88.unknown().optional(),childValue:z88.unknown().optional(),conflictingFields:z88.array(z88.string()).optional(),code:z88.object({path:z88.string(),unresolvable:z88.boolean().optional(),reason:z88.string().optional()}).optional()}),conflictSchema=backendConflictSchema.extend({surface:branchSurfaceSchema}),fieldPickSchema=z88.object({field:z88.string(),choice:z88.enum(["parent","child","pick","ai-pick"]),pickedValue:z88.unknown().optional(),aiSessionId:z88.string().optional()}),conflictResolutionSchema=z88.object({surface:branchSurfaceSchema,key:z88.string(),choice:z88.enum(["parent","child","pick"]),pickedValue:z88.unknown().optional(),fieldPicks:z88.array(fieldPickSchema).optional()}),mergeResultSchema=z88.object({ok:z88.boolean(),mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,applied:z88.array(z88.object({surface:branchSurfaceSchema,count:z88.number().int().nonnegative()})),conflicts:z88.array(conflictSchema).optional(),summary:z88.string().optional()}),mergeHydrationSchema=z88.object({mergeId:uuidSchema,conflicts:z88.array(conflictSchema),draftResolutions:z88.array(conflictResolutionSchema),status:z88.string()}).passthrough();__name(projectConflict,"projectConflict");__name(backendResolution,"backendResolution");__name(projectMergeResult,"projectMergeResult");__name(projectMergeHydration,"projectMergeHydration");codeConflictBlobSchema=z88.object({content:z88.string(),sha:z88.string().nullable().optional()}).passthrough(),codeConflictDetailOutputSchema=z88.object({path:z88.string(),base:codeConflictBlobSchema.nullable(),ours:codeConflictBlobSchema.nullable(),theirs:codeConflictBlobSchema.nullable(),result:codeConflictBlobSchema}).passthrough();__name(projectCrossSurfaceFinding,"projectCrossSurfaceFinding");__name(projectBranchRecord,"projectBranchRecord");__name(projectBranchList,"projectBranchList");__name(projectBranchStatus,"projectBranchStatus");__name(projectBranchDiff,"projectBranchDiff");branchesOperations={"branches.list":{domain:"branches",summary:"List the durable Branches of a site.",accessScope:"read",effect:"read",inputSchema:z88.object({projectId:uuidSchema,includeDeleted:z88.boolean().optional(),includeAgentBranches:z88.boolean().optional()}).strict(),outputSchema:z88.object({data:z88.array(branchSchema)}),buildRequest:__name(({projectId,includeDeleted,includeAgentBranches})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/branches"),{includeDeleted:includeDeleted?!0:void 0,includeAgentEnvs:includeAgentBranches?!0:void 0})}),"buildRequest"),projectOutput:projectBranchList},"branches.create":{domain:"branches",summary:"Create a deliberate durable Branch for lasting parallel work.",accessScope:"code",effect:"mutation",inputSchema:z88.object({projectId:uuidSchema,from:branchNameSchema.optional(),name:branchNameSchema}).strict(),outputSchema:branchResponseSchema,buildRequest:__name(({projectId,from,name})=>({method:"POST",path:managementProjectPath(projectId,"/branches"),body:from===void 0?{branch:name}:{branch:name,parentBranch:from}}),"buildRequest"),projectOutput:projectBranchRecord},"branches.get":{domain:"branches",summary:"Read one durable site Branch.",accessScope:"read",effect:"read",inputSchema:z88.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:branchSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"")}),"buildRequest"),projectOutput:__name(body=>branchResponseSchema.parse(projectBranchRecord(body)).data,"projectOutput")},"branches.sync":{domain:"branches",summary:"Sync one durable Branch from its parent or another Branch.",accessScope:"code",effect:"mutation",inputSchema:z88.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema.optional()}).strict(),outputSchema:z88.object({branch:branchSchema,conflicts:z88.number().int().nonnegative()}),buildRequest:__name(({projectId,branch,from})=>({method:"POST",path:managementBranchPath(projectId,branch,"/sync"),body:withoutUndefined({from})}),"buildRequest"),projectOutput:__name(body=>{let data=z88.object({branch:branchSchema.optional(),env:branchSchema.optional(),conflicts:z88.number().int().nonnegative()}).parse(responseData(body)),branch=data.branch??data.env;if(!branch)throw new Error("Expected a synced Branch.");return{branch,conflicts:data.conflicts}},"projectOutput")},"branches.delete":{domain:"branches",summary:"Delete one durable site Branch.",accessScope:"code",effect:"mutation",inputSchema:z88.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:z88.unknown(),buildRequest:__name(({projectId,branch})=>({method:"DELETE",path:managementBranchPath(projectId,branch,"")}),"buildRequest")},"branches.status":{domain:"branches",summary:"Summarize bounded differences between two durable Branches.",accessScope:"read",effect:"read",inputSchema:z88.object({projectId:uuidSchema,branch:branchNameSchema,against:branchNameSchema.optional(),surfaces:z88.array(branchSurfaceSchema).min(1).max(6).optional()}).strict(),outputSchema:branchStatusOutputSchema,buildRequest:__name(({projectId,branch,against,surfaces})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/status"),{against,surfaces:backendSurfaces(surfaces)?.join(",")})}),"buildRequest"),projectOutput:projectBranchStatus},"branches.diff":{domain:"branches",summary:"List a bounded index of changes between two durable Branches.",accessScope:"read",effect:"read",inputSchema:z88.object({projectId:uuidSchema,branch:branchNameSchema,against:branchNameSchema.optional(),surfaces:z88.array(branchSurfaceSchema).min(1).max(6).optional()}).strict(),outputSchema:branchDiffOutputSchema,buildRequest:__name(({projectId,branch,against,surfaces})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/diff"),{against,surfaces:backendSurfaces(surfaces)?.join(",")})}),"buildRequest"),projectOutput:projectBranchDiff},"branches.diffCodeFile":{domain:"branches",summary:"Read the unified patch for one changed code file between durable Branches.",accessScope:"read",effect:"read",inputSchema:z88.object({projectId:uuidSchema,branch:branchNameSchema,path:z88.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:codeFileDiffOutputSchema,buildRequest:__name(({projectId,branch,path:path49,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/diff/code/file"),{path:path49,against})}),"buildRequest"),projectOutput:projectDetail(codeFileDiffOutputSchema)},"branches.diffContentEntry":{domain:"branches",summary:"Read both sides of one changed content entry between durable Branches.",accessScope:"read",effect:"read",inputSchema:z88.object({projectId:uuidSchema,branch:branchNameSchema,collection:z88.string().min(1),rowId:z88.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:contentEntryDiffOutputSchema,buildRequest:__name(({projectId,branch,collection,rowId,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`),{against})}),"buildRequest"),projectOutput:projectDetail(contentEntryDiffOutputSchema)},"branches.diffSchema":{domain:"branches",summary:"Read both sides of one changed content schema between durable Branches.",accessScope:"read",effect:"read",inputSchema:z88.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z88.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:schemaDiffOutputSchema,buildRequest:__name(({projectId,branch,typeName,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/schemas/${encodeURIComponent(typeName)}`),{against})}),"buildRequest"),projectOutput:projectDetail(schemaDiffOutputSchema)},"branches.diffAsset":{domain:"branches",summary:"Read both sides of one changed media asset between durable Branches.",accessScope:"read",effect:"read",inputSchema:z88.object({projectId:uuidSchema,branch:branchNameSchema,assetId:z88.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:assetDiffOutputSchema,buildRequest:__name(({projectId,branch,assetId,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/assets/${encodeURIComponent(assetId)}`),{against})}),"buildRequest"),projectOutput:projectDetail(assetDiffOutputSchema)},"branches.diffLabel":{domain:"branches",summary:"Read both sides of one changed localized label between durable Branches.",accessScope:"read",effect:"read",inputSchema:z88.object({projectId:uuidSchema,branch:branchNameSchema,locale:z88.string().min(1),key:z88.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:labelDiffOutputSchema,buildRequest:__name(({projectId,branch,locale,key,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`),{against})}),"buildRequest"),projectOutput:projectDetail(labelDiffOutputSchema)},"branches.diffForm":{domain:"branches",summary:"Read safe form definition fields from both sides of a durable Branch diff.",accessScope:"read",effect:"read",inputSchema:z88.object({projectId:uuidSchema,branch:branchNameSchema,formName:z88.string().min(1).max(255),against:branchNameSchema.optional()}).strict(),outputSchema:formDiffOutputSchema,buildRequest:__name(({projectId,branch,formName,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/diff/forms/${encodeURIComponent(formName)}`),{against})}),"buildRequest"),projectOutput:projectDetail(formDiffOutputSchema)},"branches.merge":{domain:"branches",summary:"Merge one durable Branch into another.",accessScope:"code",effect:"mutation",inputSchema:z88.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,allowDirectMerge:z88.boolean().optional()}).strict(),outputSchema:mergeResultSchema,buildRequest:__name(({projectId,branch,from,allowDirectMerge})=>({method:"POST",path:managementBranchPath(projectId,branch,"/merge"),body:withoutUndefined({from,allowDirectMerge})}),"buildRequest"),projectOutput:projectMergeResult},"branches.resolveMerge":{domain:"branches",summary:"Resume a parked durable Branch merge with operator resolutions.",accessScope:"code",effect:"mutation",inputSchema:z88.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,mergeId:uuidSchema,resolutions:z88.array(conflictResolutionSchema)}).strict(),outputSchema:mergeResultSchema,buildRequest:__name(({projectId,branch,from,mergeId,resolutions})=>({method:"POST",path:managementBranchPath(projectId,branch,`/merge/${encodeURIComponent(from)}/resolve`),body:{mergeId,resolutions:resolutions.map(backendResolution)}}),"buildRequest"),projectOutput:projectMergeResult},"branches.cancelMerge":{domain:"branches",summary:"Cancel a parked durable Branch merge.",accessScope:"code",effect:"mutation",inputSchema:z88.object({projectId:uuidSchema,branch:branchNameSchema,mergeId:uuidSchema}).strict(),outputSchema:z88.object({ok:z88.boolean()}),buildRequest:__name(({projectId,branch,mergeId})=>({method:"POST",path:managementBranchPath(projectId,branch,"/merge/cancel"),body:{mergeId}}),"buildRequest"),projectOutput:__name(body=>z88.object({ok:z88.boolean()}).parse(responseData(body)),"projectOutput")},"branches.mergeConflicts":{domain:"branches",summary:"Read conflicts and saved resolutions for a parked durable Branch merge.",accessScope:"read",effect:"read",inputSchema:z88.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema}).strict(),outputSchema:mergeHydrationSchema,buildRequest:__name(({projectId,branch,from})=>({method:"GET",path:managementBranchPath(projectId,branch,`/merge/${encodeURIComponent(from)}/conflicts`)}),"buildRequest"),projectOutput:projectMergeHydration},"branches.saveMergeDraft":{domain:"branches",summary:"Save in-progress resolutions for a parked durable Branch merge.",accessScope:"code",effect:"mutation",inputSchema:z88.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,mergeId:uuidSchema,resolutions:z88.array(conflictResolutionSchema)}).strict(),outputSchema:z88.object({mergeId:uuidSchema,lastEditedAt:z88.string()}),buildRequest:__name(({projectId,branch,from,mergeId,resolutions})=>({method:"PUT",path:managementBranchPath(projectId,branch,`/merge/${encodeURIComponent(from)}/resolve/draft`),body:{mergeId,resolutions:resolutions.map(backendResolution)}}),"buildRequest"),projectOutput:__name(body=>z88.object({mergeId:uuidSchema,lastEditedAt:z88.string()}).parse(responseData(body)),"projectOutput")},"branches.codeConflict":{domain:"branches",summary:"Read three-way code detail for one conflicted merge path.",accessScope:"read",effect:"read",inputSchema:z88.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,path:z88.string().min(1)}).strict(),outputSchema:codeConflictDetailOutputSchema,buildRequest:__name(({projectId,branch,from,path:path49})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,`/merge/${encodeURIComponent(from)}/conflict/code`),{path:path49})}),"buildRequest"),projectOutput:projectDetail(codeConflictDetailOutputSchema)}}}});import{z as z89}from"zod";var projectDomainSchema,registeredDomainSchema,domainSearchResultSchema,domainPricingSchema,projectPath,forbidden,domainsOperations,init_domains=__esm({"../../packages/sdk/dist/operations/domains.js"(){"use strict";init_common2();projectDomainSchema=z89.object({id:z89.string(),hostname:z89.string(),status:z89.string(),ssl:z89.record(z89.string(),z89.unknown()),cnameTarget:z89.string(),apexTargets:z89.array(z89.string()),dnsAutoConfigured:z89.boolean(),createdAt:z89.unknown(),provider:z89.enum(["cloudflare","saas_custom_domains"]),domainType:z89.enum(["subdomain","apex"])}).passthrough(),registeredDomainSchema=z89.object({id:uuidSchema,domain:z89.string(),status:z89.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),source:z89.enum(["fimo","external"]),autoRenew:z89.boolean(),paymentStatus:z89.enum(["pending","paid","failed","refunded"]).nullable(),checkoutUrl:z89.string().nullable()}).passthrough(),domainSearchResultSchema=z89.object({domain:z89.string(),available:z89.boolean(),premium:z89.boolean(),price:z89.number().nullable(),renewalPrice:z89.number().nullable(),purchaseType:z89.string().nullable()}).passthrough(),domainPricingSchema=z89.object({domain:z89.string(),price:z89.number().nullable(),renewalPrice:z89.number().nullable(),premium:z89.boolean(),allowedYears:z89.array(z89.number().int().positive())}).passthrough(),projectPath=__name((projectId,suffix)=>`/management/projects/${encodeURIComponent(projectId)}${suffix}`,"projectPath"),forbidden={preserveForbidden:!0},domainsOperations={"domains.features":{domain:"domains",summary:"Read domain-purchasing feature availability and the publication domain.",accessScope:"read",effect:"read",inputSchema:z89.object({}).strict(),outputSchema:z89.object({domainPurchaseEnabled:z89.boolean(),publicationDomain:z89.string()}),buildRequest:__name(()=>({method:"GET",path:"/features"}),"buildRequest")},"domains.renameSubdomain":{domain:"domains",summary:"Change the built-in subdomain for a site.",accessScope:"write",effect:"mutation",inputSchema:z89.object({projectId:uuidSchema,slug:z89.string().min(1).max(63)}).strict(),outputSchema:z89.object({subdomain:z89.string(),subdomainUpdatedAt:z89.string()}),buildRequest:__name(({projectId,slug})=>({method:"PATCH",path:projectPath(projectId,"/subdomain"),body:{slug}}),"buildRequest"),projectOutput:responseData},"domains.suggestSubdomains":{domain:"domains",summary:"Suggest available built-in subdomains for a site.",accessScope:"read",effect:"read",inputSchema:z89.object({projectId:uuidSchema,base:z89.string().min(1).max(63).optional(),max:z89.number().int().positive().optional()}).strict(),outputSchema:z89.array(z89.string()),buildRequest:__name(({projectId,base,max})=>({method:"GET",path:addQuery(projectPath(projectId,"/subdomain/suggestions"),{base,max})}),"buildRequest"),projectOutput:__name(body=>z89.object({data:z89.object({suggestions:z89.array(z89.string())})}).parse(body).data.suggestions,"projectOutput")},"domains.list":{domain:"domains",summary:"List custom domains attached to a site.",accessScope:"read",effect:"read",inputSchema:z89.object({projectId:uuidSchema}).strict(),outputSchema:z89.array(projectDomainSchema),buildRequest:__name(({projectId})=>({method:"GET",path:projectPath(projectId,"/domains"),...forbidden}),"buildRequest"),projectOutput:responseData},"domains.add":{domain:"domains",summary:"Attach a custom domain to a site.",accessScope:"write",effect:"mutation",inputSchema:z89.object({projectId:uuidSchema,hostname:z89.string().min(1).max(255),redirectToWww:z89.boolean().optional()}).strict(),outputSchema:projectDomainSchema,buildRequest:__name(({projectId,hostname,redirectToWww})=>({method:"POST",path:projectPath(projectId,"/domains"),body:{hostname,redirectToWww},...forbidden}),"buildRequest"),projectOutput:responseData},"domains.refresh":{domain:"domains",summary:"Refresh custom-domain verification state.",accessScope:"write",effect:"mutation",inputSchema:z89.object({projectId:uuidSchema,domainId:z89.string().min(1)}).strict(),outputSchema:projectDomainSchema,buildRequest:__name(({projectId,domainId})=>({method:"POST",path:projectPath(projectId,`/domains/${encodeURIComponent(domainId)}/refresh`),...forbidden}),"buildRequest"),projectOutput:responseData},"domains.remove":{domain:"domains",summary:"Detach a custom domain from a site.",accessScope:"write",effect:"mutation",inputSchema:z89.object({projectId:uuidSchema,domainId:z89.string().min(1)}).strict(),outputSchema:z89.unknown(),buildRequest:__name(({projectId,domainId})=>({method:"DELETE",path:projectPath(projectId,`/domains/${encodeURIComponent(domainId)}`),...forbidden}),"buildRequest")},"registeredDomains.search":{domain:"domains",summary:"Search domain-registration availability.",accessScope:"read",effect:"read",inputSchema:z89.object({keyword:z89.string().min(1).max(100),tldFilter:z89.array(z89.string().min(1)).optional()}).strict(),outputSchema:z89.array(domainSearchResultSchema),buildRequest:__name(({keyword,tldFilter})=>({method:"POST",path:"/domains/search",body:{keyword,tldFilter},...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.pricing":{domain:"domains",summary:"Read registration pricing for a domain.",accessScope:"read",effect:"read",inputSchema:z89.object({domain:z89.string().min(1).max(255)}).strict(),outputSchema:domainPricingSchema,buildRequest:__name(({domain})=>({method:"GET",path:`/domains/pricing/${encodeURIComponent(domain)}`,...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.list":{domain:"domains",summary:"List domains owned by an organization.",accessScope:"read",effect:"read",inputSchema:z89.object({organizationId:z89.string().min(1)}).strict(),outputSchema:z89.array(registeredDomainSchema),buildRequest:__name(({organizationId})=>({method:"GET",path:`/domains/${encodeURIComponent(organizationId)}`,...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.purchase":{domain:"domains",summary:"Purchase and register a domain for an organization.",accessScope:"write",effect:"mutation",inputSchema:z89.object({organizationId:z89.string().min(1),domain:z89.string().min(1).max(255),years:z89.number().int().min(1).max(10).optional(),autoRenew:z89.boolean().optional()}).strict(),outputSchema:registeredDomainSchema,buildRequest:__name(({organizationId,domain,years,autoRenew})=>({method:"POST",path:`/domains/${encodeURIComponent(organizationId)}/purchase`,body:{domain,years,autoRenew},...forbidden}),"buildRequest"),projectOutput:responseData},"registeredDomains.refreshPayment":{domain:"domains",summary:"Refresh the payment state of a registered-domain purchase.",accessScope:"write",effect:"mutation",inputSchema:z89.object({organizationId:z89.string().min(1),domainId:uuidSchema}).strict(),outputSchema:registeredDomainSchema,buildRequest:__name(({organizationId,domainId})=>({method:"POST",path:`/domains/${encodeURIComponent(organizationId)}/${encodeURIComponent(domainId)}/refresh-payment`,...forbidden}),"buildRequest"),projectOutput:responseData}}}});import{z as z90}from"zod";function projectEntriesPage(body){return projectOffsetPage(PaginatedEntriesDTOSchema2.parse(body))}var EntryDTOSchema2,PaginatedEntriesDTOSchema2,EntryResponseSchema2,MAX_BULK_ENTRIES2,entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2,EntryWhereSchema2,EntryMutationBodySchema2,BulkCreateEntriesResponseSchema2,BulkUpdateEntriesResponseSchema2,BulkDeleteEntriesResponseSchema2,entriesPageSchema,typeNameSchema,localeSchema,populateSchema,entryDataSchema,entryResponseSchema,entriesOperations,init_entries=__esm({"../../packages/sdk/dist/operations/entries.js"(){"use strict";init_common2();EntryDTOSchema2=z90.object({id:z90.string(),entryId:z90.string(),documentId:z90.string(),slug:z90.string(),locale:z90.string().optional(),createdAt:z90.string(),updatedAt:z90.string(),__fimo:z90.object({contentType:z90.string()})}).passthrough(),PaginatedEntriesDTOSchema2=z90.object({data:z90.array(EntryDTOSchema2),meta:z90.object({limit:z90.number(),offset:z90.number(),total:z90.number(),hasMore:z90.boolean()})}),EntryResponseSchema2=createResponseSchema2(EntryDTOSchema2),MAX_BULK_ENTRIES2=1e3,entryWhereScalarSchema2=z90.union([z90.string(),z90.number(),z90.boolean(),z90.null()]),entryWhereOperatorSchema2=z90.object({$eq:entryWhereScalarSchema2.optional(),$ne:entryWhereScalarSchema2.optional(),$gt:entryWhereScalarSchema2.optional(),$gte:entryWhereScalarSchema2.optional(),$lt:entryWhereScalarSchema2.optional(),$lte:entryWhereScalarSchema2.optional(),$in:z90.array(entryWhereScalarSchema2).optional(),$nin:z90.array(entryWhereScalarSchema2).optional(),$contains:z90.string().optional(),$startsWith:z90.string().optional(),$null:z90.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema2=z90.record(z90.string(),z90.union([entryWhereScalarSchema2,entryWhereOperatorSchema2])),EntryWhereSchema2=z90.record(z90.string(),z90.union([entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2])),EntryMutationBodySchema2=z90.object({data:z90.record(z90.string(),z90.unknown()),locale:z90.string().min(1).optional(),documentId:z90.uuid().optional()}),BulkCreateEntriesResponseSchema2=z90.object({data:z90.array(EntryDTOSchema2),meta:z90.object({created:z90.number().int().nonnegative()})}),BulkUpdateEntriesResponseSchema2=z90.object({data:z90.array(EntryDTOSchema2),meta:z90.object({updated:z90.number().int().nonnegative(),missing:z90.array(z90.string())})}),BulkDeleteEntriesResponseSchema2=z90.object({data:z90.array(EntryDTOSchema2),meta:z90.object({deleted:z90.number().int().nonnegative(),missing:z90.array(z90.string())})});__name(projectEntriesPage,"projectEntriesPage");entriesPageSchema=pageSchema(EntryDTOSchema2),typeNameSchema=z90.string().min(1).max(255),localeSchema=z90.string().min(1),populateSchema=z90.array(z90.string().min(1)).max(50).optional(),entryDataSchema=EntryMutationBodySchema2.shape.data,entryResponseSchema=EntryResponseSchema2,entriesOperations={"entries.list":{domain:"entries",summary:"List entries for one content type on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z90.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,locale:localeSchema.optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:entriesPageSchema,buildRequest:__name(({projectId,branch,typeName,locale,limit,cursor,offset})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}`),{locale,limit,offset:paginationOffset({cursor,offset})})}),"buildRequest"),projectOutput:projectEntriesPage},"entries.get":{domain:"entries",summary:"Read one entry by ID from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z90.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional(),populate:populateSchema,localeFallbacks:z90.boolean().optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,id,locale,populate,localeFallbacks})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale,populate,localeFallbacks})}),"buildRequest")},"entries.search":{domain:"entries",summary:"Search entries across content types on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z90.object({projectId:uuidSchema,branch:branchNameSchema,search:z90.string().min(1).optional(),locale:localeSchema.optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:entriesPageSchema,buildRequest:__name(({projectId,branch,search,locale,limit,cursor,offset})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,"/entries"),{search,locale,limit,offset:paginationOffset({cursor,offset})})}),"buildRequest"),projectOutput:projectEntriesPage},"entries.create":{domain:"entries",summary:"Create one entry of a content type on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z90.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z90.string().min(1).max(255),data:entryDataSchema,locale:z90.string().min(1).optional(),documentId:z90.string().min(1).optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,data,locale,documentId})=>({method:"POST",path:tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}`),body:{data,locale,documentId}}),"buildRequest")},"entries.update":{domain:"entries",summary:"Update one entry of a content type on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z90.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z90.string().min(1).max(255),id:uuidSchema,data:entryDataSchema,locale:z90.string().min(1).optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,id,data,locale})=>({method:"PUT",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale}),body:{data}}),"buildRequest")},"entries.updateFields":{domain:"entries",summary:"Update entry fields using the direct Branch entry payload.",accessScope:"write",effect:"mutation",inputSchema:z90.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional(),fields:z90.record(z90.string(),z90.unknown())}).strict(),outputSchema:z90.unknown(),buildRequest:__name(({projectId,branch,typeName,id,locale,fields})=>({method:"PUT",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale}),body:fields}),"buildRequest"),projectOutput:__name(body=>z90.object({data:z90.unknown()}).parse(body).data,"projectOutput")},"entries.querySql":{domain:"entries",summary:"Run a read-only SQL query against Branch content.",accessScope:"read",effect:"read",inputSchema:z90.object({projectId:uuidSchema,branch:branchNameSchema,sql:z90.string().min(1)}).strict(),outputSchema:z90.object({data:z90.array(z90.record(z90.string(),z90.unknown())),meta:z90.object({rowCount:z90.number().int().nonnegative(),truncated:z90.boolean()})}),buildRequest:__name(({projectId,branch,sql})=>({method:"POST",path:tenantPath(projectId,branch,"/entries/query"),body:{sql}}),"buildRequest")},"entries.delete":{domain:"entries",summary:"Delete one entry by ID from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z90.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,id,locale})=>({method:"DELETE",path:addQuery(tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale})}),"buildRequest")},"entries.bulkCreate":{domain:"entries",summary:`Create up to ${MAX_BULK_ENTRIES2} entries of one content type on a Fimo Branch.`,accessScope:"write",effect:"mutation",inputSchema:z90.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,entries:z90.array(z90.unknown()).max(MAX_BULK_ENTRIES2)}).strict(),outputSchema:BulkCreateEntriesResponseSchema2,buildRequest:__name(({projectId,branch,typeName,entries:entries2})=>({method:"POST",path:tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/bulk-create`),body:{entries:entries2}}),"buildRequest")},"entries.bulkUpdate":{domain:"entries",summary:`Update up to ${MAX_BULK_ENTRIES2} entries by IDs, a bounded filter, or per-entry updates.`,accessScope:"write",effect:"mutation",inputSchema:z90.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,selection:z90.union([z90.object({ids:z90.array(uuidSchema).min(1).max(MAX_BULK_ENTRIES2)}),z90.object({where:EntryWhereSchema2}),z90.object({updates:z90.array(z90.object({id:uuidSchema,body:EntryMutationBodySchema2})).min(1).max(MAX_BULK_ENTRIES2)})]),body:EntryMutationBodySchema2.optional()}).strict().superRefine((input,context)=>{let perEntry="updates"in input.selection;perEntry&&input.body!==void 0&&context.addIssue({code:"custom",message:"Do not pass body with per-entry updates.",path:["body"]}),!perEntry&&input.body===void 0&&context.addIssue({code:"custom",message:"Pass body with ids or where selections.",path:["body"]})}),outputSchema:BulkUpdateEntriesResponseSchema2,buildRequest:__name(({projectId,branch,typeName,selection,body})=>({method:"POST",path:tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/bulk-update`),body:"updates"in selection?selection:{...selection,body}}),"buildRequest")},"entries.bulkDelete":{domain:"entries",summary:`Delete up to ${MAX_BULK_ENTRIES2} entries by IDs or a bounded filter.`,accessScope:"write",effect:"mutation",inputSchema:z90.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,selection:z90.union([z90.object({ids:z90.array(uuidSchema).min(1).max(MAX_BULK_ENTRIES2)}),z90.object({where:EntryWhereSchema2})]),locale:localeSchema.optional()}).strict(),outputSchema:BulkDeleteEntriesResponseSchema2,buildRequest:__name(({projectId,branch,typeName,selection,locale})=>({method:"POST",path:tenantPath(projectId,branch,`/entries/${encodeURIComponent(typeName)}/bulk-delete`),body:{...selection,locale}}),"buildRequest")}}}});import{z as z91}from"zod";var productionEnvironmentSchema,previewEnvironmentSchema,customEnvironmentSchema,environmentSchema,environmentWriteShape,environmentsOperations,init_environments=__esm({"../../packages/sdk/dist/operations/environments.js"(){"use strict";init_common2();productionEnvironmentSchema=z91.object({id:z91.literal("production"),projectId:uuidSchema,name:z91.string(),kind:z91.literal("production"),sourceBranch:z91.string().min(1),isPublished:z91.boolean(),url:z91.string().nullable()}),previewEnvironmentSchema=z91.object({id:z91.literal("preview"),projectId:uuidSchema,name:z91.string(),kind:z91.literal("preview"),matchedBranchCount:z91.number().int().nonnegative()}),customEnvironmentSchema=z91.object({id:uuidSchema,projectId:uuidSchema,name:z91.string().min(1).max(64),branchPatterns:z91.array(z91.string().min(1).max(255)).min(1),description:z91.string().max(255).nullable(),kind:z91.literal("custom"),matchedBranchCount:z91.number().int().nonnegative()}),environmentSchema=z91.discriminatedUnion("kind",[productionEnvironmentSchema,previewEnvironmentSchema,customEnvironmentSchema]),environmentWriteShape={name:z91.string().trim().min(1).max(64),branchPatterns:z91.array(z91.string().min(1).max(255)).min(1),description:z91.string().trim().max(255).nullable().optional()},environmentsOperations={"environments.list":{domain:"environments",summary:"List the compatibility Environments configured for one site.",accessScope:"read",effect:"read",inputSchema:z91.object({projectId:uuidSchema}).strict(),outputSchema:z91.array(environmentSchema),buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/environments")}),"buildRequest"),projectOutput:__name(body=>z91.array(environmentSchema).parse(responseData(body)),"projectOutput")},"environments.create":{domain:"environments",summary:"Create a custom compatibility Environment for one site.",accessScope:"write",effect:"mutation",inputSchema:z91.object({projectId:uuidSchema,...environmentWriteShape}).strict(),outputSchema:environmentSchema,buildRequest:__name(({projectId,...body})=>({method:"POST",path:managementProjectPath(projectId,"/environments"),body,preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>environmentSchema.parse(responseData(body)),"projectOutput")},"environments.update":{domain:"environments",summary:"Update one custom compatibility Environment.",accessScope:"write",effect:"mutation",inputSchema:z91.object({projectId:uuidSchema,environmentId:z91.string().min(1),...environmentWriteShape}).strict(),outputSchema:environmentSchema,buildRequest:__name(({projectId,environmentId,...body})=>({method:"PATCH",path:managementProjectPath(projectId,`/environments/${encodeURIComponent(environmentId)}`),body,preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>environmentSchema.parse(responseData(body)),"projectOutput")},"environments.delete":{domain:"environments",summary:"Delete one custom compatibility Environment.",accessScope:"write",effect:"mutation",inputSchema:z91.object({projectId:uuidSchema,environmentId:z91.string().min(1)}).strict(),outputSchema:z91.object({deletedId:uuidSchema}),buildRequest:__name(({projectId,environmentId})=>({method:"DELETE",path:managementProjectPath(projectId,`/environments/${encodeURIComponent(environmentId)}`),preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>z91.object({deletedId:uuidSchema}).parse(responseData(body)),"projectOutput")}}}});import{z as z92}from"zod";function requireBranchOrSession(input,context){!input.branch&&!input.sessionId&&context.addIssue({code:"custom",message:"Pass branch or sessionId.",path:["branch"]}),input.branch&&input.sessionId&&context.addIssue({code:"custom",message:"Pass branch or sessionId, not both.",path:["branch"]})}var fileReadOutputSchema,fileGlobOutputSchema,fileGrepOutputSchema,fileWriteInputSchema,fileEditInputSchema,fileWriteOutputSchema,fileWriteManyInputSchema,fileWriteManyOutputSchema,fileEditOutputSchema,fileDeleteOutputSchema,fileSearchInputShape,fileReadInputSchema,filesOperations,init_files=__esm({"../../packages/sdk/dist/operations/files.js"(){"use strict";init_common2();fileReadOutputSchema=z92.object({data:z92.object({path:z92.string(),content:z92.string(),totalLines:z92.number().int().nonnegative()}).passthrough()}),fileGlobOutputSchema=z92.object({data:z92.object({paths:z92.array(z92.string().min(1)).max(2e3),truncated:z92.boolean()})}),fileGrepOutputSchema=z92.object({data:z92.object({matches:z92.array(z92.object({path:z92.string().min(1),line:z92.number().int().positive(),text:z92.string()})).max(200),truncated:z92.boolean()})}),fileWriteInputSchema=z92.object({projectId:uuidSchema,sessionId:uuidSchema,path:z92.string().min(1).max(1024),content:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES2,`Content exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES2}-byte write limit.`),overwrite:z92.boolean().optional()}).strict(),fileEditInputSchema=z92.object({projectId:uuidSchema,sessionId:uuidSchema,path:z92.string().min(1).max(1024),oldString:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES2,`Text exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES2}-byte edit limit.`).min(1),newString:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES2,`Text exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES2}-byte edit limit.`),replaceAll:z92.boolean().optional()}).strict(),fileWriteOutputSchema=sessionEnvelopeSchema.extend({file:z92.object({path:z92.string(),created:z92.boolean(),tip:z92.string().min(1)}).passthrough()}),fileWriteManyInputSchema=z92.object({projectId:uuidSchema,sessionId:uuidSchema,files:z92.array(z92.object({path:z92.string().min(1).max(1024),content:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES2,`Content exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES2}-byte write limit.`)}).strict()).min(1).max(PROJECT_FILE_WRITE_MANY_MAX_FILES).refine(files=>files.reduce((total,file)=>total+new TextEncoder().encode(file.content).byteLength,0)<=PROJECT_FILE_WRITE_MANY_LIMIT_BYTES,`Files exceed the ${PROJECT_FILE_WRITE_MANY_LIMIT_BYTES}-byte total write limit.`)}).strict(),fileWriteManyOutputSchema=sessionEnvelopeSchema.extend({files:z92.array(z92.object({path:z92.string(),created:z92.boolean()}).passthrough()),tip:z92.string().min(1)}),fileEditOutputSchema=sessionEnvelopeSchema.extend({file:z92.object({path:z92.string(),replacements:z92.number().int().nonnegative(),tip:z92.string().min(1)}).passthrough()}),fileDeleteOutputSchema=sessionEnvelopeSchema.extend({file:z92.object({path:z92.string(),deleted:z92.literal(!0),tip:z92.string().min(1)})}),fileSearchInputShape={projectId:uuidSchema,branch:branchNameSchema.optional(),sessionId:uuidSchema.optional()};__name(requireBranchOrSession,"requireBranchOrSession");fileReadInputSchema=z92.object({projectId:uuidSchema,branch:branchNameSchema.optional(),sessionId:uuidSchema.optional(),path:z92.string().min(1).max(1024)}).superRefine(requireBranchOrSession),filesOperations={"files.read":{domain:"files",summary:"Read one safe text file from a Branch or owned work session.",accessScope:"read",effect:"read",inputSchema:fileReadInputSchema,outputSchema:fileReadOutputSchema,buildRequest:__name(({projectId,branch,sessionId,path:path49})=>({method:"GET",path:addQuery(projectFilesPath(projectId,branch,sessionId,"/file"),{path:path49})}),"buildRequest")},"files.glob":{domain:"files",summary:"List bounded safe site file paths from a Branch or owned work session.",accessScope:"read",effect:"read",inputSchema:z92.object({...fileSearchInputShape,pattern:z92.string().min(1).max(300).optional(),limit:z92.number().int().min(1).max(2e3).optional()}).strict().superRefine(requireBranchOrSession),outputSchema:fileGlobOutputSchema,buildRequest:__name(({projectId,branch,sessionId,pattern,limit})=>({method:"GET",path:addQuery(projectFilesPath(projectId,branch,sessionId,"/paths"),{pattern,limit})}),"buildRequest")},"files.grep":{domain:"files",summary:"Search bounded safe site file contents on a Branch or owned work session.",accessScope:"read",effect:"read",inputSchema:z92.object({...fileSearchInputShape,pattern:z92.string().min(1).max(200),include:z92.string().min(1).max(300).optional(),caseInsensitive:z92.boolean().optional(),maxMatches:z92.number().int().min(1).max(200).optional()}).strict().superRefine(requireBranchOrSession),outputSchema:fileGrepOutputSchema,buildRequest:__name(({projectId,branch,sessionId,pattern,include,caseInsensitive,maxMatches})=>({method:"GET",path:addQuery(projectFilesPath(projectId,branch,sessionId,"/grep"),{pattern,include,caseInsensitive,maxMatches})}),"buildRequest")},"files.write":{domain:"files",summary:"Create or overwrite one safe text file in an owned work session.",accessScope:"code",effect:"mutation",inputSchema:fileWriteInputSchema,outputSchema:fileWriteOutputSchema,buildRequest:__name(({projectId,sessionId,path:path49,content:content2,overwrite})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/write`),body:withoutUndefined({path:path49,content:content2,overwrite})}),"buildRequest")},"files.writeMany":{domain:"files",summary:"Create or overwrite several safe text files in an owned work session as one saved change.",accessScope:"code",effect:"mutation",inputSchema:fileWriteManyInputSchema,outputSchema:fileWriteManyOutputSchema,buildRequest:__name(({projectId,sessionId,files})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/write-many`),body:{files}}),"buildRequest")},"files.edit":{domain:"files",summary:"Replace exact text in one safe file in an owned work session.",accessScope:"code",effect:"mutation",inputSchema:fileEditInputSchema,outputSchema:fileEditOutputSchema,buildRequest:__name(({projectId,sessionId,path:path49,oldString,newString,replaceAll})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/edit`),body:withoutUndefined({path:path49,oldString,newString,replaceAll})}),"buildRequest")},"files.delete":{domain:"files",summary:"Delete one safe site file in an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z92.object({projectId:uuidSchema,sessionId:uuidSchema,path:z92.string().min(1).max(1024)}).strict(),outputSchema:fileDeleteOutputSchema,buildRequest:__name(({projectId,sessionId,path:path49})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/files/delete`),body:{path:path49}}),"buildRequest")}}}});import{z as z93}from"zod";function projectFormResponse(body){return formResponseSchema.parse(body)}function projectFormDetail(body){return formResponseSchema.parse(body).data}function projectFormList(body){return z93.object({data:z93.array(formSchema)}).parse(body).data}function projectFormSubmissionsPage(body,input){let page=z93.object({data:z93.array(formSubmissionSchema),total:z93.number().int().nonnegative()}).parse(body),offset=paginationOffset(input)??0;if(page.data.length===0&&offset<page.total)throw new Error("Expected a page that advances the cursor.");return{items:page.data,nextCursor:offset+page.data.length<page.total?encodePaginationCursor(offset+page.data.length):null,total:page.total}}var formFieldSchema,FormContentSchema2,FormUpdateSchema2,rawFormSchema,formSchema,formResponseSchema,formSubmissionSchema,formSubmissionResponseSchema,formSubmissionsPageSchema,formSubmissionStatsResponseSchema,formsOperations,init_forms=__esm({"../../packages/sdk/dist/operations/forms.js"(){"use strict";init_common2();formFieldSchema=z93.object({type:z93.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),label:z93.string(),placeholder:z93.string().optional(),required:z93.boolean().optional(),defaultValue:z93.string().optional(),options:z93.array(z93.string()).optional(),validation:z93.object({minLength:z93.number().optional(),maxLength:z93.number().optional(),min:z93.number().optional(),max:z93.number().optional(),pattern:z93.string().optional(),maxFileSize:z93.number().optional(),accept:z93.array(z93.string()).optional()}).optional()}),FormContentSchema2=z93.object({name:z93.string().min(1).max(255),label:z93.string().min(1).max(255),fields:z93.record(z93.string(),formFieldSchema)}).strict(),FormUpdateSchema2=FormContentSchema2.partial().refine(update=>update.name!==void 0||update.label!==void 0||update.fields!==void 0,{message:"Pass at least one of name, label, or fields."}),rawFormSchema=z93.object({id:uuidSchema,name:FormContentSchema2.shape.name,label:FormContentSchema2.shape.label,fields:FormContentSchema2.shape.fields,settings:z93.record(z93.string(),z93.unknown()).nullable().optional(),createdAt:z93.string(),updatedAt:z93.string()}).passthrough(),formSchema=rawFormSchema,formResponseSchema=z93.object({data:formSchema}),formSubmissionSchema=z93.object({id:uuidSchema,formId:uuidSchema,projectId:uuidSchema,branch:branchNameSchema,data:z93.record(z93.string(),z93.unknown()),submittedAt:z93.string()}),formSubmissionResponseSchema=z93.object({data:formSubmissionSchema}),formSubmissionsPageSchema=pageSchema(formSubmissionSchema),formSubmissionStatsResponseSchema=z93.object({data:z93.object({total:z93.number().int().nonnegative(),dailyCounts:z93.array(z93.object({date:z93.string(),count:z93.number().int().nonnegative()}))})});__name(projectFormResponse,"projectFormResponse");__name(projectFormDetail,"projectFormDetail");__name(projectFormList,"projectFormList");__name(projectFormSubmissionsPage,"projectFormSubmissionsPage");formsOperations={"forms.list":{domain:"forms",summary:"List form definitions on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z93.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:z93.array(formSchema),buildRequest:__name(({projectId,branch})=>({method:"GET",path:tenantPath(projectId,branch,"/forms")}),"buildRequest"),projectOutput:projectFormList},"forms.get":{domain:"forms",summary:"Read one form definition from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z93.object({projectId:uuidSchema,branch:branchNameSchema,id:z93.string().min(1).max(255)}).strict(),outputSchema:formSchema,buildRequest:__name(({projectId,branch,id})=>({method:"GET",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}`)}),"buildRequest"),projectOutput:projectFormDetail},"forms.create":{domain:"forms",summary:"Create a form definition on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z93.object({projectId:uuidSchema,branch:branchNameSchema,...FormContentSchema2.shape}).strict(),outputSchema:formResponseSchema,buildRequest:__name(({projectId,branch,name,label,fields})=>({method:"POST",path:tenantPath(projectId,branch,"/forms"),body:{name,label,fields}}),"buildRequest"),projectOutput:projectFormResponse},"forms.update":{domain:"forms",summary:"Update the name, label, or fields of one form definition.",accessScope:"write",effect:"mutation",inputSchema:z93.object({projectId:uuidSchema,branch:branchNameSchema,id:z93.string().min(1).max(255),...FormContentSchema2.partial().shape}).strict().superRefine((input,context)=>{let update=FormUpdateSchema2.safeParse({name:input.name,label:input.label,fields:input.fields});if(!update.success)for(let issue of update.error.issues)context.addIssue({...issue,path:issue.path})}),outputSchema:formResponseSchema,buildRequest:__name(({projectId,branch,id,name,label,fields})=>({method:"PUT",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}`),body:{name,label,fields}}),"buildRequest"),projectOutput:projectFormResponse},"forms.delete":{domain:"forms",summary:"Delete one form definition from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z93.object({projectId:uuidSchema,branch:branchNameSchema,id:z93.string().min(1).max(255)}).strict(),outputSchema:formResponseSchema,buildRequest:__name(({projectId,branch,id})=>({method:"DELETE",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}`)}),"buildRequest"),projectOutput:projectFormResponse},"forms.listSubmissions":{domain:"forms",summary:"List submissions for one form with cursor pagination.",accessScope:"read",effect:"read",inputSchema:z93.object({projectId:uuidSchema,branch:branchNameSchema,id:z93.string().min(1).max(255),...paginationShape,searchQuery:z93.string().max(200).optional(),sortDirection:z93.enum(["asc","desc"]).optional()}).strict().superRefine(paginationRefinement),outputSchema:formSubmissionsPageSchema,buildRequest:__name(({projectId,branch,id,limit,cursor,offset,searchQuery,sortDirection})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}/submissions`),{limit,offset:paginationOffset({cursor,offset}),searchQuery,sortDirection})}),"buildRequest"),projectOutput:projectFormSubmissionsPage},"forms.getSubmission":{domain:"forms",summary:"Read one submission for a form.",accessScope:"read",effect:"read",inputSchema:z93.object({projectId:uuidSchema,branch:branchNameSchema,id:z93.string().min(1).max(255),submissionId:z93.string().min(1).max(255)}).strict(),outputSchema:formSubmissionSchema,buildRequest:__name(({projectId,branch,id,submissionId})=>({method:"GET",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}/submissions/${encodeURIComponent(submissionId)}`)}),"buildRequest"),projectOutput:__name(body=>formSubmissionResponseSchema.parse(body).data,"projectOutput")},"forms.submissionStats":{domain:"forms",summary:"Read aggregate submission statistics for one form.",accessScope:"read",effect:"read",inputSchema:z93.object({projectId:uuidSchema,branch:branchNameSchema,id:z93.string().min(1).max(255)}).strict(),outputSchema:formSubmissionStatsResponseSchema.shape.data,buildRequest:__name(({projectId,branch,id})=>({method:"GET",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}/submissions/stats`)}),"buildRequest"),projectOutput:__name(body=>formSubmissionStatsResponseSchema.parse(body).data,"projectOutput")},"forms.deleteSubmission":{domain:"forms",summary:"Permanently delete one submission for a form. This cannot be undone.",accessScope:"write",effect:"mutation",inputSchema:z93.object({projectId:uuidSchema,branch:branchNameSchema,id:z93.string().min(1).max(255),submissionId:z93.string().min(1).max(255)}).strict(),outputSchema:formSubmissionSchema,buildRequest:__name(({projectId,branch,id,submissionId})=>({method:"DELETE",path:tenantPath(projectId,branch,`/forms/${encodeURIComponent(id)}/submissions/${encodeURIComponent(submissionId)}`)}),"buildRequest"),projectOutput:__name(body=>formSubmissionResponseSchema.parse(body).data,"projectOutput")}}}});import{z as z94}from"zod";var estimateSchema,generationOperations,init_generation=__esm({"../../packages/sdk/dist/operations/generation.js"(){"use strict";init_common2();estimateSchema=z94.object({costUsd:z94.number(),credits:z94.number().optional(),billingMode:z94.enum(["fimo-credits","provider-account"]).optional(),confidence:z94.enum(["exact","estimated","metered"]),basis:z94.string()}).passthrough(),generationOperations={"generation.estimateModel":{domain:"generation",summary:"Estimate one generation request against an enabled provider model.",accessScope:"read",effect:"read",inputSchema:z94.object({projectId:uuidSchema,model:z94.string().min(1),options:z94.record(z94.string(),z94.unknown())}).strict(),outputSchema:estimateSchema,buildRequest:__name(({projectId,model,options})=>({method:"POST",path:`/management/projects/${encodeURIComponent(projectId)}/integrations/fal/models/estimate`,body:{model,options}}),"buildRequest"),projectOutput:responseData},"generation.estimateTask":{domain:"generation",summary:"Estimate one built-in media generation task on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z94.object({projectId:uuidSchema,branch:branchNameSchema,task:z94.string().min(1),options:z94.record(z94.string(),z94.unknown())}).strict(),outputSchema:estimateSchema,buildRequest:__name(({projectId,branch,task,options})=>({method:"POST",path:tenantPath(projectId,branch,"/assets/generate/estimate"),body:{task,options}}),"buildRequest"),projectOutput:responseData}}}});import{z as z95}from"zod";var historyKindSchema,projectVersionSchema,projectVersionPageSchema,historySummarySchema,restoreResultSchema,historyOperations,init_history=__esm({"../../packages/sdk/dist/operations/history.js"(){"use strict";init_common2();historyKindSchema=z95.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),projectVersionSchema=z95.object({versionId:uuidSchema,commitHash:z95.string(),name:z95.string(),description:z95.string().nullable(),kind:historyKindSchema,createdAt:z95.iso.datetime(),expiresAt:z95.iso.datetime()}),projectVersionPageSchema=z95.object({items:z95.array(projectVersionSchema),nextCursor:z95.string().nullable()}),historySummarySchema=z95.object({usage:z95.object({versionCount:z95.number().int().nonnegative(),snapshotBytes:z95.number().int().nonnegative()}),retentionDays:z95.number().int().positive()}),restoreResultSchema=z95.object({durationMs:z95.number().nonnegative().optional(),warning:z95.string().optional()}),historyOperations={"history.list":{domain:"history",summary:"List restore points for one Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z95.object({projectId:uuidSchema,branch:branchNameSchema,limit:z95.number().int().min(1).max(100),cursor:paginationShape.cursor}).strict(),outputSchema:projectVersionPageSchema,buildRequest:__name(({projectId,branch,limit,cursor})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/versions"),{limit,cursor})}),"buildRequest"),projectOutput:__name(body=>projectVersionPageSchema.parse(responseData(body)),"projectOutput")},"history.summary":{domain:"history",summary:"Read restore-point usage and retention for one Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z95.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:historySummarySchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"/versions/summary")}),"buildRequest"),projectOutput:__name(body=>historySummarySchema.parse(responseData(body)),"projectOutput")},"history.get":{domain:"history",summary:"Read one restore point from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z95.object({projectId:uuidSchema,branch:branchNameSchema,versionId:uuidSchema}).strict(),outputSchema:projectVersionSchema,buildRequest:__name(({projectId,branch,versionId})=>({method:"GET",path:managementBranchPath(projectId,branch,`/versions/${encodeURIComponent(versionId)}`)}),"buildRequest"),projectOutput:__name(body=>projectVersionSchema.parse(responseData(body)),"projectOutput")},"history.create":{domain:"history",summary:"Create a restore point for one Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z95.object({projectId:uuidSchema,branch:branchNameSchema,name:z95.string().min(1),description:z95.string().optional()}).strict(),outputSchema:projectVersionSchema,buildRequest:__name(({projectId,branch,name,description})=>({method:"POST",path:managementBranchPath(projectId,branch,"/versions"),body:withoutUndefined({name,description})}),"buildRequest"),projectOutput:__name(body=>projectVersionSchema.parse(responseData(body)),"projectOutput")},"history.restore":{domain:"history",summary:"Restore code and content from one Fimo Branch restore point.",accessScope:"write",effect:"mutation",inputSchema:z95.object({projectId:uuidSchema,branch:branchNameSchema,versionId:uuidSchema}).strict(),outputSchema:restoreResultSchema,buildRequest:__name(({projectId,branch,versionId})=>({method:"POST",path:managementBranchPath(projectId,branch,`/versions/${encodeURIComponent(versionId)}/restore`)}),"buildRequest"),projectOutput:__name(body=>restoreResultSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z96}from"zod";function publicationRecord(value){let publication=recordValue(value,"Expected a publication record."),source=recordValue(publication.source,"Expected a publication source."),{env,targetEnv,...publicSource}=source;return{...publication,source:{...publicSource,branch:publicSource.branch??env,targetBranch:publicSource.targetBranch??targetEnv}}}function projectPublication(body){return publicationOutputSchema.parse(publicationRecord(responseData(body)))}function projectPublicationsPage(body){let page=recordValue(responseData(body),"Expected a publication history page.");if(!Array.isArray(page.items))throw new Error("Expected publication history items.");return publicationsPageOutputSchema.parse({items:page.items.map(publicationRecord),nextCursor:page.nextCursor,retention:page.retention})}function projectPublicationLogs(body){let result=recordValue(responseData(body),"Expected publication logs.");return publicationLogsOutputSchema.parse({status:result.status,publicationId:result.publicationId,reason:result.reason??null,message:result.message??null,items:result.events??[]})}function projectSandboxLogs(body){let result=recordValue(responseData(body),"Expected sandbox logs.");return sandboxLogsOutputSchema.parse({status:result.status,reason:result.reason??null,message:result.message??null,items:result.events??[],nextCursor:result.previousCursor??null,retention:result.retention??null})}var LOG_TAIL_MAX_LIMIT,logTailLimitSchema,publicationStateOutputSchema,publicationOutputSchema,publicationsPageOutputSchema,publicationLogsOutputSchema,sandboxLogsOutputSchema,previewLocationOutputSchema,previewOpenOutputSchema,publishOutputSchema,hostingOperations,init_hosting=__esm({"../../packages/sdk/dist/operations/hosting.js"(){"use strict";init_common2();LOG_TAIL_MAX_LIMIT=1e3,logTailLimitSchema=z96.number().int().min(1).max(LOG_TAIL_MAX_LIMIT).optional(),publicationStateOutputSchema=z96.object({isPublished:z96.boolean(),publishedAt:z96.iso.datetime().nullable(),publishedVersion:z96.string().nullable()}),publicationOutputSchema=z96.object({id:uuidSchema,status:z96.enum(["queued","building","published","failed","canceled"]),label:z96.string().nullable(),notes:z96.string().nullable(),source:z96.object({branch:branchNameSchema,targetBranch:branchNameSchema,configVersion:z96.string().nullable(),framework:z96.string().nullable(),commit:z96.string().nullable()}),createdAt:z96.iso.datetime(),finishedAt:z96.iso.datetime().nullable(),url:z96.string().nullable(),failureCode:z96.string().nullable()}),publicationsPageOutputSchema=z96.object({items:z96.array(publicationOutputSchema),nextCursor:z96.string().nullable(),retention:z96.object({scope:z96.literal("publication_attempt_record"),records:z96.literal("project_lifetime")})}),publicationLogsOutputSchema=z96.object({status:z96.enum(["ok","unavailable"]),publicationId:uuidSchema,reason:z96.enum(["pending","no_deployment","provider_unavailable"]).nullable(),message:z96.string().nullable(),items:z96.array(z96.object({timestamp:z96.iso.datetime(),phase:z96.enum(["build","deploy"]),stream:z96.enum(["command","stdout","stderr","status","error"]),message:z96.string()}))}),sandboxLogsOutputSchema=z96.object({status:z96.enum(["ok","unavailable"]),reason:z96.enum(["no_sandbox","sandbox_expired","provider_unsupported"]).nullable(),message:z96.string().nullable(),items:z96.array(z96.object({id:z96.string(),timestamp:z96.iso.datetime().nullable(),source:z96.enum(["install","dev-server"]),phase:z96.string(),stream:z96.enum(["combined","stdout","stderr"]),message:z96.string()})),nextCursor:z96.string().nullable(),retention:z96.object({scope:z96.literal("sandbox_process_snapshot"),timestamps:z96.literal("process_start"),droppedOldest:z96.boolean(),phases:z96.array(z96.object({phase:z96.string(),source:z96.enum(["install","dev-server"]),status:z96.string(),startedAt:z96.iso.datetime().nullable(),exitCode:z96.number().int().nullable(),events:z96.number().int().nonnegative()}))}).nullable()}),previewLocationOutputSchema=z96.object({url:z96.string(),branch:branchNameSchema}),previewOpenOutputSchema=z96.object({url:z96.url(),expiresAt:z96.iso.datetime().nullable()}),publishOutputSchema=z96.object({success:z96.boolean(),message:z96.string().optional(),firstPublish:z96.boolean(),publicationId:z96.string().optional(),url:z96.string().nullable().optional()});__name(publicationRecord,"publicationRecord");__name(projectPublication,"projectPublication");__name(projectPublicationsPage,"projectPublicationsPage");__name(projectPublicationLogs,"projectPublicationLogs");__name(projectSandboxLogs,"projectSandboxLogs");hostingOperations={"publications.state":{domain:"publications",summary:"Read whether a site has a live published site.",accessScope:"read",effect:"read",inputSchema:z96.object({projectId:uuidSchema}).strict(),outputSchema:publicationStateOutputSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/publication-state")}),"buildRequest"),projectOutput:__name(body=>publicationStateOutputSchema.parse(responseData(body)),"projectOutput")},"publications.list":{domain:"publications",summary:"List durable publication attempts, newest first.",accessScope:"read",effect:"read",inputSchema:z96.object({projectId:uuidSchema,limit:z96.number().int().min(1).max(100).optional(),cursor:paginationShape.cursor}).strict(),outputSchema:publicationsPageOutputSchema,buildRequest:__name(({projectId,limit,cursor})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/publications"),{limit,before:cursor})}),"buildRequest"),projectOutput:projectPublicationsPage},"publications.get":{domain:"publications",summary:"Read one durable publication attempt.",accessScope:"read",effect:"read",inputSchema:z96.object({projectId:uuidSchema,publicationId:z96.string().min(1)}).strict(),outputSchema:publicationOutputSchema,buildRequest:__name(({projectId,publicationId})=>({method:"GET",path:managementProjectPath(projectId,`/publications/${encodeURIComponent(publicationId)}`)}),"buildRequest"),projectOutput:projectPublication},"publications.publish":{domain:"publications",summary:"Publish the production source Branch and wait until the site is live; returns the live URL. Building can take a few minutes; if the call fails or times out, list the publications until the newest attempt is published or failed.",accessScope:"write",effect:"mutation",inputSchema:z96.object({projectId:uuidSchema,label:z96.string().trim().min(1).max(120).optional(),notes:z96.string().max(2e4).optional()}).strict(),outputSchema:publishOutputSchema,buildRequest:__name(({projectId,label,notes})=>({method:"POST",path:managementProjectPath(projectId,"/publish"),body:withoutUndefined({label,notes})}),"buildRequest"),projectOutput:__name(body=>publishOutputSchema.parse(responseData(body)),"projectOutput")},"publications.logs":{domain:"publications",summary:"Read a bounded sanitized build-log tail for one publication.",accessScope:"read",effect:"read",inputSchema:z96.object({projectId:uuidSchema,publicationId:z96.string().min(1),limit:logTailLimitSchema}).strict(),outputSchema:publicationLogsOutputSchema,buildRequest:__name(({projectId,publicationId,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId,`/publications/${encodeURIComponent(publicationId)}/logs`),{limit})}),"buildRequest"),projectOutput:projectPublicationLogs},"sandbox.logs":{domain:"sandbox",summary:"Read existing install and dev-server logs without creating or extending a sandbox.",accessScope:"read",effect:"read",inputSchema:z96.object({projectId:uuidSchema,branch:branchNameSchema,limit:logTailLimitSchema,cursor:paginationShape.cursor}).strict(),outputSchema:sandboxLogsOutputSchema,buildRequest:__name(({projectId,branch,limit,cursor})=>({method:"GET",path:addQuery(managementBranchPath(projectId,branch,"/sandbox/logs"),{limit,before:cursor})}),"buildRequest"),projectOutput:projectSandboxLogs},"preview.location":{domain:"preview",summary:"Return the Studio Preview location for one Branch without provisioning it.",accessScope:"read",effect:"read",inputSchema:z96.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:previewLocationOutputSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"/preview-location")}),"buildRequest"),projectOutput:__name(body=>previewLocationOutputSchema.parse(responseData(body)),"projectOutput")},"preview.open":{domain:"preview",summary:"Start or reuse one Branch's preview sandbox and return its signed live URL. Pass a work session's workingBranch name to preview unmerged changes; the URL expires at expiresAt.",accessScope:"read",effect:"mutation",inputSchema:z96.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:previewOpenOutputSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"/sandbox")}),"buildRequest"),projectOutput:__name(body=>previewOpenOutputSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z97}from"zod";var knowledgeSchema,knowledgeOperations,init_knowledge=__esm({"../../packages/sdk/dist/operations/knowledge.js"(){"use strict";init_common2();knowledgeSchema=z97.object({content:z97.string(),updatedAt:z97.string().nullable(),updatedBy:z97.string().nullable()}),knowledgeOperations={"knowledge.get":{domain:"knowledge",summary:"Read shared site goals, brand guidance and rules before planning, recommendations, design, copy or coding.",accessScope:"read",effect:"read",inputSchema:z97.object({projectId:uuidSchema}).strict(),outputSchema:knowledgeSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/knowledge")}),"buildRequest"),projectOutput:__name(body=>knowledgeSchema.parse(responseData(body)),"projectOutput")},"knowledge.update":{domain:"knowledge",summary:"Replace shared site knowledge only when explicitly asked and authorized. Read first to preserve unrelated guidance.",accessScope:"write",effect:"mutation",inputSchema:z97.object({projectId:uuidSchema,content:z97.string()}).strict(),outputSchema:knowledgeSchema,buildRequest:__name(({projectId,content:content2})=>({method:"PUT",path:managementProjectPath(projectId,"/knowledge"),body:{content:content2}}),"buildRequest"),projectOutput:__name(body=>knowledgeSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z98}from"zod";function responseValue(schema,body){return schema.parse(responseData(body))}var TranslationDTOSchema2,labelResponseSchema,labelListOutputSchema,labelUpsertOutputSchema,labelDeleteOutputSchema,labelsOperations,init_labels=__esm({"../../packages/sdk/dist/operations/labels.js"(){"use strict";init_common2();init_entries();TranslationDTOSchema2=z98.object({key:z98.string(),value:z98.string().optional(),defaultValue:z98.string(),locale:z98.string()}),labelResponseSchema=createResponseSchema2(TranslationDTOSchema2),labelListOutputSchema=z98.object({data:z98.array(z98.union([TranslationDTOSchema2,z98.object({key:z98.string(),values:z98.record(z98.string(),z98.string())})]))}),labelUpsertOutputSchema=z98.object({created:z98.number().int().nonnegative(),updated:z98.number().int().nonnegative(),deleted:z98.number().int().nonnegative(),defaultLocale:z98.string(),locales:z98.array(z98.string())}),labelDeleteOutputSchema=z98.object({key:z98.string(),locale:z98.string()});__name(responseValue,"responseValue");labelsOperations={"labels.list":{domain:"labels",summary:"List localized labels on a Fimo Branch, optionally grouped across locales.",accessScope:"read",effect:"read",inputSchema:z98.object({projectId:uuidSchema,branch:branchNameSchema,locale:localeSchema.optional()}).strict(),outputSchema:labelListOutputSchema,buildRequest:__name(({projectId,branch,locale})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,"/labels"),{locale})}),"buildRequest")},"labels.get":{domain:"labels",summary:"Read one localized label by locale and key.",accessScope:"read",effect:"read",inputSchema:z98.object({projectId:uuidSchema,branch:branchNameSchema,locale:localeSchema,key:z98.string().min(1).max(255)}).strict(),outputSchema:labelResponseSchema,buildRequest:__name(({projectId,branch,locale,key})=>({method:"GET",path:tenantPath(projectId,branch,`/labels/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`)}),"buildRequest")},"labels.set":{domain:"labels",summary:"Create or set one localized label.",accessScope:"write",effect:"mutation",inputSchema:z98.object({projectId:uuidSchema,branch:branchNameSchema,key:z98.string(),value:z98.string(),locale:z98.string().optional()}).strict(),outputSchema:TranslationDTOSchema2,buildRequest:__name(({projectId,branch,key,value,locale})=>({method:"POST",path:tenantPath(projectId,branch,"/labels"),body:{key,value,locale}}),"buildRequest"),projectOutput:__name(body=>responseValue(TranslationDTOSchema2,body),"projectOutput")},"labels.setMany":{domain:"labels",summary:"Create or overwrite localized labels in one request.",accessScope:"write",effect:"mutation",inputSchema:z98.object({projectId:uuidSchema,branch:branchNameSchema,records:z98.array(z98.object({key:z98.string(),value:z98.string(),locale:z98.string().optional()}))}).strict(),outputSchema:labelUpsertOutputSchema,buildRequest:__name(({projectId,branch,records})=>({method:"POST",path:tenantPath(projectId,branch,"/labels/sync"),body:{created:records,updated:[],deleted:[]}}),"buildRequest"),projectOutput:__name(body=>responseValue(labelUpsertOutputSchema,body),"projectOutput")},"labels.delete":{domain:"labels",summary:"Delete one localized label.",accessScope:"write",effect:"mutation",inputSchema:z98.object({projectId:uuidSchema,branch:branchNameSchema,locale:z98.string().optional(),key:z98.string()}).strict(),outputSchema:labelDeleteOutputSchema,buildRequest:__name(({projectId,branch,locale,key})=>({method:"DELETE",path:tenantPath(projectId,branch,locale?`/labels/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`:`/labels/${encodeURIComponent(key)}`)}),"buildRequest"),projectOutput:__name(body=>responseValue(labelDeleteOutputSchema,body),"projectOutput")}}}});import{z as z99}from"zod";var projectLocaleCoverageSchema,ProjectLocaleStatsResponseSchema2,projectLocaleInputSchema,ProjectLocaleMutationResponseSchema2,RemoveProjectLocaleResponseSchema2,localesOperations,init_locales=__esm({"../../packages/sdk/dist/operations/locales.js"(){"use strict";init_common2();projectLocaleCoverageSchema=z99.object({translated:z99.number().int().nonnegative(),total:z99.number().int().nonnegative()}),ProjectLocaleStatsResponseSchema2=createResponseSchema2(z99.object({defaultLocale:z99.string(),locales:z99.array(z99.object({locale:z99.string(),isDefault:z99.boolean(),entries:projectLocaleCoverageSchema,labels:projectLocaleCoverageSchema}))})),projectLocaleInputSchema=z99.string().min(1).max(40),ProjectLocaleMutationResponseSchema2=createResponseSchema2(z99.object({locale:z99.string()})),RemoveProjectLocaleResponseSchema2=createResponseSchema2(z99.object({locale:z99.string(),entriesDeleted:z99.number().int().nonnegative(),labelsDeleted:z99.number().int().nonnegative()})),localesOperations={"locales.list":{domain:"locales",summary:"List configured locales and content coverage on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z99.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:ProjectLocaleStatsResponseSchema2,buildRequest:__name(({projectId,branch})=>({method:"GET",path:managementBranchPath(projectId,branch,"/locales/stats")}),"buildRequest")},"locales.add":{domain:"locales",summary:"Add a configured locale to a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z99.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:ProjectLocaleMutationResponseSchema2,buildRequest:__name(({projectId,branch,locale})=>({method:"POST",path:managementBranchPath(projectId,branch,"/locales"),body:{locale}}),"buildRequest")},"locales.setDefault":{domain:"locales",summary:"Set the default configured locale on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z99.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:ProjectLocaleMutationResponseSchema2,buildRequest:__name(({projectId,branch,locale})=>({method:"PUT",path:managementBranchPath(projectId,branch,"/locales/default"),body:{locale}}),"buildRequest")},"locales.delete":{domain:"locales",summary:"Delete a non-default locale and its localized content from a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z99.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:RemoveProjectLocaleResponseSchema2,buildRequest:__name(({projectId,branch,locale})=>({method:"DELETE",path:managementBranchPath(projectId,branch,`/locales/${encodeURIComponent(locale)}`)}),"buildRequest")}}}});import{z as z100}from"zod";var organizationSchema,organizationMemberSchema,organizationInvitationSchema,referralSummarySchema,organizationsOperations,init_organizations=__esm({"../../packages/sdk/dist/operations/organizations.js"(){"use strict";init_common2();organizationSchema=z100.object({id:z100.string().min(1),name:z100.string(),slug:z100.string()}),organizationMemberSchema=z100.object({id:z100.string().min(1),role:z100.string(),createdAt:z100.string().optional(),user:z100.object({id:z100.string().min(1),name:z100.string().nullable().optional(),email:z100.string().nullable().optional()}).optional()}),organizationInvitationSchema=z100.object({id:z100.string().min(1),email:z100.email(),role:z100.string(),organizationId:z100.string().min(1),inviterId:z100.string().min(1),status:z100.string(),expiresAt:z100.string(),createdAt:z100.string()}).passthrough(),referralSummarySchema=z100.object({counts:z100.object({signed_up:z100.number().int(),activated:z100.number().int()}),credits:z100.object({total:z100.number().int(),earned:z100.number().int().optional()})}),organizationsOperations={"organizations.list":{domain:"organizations",summary:"List organizations the authenticated user belongs to.",accessScope:"read",effect:"read",inputSchema:z100.object({}).strict(),outputSchema:createResponseSchema2(z100.array(organizationSchema)),buildRequest:__name(()=>({method:"GET",path:"/management/organizations"}),"buildRequest")},"organizations.members":{domain:"organizations",summary:"List members of one organization.",accessScope:"read",effect:"read",inputSchema:z100.object({organizationId:z100.string().min(1)}).strict(),outputSchema:z100.array(organizationMemberSchema),buildRequest:__name(({organizationId})=>({method:"GET",path:`/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`}),"buildRequest"),projectOutput:__name(body=>z100.object({members:z100.array(organizationMemberSchema)}).nullable().parse(body)?.members??[],"projectOutput")},"organizations.invite":{domain:"organizations",summary:"Invite a user to an organization.",accessScope:"write",effect:"mutation",inputSchema:z100.object({organizationId:z100.string().min(1),email:z100.email(),role:z100.enum(["owner","admin","member"]),resend:z100.boolean().optional()}).strict(),outputSchema:organizationInvitationSchema,buildRequest:__name(input=>({method:"POST",path:"/auth/organization/invite-member",body:input}),"buildRequest")},"referrals.summary":{domain:"referrals",summary:"Read the referral summary for the authenticated user.",accessScope:"read",effect:"read",inputSchema:z100.object({userId:z100.string().min(1)}).strict(),outputSchema:referralSummarySchema,buildRequest:__name(({userId})=>({method:"GET",path:`/users/${encodeURIComponent(userId)}/referrals/summary`}),"buildRequest"),projectOutput:__name(body=>referralSummarySchema.parse(responseData(body)),"projectOutput")}}}});import{z as z101}from"zod";var projectSchema,projectResponseSchema,transferResultSchema,projectsOperations,init_projects=__esm({"../../packages/sdk/dist/operations/projects.js"(){"use strict";init_common2();projectSchema=z101.object({id:uuidSchema,name:z101.string(),displayName:z101.string().nullable(),organizationId:z101.string().nullable(),defaultBranch:branchNameSchema.optional(),productionSourceBranch:branchNameSchema.optional(),status:z101.string().optional(),appUrl:z101.string().nullable().optional()}).passthrough(),projectResponseSchema=z101.object({data:projectSchema}),transferResultSchema=z101.object({projectId:z101.string(),sourceOrganizationId:z101.string(),targetOrganizationId:z101.string(),movedThreads:z101.number().int().nonnegative(),revokedInvites:z101.number().int().nonnegative(),revokedGrants:z101.number().int().nonnegative(),preservedGrants:z101.number().int().nonnegative(),warnings:z101.array(z101.string())}),projectsOperations={"projects.list":{domain:"projects",summary:"List the Fimo sites the authenticated user can access.",accessScope:"read",effect:"read",inputSchema:z101.object({organizationId:z101.string().min(1).optional()}).strict(),outputSchema:z101.object({data:z101.array(projectSchema)}),buildRequest:__name(({organizationId})=>({method:"GET",path:organizationId?`/management/organizations/${encodeURIComponent(organizationId)}/projects`:"/management/projects"}),"buildRequest")},"projects.get":{domain:"projects",summary:"Read one Fimo site the authenticated user can access.",accessScope:"read",effect:"read",inputSchema:z101.object({projectId:uuidSchema}).strict(),outputSchema:projectResponseSchema,buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"")}),"buildRequest")},"projects.create":{domain:"projects",summary:"Create a Fimo site in an organization. Pass starter to commit a runnable Fimo site template so sessions, preview and publish work immediately; use nextjs unless the user asks for another framework.",accessScope:"write",effect:"mutation",inputSchema:z101.object({organizationId:z101.string().min(1),displayName:z101.string().min(1).optional(),origin:z101.enum(["scratch","migration"]).optional(),starter:z101.enum(["nextjs","astro","react-router","vite","sveltekit"]).optional()}).strict(),outputSchema:projectResponseSchema,buildRequest:__name(({organizationId,displayName,origin,starter})=>({method:"POST",path:"/management/projects",body:withoutUndefined({organizationId,displayName,origin,starter,source:"cli"})}),"buildRequest")},"projects.transfer":{domain:"projects",summary:"Transfer one Fimo site to another organization.",accessScope:"write",effect:"mutation",inputSchema:z101.object({projectId:uuidSchema,targetOrganizationId:z101.string().min(1)}).strict(),outputSchema:transferResultSchema,buildRequest:__name(({projectId,targetOrganizationId})=>({method:"POST",path:managementProjectPath(projectId,"/transfer"),body:{targetOrganizationId},preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>transferResultSchema.parse(responseData(body)),"projectOutput")},"projects.invite":{domain:"projects",summary:"Invite someone by email to collaborate on a Fimo site with full, edit, comment or view access. They receive an email and join the site's members when they accept.",accessScope:"write",effect:"mutation",inputSchema:z101.object({projectId:uuidSchema,email:z101.email(),role:z101.enum(["full","edit","comment","view"])}).strict(),outputSchema:z101.object({id:z101.string().min(1)}),buildRequest:__name(({projectId,email,role})=>({method:"POST",path:managementProjectPath(projectId,"/invites"),body:{email,roleKey:role}}),"buildRequest"),projectOutput:__name(body=>({id:z101.object({id:z101.string().min(1)}).parse(responseData(body)).id}),"projectOutput")},"projects.delete":{domain:"projects",summary:"Permanently delete a Fimo site.",accessScope:"write",effect:"mutation",inputSchema:z101.object({projectId:uuidSchema}).strict(),outputSchema:z101.unknown(),buildRequest:__name(({projectId})=>({method:"DELETE",path:managementProjectPath(projectId,""),body:{}}),"buildRequest")}}}});import{z as z102}from"zod";function projectBranchRecord2(value){let{env,...record}=value;return{...record,branch:env}}function projectSchedule(body){return scheduleSchema.parse(projectBranchRecord2(responseData(body)))}function projectRun(body){return runSchema.parse(projectBranchRecord2(responseData(body)))}function projectOverview(body){let value=responseData(body);return overviewSchema.parse({...value,items:value.items.map(projectBranchRecord2)})}function projectDetail2(body){let value=responseData(body);return detailSchema.parse({...value,schedule:projectBranchRecord2(value.schedule)})}function projectRunsPage(body){let value=responseData(body);return runsPageSchema.parse({...value,items:value.items.map(projectBranchRecord2)})}function projectRunDetail(body){return runDetailSchema.parse(projectBranchRecord2(responseData(body)))}var dateSchema,scheduleStatusSchema,runStatusSchema,scheduleSchema,usageSchema,policySchema,planSchema,runSchema,runDetailSchema,overviewSchema,detailSchema,runsPageSchema,scheduleWriteShape,scheduleContextShape,schedulesOperations,init_schedules=__esm({"../../packages/sdk/dist/operations/schedules.js"(){"use strict";init_common2();dateSchema=z102.iso.datetime(),scheduleStatusSchema=z102.enum(["ok","failed"]),runStatusSchema=z102.enum(["queued","running","succeeded","failed","skipped"]),scheduleSchema=z102.object({id:uuidSchema,createdAt:dateSchema,updatedAt:dateSchema,projectId:uuidSchema,branch:z102.string().min(1),name:z102.string().min(1),cron:z102.string().min(1),command:z102.string().min(1),secretKeys:z102.array(z102.string().min(1)),enabled:z102.boolean(),lastRunAt:dateSchema.nullable(),lastStatus:scheduleStatusSchema.nullable(),lastError:z102.string().nullable(),overPolicyReasons:z102.array(z102.string()).optional()}).passthrough(),usageSchema=z102.object({runCount:z102.number().int().nonnegative(),runsWithOutput:z102.number().int().nonnegative()}),policySchema=z102.object({maxRuns:z102.number().int().positive(),retentionDays:z102.number().int().positive().nullable(),outputRetentionDays:z102.number().int().positive(),maxOutputBytes:z102.number().int().positive()}).passthrough(),planSchema=z102.object({code:z102.enum(["Free","PAYG","Premium","Pro"]),source:z102.enum(["cached_subscription","free_fallback"]),activeSchedules:z102.object({used:z102.number().int().nonnegative(),limit:z102.number().int().positive()}),minCadenceMinutes:z102.number().int().positive(),maxRunMs:z102.number().int().positive(),concurrency:z102.object({used:z102.number().int().nonnegative(),limit:z102.number().int().positive()}),compute:z102.object({settledMs:z102.number().int().nonnegative(),activeMs:z102.number().int().nonnegative(),reservedMs:z102.number().int().nonnegative().optional(),includedMs:z102.number().int().positive(),remainingMs:z102.number().int().nonnegative(),resetsAt:dateSchema}),state:z102.enum(["ok","near_limit","exhausted","over_policy"]),overPolicyReasons:z102.array(z102.string())}).passthrough(),runSchema=z102.object({id:uuidSchema,scheduleId:uuidSchema,projectId:uuidSchema,branch:z102.string().min(1),scheduleName:z102.string().min(1),command:z102.string().min(1),status:runStatusSchema,trigger:z102.enum(["cron","ui","cli"]),triggeredBy:z102.object({id:z102.string().min(1),name:z102.string().min(1)}).nullable(),queuedAt:dateSchema,startedAt:dateSchema.nullable(),finishedAt:dateSchema.nullable(),exitCode:z102.number().int().nullable(),errorCode:z102.string().nullable(),error:z102.string().nullable(),outputBytes:z102.number().int().nonnegative(),outputTruncated:z102.boolean(),outputExpiresAt:dateSchema.nullable(),metadataExpiresAt:dateSchema.nullable()}).passthrough(),runDetailSchema=runSchema.extend({output:z102.string().nullable(),secretSnapshot:z102.object({state:z102.enum(["pending","resolved","failed"]),capturedAt:dateSchema.nullable(),items:z102.array(z102.object({key:z102.string().min(1),updatedAt:dateSchema.nullable(),resolution:z102.enum(["resolved","missing","deleted","recreated","rotated"])}))})}),overviewSchema=z102.object({items:z102.array(scheduleSchema),usage:usageSchema,policy:policySchema,plan:planSchema}),detailSchema=z102.object({schedule:scheduleSchema,usage:usageSchema,policy:policySchema,plan:planSchema}).passthrough(),runsPageSchema=z102.object({items:z102.array(runSchema),nextCursor:z102.string().nullable(),usage:usageSchema,policy:policySchema,plan:planSchema});__name(projectBranchRecord2,"projectBranchRecord");__name(projectSchedule,"projectSchedule");__name(projectRun,"projectRun");__name(projectOverview,"projectOverview");__name(projectDetail2,"projectDetail");__name(projectRunsPage,"projectRunsPage");__name(projectRunDetail,"projectRunDetail");scheduleWriteShape={name:z102.string().min(1).max(120),cron:z102.string().min(1).max(120),command:z102.string().min(1).max(500),secretKeys:z102.array(z102.string().min(1))},scheduleContextShape={projectId:uuidSchema,branch:branchNameSchema.optional()},schedulesOperations={"schedules.list":{domain:"schedules",summary:"List schedule records for one site Branch.",accessScope:"read",effect:"read",inputSchema:z102.object({...scheduleContextShape}).strict(),outputSchema:z102.array(scheduleSchema),buildRequest:__name(({projectId,branch})=>({method:"GET",context:{branch},path:managementProjectPath(projectId,"/schedules")}),"buildRequest"),projectOutput:__name(body=>z102.array(scheduleSchema).parse(responseData(body).map(projectBranchRecord2)),"projectOutput")},"schedules.overview":{domain:"schedules",summary:"Read schedules with usage and plan limits for one site Branch.",accessScope:"read",effect:"read",inputSchema:z102.object({...scheduleContextShape}).strict(),outputSchema:overviewSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",context:{branch},path:managementProjectPath(projectId,"/schedules/overview")}),"buildRequest"),projectOutput:projectOverview},"schedules.get":{domain:"schedules",summary:"Read one schedule with usage and plan limits.",accessScope:"read",effect:"read",inputSchema:z102.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:detailSchema,buildRequest:__name(({projectId,branch,scheduleId})=>({method:"GET",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}`)}),"buildRequest"),projectOutput:projectDetail2},"schedules.create":{domain:"schedules",summary:"Create a recurring command schedule for one site Branch.",accessScope:"agents",effect:"mutation",inputSchema:z102.object({...scheduleContextShape,...scheduleWriteShape,enabled:z102.boolean().optional()}).strict(),outputSchema:scheduleSchema,buildRequest:__name(({projectId,branch,...body})=>({method:"POST",context:{branch},path:managementProjectPath(projectId,"/schedules"),body}),"buildRequest"),projectOutput:projectSchedule},"schedules.update":{domain:"schedules",summary:"Update a recurring command schedule.",accessScope:"agents",effect:"mutation",inputSchema:z102.object({...scheduleContextShape,scheduleId:uuidSchema,name:scheduleWriteShape.name.optional(),cron:scheduleWriteShape.cron.optional(),command:scheduleWriteShape.command.optional(),secretKeys:scheduleWriteShape.secretKeys.optional()}).strict().refine(({projectId:_projectId,branch:_branch,scheduleId:_scheduleId,...update})=>Object.values(update).some(value=>value!==void 0),{message:"Pass at least one schedule field to update."}),outputSchema:scheduleSchema,buildRequest:__name(({projectId,branch,scheduleId,...update})=>({method:"PATCH",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}`),body:withoutUndefined(update)}),"buildRequest"),projectOutput:projectSchedule},"schedules.setEnabled":{domain:"schedules",summary:"Pause or resume a recurring command schedule.",accessScope:"agents",effect:"mutation",inputSchema:z102.object({...scheduleContextShape,scheduleId:uuidSchema,enabled:z102.boolean()}).strict(),outputSchema:scheduleSchema,buildRequest:__name(({projectId,branch,scheduleId,enabled})=>({method:"POST",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}/${enabled?"resume":"pause"}`)}),"buildRequest"),projectOutput:projectSchedule},"schedules.run":{domain:"schedules",summary:"Queue an immediate run of a site schedule.",accessScope:"agents",effect:"mutation",inputSchema:z102.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:runSchema,buildRequest:__name(({projectId,branch,scheduleId})=>({method:"POST",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}/run`),body:{trigger:"cli"}}),"buildRequest"),projectOutput:projectRun},"schedules.listRuns":{domain:"schedules",summary:"List runs of one site schedule with cursor pagination.",accessScope:"read",effect:"read",inputSchema:z102.object({...scheduleContextShape,scheduleId:uuidSchema,limit:z102.number().int().min(1).max(100).optional(),cursor:paginationShape.cursor,status:runStatusSchema.optional()}).strict(),outputSchema:runsPageSchema,buildRequest:__name(({projectId,branch,scheduleId,limit,cursor,status})=>({method:"GET",context:{branch},path:addQuery(managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}/runs`),{limit,cursor,status})}),"buildRequest"),projectOutput:projectRunsPage},"schedules.getRun":{domain:"schedules",summary:"Read one schedule run and its captured output.",accessScope:"read",effect:"read",inputSchema:z102.object({...scheduleContextShape,runId:uuidSchema}).strict(),outputSchema:runDetailSchema,buildRequest:__name(({projectId,branch,runId})=>({method:"GET",context:{branch},path:managementProjectPath(projectId,`/schedules/runs/${encodeURIComponent(runId)}`)}),"buildRequest"),projectOutput:projectRunDetail},"schedules.delete":{domain:"schedules",summary:"Delete one site schedule.",accessScope:"agents",effect:"mutation",inputSchema:z102.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:z102.object({ok:z102.literal(!0)}),buildRequest:__name(({projectId,branch,scheduleId})=>({method:"DELETE",context:{branch},path:managementProjectPath(projectId,`/schedules/${encodeURIComponent(scheduleId)}`)}),"buildRequest"),projectOutput:__name(body=>z102.object({ok:z102.literal(!0)}).parse(responseData(body)),"projectOutput")}}}});import{z as z103}from"zod";function projectSchemaDefinition(body){return z103.object({data:contentTypeSchema}).parse(body).data}var contentTypeSchema,schemaListOutputSchema,schemaMutationOutputSchema,schemaDefinitionInputSchema,schemasOperations,init_schemas=__esm({"../../packages/sdk/dist/operations/schemas.js"(){"use strict";init_common2();contentTypeSchema=z103.object({id:z103.string(),name:z103.string(),label:z103.string(),isSingleton:z103.boolean(),slugUnique:z103.boolean(),i18n:z103.record(z103.string(),z103.unknown()),groups:z103.array(z103.record(z103.string(),z103.unknown())),fields:z103.record(z103.string(),z103.unknown()),createdAt:z103.string(),updatedAt:z103.string()}).passthrough(),schemaListOutputSchema=z103.object({contentTypes:z103.array(contentTypeSchema)}),schemaMutationOutputSchema=sessionEnvelopeSchema.extend({schema:z103.object({typeName:z103.string().min(1).max(255),generatedPaths:z103.array(z103.string().min(1)).max(1e3),tip:z103.string().min(1)})}),schemaDefinitionInputSchema=z103.record(z103.string(),z103.unknown());__name(projectSchemaDefinition,"projectSchemaDefinition");schemasOperations={"schemas.list":{domain:"schemas",summary:"List content schemas on a durable Branch.",accessScope:"read",effect:"read",inputSchema:z103.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:schemaListOutputSchema,buildRequest:__name(({projectId,branch})=>({method:"GET",path:tenantPath(projectId,branch,"/schema")}),"buildRequest")},"schemas.get":{domain:"schemas",summary:"Get one complete content schema from a durable Branch.",accessScope:"read",effect:"read",inputSchema:z103.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z103.string().min(1).max(255)}).strict(),outputSchema:contentTypeSchema,buildRequest:__name(({projectId,branch,typeName})=>({method:"GET",path:tenantPath(projectId,branch,`/schema/types/${encodeURIComponent(typeName)}`)}),"buildRequest"),projectOutput:projectSchemaDefinition},"schemas.upsertBatch":{domain:"schemas",summary:"Atomically create or update a batch of content schemas on a Fimo Branch.",accessScope:"code",effect:"mutation",inputSchema:z103.object({projectId:uuidSchema,branch:branchNameSchema,contentTypes:z103.array(schemaDefinitionInputSchema).min(1).max(100),operations:z103.array(z103.record(z103.string(),z103.unknown())).optional()}).strict(),outputSchema:z103.array(z103.unknown()),buildRequest:__name(({projectId,branch,contentTypes,operations})=>({method:"POST",path:tenantPath(projectId,branch,"/schema/batch"),body:withoutUndefined({contentTypes,operations:operations?.length?operations:void 0})}),"buildRequest"),projectOutput:__name(body=>z103.object({data:z103.array(z103.unknown())}).parse(body).data,"projectOutput")},"schemas.deleteFromBranch":{domain:"schemas",summary:"Delete a content schema directly from a Fimo Branch.",accessScope:"code",effect:"mutation",inputSchema:z103.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z103.string().min(1).max(255)}).strict(),outputSchema:z103.unknown(),buildRequest:__name(({projectId,branch,typeName})=>({method:"DELETE",path:tenantPath(projectId,branch,`/schema/types/${encodeURIComponent(typeName)}`)}),"buildRequest"),projectOutput:__name(body=>z103.object({data:z103.unknown()}).parse(body).data,"projectOutput")},"schemas.create":{domain:"schemas",summary:"Create a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z103.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z103.string().min(1).max(255),definition:schemaDefinitionInputSchema}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId,sessionId,typeName,definition})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/schema`),body:{kind:"create",typeName,definition}}),"buildRequest")},"schemas.update":{domain:"schemas",summary:"Update a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z103.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z103.string().min(1).max(255),definition:schemaDefinitionInputSchema,renameFrom:z103.string().max(255).optional()}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId,sessionId,typeName,definition,renameFrom})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/schema`),body:withoutUndefined({kind:"update",typeName,definition,renameFrom})}),"buildRequest")},"schemas.delete":{domain:"schemas",summary:"Delete a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z103.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z103.string().min(1).max(255)}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId,sessionId,typeName})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/schema`),body:{kind:"delete",typeName}}),"buildRequest")}}}});import{z as z104}from"zod";var environmentSchema2,secretKindSchema,projectSecretSchema,secretWriteInputSchema,secretsOperations,init_secrets=__esm({"../../packages/sdk/dist/operations/secrets.js"(){"use strict";init_common2();environmentSchema2=z104.union([z104.literal("production"),z104.literal("preview"),uuidSchema]),secretKindSchema=z104.enum(["variable","secret"]),projectSecretSchema=z104.object({id:z104.string().min(1),projectId:z104.string().min(1),key:z104.string().min(1),kind:secretKindSchema,exposure:z104.enum(["public","private"]),environment:environmentSchema2,value:z104.string().optional(),maskedValue:z104.string().optional(),createdAt:z104.string(),updatedAt:z104.string()}),secretWriteInputSchema=z104.object({projectId:uuidSchema,key:z104.string().min(1).max(255),kind:secretKindSchema,value:z104.string(),environment:environmentSchema2}),secretsOperations={"secrets.list":{domain:"secrets",summary:"List public variables or masked secrets for one site Environment.",accessScope:"read",effect:"read",inputSchema:z104.object({projectId:uuidSchema,environment:environmentSchema2,kind:secretKindSchema.optional()}).strict(),outputSchema:z104.array(projectSecretSchema),buildRequest:__name(({projectId,environment,kind})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/secrets"),{environment,kind})}),"buildRequest"),projectOutput:__name(body=>z104.array(projectSecretSchema).parse(responseData(body)),"projectOutput")},"secrets.create":{domain:"secrets",summary:"Create a public variable or secret for one site Environment.",accessScope:"write",effect:"mutation",inputSchema:secretWriteInputSchema.strict(),outputSchema:projectSecretSchema,buildRequest:__name(({projectId,...body})=>({method:"POST",path:managementProjectPath(projectId,"/secrets"),body}),"buildRequest"),projectOutput:__name(body=>projectSecretSchema.parse(responseData(body)),"projectOutput")},"secrets.update":{domain:"secrets",summary:"Update a public variable or secret for one site Environment.",accessScope:"write",effect:"mutation",inputSchema:secretWriteInputSchema.strict(),outputSchema:projectSecretSchema,buildRequest:__name(({projectId,key,...body})=>({method:"PATCH",path:managementProjectPath(projectId,`/secrets/${encodeURIComponent(key)}`),body}),"buildRequest"),projectOutput:__name(body=>projectSecretSchema.parse(responseData(body)),"projectOutput")},"secrets.delete":{domain:"secrets",summary:"Delete a public variable or secret from one site Environment.",accessScope:"write",effect:"mutation",inputSchema:z104.object({projectId:uuidSchema,key:z104.string().min(1),kind:secretKindSchema,environment:environmentSchema2}).strict(),outputSchema:z104.unknown(),buildRequest:__name(({projectId,key,kind,environment})=>({method:"DELETE",path:addQuery(managementProjectPath(projectId,`/secrets/${encodeURIComponent(key)}`),{kind,environment})}),"buildRequest")},"environments.resolve":{domain:"environments",summary:"Resolve which compatibility Environment receives one site Branch.",accessScope:"read",effect:"read",inputSchema:z104.object({projectId:uuidSchema,branch:z104.string().min(1)}).strict(),outputSchema:z104.object({branch:z104.string().min(1),environment:environmentSchema2}),buildRequest:__name(({projectId})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/branches"),{includeAgentEnvs:!0})}),"buildRequest"),projectOutput:__name((body,input)=>{let branches=z104.array(z104.object({branch:z104.string().optional(),env:z104.string().optional(),parentBranch:z104.string().nullable().optional(),parentEnv:z104.string().nullable().optional(),resolvedEnvironment:z104.object({id:environmentSchema2}).nullable().optional()}).passthrough()).parse(responseData(body)),current=branches.find(candidate=>(candidate.branch??candidate.env)===input.branch),visited=new Set;for(;current;){let name=current.branch??current.env;if(!name||visited.has(name))break;if(visited.add(name),current.resolvedEnvironment)return{branch:input.branch,environment:current.resolvedEnvironment.id};let parent=current.parentBranch??current.parentEnv;current=parent?branches.find(candidate=>(candidate.branch??candidate.env)===parent):void 0}return{branch:input.branch,environment:"preview"}},"projectOutput")}}}});import{z as z105}from"zod";function projectConflictSurface(conflict){let value=recordValue(conflict,"Expected a session conflict object.");return{...value,surface:value.surface==="translations"?"labels":value.surface}}function projectSessionChanges(body){let value=recordValue(body,"Expected a session changes response."),changes=recordValue(value.changes,"Expected session changes.");if(!Array.isArray(changes.surfaces))throw new Error("Expected session change surfaces.");return{...value,changes:{...changes,surfaces:changes.surfaces.map(projectConflictSurface),...Array.isArray(changes.crossSurface)?{crossSurface:changes.crossSurface.map(finding=>{let parsed=backendCrossSurfaceFindingSchema.parse(finding);return projectCrossSurfaceFinding(parsed)})}:{}}}}function projectSessionConflicts(body){let value=recordValue(body,"Expected a session conflict response.");return Array.isArray(value.conflicts)?{...value,conflicts:value.conflicts.map(projectConflictSurface)}:value}function backendConflictResolutions(resolutions){return resolutions.map(resolution=>({...resolution,surface:resolution.surface==="labels"?"translations":resolution.surface}))}var sessionValidationSchema,sessionConflictSummarySchema,surfaceDeltaItemSchema,perSurfaceDeltaSchema,sessionChangesSchema,projectScriptStatusSchema,sessionOperationResultSchema,conflictSchema2,codeConflictBlobSchema2,codeConflictDetailSchema,resolutionChoiceSchema,conflictResolutionSchema2,resolvedMergeStrategySchema,sessionsOperations,init_sessions=__esm({"../../packages/sdk/dist/operations/sessions.js"(){"use strict";init_branches();init_common2();__name(projectConflictSurface,"projectConflictSurface");__name(projectSessionChanges,"projectSessionChanges");__name(projectSessionConflicts,"projectSessionConflicts");__name(backendConflictResolutions,"backendConflictResolutions");sessionValidationSchema=z105.object({status:z105.literal("passed")}).passthrough(),sessionConflictSummarySchema=z105.object({surface:surfaceNameSchema,key:z105.string().min(1),kind:z105.string().optional(),description:z105.string(),path:z105.string().optional()}).passthrough(),surfaceDeltaItemSchema=z105.object({verb:z105.enum(["added","removed","changed","conflict"]),key:z105.string(),detail:z105.string().optional(),origin:z105.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z105.record(z105.string(),z105.unknown()).optional()}).passthrough(),perSurfaceDeltaSchema=z105.object({surface:surfaceNameSchema,status:z105.enum(["ok","timed_out","failed","unchanged"]),durationMs:z105.number().int().nonnegative().optional(),changedCount:z105.number().int().nonnegative(),conflictCount:z105.number().int().nonnegative(),items:z105.array(surfaceDeltaItemSchema).max(1e3).optional(),truncated:z105.boolean().optional(),error:z105.string().optional()}).passthrough(),sessionChangesSchema=z105.object({fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),generatedAt:z105.iso.datetime(),surfaces:z105.array(perSurfaceDeltaSchema),crossSurface:z105.array(crossSurfaceFindingSchema).optional(),fingerprint:z105.string()}).passthrough(),projectScriptStatusSchema=z105.enum(["passed","failed","unavailable"]),sessionOperationResultSchema=z105.discriminatedUnion("operation",[z105.object({operation:z105.literal("dependencies_install"),repairedInstallPolicy:z105.boolean(),tip:z105.string()}),z105.object({operation:z105.literal("schemas_sync"),tip:z105.string()}),z105.object({operation:z105.literal("typecheck"),status:projectScriptStatusSchema,output:z105.string()}),z105.object({operation:z105.literal("lint"),status:projectScriptStatusSchema,output:z105.string()})]),conflictSchema2=z105.object({surface:surfaceNameSchema,key:z105.string(),kind:z105.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"]).optional(),description:z105.string(),parentValue:z105.unknown().optional(),childValue:z105.unknown().optional(),conflictingFields:z105.array(z105.string()).optional(),code:z105.object({path:z105.string(),unresolvable:z105.boolean().optional(),reason:z105.string().optional()}).optional()}).passthrough(),codeConflictBlobSchema2=z105.object({oid:z105.string().optional(),content:z105.string().optional(),truncated:z105.boolean(),binary:z105.boolean()}),codeConflictDetailSchema=z105.object({path:z105.string(),base:codeConflictBlobSchema2,ours:codeConflictBlobSchema2,theirs:codeConflictBlobSchema2,result:codeConflictBlobSchema2,sourceTipSha:z105.string(),targetTipSha:z105.string(),mergeBaseSha:z105.string().optional()}),resolutionChoiceSchema=z105.enum(["parent","child","pick"]),conflictResolutionSchema2=z105.object({surface:surfaceNameSchema,key:z105.string().min(1),choice:resolutionChoiceSchema,pickedValue:z105.unknown().optional(),fieldPicks:z105.array(z105.object({field:z105.string().min(1),choice:resolutionChoiceSchema,pickedValue:z105.unknown().optional()})).optional()}).superRefine((resolution,context)=>{resolution.choice==="pick"&&resolution.pickedValue===void 0&&!resolution.fieldPicks?.length&&context.addIssue({code:"custom",message:"Pass pickedValue when choice is 'pick'.",path:["pickedValue"]}),resolution.fieldPicks?.forEach((fieldPick,index)=>{fieldPick.choice==="pick"&&fieldPick.pickedValue===void 0&&context.addIssue({code:"custom",message:"Pass pickedValue when choice is 'pick'.",path:["fieldPicks",index,"pickedValue"]})})}),resolvedMergeStrategySchema=z105.object({engine:z105.enum(["ff-only","auto","theirs","ours","manual"]),vendor:z105.enum(["ff_only","ff_prefer","merge"]),squash:z105.boolean()}),sessionsOperations={"sessions.start":{domain:"sessions",summary:"Start an isolated work session. At capacity, Fimo cleans expired/leaked work, then the oldest inactive temporary work before refusing. Temporary expiry is a maximum lifetime, not guaranteed retention. Inspect your sessions and close unused work; durable work and active operations are not pressure-reclaimed.",accessScope:"code",effect:"mutation",inputSchema:z105.object({projectId:uuidSchema,targetBranch:branchNameSchema.optional(),name:z105.string().trim().min(1).max(120).optional(),goal:z105.string().trim().min(1).max(500).optional()}).strict(),outputSchema:z105.object({session:sessionEnvelopeSchema,adopted:z105.boolean()}),buildRequest:__name(({projectId,targetBranch,name,goal})=>({method:"POST",path:managementProjectPath(projectId,"/sessions"),body:withoutUndefined({targetBranch,name,goal})}),"buildRequest")},"sessions.get":{domain:"sessions",summary:"Get one owned Fimo work session for lifecycle recovery.",accessScope:"code",effect:"read",inputSchema:z105.object({projectId:uuidSchema,sessionId:uuidSchema}).strict(),outputSchema:sessionEnvelopeSchema,buildRequest:__name(({projectId,sessionId})=>({method:"GET",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}`)}),"buildRequest")},"sessions.list":{domain:"sessions",summary:"Discover work sessions. Defaults to mine; project lists authorized work within the connection's client boundary.",accessScope:"code",effect:"read",inputSchema:z105.object({projectId:uuidSchema,status:sessionStatusSchema.optional(),scope:z105.enum(["mine","project"]).optional(),cursor:paginationShape.cursor,limit:z105.number().int().min(1).max(100).optional()}).strict(),outputSchema:z105.object({items:z105.array(sessionEnvelopeSchema),nextCursor:z105.string().nullable()}),buildRequest:__name(({projectId,status,cursor,limit,scope:scope2})=>({method:"GET",path:addQuery(managementProjectPath(projectId,"/sessions"),{status,cursor,limit,scope:scope2})}),"buildRequest")},"sessions.changes":{domain:"sessions",summary:"Review bounded changes in an owned work session before closing it.",accessScope:"code",effect:"read",inputSchema:z105.object({projectId:uuidSchema,sessionId:uuidSchema,detail:z105.boolean().optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({changes:sessionChangesSchema}),buildRequest:__name(({projectId,sessionId,detail})=>({method:"GET",path:addQuery(managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/changes`),{detail})}),"buildRequest"),projectOutput:projectSessionChanges},"sessions.requestReview":{domain:"sessions",summary:"Save current work in one owned session and request human review. Keeps that same session visible and durable, with no expiry. Returns the saved revision and secure review URL. Does not merge, publish or finish a run. Retry unchanged work to reuse its review.",accessScope:"code",effect:"mutation",inputSchema:z105.object({projectId:uuidSchema,sessionId:uuidSchema,summary:z105.string().trim().min(1).max(240),targetBranch:branchNameSchema.optional()}).strict(),outputSchema:z105.object({requested:z105.literal(!0),alreadyRequested:z105.boolean(),reviewId:uuidSchema,reviewUrl:z105.url(),status:z105.literal("pending"),sessionId:uuidSchema,branch:branchNameSchema,targetBranch:branchNameSchema,revision:z105.string().min(1),savedRevision:z105.string().min(1),fingerprint:z105.string().min(1),visibility:z105.literal("user-visible"),retention:z105.literal("durable"),expiresAt:z105.null(),merged:z105.literal(!1),published:z105.literal(!1),links:z105.object({preview:z105.url(),changes:z105.url(),conversation:z105.url().nullable()})}),buildRequest:__name(({projectId,sessionId,summary:summary2,targetBranch})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/review`),body:withoutUndefined({summary:summary2,targetBranch})}),"buildRequest")},"sessions.setRetention":{domain:"sessions",summary:"Add exactly 1\u201330 whole days to the current expiry of temporary work. Repeat for more time; each request is bounded to that range, not the total. Returns actual expiry. Rejects unchanged with invalid_session_retention when the work is not temporary or has no deadline. Does not save, show, merge or publish; eligible early capacity cleanup still applies.",accessScope:"code",effect:"mutation",inputSchema:z105.object({projectId:uuidSchema,sessionId:uuidSchema,additionalDays:z105.number().int().min(1).max(30)}).strict(),outputSchema:sessionEnvelopeSchema.extend({retention:z105.literal("temporary"),visibility:z105.enum(["internal","user-visible"]),expiresAt:z105.iso.datetime()}),buildRequest:__name(({projectId,sessionId,additionalDays})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/retention`),body:{additionalDays}}),"buildRequest")},"sessions.validate":{domain:"sessions",summary:"Run site validation inside an owned Fimo work session and wait for its terminal result.",accessScope:"code",effect:"mutation",inputSchema:z105.object({projectId:uuidSchema,sessionId:uuidSchema}).strict(),outputSchema:sessionEnvelopeSchema.extend({validation:sessionValidationSchema}),buildRequest:__name(({projectId,sessionId})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/validate`)}),"buildRequest")},"sessions.runOperation":{domain:"sessions",summary:"Run an approved sandbox operation in an owned work session: 'dependencies_install', 'schemas_sync', or the project's own 'typecheck' or 'lint' script, which report their output without saving.",accessScope:"code",effect:"mutation",inputSchema:z105.object({projectId:uuidSchema,sessionId:uuidSchema,operation:z105.string().min(1).max(100),args:z105.record(z105.string(),z105.unknown()).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({operation:sessionOperationResultSchema}),buildRequest:__name(({projectId,sessionId,operation,args})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/operations`),body:args===void 0?{operation}:{operation,args}}),"buildRequest")},"sessions.close":{domain:"sessions",summary:"Merge or discard an owned Fimo work session.",accessScope:"code",effect:"mutation",inputSchema:z105.object({projectId:uuidSchema,sessionId:uuidSchema,action:z105.enum(["merge","discard"]),message:z105.string().max(1e3).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({outcome:z105.enum(["merged","no_changes","discarded","conflicts","failed"]),closed:z105.boolean(),mergeId:uuidSchema.optional(),conflictCount:z105.number().int().nonnegative().optional(),conflicts:z105.array(sessionConflictSummarySchema).optional(),parentAdvanced:z105.boolean().optional(),code:z105.string().optional(),summary:z105.string().nullable().optional()}),buildRequest:__name(({projectId,sessionId,action,message})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/close`),body:withoutUndefined({action,message})}),"buildRequest"),projectOutput:projectSessionConflicts},"sessions.conflicts":{domain:"sessions",summary:"Inspect one cursor-paginated parked session merge and optionally hydrate one code conflict.",accessScope:"code",effect:"read",inputSchema:z105.object({projectId:uuidSchema,sessionId:uuidSchema,mergeId:uuidSchema.optional(),cursor:paginationShape.cursor,limit:z105.number().int().min(1).max(100).optional(),codePath:z105.string().min(1).max(1024).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({merge:z105.object({mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,status:z105.enum(["in_progress","complete","failed","rolled_back","conflicts"]),conflictCount:z105.number().int().nonnegative(),error:z105.string().nullable()}),conflicts:z105.array(conflictSchema2).max(100),nextCursor:z105.string().nullable(),codeDetail:codeConflictDetailSchema.nullable().optional()}),buildRequest:__name(({projectId,sessionId,mergeId,cursor,limit,codePath})=>({method:"GET",path:addQuery(managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/conflicts`),{mergeId,cursor,limit,codePath})}),"buildRequest"),projectOutput:projectSessionConflicts},"sessions.resolve":{domain:"sessions",summary:"Resolve a parked session merge and start its successor merge.",accessScope:"code",effect:"mutation",inputSchema:z105.object({projectId:uuidSchema,sessionId:uuidSchema,mergeId:uuidSchema,resolutions:z105.array(conflictResolutionSchema2).min(1).max(500)}).strict(),outputSchema:sessionEnvelopeSchema.extend({outcome:z105.literal("resolving"),mergeId:uuidSchema,supersededMergeId:uuidSchema,strategy:resolvedMergeStrategySchema,acceptedAt:z105.iso.datetime()}),buildRequest:__name(({projectId,sessionId,mergeId,resolutions})=>({method:"POST",path:managementProjectPath(projectId,`/sessions/${encodeURIComponent(sessionId)}/resolve`),body:{mergeId,resolutions:backendConflictResolutions(resolutions)}}),"buildRequest")}}}});import{z as z106}from"zod";var singlesOperations,init_singles=__esm({"../../packages/sdk/dist/operations/singles.js"(){"use strict";init_common2();init_entries();singlesOperations={"singles.get":{domain:"singles",summary:"Read the document-scoped value of a Single content type.",accessScope:"read",effect:"read",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,locale:localeSchema.optional(),populate:populateSchema}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,locale,populate})=>({method:"GET",path:addQuery(tenantPath(projectId,branch,`/documents/${encodeURIComponent(typeName)}`),{locale,populate})}),"buildRequest")},"singles.update":{domain:"singles",summary:"Update the document-scoped value of a Single content type.",accessScope:"write",effect:"mutation",inputSchema:z106.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,data:entryDataSchema,locale:localeSchema.optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId,branch,typeName,data,locale})=>({method:"PUT",path:addQuery(tenantPath(projectId,branch,`/documents/${encodeURIComponent(typeName)}`),{locale}),body:{data}}),"buildRequest")}}}});import{z as z107}from"zod";var supportReportInputSchema,supportReportResultSchema,supportOperations,init_support=__esm({"../../packages/sdk/dist/operations/support.js"(){"use strict";init_common2();supportReportInputSchema=z107.object({message:z107.string().trim().min(1).max(2e4),projectId:uuidSchema.optional(),branch:branchNameSchema.optional()}).strict().superRefine((input,context)=>{input.branch!==void 0&&input.projectId===void 0&&context.addIssue({code:"custom",message:"Pass projectId when providing branch.",path:["projectId"]})}),supportReportResultSchema=z107.object({id:uuidSchema,deliveryStatus:z107.enum(["pending","delivered","failed"]),message:z107.string()}),supportOperations={"support.report":{domain:"support",summary:"Submit an approved report to Fimo support immediately. Call only when the user explicitly asks to contact support or approves the exact report.",accessScope:"write",effect:"mutation",inputSchema:supportReportInputSchema,outputSchema:z107.object({data:supportReportResultSchema}),buildRequest:__name(({message,projectId,branch})=>({method:"POST",path:"/support/issues/agent",body:withoutUndefined({message,projectId,branch})}),"buildRequest")}}}});import{z as z108}from"zod";var jsonObjectSchema,deliveryStatusSchema,webhookSchema,deliverySchema,attemptSchema,deliveriesPageSchema,eventSchema,webhookWriteSchema,webhooksOperations,init_webhooks=__esm({"../../packages/sdk/dist/operations/webhooks.js"(){"use strict";init_common2();jsonObjectSchema=z108.record(z108.string(),z108.unknown()),deliveryStatusSchema=z108.enum(["pending","delivering","retrying","succeeded","failed"]),webhookSchema=z108.object({id:uuidSchema,projectId:uuidSchema,name:z108.string(),eventType:z108.string().min(1),enabled:z108.boolean(),destination:z108.object({host:z108.string(),maskedUrl:z108.string(),kind:z108.string()}),filter:jsonObjectSchema,headers:z108.array(jsonObjectSchema),bodyTemplate:z108.unknown().nullable(),signingEnabled:z108.boolean(),lastDeliveryStatus:deliveryStatusSchema.nullable()}).passthrough(),deliverySchema=z108.object({id:uuidSchema,webhookId:uuidSchema,projectId:uuidSchema,eventType:z108.string().min(1),status:deliveryStatusSchema,attemptCount:z108.number().int().nonnegative(),responseStatus:z108.number().int().nullable(),createdAt:z108.iso.datetime()}).passthrough(),attemptSchema=z108.object({id:uuidSchema,deliveryId:uuidSchema,attempt:z108.number().int().positive(),status:z108.enum(["delivering","succeeded","failed"]),createdAt:z108.iso.datetime()}).passthrough(),deliveriesPageSchema=z108.object({items:z108.array(deliverySchema),pagination:z108.object({page:z108.number().int().positive(),limit:z108.number().int().positive(),total:z108.number().int().nonnegative(),totalPages:z108.number().int().positive(),hasMore:z108.boolean()}),stats:z108.object({total:z108.number().int().nonnegative(),succeeded:z108.number().int().nonnegative(),failed:z108.number().int().nonnegative()})}),eventSchema=z108.object({type:z108.string().min(1),family:z108.string(),description:z108.string(),variables:z108.array(z108.string()),data:z108.unknown().optional()}).passthrough(),webhookWriteSchema=jsonObjectSchema,webhooksOperations={"webhooks.events":{domain:"webhooks",summary:"List the webhook event catalog available to one site.",accessScope:"read",effect:"read",inputSchema:z108.object({projectId:uuidSchema}).strict(),outputSchema:z108.array(eventSchema),buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/webhooks/events")}),"buildRequest"),projectOutput:__name(body=>z108.array(eventSchema).parse(responseData(body)),"projectOutput")},"webhooks.list":{domain:"webhooks",summary:"List outbound webhooks configured for one site.",accessScope:"read",effect:"read",inputSchema:z108.object({projectId:uuidSchema}).strict(),outputSchema:z108.array(webhookSchema),buildRequest:__name(({projectId})=>({method:"GET",path:managementProjectPath(projectId,"/webhooks")}),"buildRequest"),projectOutput:__name(body=>z108.array(webhookSchema).parse(responseData(body)),"projectOutput")},"webhooks.get":{domain:"webhooks",summary:"Read one outbound site webhook.",accessScope:"read",effect:"read",inputSchema:z108.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:webhookSchema,buildRequest:__name(({projectId,webhookId})=>({method:"GET",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}`)}),"buildRequest"),projectOutput:__name(body=>webhookSchema.parse(responseData(body)),"projectOutput")},"webhooks.create":{domain:"webhooks",summary:"Create an outbound site webhook.",accessScope:"write",effect:"mutation",inputSchema:z108.object({projectId:uuidSchema,webhook:webhookWriteSchema}).strict(),outputSchema:z108.object({webhook:webhookSchema,signingSecret:z108.string().min(1)}),buildRequest:__name(({projectId,webhook})=>({method:"POST",path:managementProjectPath(projectId,"/webhooks"),body:webhook}),"buildRequest"),projectOutput:__name(body=>z108.object({webhook:webhookSchema,signingSecret:z108.string().min(1)}).parse(responseData(body)),"projectOutput")},"webhooks.update":{domain:"webhooks",summary:"Update one outbound site webhook.",accessScope:"write",effect:"mutation",inputSchema:z108.object({projectId:uuidSchema,webhookId:uuidSchema,webhook:webhookWriteSchema}).strict(),outputSchema:webhookSchema,buildRequest:__name(({projectId,webhookId,webhook})=>({method:"PATCH",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}`),body:webhook}),"buildRequest"),projectOutput:__name(body=>webhookSchema.parse(responseData(body)),"projectOutput")},"webhooks.delete":{domain:"webhooks",summary:"Delete one outbound site webhook.",accessScope:"write",effect:"mutation",inputSchema:z108.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:z108.unknown(),buildRequest:__name(({projectId,webhookId})=>({method:"DELETE",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}`)}),"buildRequest")},"webhooks.rotateSecret":{domain:"webhooks",summary:"Rotate and reveal the signing secret for one site webhook.",accessScope:"write",effect:"mutation",inputSchema:z108.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:z108.string().min(1),buildRequest:__name(({projectId,webhookId})=>({method:"POST",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/rotate-signing-secret`)}),"buildRequest"),projectOutput:__name(body=>z108.object({signingSecret:z108.string().min(1)}).parse(responseData(body)).signingSecret,"projectOutput")},"webhooks.test":{domain:"webhooks",summary:"Queue a test delivery for one site webhook.",accessScope:"write",effect:"mutation",inputSchema:z108.object({projectId:uuidSchema,webhookId:uuidSchema,data:jsonObjectSchema.optional()}).strict(),outputSchema:deliverySchema,buildRequest:__name(({projectId,webhookId,data})=>({method:"POST",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/test`),body:data===void 0?{}:{data}}),"buildRequest"),projectOutput:__name(body=>deliverySchema.parse(responseData(body)),"projectOutput")},"webhooks.listDeliveries":{domain:"webhooks",summary:"List webhook delivery history with cursor pagination; legacy page input remains supported.",accessScope:"read",effect:"read",inputSchema:z108.object({projectId:uuidSchema,webhookId:uuidSchema,...numberedPaginationShape,limit:z108.number().int().min(1).max(100).optional()}).strict().superRefine(numberedPaginationRefinement),outputSchema:deliveriesPageSchema.extend({nextCursor:z108.string().nullable()}),buildRequest:__name(({projectId,webhookId,page,cursor,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/deliveries`),{page:paginationPage({page,cursor}),limit})}),"buildRequest"),projectOutput:__name(body=>{let result=deliveriesPageSchema.parse(responseData(body));return{...result,nextCursor:result.pagination.hasMore?String(result.pagination.page+1):null}},"projectOutput")},"webhooks.getDelivery":{domain:"webhooks",summary:"Read one webhook delivery and all of its attempts.",accessScope:"read",effect:"read",inputSchema:z108.object({projectId:uuidSchema,webhookId:uuidSchema,deliveryId:uuidSchema}).strict(),outputSchema:z108.object({delivery:deliverySchema,attempts:z108.array(attemptSchema)}),buildRequest:__name(({projectId,webhookId,deliveryId})=>({method:"GET",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/deliveries/${encodeURIComponent(deliveryId)}`)}),"buildRequest"),projectOutput:__name(body=>z108.object({delivery:deliverySchema,attempts:z108.array(attemptSchema)}).parse(responseData(body)),"projectOutput")},"webhooks.retryDelivery":{domain:"webhooks",summary:"Retry one failed webhook delivery.",accessScope:"write",effect:"mutation",inputSchema:z108.object({projectId:uuidSchema,webhookId:uuidSchema,deliveryId:uuidSchema}).strict(),outputSchema:deliverySchema,buildRequest:__name(({projectId,webhookId,deliveryId})=>({method:"POST",path:managementProjectPath(projectId,`/webhooks/${encodeURIComponent(webhookId)}/deliveries/${encodeURIComponent(deliveryId)}/retry`)}),"buildRequest"),projectOutput:__name(body=>deliverySchema.parse(responseData(body)),"projectOutput")}}}});import{z as z109}from"zod";var fimoOperations,fimoOperationManifestEntrySchema,fimoOperationManifestSchema,fimoOperationManifest,init_operations=__esm({"../../packages/sdk/dist/operations.js"(){"use strict";init_analytics();init_assets();init_billing();init_branches();init_domains();init_entries();init_environments();init_files();init_forms();init_generation();init_history();init_hosting();init_knowledge();init_labels();init_locales();init_organizations();init_projects();init_schedules();init_schemas();init_secrets();init_sessions();init_singles();init_support();init_webhooks();fimoOperations={...projectsOperations,...organizationsOperations,...domainsOperations,...generationOperations,...historyOperations,...environmentsOperations,...secretsOperations,...schedulesOperations,...webhooksOperations,...branchesOperations,...schemasOperations,...supportOperations,...sessionsOperations,...entriesOperations,...singlesOperations,...knowledgeOperations,...labelsOperations,...localesOperations,...assetsOperations,...formsOperations,...hostingOperations,...analyticsOperations,...filesOperations,...billingOperations},fimoOperationManifestEntrySchema=z109.object({id:z109.string().regex(/^[a-zA-Z_$][\w$]*\.[a-zA-Z_$][\w$]*$/),domain:z109.string().min(1),summary:z109.string().min(1),accessScope:z109.enum(["read","write","code","agents"]),effect:z109.enum(["read","mutation"]),inputJsonSchema:z109.record(z109.string(),z109.unknown()),outputJsonSchema:z109.record(z109.string(),z109.unknown())}).strict(),fimoOperationManifestSchema=z109.array(fimoOperationManifestEntrySchema),fimoOperationManifest=Object.entries(fimoOperations).map(([id,operation])=>({id,domain:operation.domain,summary:operation.summary,accessScope:operation.accessScope,effect:operation.effect,inputJsonSchema:z109.toJSONSchema(operation.inputSchema,{target:"draft-7",io:"input"}),outputJsonSchema:z109.toJSONSchema(operation.outputSchema,{target:"draft-7"})}))}});function createFimoClient(input){return{async execute(operationId,operationInput){let operation=fimoOperations[operationId],parsedInput=operation.inputSchema.parse(operationInput),response=await input.transport.execute(operation.buildRequest(parsedInput)),output=operation.projectOutput?operation.projectOutput(response,parsedInput):response;return operation.outputSchema.parse(output)}}}var init_client=__esm({"../../packages/sdk/dist/client.js"(){"use strict";init_operations();__name(createFimoClient,"createFimoClient")}});var init_dist2=__esm({"../../packages/sdk/dist/index.js"(){"use strict";init_client()}});import{spawnSync}from"node:child_process";import fs4 from"node:fs";import path4 from"node:path";import{setTimeout as sleep}from"node:timers/promises";function isPublishedInstall(cliRoot=CLI_ROOT){return fs4.existsSync(path4.join(cliRoot,"release.json"))}function buildSkipsVersionCheck(cliRoot=CLI_ROOT,readFile6=defaultReadFile){try{return JSON.parse(readFile6(path4.join(cliRoot,"release.json"))).skipVersionCheck===!0}catch{return!1}}function defaultReadFile(file){return fs4.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:path4.resolve(result.stdout.trim(),"fimo")}function normalizedPath(input){try{return fs4.realpathSync(input)}catch{return path4.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{fs4.mkdirSync(lockDir);return}catch(error){if(error.code!=="EEXIST")throw error}let stale=!1;try{stale=Date.now()-fs4.statSync(lockDir).mtimeMs>LOCK_STALE_MS}catch{continue}if(stale){try{fs4.rmdirSync(lockDir)}catch{}continue}if(Date.now()>=deadline)throw new Error("auto-upgrade lock timeout");await sleep(LOCK_POLL_MS)}}function readGlobalFimoVersion(){let root=resolveGlobalFimoRoot();if(!root)return null;try{let pkg=JSON.parse(fs4.readFileSync(path4.join(root,"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=path4.join(loadConfig().configDir,"auto-upgrade.lock");try{fs4.mkdirSync(path4.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{fs4.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 fs5 from"node:fs";import path5 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";function getCliVersion(){try{let raw=fs5.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=path5.resolve(path5.dirname(THIS_FILE2),"..",".."),PACKAGE_JSON_PATH=path5.join(CLI_ROOT2,"package.json");__name(getCliVersion,"getCliVersion")}});function branchNameOf(row2){return row2.branch??row2.env}function parentBranchOf(row2){return row2.parentBranch??row2.parentEnv}function projectUnclaimedError(cfg,body){let{feature,message}=body&&typeof body=="object"?body:{};return new ProjectUnclaimedError(cfg.apiUrl,typeof feature=="string"?feature:null,findProjectToken(cfg)?.file.claimUrl??null,typeof message=="string"&&message?message:void 0)}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,container=error&&typeof error=="object"?error:parsed,issues="issues"in container?container.issues:void 0;return!Array.isArray(issues)||issues.length===0?null:issues.map(issue=>{let{path:path49,message}=issue;return`${Array.isArray(path49)&&path49.length>0?`${path49.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}function formatError(status,text,body){if(!text)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 text}async function parseError(response){let text=await response.text(),body;try{body=text?JSON.parse(text):void 0}catch{return{detail:formatError(response.status,text)}}let code2=body&&typeof body=="object"&&!Array.isArray(body)&&typeof body.code=="string"?body.code:void 0;return{detail:formatError(response.status,text,body),code:code2,body}}function throwUnauthorized(cfg,status){if(resolveAuth(cfg)?.kind==="project")throw new ProjectTokenRejectedError(cfg.apiUrl,status);try{recordAuthFailure(cfg)}catch{}throw new UnauthorizedError(cfg.apiUrl,status)}async function throwPermissionDenied(cfg,response){let required=[],server={},body;try{body=await response.json(),required=Array.isArray(body.required)?body.required:body.required?[body.required]:[],typeof body.code=="string"&&body.code&&(server.code=body.code),typeof body.message=="string"&&body.message&&(server.detail=body.message)}catch{}throw server.code==="project_unclaimed"?projectUnclaimedError(cfg,body):new PermissionDeniedError(cfg.apiUrl,required,void 0,server)}function createCliHttpTransport(cfg=loadConfig(),branch){let authHeaders=__name((init,defaultJsonContentType)=>{let headers=new Headers(init.headers),token=requireToken(cfg);return headers.set("Authorization",`Bearer ${token}`),defaultJsonContentType&&init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),branch&&!headers.has(FIMO_BRANCH_HEADER)&&headers.set(FIMO_BRANCH_HEADER,branch),headers},"authHeaders"),send=__name(async(path49,init={},defaultJsonContentType=!0)=>fimoFetch(`${cfg.apiUrl}${path49}`,{...init,headers:authHeaders(init,defaultJsonContentType)}),"send");return{async request(path49,init={},options={}){let response=await send(path49,init);if(response.status===401&&throwUnauthorized(cfg,response.status),response.status===403&&!options.preserveForbidden&&await throwPermissionDenied(cfg,response),!response.ok){let error=await parseError(response);throw error.code==="project_unclaimed"?projectUnclaimedError(cfg,error.body):new ApiRequestError(init.method??"GET",path49,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()},async response(path49,init={}){let response=await send(path49,init,!1);if(response.status===401&&throwUnauthorized(cfg,response.status),response.status===403&&await throwPermissionDenied(cfg,response),!response.ok){let error=await parseError(response);throw new ApiRequestError(init.method??"GET",path49,response.status,error.detail,error.code,error.body)}return response}}}function createCliFimoClient(cfg=loadConfig(),branch){let transport=createCliHttpTransport(cfg,branch);return createFimoClient({transport:{execute:__name(request=>transport.request(`/api${request.path}`,{method:request.method,headers:!branch&&request.context?.branch!==void 0?{[FIMO_BRANCH_HEADER]:request.context.branch}:void 0,body:request.body===void 0?void 0:JSON.stringify(request.body)},{preserveForbidden:request.preserveForbidden}),"execute")}})}function requiredPermissions(body){let required=typeof body=="object"&&body!==null?body.required:void 0;return Array.isArray(required)?required.filter(value=>typeof value=="string"):typeof required=="string"?[required]:[]}var ApiRequestError,UnauthorizedError,ProjectTokenRejectedError,PermissionDeniedError,ProjectUnclaimedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_BRANCH_HEADER,init_sdk_transport=__esm({"src/cli/sdk-transport.ts"(){init_esm();init_dist();init_dist2();init_auth();init_auto_upgrade();init_config();init_version();__name(branchNameOf,"branchNameOf");__name(parentBranchOf,"parentBranchOf");ApiRequestError=class extends Error{static{__name(this,"ApiRequestError")}status;method;path;detail;code;body;constructor(method,path49,status,detail,code2,body){super(`API ${method} ${path49} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path49,this.status=status,this.detail=detail,this.code=code2,this.body=body}},UnauthorizedError=class extends Error{static{__name(this,"UnauthorizedError")}apiUrl;status;constructor(apiUrl,status,message){super(message??`Session for ${apiUrl} expired or invalid (HTTP ${status}).`),this.name="UnauthorizedError",this.apiUrl=apiUrl,this.status=status}},ProjectTokenRejectedError=class extends UnauthorizedError{static{__name(this,"ProjectTokenRejectedError")}constructor(apiUrl,status){super(apiUrl,status,"The project token in this directory no longer works."),this.name="ProjectTokenRejectedError"}},PermissionDeniedError=class extends Error{static{__name(this,"PermissionDeniedError")}apiUrl;required;code;detail;constructor(apiUrl,required=[],message,server={}){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,this.code=server.code,this.detail=server.detail}},ProjectUnclaimedError=class extends PermissionDeniedError{static{__name(this,"ProjectUnclaimedError")}feature;claimUrl;constructor(apiUrl,feature,claimUrl,detail){let label=feature?UNCLAIMED_PLAN.locked[feature]:void 0,message=label?`${label} unlocks once a person claims this site.`:detail??"This action unlocks once a person claims this site.";super(apiUrl,[],message,{code:"project_unclaimed",detail}),this.name="ProjectUnclaimedError",this.feature=feature,this.claimUrl=claimUrl}};__name(projectUnclaimedError,"projectUnclaimedError");CLI_VERSION_HEADER="X-Fimo-CLI-Version",CLI_LATEST_HEADER="X-Fimo-CLI-Latest",CLI_AUTO_UPGRADE_HEADER="X-Fimo-CLI-Auto-Upgrade",FIMO_BRANCH_HEADER="X-Fimo-Branch";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");__name(formatError,"formatError");__name(parseError,"parseError");__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");__name(createCliHttpTransport,"createCliHttpTransport");__name(createCliFimoClient,"createCliFimoClient");__name(requiredPermissions,"requiredPermissions")}});import{execFile}from"node:child_process";import{promisify}from"node:util";async function runGit(args,cwd){let{stdout}=await execFileAsync("git",args,{cwd});return stdout.trim()}async function isGitRepo(cwd){try{return await runGit(["rev-parse","--is-inside-work-tree"],cwd),!0}catch{return!1}}async function hasUncommittedChanges(cwd){return(await runGit(["status","--porcelain"],cwd)).length>0}async function cloneRepo(args){await execFileAsync("git",["clone","--branch",args.branch,"--single-branch",args.url,args.targetDir])}function isMissingRemoteBranch(error){let stderr=extractStderr(error).toLowerCase();return stderr.includes("remote branch")&&stderr.includes("not found")}async function remoteHasBranch(remoteUrl,branch){let{stdout}=await execFileAsync("git",["ls-remote","--heads",remoteUrl,branch]);return stdout.trim().length>0}async function currentBranch2(cwd){return runGit(["symbolic-ref","--short","-q","HEAD"],cwd)}async function commitSubjectOrNull(cwd,sha){try{return await runGit(["log","-1","--format=%s",sha,"--"],cwd)}catch{return null}}async function currentTagOrNull(cwd){try{return await runGit(["describe","--tags","--exact-match","HEAD"],cwd)||null}catch{return null}}function isReleaseTag(tag){return tag?/^release\/.+/.test(tag):!1}function classifyPushError(error){let stderr=extractStderr(error),lower=stderr.toLowerCase();return lower.includes("invalid or expired token")||lower.includes("expired token")||lower.includes("invalid token")||lower.includes("could not obtain git credentials")||lower.includes("not signed in")?{kind:"auth",stderr}:lower.includes("remote rejected")||lower.includes("protected")||lower.includes("no-push")||lower.includes("push declined")||lower.includes("not allowed to push")||lower.includes("permission to push")||lower.includes("forbidden")||lower.includes("403")?{kind:"protected",stderr}:lower.includes("non-fast-forward")||lower.includes("rejected")||lower.includes("fetch first")||lower.includes("updates were rejected")?{kind:"non-fast-forward",stderr}:lower.includes("authentication")||lower.includes("permission denied")?{kind:"auth",stderr}:lower.includes("could not resolve host")||lower.includes("timed out")||lower.includes("connection")?{kind:"network",stderr}:{kind:"unknown",stderr}}function gitErrorSummary(error){let lines=extractStderr(error).split(`
|
|
45
45
|
`).map(line=>line.trim()).filter(line=>line.length>0);return(lines.find(line=>line.startsWith("fatal:")||line.startsWith("error:"))??lines[0]??"git failed").replace(/\/\/[^/\s@]*@/g,"//")}function extractStderr(error){if(error&&typeof error=="object"&&"stderr"in error){let value=error.stderr;if(typeof value=="string")return value;if(Buffer.isBuffer(value))return value.toString("utf8")}return error instanceof Error?error.message:String(error)}var execFileAsync,init_git=__esm({"src/cli/utils/git.ts"(){execFileAsync=promisify(execFile);__name(runGit,"runGit");__name(isGitRepo,"isGitRepo");__name(hasUncommittedChanges,"hasUncommittedChanges");__name(cloneRepo,"cloneRepo");__name(isMissingRemoteBranch,"isMissingRemoteBranch");__name(remoteHasBranch,"remoteHasBranch");__name(currentBranch2,"currentBranch");__name(commitSubjectOrNull,"commitSubjectOrNull");__name(currentTagOrNull,"currentTagOrNull");__name(isReleaseTag,"isReleaseTag");__name(classifyPushError,"classifyPushError");__name(gitErrorSummary,"gitErrorSummary");__name(extractStderr,"extractStderr")}});import fs6 from"node:fs";import path6 from"node:path";function existingLayoutPaths(cwd){return[CURRENT_PROJECT_LAYOUT.project,CURRENT_PROJECT_LAYOUT.config,LEGACY_PROJECT_LAYOUT.project,LEGACY_PROJECT_LAYOUT.config,LEGACY_AGENT_POLICY_PATH].filter(file=>fs6.existsSync(path6.join(cwd,file)))}function detectProjectLayoutAtRoot(cwd){return detectProjectLayout(existingLayoutPaths(cwd))}function resolveProjectLayoutPaths(cwd,fallback="current"){return getProjectLayoutPaths(detectProjectLayoutAtRoot(cwd)??fallback)}function resolveProjectSettingsPath(cwd){return path6.join(cwd,resolveProjectLayoutPaths(cwd).project)}function resolveProjectConfigPath(cwd){let files=existingLayoutPaths(cwd);return path6.join(cwd,selectProjectConfigPath(files,detectProjectLayout(files)))}function loadProjectSettings(cwd){let settingsPath=resolveProjectSettingsPath(cwd);if(!fs6.existsSync(settingsPath))throw new Error("You are not in a Fimo project. Run `fimo create` to start one, or cd into a linked project.");return JSON.parse(fs6.readFileSync(settingsPath,"utf-8"))}function findProjectRoot2(start){let dir=path6.resolve(start);for(;;){if(fs6.existsSync(path6.join(dir,CURRENT_PROJECT_LAYOUT.project))||fs6.existsSync(path6.join(dir,LEGACY_PROJECT_LAYOUT.project)))return dir;let parent=path6.dirname(dir);if(parent===dir)return null;dir=parent}}function resolveProjectCwd(cwdOption){let start=path6.resolve(cwdOption??process.cwd());return findProjectRoot2(start)??start}var init_project=__esm({"src/cli/utils/project.ts"(){init_project_layout();__name(existingLayoutPaths,"existingLayoutPaths");__name(detectProjectLayoutAtRoot,"detectProjectLayoutAtRoot");__name(resolveProjectLayoutPaths,"resolveProjectLayoutPaths");__name(resolveProjectSettingsPath,"resolveProjectSettingsPath");__name(resolveProjectConfigPath,"resolveProjectConfigPath");__name(loadProjectSettings,"loadProjectSettings");__name(findProjectRoot2,"findProjectRoot");__name(resolveProjectCwd,"resolveProjectCwd")}});function projectSettingsFromEnv(){let projectId=process.env.FIMO_PROJECT_ID?.trim();return projectId?{projectId,organizationId:process.env.FIMO_ORGANIZATION_ID?.trim()??"",name:process.env.FIMO_PROJECT_NAME?.trim()??projectId,apiUrl:process.env.FIMO_API_URL?.trim()??loadConfig().apiUrl}:null}async function resolveBranchFromGit(cwd){if(!await isGitRepo(cwd))return null;try{let tag=await currentTagOrNull(cwd);if(isReleaseTag(tag))return{branch:"prod",source:"tag",readOnly:!0};let branch=await currentBranch2(cwd);return!branch||!isValidBranch(branch)?null:{branch,source:"branch"}}catch{return null}}function resolveBranchFromEnvironment(cwd){let branch=process.env.FIMO_ENV?.trim()||readLocalEnvFiles(cwd).FIMO_ENV?.trim();return branch&&isValidBranch(branch)?branch:null}async function getProjectContext(opts={}){let cwd=resolveProjectCwd(opts.cwd),settings;try{settings=loadProjectSettings(cwd)}catch{let fromEnv=projectSettingsFromEnv();if(!fromEnv)throw new NotInProjectError;settings=fromEnv}let branch,source,readOnly=!1;if(opts.branchOverride!==void 0){if(!isValidBranch(opts.branchOverride))throw new InvalidBranchOverrideError(opts.branchOverride);branch=opts.branchOverride,source="flag"}else if(opts.defaultBranch!==void 0)branch=opts.defaultBranch,source="default";else{let fromGit=await resolveBranchFromGit(cwd);if(fromGit)branch=fromGit.branch,source=fromGit.source,readOnly=fromGit.readOnly===!0;else{let fromEnvironment=resolveBranchFromEnvironment(cwd);if(!fromEnvironment)throw new GitBranchUndetectedError;branch=fromEnvironment,source="environment"}}if(opts.fimo&&branch!=="prod")try{let{data:branches}=await opts.fimo.execute("branches.list",{projectId:settings.projectId,includeAgentBranches:!0}),names=branches.map(candidate=>candidate.branch);if(!names.includes(branch)&&source==="flag")throw new BranchNotFoundError(branch,names)}catch(err){if(err instanceof BranchNotFoundError)throw err}return{projectId:settings.projectId,organizationId:settings.organizationId,name:settings.name,apiUrl:settings.apiUrl,branch,source,readOnly:readOnly||void 0}}function branchSourceBanner(ctx){let sourceHint=ctx.source==="flag"?"--branch":ctx.source==="branch"?"git branch":ctx.source==="tag"?"git tag":ctx.source==="default"?"command default":"FIMO_ENV",ro=ctx.readOnly?" \xB7 read-only":"";return`\u2192 Branch: ${ctx.branch} (from ${sourceHint}${ro})`}function branchOverrideFromCommand(cmd){let cur=cmd??void 0;for(;cur;){let branch=cur.opts().branch;if(typeof branch=="string"&&branch.length>0)return branch;cur=cur.parent??null}}async function bootstrapProjectCommand(options={},cmd,bootstrapOpts={}){let branchOverride2=branchOverrideFromCommand(cmd),cfg=loadConfig(),baseFimo=createCliFimoClient(cfg),ctx=await getProjectContext({cwd:options.cwd,branchOverride:branchOverride2,defaultBranch:bootstrapOpts.defaultBranch,fimo:baseFimo});if(!bootstrapOpts.quiet){let{currentMode:currentMode2}=await Promise.resolve().then(()=>(init_dist(),dist_exports));currentMode2().format==="pretty"&&process.stderr.write(`${branchSourceBanner(ctx)}
|
|
46
46
|
`)}if(bootstrapOpts.refuseReadOnly&&ctx.readOnly)throw new Error(`Refusing to run a mutating command against read-only Branch '${ctx.branch}'. Switch off the release/* tag or pass --branch <writable-branch>.`);return{ctx,fimo:createCliFimoClient(cfg,ctx.branch)}}var NotInProjectError,InvalidBranchOverrideError,BranchNotFoundError,GitBranchUndetectedError,init_project_context=__esm({"src/cli/utils/project-context.ts"(){init_esm();init_local_runtime_env();init_config();init_sdk_transport();init_git();init_project();NotInProjectError=class extends Error{static{__name(this,"NotInProjectError")}constructor(){super("You are not in a Fimo project. Run `fimo create` to start one, or cd into a linked project."),this.name="NotInProjectError"}};__name(projectSettingsFromEnv,"projectSettingsFromEnv");InvalidBranchOverrideError=class extends Error{static{__name(this,"InvalidBranchOverrideError")}value;constructor(value){super(`--branch value '${value}' is invalid. Branch names must match /^[a-zA-Z0-9._/-]+$/, not start with '-', and be \u2264255 chars.`),this.name="InvalidBranchOverrideError",this.value=value}},BranchNotFoundError=class extends Error{static{__name(this,"BranchNotFoundError")}branch;knownBranches;constructor(branch,knownBranches){super(`Branch '${branch}' not found on the server. Known Branches: ${knownBranches.length>0?knownBranches.join(", "):"(none yet)"}.`),this.name="BranchNotFoundError",this.branch=branch,this.knownBranches=knownBranches}},GitBranchUndetectedError=class extends Error{static{__name(this,"GitBranchUndetectedError")}constructor(){super("Fimo could not detect a current Git Branch. Check out a Branch or pass --branch <name>."),this.name="GitBranchUndetectedError"}};__name(resolveBranchFromGit,"resolveBranchFromGit");__name(resolveBranchFromEnvironment,"resolveBranchFromEnvironment");__name(getProjectContext,"getProjectContext");__name(branchSourceBanner,"branchSourceBanner");__name(branchOverrideFromCommand,"branchOverrideFromCommand");__name(bootstrapProjectCommand,"bootstrapProjectCommand")}});var require_identity=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/identity.js"(exports2){"use strict";var ALIAS=Symbol.for("yaml.alias"),DOC=Symbol.for("yaml.document"),MAP=Symbol.for("yaml.map"),PAIR=Symbol.for("yaml.pair"),SCALAR=Symbol.for("yaml.scalar"),SEQ=Symbol.for("yaml.seq"),NODE_TYPE=Symbol.for("yaml.node.type"),isAlias=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===ALIAS,"isAlias"),isDocument=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===DOC,"isDocument"),isMap=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===MAP,"isMap"),isPair=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===PAIR,"isPair"),isScalar=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===SCALAR,"isScalar"),isSeq=__name(node=>!!node&&typeof node=="object"&&node[NODE_TYPE]===SEQ,"isSeq");function isCollection(node){if(node&&typeof node=="object")switch(node[NODE_TYPE]){case MAP:case SEQ:return!0}return!1}__name(isCollection,"isCollection");function isNode(node){if(node&&typeof node=="object")switch(node[NODE_TYPE]){case ALIAS:case MAP:case SCALAR:case SEQ:return!0}return!1}__name(isNode,"isNode");var hasAnchor=__name(node=>(isScalar(node)||isCollection(node))&&!!node.anchor,"hasAnchor");exports2.ALIAS=ALIAS;exports2.DOC=DOC;exports2.MAP=MAP;exports2.NODE_TYPE=NODE_TYPE;exports2.PAIR=PAIR;exports2.SCALAR=SCALAR;exports2.SEQ=SEQ;exports2.hasAnchor=hasAnchor;exports2.isAlias=isAlias;exports2.isCollection=isCollection;exports2.isDocument=isDocument;exports2.isMap=isMap;exports2.isNode=isNode;exports2.isPair=isPair;exports2.isScalar=isScalar;exports2.isSeq=isSeq}});var require_visit=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/visit.js"(exports2){"use strict";var identity2=require_identity(),BREAK=Symbol("break visit"),SKIP=Symbol("skip children"),REMOVE=Symbol("remove node");function visit2(node,visitor){let visitor_=initVisitor(visitor);identity2.isDocument(node)?visit_(null,node.contents,visitor_,Object.freeze([node]))===REMOVE&&(node.contents=null):visit_(null,node,visitor_,Object.freeze([]))}__name(visit2,"visit");visit2.BREAK=BREAK;visit2.SKIP=SKIP;visit2.REMOVE=REMOVE;function visit_(key,node,visitor,path49){let ctrl=callVisitor(key,node,visitor,path49);if(identity2.isNode(ctrl)||identity2.isPair(ctrl))return replaceNode(key,path49,ctrl),visit_(key,ctrl,visitor,path49);if(typeof ctrl!="symbol"){if(identity2.isCollection(node)){path49=Object.freeze(path49.concat(node));for(let i=0;i<node.items.length;++i){let ci=visit_(i,node.items[i],visitor,path49);if(typeof ci=="number")i=ci-1;else{if(ci===BREAK)return BREAK;ci===REMOVE&&(node.items.splice(i,1),i-=1)}}}else if(identity2.isPair(node)){path49=Object.freeze(path49.concat(node));let ck=visit_("key",node.key,visitor,path49);if(ck===BREAK)return BREAK;ck===REMOVE&&(node.key=null);let cv=visit_("value",node.value,visitor,path49);if(cv===BREAK)return BREAK;cv===REMOVE&&(node.value=null)}}return ctrl}__name(visit_,"visit_");async function visitAsync(node,visitor){let visitor_=initVisitor(visitor);identity2.isDocument(node)?await visitAsync_(null,node.contents,visitor_,Object.freeze([node]))===REMOVE&&(node.contents=null):await visitAsync_(null,node,visitor_,Object.freeze([]))}__name(visitAsync,"visitAsync");visitAsync.BREAK=BREAK;visitAsync.SKIP=SKIP;visitAsync.REMOVE=REMOVE;async function visitAsync_(key,node,visitor,path49){let ctrl=await callVisitor(key,node,visitor,path49);if(identity2.isNode(ctrl)||identity2.isPair(ctrl))return replaceNode(key,path49,ctrl),visitAsync_(key,ctrl,visitor,path49);if(typeof ctrl!="symbol"){if(identity2.isCollection(node)){path49=Object.freeze(path49.concat(node));for(let i=0;i<node.items.length;++i){let ci=await visitAsync_(i,node.items[i],visitor,path49);if(typeof ci=="number")i=ci-1;else{if(ci===BREAK)return BREAK;ci===REMOVE&&(node.items.splice(i,1),i-=1)}}}else if(identity2.isPair(node)){path49=Object.freeze(path49.concat(node));let ck=await visitAsync_("key",node.key,visitor,path49);if(ck===BREAK)return BREAK;ck===REMOVE&&(node.key=null);let cv=await visitAsync_("value",node.value,visitor,path49);if(cv===BREAK)return BREAK;cv===REMOVE&&(node.value=null)}}return ctrl}__name(visitAsync_,"visitAsync_");function initVisitor(visitor){return typeof visitor=="object"&&(visitor.Collection||visitor.Node||visitor.Value)?Object.assign({Alias:visitor.Node,Map:visitor.Node,Scalar:visitor.Node,Seq:visitor.Node},visitor.Value&&{Map:visitor.Value,Scalar:visitor.Value,Seq:visitor.Value},visitor.Collection&&{Map:visitor.Collection,Seq:visitor.Collection},visitor):visitor}__name(initVisitor,"initVisitor");function callVisitor(key,node,visitor,path49){if(typeof visitor=="function")return visitor(key,node,path49);if(identity2.isMap(node))return visitor.Map?.(key,node,path49);if(identity2.isSeq(node))return visitor.Seq?.(key,node,path49);if(identity2.isPair(node))return visitor.Pair?.(key,node,path49);if(identity2.isScalar(node))return visitor.Scalar?.(key,node,path49);if(identity2.isAlias(node))return visitor.Alias?.(key,node,path49)}__name(callVisitor,"callVisitor");function replaceNode(key,path49,node){let parent=path49[path49.length-1];if(identity2.isCollection(parent))parent.items[key]=node;else if(identity2.isPair(parent))key==="key"?parent.key=node:parent.value=node;else if(identity2.isDocument(parent))parent.contents=node;else{let pt2=identity2.isAlias(parent)?"alias":"scalar";throw new Error(`Cannot replace node with ${pt2} parent`)}}__name(replaceNode,"replaceNode");exports2.visit=visit2;exports2.visitAsync=visitAsync}});var require_directives=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/doc/directives.js"(exports2){"use strict";var identity2=require_identity(),visit2=require_visit(),escapeChars={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},escapeTagName=__name(tn=>tn.replace(/[!,[\]{}]/g,ch=>escapeChars[ch]),"escapeTagName"),Directives=class _Directives{static{__name(this,"Directives")}constructor(yaml,tags){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},_Directives.defaultYaml,yaml),this.tags=Object.assign({},_Directives.defaultTags,tags)}clone(){let copy=new _Directives(this.yaml,this.tags);return copy.docStart=this.docStart,copy}atDocument(){let res=new _Directives(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},_Directives.defaultTags);break}return res}add(line,onError){this.atNextDocument&&(this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},_Directives.defaultTags),this.atNextDocument=!1);let parts=line.trim().split(/[ \t]+/),name=parts.shift();switch(name){case"%TAG":{if(parts.length!==2&&(onError(0,"%TAG directive should contain exactly two parts"),parts.length<2))return!1;let[handle,prefix]=parts;return this.tags[handle]=prefix,!0}case"%YAML":{if(this.yaml.explicit=!0,parts.length!==1)return onError(0,"%YAML directive should contain exactly one part"),!1;let[version]=parts;if(version==="1.1"||version==="1.2")return this.yaml.version=version,!0;{let isValid=/^\d+\.\d+$/.test(version);return onError(6,`Unsupported YAML version ${version}`,isValid),!1}}default:return onError(0,`Unknown directive ${name}`,!0),!1}}tagName(source,onError){if(source==="!")return"!";if(source[0]!=="!")return onError(`Not a valid tag: ${source}`),null;if(source[1]==="<"){let verbatim=source.slice(2,-1);return verbatim==="!"||verbatim==="!!"?(onError(`Verbatim tags aren't resolved, so ${source} is invalid.`),null):(source[source.length-1]!==">"&&onError("Verbatim tags must end with a >"),verbatim)}let[,handle,suffix]=source.match(/^(.*!)([^!]*)$/s);suffix||onError(`The ${source} tag has no suffix`);let prefix=this.tags[handle];if(prefix)try{return prefix+decodeURIComponent(suffix)}catch(error){return onError(String(error)),null}return handle==="!"?source:(onError(`Could not resolve tag: ${source}`),null)}tagString(tag){for(let[handle,prefix]of Object.entries(this.tags))if(tag.startsWith(prefix))return handle+escapeTagName(tag.substring(prefix.length));return tag[0]==="!"?tag:`!<${tag}>`}toString(doc){let lines=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],tagEntries=Object.entries(this.tags),tagNames;if(doc&&tagEntries.length>0&&identity2.isNode(doc.contents)){let tags={};visit2.visit(doc.contents,(_key,node)=>{identity2.isNode(node)&&node.tag&&(tags[node.tag]=!0)}),tagNames=Object.keys(tags)}else tagNames=[];for(let[handle,prefix]of tagEntries)handle==="!!"&&prefix==="tag:yaml.org,2002:"||(!doc||tagNames.some(tn=>tn.startsWith(prefix)))&&lines.push(`%TAG ${handle} ${prefix}`);return lines.join(`
|
|
47
47
|
`)}};Directives.defaultYaml={explicit:!1,version:"1.2"};Directives.defaultTags={"!!":"tag:yaml.org,2002:"};exports2.Directives=Directives}});var require_anchors=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/doc/anchors.js"(exports2){"use strict";var identity2=require_identity(),visit2=require_visit();function anchorIsValid(anchor){if(/[\x00-\x19\s,[\]{}]/.test(anchor)){let msg=`Anchor must not contain whitespace or control characters: ${JSON.stringify(anchor)}`;throw new Error(msg)}return!0}__name(anchorIsValid,"anchorIsValid");function anchorNames(root){let anchors=new Set;return visit2.visit(root,{Value(_key,node){node.anchor&&anchors.add(node.anchor)}}),anchors}__name(anchorNames,"anchorNames");function findNewAnchor(prefix,exclude){for(let i=1;;++i){let name=`${prefix}${i}`;if(!exclude.has(name))return name}}__name(findNewAnchor,"findNewAnchor");function createNodeAnchors(doc,prefix){let aliasObjects=[],sourceObjects=new Map,prevAnchors=null;return{onAnchor:__name(source=>{aliasObjects.push(source),prevAnchors??(prevAnchors=anchorNames(doc));let anchor=findNewAnchor(prefix,prevAnchors);return prevAnchors.add(anchor),anchor},"onAnchor"),setAnchors:__name(()=>{for(let source of aliasObjects){let ref=sourceObjects.get(source);if(typeof ref=="object"&&ref.anchor&&(identity2.isScalar(ref.node)||identity2.isCollection(ref.node)))ref.node.anchor=ref.anchor;else{let error=new Error("Failed to resolve repeated object (this should not happen)");throw error.source=source,error}}},"setAnchors"),sourceObjects}}__name(createNodeAnchors,"createNodeAnchors");exports2.anchorIsValid=anchorIsValid;exports2.anchorNames=anchorNames;exports2.createNodeAnchors=createNodeAnchors;exports2.findNewAnchor=findNewAnchor}});var require_applyReviver=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/doc/applyReviver.js"(exports2){"use strict";function applyReviver(reviver,obj,key,val){if(val&&typeof val=="object")if(Array.isArray(val))for(let i=0,len=val.length;i<len;++i){let v0=val[i],v1=applyReviver(reviver,val,String(i),v0);v1===void 0?delete val[i]:v1!==v0&&(val[i]=v1)}else if(val instanceof Map)for(let k of Array.from(val.keys())){let v0=val.get(k),v1=applyReviver(reviver,val,k,v0);v1===void 0?val.delete(k):v1!==v0&&val.set(k,v1)}else if(val instanceof Set)for(let v0 of Array.from(val)){let v1=applyReviver(reviver,val,v0,v0);v1===void 0?val.delete(v0):v1!==v0&&(val.delete(v0),val.add(v1))}else for(let[k,v0]of Object.entries(val)){let v1=applyReviver(reviver,val,k,v0);v1===void 0?delete val[k]:v1!==v0&&(val[k]=v1)}return reviver.call(obj,key,val)}__name(applyReviver,"applyReviver");exports2.applyReviver=applyReviver}});var require_toJS=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/toJS.js"(exports2){"use strict";var identity2=require_identity();function toJS(value,arg,ctx){if(Array.isArray(value))return value.map((v,i)=>toJS(v,String(i),ctx));if(value&&typeof value.toJSON=="function"){if(!ctx||!identity2.hasAnchor(value))return value.toJSON(arg,ctx);let data={aliasCount:0,count:1,res:void 0};ctx.anchors.set(value,data),ctx.onCreate=res2=>{data.res=res2,delete ctx.onCreate};let res=value.toJSON(arg,ctx);return ctx.onCreate&&ctx.onCreate(res),res}return typeof value=="bigint"&&!ctx?.keep?Number(value):value}__name(toJS,"toJS");exports2.toJS=toJS}});var require_Node=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/Node.js"(exports2){"use strict";var applyReviver=require_applyReviver(),identity2=require_identity(),toJS=require_toJS(),NodeBase=class{static{__name(this,"NodeBase")}constructor(type){Object.defineProperty(this,identity2.NODE_TYPE,{value:type})}clone(){let copy=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(copy.range=this.range.slice()),copy}toJS(doc,{mapAsMap,maxAliasCount,onAnchor,reviver}={}){if(!identity2.isDocument(doc))throw new TypeError("A document argument is required");let ctx={anchors:new Map,doc,keep:!0,mapAsMap:mapAsMap===!0,mapKeyWarned:!1,maxAliasCount:typeof maxAliasCount=="number"?maxAliasCount:100},res=toJS.toJS(this,"",ctx);if(typeof onAnchor=="function")for(let{count,res:res2}of ctx.anchors.values())onAnchor(res2,count);return typeof reviver=="function"?applyReviver.applyReviver(reviver,{"":res},"",res):res}};exports2.NodeBase=NodeBase}});var require_Alias=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/Alias.js"(exports2){"use strict";var anchors=require_anchors(),visit2=require_visit(),identity2=require_identity(),Node=require_Node(),toJS=require_toJS(),Alias=class extends Node.NodeBase{static{__name(this,"Alias")}constructor(source){super(identity2.ALIAS),this.source=source,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(doc,ctx){let nodes;ctx?.aliasResolveCache?nodes=ctx.aliasResolveCache:(nodes=[],visit2.visit(doc,{Node:__name((_key,node)=>{(identity2.isAlias(node)||identity2.hasAnchor(node))&&nodes.push(node)},"Node")}),ctx&&(ctx.aliasResolveCache=nodes));let found;for(let node of nodes){if(node===this)break;node.anchor===this.source&&(found=node)}return found}toJSON(_arg,ctx){if(!ctx)return{source:this.source};let{anchors:anchors2,doc,maxAliasCount}=ctx,source=this.resolve(doc,ctx);if(!source){let msg=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(msg)}let data=anchors2.get(source);if(data||(toJS.toJS(source,null,ctx),data=anchors2.get(source)),data?.res===void 0){let msg="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(msg)}if(maxAliasCount>=0&&(data.count+=1,data.aliasCount===0&&(data.aliasCount=getAliasCount(doc,source,anchors2)),data.count*data.aliasCount>maxAliasCount)){let msg="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(msg)}return data.res}toString(ctx,_onComment,_onChompKeep){let src=`*${this.source}`;if(ctx){if(anchors.anchorIsValid(this.source),ctx.options.verifyAliasOrder&&!ctx.anchors.has(this.source)){let msg=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(msg)}if(ctx.implicitKey)return`${src} `}return src}};function getAliasCount(doc,node,anchors2){if(identity2.isAlias(node)){let source=node.resolve(doc),anchor=anchors2&&source&&anchors2.get(source);return anchor?anchor.count*anchor.aliasCount:0}else if(identity2.isCollection(node)){let count=0;for(let item of node.items){let c2=getAliasCount(doc,item,anchors2);c2>count&&(count=c2)}return count}else if(identity2.isPair(node)){let kc=getAliasCount(doc,node.key,anchors2),vc=getAliasCount(doc,node.value,anchors2);return Math.max(kc,vc)}return 1}__name(getAliasCount,"getAliasCount");exports2.Alias=Alias}});var require_Scalar=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/Scalar.js"(exports2){"use strict";var identity2=require_identity(),Node=require_Node(),toJS=require_toJS(),isScalarValue=__name(value=>!value||typeof value!="function"&&typeof value!="object","isScalarValue"),Scalar=class extends Node.NodeBase{static{__name(this,"Scalar")}constructor(value){super(identity2.SCALAR),this.value=value}toJSON(arg,ctx){return ctx?.keep?this.value:toJS.toJS(this.value,arg,ctx)}toString(){return String(this.value)}};Scalar.BLOCK_FOLDED="BLOCK_FOLDED";Scalar.BLOCK_LITERAL="BLOCK_LITERAL";Scalar.PLAIN="PLAIN";Scalar.QUOTE_DOUBLE="QUOTE_DOUBLE";Scalar.QUOTE_SINGLE="QUOTE_SINGLE";exports2.Scalar=Scalar;exports2.isScalarValue=isScalarValue}});var require_createNode=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/doc/createNode.js"(exports2){"use strict";var Alias=require_Alias(),identity2=require_identity(),Scalar=require_Scalar(),defaultTagPrefix="tag:yaml.org,2002:";function findTagObject(value,tagName,tags){if(tagName){let match=tags.filter(t2=>t2.tag===tagName),tagObj=match.find(t2=>!t2.format)??match[0];if(!tagObj)throw new Error(`Tag ${tagName} not found`);return tagObj}return tags.find(t2=>t2.identify?.(value)&&!t2.format)}__name(findTagObject,"findTagObject");function createNode(value,tagName,ctx){if(identity2.isDocument(value)&&(value=value.contents),identity2.isNode(value))return value;if(identity2.isPair(value)){let map=ctx.schema[identity2.MAP].createNode?.(ctx.schema,null,ctx);return map.items.push(value),map}(value instanceof String||value instanceof Number||value instanceof Boolean||typeof BigInt<"u"&&value instanceof BigInt)&&(value=value.valueOf());let{aliasDuplicateObjects,onAnchor,onTagObj,schema,sourceObjects}=ctx,ref;if(aliasDuplicateObjects&&value&&typeof value=="object"){if(ref=sourceObjects.get(value),ref)return ref.anchor??(ref.anchor=onAnchor(value)),new Alias.Alias(ref.anchor);ref={anchor:null,node:null},sourceObjects.set(value,ref)}tagName?.startsWith("!!")&&(tagName=defaultTagPrefix+tagName.slice(2));let tagObj=findTagObject(value,tagName,schema.tags);if(!tagObj){if(value&&typeof value.toJSON=="function"&&(value=value.toJSON()),!value||typeof value!="object"){let node2=new Scalar.Scalar(value);return ref&&(ref.node=node2),node2}tagObj=value instanceof Map?schema[identity2.MAP]:Symbol.iterator in Object(value)?schema[identity2.SEQ]:schema[identity2.MAP]}onTagObj&&(onTagObj(tagObj),delete ctx.onTagObj);let node=tagObj?.createNode?tagObj.createNode(ctx.schema,value,ctx):typeof tagObj?.nodeClass?.from=="function"?tagObj.nodeClass.from(ctx.schema,value,ctx):new Scalar.Scalar(value);return tagName?node.tag=tagName:tagObj.default||(node.tag=tagObj.tag),ref&&(ref.node=node),node}__name(createNode,"createNode");exports2.createNode=createNode}});var require_Collection=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/nodes/Collection.js"(exports2){"use strict";var createNode=require_createNode(),identity2=require_identity(),Node=require_Node();function collectionFromPath(schema,path49,value){let v=value;for(let i=path49.length-1;i>=0;--i){let k=path49[i];if(typeof k=="number"&&Number.isInteger(k)&&k>=0){let a=[];a[k]=v,v=a}else v=new Map([[k,v]])}return createNode.createNode(v,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:__name(()=>{throw new Error("This should not happen, please report a bug.")},"onAnchor"),schema,sourceObjects:new Map})}__name(collectionFromPath,"collectionFromPath");var isEmptyPath=__name(path49=>path49==null||typeof path49=="object"&&!!path49[Symbol.iterator]().next().done,"isEmptyPath"),Collection=class extends Node.NodeBase{static{__name(this,"Collection")}constructor(type,schema){super(type),Object.defineProperty(this,"schema",{value:schema,configurable:!0,enumerable:!1,writable:!0})}clone(schema){let copy=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return schema&&(copy.schema=schema),copy.items=copy.items.map(it2=>identity2.isNode(it2)||identity2.isPair(it2)?it2.clone(schema):it2),this.range&&(copy.range=this.range.slice()),copy}addIn(path49,value){if(isEmptyPath(path49))this.add(value);else{let[key,...rest]=path49,node=this.get(key,!0);if(identity2.isCollection(node))node.addIn(rest,value);else if(node===void 0&&this.schema)this.set(key,collectionFromPath(this.schema,rest,value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}}deleteIn(path49){let[key,...rest]=path49;if(rest.length===0)return this.delete(key);let node=this.get(key,!0);if(identity2.isCollection(node))return node.deleteIn(rest);throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}getIn(path49,keepScalar){let[key,...rest]=path49,node=this.get(key,!0);return rest.length===0?!keepScalar&&identity2.isScalar(node)?node.value:node:identity2.isCollection(node)?node.getIn(rest,keepScalar):void 0}hasAllNullValues(allowScalar){return this.items.every(node=>{if(!identity2.isPair(node))return!1;let n=node.value;return n==null||allowScalar&&identity2.isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(path49){let[key,...rest]=path49;if(rest.length===0)return this.has(key);let node=this.get(key,!0);return identity2.isCollection(node)?node.hasIn(rest):!1}setIn(path49,value){let[key,...rest]=path49;if(rest.length===0)this.set(key,value);else{let node=this.get(key,!0);if(identity2.isCollection(node))node.setIn(rest,value);else if(node===void 0&&this.schema)this.set(key,collectionFromPath(this.schema,rest,value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}}};exports2.Collection=Collection;exports2.collectionFromPath=collectionFromPath;exports2.isEmptyPath=isEmptyPath}});var require_stringifyComment=__commonJS({"../../node_modules/.pnpm/yaml@2.8.2/node_modules/yaml/dist/stringify/stringifyComment.js"(exports2){"use strict";var stringifyComment=__name(str=>str.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function indentComment(comment,indent){return/^\n+$/.test(comment)?comment.substring(1):indent?comment.replace(/^(?! *$)/gm,indent):comment}__name(indentComment,"indentComment");var lineComment=__name((str,indent,comment)=>str.endsWith(`
|
|
@@ -421,7 +421,7 @@ ${end.comment}`:end.comment}this.doc.range[2]=end.offset;break}default:this.erro
|
|
|
421
421
|
${target}: Fimo branch not created yet`}}function pickSurfaces(opts){let selected=[["code","code"],["content","content"],["i18n","translations"],["assets","assets"],["forms","forms"]].filter(([flag2])=>opts[flag2]===!0).map(([,surface])=>surface);return selected.length>0?selected:void 0}function withSoftTimeout(p2,ms){return new Promise(resolve10=>{let t2=setTimeout(()=>resolve10({kind:"timeout"}),ms);p2.then(value=>{clearTimeout(t2),resolve10({kind:"ok",value})},error=>{clearTimeout(t2),resolve10({kind:"error",error})})})}async function localCodeSurface(cwd){if(!await isGitRepo(cwd))return{surface:"code",status:"unchanged",changedCount:0,conflictCount:0,items:[]};try{let items=(await runGit(["status","--porcelain"],cwd)).split(`
|
|
422
422
|
`).filter(Boolean).map(line=>{let code2=line.slice(0,2),path49=line.slice(3).trim();return{verb:code2.startsWith("A")||code2.startsWith("?")?"added":code2.startsWith("D")?"removed":"changed",key:path49,origin:"local-uncommitted"}});return{surface:"code",status:items.length===0?"unchanged":"ok",changedCount:items.length,conflictCount:0,items}}catch{return{surface:"code",status:"unchanged",changedCount:0,conflictCount:0,items:[]}}}function mergeCodeSurfaces(serverCode,local){if(!serverCode)return local;if(serverCode.status==="failed"||serverCode.status==="timed_out")return{...serverCode,items:[...serverCode.items??[],...local.items??[]],changedCount:serverCode.changedCount+local.changedCount};let items=[...serverCode.items??[],...local.items??[]],changedCount=serverCode.changedCount+local.changedCount,conflictCount=serverCode.conflictCount+local.conflictCount;return{surface:"code",status:changedCount>0||conflictCount>0?"ok":"unchanged",durationMs:serverCode.durationMs,changedCount,conflictCount,items}}async function statusCommand2(arg1,maybeCmd){let cmd=maybeCmd??arg1,options=maybeCmd?arg1:cmd.opts(),program2=cmd.parent??cmd,branchOverride2=branchOverrideFromCommand(program2),ctx=await getProjectContext({cwd:options.cwd,branchOverride:branchOverride2}),fimo=createCliFimoClient(loadConfig(),ctx.branch),git=createGitService(loadConfig(),ctx.branch),cwd=resolveProjectCwd(options.cwd),surfaces=pickSurfaces(options),codePromise=localCodeSurface(cwd),checkoutPromise=localCheckoutStatus(git,ctx.projectId,ctx.branch,cwd),serverPromise=withSoftTimeout(fimo.execute("branches.status",{projectId:ctx.projectId,branch:ctx.branch,against:options.vs,surfaces:surfaces?.map(surface=>surface==="translations"?"labels":surface)}),SOFT_TIMEOUT_MS*15),[local,checkout,serverResult]=await Promise.all([codePromise,checkoutPromise,serverPromise]);if(serverResult.kind==="timeout"){ui.error({command:"status",code:"STATUS_TIMEOUT",message:`Server did not respond within ${SOFT_TIMEOUT_MS*15/1e3}s. Try again, or run \`fimo diff\` to drill in.`});return}if(serverResult.kind==="error"){let err=serverResult.error,message=err instanceof Error?err.message:String(err);ui.error({command:"status",code:"STATUS_REQUEST_FAILED",message:`Failed to fetch status: ${message}`});return}let portableServer=serverResult.value,server={branch:portableServer.branch,env:portableServer.branch,vs:portableServer.against,syncState:portableServer.syncState??(portableServer.state==="clean"?"in-sync":"diverged"),generatedAt:portableServer.generatedAt,surfaces:portableServer.surfaces.map(item=>({...item,surface:item.surface==="labels"?"translations":item.surface})),crossSurface:portableServer.crossSurface?.map(finding=>({...finding,source:{...finding.source,surface:finding.source.surface==="labels"?"translations":finding.source.surface},target:{...finding.target,surface:finding.target.surface==="labels"?"translations":finding.target.surface}}))},serverCode=server.surfaces.find(s=>s.surface==="code"),code2=mergeCodeSurfaces(serverCode,local),merged={...server,checkout,surfaces:[code2,...server.surfaces.filter(s=>s.surface!=="code")]};ui.result({command:"status",data:merged,render:__name(rctx=>{let p2=rctx.color?palette:makeColorPalette({forceDisable:!0}),environmentStatus=renderStatus2(merged,p2,{short:options.short,surface:surfaces?.length===1?surfaces[0]:void 0,all:options.all,ascii:rctx.ascii});return`${renderLocalCheckoutStatus(checkout)}
|
|
423
423
|
|
|
424
|
-
${environmentStatus}`},"render")})}var SOFT_TIMEOUT_MS,init_status=__esm({"src/cli/commands/status.ts"(){init_dist();init_config();init_sdk_transport();init_project_services();init_branch_checkout();init_color();init_render_status();init_git_credential_setup();init_git();init_project_context();init_project();SOFT_TIMEOUT_MS=2e3;__name(withCheckoutRecovery,"withCheckoutRecovery");__name(localCheckoutStatus,"localCheckoutStatus");__name(renderLocalCheckoutStatus,"renderLocalCheckoutStatus");__name(pickSurfaces,"pickSurfaces");__name(withSoftTimeout,"withSoftTimeout");__name(localCodeSurface,"localCodeSurface");__name(mergeCodeSurfaces,"mergeCodeSurfaces");__name(statusCommand2,"statusCommand")}});init_esm();init_dist();import fs48 from"node:fs";import path48 from"node:path";var import_index=__toESM(require_commander(),1),{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import_index.default;init_auth();init_esm();init_dist();init_project_context();function parseRangeOptions(options){let params={};if(options.preset&&(params.preset=options.preset),options.groupBy&&(params.groupBy=options.groupBy),options.from&&(params.from=options.from),options.to&&(params.to=options.to),options.device&&(params.device=options.device),options.days!==void 0){let n=Number(options.days);if(!Number.isFinite(n))throw new Error(`Invalid --days value: ${options.days}`);params.days=n}return params}__name(parseRangeOptions,"parseRangeOptions");function renderPrettyJson(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson,"renderPrettyJson");async function analyticsPageviewsCommand(options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{defaultBranch:PRODUCTION_BRANCH}),{data:result}=await fimo.execute("analytics.pageviews",{projectId:ctx.projectId,branch:ctx.branch,...parseRangeOptions(options)});ui.result({command:"analytics pageviews",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsPageviewsCommand,"analyticsPageviewsCommand");var TOP_DIMENSIONS=["pages","browsers","devices","countries","sources"];async function analyticsTopCommand(dimension,options,cmd){if(!TOP_DIMENSIONS.includes(dimension))throw new Error(`Unknown dimension: ${dimension}. Expected one of: ${TOP_DIMENSIONS.join(", ")}`);let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{defaultBranch:PRODUCTION_BRANCH}),{items,branch}=await fimo.execute("analytics.top",{projectId:ctx.projectId,branch:ctx.branch,dimension,...parseRangeOptions(options)}),limit;if(options.limit!==void 0){let n=Number(options.limit);if(!Number.isFinite(n)||n<1)throw new Error(`Invalid --limit value: ${options.limit}`);limit=n}let trimmed=limit!==void 0?items.slice(0,limit):items;ui.result({command:"analytics top",data:{branch,dimension,items:trimmed},render:__name(()=>renderPrettyJson(trimmed),"render")})}__name(analyticsTopCommand,"analyticsTopCommand");async function analyticsAnnotationsListCommand(options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{defaultBranch:PRODUCTION_BRANCH}),{annotations:annotations2,branch}=await fimo.execute("analytics.annotationsList",{projectId:ctx.projectId,branch:ctx.branch,...parseRangeOptions(options)});ui.result({command:"analytics annotations list",data:{branch,annotations:annotations2},render:__name(()=>renderPrettyJson(annotations2),"render")})}__name(analyticsAnnotationsListCommand,"analyticsAnnotationsListCommand");async function analyticsAnnotationsSetCommand(date,content2,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd),result=(await fimo.execute("analytics.annotationsSet",{projectId:ctx.projectId,branch:ctx.branch,date,content:content2}))?.data??null;ui.result({command:"analytics annotations set",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsAnnotationsSetCommand,"analyticsAnnotationsSetCommand");async function analyticsAnnotationsDeleteCommand(date,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await fimo.execute("analytics.annotationsDelete",{projectId:ctx.projectId,branch:ctx.branch,date}),ui.ok({command:"analytics annotations delete",headline:`Deleted annotation for ${date}.`,details:{date}})}__name(analyticsAnnotationsDeleteCommand,"analyticsAnnotationsDeleteCommand");init_dist();import{spawn}from"node:child_process";import{mkdirSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{dirname,extname,isAbsolute,join as join2,resolve as resolvePath}from"node:path";var import_yaml=__toESM(require_dist(),1);import{z as z109}from"zod";var CapabilityTokenSchema=z109.string().min(1).regex(/^(?:[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?|[a-z][a-z0-9_]*:\*)$/,{error:"capabilities must be an exact token or namespace selector such as cms:* (lowercase + digits + underscores)"}),CapabilitiesFileSchema=z109.array(CapabilityTokenSchema);import{z as z110}from"zod";var CronTriggerSchema=z110.object({type:z110.literal("schedule"),cron:z110.string().min(1,"cron expression required"),tz:z110.string().optional()}),ManualTriggerSchema=z110.object({type:z110.literal("manual")}),WebhookTriggerSchema=z110.object({type:z110.literal("webhook"),path:z110.string().min(1).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z110.discriminatedUnion("type",[ManualTriggerSchema,CronTriggerSchema,WebhookTriggerSchema]),SubAgentRefSchema=z110.object({name:z110.string().min(1),capability_grant:z110.enum(["inherit","explicit"]).optional(),explicit_grants:z110.array(z110.string()).optional()}).refine(v=>v.capability_grant!=="explicit"||Array.isArray(v.explicit_grants)&&v.explicit_grants.length>0,{message:"`explicit_grants` is required when `capability_grant: explicit`",path:["explicit_grants"]}),CompositionConfigSchema=z110.object({"sub-agents":z110.array(SubAgentRefSchema)}),RuntimeConfigSchema=z110.object({cloud:z110.boolean().optional(),dev:z110.boolean().optional(),max_credits:z110.number().int().min(1).optional(),max_steps:z110.number().int().min(1).optional()}),DataSourceSchema=z110.enum(["main","prod"]),ConfigValueKeySchema=z110.string().min(1).max(255).regex(/^[A-Z_][A-Z0-9_]*$/,"secret keys must be UPPER_SNAKE_CASE and start with a letter or underscore"),PUBLIC_CONFIG_PREFIX=/^(PUBLIC_|VITE_|NEXT_PUBLIC_)/,AgentSecretRequestSchema=z110.preprocess(value=>typeof value=="string"?{key:value}:value,z110.object({key:ConfigValueKeySchema.refine(key=>!PUBLIC_CONFIG_PREFIX.test(key),{message:"agent secrets cannot use public variable prefixes (PUBLIC_, VITE_, NEXT_PUBLIC_)"}),required:z110.boolean().default(!0),delivery:z110.literal("process_env").default("process_env")})),IntegrationKeySchema=z110.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*$/,"integration keys must be lowercase alphanumeric with optional _ or -"),IntegrationToolKeySchema=z110.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)*$/,"integration tool keys must be lowercase dot-separated identifiers with optional _ or -"),IntegrationPolicyEntrySchema=z110.preprocess(value=>typeof value=="boolean"?{enabled:value}:value,z110.object({enabled:z110.boolean().default(!0),tools:z110.record(IntegrationToolKeySchema,z110.boolean()).optional()})),IntegrationPolicySchema=z110.record(IntegrationKeySchema,IntegrationPolicyEntrySchema),AgentConfigSchema=z110.object({version:z110.literal(1),description:z110.string().min(1).max(280).optional(),model:z110.string().trim().min(1).max(255).optional(),runtime:RuntimeConfigSchema.optional(),triggers:z110.array(TriggerSchema).optional(),composition:CompositionConfigSchema.optional(),data_sources:z110.array(DataSourceSchema).optional(),secrets:z110.array(AgentSecretRequestSchema).optional(),integrations:IntegrationPolicySchema.optional(),integration_policy:IntegrationPolicySchema.optional()}).refine(config=>!(config.integrations&&config.integration_policy),{message:"use either `integrations` or legacy `integration_policy`, not both",path:["integrations"]});var ENTRIES=[{token:"knowledge:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read private project goals, brand guidance and rules"},{token:"knowledge:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Update shared project knowledge only when explicitly requested"},{token:"files:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read project files"},{token:"files:write",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Write or delete project files"},{token:"cms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS content"},{token:"cms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Create, update, or delete CMS entries"},{token:"cms:schema:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS schemas"},{token:"cms:schema:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Modify CMS schemas (destructive \u2014 alters all entries of the type)"},{token:"assets:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read uploaded media"},{token:"assets:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Upload, replace, or delete media"},{token:"i18n:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read translation catalogs"},{token:"i18n:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify translation catalogs via the fimo i18n CLI"},{token:"forms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read form schemas and submissions"},{token:"forms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify form schemas or clear submissions"},{token:"webhooks:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read webhook configurations and delivery history"},{token:"webhooks:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger webhooks that send project data to external URLs"},{token:"schedules:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read schedule configurations and run history"},{token:"schedules:write",risk:"critical",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger scheduled commands that run with publish and code-edit rights"},{token:"git:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read git state"},{token:"git:branch",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Create agent-proposed branches off main"},{token:"git:commit",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Commit changes to an agent branch"},{token:"git:push",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Push to the project remote (main push is intercepted)"},{token:"git:tag",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Used by runtime for prod release tags; agents cannot call directly"},{token:"fimo:deploy",risk:"critical",declarable:!0,enforcedBy:"api",description:"Trigger a production deploy"},{token:"fimo:logs:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project deployment logs"},{token:"fimo:analytics:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read analytics data"},{token:"fimo:domains:manage",risk:"high",declarable:!0,enforcedBy:"api",description:"Read and manage project domains"},{token:"fimo:agents:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run project agents"},{token:"fimo:preview:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read a current preview URL for an env (no commit, no deploy)"},{token:"fimo:history:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project restore points"},{token:"integrations:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run enabled project integration tools allowed by the agent policy"},{token:"shell:exec",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Run arbitrary shell commands inside the sandbox"},{token:"agent:delegate",risk:"medium",declarable:!0,enforcedBy:"engine",description:"Invoke declared sub-agents"},{token:"runtime:auto_merge",risk:"critical",declarable:!0,enforcedBy:"runtime",description:"Merge work sessions into their target Branch without per-change human review"}],BY_TOKEN=new Map(ENTRIES.map(entry=>[entry.token,entry])),CAPABILITY_VOCABULARY=ENTRIES;function getCapability(token){return BY_TOKEN.get(token)??null}__name(getCapability,"getCapability");import{z as z111}from"zod";var SurfaceGuardPolicySchema=z111.enum(["block","warn","allow"]),ClassificationSchema=z111.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z111.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z111.object({enabled:z111.boolean(),allowed_skills:z111.array(z111.string().min(1)).default([]),allowed_classifications:z111.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z111.enum(["off","daily","weekly"]),NotificationFormatSchema=z111.object({markdown:z111.boolean().default(!0),html:z111.boolean().default(!1)}),NotificationsPolicySchema=z111.object({email_recipients:z111.array(z111.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z111.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z111.object({agents:FimoAgentsConfigSchema.optional()}).passthrough();import{z as z112}from"zod";function toSpec(def){return{token:def.token,riskTier:def.risk,description:def.description}}__name(toSpec,"toSpec");var VOCABULARY=Object.freeze(Object.fromEntries(CAPABILITY_VOCABULARY.filter(definition=>definition.declarable).map(definition=>[definition.token,toSpec(definition)]))),CapabilityToken=z112.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z112.array(CapabilityToken);var RUNTIME_BASELINE_OPERATION_CAPABILITIES=["files:read","files:write"];function isRuntimeBaselineOperationCapability(capability){return RUNTIME_BASELINE_OPERATION_CAPABILITIES.includes(capability)}__name(isRuntimeBaselineOperationCapability,"isRuntimeBaselineOperationCapability");var OPERATION_CAP={"knowledge.get":"knowledge:read","knowledge.update":"knowledge:write","cms.list":"cms:read","cms.get":"cms:read","cms.query":"cms:read","cms.create":"cms:write","cms.update":"cms:write","cms.delete":"cms:write","cms.bulk_create":"cms:write","cms.bulk_update":"cms:write","cms.bulk_delete":"cms:write","cms.schema.list":"cms:schema:read","cms.schema.get":"cms:schema:read","cms.schema.push":"cms:schema:write","cms.schema.delete":"cms:schema:write","assets.list":"assets:read","assets.get":"assets:read","assets.read":"assets:read","assets.upload":"assets:write","assets.generate":"assets:write","assets.create_folder":"assets:write","assets.move":"assets:write","assets.delete":"assets:write","i18n.list":"i18n:read","i18n.get":"i18n:read","i18n.create":"i18n:write","i18n.update":"i18n:write","i18n.delete":"i18n:write","forms.list":"forms:read","forms.get":"forms:read","forms.push":"forms:write","forms.delete":"forms:write","webhooks.events":"webhooks:read","webhooks.list":"webhooks:read","webhooks.get":"webhooks:read","webhooks.deliveries.list":"webhooks:read","webhooks.deliveries.get":"webhooks:read","webhooks.create":"webhooks:write","webhooks.update":"webhooks:write","webhooks.delete":"webhooks:write","webhooks.test":"webhooks:write","webhooks.deliveries.retry":"webhooks:write","webhooks.rotate_secret":"webhooks:write","schedules.list":"schedules:read","schedules.get":"schedules:read","schedules.runs.list":"schedules:read","schedules.runs.get":"schedules:read","schedules.create":"schedules:write","schedules.update":"schedules:write","schedules.delete":"schedules:write","schedules.pause":"schedules:write","schedules.resume":"schedules:write","schedules.run":"schedules:write","files.read":"files:read","files.write":"files:write","fimo.deploy":"fimo:deploy","fimo.logs.read":"fimo:logs:read","fimo.analytics.read":"fimo:analytics:read","fimo.preview.url":"fimo:preview:read","fimo.history.list":"fimo:history:read","fimo.history.get":"fimo:history:read","agent.delegate":"agent:delegate","runtime.auto_merge":"runtime:auto_merge"};function capabilityFor(op){return OPERATION_CAP[op]}__name(capabilityFor,"capabilityFor");function hasOperation(op){return Object.prototype.hasOwnProperty.call(OPERATION_CAP,op)}__name(hasOperation,"hasOperation");var import_yaml2=__toESM(require_dist(),1);function _define_property(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property,"_define_property");var CapabilityDenied=class extends Error{static{__name(this,"CapabilityDenied")}constructor(detail){let def=getCapability(detail.cap),description=def?.description?` (${def.description})`:"";super(`capability denied: ${detail.cap}${description} \u2014 reason: ${detail.reason}`),_define_property(this,"cap",void 0),_define_property(this,"reason",void 0),_define_property(this,"granted",void 0),_define_property(this,"sessionId",void 0),_define_property(this,"fixHint",void 0),this.name="CapabilityDenied",this.cap=detail.cap,this.reason=detail.reason,this.granted=detail.granted??[],this.sessionId=detail.sessionId,this.fixHint=fixHintFor(detail)}};function fixHintFor(detail){switch(detail.reason){case"not-declared":return`Add '${detail.cap}' to the agent's capabilities.yaml and re-activate.`;case"session-not-found":return`Session '${detail.sessionId??"<unknown>"}' does not exist or has expired.`;case"snapshot-stale":return"Session capability snapshot is corrupted. Restart the agent session.";case"runtime-only":return`'${detail.cap}' is reserved for the platform \u2014 drop it from capabilities.yaml.`;case"auto-merge-blocked":return"runtime:auto_merge is declared but blocked by project policy (.fimo/config.json \u2192 agents.auto_merge)."}}__name(fixHintFor,"fixHintFor");var configured=null;async function auditCapabilityDecision(event){if(!configured)return;let row2={...event,ts:new Date().toISOString()};if(event.decision==="deny"){try{await configured.transport.write(row2)}catch(err){throw configured.breadcrumb?.({category:"audit",level:"error",message:"audit deny row write failed",data:{cap:event.cap,error:err.message}}),err}configured.breadcrumb?.({category:"audit",level:"warning",message:`capability denied: ${event.cap}`,data:{sessionId:event.sessionId,cap:event.cap,reason:event.reason}});return}configured.transport.write(row2).catch(err=>{configured?.breadcrumb?.({category:"audit",level:"warning",message:"audit allow row write failed (best-effort)",data:{cap:event.cap,error:err.message}})})}__name(auditCapabilityDecision,"auditCapabilityDecision");var ENV_SESSION="FIMO_AGENT_SESSION",ENV_CAPS_FALLBACK="FIMO_AGENT_CAPABILITIES";function currentAgentSession(){let id=process.env[ENV_SESSION];return id&&id.length>0?id:void 0}__name(currentAgentSession,"currentAgentSession");async function defaultFetchSessionCapabilities(_sessionId){let raw=process.env[ENV_CAPS_FALLBACK];return raw?raw.split(",").map(s=>s.trim()).filter(s=>s.length>0):[]}__name(defaultFetchSessionCapabilities,"defaultFetchSessionCapabilities");async function requireCapability(cap,ctx={}){let sessionId=currentAgentSession();if(!sessionId)return{ok:!0,bypassed:!0};let granted=await(ctx.fetchSessionCapabilities??defaultFetchSessionCapabilities)(sessionId);if(!granted.includes(cap)){try{await auditCapabilityDecision({sessionId,cap,decision:"deny",reason:granted.length===0?"session-not-found":"not-declared",projectId:ctx.projectId,env:ctx.branch})}catch{}throw new CapabilityDenied({cap,reason:granted.length===0?"session-not-found":"not-declared",granted,sessionId})}return auditCapabilityDecision({sessionId,cap,decision:"allow",projectId:ctx.projectId,env:ctx.branch}),{ok:!0,bypassed:!1}}__name(requireCapability,"requireCapability");async function requireOperation(op,ctx={}){if(!hasOperation(op))throw new Error(`requireOperation: unknown operation id '${op}' \u2014 register it in @fimo/agents capabilities/operation-map.ts`);let cap=capabilityFor(op);return isRuntimeBaselineOperationCapability(cap)?{ok:!0,bypassed:currentAgentSession()===void 0}:requireCapability(cap,ctx)}__name(requireOperation,"requireOperation");init_project_context();init_project();function extensionFor(asset){let fromName=extname(asset.name);if(fromName&&fromName.length<=6)return fromName;let mime=asset.mimeType??"";return mime.startsWith("image/")?"."+(mime.split("/")[1]??"bin"):mime.startsWith("video/")?"."+(mime.split("/")[1]??"mp4"):mime.startsWith("audio/")?"."+(mime.split("/")[1]??"mp3"):""}__name(extensionFor,"extensionFor");function defaultDownloadPath(asset){let ext=extensionFor(asset);return join2(tmpdir(),"fimo-assets",`${asset.id}${ext}`)}__name(defaultDownloadPath,"defaultDownloadPath");async function downloadToPath(url,dest){let response=await fetch(url);if(!response.ok)throw new Error(`Failed to download asset: HTTP ${response.status} ${response.statusText}`);let arrayBuffer=await response.arrayBuffer();mkdirSync(dirname(dest),{recursive:!0}),writeFileSync(dest,new Uint8Array(arrayBuffer))}__name(downloadToPath,"downloadToPath");function spawnBrowser(url){let command=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(process.platform==="win32"?spawn("cmd",["/c","start","",url],{detached:!0,stdio:"ignore"}):spawn(command,[url],{detached:!0,stdio:"ignore"})).unref()}__name(spawnBrowser,"spawnBrowser");function renderPrettyJson2(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson2,"renderPrettyJson");async function assetsOpenCommand(id,options,cmd){if(options.download&&options.browser)throw new Error("--download and --browser are mutually exclusive \u2014 pick one");let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.get",{projectId:ctx.projectId,branch:ctx.branch});let cwd=resolveProjectCwd(options.cwd),{data:asset}=await fimo.execute("assets.get",{projectId:ctx.projectId,branch:ctx.branch,id});if(asset.type==="folder")throw new Error(`Asset ${id} is a folder; can only open files`);if(!asset.url)throw new Error(`Asset ${id} has no public URL \u2014 it may not have finished uploading`);if(options.browser){spawnBrowser(asset.url);let payload2={opened:asset.url};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}if(options.download){let dest=options.path?isAbsolute(options.path)?options.path:resolvePath(cwd,options.path):defaultDownloadPath(asset);await downloadToPath(asset.url,dest);let payload2={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,path:dest,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,aiAltText:asset.aiAltText??null};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}let payload={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,caption:asset.caption??null,aiAltText:asset.aiAltText??null,aiCaption:asset.aiCaption??null,aiTags:asset.aiTags??null};ui.result({command:"assets open",data:payload,render:__name(()=>renderPrettyJson2(payload),"render")})}__name(assetsOpenCommand,"assetsOpenCommand");import fs7 from"node:fs";import path7 from"node:path";import{styleText as y}from"node:util";import{stdout as S,stdin as $}from"node:process";import P from"node:readline";var isAmbiguous=__name(x=>x===161||x===164||x===167||x===168||x===170||x===173||x===174||x>=176&&x<=180||x>=182&&x<=186||x>=188&&x<=191||x===198||x===208||x===215||x===216||x>=222&&x<=225||x===230||x>=232&&x<=234||x===236||x===237||x===240||x===242||x===243||x>=247&&x<=250||x===252||x===254||x===257||x===273||x===275||x===283||x===294||x===295||x===299||x>=305&&x<=307||x===312||x>=319&&x<=322||x===324||x>=328&&x<=331||x===333||x===338||x===339||x===358||x===359||x===363||x===462||x===464||x===466||x===468||x===470||x===472||x===474||x===476||x===593||x===609||x===708||x===711||x>=713&&x<=715||x===717||x===720||x>=728&&x<=731||x===733||x===735||x>=768&&x<=879||x>=913&&x<=929||x>=931&&x<=937||x>=945&&x<=961||x>=963&&x<=969||x===1025||x>=1040&&x<=1103||x===1105||x===8208||x>=8211&&x<=8214||x===8216||x===8217||x===8220||x===8221||x>=8224&&x<=8226||x>=8228&&x<=8231||x===8240||x===8242||x===8243||x===8245||x===8251||x===8254||x===8308||x===8319||x>=8321&&x<=8324||x===8364||x===8451||x===8453||x===8457||x===8467||x===8470||x===8481||x===8482||x===8486||x===8491||x===8531||x===8532||x>=8539&&x<=8542||x>=8544&&x<=8555||x>=8560&&x<=8569||x===8585||x>=8592&&x<=8601||x===8632||x===8633||x===8658||x===8660||x===8679||x===8704||x===8706||x===8707||x===8711||x===8712||x===8715||x===8719||x===8721||x===8725||x===8730||x>=8733&&x<=8736||x===8739||x===8741||x>=8743&&x<=8748||x===8750||x>=8756&&x<=8759||x===8764||x===8765||x===8776||x===8780||x===8786||x===8800||x===8801||x>=8804&&x<=8807||x===8810||x===8811||x===8814||x===8815||x===8834||x===8835||x===8838||x===8839||x===8853||x===8857||x===8869||x===8895||x===8978||x>=9312&&x<=9449||x>=9451&&x<=9547||x>=9552&&x<=9587||x>=9600&&x<=9615||x>=9618&&x<=9621||x===9632||x===9633||x>=9635&&x<=9641||x===9650||x===9651||x===9654||x===9655||x===9660||x===9661||x===9664||x===9665||x>=9670&&x<=9672||x===9675||x>=9678&&x<=9681||x>=9698&&x<=9701||x===9711||x===9733||x===9734||x===9737||x===9742||x===9743||x===9756||x===9758||x===9792||x===9794||x===9824||x===9825||x>=9827&&x<=9829||x>=9831&&x<=9834||x===9836||x===9837||x===9839||x===9886||x===9887||x===9919||x>=9926&&x<=9933||x>=9935&&x<=9939||x>=9941&&x<=9953||x===9955||x===9960||x===9961||x>=9963&&x<=9969||x===9972||x>=9974&&x<=9977||x===9979||x===9980||x===9982||x===9983||x===10045||x>=10102&&x<=10111||x>=11094&&x<=11097||x>=12872&&x<=12879||x>=57344&&x<=63743||x>=65024&&x<=65039||x===65533||x>=127232&&x<=127242||x>=127248&&x<=127277||x>=127280&&x<=127337||x>=127344&&x<=127373||x===127375||x===127376||x>=127387&&x<=127404||x>=917760&&x<=917999||x>=983040&&x<=1048573||x>=1048576&&x<=1114109,"isAmbiguous"),isFullWidth=__name(x=>x===12288||x>=65281&&x<=65376||x>=65504&&x<=65510,"isFullWidth"),isWide=__name(x=>x>=4352&&x<=4447||x===8986||x===8987||x===9001||x===9002||x>=9193&&x<=9196||x===9200||x===9203||x===9725||x===9726||x===9748||x===9749||x>=9800&&x<=9811||x===9855||x===9875||x===9889||x===9898||x===9899||x===9917||x===9918||x===9924||x===9925||x===9934||x===9940||x===9962||x===9970||x===9971||x===9973||x===9978||x===9981||x===9989||x===9994||x===9995||x===10024||x===10060||x===10062||x>=10067&&x<=10069||x===10071||x>=10133&&x<=10135||x===10160||x===10175||x===11035||x===11036||x===11088||x===11093||x>=11904&&x<=11929||x>=11931&&x<=12019||x>=12032&&x<=12245||x>=12272&&x<=12287||x>=12289&&x<=12350||x>=12353&&x<=12438||x>=12441&&x<=12543||x>=12549&&x<=12591||x>=12593&&x<=12686||x>=12688&&x<=12771||x>=12783&&x<=12830||x>=12832&&x<=12871||x>=12880&&x<=19903||x>=19968&&x<=42124||x>=42128&&x<=42182||x>=43360&&x<=43388||x>=44032&&x<=55203||x>=63744&&x<=64255||x>=65040&&x<=65049||x>=65072&&x<=65106||x>=65108&&x<=65126||x>=65128&&x<=65131||x>=94176&&x<=94180||x===94192||x===94193||x>=94208&&x<=100343||x>=100352&&x<=101589||x>=101632&&x<=101640||x>=110576&&x<=110579||x>=110581&&x<=110587||x===110589||x===110590||x>=110592&&x<=110882||x===110898||x>=110928&&x<=110930||x===110933||x>=110948&&x<=110951||x>=110960&&x<=111355||x===126980||x===127183||x===127374||x>=127377&&x<=127386||x>=127488&&x<=127490||x>=127504&&x<=127547||x>=127552&&x<=127560||x===127568||x===127569||x>=127584&&x<=127589||x>=127744&&x<=127776||x>=127789&&x<=127797||x>=127799&&x<=127868||x>=127870&&x<=127891||x>=127904&&x<=127946||x>=127951&&x<=127955||x>=127968&&x<=127984||x===127988||x>=127992&&x<=128062||x===128064||x>=128066&&x<=128252||x>=128255&&x<=128317||x>=128331&&x<=128334||x>=128336&&x<=128359||x===128378||x===128405||x===128406||x===128420||x>=128507&&x<=128591||x>=128640&&x<=128709||x===128716||x>=128720&&x<=128722||x>=128725&&x<=128727||x>=128732&&x<=128735||x===128747||x===128748||x>=128756&&x<=128764||x>=128992&&x<=129003||x===129008||x>=129292&&x<=129338||x>=129340&&x<=129349||x>=129351&&x<=129535||x>=129648&&x<=129660||x>=129664&&x<=129672||x>=129680&&x<=129725||x>=129727&&x<=129733||x>=129742&&x<=129755||x>=129760&&x<=129768||x>=129776&&x<=129784||x>=131072&&x<=196605||x>=196608&&x<=262141,"isWide");var ANSI_RE=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,CONTROL_RE=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,TAB_RE=/\t{1,1000}/y,EMOJI_RE=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),LATIN_RE=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,MODIFIER_RE=new RegExp("\\p{M}+","gu"),NO_TRUNCATION={limit:1/0,ellipsis:""},getStringTruncatedWidth=__name((input,truncationOptions={},widthOptions={})=>{let LIMIT=truncationOptions.limit??1/0,ELLIPSIS=truncationOptions.ellipsis??"",ELLIPSIS_WIDTH=truncationOptions?.ellipsisWidth??(ELLIPSIS?getStringTruncatedWidth(ELLIPSIS,NO_TRUNCATION,widthOptions).width:0),ANSI_WIDTH=widthOptions.ansiWidth??0,CONTROL_WIDTH=widthOptions.controlWidth??0,TAB_WIDTH=widthOptions.tabWidth??8,AMBIGUOUS_WIDTH=widthOptions.ambiguousWidth??1,EMOJI_WIDTH=widthOptions.emojiWidth??2,FULL_WIDTH_WIDTH=widthOptions.fullWidthWidth??2,REGULAR_WIDTH=widthOptions.regularWidth??1,WIDE_WIDTH=widthOptions.wideWidth??2,indexPrev=0,index=0,length=input.length,lengthExtra=0,truncationEnabled=!1,truncationIndex=length,truncationLimit=Math.max(0,LIMIT-ELLIPSIS_WIDTH),unmatchedStart=0,unmatchedEnd=0,width=0,widthExtra=0;outer:for(;;){if(unmatchedEnd>unmatchedStart||index>=length&&index>indexPrev){let unmatched=input.slice(unmatchedStart,unmatchedEnd)||input.slice(indexPrev,index);lengthExtra=0;for(let char of unmatched.replaceAll(MODIFIER_RE,"")){let codePoint=char.codePointAt(0)||0;if(isFullWidth(codePoint)?widthExtra=FULL_WIDTH_WIDTH:isWide(codePoint)?widthExtra=WIDE_WIDTH:AMBIGUOUS_WIDTH!==REGULAR_WIDTH&&isAmbiguous(codePoint)?widthExtra=AMBIGUOUS_WIDTH:widthExtra=REGULAR_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,Math.max(unmatchedStart,indexPrev)+lengthExtra)),width+widthExtra>LIMIT){truncationEnabled=!0;break outer}lengthExtra+=char.length,width+=widthExtra}unmatchedStart=unmatchedEnd=0}if(index>=length)break;if(LATIN_RE.lastIndex=index,LATIN_RE.test(input)){if(lengthExtra=LATIN_RE.lastIndex-index,widthExtra=lengthExtra*REGULAR_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index+Math.floor((truncationLimit-width)/REGULAR_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=LATIN_RE.lastIndex;continue}if(ANSI_RE.lastIndex=index,ANSI_RE.test(input)){if(width+ANSI_WIDTH>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index)),width+ANSI_WIDTH>LIMIT){truncationEnabled=!0;break}width+=ANSI_WIDTH,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=ANSI_RE.lastIndex;continue}if(CONTROL_RE.lastIndex=index,CONTROL_RE.test(input)){if(lengthExtra=CONTROL_RE.lastIndex-index,widthExtra=lengthExtra*CONTROL_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index+Math.floor((truncationLimit-width)/CONTROL_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=CONTROL_RE.lastIndex;continue}if(TAB_RE.lastIndex=index,TAB_RE.test(input)){if(lengthExtra=TAB_RE.lastIndex-index,widthExtra=lengthExtra*TAB_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index+Math.floor((truncationLimit-width)/TAB_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=TAB_RE.lastIndex;continue}if(EMOJI_RE.lastIndex=index,EMOJI_RE.test(input)){if(width+EMOJI_WIDTH>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index)),width+EMOJI_WIDTH>LIMIT){truncationEnabled=!0;break}width+=EMOJI_WIDTH,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=EMOJI_RE.lastIndex;continue}index+=1}return{width:truncationEnabled?truncationLimit:width,index:truncationEnabled?truncationIndex:length,truncated:truncationEnabled,ellipsed:truncationEnabled&&LIMIT>=ELLIPSIS_WIDTH}},"getStringTruncatedWidth"),dist_default=getStringTruncatedWidth;var NO_TRUNCATION2={limit:1/0,ellipsis:"",ellipsisWidth:0},fastStringWidth=__name((input,options={})=>dist_default(input,NO_TRUNCATION2,options).width,"fastStringWidth"),dist_default2=fastStringWidth;var ESC="\x1B",CSI="\x9B",END_CODE=39,ANSI_ESCAPE_BELL="\x07",ANSI_CSI="[",ANSI_OSC="]",ANSI_SGR_TERMINATOR="m",ANSI_ESCAPE_LINK=`${ANSI_OSC}8;;`,GROUP_REGEX=new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`,"y"),getClosingCode=__name(openingCode=>{if(openingCode>=30&&openingCode<=37||openingCode>=90&&openingCode<=97)return 39;if(openingCode>=40&&openingCode<=47||openingCode>=100&&openingCode<=107)return 49;if(openingCode===1||openingCode===2)return 22;if(openingCode===3)return 23;if(openingCode===4)return 24;if(openingCode===7)return 27;if(openingCode===8)return 28;if(openingCode===9)return 29;if(openingCode===0)return 0},"getClosingCode"),wrapAnsiCode=__name(code2=>`${ESC}${ANSI_CSI}${code2}${ANSI_SGR_TERMINATOR}`,"wrapAnsiCode"),wrapAnsiHyperlink=__name(url=>`${ESC}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`,"wrapAnsiHyperlink"),wrapWord=__name((rows,word,columns)=>{let characters=word[Symbol.iterator](),isInsideEscape=!1,isInsideLinkEscape=!1,lastRow=rows.at(-1),visible=lastRow===void 0?0:dist_default2(lastRow),currentCharacter=characters.next(),nextCharacter=characters.next(),rawCharacterIndex=0;for(;!currentCharacter.done;){let character=currentCharacter.value,characterLength=dist_default2(character);visible+characterLength<=columns?rows[rows.length-1]+=character:(rows.push(character),visible=0),(character===ESC||character===CSI)&&(isInsideEscape=!0,isInsideLinkEscape=word.startsWith(ANSI_ESCAPE_LINK,rawCharacterIndex+1)),isInsideEscape?isInsideLinkEscape?character===ANSI_ESCAPE_BELL&&(isInsideEscape=!1,isInsideLinkEscape=!1):character===ANSI_SGR_TERMINATOR&&(isInsideEscape=!1):(visible+=characterLength,visible===columns&&!nextCharacter.done&&(rows.push(""),visible=0)),currentCharacter=nextCharacter,nextCharacter=characters.next(),rawCharacterIndex+=character.length}lastRow=rows.at(-1),!visible&&lastRow!==void 0&&lastRow.length&&rows.length>1&&(rows[rows.length-2]+=rows.pop())},"wrapWord"),stringVisibleTrimSpacesRight=__name(string=>{let words=string.split(" "),last=words.length;for(;last&&!dist_default2(words[last-1]);)last--;return last===words.length?string:words.slice(0,last).join(" ")+words.slice(last).join("")},"stringVisibleTrimSpacesRight"),exec=__name((string,columns,options={})=>{if(options.trim!==!1&&string.trim()==="")return"";let returnValue="",escapeCode,escapeUrl,words=string.split(" "),rows=[""],rowLength=0;for(let index=0;index<words.length;index++){let word=words[index];if(options.trim!==!1){let row2=rows.at(-1)??"",trimmed=row2.trimStart();row2.length!==trimmed.length&&(rows[rows.length-1]=trimmed,rowLength=dist_default2(trimmed))}index!==0&&(rowLength>=columns&&(options.wordWrap===!1||options.trim===!1)&&(rows.push(""),rowLength=0),(rowLength||options.trim===!1)&&(rows[rows.length-1]+=" ",rowLength++));let wordLength=dist_default2(word);if(options.hard&&wordLength>columns){let remainingColumns=columns-rowLength,breaksStartingThisLine=1+Math.floor((wordLength-remainingColumns-1)/columns);Math.floor((wordLength-1)/columns)<breaksStartingThisLine&&rows.push(""),wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}if(rowLength+wordLength>columns&&rowLength&&wordLength){if(options.wordWrap===!1&&rowLength<columns){wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}rows.push(""),rowLength=0}if(rowLength+wordLength>columns&&options.wordWrap===!1){wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}rows[rows.length-1]+=word,rowLength+=wordLength}options.trim!==!1&&(rows=rows.map(row2=>stringVisibleTrimSpacesRight(row2)));let preString=rows.join(`
|
|
424
|
+
${environmentStatus}`},"render")})}var SOFT_TIMEOUT_MS,init_status=__esm({"src/cli/commands/status.ts"(){init_dist();init_config();init_sdk_transport();init_project_services();init_branch_checkout();init_color();init_render_status();init_git_credential_setup();init_git();init_project_context();init_project();SOFT_TIMEOUT_MS=2e3;__name(withCheckoutRecovery,"withCheckoutRecovery");__name(localCheckoutStatus,"localCheckoutStatus");__name(renderLocalCheckoutStatus,"renderLocalCheckoutStatus");__name(pickSurfaces,"pickSurfaces");__name(withSoftTimeout,"withSoftTimeout");__name(localCodeSurface,"localCodeSurface");__name(mergeCodeSurfaces,"mergeCodeSurfaces");__name(statusCommand2,"statusCommand")}});init_esm();init_dist();import fs48 from"node:fs";import path48 from"node:path";var import_index=__toESM(require_commander(),1),{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import_index.default;init_auth();init_esm();init_dist();init_project_context();function parseRangeOptions(options){let params={};if(options.preset&&(params.preset=options.preset),options.groupBy&&(params.groupBy=options.groupBy),options.from&&(params.from=options.from),options.to&&(params.to=options.to),options.device&&(params.device=options.device),options.days!==void 0){let n=Number(options.days);if(!Number.isFinite(n))throw new Error(`Invalid --days value: ${options.days}`);params.days=n}return params}__name(parseRangeOptions,"parseRangeOptions");function renderPrettyJson(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson,"renderPrettyJson");async function analyticsPageviewsCommand(options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{defaultBranch:PRODUCTION_BRANCH}),{data:result}=await fimo.execute("analytics.pageviews",{projectId:ctx.projectId,branch:ctx.branch,...parseRangeOptions(options)});ui.result({command:"analytics pageviews",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsPageviewsCommand,"analyticsPageviewsCommand");var TOP_DIMENSIONS=["pages","browsers","devices","countries","sources"];async function analyticsTopCommand(dimension,options,cmd){if(!TOP_DIMENSIONS.includes(dimension))throw new Error(`Unknown dimension: ${dimension}. Expected one of: ${TOP_DIMENSIONS.join(", ")}`);let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{defaultBranch:PRODUCTION_BRANCH}),{items,branch}=await fimo.execute("analytics.top",{projectId:ctx.projectId,branch:ctx.branch,dimension,...parseRangeOptions(options)}),limit;if(options.limit!==void 0){let n=Number(options.limit);if(!Number.isFinite(n)||n<1)throw new Error(`Invalid --limit value: ${options.limit}`);limit=n}let trimmed=limit!==void 0?items.slice(0,limit):items;ui.result({command:"analytics top",data:{branch,dimension,items:trimmed},render:__name(()=>renderPrettyJson(trimmed),"render")})}__name(analyticsTopCommand,"analyticsTopCommand");async function analyticsAnnotationsListCommand(options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{defaultBranch:PRODUCTION_BRANCH}),{annotations:annotations2,branch}=await fimo.execute("analytics.annotationsList",{projectId:ctx.projectId,branch:ctx.branch,...parseRangeOptions(options)});ui.result({command:"analytics annotations list",data:{branch,annotations:annotations2},render:__name(()=>renderPrettyJson(annotations2),"render")})}__name(analyticsAnnotationsListCommand,"analyticsAnnotationsListCommand");async function analyticsAnnotationsSetCommand(date,content2,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd),result=(await fimo.execute("analytics.annotationsSet",{projectId:ctx.projectId,branch:ctx.branch,date,content:content2}))?.data??null;ui.result({command:"analytics annotations set",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsAnnotationsSetCommand,"analyticsAnnotationsSetCommand");async function analyticsAnnotationsDeleteCommand(date,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await fimo.execute("analytics.annotationsDelete",{projectId:ctx.projectId,branch:ctx.branch,date}),ui.ok({command:"analytics annotations delete",headline:`Deleted annotation for ${date}.`,details:{date}})}__name(analyticsAnnotationsDeleteCommand,"analyticsAnnotationsDeleteCommand");init_dist();import{spawn}from"node:child_process";import{mkdirSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{dirname,extname,isAbsolute,join as join2,resolve as resolvePath}from"node:path";var import_yaml=__toESM(require_dist(),1);import{z as z110}from"zod";var CapabilityTokenSchema=z110.string().min(1).regex(/^(?:[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?|[a-z][a-z0-9_]*:\*)$/,{error:"capabilities must be an exact token or namespace selector such as cms:* (lowercase + digits + underscores)"}),CapabilitiesFileSchema=z110.array(CapabilityTokenSchema);import{z as z111}from"zod";var CronTriggerSchema=z111.object({type:z111.literal("schedule"),cron:z111.string().min(1,"cron expression required"),tz:z111.string().optional()}),ManualTriggerSchema=z111.object({type:z111.literal("manual")}),WebhookTriggerSchema=z111.object({type:z111.literal("webhook"),path:z111.string().min(1).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z111.discriminatedUnion("type",[ManualTriggerSchema,CronTriggerSchema,WebhookTriggerSchema]),SubAgentRefSchema=z111.object({name:z111.string().min(1),capability_grant:z111.enum(["inherit","explicit"]).optional(),explicit_grants:z111.array(z111.string()).optional()}).refine(v=>v.capability_grant!=="explicit"||Array.isArray(v.explicit_grants)&&v.explicit_grants.length>0,{message:"`explicit_grants` is required when `capability_grant: explicit`",path:["explicit_grants"]}),CompositionConfigSchema=z111.object({"sub-agents":z111.array(SubAgentRefSchema)}),RuntimeConfigSchema=z111.object({cloud:z111.boolean().optional(),dev:z111.boolean().optional(),max_credits:z111.number().int().min(1).optional(),max_steps:z111.number().int().min(1).optional()}),DataSourceSchema=z111.enum(["main","prod"]),ConfigValueKeySchema=z111.string().min(1).max(255).regex(/^[A-Z_][A-Z0-9_]*$/,"secret keys must be UPPER_SNAKE_CASE and start with a letter or underscore"),PUBLIC_CONFIG_PREFIX=/^(PUBLIC_|VITE_|NEXT_PUBLIC_)/,AgentSecretRequestSchema=z111.preprocess(value=>typeof value=="string"?{key:value}:value,z111.object({key:ConfigValueKeySchema.refine(key=>!PUBLIC_CONFIG_PREFIX.test(key),{message:"agent secrets cannot use public variable prefixes (PUBLIC_, VITE_, NEXT_PUBLIC_)"}),required:z111.boolean().default(!0),delivery:z111.literal("process_env").default("process_env")})),IntegrationKeySchema=z111.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*$/,"integration keys must be lowercase alphanumeric with optional _ or -"),IntegrationToolKeySchema=z111.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)*$/,"integration tool keys must be lowercase dot-separated identifiers with optional _ or -"),IntegrationPolicyEntrySchema=z111.preprocess(value=>typeof value=="boolean"?{enabled:value}:value,z111.object({enabled:z111.boolean().default(!0),tools:z111.record(IntegrationToolKeySchema,z111.boolean()).optional()})),IntegrationPolicySchema=z111.record(IntegrationKeySchema,IntegrationPolicyEntrySchema),AgentConfigSchema=z111.object({version:z111.literal(1),description:z111.string().min(1).max(280).optional(),model:z111.string().trim().min(1).max(255).optional(),runtime:RuntimeConfigSchema.optional(),triggers:z111.array(TriggerSchema).optional(),composition:CompositionConfigSchema.optional(),data_sources:z111.array(DataSourceSchema).optional(),secrets:z111.array(AgentSecretRequestSchema).optional(),integrations:IntegrationPolicySchema.optional(),integration_policy:IntegrationPolicySchema.optional()}).refine(config=>!(config.integrations&&config.integration_policy),{message:"use either `integrations` or legacy `integration_policy`, not both",path:["integrations"]});var ENTRIES=[{token:"knowledge:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read private project goals, brand guidance and rules"},{token:"knowledge:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Update shared project knowledge only when explicitly requested"},{token:"files:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read project files"},{token:"files:write",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Write or delete project files"},{token:"cms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS content"},{token:"cms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Create, update, or delete CMS entries"},{token:"cms:schema:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read CMS schemas"},{token:"cms:schema:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Modify CMS schemas (destructive \u2014 alters all entries of the type)"},{token:"assets:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read uploaded media"},{token:"assets:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Upload, replace, or delete media"},{token:"i18n:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read translation catalogs"},{token:"i18n:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify translation catalogs via the fimo i18n CLI"},{token:"forms:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read form schemas and submissions"},{token:"forms:write",risk:"medium",declarable:!0,enforcedBy:"api",description:"Modify form schemas or clear submissions"},{token:"webhooks:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read webhook configurations and delivery history"},{token:"webhooks:write",risk:"high",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger webhooks that send project data to external URLs"},{token:"schedules:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read schedule configurations and run history"},{token:"schedules:write",risk:"critical",declarable:!0,enforcedBy:"api",description:"Create, modify, delete, or trigger scheduled commands that run with publish and code-edit rights"},{token:"git:read",risk:"low",declarable:!1,enforcedBy:"runtime",description:"Read git state"},{token:"git:branch",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Create agent-proposed branches off main"},{token:"git:commit",risk:"medium",declarable:!1,enforcedBy:"runtime",description:"Commit changes to an agent branch"},{token:"git:push",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Push to the project remote (main push is intercepted)"},{token:"git:tag",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Used by runtime for prod release tags; agents cannot call directly"},{token:"fimo:deploy",risk:"critical",declarable:!0,enforcedBy:"api",description:"Trigger a production deploy"},{token:"fimo:logs:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project deployment logs"},{token:"fimo:analytics:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read analytics data"},{token:"fimo:domains:manage",risk:"high",declarable:!0,enforcedBy:"api",description:"Read and manage project domains"},{token:"fimo:agents:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run project agents"},{token:"fimo:preview:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read a current preview URL for an env (no commit, no deploy)"},{token:"fimo:history:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project restore points"},{token:"integrations:run",risk:"high",declarable:!0,enforcedBy:"api",description:"Run enabled project integration tools allowed by the agent policy"},{token:"shell:exec",risk:"high",declarable:!1,enforcedBy:"runtime",description:"Run arbitrary shell commands inside the sandbox"},{token:"agent:delegate",risk:"medium",declarable:!0,enforcedBy:"engine",description:"Invoke declared sub-agents"},{token:"runtime:auto_merge",risk:"critical",declarable:!0,enforcedBy:"runtime",description:"Merge work sessions into their target Branch without per-change human review"}],BY_TOKEN=new Map(ENTRIES.map(entry=>[entry.token,entry])),CAPABILITY_VOCABULARY=ENTRIES;function getCapability(token){return BY_TOKEN.get(token)??null}__name(getCapability,"getCapability");import{z as z112}from"zod";var SurfaceGuardPolicySchema=z112.enum(["block","warn","allow"]),ClassificationSchema=z112.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z112.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z112.object({enabled:z112.boolean(),allowed_skills:z112.array(z112.string().min(1)).default([]),allowed_classifications:z112.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z112.enum(["off","daily","weekly"]),NotificationFormatSchema=z112.object({markdown:z112.boolean().default(!0),html:z112.boolean().default(!1)}),NotificationsPolicySchema=z112.object({email_recipients:z112.array(z112.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z112.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z112.object({agents:FimoAgentsConfigSchema.optional()}).passthrough();import{z as z113}from"zod";function toSpec(def){return{token:def.token,riskTier:def.risk,description:def.description}}__name(toSpec,"toSpec");var VOCABULARY=Object.freeze(Object.fromEntries(CAPABILITY_VOCABULARY.filter(definition=>definition.declarable).map(definition=>[definition.token,toSpec(definition)]))),CapabilityToken=z113.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z113.array(CapabilityToken);var RUNTIME_BASELINE_OPERATION_CAPABILITIES=["files:read","files:write"];function isRuntimeBaselineOperationCapability(capability){return RUNTIME_BASELINE_OPERATION_CAPABILITIES.includes(capability)}__name(isRuntimeBaselineOperationCapability,"isRuntimeBaselineOperationCapability");var OPERATION_CAP={"knowledge.get":"knowledge:read","knowledge.update":"knowledge:write","cms.list":"cms:read","cms.get":"cms:read","cms.query":"cms:read","cms.create":"cms:write","cms.update":"cms:write","cms.delete":"cms:write","cms.bulk_create":"cms:write","cms.bulk_update":"cms:write","cms.bulk_delete":"cms:write","cms.schema.list":"cms:schema:read","cms.schema.get":"cms:schema:read","cms.schema.push":"cms:schema:write","cms.schema.delete":"cms:schema:write","assets.list":"assets:read","assets.get":"assets:read","assets.read":"assets:read","assets.upload":"assets:write","assets.generate":"assets:write","assets.create_folder":"assets:write","assets.move":"assets:write","assets.delete":"assets:write","i18n.list":"i18n:read","i18n.get":"i18n:read","i18n.create":"i18n:write","i18n.update":"i18n:write","i18n.delete":"i18n:write","forms.list":"forms:read","forms.get":"forms:read","forms.push":"forms:write","forms.delete":"forms:write","webhooks.events":"webhooks:read","webhooks.list":"webhooks:read","webhooks.get":"webhooks:read","webhooks.deliveries.list":"webhooks:read","webhooks.deliveries.get":"webhooks:read","webhooks.create":"webhooks:write","webhooks.update":"webhooks:write","webhooks.delete":"webhooks:write","webhooks.test":"webhooks:write","webhooks.deliveries.retry":"webhooks:write","webhooks.rotate_secret":"webhooks:write","schedules.list":"schedules:read","schedules.get":"schedules:read","schedules.runs.list":"schedules:read","schedules.runs.get":"schedules:read","schedules.create":"schedules:write","schedules.update":"schedules:write","schedules.delete":"schedules:write","schedules.pause":"schedules:write","schedules.resume":"schedules:write","schedules.run":"schedules:write","files.read":"files:read","files.write":"files:write","fimo.deploy":"fimo:deploy","fimo.logs.read":"fimo:logs:read","fimo.analytics.read":"fimo:analytics:read","fimo.preview.url":"fimo:preview:read","fimo.history.list":"fimo:history:read","fimo.history.get":"fimo:history:read","agent.delegate":"agent:delegate","runtime.auto_merge":"runtime:auto_merge"};function capabilityFor(op){return OPERATION_CAP[op]}__name(capabilityFor,"capabilityFor");function hasOperation(op){return Object.prototype.hasOwnProperty.call(OPERATION_CAP,op)}__name(hasOperation,"hasOperation");var import_yaml2=__toESM(require_dist(),1);function _define_property(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property,"_define_property");var CapabilityDenied=class extends Error{static{__name(this,"CapabilityDenied")}constructor(detail){let def=getCapability(detail.cap),description=def?.description?` (${def.description})`:"";super(`capability denied: ${detail.cap}${description} \u2014 reason: ${detail.reason}`),_define_property(this,"cap",void 0),_define_property(this,"reason",void 0),_define_property(this,"granted",void 0),_define_property(this,"sessionId",void 0),_define_property(this,"fixHint",void 0),this.name="CapabilityDenied",this.cap=detail.cap,this.reason=detail.reason,this.granted=detail.granted??[],this.sessionId=detail.sessionId,this.fixHint=fixHintFor(detail)}};function fixHintFor(detail){switch(detail.reason){case"not-declared":return`Add '${detail.cap}' to the agent's capabilities.yaml and re-activate.`;case"session-not-found":return`Session '${detail.sessionId??"<unknown>"}' does not exist or has expired.`;case"snapshot-stale":return"Session capability snapshot is corrupted. Restart the agent session.";case"runtime-only":return`'${detail.cap}' is reserved for the platform \u2014 drop it from capabilities.yaml.`;case"auto-merge-blocked":return"runtime:auto_merge is declared but blocked by project policy (.fimo/config.json \u2192 agents.auto_merge)."}}__name(fixHintFor,"fixHintFor");var configured=null;async function auditCapabilityDecision(event){if(!configured)return;let row2={...event,ts:new Date().toISOString()};if(event.decision==="deny"){try{await configured.transport.write(row2)}catch(err){throw configured.breadcrumb?.({category:"audit",level:"error",message:"audit deny row write failed",data:{cap:event.cap,error:err.message}}),err}configured.breadcrumb?.({category:"audit",level:"warning",message:`capability denied: ${event.cap}`,data:{sessionId:event.sessionId,cap:event.cap,reason:event.reason}});return}configured.transport.write(row2).catch(err=>{configured?.breadcrumb?.({category:"audit",level:"warning",message:"audit allow row write failed (best-effort)",data:{cap:event.cap,error:err.message}})})}__name(auditCapabilityDecision,"auditCapabilityDecision");var ENV_SESSION="FIMO_AGENT_SESSION",ENV_CAPS_FALLBACK="FIMO_AGENT_CAPABILITIES";function currentAgentSession(){let id=process.env[ENV_SESSION];return id&&id.length>0?id:void 0}__name(currentAgentSession,"currentAgentSession");async function defaultFetchSessionCapabilities(_sessionId){let raw=process.env[ENV_CAPS_FALLBACK];return raw?raw.split(",").map(s=>s.trim()).filter(s=>s.length>0):[]}__name(defaultFetchSessionCapabilities,"defaultFetchSessionCapabilities");async function requireCapability(cap,ctx={}){let sessionId=currentAgentSession();if(!sessionId)return{ok:!0,bypassed:!0};let granted=await(ctx.fetchSessionCapabilities??defaultFetchSessionCapabilities)(sessionId);if(!granted.includes(cap)){try{await auditCapabilityDecision({sessionId,cap,decision:"deny",reason:granted.length===0?"session-not-found":"not-declared",projectId:ctx.projectId,env:ctx.branch})}catch{}throw new CapabilityDenied({cap,reason:granted.length===0?"session-not-found":"not-declared",granted,sessionId})}return auditCapabilityDecision({sessionId,cap,decision:"allow",projectId:ctx.projectId,env:ctx.branch}),{ok:!0,bypassed:!1}}__name(requireCapability,"requireCapability");async function requireOperation(op,ctx={}){if(!hasOperation(op))throw new Error(`requireOperation: unknown operation id '${op}' \u2014 register it in @fimo/agents capabilities/operation-map.ts`);let cap=capabilityFor(op);return isRuntimeBaselineOperationCapability(cap)?{ok:!0,bypassed:currentAgentSession()===void 0}:requireCapability(cap,ctx)}__name(requireOperation,"requireOperation");init_project_context();init_project();function extensionFor(asset){let fromName=extname(asset.name);if(fromName&&fromName.length<=6)return fromName;let mime=asset.mimeType??"";return mime.startsWith("image/")?"."+(mime.split("/")[1]??"bin"):mime.startsWith("video/")?"."+(mime.split("/")[1]??"mp4"):mime.startsWith("audio/")?"."+(mime.split("/")[1]??"mp3"):""}__name(extensionFor,"extensionFor");function defaultDownloadPath(asset){let ext=extensionFor(asset);return join2(tmpdir(),"fimo-assets",`${asset.id}${ext}`)}__name(defaultDownloadPath,"defaultDownloadPath");async function downloadToPath(url,dest){let response=await fetch(url);if(!response.ok)throw new Error(`Failed to download asset: HTTP ${response.status} ${response.statusText}`);let arrayBuffer=await response.arrayBuffer();mkdirSync(dirname(dest),{recursive:!0}),writeFileSync(dest,new Uint8Array(arrayBuffer))}__name(downloadToPath,"downloadToPath");function spawnBrowser(url){let command=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(process.platform==="win32"?spawn("cmd",["/c","start","",url],{detached:!0,stdio:"ignore"}):spawn(command,[url],{detached:!0,stdio:"ignore"})).unref()}__name(spawnBrowser,"spawnBrowser");function renderPrettyJson2(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson2,"renderPrettyJson");async function assetsOpenCommand(id,options,cmd){if(options.download&&options.browser)throw new Error("--download and --browser are mutually exclusive \u2014 pick one");let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.get",{projectId:ctx.projectId,branch:ctx.branch});let cwd=resolveProjectCwd(options.cwd),{data:asset}=await fimo.execute("assets.get",{projectId:ctx.projectId,branch:ctx.branch,id});if(asset.type==="folder")throw new Error(`Asset ${id} is a folder; can only open files`);if(!asset.url)throw new Error(`Asset ${id} has no public URL \u2014 it may not have finished uploading`);if(options.browser){spawnBrowser(asset.url);let payload2={opened:asset.url};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}if(options.download){let dest=options.path?isAbsolute(options.path)?options.path:resolvePath(cwd,options.path):defaultDownloadPath(asset);await downloadToPath(asset.url,dest);let payload2={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,path:dest,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,aiAltText:asset.aiAltText??null};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}let payload={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,caption:asset.caption??null,aiAltText:asset.aiAltText??null,aiCaption:asset.aiCaption??null,aiTags:asset.aiTags??null};ui.result({command:"assets open",data:payload,render:__name(()=>renderPrettyJson2(payload),"render")})}__name(assetsOpenCommand,"assetsOpenCommand");import fs7 from"node:fs";import path7 from"node:path";import{styleText as y}from"node:util";import{stdout as S,stdin as $}from"node:process";import P from"node:readline";var isAmbiguous=__name(x=>x===161||x===164||x===167||x===168||x===170||x===173||x===174||x>=176&&x<=180||x>=182&&x<=186||x>=188&&x<=191||x===198||x===208||x===215||x===216||x>=222&&x<=225||x===230||x>=232&&x<=234||x===236||x===237||x===240||x===242||x===243||x>=247&&x<=250||x===252||x===254||x===257||x===273||x===275||x===283||x===294||x===295||x===299||x>=305&&x<=307||x===312||x>=319&&x<=322||x===324||x>=328&&x<=331||x===333||x===338||x===339||x===358||x===359||x===363||x===462||x===464||x===466||x===468||x===470||x===472||x===474||x===476||x===593||x===609||x===708||x===711||x>=713&&x<=715||x===717||x===720||x>=728&&x<=731||x===733||x===735||x>=768&&x<=879||x>=913&&x<=929||x>=931&&x<=937||x>=945&&x<=961||x>=963&&x<=969||x===1025||x>=1040&&x<=1103||x===1105||x===8208||x>=8211&&x<=8214||x===8216||x===8217||x===8220||x===8221||x>=8224&&x<=8226||x>=8228&&x<=8231||x===8240||x===8242||x===8243||x===8245||x===8251||x===8254||x===8308||x===8319||x>=8321&&x<=8324||x===8364||x===8451||x===8453||x===8457||x===8467||x===8470||x===8481||x===8482||x===8486||x===8491||x===8531||x===8532||x>=8539&&x<=8542||x>=8544&&x<=8555||x>=8560&&x<=8569||x===8585||x>=8592&&x<=8601||x===8632||x===8633||x===8658||x===8660||x===8679||x===8704||x===8706||x===8707||x===8711||x===8712||x===8715||x===8719||x===8721||x===8725||x===8730||x>=8733&&x<=8736||x===8739||x===8741||x>=8743&&x<=8748||x===8750||x>=8756&&x<=8759||x===8764||x===8765||x===8776||x===8780||x===8786||x===8800||x===8801||x>=8804&&x<=8807||x===8810||x===8811||x===8814||x===8815||x===8834||x===8835||x===8838||x===8839||x===8853||x===8857||x===8869||x===8895||x===8978||x>=9312&&x<=9449||x>=9451&&x<=9547||x>=9552&&x<=9587||x>=9600&&x<=9615||x>=9618&&x<=9621||x===9632||x===9633||x>=9635&&x<=9641||x===9650||x===9651||x===9654||x===9655||x===9660||x===9661||x===9664||x===9665||x>=9670&&x<=9672||x===9675||x>=9678&&x<=9681||x>=9698&&x<=9701||x===9711||x===9733||x===9734||x===9737||x===9742||x===9743||x===9756||x===9758||x===9792||x===9794||x===9824||x===9825||x>=9827&&x<=9829||x>=9831&&x<=9834||x===9836||x===9837||x===9839||x===9886||x===9887||x===9919||x>=9926&&x<=9933||x>=9935&&x<=9939||x>=9941&&x<=9953||x===9955||x===9960||x===9961||x>=9963&&x<=9969||x===9972||x>=9974&&x<=9977||x===9979||x===9980||x===9982||x===9983||x===10045||x>=10102&&x<=10111||x>=11094&&x<=11097||x>=12872&&x<=12879||x>=57344&&x<=63743||x>=65024&&x<=65039||x===65533||x>=127232&&x<=127242||x>=127248&&x<=127277||x>=127280&&x<=127337||x>=127344&&x<=127373||x===127375||x===127376||x>=127387&&x<=127404||x>=917760&&x<=917999||x>=983040&&x<=1048573||x>=1048576&&x<=1114109,"isAmbiguous"),isFullWidth=__name(x=>x===12288||x>=65281&&x<=65376||x>=65504&&x<=65510,"isFullWidth"),isWide=__name(x=>x>=4352&&x<=4447||x===8986||x===8987||x===9001||x===9002||x>=9193&&x<=9196||x===9200||x===9203||x===9725||x===9726||x===9748||x===9749||x>=9800&&x<=9811||x===9855||x===9875||x===9889||x===9898||x===9899||x===9917||x===9918||x===9924||x===9925||x===9934||x===9940||x===9962||x===9970||x===9971||x===9973||x===9978||x===9981||x===9989||x===9994||x===9995||x===10024||x===10060||x===10062||x>=10067&&x<=10069||x===10071||x>=10133&&x<=10135||x===10160||x===10175||x===11035||x===11036||x===11088||x===11093||x>=11904&&x<=11929||x>=11931&&x<=12019||x>=12032&&x<=12245||x>=12272&&x<=12287||x>=12289&&x<=12350||x>=12353&&x<=12438||x>=12441&&x<=12543||x>=12549&&x<=12591||x>=12593&&x<=12686||x>=12688&&x<=12771||x>=12783&&x<=12830||x>=12832&&x<=12871||x>=12880&&x<=19903||x>=19968&&x<=42124||x>=42128&&x<=42182||x>=43360&&x<=43388||x>=44032&&x<=55203||x>=63744&&x<=64255||x>=65040&&x<=65049||x>=65072&&x<=65106||x>=65108&&x<=65126||x>=65128&&x<=65131||x>=94176&&x<=94180||x===94192||x===94193||x>=94208&&x<=100343||x>=100352&&x<=101589||x>=101632&&x<=101640||x>=110576&&x<=110579||x>=110581&&x<=110587||x===110589||x===110590||x>=110592&&x<=110882||x===110898||x>=110928&&x<=110930||x===110933||x>=110948&&x<=110951||x>=110960&&x<=111355||x===126980||x===127183||x===127374||x>=127377&&x<=127386||x>=127488&&x<=127490||x>=127504&&x<=127547||x>=127552&&x<=127560||x===127568||x===127569||x>=127584&&x<=127589||x>=127744&&x<=127776||x>=127789&&x<=127797||x>=127799&&x<=127868||x>=127870&&x<=127891||x>=127904&&x<=127946||x>=127951&&x<=127955||x>=127968&&x<=127984||x===127988||x>=127992&&x<=128062||x===128064||x>=128066&&x<=128252||x>=128255&&x<=128317||x>=128331&&x<=128334||x>=128336&&x<=128359||x===128378||x===128405||x===128406||x===128420||x>=128507&&x<=128591||x>=128640&&x<=128709||x===128716||x>=128720&&x<=128722||x>=128725&&x<=128727||x>=128732&&x<=128735||x===128747||x===128748||x>=128756&&x<=128764||x>=128992&&x<=129003||x===129008||x>=129292&&x<=129338||x>=129340&&x<=129349||x>=129351&&x<=129535||x>=129648&&x<=129660||x>=129664&&x<=129672||x>=129680&&x<=129725||x>=129727&&x<=129733||x>=129742&&x<=129755||x>=129760&&x<=129768||x>=129776&&x<=129784||x>=131072&&x<=196605||x>=196608&&x<=262141,"isWide");var ANSI_RE=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,CONTROL_RE=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,TAB_RE=/\t{1,1000}/y,EMOJI_RE=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),LATIN_RE=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,MODIFIER_RE=new RegExp("\\p{M}+","gu"),NO_TRUNCATION={limit:1/0,ellipsis:""},getStringTruncatedWidth=__name((input,truncationOptions={},widthOptions={})=>{let LIMIT=truncationOptions.limit??1/0,ELLIPSIS=truncationOptions.ellipsis??"",ELLIPSIS_WIDTH=truncationOptions?.ellipsisWidth??(ELLIPSIS?getStringTruncatedWidth(ELLIPSIS,NO_TRUNCATION,widthOptions).width:0),ANSI_WIDTH=widthOptions.ansiWidth??0,CONTROL_WIDTH=widthOptions.controlWidth??0,TAB_WIDTH=widthOptions.tabWidth??8,AMBIGUOUS_WIDTH=widthOptions.ambiguousWidth??1,EMOJI_WIDTH=widthOptions.emojiWidth??2,FULL_WIDTH_WIDTH=widthOptions.fullWidthWidth??2,REGULAR_WIDTH=widthOptions.regularWidth??1,WIDE_WIDTH=widthOptions.wideWidth??2,indexPrev=0,index=0,length=input.length,lengthExtra=0,truncationEnabled=!1,truncationIndex=length,truncationLimit=Math.max(0,LIMIT-ELLIPSIS_WIDTH),unmatchedStart=0,unmatchedEnd=0,width=0,widthExtra=0;outer:for(;;){if(unmatchedEnd>unmatchedStart||index>=length&&index>indexPrev){let unmatched=input.slice(unmatchedStart,unmatchedEnd)||input.slice(indexPrev,index);lengthExtra=0;for(let char of unmatched.replaceAll(MODIFIER_RE,"")){let codePoint=char.codePointAt(0)||0;if(isFullWidth(codePoint)?widthExtra=FULL_WIDTH_WIDTH:isWide(codePoint)?widthExtra=WIDE_WIDTH:AMBIGUOUS_WIDTH!==REGULAR_WIDTH&&isAmbiguous(codePoint)?widthExtra=AMBIGUOUS_WIDTH:widthExtra=REGULAR_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,Math.max(unmatchedStart,indexPrev)+lengthExtra)),width+widthExtra>LIMIT){truncationEnabled=!0;break outer}lengthExtra+=char.length,width+=widthExtra}unmatchedStart=unmatchedEnd=0}if(index>=length)break;if(LATIN_RE.lastIndex=index,LATIN_RE.test(input)){if(lengthExtra=LATIN_RE.lastIndex-index,widthExtra=lengthExtra*REGULAR_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index+Math.floor((truncationLimit-width)/REGULAR_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=LATIN_RE.lastIndex;continue}if(ANSI_RE.lastIndex=index,ANSI_RE.test(input)){if(width+ANSI_WIDTH>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index)),width+ANSI_WIDTH>LIMIT){truncationEnabled=!0;break}width+=ANSI_WIDTH,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=ANSI_RE.lastIndex;continue}if(CONTROL_RE.lastIndex=index,CONTROL_RE.test(input)){if(lengthExtra=CONTROL_RE.lastIndex-index,widthExtra=lengthExtra*CONTROL_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index+Math.floor((truncationLimit-width)/CONTROL_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=CONTROL_RE.lastIndex;continue}if(TAB_RE.lastIndex=index,TAB_RE.test(input)){if(lengthExtra=TAB_RE.lastIndex-index,widthExtra=lengthExtra*TAB_WIDTH,width+widthExtra>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index+Math.floor((truncationLimit-width)/TAB_WIDTH))),width+widthExtra>LIMIT){truncationEnabled=!0;break}width+=widthExtra,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=TAB_RE.lastIndex;continue}if(EMOJI_RE.lastIndex=index,EMOJI_RE.test(input)){if(width+EMOJI_WIDTH>truncationLimit&&(truncationIndex=Math.min(truncationIndex,index)),width+EMOJI_WIDTH>LIMIT){truncationEnabled=!0;break}width+=EMOJI_WIDTH,unmatchedStart=indexPrev,unmatchedEnd=index,index=indexPrev=EMOJI_RE.lastIndex;continue}index+=1}return{width:truncationEnabled?truncationLimit:width,index:truncationEnabled?truncationIndex:length,truncated:truncationEnabled,ellipsed:truncationEnabled&&LIMIT>=ELLIPSIS_WIDTH}},"getStringTruncatedWidth"),dist_default=getStringTruncatedWidth;var NO_TRUNCATION2={limit:1/0,ellipsis:"",ellipsisWidth:0},fastStringWidth=__name((input,options={})=>dist_default(input,NO_TRUNCATION2,options).width,"fastStringWidth"),dist_default2=fastStringWidth;var ESC="\x1B",CSI="\x9B",END_CODE=39,ANSI_ESCAPE_BELL="\x07",ANSI_CSI="[",ANSI_OSC="]",ANSI_SGR_TERMINATOR="m",ANSI_ESCAPE_LINK=`${ANSI_OSC}8;;`,GROUP_REGEX=new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`,"y"),getClosingCode=__name(openingCode=>{if(openingCode>=30&&openingCode<=37||openingCode>=90&&openingCode<=97)return 39;if(openingCode>=40&&openingCode<=47||openingCode>=100&&openingCode<=107)return 49;if(openingCode===1||openingCode===2)return 22;if(openingCode===3)return 23;if(openingCode===4)return 24;if(openingCode===7)return 27;if(openingCode===8)return 28;if(openingCode===9)return 29;if(openingCode===0)return 0},"getClosingCode"),wrapAnsiCode=__name(code2=>`${ESC}${ANSI_CSI}${code2}${ANSI_SGR_TERMINATOR}`,"wrapAnsiCode"),wrapAnsiHyperlink=__name(url=>`${ESC}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`,"wrapAnsiHyperlink"),wrapWord=__name((rows,word,columns)=>{let characters=word[Symbol.iterator](),isInsideEscape=!1,isInsideLinkEscape=!1,lastRow=rows.at(-1),visible=lastRow===void 0?0:dist_default2(lastRow),currentCharacter=characters.next(),nextCharacter=characters.next(),rawCharacterIndex=0;for(;!currentCharacter.done;){let character=currentCharacter.value,characterLength=dist_default2(character);visible+characterLength<=columns?rows[rows.length-1]+=character:(rows.push(character),visible=0),(character===ESC||character===CSI)&&(isInsideEscape=!0,isInsideLinkEscape=word.startsWith(ANSI_ESCAPE_LINK,rawCharacterIndex+1)),isInsideEscape?isInsideLinkEscape?character===ANSI_ESCAPE_BELL&&(isInsideEscape=!1,isInsideLinkEscape=!1):character===ANSI_SGR_TERMINATOR&&(isInsideEscape=!1):(visible+=characterLength,visible===columns&&!nextCharacter.done&&(rows.push(""),visible=0)),currentCharacter=nextCharacter,nextCharacter=characters.next(),rawCharacterIndex+=character.length}lastRow=rows.at(-1),!visible&&lastRow!==void 0&&lastRow.length&&rows.length>1&&(rows[rows.length-2]+=rows.pop())},"wrapWord"),stringVisibleTrimSpacesRight=__name(string=>{let words=string.split(" "),last=words.length;for(;last&&!dist_default2(words[last-1]);)last--;return last===words.length?string:words.slice(0,last).join(" ")+words.slice(last).join("")},"stringVisibleTrimSpacesRight"),exec=__name((string,columns,options={})=>{if(options.trim!==!1&&string.trim()==="")return"";let returnValue="",escapeCode,escapeUrl,words=string.split(" "),rows=[""],rowLength=0;for(let index=0;index<words.length;index++){let word=words[index];if(options.trim!==!1){let row2=rows.at(-1)??"",trimmed=row2.trimStart();row2.length!==trimmed.length&&(rows[rows.length-1]=trimmed,rowLength=dist_default2(trimmed))}index!==0&&(rowLength>=columns&&(options.wordWrap===!1||options.trim===!1)&&(rows.push(""),rowLength=0),(rowLength||options.trim===!1)&&(rows[rows.length-1]+=" ",rowLength++));let wordLength=dist_default2(word);if(options.hard&&wordLength>columns){let remainingColumns=columns-rowLength,breaksStartingThisLine=1+Math.floor((wordLength-remainingColumns-1)/columns);Math.floor((wordLength-1)/columns)<breaksStartingThisLine&&rows.push(""),wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}if(rowLength+wordLength>columns&&rowLength&&wordLength){if(options.wordWrap===!1&&rowLength<columns){wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}rows.push(""),rowLength=0}if(rowLength+wordLength>columns&&options.wordWrap===!1){wrapWord(rows,word,columns),rowLength=dist_default2(rows.at(-1)??"");continue}rows[rows.length-1]+=word,rowLength+=wordLength}options.trim!==!1&&(rows=rows.map(row2=>stringVisibleTrimSpacesRight(row2)));let preString=rows.join(`
|
|
425
425
|
`),inSurrogate=!1;for(let i=0;i<preString.length;i++){let character=preString[i];if(returnValue+=character,!inSurrogate)inSurrogate=character>="\uD800"&&character<="\uDBFF";else continue;if(character===ESC||character===CSI){GROUP_REGEX.lastIndex=i+1;let groups=GROUP_REGEX.exec(preString)?.groups;if(groups?.code!==void 0){let code2=Number.parseFloat(groups.code);escapeCode=code2===END_CODE?void 0:code2}else groups?.uri!==void 0&&(escapeUrl=groups.uri.length===0?void 0:groups.uri)}if(preString[i+1]===`
|
|
426
426
|
`){escapeUrl&&(returnValue+=wrapAnsiHyperlink(""));let closingCode=escapeCode?getClosingCode(escapeCode):void 0;escapeCode&&closingCode&&(returnValue+=wrapAnsiCode(closingCode))}else character===`
|
|
427
427
|
`&&(escapeCode&&getClosingCode(escapeCode)&&(returnValue+=wrapAnsiCode(escapeCode)),escapeUrl&&(returnValue+=wrapAnsiHyperlink(escapeUrl)))}return returnValue},"exec"),CRLF_OR_LF=/\r?\n/;function wrapAnsi(string,columns,options){return String(string).normalize().split(CRLF_OR_LF).map(line=>exec(line,columns,options)).join(`
|
|
@@ -434,13 +434,13 @@ ${environmentStatus}`},"render")})}var SOFT_TIMEOUT_MS,init_status=__esm({"src/c
|
|
|
434
434
|
`).length-1;this.output.write(import_sisteransi.cursor.move(-999,t2*-1))}render(){let t2=wrapAnsi(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t2!==this._prevFrame){if(this.state==="initial")this.output.write(import_sisteransi.cursor.hide);else{let e=j(this._prevFrame,t2),s=A(this.output);if(this.restoreCursor(),e){let i=Math.max(0,e.numLinesAfter-s),n=Math.max(0,e.numLinesBefore-s),o=e.lines.find(a=>a>=i);if(o===void 0){this._prevFrame=t2;return}if(e.lines.length===1){this.output.write(import_sisteransi.cursor.move(0,o-n)),this.output.write(import_sisteransi.erase.lines(1));let a=t2.split(`
|
|
435
435
|
`);this.output.write(a[o]),this._prevFrame=t2,this.output.write(import_sisteransi.cursor.move(0,a.length-o-1));return}else if(e.lines.length>1){if(i<n)o=i;else{let h=o-n;h>0&&this.output.write(import_sisteransi.cursor.move(0,h))}this.output.write(import_sisteransi.erase.down());let a=t2.split(`
|
|
436
436
|
`).slice(o);this.output.write(a.join(`
|
|
437
|
-
`)),this._prevFrame=t2;return}}this.output.write(import_sisteransi.erase.down())}this.output.write(t2),this.state==="initial"&&(this.state="active"),this._prevFrame=t2}}};var Q=class extends p{static{__name(this,"Q")}get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t2){super(t2,!1),this.value=!!t2.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",e=>{this.output.write(import_sisteransi.cursor.move(0,-1)),this.value=e,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}};var it=class extends p{static{__name(this,"it")}options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter(t2=>t2.disabled!==!0)}toggleAll(){let t2=this._enabledOptions,e=this.value!==void 0&&this.value.length===t2.length;this.value=e?[]:t2.map(s=>s.value)}toggleInvert(){let t2=this.value;if(!t2)return;let e=this._enabledOptions.filter(s=>!t2.includes(s.value));this.value=e.map(s=>s.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t2=this.value.includes(this._value);this.value=t2?this.value.filter(e=>e!==this._value):[...this.value,this._value]}constructor(t2){super(t2,!1),this.options=t2.options,this.value=[...t2.initialValues??[]];let e=Math.max(this.options.findIndex(({value:s})=>s===t2.cursorAt),0);this.cursor=this.options[e].disabled?d(e,1,this.options):e,this.on("key",s=>{s==="a"&&this.toggleAll(),s==="i"&&this.toggleInvert()}),this.on("cursor",s=>{switch(s){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},rt=class extends p{static{__name(this,"rt")}_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.masked}${y(["inverse","hidden"],"_")}`;let e=this.masked,s=e.slice(0,this.cursor),i=e.slice(this.cursor);return`${s}${y("inverse",i[0])}${i.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:t2,...e}){super(e),this._mask=t2??"\u2022",this.on("userInput",s=>{this._setValue(s)})}},nt=class extends p{static{__name(this,"nt")}options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(t2){super(t2,!1),this.options=t2.options;let e=this.options.findIndex(({value:i})=>i===t2.initialValue),s=e===-1?0:e;this.cursor=this.options[s].disabled?d(s,1,this.options):s,this.changeValue(),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break}this.changeValue()})}};var at=class extends p{static{__name(this,"at")}get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.userInput}\u2588`;let e=t2.slice(0,this.cursor),[s,...i]=t2.slice(this.cursor);return`${e}${y("inverse",s)}${i.join("")}`}get cursor(){return this._cursor}constructor(t2){super({...t2,initialUserInput:t2.initialUserInput??t2.initialValue}),this.on("userInput",e=>{this._setValue(e)}),this.on("finalize",()=>{this.value||(this.value=t2.defaultValue),this.value===void 0&&(this.value="")})}};import{styleText as t,stripVTControlCharacters as ne}from"node:util";import P2 from"node:process";var import_sisteransi2=__toESM(require_src(),1);function Ze(){return P2.platform!=="win32"?P2.env.TERM!=="linux":!!P2.env.CI||!!P2.env.WT_SESSION||!!P2.env.TERMINUS_SUBLIME||P2.env.ConEmuTask==="{cmd::Cmder}"||P2.env.TERM_PROGRAM==="Terminus-Sublime"||P2.env.TERM_PROGRAM==="vscode"||P2.env.TERM==="xterm-256color"||P2.env.TERM==="alacritty"||P2.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}__name(Ze,"Ze");var ee=Ze();var w2=__name((e,i)=>ee?e:i,"w"),_e=w2("\u25C6","*"),oe=w2("\u25A0","x"),ue=w2("\u25B2","x"),F=w2("\u25C7","o"),le=w2("\u250C","T"),d2=w2("\u2502","|"),E2=w2("\u2514","\u2014"),Ie=w2("\u2510","T"),Ee=w2("\u2518","\u2014"),
|
|
437
|
+
`)),this._prevFrame=t2;return}}this.output.write(import_sisteransi.erase.down())}this.output.write(t2),this.state==="initial"&&(this.state="active"),this._prevFrame=t2}}};var Q=class extends p{static{__name(this,"Q")}get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t2){super(t2,!1),this.value=!!t2.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",e=>{this.output.write(import_sisteransi.cursor.move(0,-1)),this.value=e,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}};var it=class extends p{static{__name(this,"it")}options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter(t2=>t2.disabled!==!0)}toggleAll(){let t2=this._enabledOptions,e=this.value!==void 0&&this.value.length===t2.length;this.value=e?[]:t2.map(s=>s.value)}toggleInvert(){let t2=this.value;if(!t2)return;let e=this._enabledOptions.filter(s=>!t2.includes(s.value));this.value=e.map(s=>s.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t2=this.value.includes(this._value);this.value=t2?this.value.filter(e=>e!==this._value):[...this.value,this._value]}constructor(t2){super(t2,!1),this.options=t2.options,this.value=[...t2.initialValues??[]];let e=Math.max(this.options.findIndex(({value:s})=>s===t2.cursorAt),0);this.cursor=this.options[e].disabled?d(e,1,this.options):e,this.on("key",s=>{s==="a"&&this.toggleAll(),s==="i"&&this.toggleInvert()}),this.on("cursor",s=>{switch(s){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},rt=class extends p{static{__name(this,"rt")}_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.masked}${y(["inverse","hidden"],"_")}`;let e=this.masked,s=e.slice(0,this.cursor),i=e.slice(this.cursor);return`${s}${y("inverse",i[0])}${i.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:t2,...e}){super(e),this._mask=t2??"\u2022",this.on("userInput",s=>{this._setValue(s)})}},nt=class extends p{static{__name(this,"nt")}options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(t2){super(t2,!1),this.options=t2.options;let e=this.options.findIndex(({value:i})=>i===t2.initialValue),s=e===-1?0:e;this.cursor=this.options[s].disabled?d(s,1,this.options):s,this.changeValue(),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break}this.changeValue()})}};var at=class extends p{static{__name(this,"at")}get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.userInput}\u2588`;let e=t2.slice(0,this.cursor),[s,...i]=t2.slice(this.cursor);return`${e}${y("inverse",s)}${i.join("")}`}get cursor(){return this._cursor}constructor(t2){super({...t2,initialUserInput:t2.initialUserInput??t2.initialValue}),this.on("userInput",e=>{this._setValue(e)}),this.on("finalize",()=>{this.value||(this.value=t2.defaultValue),this.value===void 0&&(this.value="")})}};import{styleText as t,stripVTControlCharacters as ne}from"node:util";import P2 from"node:process";var import_sisteransi2=__toESM(require_src(),1);function Ze(){return P2.platform!=="win32"?P2.env.TERM!=="linux":!!P2.env.CI||!!P2.env.WT_SESSION||!!P2.env.TERMINUS_SUBLIME||P2.env.ConEmuTask==="{cmd::Cmder}"||P2.env.TERM_PROGRAM==="Terminus-Sublime"||P2.env.TERM_PROGRAM==="vscode"||P2.env.TERM==="xterm-256color"||P2.env.TERM==="alacritty"||P2.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}__name(Ze,"Ze");var ee=Ze();var w2=__name((e,i)=>ee?e:i,"w"),_e=w2("\u25C6","*"),oe=w2("\u25A0","x"),ue=w2("\u25B2","x"),F=w2("\u25C7","o"),le=w2("\u250C","T"),d2=w2("\u2502","|"),E2=w2("\u2514","\u2014"),Ie=w2("\u2510","T"),Ee=w2("\u2518","\u2014"),z115=w2("\u25CF",">"),H2=w2("\u25CB"," "),te=w2("\u25FB","[\u2022]"),U=w2("\u25FC","[+]"),J=w2("\u25FB","[ ]"),xe=w2("\u25AA","\u2022"),se=w2("\u2500","-"),ce=w2("\u256E","+"),Ge=w2("\u251C","+"),$e=w2("\u256F","+"),de=w2("\u2570","+"),Oe=w2("\u256D","+"),he=w2("\u25CF","\u2022"),pe=w2("\u25C6","*"),me=w2("\u25B2","!"),ge=w2("\u25A0","x"),V2=__name(e=>{switch(e){case"initial":case"active":return t("cyan",_e);case"cancel":return t("red",oe);case"error":return t("yellow",ue);case"submit":return t("green",F)}},"V"),ye=__name(e=>{switch(e){case"initial":case"active":return t("cyan",d2);case"cancel":return t("red",d2);case"error":return t("yellow",d2);case"submit":return t("green",d2)}},"ye"),et2=__name((e,i,s,r,u2)=>{let n=i,o=0;for(let c2=s;c2<r;c2++){let a=e[c2];if(n=n-a.length,o++,n<=u2)break}return{lineCount:n,removals:o}},"et"),Y2=__name(({cursor:e,options:i,style:s,output:r=process.stdout,maxItems:u2=Number.POSITIVE_INFINITY,columnPadding:n=0,rowPadding:o=4})=>{let c2=O(r)-n,a=A(r),l=t("dim","..."),$2=Math.max(a-o,0),y2=Math.max(Math.min(u2,$2),5),p2=0;e>=y2-3&&(p2=Math.max(Math.min(e-y2+3,i.length-y2),0));let m=y2<i.length&&p2>0,g=y2<i.length&&p2+y2<i.length,S2=Math.min(p2+y2,i.length),h=[],f=0;m&&f++,g&&f++;let v=p2+(m?1:0),T=S2-(g?1:0);for(let b=v;b<T;b++){let x=wrapAnsi(s(i[b],b===e),c2,{hard:!0,trim:!1}).split(`
|
|
438
438
|
`);h.push(x),f+=x.length}if(f>$2){let b=0,x=0,G2=f,M2=e-v,R2=__name((j2,D)=>et2(h,G2,j2,D,$2),"R");m?({lineCount:G2,removals:b}=R2(0,M2),G2>$2&&({lineCount:G2,removals:x}=R2(M2+1,h.length))):({lineCount:G2,removals:x}=R2(M2+1,h.length),G2>$2&&({lineCount:G2,removals:b}=R2(0,M2))),b>0&&(m=!0,h.splice(0,b)),x>0&&(g=!0,h.splice(h.length-x,x))}let C2=[];m&&C2.push(l);for(let b of h)for(let x of b)C2.push(x);return g&&C2.push(l),C2},"Y");var ot2=__name(e=>{let i=e.active??"Yes",s=e.inactive??"No";return new Q({active:i,inactive:s,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??u.withGuide,u2=`${V2(this.state)} `,n=r?`${t("gray",d2)} `:"",o=R(e.output,e.message,n,u2),c2=`${r?`${t("gray",d2)}
|
|
439
439
|
`:""}${o}
|
|
440
440
|
`,a=this.value?i:s;switch(this.state){case"submit":{let l=r?`${t("gray",d2)} `:"";return`${c2}${l}${t("dim",a)}`}case"cancel":{let l=r?`${t("gray",d2)} `:"";return`${c2}${l}${t(["strikethrough","dim"],a)}${r?`
|
|
441
|
-
${t("gray",d2)}`:""}`}default:{let l=r?`${t("cyan",d2)} `:"",$2=r?t("cyan",E2):"";return`${c2}${l}${this.value?`${t("green",
|
|
441
|
+
${t("gray",d2)}`:""}`}default:{let l=r?`${t("cyan",d2)} `:"",$2=r?t("cyan",E2):"";return`${c2}${l}${this.value?`${t("green",z115)} ${i}`:`${t("dim",H2)} ${t("dim",i)}`}${e.vertical?r?`
|
|
442
442
|
${t("cyan",d2)} `:`
|
|
443
|
-
`:` ${t("dim","/")} `}${this.value?`${t("dim",H2)} ${t("dim",s)}`:`${t("green",
|
|
443
|
+
`:` ${t("dim","/")} `}${this.value?`${t("dim",H2)} ${t("dim",s)}`:`${t("green",z115)} ${s}`}
|
|
444
444
|
${$2}
|
|
445
445
|
`}}}}).prompt()},"ot");var O2={message:__name((e=[],{symbol:i=t("gray",d2),secondarySymbol:s=t("gray",d2),output:r=process.stdout,spacing:u2=1,withGuide:n}={})=>{let o=[],c2=n??u.withGuide,a=c2?s:"",l=c2?`${i} `:"",$2=c2?`${s} `:"";for(let p2=0;p2<u2;p2++)o.push(a);let y2=Array.isArray(e)?e:e.split(`
|
|
446
446
|
`);if(y2.length>0){let[p2,...m]=y2;p2.length>0?o.push(`${l}${p2}`):o.push(c2?i:"");for(let g of m)g.length>0?o.push(`${$2}${g}`):o.push(c2?s:"")}r.write(`${o.join(`
|
|
@@ -466,7 +466,7 @@ ${o}
|
|
|
466
466
|
`}}}}).prompt(),"bt");var Ve={light:w2("\u2500","-"),heavy:w2("\u2501","="),block:w2("\u2588","#")};var re=__name((e,i)=>e.includes(`
|
|
467
467
|
`)?e.split(`
|
|
468
468
|
`).map(s=>i(s)).join(`
|
|
469
|
-
`):i(e),"re"),_t=__name(e=>{let i=__name((s,r)=>{let u2=s.label??String(s.value);switch(r){case"disabled":return`${t("gray",H2)} ${re(u2,n=>t("gray",n))}${s.hint?` ${t("dim",`(${s.hint??"disabled"})`)}`:""}`;case"selected":return`${re(u2,n=>t("dim",n))}`;case"active":return`${t("green",
|
|
469
|
+
`):i(e),"re"),_t=__name(e=>{let i=__name((s,r)=>{let u2=s.label??String(s.value);switch(r){case"disabled":return`${t("gray",H2)} ${re(u2,n=>t("gray",n))}${s.hint?` ${t("dim",`(${s.hint??"disabled"})`)}`:""}`;case"selected":return`${re(u2,n=>t("dim",n))}`;case"active":return`${t("green",z115)} ${u2}${s.hint?` ${t("dim",`(${s.hint})`)}`:""}`;case"cancelled":return`${re(u2,n=>t(["strikethrough","dim"],n))}`;default:return`${t("dim",H2)} ${re(u2,n=>t("dim",n))}`}},"i");return new nt({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let s=e.withGuide??u.withGuide,r=`${V2(this.state)} `,u2=`${ye(this.state)} `,n=R(e.output,e.message,u2,r),o=`${s?`${t("gray",d2)}
|
|
470
470
|
`:""}${n}
|
|
471
471
|
`;switch(this.state){case"submit":{let c2=s?`${t("gray",d2)} `:"",a=R(e.output,i(this.options[this.cursor],"selected"),c2);return`${o}${a}`}case"cancel":{let c2=s?`${t("gray",d2)} `:"",a=R(e.output,i(this.options[this.cursor],"cancelled"),c2);return`${o}${a}${s?`
|
|
472
472
|
${t("gray",d2)}`:""}`}default:{let c2=s?`${t("cyan",d2)} `:"",a=s?t("cyan",E2):"",l=o.split(`
|
|
@@ -481,8 +481,8 @@ ${a}${o}
|
|
|
481
481
|
`}case"submit":{let o=n?` ${t("dim",n)}`:"",c2=i?t("gray",d2):"";return`${s}${c2}${o}`}case"cancel":{let o=n?` ${t(["strikethrough","dim"],n)}`:"",c2=i?t("gray",d2):"";return`${s}${c2}${o}${n.trim()?`
|
|
482
482
|
${c2}`:""}`}default:{let o=i?`${t("cyan",d2)} `:"",c2=i?t("cyan",E2):"";return`${s}${o}${u2}
|
|
483
483
|
${c2}
|
|
484
|
-
`}}}}).prompt(),"Ot");init_esm();init_dist();init_config();init_sdk_transport();import{z as
|
|
485
|
-
`).filter(line=>line.trim().length>0).map(line=>AssetReferenceImpactEventDTOSchema.parse(JSON.parse(line)))},async createForm(projectId,data){return(await transport.request(tenantPath2(projectId,"/forms"),{method:"POST",body:JSON.stringify(data)})).data},async updateForm(projectId,id,data){return(await transport.request(tenantPath2(projectId,`/forms/${id}`),{method:"PUT",body:JSON.stringify(data)})).data}}}__name(createContentTransferService,"createContentTransferService");init_dist();function isInteractive(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}__name(isInteractive,"isInteractive");function assertInteractive(hint,command="fimo"){currentMode().format==="json"&&(ui.error({command,code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in --json mode.",hint}),process.exit(1)),!isInteractive()&&(ui.error({command,code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in a non-interactive shell.",hint}),process.exit(1))}__name(assertInteractive,"assertInteractive");var PaginationValidationError=class extends Error{static{__name(this,"PaginationValidationError")}kind;constructor(kind,message){super(message),this.name="PaginationValidationError",this.kind=kind}};function addPaginationOptions(command,config){return command.option("--limit <count>",`Maximum items per page (1-${config.maxLimit}, default ${config.defaultLimit})`).option("--cursor <cursor>","Continue from the cursor returned by the previous page").option("--all-pages","Fetch every remaining page"),config.legacyCursor==="before"&&command.addOption(new Option("--before <cursor>","Deprecated alias for --cursor").hideHelp()),config.legacyCursor==="offset"&&command.addOption(new Option("--offset <count>","Deprecated alias for --cursor").hideHelp()),config.legacyAll&&command.addOption(new Option("--all","Deprecated alias for --all-pages").hideHelp()),command}__name(addPaginationOptions,"addPaginationOptions");function toOffsetPaginationPage(response){return{items:response.data,nextCursor:response.meta.hasMore?String(response.meta.offset+response.meta.limit):null,total:response.meta.total,meta:response.meta}}__name(toOffsetPaginationPage,"toOffsetPaginationPage");function parsePaginationOptions(input,config){let limit=Number(input.limit??config.defaultLimit);if(!Number.isInteger(limit)||limit<1||limit>config.maxLimit)throw new PaginationValidationError("invalid_limit",`--limit must be an integer between 1 and ${config.maxLimit}.`);let legacyCursor=config.legacyCursor?input[config.legacyCursor]:void 0;if(input.cursor!==void 0&&legacyCursor!==void 0)throw new PaginationValidationError("conflicting_cursor",`--cursor cannot be combined with --${config.legacyCursor}.`);if(input.cursor==="")throw new PaginationValidationError("invalid_cursor","--cursor must not be empty.");if(config.legacyCursor==="offset"&&legacyCursor!==void 0){let offset=Number(legacyCursor);if(!Number.isInteger(offset)||offset<0)throw new PaginationValidationError("invalid_cursor","--offset must be a non-negative integer.")}return{limit,cursor:input.cursor??legacyCursor,allPages:input.allPages===!0||input.all===!0}}__name(parsePaginationOptions,"parsePaginationOptions");function parseCursorNumber(cursor,config){let value=Number(cursor??config.defaultValue);if(!Number.isInteger(value)||value<config.minimum)throw new PaginationValidationError("invalid_cursor",`--cursor must be an integer greater than or equal to ${config.minimum}.`);return value}__name(parseCursorNumber,"parseCursorNumber");async function collectPaginatedItems(input){let page=await input.fetchPage(input.cursor);if(!input.allPages||page.nextCursor===null)return page;let items=[...page.items],seen=new Set;for(input.cursor!==void 0&&seen.add(input.cursor);page.nextCursor!==null;){if(seen.has(page.nextCursor))throw new Error("Pagination cursor did not advance.");seen.add(page.nextCursor),page=await input.fetchPage(page.nextCursor),items.push(...page.items)}return{...page,items,nextCursor:null}}__name(collectPaginatedItems,"collectPaginatedItems");function buildPaginationHint(command,input,label="More"){let args=[...command,"--limit",String(input.limit),"--cursor",input.cursor,...input.trailingArgs??[]];return`${label}: ${args.map(quoteCommandArgument).join(" ")}`}__name(buildPaginationHint,"buildPaginationHint");function quoteCommandArgument(value){return/^[A-Za-z0-9_./:@+-]+$/.test(value)?value:`'${value.replaceAll("'",`'"'"'`)}'`}__name(quoteCommandArgument,"quoteCommandArgument");init_project_context();init_project();function renderPrettyJson3(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson3,"renderPrettyJson");var bulkUploadItemSchema=
|
|
484
|
+
`}}}}).prompt(),"Ot");init_esm();init_dist();init_config();init_sdk_transport();import{z as z116}from"zod";init_esm();init_config();init_sdk_transport();function createContentTransferService(cfg=loadConfig(),branch){let transport=createCliHttpTransport(cfg,branch),tenantPath2=__name((projectId,route)=>`/api/tenant/${projectId}/branches/${encodeBranchPathSegment(branch)}${route}`,"tenantPath");return{async listEntries(projectId,typeName,params){let query=params?`?${new URLSearchParams(params).toString()}`:"";return transport.request(tenantPath2(projectId,`/entries/${typeName}${query}`))},async uploadAsset(projectId,formData){return(await(await transport.response(tenantPath2(projectId,"/assets/upload"),{method:"POST",body:formData})).json()).data},async admitAssetUploads(projectId,sizes){return(await transport.request(tenantPath2(projectId,"/assets/upload-admissions"),{method:"POST",body:JSON.stringify({files:sizes.map(sizeBytes=>({sizeBytes}))})})).data.admissionId},async completeAssetUploads(projectId,admissionId){await transport.request(tenantPath2(projectId,`/assets/upload-admissions/${admissionId}/complete`),{method:"POST"})},async getAssetReferenceImpact(projectId,request){return(await(await transport.response(tenantPath2(projectId,"/assets/reference-impact"),{method:"POST",headers:{Accept:"application/x-ndjson","Content-Type":"application/json"},body:JSON.stringify(request)})).text()).split(`
|
|
485
|
+
`).filter(line=>line.trim().length>0).map(line=>AssetReferenceImpactEventDTOSchema.parse(JSON.parse(line)))},async createForm(projectId,data){return(await transport.request(tenantPath2(projectId,"/forms"),{method:"POST",body:JSON.stringify(data)})).data},async updateForm(projectId,id,data){return(await transport.request(tenantPath2(projectId,`/forms/${id}`),{method:"PUT",body:JSON.stringify(data)})).data}}}__name(createContentTransferService,"createContentTransferService");init_dist();function isInteractive(){return!!(process.stdin.isTTY&&process.stdout.isTTY)}__name(isInteractive,"isInteractive");function assertInteractive(hint,command="fimo"){currentMode().format==="json"&&(ui.error({command,code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in --json mode.",hint}),process.exit(1)),!isInteractive()&&(ui.error({command,code:"NON_INTERACTIVE_REFUSAL",message:"Cannot prompt in a non-interactive shell.",hint}),process.exit(1))}__name(assertInteractive,"assertInteractive");var PaginationValidationError=class extends Error{static{__name(this,"PaginationValidationError")}kind;constructor(kind,message){super(message),this.name="PaginationValidationError",this.kind=kind}};function addPaginationOptions(command,config){return command.option("--limit <count>",`Maximum items per page (1-${config.maxLimit}, default ${config.defaultLimit})`).option("--cursor <cursor>","Continue from the cursor returned by the previous page").option("--all-pages","Fetch every remaining page"),config.legacyCursor==="before"&&command.addOption(new Option("--before <cursor>","Deprecated alias for --cursor").hideHelp()),config.legacyCursor==="offset"&&command.addOption(new Option("--offset <count>","Deprecated alias for --cursor").hideHelp()),config.legacyAll&&command.addOption(new Option("--all","Deprecated alias for --all-pages").hideHelp()),command}__name(addPaginationOptions,"addPaginationOptions");function toOffsetPaginationPage(response){return{items:response.data,nextCursor:response.meta.hasMore?String(response.meta.offset+response.meta.limit):null,total:response.meta.total,meta:response.meta}}__name(toOffsetPaginationPage,"toOffsetPaginationPage");function parsePaginationOptions(input,config){let limit=Number(input.limit??config.defaultLimit);if(!Number.isInteger(limit)||limit<1||limit>config.maxLimit)throw new PaginationValidationError("invalid_limit",`--limit must be an integer between 1 and ${config.maxLimit}.`);let legacyCursor=config.legacyCursor?input[config.legacyCursor]:void 0;if(input.cursor!==void 0&&legacyCursor!==void 0)throw new PaginationValidationError("conflicting_cursor",`--cursor cannot be combined with --${config.legacyCursor}.`);if(input.cursor==="")throw new PaginationValidationError("invalid_cursor","--cursor must not be empty.");if(config.legacyCursor==="offset"&&legacyCursor!==void 0){let offset=Number(legacyCursor);if(!Number.isInteger(offset)||offset<0)throw new PaginationValidationError("invalid_cursor","--offset must be a non-negative integer.")}return{limit,cursor:input.cursor??legacyCursor,allPages:input.allPages===!0||input.all===!0}}__name(parsePaginationOptions,"parsePaginationOptions");function parseCursorNumber(cursor,config){let value=Number(cursor??config.defaultValue);if(!Number.isInteger(value)||value<config.minimum)throw new PaginationValidationError("invalid_cursor",`--cursor must be an integer greater than or equal to ${config.minimum}.`);return value}__name(parseCursorNumber,"parseCursorNumber");async function collectPaginatedItems(input){let page=await input.fetchPage(input.cursor);if(!input.allPages||page.nextCursor===null)return page;let items=[...page.items],seen=new Set;for(input.cursor!==void 0&&seen.add(input.cursor);page.nextCursor!==null;){if(seen.has(page.nextCursor))throw new Error("Pagination cursor did not advance.");seen.add(page.nextCursor),page=await input.fetchPage(page.nextCursor),items.push(...page.items)}return{...page,items,nextCursor:null}}__name(collectPaginatedItems,"collectPaginatedItems");function buildPaginationHint(command,input,label="More"){let args=[...command,"--limit",String(input.limit),"--cursor",input.cursor,...input.trailingArgs??[]];return`${label}: ${args.map(quoteCommandArgument).join(" ")}`}__name(buildPaginationHint,"buildPaginationHint");function quoteCommandArgument(value){return/^[A-Za-z0-9_./:@+-]+$/.test(value)?value:`'${value.replaceAll("'",`'"'"'`)}'`}__name(quoteCommandArgument,"quoteCommandArgument");init_project_context();init_project();function renderPrettyJson3(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson3,"renderPrettyJson");var bulkUploadItemSchema=z116.object({sourceId:z116.string().min(1),path:z116.string().min(1),name:z116.string().min(1).optional(),parentId:z116.string().min(1).optional(),folderPath:z116.string().min(1).optional()}).strict().refine(item=>!(item.parentId&&item.folderPath),{message:"Use either parentId or folderPath, not both"}),bulkUploadManifestSchema=z116.array(bulkUploadItemSchema).superRefine((items,ctx)=>{let seen=new Set;for(let[index,item]of items.entries())seen.has(item.sourceId)&&ctx.addIssue({code:"custom",message:`Duplicate sourceId: ${item.sourceId}`,path:[index,"sourceId"]}),seen.add(item.sourceId)});function buildAssetFormData(cwd,item,admissionId){let filePath=path7.resolve(cwd,item.path);if(!fs7.existsSync(filePath))throw new Error(`File not found: ${filePath}`);let fileBuffer=fs7.readFileSync(filePath),fileName=path7.basename(filePath),formData=new FormData,mimeType=path7.extname(fileName).toLowerCase()===".svg"?"image/svg+xml":void 0;return formData.append("file",new Blob([fileBuffer],{type:mimeType}),fileName),item.name&&formData.append("name",item.name),item.parentId&&formData.append("parentId",item.parentId),item.folderPath&&formData.append("folderPath",item.folderPath),admissionId&&formData.append("admissionId",admissionId),formData}__name(buildAssetFormData,"buildAssetFormData");function admissibleFileSize(cwd,item){try{let{size}=fs7.statSync(path7.resolve(cwd,item.path));return size>0&&size<=MAX_UPLOAD_FILE_SIZE_BYTES?size:null}catch{return null}}__name(admissibleFileSize,"admissibleFileSize");function isRejectedAdmission(error){return error instanceof ApiRequestError&&error.code==="media_upload_admission_invalid"}__name(isRejectedAdmission,"isRejectedAdmission");function readBulkUploadManifest(cwd,manifest){let manifestPath=path7.resolve(cwd,manifest);if(!fs7.existsSync(manifestPath))throw new Error(`Manifest not found: ${manifestPath}`);let parsed;try{parsed=JSON.parse(fs7.readFileSync(manifestPath,"utf8"))}catch(error){throw new Error(`Could not parse asset manifest ${manifestPath}`,{cause:error})}let result=bulkUploadManifestSchema.safeParse(parsed);if(!result.success){let issues=result.error.issues.map(issue=>`${issue.path.join(".")||"manifest"}: ${issue.message}`);throw new Error(`Invalid asset manifest:
|
|
486
486
|
${issues.join(`
|
|
487
487
|
`)}`)}return result.data}__name(readBulkUploadManifest,"readBulkUploadManifest");function parseConcurrency(value){let concurrency=Number(value);if(!Number.isInteger(concurrency)||concurrency<1||concurrency>16)throw new Error("--concurrency must be an integer between 1 and 16");return concurrency}__name(parseConcurrency,"parseConcurrency");async function mapWithConcurrency(items,concurrency,run){let results=new Array(items.length),nextIndex=0;return await Promise.all(Array.from({length:Math.min(concurrency,items.length)},async()=>{for(;nextIndex<items.length;){let index=nextIndex;nextIndex+=1,results[index]=await run(items[index])}})),results}__name(mapWithConcurrency,"mapWithConcurrency");async function assetsListCommand(options,cmd){let pagination=parsePaginationOptions(options,{defaultLimit:20,maxLimit:100,legacyCursor:"offset"}),{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.list",{projectId:ctx.projectId,branch:ctx.branch});let mimePrefix=options.mimePrefix;mimePrefix||(options.image?mimePrefix="image/":options.video?mimePrefix="video/":options.audio&&(mimePrefix="audio/"));let initialOffset=parseCursorNumber(pagination.cursor,{defaultValue:0,minimum:0}),page=await collectPaginatedItems({cursor:pagination.cursor,allPages:pagination.allPages,fetchPage:__name(async cursor=>{let offset=parseCursorNumber(cursor,{defaultValue:0,minimum:0}),response=await fimo.execute("assets.list",{projectId:ctx.projectId,branch:ctx.branch,parentId:options.parentId||void 0,search:options.search||void 0,type:options.type||void 0,mimePrefix:mimePrefix||void 0,sortBy:options.sortBy||void 0,limit:pagination.limit,offset}),hasMore=response.nextCursor!==null;return{...response,nextCursor:hasMore?String(offset+pagination.limit):null,meta:{limit:pagination.limit,offset,total:response.total,hasMore}}},"fetchPage")}),result={data:page.items,items:page.items,nextCursor:page.nextCursor,total:page.total,meta:{...page.meta,offset:initialOffset,hasMore:page.nextCursor!==null}},trailingArgs=assetPaginationTrailingArgs(options,ctx.branch);ui.result({command:"assets list",data:result,render:__name(()=>renderPrettyJson3(result),"render"),...page.nextCursor?{hint:buildPaginationHint(["fimo","assets","list"],{cursor:page.nextCursor,limit:pagination.limit,trailingArgs})}:{}})}__name(assetsListCommand,"assetsListCommand");function assetPaginationTrailingArgs(options,branch){let args=[];for(let[flag2,value]of[["--branch",branch],["--parent-id",options.parentId],["--search",options.search],["--type",options.type],["--mime-prefix",options.mimePrefix],["--sort-by",options.sortBy],["--cwd",options.cwd]])value!==void 0&&args.push(flag2,value);for(let[flag2,enabled]of[["--image",options.image],["--video",options.video],["--audio",options.audio]])enabled&&args.push(flag2);return args}__name(assetPaginationTrailingArgs,"assetPaginationTrailingArgs");async function assetsUploadCommand(file,options,cmd){let{ctx}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0}),content2=createContentTransferService(loadConfig(),ctx.branch);await requireOperation("assets.upload",{projectId:ctx.projectId,branch:ctx.branch});let cwd=resolveProjectCwd(options.cwd);if(options.parentId&&options.folderPath)throw new Error("Use either --parent-id or --folder-path, not both");let result;try{result=await content2.uploadAsset(ctx.projectId,buildAssetFormData(cwd,{path:file,name:options.name,parentId:options.parentId,folderPath:options.folderPath}))}catch(error){if(error instanceof ApiRequestError&&error.code==="unclaimed_media_limit"){ui.error({command:"assets upload",code:"UNCLAIMED_MEDIA_LIMIT",message:error.detail,details:{limits:error.body.limits}});return}throw error}ui.result({command:"assets upload",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsUploadCommand,"assetsUploadCommand");async function assetsBulkUploadCommand(options,cmd){let cwd=resolveProjectCwd(options.cwd),items=readBulkUploadManifest(cwd,options.file),concurrency=parseConcurrency(options.concurrency),{ctx}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0}),content2=createContentTransferService(loadConfig(),ctx.branch);await requireOperation("assets.upload",{projectId:ctx.projectId,branch:ctx.branch});let admissions=new Set,finished=new Set,admit=__name(async pending=>{let sizes=pending.map(item=>admissibleFileSize(cwd,item)).filter(size=>size!==null);if(sizes.length===0)return;let id=await content2.admitAssetUploads(ctx.projectId,sizes);return admissions.add(id),id},"admit"),admissionId;try{admissionId=await admit(items)}catch(error){if(error instanceof ApiRequestError&&error.code==="media_storage_limit_exceeded"){let body=error.body;ui.error({command:"assets bulk-upload",code:"MEDIA_STORAGE_LIMIT_EXCEEDED",message:"The files do not fit the media storage allowance. Nothing was uploaded.",details:{used_bytes:body.usedBytes,limit_bytes:body.limitBytes,incoming_bytes:body.incomingBytes}});return}throw error}let renewal,renewAdmission=__name(rejectedId=>admissionId!==rejectedId?Promise.resolve(admissionId):(renewal??=admit(items.filter(item=>!finished.has(item))).then(id=>(admissionId=id,id)).finally(()=>{renewal=void 0}),renewal),"renewAdmission"),upload=__name(async item=>{let id=admissionId;try{return await content2.uploadAsset(ctx.projectId,buildAssetFormData(cwd,item,id))}catch(error){if(!id||!isRejectedAdmission(error))throw error;return content2.uploadAsset(ctx.projectId,buildAssetFormData(cwd,item,await renewAdmission(id)))}},"upload"),uploaded=await mapWithConcurrency(items,concurrency,async item=>{try{let asset=await upload(item);return{sourceId:item.sourceId,path:item.path,status:"uploaded",asset}}catch(error){return{sourceId:item.sourceId,path:item.path,status:"failed",error:error instanceof Error?error.message:String(error)}}finally{finished.add(item)}});for(let id of admissions)try{await content2.completeAssetUploads(ctx.projectId,id)}catch(error){isRejectedAdmission(error)||ui.warn({command:"assets bulk-upload",message:`Uploads finished, but the upload batch could not be closed: ${error instanceof Error?error.message:String(error)}`})}let failed=uploaded.filter(item=>item.status==="failed").length,result={total:uploaded.length,uploaded:uploaded.length-failed,failed,items:uploaded};ui.result({command:"assets bulk-upload",data:result,render:__name(()=>renderPrettyJson3(result),"render")}),failed>0&&(process.exitCode=1)}__name(assetsBulkUploadCommand,"assetsBulkUploadCommand");async function assetsReadCommand(id,options,cmd){if(options.cursor!==void 0&&options.query!==void 0)throw new Error("--cursor and --query are mutually exclusive");let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.read",{projectId:ctx.projectId,branch:ctx.branch});let{data:result}=await fimo.execute("assets.read",{projectId:ctx.projectId,branch:ctx.branch,id,cursor:options.cursor,query:options.query});ui.result({command:"assets read",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsReadCommand,"assetsReadCommand");async function assetsCreateFolderCommand(name,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.create_folder",{projectId:ctx.projectId,branch:ctx.branch});let{data:result}=await fimo.execute("assets.createFolder",{projectId:ctx.projectId,branch:ctx.branch,name,parentId:options.parentId});ui.result({command:"assets create-folder",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsCreateFolderCommand,"assetsCreateFolderCommand");async function assetsMoveCommand(id,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.move",{projectId:ctx.projectId,branch:ctx.branch});let{data:result}=await fimo.execute("assets.move",{projectId:ctx.projectId,branch:ctx.branch,id,parentId:options.parentId});ui.result({command:"assets move",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsMoveCommand,"assetsMoveCommand");var OTHER_BRANCHES_CAVEAT="Other Branches are not checked. This result is guidance for Current, Main, and Live, not a global unused claim.",scopeCount=__name(scope2=>scope2.referenceCount??scope2.references.length,"scopeCount");function summarizeImpact(scopes){let counts=Object.fromEntries(scopes.map(scope2=>[scope2.scope,scopeCount(scope2)])),referenceCount=scopes.reduce((total,scope2)=>total+scopeCount(scope2),0),codeReferenceCount=scopes.reduce((total,scope2)=>total+(scope2.codeReferenceCount??0),0);return{status:scopes.some(scope2=>scope2.coverage!=="complete"||scope2.state==="failed")?"uncertain":referenceCount>0?"referenced":"no-references-found",coverage:Object.fromEntries(scopes.map(scope2=>[scope2.scope,scope2.coverage])),counts,referenceCount,codeReferenceCount,scopes,otherBranches:{checked:!1,caveat:OTHER_BRANCHES_CAVEAT}}}__name(summarizeImpact,"summarizeImpact");async function loadAssetImpact(content2,projectId,id){let events=await content2.getAssetReferenceImpact(projectId,{assetIds:[id],scopes:["current","main","live"]}),complete=events.some(event=>event.type==="complete"),scopes=events.filter(event=>event.type==="scope").map(event=>event.data);if(!complete||scopes.length!==3)throw new Error("Asset usage scan ended before Current, Main, and Live were reported");return summarizeImpact(scopes)}__name(loadAssetImpact,"loadAssetImpact");async function assetsUsageCommand(id,options,cmd){let{ctx}=await bootstrapProjectCommand(options,cmd),content2=createContentTransferService(loadConfig(),ctx.branch);await requireOperation("assets.delete",{projectId:ctx.projectId,branch:ctx.branch});let result=await loadAssetImpact(content2,ctx.projectId,id);ui.result({command:"assets usage",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsUsageCommand,"assetsUsageCommand");async function assetsReplaceCommand(id,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.move",{projectId:ctx.projectId,branch:ctx.branch}),await requireOperation("cms.update",{projectId:ctx.projectId,branch:ctx.branch});let result=await fimo.execute("assets.replaceReferences",{projectId:ctx.projectId,branch:ctx.branch,sourceAssetId:id,replacementAssetId:options.with}),receipt={sourceAssetId:id,replacementAssetId:options.with,scope:"current",...result,sourceRemoved:!1};ui.result({command:"assets replace",data:receipt,render:__name(()=>renderPrettyJson3(receipt),"render")})}__name(assetsReplaceCommand,"assetsReplaceCommand");async function assetsRemoveCommand(id,options,cmd){if(options.permanent&&options.withoutChecking)throw new Error("--permanent cannot be combined with --without-checking");if(options.replaceWith&&options.withoutChecking)throw new Error("--replace-with and --without-checking are mutually exclusive");let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0}),content2=createContentTransferService(loadConfig(),ctx.branch);if(await requireOperation("assets.delete",{projectId:ctx.projectId,branch:ctx.branch}),options.permanent){if(options.replaceWith&&await requireOperation("cms.update",{projectId:ctx.projectId,branch:ctx.branch}),!options.yes){assertInteractive("Pass --yes to permanently destroy the asset without a prompt.","assets remove");let confirmed=await ot2({message:options.replaceWith?`Point references everywhere at ${options.replaceWith}, then permanently destroy asset ${id} across the site? This cannot be undone.`:`Permanently destroy asset ${id} across the site? This cannot be undone.`,initialValue:!1});if(q(confirmed)||!confirmed){ui.info({command:"assets remove",message:"Cancelled."});return}}if(options.replaceWith){let replacement=await fimo.execute("assets.replaceAndDestroy",{projectId:ctx.projectId,branch:ctx.branch,id,replacementAssetId:options.replaceWith}),receipt3={assetId:id,scope:"project",permanent:!0,removed:!0,replacement:{assetId:options.replaceWith,...replacement}};ui.result({command:"assets remove",data:receipt3,render:__name(()=>renderPrettyJson3(receipt3),"render")});return}await fimo.execute("assets.destroy",{projectId:ctx.projectId,branch:ctx.branch,id});let receipt2={assetId:id,scope:"project",permanent:!0,removed:!0};ui.result({command:"assets remove",data:receipt2,render:__name(()=>renderPrettyJson3(receipt2),"render")});return}if(options.replaceWith){await requireOperation("cms.update",{projectId:ctx.projectId,branch:ctx.branch});let outcome=await fimo.execute("assets.replaceAndRemove",{projectId:ctx.projectId,branch:ctx.branch,sourceAssetId:id,replacementAssetId:options.replaceWith}),receipt2={assetId:id,scope:"environment",environment:ctx.branch,permanent:!1,removed:!1,removal:{operationId:outcome.id,expiresAt:outcome.expiresAt,undoable:outcome.undoable},replacement:{assetId:options.replaceWith,code:outcome.codeReplacement}};ui.result({command:"assets remove",data:receipt2,render:__name(()=>renderPrettyJson3(receipt2),"render")});return}let usage,usageError;if(!options.withoutChecking)try{usage=await loadAssetImpact(content2,ctx.projectId,id)}catch(error){usageError={message:error instanceof Error?error.message:String(error)}}await fimo.execute("assets.delete",{projectId:ctx.projectId,branch:ctx.branch,id});let receipt={assetId:id,scope:"environment",environment:ctx.branch,permanent:!1,removed:!0,checked:!options.withoutChecking,usage,usageError};ui.result({command:"assets remove",data:receipt,render:__name(()=>renderPrettyJson3(receipt),"render")})}__name(assetsRemoveCommand,"assetsRemoveCommand");init_esm();init_dist();init_local_runtime_env();init_config();init_sdk_transport();init_sdk_transport();init_git();init_project_context();function buildProjectPreviewUrl(webUrl,projectId,branch){return new URL(`/app/projects/${encodeURIComponent(projectId)}/branch/${encodeURIComponent(branch)}/preview`,webUrl).toString()}__name(buildProjectPreviewUrl,"buildProjectPreviewUrl");init_project();function branchOverride(program2){return branchOverrideFromCommand(program2)}__name(branchOverride,"branchOverride");async function branchListCommand(cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({branchOverride:branchOverride(program2)}),fimo=createCliFimoClient(loadConfig(),ctx.branch),{data:branches}=await fimo.execute("branches.list",{projectId:ctx.projectId,includeDeleted:opts.verbose,includeAgentBranches:opts.all});if(branches.length===0){ui.info({command:"branch",message:"(no Branches yet)",hint:"Run `fimo branch <name>` to create one."});return}ui.table({command:"branch",columns:[{key:"branch",label:"BRANCH"},{key:"status",label:"STATUS"},{key:"parent",label:"PARENT"}],rows:branches.map(row2=>({branch:row2.branch,status:row2.status,parent:row2.parentBranch??"\u2014"})),isActive:__name(row2=>row2.branch===ctx.branch,"isActive")})}__name(branchListCommand,"branchListCommand");async function branchCreateCommand(name,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({branchOverride:branchOverride(program2)}),fimo=createCliFimoClient(loadConfig(),ctx.branch),parentBranch=opts.from??ctx.branch;if(isProductionBranch(name)||isProductionBranch(parentBranch)){ui.error({command:"branch",code:"PROTECTED_ENV",message:`The '${PRODUCTION_BRANCH}' Branch is protected \u2014 it cannot be created or forked from.`});return}let parentValidation=await validateParentBranch(fimo,ctx.projectId,parentBranch,ctx,opts.from);if(!parentValidation.ok){ui.error({command:"branch",code:"ENV_NOT_FOUND",message:parentValidation.message});return}let{data:created}=await fimo.execute("branches.create",{projectId:ctx.projectId,name,from:parentBranch}),createdBranch=branchNameOf(created),studioUrl=buildProjectPreviewUrl(loadConfig().webUrl,ctx.projectId,createdBranch),headline=`Created Branch '${createdBranch}' (status: ${created.status})`;ui.result({command:"branch",data:{headline,details:{branch:createdBranch,parent_branch:parentBranch,env:createdBranch,parent_env:parentBranch,status:created.status,studio_url:studioUrl,dashboard_url:studioUrl}},render:__name(context=>renderBranchCreated({headline,parentBranch,studioUrl},context),"render")})}__name(branchCreateCommand,"branchCreateCommand");function renderBranchCreated(result,context){let lines=[`${context.ascii?"[ok]":"\u2713"} ${result.headline}`,` Parent: ${result.parentBranch}`];return lines.push(` Studio: ${terminalLink("Open in Studio",result.studioUrl,context.hyperlinks)}`),lines.join(`
|
|
488
488
|
`)}__name(renderBranchCreated,"renderBranchCreated");async function branchDeleteCommand(name,cmd){let program2=cmd.parent??cmd,ctx=await getProjectContext({branchOverride:branchOverride(program2)}),fimo=createCliFimoClient(loadConfig(),ctx.branch);if(name===DEFAULT_BRANCH){ui.error({command:"branch",code:"PROTECTED_ENV",message:`Refusing to delete the default Branch '${DEFAULT_BRANCH}'.`});return}if(isProductionBranch(name)){ui.error({command:"branch",code:"PROTECTED_ENV",message:`The '${PRODUCTION_BRANCH}' Branch is protected and cannot be deleted.`});return}await fimo.execute("branches.delete",{projectId:ctx.projectId,branch:name}),ui.ok({command:"branch",headline:`Deleted Branch '${name}'`,details:{branch:name,env:name}})}__name(branchDeleteCommand,"branchDeleteCommand");async function checkoutCommand(name,_options,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({branchOverride:branchOverride(program2)}),fimo=createCliFimoClient(loadConfig(),ctx.branch),cwd=resolveProjectCwd();if(isProductionBranch(name)){ui.error({command:"checkout",code:"PROTECTED_ENV",message:`The '${PRODUCTION_BRANCH}' Branch is protected and cannot be checked out.`});return}let created=!1;if(opts.create){let parentBranch=opts.from??ctx.branch,parentValidation=await validateParentBranch(fimo,ctx.projectId,parentBranch,ctx,opts.from);if(!parentValidation.ok){ui.error({command:"checkout",code:"ENV_NOT_FOUND",message:parentValidation.message});return}await fimo.execute("branches.create",{projectId:ctx.projectId,name,from:parentBranch}),created=!0}else await fimo.execute("branches.get",{projectId:ctx.projectId,branch:name});let gitSwitched=!1;if(await isGitRepo(cwd))try{await runGit(["checkout",name],cwd),gitSwitched=!0}catch(err){let stderr=err instanceof Error&&"stderr"in err?String(err.stderr):"";if(/did not match any file|pathspec/i.test(stderr))await runGit(["checkout","-b",name],cwd),gitSwitched=!0;else throw err}let runtime=resolveLocalRuntimeEnv({cwd});ui.ok({command:"checkout",headline:`Now on Branch '${name}'`,details:{branch:name,created,git_switched:gitSwitched,parent_branch:opts.from??null,env:name,parent_env:opts.from??null,tenant_api_url:runtime?.tenantApiUrl??null},warnings:describeRuntimeWarnings(cwd,runtime)})}__name(checkoutCommand,"checkoutCommand");function describeRuntimeWarnings(cwd,runtime){if(!runtime)return["This checkout cannot derive its tenant API URL \u2014 the project link predates that. Run `fimo link` once to record it; until then the app keeps whatever runtime env values it already has."];let stale=findStaleFimoOverride({...readLocalEnvFiles(cwd),...process.env},runtime);return stale?[staleOverrideMessage(stale)]:void 0}__name(describeRuntimeWarnings,"describeRuntimeWarnings");async function pullCommand(_options,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({branchOverride:branchOverride(program2)}),fimo=createCliFimoClient(loadConfig(),ctx.branch),{branch,conflicts}=await fimo.execute("branches.sync",{projectId:ctx.projectId,branch:ctx.branch,from:opts.from}),warnings=conflicts>0?[`Resolved ${conflicts} conflict(s) (parent-wins for now \u2014 M12 conflict UI will add per-row picks)`]:void 0,synced=branchNameOf(branch);ui.ok({command:"pull",headline:`Branch '${synced}' synced`,details:{branch:synced,env:synced,from:opts.from??null,conflicts},warnings})}__name(pullCommand,"pullCommand");async function validateParentBranch(fimo,projectId,parentBranch,ctx,fromFlag){try{return await fimo.execute("branches.get",{projectId,branch:parentBranch}),{ok:!0}}catch(err){if(!(err instanceof ApiRequestError)||err.status!==404)throw err;let origin=fromFlag?`the \`--from ${fromFlag}\` flag`:ctx.source==="branch"?`your active Branch (\`${ctx.branch}\`)`:ctx.source==="flag"?`the Branch override flag (\`${ctx.branch}\`)`:ctx.source==="tag"?`the release tag \`${ctx.branch}\``:`the site default (\`${ctx.branch}\`)`,fixes=[];return fromFlag?fixes.push(`pass an existing Branch via \`--from <branch>\` (try \`--from ${DEFAULT_BRANCH}\`)`):ctx.source==="branch"?(fixes.push(`switch Branches first: \`fimo checkout ${DEFAULT_BRANCH}\``),fixes.push(`or pass \`--from ${DEFAULT_BRANCH}\` to override for this command`)):ctx.source==="flag"?fixes.push(`use a different \`--branch <existing>\` (try \`--branch ${DEFAULT_BRANCH}\`)`):fixes.push(`pass \`--from ${DEFAULT_BRANCH}\` to fork from main`),{ok:!1,message:`Cannot create Branch: parent Branch '${parentBranch}' doesn't exist on this site. The CLI resolved the parent from ${origin}. Fix: ${fixes.join(", or ")}.`}}}__name(validateParentBranch,"validateParentBranch");init_dist();init_config();init_config();init_sdk_transport();function createIntegrationService(cfg=loadConfig()){let transport=createCliHttpTransport(cfg),projectPath2=__name((projectId,integrationKey)=>`/api/management/projects/${projectId}/integrations${integrationKey?`/${encodeURIComponent(integrationKey)}`:""}`,"projectPath");return{async list(projectId){return(await transport.request(projectPath2(projectId))).data},async addMcp(input){return(await transport.request(projectPath2(input.projectId),{method:"POST",body:JSON.stringify(input.request)})).data},async getInfo(projectId,integrationKey){return(await transport.request(`${projectPath2(projectId,integrationKey)}/info`)).data},async getStatus(projectId,integrationKey){return(await transport.request(`${projectPath2(projectId,integrationKey)}/status`)).data},async connect(input){return(await transport.request(`${projectPath2(input.projectId,input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify(input.request)})).data},async enable(input){let payload={...input.authMode?{authMode:input.authMode}:{},...input.connectionAlias?{connectionAlias:input.connectionAlias}:{}};return(await transport.request(projectPath2(input.projectId,input.integrationKey),{method:"PUT",body:JSON.stringify(payload)})).data},async connectOrganizationWithToken(input){return(await transport.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 switchAuth(input){return(await transport.request(`${projectPath2(input.projectId,input.integrationKey)}/auth`,{method:"PATCH",body:JSON.stringify({authMode:input.authMode})})).data},async disable(projectId,integrationKey){await transport.request(projectPath2(projectId,integrationKey),{method:"DELETE"})},async runTool(input){return(await transport.request(`${projectPath2(input.projectId,input.integrationKey)}/run`,{method:"POST",body:JSON.stringify(input.request)})).data},async bindChannel(projectId,request){return(await transport.request(`/api/management/projects/${projectId}/channels/bind`,{method:"POST",body:JSON.stringify(request)})).data}}}__name(createIntegrationService,"createIntegrationService");function createModelCatalogService(cfg=loadConfig()){let transport=createCliHttpTransport(cfg);return{async list(projectId,query={}){let params=new URLSearchParams;query.modality&¶ms.set("modality",query.modality);for(let tag of query.tag??[])params.append("tag",tag);query.q&¶ms.set("q",query.q),query.category&¶ms.set("category",query.category);let search=params.toString();return(await transport.request(`/api/management/projects/${projectId}/integrations/fal/models${search?`?${search}`:""}`)).data},async get(projectId,key){try{return(await transport.request(`/api/management/projects/${projectId}/integrations/fal/models/${key}`)).data}catch(error){if(error instanceof ApiRequestError&&error.status===404)return null;throw error}}}}__name(createModelCatalogService,"createModelCatalogService");init_project();function registerChannelsCommands(program2){program2.command("channels").description("Manage site channel bindings").addHelpText("after",`
|
|
@@ -495,7 +495,7 @@ Run \`fimo channels <command> --help\` for command-specific help.
|
|
|
495
495
|
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}__name(bundleName,"bundleName");import{promisify as promisify4}from"node:util";import{execFile as execFile4}from"node:child_process";var execFileAsync4=promisify4(execFile4),windowsBrowserProgIds={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},_windowsBrowserProgIdMap=new Map(Object.entries(windowsBrowserProgIds)),UnknownBrowserError=class extends Error{static{__name(this,"UnknownBrowserError")}};async function defaultBrowser(_execFileAsync=execFileAsync4){let{stdout}=await _execFileAsync("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),match=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);if(!match)throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);let{id}=match.groups,dotIndex=id.lastIndexOf("."),hyphenIndex=id.lastIndexOf("-"),baseIdByDot=dotIndex===-1?void 0:id.slice(0,dotIndex),baseIdByHyphen=hyphenIndex===-1?void 0:id.slice(0,hyphenIndex);return windowsBrowserProgIds[id]??windowsBrowserProgIds[baseIdByDot]??windowsBrowserProgIds[baseIdByHyphen]??{name:id,id}}__name(defaultBrowser,"defaultBrowser");var execFileAsync5=promisify5(execFile5),titleize=__name(string=>string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,x=>x.toUpperCase()),"titleize");async function defaultBrowser2(){if(process6.platform==="darwin"){let id=await defaultBrowserId();return{name:await bundleName(id),id}}if(process6.platform==="linux"){let{stdout}=await execFileAsync5("xdg-mime",["query","default","x-scheme-handler/http"]),id=stdout.trim();return{name:titleize(id.replace(/.desktop$/,"").replace("-"," ")),id}}if(process6.platform==="win32")return defaultBrowser();throw new Error("Only macOS, Linux, and Windows are supported")}__name(defaultBrowser2,"defaultBrowser");var execFile6=promisify6(childProcess.execFile),__dirname=path8.dirname(fileURLToPath3(import.meta.url)),localXdgOpenPath=path8.join(__dirname,"xdg-open"),{platform,arch}=process7;async function getWindowsDefaultBrowserFromWsl(){let powershellPath=await powerShellPath(),rawCommand=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,encodedCommand=Buffer2.from(rawCommand,"utf16le").toString("base64"),{stdout}=await execFile6(powershellPath,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",encodedCommand],{encoding:"utf8"}),progId=stdout.trim(),browserMap={ChromeHTML:"com.google.chrome",BraveHTML:"com.brave.Browser",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return browserMap[progId]?{id:browserMap[progId]}:{}}__name(getWindowsDefaultBrowserFromWsl,"getWindowsDefaultBrowserFromWsl");var pTryEach=__name(async(array,mapper)=>{let latestError;for(let item of array)try{return await mapper(item)}catch(error){latestError=error}throw latestError},"pTryEach"),baseOpen=__name(async options=>{if(options={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...options},Array.isArray(options.app))return pTryEach(options.app,singleApp=>baseOpen({...options,app:singleApp}));let{name:app,arguments:appArguments=[]}=options.app??{};if(appArguments=[...appArguments],Array.isArray(app))return pTryEach(app,appName=>baseOpen({...options,app:{name:appName,arguments:appArguments}}));if(app==="browser"||app==="browserPrivate"){let ids={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.Browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},flags={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},browser=is_wsl_default?await getWindowsDefaultBrowserFromWsl():await defaultBrowser2();if(browser.id in ids){let browserName=ids[browser.id];return app==="browserPrivate"&&appArguments.push(flags[browserName]),baseOpen({...options,app:{name:apps[browserName],arguments:appArguments}})}throw new Error(`${browser.name} is not supported as a default browser`)}let command,cliArguments=[],childProcessOptions={};if(platform==="darwin")command="open",options.wait&&cliArguments.push("--wait-apps"),options.background&&cliArguments.push("--background"),options.newInstance&&cliArguments.push("--new"),app&&cliArguments.push("-a",app);else if(platform==="win32"||is_wsl_default&&!isInsideContainer()&&!app){command=await powerShellPath(),cliArguments.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),is_wsl_default||(childProcessOptions.windowsVerbatimArguments=!0);let encodedArguments=["Start"];options.wait&&encodedArguments.push("-Wait"),app?(encodedArguments.push(`"\`"${app}\`""`),options.target&&appArguments.push(options.target)):options.target&&encodedArguments.push(`"${options.target}"`),appArguments.length>0&&(appArguments=appArguments.map(argument=>`"\`"${argument}\`""`),encodedArguments.push("-ArgumentList",appArguments.join(","))),options.target=Buffer2.from(encodedArguments.join(" "),"utf16le").toString("base64")}else{if(app)command=app;else{let isBundled=!__dirname||__dirname==="/",exeLocalXdgOpen=!1;try{await fs12.access(localXdgOpenPath,fsConstants2.X_OK),exeLocalXdgOpen=!0}catch{}command=process7.versions.electron??(platform==="android"||isBundled||!exeLocalXdgOpen)?"xdg-open":localXdgOpenPath}appArguments.length>0&&cliArguments.push(...appArguments),options.wait||(childProcessOptions.stdio="ignore",childProcessOptions.detached=!0)}platform==="darwin"&&appArguments.length>0&&cliArguments.push("--args",...appArguments),options.target&&cliArguments.push(options.target);let subprocess=childProcess.spawn(command,cliArguments,childProcessOptions);return options.wait?new Promise((resolve10,reject)=>{subprocess.once("error",reject),subprocess.once("close",exitCode=>{if(!options.allowNonzeroExitCode&&exitCode>0){reject(new Error(`Exited with code ${exitCode}`));return}resolve10(subprocess)})}):(subprocess.unref(),subprocess)},"baseOpen"),open=__name((target,options)=>{if(typeof target!="string")throw new TypeError("Expected a `target`");return baseOpen({...options,target})},"open");function detectArchBinary(binary){if(typeof binary=="string"||Array.isArray(binary))return binary;let{[arch]:archBinary}=binary;if(!archBinary)throw new Error(`${arch} is not supported`);return archBinary}__name(detectArchBinary,"detectArchBinary");function detectPlatformBinary({[platform]:platformBinary},{wsl}){if(wsl&&is_wsl_default)return detectArchBinary(wsl);if(!platformBinary)throw new Error(`${platform} is not supported`);return detectArchBinary(platformBinary)}__name(detectPlatformBinary,"detectPlatformBinary");var apps={};defineLazyProperty(apps,"chrome",()=>detectPlatformBinary({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));defineLazyProperty(apps,"brave",()=>detectPlatformBinary({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));defineLazyProperty(apps,"firefox",()=>detectPlatformBinary({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));defineLazyProperty(apps,"edge",()=>detectPlatformBinary({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));defineLazyProperty(apps,"browser",()=>"browser");defineLazyProperty(apps,"browserPrivate",()=>"browserPrivate");var open_default=open;init_auth();init_config();init_auth();init_esm();init_config();init_sdk_transport();var UNCLAIMED_PROJECTS_PATH="/api/management/unclaimed-projects",CLAIM_STATES_BATCH_SIZE=20;async function postWithoutAuth(cfg,path49,body){let response=await fimoFetch(`${cfg.apiUrl}${path49}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body)});if(!response.ok){let error=await parseError(response);throw new ApiRequestError("POST",path49,response.status,error.detail,error.code,error.body)}return(await response.json()).data}__name(postWithoutAuth,"postWithoutAuth");function createUnclaimedProjectsService(cfg=loadConfig()){return{async provision(input){return ProvisionUnclaimedProjectResponseDTO.schema.parse(await postWithoutAuth(cfg,UNCLAIMED_PROJECTS_PATH,input))},async claimStates(secrets){let claims=[];for(let start=0;start<secrets.length;start+=CLAIM_STATES_BATCH_SIZE){let data=await postWithoutAuth(cfg,`${UNCLAIMED_PROJECTS_PATH}/claims/state`,{secrets:secrets.slice(start,start+CLAIM_STATES_BATCH_SIZE)});claims.push(...UnclaimedClaimStatesResponseDTO.schema.parse(data).claims)}return claims},async self(){let body=await createCliHttpTransport(cfg).request(`${UNCLAIMED_PROJECTS_PATH}/self`);return ProjectTokenSelfDTO.schema.parse(body.data)}}}__name(createUnclaimedProjectsService,"createUnclaimedProjectsService");init_project();import fs13 from"node:fs";import path9 from"node:path";function writeLocalProjectFiles(args){let{targetDir,project,apiUrl,tenantApiBaseUrl}=args,fimoJson={projectId:project.id,organizationId:project.organizationId,name:project.name,apiUrl,...tenantApiBaseUrl?{tenantApiBaseUrl}:{}},layout=resolveProjectLayoutPaths(targetDir),projectPath2=path9.join(targetDir,layout.project);fs13.mkdirSync(path9.dirname(projectPath2),{recursive:!0}),writeIfChanged(projectPath2,`${JSON.stringify(fimoJson,null,2)}
|
|
496
496
|
`)}__name(writeLocalProjectFiles,"writeLocalProjectFiles");function updateLocalProjectOrganization(targetDir,organizationId){let settingsPath=resolveProjectSettingsPath(targetDir);if(!fs13.existsSync(settingsPath))return;let marker=JSON.parse(fs13.readFileSync(settingsPath,"utf-8"));marker.organizationId=organizationId,writeIfChanged(settingsPath,`${JSON.stringify(marker,null,2)}
|
|
497
497
|
`)}__name(updateLocalProjectOrganization,"updateLocalProjectOrganization");function seedSiteName(args){let{targetDir,project}=args,configPath=resolveProjectConfigPath(targetDir);if(fs13.existsSync(configPath))try{let original=fs13.readFileSync(configPath,"utf-8"),config=JSON.parse(original),seo=config.seo??{};if(!(typeof seo.siteName=="string"?seo.siteName:"").trim()){let initialSiteName=project.displayName?.trim()||project.name;config.seo={...seo,siteName:initialSiteName},writeIfChanged(configPath,`${JSON.stringify(config,null,2)}
|
|
498
|
-
`)}}catch{}}__name(seedSiteName,"seedSiteName");function writeIfChanged(filePath,content2){fs13.existsSync(filePath)&&fs13.readFileSync(filePath,"utf-8")===content2||fs13.writeFileSync(filePath,content2)}__name(writeIfChanged,"writeIfChanged");var MINUTE_MS=60*1e3,HOUR_MS=60*MINUTE_MS,DAY_MS=24*HOUR_MS,CLAIM_STATE_TTL_MS=10*MINUTE_MS;function formatClaimDate(date){return new Date(date).toLocaleString("en-GB",{weekday:"short",day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"})}__name(formatClaimDate,"formatClaimDate");function formatTimeLeft(date,now=new Date){let left=new Date(date).getTime()-now.getTime();if(left<MINUTE_MS)return"less than a minute";let days=Math.floor(left/DAY_MS),hours=Math.floor(left%DAY_MS/HOUR_MS),minutes=Math.floor(left%HOUR_MS/MINUTE_MS);return days>0?`${days} ${days===1?"day":"days"} ${hours} h`:hours>0?`${hours} h ${minutes} min`:`${minutes} min`}__name(formatTimeLeft,"formatTimeLeft");async function fetchClaimStatus(cfg,tokenFile,now=new Date){let self=await createUnclaimedProjectsService(cfg).self();return tokenFile&&(rememberClaimState(tokenFile,self.claimState,now),self.organizationId&&updateLocalProjectOrganization(tokenFile.root,self.organizationId)),self}__name(fetchClaimStatus,"fetchClaimStatus");function rememberClaimState(tokenFile,claimState,now){tokenFile.file.claimState=claimState,tokenFile.file.claimCheckedAt=now.toISOString(),writeProjectToken(tokenFile.root,tokenFile.file)}__name(rememberClaimState,"rememberClaimState");async function unclaimedReminder(cfg,tokenFile,now=new Date){let{file}=tokenFile;if(file.claimState==="claimed")return null;let checkedAt=file.claimCheckedAt?new Date(file.claimCheckedAt).getTime():0,claimState=now.getTime()-checkedAt<CLAIM_STATE_TTL_MS?file.claimState:(await fetchClaimStatus(cfg,tokenFile,now)).claimState;return claimState==="claimed"?null:claimState==="expired"||new Date(file.expiresAt).getTime()<=now.getTime()?"This site was not claimed in time and is being deleted.":`This site isn't claimed yet \u2014 ${formatTimeLeft(file.expiresAt,now)} left. Run \`fimo claim\`.`}__name(unclaimedReminder,"unclaimedReminder");init_color();var CLAIM_POLL_INTERVAL_MS=3e3,CLAIM_WAIT_TIMEOUT_MS=900*1e3;async function claimCommand(options={},deps={}){let cfg=loadConfig(),auth=resolveAuth(cfg);if(auth?.kind!=="project"||!auth.tokenFile){ui.error({command:"claim",code:"NOT_UNCLAIMED_PROJECT",message:"`fimo claim` works inside a site created with `fimo
|
|
498
|
+
`)}}catch{}}__name(seedSiteName,"seedSiteName");function writeIfChanged(filePath,content2){fs13.existsSync(filePath)&&fs13.readFileSync(filePath,"utf-8")===content2||fs13.writeFileSync(filePath,content2)}__name(writeIfChanged,"writeIfChanged");var MINUTE_MS=60*1e3,HOUR_MS=60*MINUTE_MS,DAY_MS=24*HOUR_MS,CLAIM_STATE_TTL_MS=10*MINUTE_MS;function formatClaimDate(date){return new Date(date).toLocaleString("en-GB",{weekday:"short",day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"})}__name(formatClaimDate,"formatClaimDate");function formatTimeLeft(date,now=new Date){let left=new Date(date).getTime()-now.getTime();if(left<MINUTE_MS)return"less than a minute";let days=Math.floor(left/DAY_MS),hours=Math.floor(left%DAY_MS/HOUR_MS),minutes=Math.floor(left%HOUR_MS/MINUTE_MS);return days>0?`${days} ${days===1?"day":"days"} ${hours} h`:hours>0?`${hours} h ${minutes} min`:`${minutes} min`}__name(formatTimeLeft,"formatTimeLeft");async function fetchClaimStatus(cfg,tokenFile,now=new Date){let self=await createUnclaimedProjectsService(cfg).self();return tokenFile&&(rememberClaimState(tokenFile,self.claimState,now),self.organizationId&&updateLocalProjectOrganization(tokenFile.root,self.organizationId)),self}__name(fetchClaimStatus,"fetchClaimStatus");function rememberClaimState(tokenFile,claimState,now){tokenFile.file.claimState=claimState,tokenFile.file.claimCheckedAt=now.toISOString(),writeProjectToken(tokenFile.root,tokenFile.file)}__name(rememberClaimState,"rememberClaimState");async function unclaimedReminder(cfg,tokenFile,now=new Date){let{file}=tokenFile;if(file.claimState==="claimed")return null;let checkedAt=file.claimCheckedAt?new Date(file.claimCheckedAt).getTime():0,claimState=now.getTime()-checkedAt<CLAIM_STATE_TTL_MS?file.claimState:(await fetchClaimStatus(cfg,tokenFile,now)).claimState;return claimState==="claimed"?null:claimState==="expired"||new Date(file.expiresAt).getTime()<=now.getTime()?"This site was not claimed in time and is being deleted.":`This site isn't claimed yet \u2014 ${formatTimeLeft(file.expiresAt,now)} left. Run \`fimo claim\`.`}__name(unclaimedReminder,"unclaimedReminder");init_color();var CLAIM_POLL_INTERVAL_MS=3e3,CLAIM_WAIT_TIMEOUT_MS=900*1e3;async function claimCommand(options={},deps={}){let cfg=loadConfig(),auth=resolveAuth(cfg);if(auth?.kind!=="project"||!auth.tokenFile){ui.error({command:"claim",code:"NOT_UNCLAIMED_PROJECT",message:"`fimo claim` works inside a site created with `fimo new`.",hint:"Run it from that site's directory. Sites created with an account already belong to you."});return}let now=deps.now??(()=>new Date),tokenFile=auth.tokenFile,self=await fetchClaimStatus(cfg,tokenFile,now()),interactive=deps.interactive??(currentMode().format==="pretty"&&process.stdout.isTTY===!0&&process.stdin.isTTY===!0);self.claimState==="claimable"&&interactive&&options.wait!==!1&&(self=await openAndWait(cfg,tokenFile,self,options,{...deps,now})),emitClaimResult(tokenFile,self,now())}__name(claimCommand,"claimCommand");async function openAndWait(cfg,tokenFile,initial,options,deps){let{claimUrl}=tokenFile.file;process.stderr.write(`${claimIntro(palette,initial,claimUrl,deps.now())}
|
|
499
499
|
`),options.open!==!1&&isFimoClaimUrl(claimUrl,cfg)&&await(deps.openUrl??open_default)(claimUrl).catch(()=>{});let sleep2=deps.sleep??(ms=>new Promise(resolve10=>setTimeout(resolve10,ms))),waitSpinner=spinner("Waiting for the claim (Ctrl-C to stop; the link keeps working)"),deadline=deps.now().getTime()+CLAIM_WAIT_TIMEOUT_MS,self=initial;for(;self.claimState==="claimable"&&deps.now().getTime()<deadline;)await sleep2(CLAIM_POLL_INTERVAL_MS),self=await fetchClaimStatus(cfg,tokenFile,deps.now());return self.claimState==="claimed"?waitSpinner.succeed("Claimed"):waitSpinner.stop(),self}__name(openAndWait,"openAndWait");function isFimoClaimUrl(claimUrl,cfg){try{let url=new URL(claimUrl);return url.origin===new URL(cfg.webUrl).origin&&url.pathname.startsWith("/projects/claim/")}catch{return!1}}__name(isFimoClaimUrl,"isFimoClaimUrl");function claimIntro(p2,self,claimUrl,now){let name=self.displayName??self.projectName,deadline=self.expiresAt?` Claim it by ${formatClaimDate(self.expiresAt)} (${formatTimeLeft(self.expiresAt,now)} left).`:"";return[`${p2.bold(name)} isn't claimed yet.${deadline}`,` ${p2.cyan(claimUrl)}`,p2.dim("Opening it in your browser. Anyone with this link becomes the owner, so share it only with them.")].join(`
|
|
500
500
|
`)}__name(claimIntro,"claimIntro");function emitClaimResult(tokenFile,self,now){let name=self.displayName??self.projectName,{claimUrl}=tokenFile.file;if(self.claimState==="expired"){ui.error({command:"claim",code:"UNCLAIMED_PROJECT_EXPIRED",message:`${name} was not claimed in time. The hosted site and its content are being deleted.`,hint:"The code in this directory is intact. Sign in with `fimo login`, then run `fimo link` to put it in a new site.",details:{project_id:self.projectId}});return}let data={project_id:self.projectId,project_name:name,claim_state:self.claimState,claim_url:self.claimState==="claimable"?claimUrl:null,expires_at:self.expiresAt?.toISOString()??null,organization_id:self.organizationId,organization_name:self.organizationName,token_expires_at:self.tokenExpiresAt?.toISOString()??null};ui.result({command:"claim",data,render:__name(()=>renderClaimResult(palette,self,claimUrl,now),"render"),hint:self.claimState==="claimed"?"Run `fimo login`, then delete .fimo/credentials.local.json to keep working through your account.":"Give the claim link to the person who should own this site. Run `fimo claim` again at any time to see it."})}__name(emitClaimResult,"emitClaimResult");function renderClaimResult(p2,self,claimUrl,now){let name=self.displayName??self.projectName;if(self.claimState==="claimed"){let owner=self.organizationName?` into ${p2.bold(self.organizationName)}`:"",token=self.tokenExpiresAt?`This token keeps working until ${formatClaimDate(self.tokenExpiresAt)} (${formatTimeLeft(self.tokenExpiresAt,now)} left).`:"This token keeps working for a short while.";return[`${p2.green("\u2713")} ${p2.bold(name)} is claimed${owner}.`,` ${token}`].join(`
|
|
501
501
|
`)}let deadline=self.expiresAt?`Claim it by ${formatClaimDate(self.expiresAt)} (${formatTimeLeft(self.expiresAt,now)} left):`:"Claim it at:";return[`${p2.yellow("!")} ${p2.bold(name)} isn't claimed yet. ${deadline}`,` ${p2.cyan(claimUrl)}`].join(`
|
|
@@ -553,7 +553,7 @@ return __eta.res;
|
|
|
553
553
|
`)}}return returnStr}__name(compileBody,"compileBody");function trimWS(str,config,wsLeft,wsRight){let leftTrim,rightTrim;return Array.isArray(config.autoTrim)?(leftTrim=config.autoTrim[1],rightTrim=config.autoTrim[0]):leftTrim=rightTrim=config.autoTrim,(wsLeft||wsLeft===!1)&&(leftTrim=wsLeft),(wsRight||wsRight===!1)&&(rightTrim=wsRight),!rightTrim&&!leftTrim?str:leftTrim==="slurp"&&rightTrim==="slurp"?str.trim():(leftTrim==="_"||leftTrim==="slurp"?str=str.trimStart():(leftTrim==="-"||leftTrim==="nl")&&(str=str.replace(/^(?:\r\n|\n|\r)/,"")),rightTrim==="_"||rightTrim==="slurp"?str=str.trimEnd():(rightTrim==="-"||rightTrim==="nl")&&(str=str.replace(/(?:\r\n|\n|\r)$/,"")),str)}__name(trimWS,"trimWS");var escMap={"&":"&","<":"<",">":">",'"':""","'":"'"};function replaceChar(s){return escMap[s]}__name(replaceChar,"replaceChar");function XMLEscape(str){let newStr=String(str);return/[&<>"']/.test(newStr)?newStr.replace(/[&<>"']/g,replaceChar):newStr}__name(XMLEscape,"XMLEscape");var defaultConfig2={autoEscape:!0,autoFilter:!1,autoTrim:[!1,"nl"],cache:!1,cacheFilepaths:!0,debug:!1,escapeFunction:XMLEscape,filterFunction:__name(val=>String(val),"filterFunction"),functionHeader:"",parse:{exec:"",interpolate:"=",raw:"~"},plugins:[],rmWhitespace:!1,tags:["<%","%>"],useWith:!1,varName:"it",defaultExtension:".eta"},templateLitReg=/`(?:\\[\s\S]|\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})*}|(?!\${)[^\\`])*`/g,singleQuoteReg=/'(?:\\[\s\w"'\\`]|[^\n\r'\\])*?'/g,doubleQuoteReg=/"(?:\\[\s\w"'\\`]|[^\n\r"\\])*?"/g;function escapeRegExp(string){return string.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&")}__name(escapeRegExp,"escapeRegExp");function getLineNo(str,index){return str.slice(0,index).split(`
|
|
554
554
|
`).length}__name(getLineNo,"getLineNo");function parse5(str){let config=this.config,buffer=[],trimLeftOfNextStr=!1,lastIndex=0,parseOptions=config.parse;if(config.plugins)for(let i=0;i<config.plugins.length;i++){let plugin=config.plugins[i];plugin.processTemplate&&(str=plugin.processTemplate(str,config))}config.rmWhitespace&&(str=str.replace(/[\r\n]+/g,`
|
|
555
555
|
`).replace(/^\s+|\s+$/gm,"")),templateLitReg.lastIndex=0,singleQuoteReg.lastIndex=0,doubleQuoteReg.lastIndex=0;function pushString(strng,shouldTrimRightOfString){strng&&(strng=trimWS(strng,config,trimLeftOfNextStr,shouldTrimRightOfString),strng&&(strng=strng.replace(/\\|'/g,"\\$&").replace(/\r\n|\n|\r/g,"\\n"),buffer.push(strng)))}__name(pushString,"pushString");let prefixes=[parseOptions.exec,parseOptions.interpolate,parseOptions.raw].reduce(function(accumulator,prefix){return accumulator&&prefix?accumulator+"|"+escapeRegExp(prefix):prefix?escapeRegExp(prefix):accumulator},""),parseOpenReg=new RegExp(escapeRegExp(config.tags[0])+"(-|_)?\\s*("+prefixes+")?\\s*","g"),parseCloseReg=new RegExp("'|\"|`|\\/\\*|(\\s*(-|_)?"+escapeRegExp(config.tags[1])+")","g"),m;for(;m=parseOpenReg.exec(str);){let precedingString=str.slice(lastIndex,m.index);lastIndex=m[0].length+m.index;let wsLeft=m[1],prefix=m[2]||"";pushString(precedingString,wsLeft),parseCloseReg.lastIndex=lastIndex;let closeTag,currentObj=!1;for(;closeTag=parseCloseReg.exec(str);)if(closeTag[1]){let content2=str.slice(lastIndex,closeTag.index);parseOpenReg.lastIndex=lastIndex=parseCloseReg.lastIndex,trimLeftOfNextStr=closeTag[2],currentObj={t:prefix===parseOptions.exec?"e":prefix===parseOptions.raw?"r":prefix===parseOptions.interpolate?"i":"",val:content2};break}else{let char=closeTag[0];if(char==="/*"){let commentCloseInd=str.indexOf("*/",parseCloseReg.lastIndex);commentCloseInd===-1&&ParseErr("unclosed comment",str,closeTag.index),parseCloseReg.lastIndex=commentCloseInd}else char==="'"?(singleQuoteReg.lastIndex=closeTag.index,singleQuoteReg.exec(str)?parseCloseReg.lastIndex=singleQuoteReg.lastIndex:ParseErr("unclosed string",str,closeTag.index)):char==='"'?(doubleQuoteReg.lastIndex=closeTag.index,doubleQuoteReg.exec(str)?parseCloseReg.lastIndex=doubleQuoteReg.lastIndex:ParseErr("unclosed string",str,closeTag.index)):char==="`"&&(templateLitReg.lastIndex=closeTag.index,templateLitReg.exec(str)?parseCloseReg.lastIndex=templateLitReg.lastIndex:ParseErr("unclosed string",str,closeTag.index))}currentObj?(config.debug&&(currentObj.lineNo=getLineNo(str,m.index)),buffer.push(currentObj)):ParseErr("unclosed tag",str,m.index)}if(pushString(str.slice(lastIndex,str.length),!1),config.plugins)for(let i=0;i<config.plugins.length;i++){let plugin=config.plugins[i];plugin.processAST&&(buffer=plugin.processAST(buffer,config))}return buffer}__name(parse5,"parse");function handleCache(template,options){let templateStore=options&&options.async?this.templatesAsync:this.templatesSync;if(this.resolvePath&&this.readFile&&!template.startsWith("@")){let templatePath2=options.filepath,cachedTemplate=templateStore.get(templatePath2);if(this.config.cache&&cachedTemplate)return cachedTemplate;{let templateString=this.readFile(templatePath2),templateFn=this.compile(templateString,options);return this.config.cache&&templateStore.define(templatePath2,templateFn),templateFn}}else{let cachedTemplate=templateStore.get(template);if(cachedTemplate)return cachedTemplate;throw new EtaNameResolutionError("Failed to get template '"+template+"'")}}__name(handleCache,"handleCache");function render(template,data,meta){let templateFn,options={...meta,async:!1};return typeof template=="string"?(this.resolvePath&&this.readFile&&!template.startsWith("@")&&(options.filepath=this.resolvePath(template,options)),templateFn=handleCache.call(this,template,options)):templateFn=template,templateFn.call(this,data,options)}__name(render,"render");function renderAsync(template,data,meta){let templateFn,options={...meta,async:!0};typeof template=="string"?(this.resolvePath&&this.readFile&&!template.startsWith("@")&&(options.filepath=this.resolvePath(template,options)),templateFn=handleCache.call(this,template,options)):templateFn=template;let res=templateFn.call(this,data,options);return Promise.resolve(res)}__name(renderAsync,"renderAsync");function renderString(template,data){let templateFn=this.compile(template,{async:!1});return render.call(this,templateFn,data)}__name(renderString,"renderString");function renderStringAsync(template,data){let templateFn=this.compile(template,{async:!0});return renderAsync.call(this,templateFn,data)}__name(renderStringAsync,"renderStringAsync");var Eta$1=class{static{__name(this,"Eta$1")}constructor(customConfig){this.config=void 0,this.RuntimeErr=RuntimeErr,this.compile=compile,this.compileToString=compileToString,this.compileBody=compileBody,this.parse=parse5,this.render=render,this.renderAsync=renderAsync,this.renderString=renderString,this.renderStringAsync=renderStringAsync,this.filepathCache={},this.templatesSync=new Cacher({}),this.templatesAsync=new Cacher({}),this.resolvePath=null,this.readFile=null,customConfig?this.config={...defaultConfig2,...customConfig}:this.config={...defaultConfig2}}configure(customConfig){this.config={...this.config,...customConfig}}withConfig(customConfig){return{...this,config:{...this.config,...customConfig}}}loadTemplate(name,template,options){if(typeof template=="string")(options&&options.async?this.templatesAsync:this.templatesSync).define(name,this.compile(template,options));else{let templates=this.templatesSync;(template.constructor.name==="AsyncFunction"||options&&options.async)&&(templates=this.templatesAsync),templates.define(name,template)}}};function readFile2(path49){let res="";try{res=fs19.readFileSync(path49,"utf8")}catch(err){throw err?.code==="ENOENT"?new EtaFileResolutionError(`Could not find template: ${path49}`):err}return res}__name(readFile2,"readFile");function resolvePath2(templatePath2,options){let resolvedFilePath="",views=this.config.views;if(!views)throw new EtaFileResolutionError("Views directory is not defined");let baseFilePath=options&&options.filepath,defaultExtension=this.config.defaultExtension===void 0?".eta":this.config.defaultExtension,cacheIndex=JSON.stringify({filename:baseFilePath,path:templatePath2,views:this.config.views});if(templatePath2+=path16.extname(templatePath2)?"":defaultExtension,baseFilePath){if(this.config.cacheFilepaths&&this.filepathCache[cacheIndex])return this.filepathCache[cacheIndex];let absolutePathTest=absolutePathRegExp.exec(templatePath2);if(absolutePathTest&&absolutePathTest.length){let formattedPath=templatePath2.replace(/^\/*|^\\*/,"");resolvedFilePath=path16.join(views,formattedPath)}else resolvedFilePath=path16.join(path16.dirname(baseFilePath),templatePath2)}else resolvedFilePath=path16.join(views,templatePath2);if(dirIsChild(views,resolvedFilePath))return baseFilePath&&this.config.cacheFilepaths&&(this.filepathCache[cacheIndex]=resolvedFilePath),resolvedFilePath;throw new EtaFileResolutionError(`Template '${templatePath2}' is not in the views directory`)}__name(resolvePath2,"resolvePath");function dirIsChild(parent,dir){let relative3=path16.relative(parent,dir);return relative3&&!relative3.startsWith("..")&&!path16.isAbsolute(relative3)}__name(dirIsChild,"dirIsChild");var absolutePathRegExp=/^\\|^\//,Eta=class extends Eta$1{static{__name(this,"Eta")}constructor(...args){super(...args),this.readFile=readFile2,this.resolvePath=resolvePath2}};import{existsSync as existsSync3}from"node:fs";import{dirname as dirname3,resolve as resolve3}from"node:path";import{fileURLToPath as fileURLToPath5}from"node:url";var HERE=dirname3(fileURLToPath5(import.meta.url)),IS_BUNDLED=existsSync3(resolve3(HERE,"bundle.json")),PACKAGE_ROOT2=IS_BUNDLED?resolve3(HERE,"..",".."):resolve3(HERE,"..","..","..");function assetPath(...segments){return resolve3(PACKAGE_ROOT2,"assets",...segments)}__name(assetPath,"assetPath");var FORMS_REL="src/forms";function getFormFiles(formsDir){return existsSync4(formsDir)?readdirSync2(formsDir).filter(f=>f.endsWith(".json")).map(f=>join5(formsDir,f)):[]}__name(getFormFiles,"getFormFiles");function readForm(path49){try{return JSON.parse(readFileSync4(path49,"utf-8"))}catch{return null}}__name(readForm,"readForm");function generateIndexContent(forms3){let lines=["// AUTO-GENERATED \u26A0\uFE0F \u2014 do not edit by hand",""];for(let form of forms3){let pascal=pascalCase(form.name),varName=pascal.charAt(0).toLowerCase()+pascal.slice(1);lines.push(`export { ${pascal}Schema, parse${pascal}FormData, submit${pascal}, FORM_ID as ${varName}FormId } from "./${form.name}";`),lines.push(`export type { ${pascal}Data } from "./${form.name}";`)}return lines.push(""),lines.join(`
|
|
556
|
-
`)}__name(generateIndexContent,"generateIndexContent");function frameworkFormsTarget(framework){return framework==="nextjs"?"next":framework==="astro"?"astro":framework==="sveltekit"?"sveltekit":null}__name(frameworkFormsTarget,"frameworkFormsTarget");function hasPackageExport(cwd,entry){let slash=entry.indexOf("/"),name=slash===-1?entry:entry.slice(0,slash),subpath=slash===-1?".":`.${entry.slice(slash)}`,packagePath=join5(cwd,"node_modules",name,"package.json");if(!existsSync4(packagePath))return!1;try{let packageJson=JSON.parse(readFileSync4(packagePath,"utf-8"));return!!(packageJson.exports&&Object.prototype.hasOwnProperty.call(packageJson.exports,subpath))}catch{return!1}}__name(hasPackageExport,"hasPackageExport");function requiredFormEntries(target){return target==="next"?["fimo/forms","fimo-next","fimo-next/client"]:target==="sveltekit"?["fimo/forms","fimo-sveltekit"]:["fimo/forms",`fimo/${target}`]}__name(requiredFormEntries,"requiredFormEntries");function assertFrameworkRuntime(cwd,target){let missing=requiredFormEntries(target).filter(entry=>!hasPackageExport(cwd,entry));if(missing.length!==0)throw new Error(`Cannot generate ${target} form clients because the project cannot resolve ${missing.join(", ")}. Install the current Fimo packages, then run \`fimo validate\` again. No generated files were changed.`)}__name(assertFrameworkRuntime,"assertFrameworkRuntime");function generatedFormFiles(target){return target==="next"?[{suffix:".ts",runtimeImport:"fimo-next"},{suffix:".client.ts",runtimeImport:"fimo-next/client",clientDirective:"'use client';"}]:target==="astro"?[{suffix:".ts",runtimeImport:"fimo/astro"}]:target==="sveltekit"?[{suffix:".ts",runtimeImport:"fimo-sveltekit"}]:[]}__name(generatedFormFiles,"generatedFormFiles");function syncForms(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),formsDir=resolve4(cwd,FORMS_REL),formFiles=getFormFiles(formsDir),target=frameworkFormsTarget(options.framework);target&&formFiles.length>0&&assertFrameworkRuntime(cwd,target);let legacyTemplateSource=readFileSync4(assetPath("content-templates","forms","react.eta"),"utf-8"),frameworkTemplateSource=target?readFileSync4(assetPath("content-templates","forms","framework.eta"),"utf-8"):null,outputFiles=generatedFormFiles(target),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),expectedTsFiles=new Set,allForms=[],created=0,updated=0,deleted=0;for(let jsonPath of formFiles){let form=readForm(jsonPath);if(!form){console.error(`Failed to parse form: ${jsonPath}`);continue}form.name||(form.name=jsonPath.split("/").pop().replace(/\.json$/,"")),allForms.push(form);let formModel={...form,pascal:pascalCase(form.name)},files=target?outputFiles:[{suffix:".ts",runtimeImport:"",clientDirective:""}];for(let output of files){let tsPath=join5(formsDir,`${form.name}${output.suffix}`);expectedTsFiles.add(tsPath);try{let content2=eta.renderString(target?frameworkTemplateSource:legacyTemplateSource,{form:{...formModel,...output}}),dir=dirname4(tsPath);if(existsSync4(dir)||mkdirSync2(dir,{recursive:!0}),!existsSync4(tsPath)){writeFileSync2(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync4(tsPath,"utf-8")!==content2&&(writeFileSync2(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}catch(error){console.error(`Failed to generate ${tsPath}:`,error)}}}if(allForms.length>0){let indexPath=join5(formsDir,"index.ts");expectedTsFiles.add(indexPath);let indexContent=generateIndexContent(allForms);(!existsSync4(indexPath)||readFileSync4(indexPath,"utf-8")!==indexContent)&&(writeFileSync2(indexPath,indexContent,"utf-8"),log(`Updated: ${indexPath}`))}if(existsSync4(formsDir)){let allTsFiles=readdirSync2(formsDir).filter(f=>f.endsWith(".ts")).map(f=>join5(formsDir,f));for(let tsFile of allTsFiles)if(!expectedTsFiles.has(tsFile))try{unlinkSync(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}}return(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync forms: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}__name(syncForms,"syncForms");import{existsSync as existsSync5,mkdirSync as mkdirSync3,readFileSync as readFileSync5,readdirSync as readdirSync3,unlinkSync as unlinkSync2,writeFileSync as writeFileSync3}from"node:fs";import{basename,dirname as dirname5,join as join6,resolve as resolve5}from"node:path";import{z as z116}from"zod";var SCHEMAS_REL="src/schemas",GENERATED_REGISTRY_MARKER="// AUTO-GENERATED by `fimo` from src/schemas/*.json - DO NOT EDIT.",MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION="0.7.0",MINIMUM_FRAMEWORK_COMPANION_RUNTIME_VERSION="0.21.0-0",CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND="npm install fimo@latest",SCHEMA_DEFINITION_SCHEMA=z116.object({uid:z116.string().min(1),name:z116.string().min(1).optional(),isSingleton:z116.boolean().optional(),i18n:z116.object({enabled:z116.boolean().optional()}).optional(),groups:z116.array(z116.object({id:z116.string().min(1),label:z116.string().min(1),default:z116.boolean().optional()}).strict()).optional(),fields:z116.record(z116.string(),z116.unknown()).optional()}),RUNTIME_TYPE_IMPORT_ORDER=["Fields","FimoBoolean","FimoMedia","FimoPolymorphicReference","FimoReference","FimoRichText","FimoRichTextContent","FimoString","Populate","PopulatedResult","ProjectedWithPopulate","Query","Sort","Where","WithReferences"],CONTENT_TEMPLATE_PATHS={types:{current:"shared/types.eta",legacy:"types-template.eta"},sharedServer:{current:"shared/server.eta"},reactClient:{current:"react/client.eta",legacy:"hooks-template.eta"},nextServer:{current:"next/server.eta"},nextClient:{current:"next/client.eta"},svelteKitContent:{current:"sveltekit/content.eta"}};function getSchemaFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".json")).sort().map(f=>join6(schemasDir,f)):[]}__name(getSchemaFiles,"getSchemaFiles");function getGeneratedFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".ts")&&f!=="index.ts").map(f=>join6(schemasDir,f)):[]}__name(getGeneratedFiles,"getGeneratedFiles");function parseVersion(version){let match=/^(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?(?:\+.*)?$/.exec(version);return match?{parts:[Number(match[1]),Number(match[2]),Number(match[3])],prerelease:match[4]!==void 0}:null}__name(parseVersion,"parseVersion");function isVersionAtLeast(version,minimum){let parsed=parseVersion(version),parsedMinimum=parseVersion(minimum);if(!parsed||!parsedMinimum)return!1;for(let index=0;index<parsed.parts.length;index++)if(parsed.parts[index]!==parsedMinimum.parts[index])return parsed.parts[index]>parsedMinimum.parts[index];return!parsed.prerelease||parsedMinimum.prerelease}__name(isVersionAtLeast,"isVersionAtLeast");function packageExportsSubpath(packageJson,subpath){if(!packageJson||typeof packageJson!="object"||Array.isArray(packageJson))return!1;let exports2=packageJson.exports;return!!(exports2&&typeof exports2=="object"&&!Array.isArray(exports2)&&Object.prototype.hasOwnProperty.call(exports2,subpath))}__name(packageExportsSubpath,"packageExportsSubpath");function readProjectPackage(cwd,name){let packagePath=join6(cwd,"node_modules",name,"package.json");if(!existsSync5(packagePath))return null;try{return JSON.parse(readFileSync5(packagePath,"utf-8"))}catch{return null}}__name(readProjectPackage,"readProjectPackage");function resolveProjectRuntime(cwd){let packagePath=join6(cwd,"node_modules","fimo","package.json");if(!existsSync5(packagePath))throw new Error(`Cannot generate schema clients because the project-local fimo package could not be resolved from ${cwd}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);let packageJson;try{packageJson=JSON.parse(readFileSync5(packagePath,"utf-8"))}catch{packageJson=null}let version=packageJson&&typeof packageJson=="object"&&!Array.isArray(packageJson)?packageJson.version:null;if(typeof version!="string"||!parseVersion(version))throw new Error(`Cannot generate schema clients with project-local fimo@${typeof version=="string"?version:"unknown"}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return{packageRoot:dirname5(packagePath),version,providesLegacyReactRuntime:packageExportsSubpath(packageJson,"./ui"),providesReactRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-react"),"."),providesLegacyNextRuntime:packageExportsSubpath(packageJson,"./next")&&packageExportsSubpath(packageJson,"./next/client"),providesNextRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-next"),".")&&packageExportsSubpath(readProjectPackage(cwd,"fimo-next"),"./client"),providesAstroRuntime:packageExportsSubpath(packageJson,"./astro"),providesSvelteKitRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-sveltekit"),".")}}__name(resolveProjectRuntime,"resolveProjectRuntime");function contentRuntimeImportFor(framework,runtime){return framework==="nextjs"?isVersionAtLeast(runtime.version,MINIMUM_FRAMEWORK_COMPANION_RUNTIME_VERSION)?"fimo-next":"fimo/next":framework==="astro"?"fimo/astro":framework==="sveltekit"||framework==="sveltekit-1"?"fimo-sveltekit":isVersionAtLeast(runtime.version,MINIMUM_FRAMEWORK_COMPANION_RUNTIME_VERSION)?"fimo-react":"fimo/ui"}__name(contentRuntimeImportFor,"contentRuntimeImportFor");function templatePath(runtime,templateName){let template=CONTENT_TEMPLATE_PATHS[templateName];if(runtime&&!isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)){let legacyPath="legacy"in template?template.legacy:template.current;return join6(runtime.packageRoot,"assets","content-templates",legacyPath)}return assetPath("content-templates",template.current)}__name(templatePath,"templatePath");function resolveSchemaGenerationTarget(runtimeImport,runtime){if(runtimeImport==="fimo/ui"&&isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)&&!runtime.providesLegacyReactRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the legacy fimo/ui export required by this React project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo/ui")return"react";if(runtimeImport==="fimo-react"&&!runtime.providesReactRuntime)throw new Error(`Cannot generate schema clients because the project does not provide the fimo-react package required by this React project. Install fimo-react@${runtime.version} alongside fimo, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo-react")return"react";if(runtimeImport==="fimo/next"&&!runtime.providesLegacyNextRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the legacy fimo/next and fimo/next/client exports required by this Next.js project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo-next"&&!runtime.providesNextRuntime)throw new Error(`Cannot generate schema clients because the project does not provide the fimo-next and fimo-next/client exports required by this Next.js project. Install fimo-next@${runtime.version} alongside fimo, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo/astro"&&!runtime.providesAstroRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the fimo/astro export required by this Astro project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo-sveltekit"&&!runtime.providesSvelteKitRuntime)throw new Error(`Cannot generate schema clients because this SvelteKit project has no project-local fimo-sveltekit package. Run \`npm install fimo-sveltekit@${runtime.version}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return runtimeImport==="fimo/next"||runtimeImport==="fimo-next"?"next":runtimeImport==="fimo/astro"?"astro":"sveltekit"}__name(resolveSchemaGenerationTarget,"resolveSchemaGenerationTarget");function templatesForTarget(target,runtime,runtimeImport){return target==="next"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport},{suffix:".ts",path:templatePath(runtime,"nextServer"),runtimeImport},{suffix:".client.ts",path:templatePath(runtime,"nextClient"),runtimeImport:`${runtimeImport}/client`}]:target==="astro"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo/astro"},{suffix:".ts",path:templatePath(runtime,"sharedServer"),runtimeImport:"fimo/astro"}]:target==="sveltekit"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo-sveltekit"},{suffix:".ts",path:templatePath(runtime,"svelteKitContent"),runtimeImport:"fimo-sveltekit"}]:[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport},{suffix:".ts",path:templatePath(runtime,"reactClient"),runtimeImport}]}__name(templatesForTarget,"templatesForTarget");function loadSchemas(schemaFiles){let errors=[],schemas3=[],outputOwners=new Map,registryOwners=new Map;for(let path49 of schemaFiles){let fileUid=basename(path49,".json"),pascal=pascalCase(fileUid),existingOwner=outputOwners.get(pascal);existingOwner&&existingOwner!==fileUid?errors.push(`${basename(path49)} and ${existingOwner}.json both generate ${pascal}.ts. Rename one schema to keep generated module names unique.`):outputOwners.set(pascal,fileUid);let parsed;try{parsed=JSON.parse(readFileSync5(path49,"utf-8"))}catch(error){errors.push(`${basename(path49)} is invalid JSON: ${error instanceof Error?error.message:String(error)}`);continue}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){errors.push(`${basename(path49)} must contain a JSON object.`);continue}let candidate=parsed;if(typeof candidate.uid!="string"||candidate.uid.length===0){errors.push(`${basename(path49)} is missing "uid". Set it to "${fileUid}".`);continue}if(candidate.uid!==fileUid){errors.push(`${basename(path49)} declares uid "${candidate.uid}". It must match the file name "${fileUid}".`);continue}let validation=SCHEMA_DEFINITION_SCHEMA.safeParse(candidate);if(!validation.success){let details=validation.error.issues.map(issue=>`${issue.path.join(".")||"schema"}: ${issue.message}`).join("; ");errors.push(`${basename(path49)} has an invalid schema shape: ${details}`);continue}let registryKey=camelCase(validation.data.name??validation.data.uid),existingRegistryOwner=registryOwners.get(registryKey);if(existingRegistryOwner&&existingRegistryOwner!==fileUid){errors.push(`${basename(path49)} and ${existingRegistryOwner}.json both generate the content registry key "${registryKey}". Rename one schema display name to keep generated registry keys unique.`);continue}registryOwners.set(registryKey,fileUid),schemas3.push({pascal,registryKey,schema:validation.data})}if(errors.length>0)throw new Error(`Cannot generate schema clients:
|
|
556
|
+
`)}__name(generateIndexContent,"generateIndexContent");function frameworkFormsTarget(framework){return framework==="nextjs"?"next":framework==="astro"?"astro":framework==="sveltekit"?"sveltekit":null}__name(frameworkFormsTarget,"frameworkFormsTarget");function hasPackageExport(cwd,entry){let slash=entry.indexOf("/"),name=slash===-1?entry:entry.slice(0,slash),subpath=slash===-1?".":`.${entry.slice(slash)}`,packagePath=join5(cwd,"node_modules",name,"package.json");if(!existsSync4(packagePath))return!1;try{let packageJson=JSON.parse(readFileSync4(packagePath,"utf-8"));return!!(packageJson.exports&&Object.prototype.hasOwnProperty.call(packageJson.exports,subpath))}catch{return!1}}__name(hasPackageExport,"hasPackageExport");function requiredFormEntries(target){return target==="next"?["fimo/forms","fimo-next","fimo-next/client"]:target==="sveltekit"?["fimo/forms","fimo-sveltekit"]:["fimo/forms",`fimo/${target}`]}__name(requiredFormEntries,"requiredFormEntries");function assertFrameworkRuntime(cwd,target){let missing=requiredFormEntries(target).filter(entry=>!hasPackageExport(cwd,entry));if(missing.length!==0)throw new Error(`Cannot generate ${target} form clients because the project cannot resolve ${missing.join(", ")}. Install the current Fimo packages, then run \`fimo validate\` again. No generated files were changed.`)}__name(assertFrameworkRuntime,"assertFrameworkRuntime");function generatedFormFiles(target){return target==="next"?[{suffix:".ts",runtimeImport:"fimo-next"},{suffix:".client.ts",runtimeImport:"fimo-next/client",clientDirective:"'use client';"}]:target==="astro"?[{suffix:".ts",runtimeImport:"fimo/astro"}]:target==="sveltekit"?[{suffix:".ts",runtimeImport:"fimo-sveltekit"}]:[]}__name(generatedFormFiles,"generatedFormFiles");function syncForms(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),formsDir=resolve4(cwd,FORMS_REL),formFiles=getFormFiles(formsDir),target=frameworkFormsTarget(options.framework);target&&formFiles.length>0&&assertFrameworkRuntime(cwd,target);let legacyTemplateSource=readFileSync4(assetPath("content-templates","forms","react.eta"),"utf-8"),frameworkTemplateSource=target?readFileSync4(assetPath("content-templates","forms","framework.eta"),"utf-8"):null,outputFiles=generatedFormFiles(target),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),expectedTsFiles=new Set,allForms=[],created=0,updated=0,deleted=0;for(let jsonPath of formFiles){let form=readForm(jsonPath);if(!form){console.error(`Failed to parse form: ${jsonPath}`);continue}form.name||(form.name=jsonPath.split("/").pop().replace(/\.json$/,"")),allForms.push(form);let formModel={...form,pascal:pascalCase(form.name)},files=target?outputFiles:[{suffix:".ts",runtimeImport:"",clientDirective:""}];for(let output of files){let tsPath=join5(formsDir,`${form.name}${output.suffix}`);expectedTsFiles.add(tsPath);try{let content2=eta.renderString(target?frameworkTemplateSource:legacyTemplateSource,{form:{...formModel,...output}}),dir=dirname4(tsPath);if(existsSync4(dir)||mkdirSync2(dir,{recursive:!0}),!existsSync4(tsPath)){writeFileSync2(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync4(tsPath,"utf-8")!==content2&&(writeFileSync2(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}catch(error){console.error(`Failed to generate ${tsPath}:`,error)}}}if(allForms.length>0){let indexPath=join5(formsDir,"index.ts");expectedTsFiles.add(indexPath);let indexContent=generateIndexContent(allForms);(!existsSync4(indexPath)||readFileSync4(indexPath,"utf-8")!==indexContent)&&(writeFileSync2(indexPath,indexContent,"utf-8"),log(`Updated: ${indexPath}`))}if(existsSync4(formsDir)){let allTsFiles=readdirSync2(formsDir).filter(f=>f.endsWith(".ts")).map(f=>join5(formsDir,f));for(let tsFile of allTsFiles)if(!expectedTsFiles.has(tsFile))try{unlinkSync(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}}return(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync forms: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}__name(syncForms,"syncForms");import{existsSync as existsSync5,mkdirSync as mkdirSync3,readFileSync as readFileSync5,readdirSync as readdirSync3,unlinkSync as unlinkSync2,writeFileSync as writeFileSync3}from"node:fs";import{basename,dirname as dirname5,join as join6,resolve as resolve5}from"node:path";import{z as z117}from"zod";var SCHEMAS_REL="src/schemas",GENERATED_REGISTRY_MARKER="// AUTO-GENERATED by `fimo` from src/schemas/*.json - DO NOT EDIT.",MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION="0.7.0",MINIMUM_FRAMEWORK_COMPANION_RUNTIME_VERSION="0.21.0-0",CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND="npm install fimo@latest",SCHEMA_DEFINITION_SCHEMA=z117.object({uid:z117.string().min(1),name:z117.string().min(1).optional(),isSingleton:z117.boolean().optional(),i18n:z117.object({enabled:z117.boolean().optional()}).optional(),groups:z117.array(z117.object({id:z117.string().min(1),label:z117.string().min(1),default:z117.boolean().optional()}).strict()).optional(),fields:z117.record(z117.string(),z117.unknown()).optional()}),RUNTIME_TYPE_IMPORT_ORDER=["Fields","FimoBoolean","FimoMedia","FimoPolymorphicReference","FimoReference","FimoRichText","FimoRichTextContent","FimoString","Populate","PopulatedResult","ProjectedWithPopulate","Query","Sort","Where","WithReferences"],CONTENT_TEMPLATE_PATHS={types:{current:"shared/types.eta",legacy:"types-template.eta"},sharedServer:{current:"shared/server.eta"},reactClient:{current:"react/client.eta",legacy:"hooks-template.eta"},nextServer:{current:"next/server.eta"},nextClient:{current:"next/client.eta"},svelteKitContent:{current:"sveltekit/content.eta"}};function getSchemaFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".json")).sort().map(f=>join6(schemasDir,f)):[]}__name(getSchemaFiles,"getSchemaFiles");function getGeneratedFiles(schemasDir){return existsSync5(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".ts")&&f!=="index.ts").map(f=>join6(schemasDir,f)):[]}__name(getGeneratedFiles,"getGeneratedFiles");function parseVersion(version){let match=/^(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?(?:\+.*)?$/.exec(version);return match?{parts:[Number(match[1]),Number(match[2]),Number(match[3])],prerelease:match[4]!==void 0}:null}__name(parseVersion,"parseVersion");function isVersionAtLeast(version,minimum){let parsed=parseVersion(version),parsedMinimum=parseVersion(minimum);if(!parsed||!parsedMinimum)return!1;for(let index=0;index<parsed.parts.length;index++)if(parsed.parts[index]!==parsedMinimum.parts[index])return parsed.parts[index]>parsedMinimum.parts[index];return!parsed.prerelease||parsedMinimum.prerelease}__name(isVersionAtLeast,"isVersionAtLeast");function packageExportsSubpath(packageJson,subpath){if(!packageJson||typeof packageJson!="object"||Array.isArray(packageJson))return!1;let exports2=packageJson.exports;return!!(exports2&&typeof exports2=="object"&&!Array.isArray(exports2)&&Object.prototype.hasOwnProperty.call(exports2,subpath))}__name(packageExportsSubpath,"packageExportsSubpath");function readProjectPackage(cwd,name){let packagePath=join6(cwd,"node_modules",name,"package.json");if(!existsSync5(packagePath))return null;try{return JSON.parse(readFileSync5(packagePath,"utf-8"))}catch{return null}}__name(readProjectPackage,"readProjectPackage");function resolveProjectRuntime(cwd){let packagePath=join6(cwd,"node_modules","fimo","package.json");if(!existsSync5(packagePath))throw new Error(`Cannot generate schema clients because the project-local fimo package could not be resolved from ${cwd}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);let packageJson;try{packageJson=JSON.parse(readFileSync5(packagePath,"utf-8"))}catch{packageJson=null}let version=packageJson&&typeof packageJson=="object"&&!Array.isArray(packageJson)?packageJson.version:null;if(typeof version!="string"||!parseVersion(version))throw new Error(`Cannot generate schema clients with project-local fimo@${typeof version=="string"?version:"unknown"}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return{packageRoot:dirname5(packagePath),version,providesLegacyReactRuntime:packageExportsSubpath(packageJson,"./ui"),providesReactRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-react"),"."),providesLegacyNextRuntime:packageExportsSubpath(packageJson,"./next")&&packageExportsSubpath(packageJson,"./next/client"),providesNextRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-next"),".")&&packageExportsSubpath(readProjectPackage(cwd,"fimo-next"),"./client"),providesAstroRuntime:packageExportsSubpath(packageJson,"./astro"),providesSvelteKitRuntime:packageExportsSubpath(readProjectPackage(cwd,"fimo-sveltekit"),".")}}__name(resolveProjectRuntime,"resolveProjectRuntime");function contentRuntimeImportFor(framework,runtime){return framework==="nextjs"?isVersionAtLeast(runtime.version,MINIMUM_FRAMEWORK_COMPANION_RUNTIME_VERSION)?"fimo-next":"fimo/next":framework==="astro"?"fimo/astro":framework==="sveltekit"||framework==="sveltekit-1"?"fimo-sveltekit":isVersionAtLeast(runtime.version,MINIMUM_FRAMEWORK_COMPANION_RUNTIME_VERSION)?"fimo-react":"fimo/ui"}__name(contentRuntimeImportFor,"contentRuntimeImportFor");function templatePath(runtime,templateName){let template=CONTENT_TEMPLATE_PATHS[templateName];if(runtime&&!isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)){let legacyPath="legacy"in template?template.legacy:template.current;return join6(runtime.packageRoot,"assets","content-templates",legacyPath)}return assetPath("content-templates",template.current)}__name(templatePath,"templatePath");function resolveSchemaGenerationTarget(runtimeImport,runtime){if(runtimeImport==="fimo/ui"&&isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)&&!runtime.providesLegacyReactRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the legacy fimo/ui export required by this React project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo/ui")return"react";if(runtimeImport==="fimo-react"&&!runtime.providesReactRuntime)throw new Error(`Cannot generate schema clients because the project does not provide the fimo-react package required by this React project. Install fimo-react@${runtime.version} alongside fimo, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo-react")return"react";if(runtimeImport==="fimo/next"&&!runtime.providesLegacyNextRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the legacy fimo/next and fimo/next/client exports required by this Next.js project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo-next"&&!runtime.providesNextRuntime)throw new Error(`Cannot generate schema clients because the project does not provide the fimo-next and fimo-next/client exports required by this Next.js project. Install fimo-next@${runtime.version} alongside fimo, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo/astro"&&!runtime.providesAstroRuntime)throw new Error(`Cannot generate schema clients because project-local fimo@${runtime.version} does not provide the fimo/astro export required by this Astro project. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);if(runtimeImport==="fimo-sveltekit"&&!runtime.providesSvelteKitRuntime)throw new Error(`Cannot generate schema clients because this SvelteKit project has no project-local fimo-sveltekit package. Run \`npm install fimo-sveltekit@${runtime.version}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return runtimeImport==="fimo/next"||runtimeImport==="fimo-next"?"next":runtimeImport==="fimo/astro"?"astro":"sveltekit"}__name(resolveSchemaGenerationTarget,"resolveSchemaGenerationTarget");function templatesForTarget(target,runtime,runtimeImport){return target==="next"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport},{suffix:".ts",path:templatePath(runtime,"nextServer"),runtimeImport},{suffix:".client.ts",path:templatePath(runtime,"nextClient"),runtimeImport:`${runtimeImport}/client`}]:target==="astro"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo/astro"},{suffix:".ts",path:templatePath(runtime,"sharedServer"),runtimeImport:"fimo/astro"}]:target==="sveltekit"?[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport:"fimo-sveltekit"},{suffix:".ts",path:templatePath(runtime,"svelteKitContent"),runtimeImport:"fimo-sveltekit"}]:[{suffix:".types.ts",path:templatePath(runtime,"types"),runtimeImport},{suffix:".ts",path:templatePath(runtime,"reactClient"),runtimeImport}]}__name(templatesForTarget,"templatesForTarget");function loadSchemas(schemaFiles){let errors=[],schemas3=[],outputOwners=new Map,registryOwners=new Map;for(let path49 of schemaFiles){let fileUid=basename(path49,".json"),pascal=pascalCase(fileUid),existingOwner=outputOwners.get(pascal);existingOwner&&existingOwner!==fileUid?errors.push(`${basename(path49)} and ${existingOwner}.json both generate ${pascal}.ts. Rename one schema to keep generated module names unique.`):outputOwners.set(pascal,fileUid);let parsed;try{parsed=JSON.parse(readFileSync5(path49,"utf-8"))}catch(error){errors.push(`${basename(path49)} is invalid JSON: ${error instanceof Error?error.message:String(error)}`);continue}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){errors.push(`${basename(path49)} must contain a JSON object.`);continue}let candidate=parsed;if(typeof candidate.uid!="string"||candidate.uid.length===0){errors.push(`${basename(path49)} is missing "uid". Set it to "${fileUid}".`);continue}if(candidate.uid!==fileUid){errors.push(`${basename(path49)} declares uid "${candidate.uid}". It must match the file name "${fileUid}".`);continue}let validation=SCHEMA_DEFINITION_SCHEMA.safeParse(candidate);if(!validation.success){let details=validation.error.issues.map(issue=>`${issue.path.join(".")||"schema"}: ${issue.message}`).join("; ");errors.push(`${basename(path49)} has an invalid schema shape: ${details}`);continue}let registryKey=camelCase(validation.data.name??validation.data.uid),existingRegistryOwner=registryOwners.get(registryKey);if(existingRegistryOwner&&existingRegistryOwner!==fileUid){errors.push(`${basename(path49)} and ${existingRegistryOwner}.json both generate the content registry key "${registryKey}". Rename one schema display name to keep generated registry keys unique.`);continue}registryOwners.set(registryKey,fileUid),schemas3.push({pascal,registryKey,schema:validation.data})}if(errors.length>0)throw new Error(`Cannot generate schema clients:
|
|
557
557
|
- ${errors.join(`
|
|
558
558
|
- `)}
|
|
559
559
|
No generated files were changed.`);return schemas3}__name(loadSchemas,"loadSchemas");function renderContentRegistry(schemas3){let imports=schemas3.map(({pascal})=>`import * as ${pascal} from "./${pascal}";`).join(`
|
|
@@ -813,13 +813,13 @@ Aborted. Deleting site ${projectName}\u2026
|
|
|
813
813
|
`),fimo.execute("projects.delete",{projectId}).then(()=>{process.stderr.write(`Deleted site ${projectName}.
|
|
814
814
|
`)}).catch(error=>{process.stderr.write(`Failed to delete project: ${error instanceof Error?error.message:String(error)}
|
|
815
815
|
`)}).finally(()=>{process.exit(130)})},"handler");return process.on("SIGINT",handler),()=>{process.off("SIGINT",handler)}}__name(installAbortHandler,"installAbortHandler");function installArgsForPackageManager(_packageManager){return["install"]}__name(installArgsForPackageManager,"installArgsForPackageManager");function formatPackageManagerCommand(packageManager,args){return[packageManager,...args].join(" ")}__name(formatPackageManagerCommand,"formatPackageManagerCommand");async function configureGeneratedPackageManager(packageManager,targetDir){let packagePath=path32.join(targetDir,"package.json"),projectPackage=JSON.parse(await readFile4(packagePath,"utf8"));if(packageManager==="pnpm"?projectPackage.packageManager=GENERATED_PNPM_PACKAGE_MANAGER:projectPackage.packageManager===GENERATED_PNPM_PACKAGE_MANAGER&&delete projectPackage.packageManager,packageManager==="bun"){let trustedDependencies=Array.isArray(projectPackage.trustedDependencies)?projectPackage.trustedDependencies.filter(value=>typeof value=="string"):[];projectPackage.trustedDependencies=[...new Set([...trustedDependencies,"esbuild","fimo"])]}await writeFile2(packagePath,`${JSON.stringify(projectPackage,null,2)}
|
|
816
|
-
`)}__name(configureGeneratedPackageManager,"configureGeneratedPackageManager");async function installDependencies(packageManager,targetDir){let args=installArgsForPackageManager(packageManager),command=formatPackageManagerCommand(packageManager,args),installSp=spinner(`Installing dependencies (${command})`);try{return await execFileAsync8(packageManager,args,{cwd:targetDir}),installSp.succeed("Dependencies installed"),{installed:!0,command,error:null}}catch(error){let message=error instanceof Error?error.message:String(error);return installSp.fail(`Failed to install dependencies: ${message}`),{installed:!1,command,error:message}}}__name(installDependencies,"installDependencies");function detectPackageManager2(){return isCommandAvailable("pnpm")?"pnpm":isCommandAvailable("bun")?"bun":isCommandAvailable("yarn")?"yarn":"npm"}__name(detectPackageManager2,"detectPackageManager");function isCommandAvailable(command){let probe=process.platform==="win32"?"where":"which";return spawnSync2(probe,[command],{stdio:"ignore"}).status===0}__name(isCommandAvailable,"isCommandAvailable");async function resolveOrganization(fimo,explicit,options={}){if(explicit)return explicit;let activeOrganizationId=readCredentials()?.activeOrganization?.id,nonInteractive2=options.nonInteractive??(currentMode().format==="json"||!isInteractive());if(nonInteractive2&&activeOrganizationId)return activeOrganizationId;let orgs2;try{({data:orgs2}=await fimo.execute("organizations.list",{}))}catch(error){throw rethrowCliAuthError(error),new ScaffoldError("LIST_ORGS_FAILED",`Failed to list organizations: ${error instanceof Error?error.message:String(error)}`)}if(orgs2.length===0)throw new ScaffoldError("NO_ORGANIZATIONS","No organization found for this account.");if(orgs2.length===1)return orgs2[0].id;if(nonInteractive2)throw new ScaffoldError("ORGANIZATION_REQUIRED","Several organizations are available and no active organization is configured.","Pass --org <organizationId>, or run `fimo orgs switch --org <id-or-slug>` first.");let currentId=orgs2.some(organization=>organization.id===activeOrganizationId)?activeOrganizationId:void 0,selected=await _t({message:"Select an organization for this site",initialValue:currentId,options:orgs2.map(organization=>({value:organization.id,label:organization.name,hint:organization.id===currentId?"current":organization.slug}))});if(q(selected))throw new ScaffoldError("ORGANIZATION_SELECTION_CANCELLED","Organization selection cancelled.");return selected}__name(resolveOrganization,"resolveOrganization");var PACKAGE_MANAGERS=["npm","pnpm","yarn","bun"],MANUAL_INSTALL="manual";function emitInitOutcome(command,outcome){switch(outcome.status){case"ok":ui.result({command,data:outcome.data,render:__name(ctx=>renderInitSuccess(ctx,outcome.renderArgs),"render"),warnings:outcome.warnings.length>0?outcome.warnings:void 0});return;case"cancelled":ui.info({command,message:"Cancelled."});return;case"info":ui.info({command,message:outcome.message});return;case"error":ui.error({command,code:outcome.code,message:outcome.message,...outcome.hint?{hint:outcome.hint}:{}})}}__name(emitInitOutcome,"emitInitOutcome");function isPretty(){return currentMode().format==="pretty"}__name(isPretty,"isPretty");function nonInteractive(options){return options.yes===!0||currentMode().format==="json"||!isInteractive()}__name(nonInteractive,"nonInteractive");async function initCommand(dirArg,options){if(options.instructions){await emitAgentInstructions();return}isPretty()&&mt("
|
|
816
|
+
`)}__name(configureGeneratedPackageManager,"configureGeneratedPackageManager");async function installDependencies(packageManager,targetDir){let args=installArgsForPackageManager(packageManager),command=formatPackageManagerCommand(packageManager,args),installSp=spinner(`Installing dependencies (${command})`);try{return await execFileAsync8(packageManager,args,{cwd:targetDir}),installSp.succeed("Dependencies installed"),{installed:!0,command,error:null}}catch(error){let message=error instanceof Error?error.message:String(error);return installSp.fail(`Failed to install dependencies: ${message}`),{installed:!1,command,error:message}}}__name(installDependencies,"installDependencies");function detectPackageManager2(){return isCommandAvailable("pnpm")?"pnpm":isCommandAvailable("bun")?"bun":isCommandAvailable("yarn")?"yarn":"npm"}__name(detectPackageManager2,"detectPackageManager");function isCommandAvailable(command){let probe=process.platform==="win32"?"where":"which";return spawnSync2(probe,[command],{stdio:"ignore"}).status===0}__name(isCommandAvailable,"isCommandAvailable");async function resolveOrganization(fimo,explicit,options={}){if(explicit)return explicit;let activeOrganizationId=readCredentials()?.activeOrganization?.id,nonInteractive2=options.nonInteractive??(currentMode().format==="json"||!isInteractive());if(nonInteractive2&&activeOrganizationId)return activeOrganizationId;let orgs2;try{({data:orgs2}=await fimo.execute("organizations.list",{}))}catch(error){throw rethrowCliAuthError(error),new ScaffoldError("LIST_ORGS_FAILED",`Failed to list organizations: ${error instanceof Error?error.message:String(error)}`)}if(orgs2.length===0)throw new ScaffoldError("NO_ORGANIZATIONS","No organization found for this account.");if(orgs2.length===1)return orgs2[0].id;if(nonInteractive2)throw new ScaffoldError("ORGANIZATION_REQUIRED","Several organizations are available and no active organization is configured.","Pass --org <organizationId>, or run `fimo orgs switch --org <id-or-slug>` first.");let currentId=orgs2.some(organization=>organization.id===activeOrganizationId)?activeOrganizationId:void 0,selected=await _t({message:"Select an organization for this site",initialValue:currentId,options:orgs2.map(organization=>({value:organization.id,label:organization.name,hint:organization.id===currentId?"current":organization.slug}))});if(q(selected))throw new ScaffoldError("ORGANIZATION_SELECTION_CANCELLED","Organization selection cancelled.");return selected}__name(resolveOrganization,"resolveOrganization");var PACKAGE_MANAGERS=["npm","pnpm","yarn","bun"],MANUAL_INSTALL="manual";function emitInitOutcome(command,outcome){switch(outcome.status){case"ok":ui.result({command,data:outcome.data,render:__name(ctx=>renderInitSuccess(ctx,outcome.renderArgs),"render"),warnings:outcome.warnings.length>0?outcome.warnings:void 0});return;case"cancelled":ui.info({command,message:"Cancelled."});return;case"info":ui.info({command,message:outcome.message});return;case"error":ui.error({command,code:outcome.code,message:outcome.message,...outcome.hint?{hint:outcome.hint}:{}})}}__name(emitInitOutcome,"emitInitOutcome");function isPretty(){return currentMode().format==="pretty"}__name(isPretty,"isPretty");function nonInteractive(options){return options.yes===!0||currentMode().format==="json"||!isInteractive()}__name(nonInteractive,"nonInteractive");async function initCommand(dirArg,options){isPretty()&&mt("Set up your Fimo site"),emitInitOutcome("init",await runInit(dirArg,options))}__name(initCommand,"initCommand");async function newCommand(dirArg,options){if(options.instructions){await emitAgentInstructions();return}isPretty()&&mt("Create a Fimo site without an account"),emitInitOutcome("new",await runInit(dirArg,{...options,account:!1}))}__name(newCommand,"newCommand");async function runInit(dirArg,options){let framework;try{framework=resolveTemplateFramework(options.framework)}catch(error){if(error instanceof TemplateFrameworkError)return{status:"error",code:"FRAMEWORK_INVALID",message:error.message};throw error}let initOptions={...options,framework},cfg=loadConfig();if(initOptions.packageManager&&!PACKAGE_MANAGERS.includes(initOptions.packageManager.toLowerCase()))return{status:"error",code:"PACKAGE_MANAGER_INVALID",message:`Unknown package manager "${initOptions.packageManager}".`,hint:`Use one of: ${PACKAGE_MANAGERS.join(", ")}.`};let account=await resolveAccount(cfg,initOptions);if(typeof account=="object")return account;let accountless=account==="none",fimo=createCliFimoClient(cfg),creds=readCredentials(cfg),mode2=accountless?"new":await resolveUseExisting(initOptions);if(mode2==="cancelled")return{status:"cancelled"};let useExisting=mode2==="existing",planned=await planInit({fimo,creds,useExisting,accountless,dirArg,options:initOptions});if("status"in planned)return planned;let{plan}=planned,ran=useExisting?await runExisting({fimo,cfg,projectId:plan.projectId,dirArg,options:plan.options}):accountless?await runUnclaimed({cfg,targetDir:plan.targetDir,displayName:plan.displayName,options:plan.options}):await runNew({fimo,cfg,targetDir:plan.targetDir,displayName:plan.displayName,options:plan.options});if("status"in ran)return ran;let{checkout}=ran.run,scaffoldSummary=ran.run.summary,scaffoldedAgents=ran.run.selectedAgents,pushedInitial=!0;ran.run.scaffolded&&await configureGeneratedPackageManager(plan.options.templatePackageManager??"pnpm",checkout.targetDir);let depResult=await maybeInstallDependencies(checkout.targetDir,plan.packageManager);try{({pushedInitial}=await ran.run.finalize(checkout.targetDir))}finally{ran.run.releaseAbort()}let skills2=await maybeInstallSkills(plan.options,scaffoldedAgents),warnings=[];pushedInitial||warnings.push(accountless?"Initial commit was not pushed \u2014 the site's remote is empty. Run `fimo deploy` from the site directory to push it.":"Initial commit was not pushed \u2014 the site's remote is empty. Sign in (`fimo login`), then run `fimo deploy` from the site directory to push it.");let unclaimed=ran.run.unclaimed;return depResult.error&&warnings.push(`Dependency install failed: ${depResult.error}`),skills2.error&&warnings.push(skills2.error),{status:"ok",data:{ok:!0,project_id:checkout.projectId,project_name:checkout.projectName,mode:useExisting?"existing":"new",target_dir:checkout.targetDir,relative_dir:checkout.relativeTarget,scaffold:scaffoldSummary,installed_deps:depResult.installed,package_manager:depResult.packageManager,install_error:depResult.error,skills_set_up:skills2.setUp,skills_error:skills2.error,pushed_initial:pushedInitial,...unclaimed?{account:"none",claim:{url:unclaimed.claim.url,expires_at:unclaimed.claim.expiresAt.toISOString(),state:"claimable"},limits:{ttl_hours:unclaimed.limits.ttlHours,locked_features:unclaimed.limits.lockedFeatures,media:{total_bytes:unclaimed.limits.media.totalBytes,file_bytes:unclaimed.limits.media.fileBytes,max_files:unclaimed.limits.media.maxFiles,mime_types:unclaimed.limits.media.mimeTypes},database:{storage_bytes:unclaimed.limits.database.storageBytes,compute_seconds:unclaimed.limits.database.computeSeconds,max_compute_units:unclaimed.limits.database.maxComputeUnits}},token_file:PROJECT_TOKEN_FILE}:{}},renderArgs:{projectName:checkout.projectName,relativeDir:checkout.relativeTarget,isNew:!useExisting,installedDeps:depResult.installed,packageManager:depResult.packageManager,pushedInitial,...unclaimed?{claim:{url:unclaimed.claim.url,expiresAt:unclaimed.claim.expiresAt,ttlHours:unclaimed.limits.ttlHours}}:{}},warnings}}__name(runInit,"runInit");function renderInitSuccess(ctx,args){let p2=ctx.color?palette:makeColorPalette({forceDisable:!0});if(!args.pushedInitial)return renderInitPushFailed(p2,ctx.ascii,args);let check=ctx.ascii?"[ok]":"\u2705",pm=args.packageManager??"pnpm",dev=args.installedDeps?`${pm} dev`:`${pm} install`,devTail=args.installedDeps?"to launch your site's development server":`then ${p2.cyan(`${pm} dev`)} to launch it`,commands=[["npx fimo deploy","to push a preview of your site"],...args.claim?[]:[["npx fimo deploy --publish","to push your site live"]],["npx fimo skills install","to set up Fimo skills for your AI tools"],["npx fimo --help","to explore the CLI"]],width=Math.max(...commands.map(([c2])=>c2.length)),lines=[];lines.push(`${check} ${p2.bold(`Success! Your site ${args.projectName} ${args.isNew?"has been created":"is linked"}.`)}`),lines.push(""),args.claim&&(lines.push(...renderClaimBlock(p2,args.claim)),lines.push("")),args.relativeDir!=="."&&args.relativeDir!==""&&(lines.push(`${p2.cyan(`cd ${args.relativeDir}`)} ${p2.dim("to navigate to your site directory")}`),lines.push("")),lines.push(`Get started by running ${p2.cyan(dev)} ${devTail}`),lines.push(""),lines.push(""),lines.push(p2.bold("Other helpful commands:"));for(let[cmd,desc]of commands)lines.push(`${p2.cyan(cmd.padEnd(width))} ${p2.dim(desc)}`);return lines.join(`
|
|
817
817
|
`)}__name(renderInitSuccess,"renderInitSuccess");function renderInitPushFailed(p2,ascii,args){let warn=ascii?"[!]":"\u26A0\uFE0F",steps=[...args.claim?[]:[["npx fimo login","to sign in (if you are not already)"]],["npx fimo deploy","to push the first commit and finish setup"]],width=Math.max(...steps.map(([c2])=>c2.length)),lines=[];lines.push(`${warn} ${p2.bold(`Your site ${args.projectName} was created, but its first commit was not pushed.`)}`),lines.push(""),lines.push(p2.dim("The remote is empty until you push, so it can't be cloned or deployed yet.")),lines.push(""),args.relativeDir!=="."&&args.relativeDir!==""?lines.push(`${p2.cyan(`cd ${args.relativeDir}`)} ${p2.dim("then finish setup:")}`):lines.push(p2.dim("Finish setup:"));for(let[cmd,desc]of steps)lines.push(`${p2.cyan(cmd.padEnd(width))} ${p2.dim(desc)}`);return args.claim&&(lines.push(""),lines.push(...renderClaimBlock(p2,args.claim))),lines.join(`
|
|
818
818
|
`)}__name(renderInitPushFailed,"renderInitPushFailed");function renderClaimBlock(p2,claim){return[p2.bold(`Claim this site within ${claim.ttlHours} hours: ${claim.url}`),p2.dim(`Anyone with this link becomes the site's owner. Claim the site to publish, connect domains, and invite people. The link expires ${formatClaimDate(claim.expiresAt)} (${formatTimeLeft(claim.expiresAt)} left).`),p2.dim("Run `fimo claim` in the site directory to see the link again or wait for the claim.")]}__name(renderClaimBlock,"renderClaimBlock");async function resolveAccount(cfg,options){if(options.account===!1)return"none";if(readCredentials(cfg)?.access_token)return"account";if(nonInteractive(options))return{status:"error",code:"NOT_AUTHENTICATED",message:"You are not signed in to Fimo.",hint:"Run `fimo login` first, then re-run `fimo init`."};isPretty()&&O2.step("You are not signed in yet \u2014 opening your browser to sign in.");try{return await performBrowserLogin(cfg),"account"}catch(error){if(error instanceof LoginError)return{status:"error",code:error.code,message:error.message};throw error}}__name(resolveAccount,"resolveAccount");async function resolveUseExisting(options){if(options.projectId)return"existing";if(nonInteractive(options))return"new";let choice=await _t({message:"What do you want to do?",options:[{value:"new",label:"Create a new site"},{value:"existing",label:"Link an existing site"}]});return q(choice)?"cancelled":choice==="existing"?"existing":"new"}__name(resolveUseExisting,"resolveUseExisting");async function planInit(args){let{fimo,creds,useExisting,accountless,dirArg,options}=args,projectId,targetDir,displayName,derived={...options};if(useExisting)if(options.projectId)projectId=options.projectId;else{let picked=await selectProjectId({fimo,activeOrganizationId:creds?.activeOrganization?.id??null,message:"Select a site to link"});if(picked.status==="empty")return{status:"info",message:picked.message};if(picked.status!=="selected")return picked;projectId=picked.projectId}else{let resolved=await resolveTargetDir(dirArg,nonInteractive(options));if("status"in resolved)return resolved;if(targetDir=resolved.targetDir,displayName=resolved.displayName,fs34.existsSync(targetDir)&&fs34.readdirSync(targetDir).length>0){let name=path33.basename(targetDir);return{status:"error",code:"DIRECTORY_NOT_EMPTY",message:`The folder "${name}" already exists and isn't empty.`,hint:`Run \`fimo link\` inside "${name}" to adopt the application that is already there, or pick a different directory to scaffold a new one.`}}if(!accountless)try{derived.org=await resolveOrganization(fimo,options.org,{nonInteractive:nonInteractive(options)})}catch(error){if(error instanceof ScaffoldError&&error.code==="ORGANIZATION_SELECTION_CANCELLED")return{status:"cancelled"};if(error instanceof ScaffoldError)return{status:"error",code:error.code,message:error.message,...error.hint?{hint:error.hint}:{}};throw error}}if(nonInteractive(options))options.skills===!1&&!derived.agents&&(derived.agents="none");else{let wantSkills;if(options.skills===!0||options.skills===!1)wantSkills=options.skills;else{let alreadySetUp=(await detectAgentsWithFimoSkills()).length>0,answer=await ot2({message:alreadySetUp?"Fimo skills are already set up for your AI agents. Set them up again?":"Set up Fimo skills for your AI coding agents?",initialValue:!alreadySetUp});if(q(answer))return{status:"cancelled"};wantSkills=answer}if(wantSkills){let agents;try{agents=await selectAgents(options,{promptMessage:"Which agents do you want to set up?",detectFn:detectAgentsWithFimoSkills})}catch(err){return{status:"error",code:"AGENT_SELECTION_FAILED",message:err instanceof Error?err.message:String(err)}}derived.skills=!0,derived.agents=agents.length>0?agents.join(","):"none"}else derived.skills=!1,derived.agents="none"}let packageManager=options.install===!1?null:await resolvePackageManager(derived);return derived.templatePackageManager=options.packageManager?.toLowerCase()??packageManager??"pnpm",{plan:{projectId,targetDir,displayName,packageManager,options:derived}}}__name(planInit,"planInit");async function runExisting(args){let{fimo,cfg,projectId,dirArg,options}=args;try{let result=await cloneProject({fimo,cfg,projectId,dir:dirArg,branch:options.branch});return{run:{checkout:{projectId:result.project.id,projectName:result.project.displayName??result.project.name,targetDir:result.targetDir,relativeTarget:result.relativeTarget},scaffolded:!1,summary:null,selectedAgents:null,finalize:__name(async()=>({pushedInitial:!0}),"finalize"),releaseAbort:__name(()=>{},"releaseAbort")}}}catch(error){if(error instanceof CloneError&&error.code==="EMPTY_REMOTE"&&error.emptyRemote)return adoptEmptyRemote({cfg,ctx:error.emptyRemote,options});if(error instanceof CloneError)return{status:"error",code:error.code,message:error.message,...error.hint?{hint:error.hint}:{}};throw error}}__name(runExisting,"runExisting");async function adoptEmptyRemote(args){let{cfg,ctx,options}=args;isPretty()&&O2.step("This site has no content yet \u2014 scaffolding the site template and pushing the first commit.");try{let result=await scaffoldIntoProject({project:ctx.project,cfg,targetDir:ctx.targetDir,options});return{run:{checkout:{projectId:result.project.id,projectName:result.project.displayName??result.project.name,targetDir:result.targetDir,relativeTarget:result.relativeTarget},scaffolded:!0,summary:null,selectedAgents:result.selectedAgents,finalize:__name(targetDir=>finalizeInitialCommit({targetDir}),"finalize"),releaseAbort:__name(()=>{},"releaseAbort")}}}catch(error){if(error instanceof ScaffoldError)return{status:"error",code:error.code,message:error.message,...error.hint?{hint:error.hint}:{}};throw error}}__name(adoptEmptyRemote,"adoptEmptyRemote");async function runNew(args){let{fimo,cfg,targetDir,displayName,options}=args;try{let{scaffold,releaseAbort}=await scaffoldNewProject({fimo,cfg,targetDir,displayName,options});return{run:{checkout:{projectId:scaffold.project.id,projectName:scaffold.project.displayName??scaffold.project.name,targetDir:scaffold.targetDir,relativeTarget:scaffold.relativeTarget},scaffolded:!0,summary:null,selectedAgents:scaffold.selectedAgents,finalize:__name(dir=>finalizeInitialCommit({targetDir:dir}),"finalize"),releaseAbort}}}catch(error){if(error instanceof ScaffoldError)return{status:"error",code:error.code,message:error.message,...error.hint?{hint:error.hint}:{}};throw error}}__name(runNew,"runNew");async function runUnclaimed(args){let{cfg,targetDir,displayName,options}=args,createSpinner=spinner("Creating Fimo site"),provisioned;try{provisioned=await createUnclaimedProjectsService(cfg).provision({displayName:displayName??path33.basename(targetDir),cliVersion:getCliVersion()})}catch(error){return createSpinner.fail("Project creation failed"),provisionAbort(error)}let{claim,token}=provisioned,project={...provisioned.project,organizationId:null},projectName=project.displayName??project.name;if(createSpinner.succeed(`Site ${projectName} created (${project.id})`),currentMode().format==="pretty"){let claimBlock=renderClaimBlock(palette,{url:claim.url,expiresAt:claim.expiresAt,ttlHours:provisioned.limits.ttlHours});process.stderr.write(`
|
|
819
819
|
${claimBlock.join(`
|
|
820
820
|
`)}
|
|
821
821
|
|
|
822
|
-
`)}recordUnclaimedProject({projectId:project.id,name:projectName,dir:targetDir,claimUrl:claim.url,expiresAt:claim.expiresAt.toISOString(),createdAt:new Date().toISOString()},cfg);try{let scaffold=await scaffoldIntoProject({project,cfg:{...cfg,token},targetDir,options});return writeProjectToken(targetDir,{token,projectId:project.id,apiUrl:cfg.apiUrl,claimUrl:claim.url,expiresAt:claim.expiresAt.toISOString()}),excludeLocalCredentials(targetDir),{run:{checkout:{projectId:project.id,projectName,targetDir:scaffold.targetDir,relativeTarget:scaffold.relativeTarget},scaffolded:!0,summary:null,selectedAgents:scaffold.selectedAgents,finalize:__name(dir=>finalizeInitialCommit({targetDir:dir}),"finalize"),releaseAbort:__name(()=>{},"releaseAbort"),unclaimed:provisioned}}}catch(error){let recovery=`The site was created: claim it at ${claim.url}, or find it again with \`fimo projects unclaimed\`.`;if(error instanceof ScaffoldError)return{status:"error",code:error.code,message:error.message,hint:error.hint?`${error.hint} ${recovery}`:recovery};throw error}}__name(runUnclaimed,"runUnclaimed");function provisionAbort(error){return error instanceof ApiRequestError&&error.code==="
|
|
822
|
+
`)}recordUnclaimedProject({projectId:project.id,name:projectName,dir:targetDir,claimUrl:claim.url,expiresAt:claim.expiresAt.toISOString(),createdAt:new Date().toISOString()},cfg);try{let scaffold=await scaffoldIntoProject({project,cfg:{...cfg,token},targetDir,options});return writeProjectToken(targetDir,{token,projectId:project.id,apiUrl:cfg.apiUrl,claimUrl:claim.url,expiresAt:claim.expiresAt.toISOString()}),excludeLocalCredentials(targetDir),{run:{checkout:{projectId:project.id,projectName,targetDir:scaffold.targetDir,relativeTarget:scaffold.relativeTarget},scaffolded:!0,summary:null,selectedAgents:scaffold.selectedAgents,finalize:__name(dir=>finalizeInitialCommit({targetDir:dir}),"finalize"),releaseAbort:__name(()=>{},"releaseAbort"),unclaimed:provisioned}}}catch(error){let recovery=`The site was created: claim it at ${claim.url}, or find it again with \`fimo projects unclaimed\`.`;if(error instanceof ScaffoldError)return{status:"error",code:error.code,message:error.message,hint:error.hint?`${error.hint} ${recovery}`:recovery};throw error}}__name(runUnclaimed,"runUnclaimed");function provisionAbort(error){return error instanceof ApiRequestError&&error.code==="unclaimed_limit_reached"?{status:"error",code:"UNCLAIMED_LIMIT_REACHED",message:error.detail,hint:"Claim an existing site first (`fimo projects unclaimed` lists them), or run `fimo login`."}:{status:"error",code:"PROJECT_CREATE_FAILED",message:explainCreateProjectError(error)}}__name(provisionAbort,"provisionAbort");async function resolveTargetDir(dirArg,noPrompt2){if(dirArg)return{targetDir:path33.resolve(dirArg)};if(noPrompt2)return{status:"error",code:"DIRECTORY_REQUIRED",message:"A target directory is required to create a new site.",hint:"Pass [dir] (e.g. `fimo init my-site`), or `--project-id <id>` to link an existing site."};let input=await Ot({message:"Site name",placeholder:"My Fimo Site",validate:__name(value=>value&&value.trim().length>0?void 0:"site name required","validate")});if(q(input))return{status:"cancelled"};let displayName=String(input).trim(),folder=slugifyName(displayName)||"fimo-project";return{targetDir:path33.resolve(folder),displayName}}__name(resolveTargetDir,"resolveTargetDir");var NEW_URL="https://fimo.new";async function emitAgentInstructions(){let url=`${(process.env.FIMO_NEW_URL?.trim()||NEW_URL).replace(/\/+$/,"")}/llms.txt`;try{ui.raw({command:"new",value:await fetchAgentInstructions(url),field:"markdown"})}catch(error){ui.error({command:"new",code:"INSTRUCTIONS_UNAVAILABLE",message:`Could not load the agent instructions from ${url}: ${error instanceof Error?error.message:String(error)}`,hint:"Retry later, or run `npx fimo@latest new <dir> --yes --json` directly."})}}__name(emitAgentInstructions,"emitAgentInstructions");async function fetchAgentInstructions(url){let response=await fetch(url,{headers:{Accept:"text/markdown"},signal:AbortSignal.timeout(1e4)});if(!response.ok)throw new Error(`HTTP ${response.status}`);let body=await response.text();if((response.headers.get("content-type")??"").includes("text/html")||/^\s*<(!doctype|html)/i.test(body))throw new Error("the server returned HTML instead of Markdown");return body}__name(fetchAgentInstructions,"fetchAgentInstructions");async function maybeInstallDependencies(targetDir,packageManager){if(!packageManager)return{installed:!1,packageManager:null,error:null};let result=await installDependencies(packageManager,targetDir);return{installed:result.installed,packageManager,error:result.error}}__name(maybeInstallDependencies,"maybeInstallDependencies");async function resolvePackageManager(options){if(options.packageManager)return options.packageManager.toLowerCase();let detected=detectPackageManager2();if(nonInteractive(options))return detected;let selected=await _t({message:"Install dependencies with which package manager?",initialValue:detected,options:[...PACKAGE_MANAGERS.map(pm=>({value:pm,label:pm})),{value:MANUAL_INSTALL,label:"Manual \u2014 I'll install dependencies myself"}]});return q(selected)||selected===MANUAL_INSTALL?null:selected}__name(resolvePackageManager,"resolvePackageManager");async function maybeInstallSkills(options,scaffoldedAgents){if(options.skills===!1)return{setUp:!1,error:null};if(options.skills!==!0&&nonInteractive(options))return{setUp:!1,error:null};let agentsFlag=options.agents;if(scaffoldedAgents!==null){if(scaffoldedAgents.length===0)return{setUp:!1,error:null};agentsFlag=scaffoldedAgents.join(",")}else if(nonInteractive(options)&&!agentsFlag)return{setUp:!1,error:null};let outcome=await runSkillsInstall({agents:agentsFlag,agent:scaffoldedAgents!==null?void 0:options.agent,yes:!0});return outcome.status==="error"&&outcome.code==="NO_AGENTS_SELECTED"?{setUp:!1,error:null}:outcome.status==="ok"?{setUp:!0,error:outcome.data.ok?null:"Some skills failed to install."}:outcome.status==="cancelled"?{setUp:!1,error:null}:{setUp:!1,error:outcome.message}}__name(maybeInstallSkills,"maybeInstallSkills");import fs35 from"node:fs";import path34 from"node:path";init_dist();init_auth();init_config();init_project();function registerIntegrationsCommands(program2){let integrations=program2.command("integrations").description("Manage site integrations").addHelpText("after",`
|
|
823
823
|
Examples:
|
|
824
824
|
fimo integrations list
|
|
825
825
|
fimo integrations info firecrawl
|
|
@@ -979,10 +979,10 @@ Header values use Name=secret:KEY, Name=bearer:KEY, Name=token:KEY, or Name=lite
|
|
|
979
979
|
`)}__name(formatHelpWithGroupedCommands,"formatHelpWithGroupedCommands");function formatGroupedCommandSections(cmd,helper,groups,termWidth){let visibleCommands=helper.visibleCommands(cmd);if(visibleCommands.length===0)return[];let commandByName=new Map(visibleCommands.map(command=>[command.name(),command])),renderedNames=new Set,sections=[];for(let group of groups){let rows=group.commands.map(name=>commandByName.get(name)).filter(command=>command!==void 0).map(command=>(renderedNames.add(command.name()),indentBlock(helper.formatItem(helper.styleSubcommandTerm(helper.subcommandTerm(command)),termWidth,helper.styleSubcommandDescription(helper.subcommandDescription(command)),helper))));rows.length>0&&(sections.length>0&§ions.push(""),sections.push(` ${group.title}:`,...rows))}let ungroupedRows=visibleCommands.filter(command=>!renderedNames.has(command.name())).map(command=>indentBlock(helper.formatItem(helper.styleSubcommandTerm(helper.subcommandTerm(command)),termWidth,helper.styleSubcommandDescription(helper.subcommandDescription(command)),helper)));return ungroupedRows.length>0&&(sections.length>0&§ions.push(""),sections.push(" Other commands:",...ungroupedRows)),sections}__name(formatGroupedCommandSections,"formatGroupedCommandSections");function indentBlock(value){return value.split(`
|
|
980
980
|
`).map(line=>` ${line}`).join(`
|
|
981
981
|
`)}__name(indentBlock,"indentBlock");init_sdk_transport();init_color();init_project_context();function computeVersionString(){let pkgVersion="0.0.0";try{let pkg=JSON.parse(fs48.readFileSync(path48.join(CLI_ROOT,"package.json"),"utf8"));typeof pkg.version=="string"&&pkg.version.length>0&&(pkgVersion=pkg.version)}catch{}let releaseId;try{let release=JSON.parse(fs48.readFileSync(path48.join(CLI_ROOT,"release.json"),"utf8"));typeof release.id=="string"&&release.id.length>0&&(releaseId=release.id)}catch{}let{apiUrl}=loadConfig(),detailParts=[];return releaseId&&detailParts.push(`release ${releaseId}`),detailParts.push(apiUrl),`fimo ${pkgVersion} (${detailParts.join(", ")})`}__name(computeVersionString,"computeVersionString");program.name("fimo").description("Fimo CLI").version(computeVersionString()).option("--branch <name>","Override the target Branch (analytics reads default to prod; other commands use the current Git branch or FIMO_ENV)").option("--json","Emit one structured JSON envelope per command (for tools / agents). FIMO_OUTPUT=json env also enables this.").option("--no-color","Disable colour in pretty mode (NO_COLOR env var also honoured)").option("--ascii","Use ASCII fallbacks for unicode glyphs (\u2713 \u2192 [ok], etc.) - for legacy terminals").hook("preAction",async(thisCommand,actionCommand)=>{let opts=thisCommand.optsWithGlobals();initUi({json:opts.json===!0,noColor:opts.color===!1,ascii:opts.ascii===!0,jsonEnvVar:"FIMO_OUTPUT",asciiEnvVar:"FIMO_ASCII"}),await printUnclaimedReminder(commandPath(actionCommand))});var NO_UNCLAIMED_REMINDER=new Set(["claim","whoami","init","login","logout","git-credential","projects unclaimed"]);function commandPath(command){let names=[];for(let current=command;current?.parent;current=current.parent)names.unshift(current.name());return names.join(" ")}__name(commandPath,"commandPath");async function printUnclaimedReminder(path49){if(!(currentMode().format!=="pretty"||NO_UNCLAIMED_REMINDER.has(path49)))try{let cfg=loadConfig(),auth=resolveAuth(cfg);if(auth?.kind!=="project"||!auth.tokenFile)return;let reminder=await unclaimedReminder(cfg,auth.tokenFile);reminder&&process.stderr.write(`${palette.yellow("!")} ${reminder}
|
|
982
|
-
`)}catch{}}__name(printUnclaimedReminder,"printUnclaimedReminder");program.command("login").description("Sign in through your browser").action(loginCommand);program.command("logout").description("Revoke the current session and clear local credentials").action(logoutCommand);program.command("whoami").description("Show the current signed-in user").action(whoamiCommand);program.command("claim"
|
|
982
|
+
`)}catch{}}__name(printUnclaimedReminder,"printUnclaimedReminder");program.command("login").description("Sign in through your browser").action(loginCommand);program.command("logout").description("Revoke the current session and clear local credentials").action(logoutCommand);program.command("whoami").description("Show the current signed-in user").action(whoamiCommand);program.command("claim").description("Show the claim link of a site created without an account, open it, and wait for the claim").option("--no-open","Print the claim link without opening a browser").option("--no-wait","Return right away instead of waiting for the claim").action(options=>claimCommand(options));registerProjectSecretsCommands(program);registerIntegrationsCommands(program);registerMcpCommands(program);registerChannelsCommands(program);registerSchedulesCommands(program);registerHistoryCommands(program);registerSupportCommands(program);registerWebhooksCommands(program);registerLocalesCommands(program);registerEnvironmentsCommands(program);program.command("invite").description("Invite a user to an organization or site").option("--target <target>","Invite target: organization or project (for a site)").option("--org <organizationId>","Organization ID (defaults to active when needed)").option("--project <projectId>","Site ID (defaults to the current site when available)").option("--email <email>","Email address of the user to invite").option("--role <role>","Role or access level to grant").option("-C, --cwd <dir>","Site directory used to resolve the current site").option("-y, --yes","Skip the confirmation prompt").option("--resend","Resend an existing pending organization invite").action(inviteCommand);program.command("clone").description("Clone an existing Fimo site locally").argument("[projectId]","Site ID to clone").argument("[dir]","Target directory (defaults to the site name)").option("--branch <name>","Branch to clone (defaults to main)").action(cloneCommand);program.command("link").description("Link the current application to a Fimo site, in place (repairs an existing link)").argument("[projectId]","Site ID to link (defaults to the linked site, else prompts)").option("--branch <name>","Branch to link (defaults to the current git branch, else main)").option("--relink","Replace an existing link to a different site").option("-C, --cwd <dir>","Application directory").action(linkCommand);program.command("init").description("Set up a Fimo site locally: sign in, create or link a site, install deps and skills").argument("[dir]","Target directory").option("--project-id <id>","Link an existing site instead of creating a new one").option("--org <organizationId>","Target organization ID when creating (recommended for agents and CI)").option("--branch <name>","Branch to check out when linking an existing site (defaults to main)").option("--framework <framework>","Site scaffold: react-router | vite | astro | nextjs | sveltekit (defaults to nextjs)").option("--template-root <path>","Override template directory when creating").option("--package-manager <pm>","Install dependencies with: npm | pnpm | yarn | bun").option("--install","Install dependencies after checkout").option("--no-install","Skip dependency installation after checkout").option("--skills","Install the global Fimo skill for your AI coding agents").option("--no-skills","Skip installing the global Fimo skill").option("--agents <list>",'Comma-separated list of AI agents to install the global Fimo skill for (e.g. claude-code,cursor). Pass "none" to skip.').option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev=[])=>[...prev,value]).option("-y, --yes","Run non-interactively using defaults (no prompts)").action(initCommand);program.command("new").description(`Create a site without an account; a person claims it within ${UNCLAIMED_PLAN.ttlHours} hours through the printed claim link`).argument("[dir]","Target directory").option("--instructions","Print the setup instructions for coding agents and exit without creating anything").option("--framework <framework>","Site scaffold: react-router | vite | astro | nextjs | sveltekit (defaults to nextjs)").option("--template-root <path>","Override template directory").option("--package-manager <pm>","Install dependencies with: npm | pnpm | yarn | bun").option("--install","Install dependencies after scaffolding").option("--no-install","Skip dependency installation after scaffolding").option("--skills","Install the global Fimo skill for your AI coding agents").option("--no-skills","Skip installing the global Fimo skill").option("--agents <list>",'Comma-separated list of AI agents to install the global Fimo skill for (e.g. claude-code,cursor). Pass "none" to skip.').option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev=[])=>[...prev,value]).option("-y, --yes","Run non-interactively using defaults (no prompts)").action(newCommand);var migrate=program.command("migrate").description("Set up a Fimo site as the target of an agent-driven migration").action(()=>{migrate.help()});migrate.command("init").description("Set up the migration target: link or create its Fimo site, scaffold it, and push the first commit").argument("[dir]","Target Fimo site directory (creates one if empty/missing)").option("-C, --cwd <dir>","Existing site directory when omitting [dir]").option("--project-id <projectId>","Link an owner-supplied existing site (delegates to `fimo init`)").option("--org <organizationId>","Target organization ID when creating a new site").option("--framework <framework>","Site scaffold: react-router | vite | astro | nextjs | sveltekit (defaults to react-router)").option("--template-root <path>","Override template directory when creating a new site").option("--install","Install dependencies after scaffolding a new site").option("--no-install","Skip dependency installation after scaffolding a new site").option("--agents <list>","Comma-separated list of AI agents to set up when creating a new site (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev=[])=>[...prev,value]).option("--mode <mode>","Local skill install method for newly created sites: symlink | copy").option("--source-platform <platform>","Where the site comes from: webflow | framer | squarespace | wix | carrd | wordpress | nextjs | astro | react-router | other").option("--json","Output the setup receipt as JSON").action((dir,_options,command)=>migrateInitCommand(dir,command.optsWithGlobals()));program.command("deploy").description("Push the current Branch to Fimo and deploy to Preview (use --publish from the Production source)").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--publish","Also publish the new version after deploying to preview").option("-m, --message <msg>","Commit message for any uncommitted changes").option("--no-restart","Don't restart the sandbox dev server after pull \u2014 rely on Vite HMR. Use when only HMR-safe files changed (components/pages/styles/content). See the `fimo` skill for when to use this.").option("--no-wait","Don't wait for the deployed preview to serve a page. Validation, push, and sandbox sync are still waited for; the result reports readiness as skipped. Not a substitute for --no-restart.").option("--force","Deploy even if validation fails (escape hatch; may still fail later in the sandbox)").action(deployCommand);addPaginationOptions(program.command("logs").description("Show the current Branch sandbox's dependency-install and dev-server output (newest first)"),{defaultLimit:200,maxLimit:1e3,legacyCursor:"before"}).option("-C, --cwd <dir>","Run against this directory instead of cwd").addHelpText("after",`
|
|
983
983
|
Logs come from the sandbox's own process buffers, so they end when the sandbox does.
|
|
984
984
|
There is no --follow; re-run the command instead.
|
|
985
|
-
`).action(logsCommand);program.command("validate").description("Run all checks and sync local state with the Fimo backend").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--json","Emit structured JSON output (for CI / agents)").action(validateCommand);program.command("update").description("Update this checkout's Fimo packages to an exact release and apply the bundled migrations").argument("<version>","Exact target version, for example 1.0.0").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--dry-run","Show the update plan without writing anything").option("--apply","Apply without prompting (required in --json / non-interactive shells)").option("--allow-dirty","Skip the clean-working-tree check").option("--no-install","Skip dependency installation after applying").option("--no-validate","Skip `fimo validate` after applying").action(updateCommand3);program.command("describe [path]").description("Print a structured snapshot of the current Fimo site (read-only)").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--depth <n>","Tree depth (default 3). Ignored when --full is set.").option("--full","Disable depth and width truncation (still respects the 10k-entry cap)").option("--json","Emit structured JSON output (for CI / agents)").action(describeCommand);program.command("credits").description("Show the current site credit balance").option("-C, --cwd <dir>","Site directory").option("--project <projectId>","Site ID (defaults to the current site)").option("--json","Emit structured JSON output").action(creditsCommand);program.command("delete").description("Delete the current linked site").option("-C, --cwd <dir>","Site directory").option("-y, --yes","Skip confirmation prompt").action(options=>projectsDeleteCommand(void 0,options));program.command("unpublish").description("Unpublish the current site").option("-C, --cwd <dir>","Site directory").action(options=>projectsUnpublishCommand(void 0,options));program.command("rename").description("Set the display name of the current site").argument("<name>",'New display name (e.g. "Acme Blog")').option("-C, --cwd <dir>","Site directory").action((name,options)=>projectsRenameCommand(name,void 0,options));var orgs=program.command("orgs").description("Manage organizations");orgs.command("list").description("List organizations you belong to").action(orgsListCommand);orgs.command("switch").description("Switch the active organization used by `fimo init`").option("--org <id-or-slug>","Switch to this organization without prompting").action(switchCommand);orgs.command("members").description("List members of an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(orgsMembersCommand);var referral=program.command("referral").description("Share and inspect your referral program tools");referral.command("link").description("Print your referral link").action(referralLinkCommand);referral.command("stats").description("Show your referral stats").action(referralStatsCommand);var projects=program.command("projects").description("Manage sites across an organization");projects.command("list").description("List sites in an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(projectsListCommand);projects.command("unclaimed",{hidden:!0}).description("List sites created without an account on this machine, with their claim links and state").action(projectsUnclaimedCommand);projects.command("create").description("Scaffold a new site (alias of `fimo init`)").argument("[dir]","Target directory").option("--org <organizationId>","Target organization ID (auto if you belong to one)").option("--framework <framework>","Site scaffold: react-router | vite | astro | nextjs | sveltekit (defaults to nextjs)").option("--template-root <path>","Override template directory").option("--package-manager <pm>","Install dependencies with: npm | pnpm | yarn | bun").option("--install","Install dependencies after scaffolding").option("--no-install","Skip dependency installation after scaffolding").action(initCommand);projects.command("clone").description("Clone an existing Fimo site locally").argument("[projectId]","Site ID to clone").argument("[dir]","Target directory (defaults to the site name)").option("--branch <name>","Branch to clone (defaults to main)").action(cloneCommand);projects.command("delete").description("Delete a site (defaults to the current linked site)").argument("[projectId]","Explicit site ID").option("-C, --cwd <dir>","Site directory").option("-y, --yes","Skip confirmation prompt").action(projectsDeleteCommand);projects.command("publish").description("Publish a site (defaults to the current site)").argument("[projectId]","Explicit site ID").option("-C, --cwd <dir>","Site directory").action(projectsPublishCommand);projects.command("unpublish").description("Unpublish a site (defaults to the current site)").argument("[projectId]","Explicit site ID").option("-C, --cwd <dir>","Site directory").action(projectsUnpublishCommand);projects.command("rename").description("Set the display name of a site (defaults to the current site)").argument("<name>",'New display name (e.g. "Acme Blog")').argument("[projectId]","Explicit site ID").option("-C, --cwd <dir>","Site directory").action(projectsRenameCommand);projects.command("transfer").description("Move a site to another organization you administer (defaults to the current site)").argument("[projectId]","Explicit site ID").option("--to <organization>","Destination organization ID or slug").option("-C, --cwd <dir>","Site directory").option("-y, --yes","Skip confirmation prompt").action(projectsTransferCommand);var domains=program.command("domains").description("Manage your default URL and custom domains");domains.command("list").alias("ls").description("Show the default URL and any custom domains").option("--project <projectId>","Site ID (defaults to the current site)").option("-C, --cwd <dir>","Site directory").option("--json","Output as JSON").action(domainsListCommand);domains.command("rename-default").description("Rename your default URL (the <slug>.fimo.site subdomain Fimo provides)").argument("<slug>",'New slug (e.g. "acme-coffee")').option("--project <projectId>","Site ID (defaults to the current site)").option("-C, --cwd <dir>","Site directory").option("--json","Output as JSON").action(domainsRenameDefaultCommand);domains.command("suggest-default").description("Suggest available default URLs; pick one to claim (or list with --json)").option("--base <text>","Override the base text used to generate suggestions (defaults to your site display name)").option("--max <n>","Number of suggestions to fetch (1\u201310, default 5)").option("--pick <slug-or-index>","Non-interactive: claim this suggestion by slug or numeric index").option("--project <projectId>","Site ID (defaults to the current site)").option("-C, --cwd <dir>","Site directory").option("--json","Output as JSON (no prompt, no claim)").action(domainsSuggestDefaultCommand);domains.command("add").description("Attach a custom domain to your site (requires an eligible plan)").argument("<hostname>",'The hostname to attach (e.g. "blog.example.com")').option("--redirect-www","Also configure an apex \u2192 www redirect").option("--wait [duration]","Poll until DNS is verified (e.g. --wait, --wait 10m)").option("--project <projectId>","Site ID (defaults to the current site)").option("-C, --cwd <dir>","Site directory").option("--json","Output the resulting domain record as JSON after instructions").action(domainsAddCommand);domains.command("remove").alias("rm").description("Detach a custom domain by hostname or ID").argument("<hostname-or-id>","Hostname or domain ID").option("-y, --yes","Skip the confirmation prompt").option("--project <projectId>","Site ID (defaults to the current site)").option("-C, --cwd <dir>","Site directory").action(domainsRemoveCommand);domains.command("refresh").description("Re-check DNS and SSL status for a custom domain").argument("<hostname-or-id>","Hostname or domain ID").option("--wait [duration]","Poll until SSL is active (default; pass --no-wait to print one snapshot)").option("--no-wait","Print the refreshed status once and exit").option("--project <projectId>","Site ID (defaults to the current site)").option("-C, --cwd <dir>","Site directory").option("--json","Output the resulting domain record as JSON").action(domainsRefreshCommand);domains.command("search").description("Search for available domain names to buy through Fimo").argument("<keyword>",'Search keyword (e.g. "acme coffee")').option("--tld <list>",'Restrict TLDs (comma-separated, e.g. "com,io,dev")').option("--max-price <amount>","Filter results to this purchase price ceiling (in dollars)").option("--limit <n>","Truncate to the first N results (default 20)").option("--json","Output as JSON").action(domainsSearchCommand);domains.command("pricing").description("Show the price for a specific domain (purchase + renewal)").argument("<domain>",'Domain name (e.g. "example.com")').option("--years <n>","Multiply purchase price by this many years (default 1)").option("--json","Output as JSON").action(domainsPricingCommand);domains.command("buy").description("Buy a domain through Fimo. Creates a checkout invoice; no charge until you pay it in the browser.").argument("<domain>",'Domain name to register (e.g. "example.com")').option("--years <n>","Years to register for (default uses the TLD minimum)").option("--auto-renew","Enable auto-renewal (default)").option("--no-auto-renew","Disable auto-renewal \u2014 domain will not renew automatically").option("-y, --yes","Skip the interactive confirmation prompt").option("--open","Open the checkout URL in your browser after creating the invoice").option("--wait [duration]","Poll until payment completes and registration succeeds").option("--org <organizationId>","Organization ID (defaults to the current site's org)").option("-C, --cwd <dir>","Site directory used to resolve the org").option("--json","Output the resulting invoice record as JSON").action(domainsBuyCommand);domains.command("owned").description("List domains your organization has registered through Fimo").option("--org <organizationId>","Organization ID (defaults to the current site's org)").option("--status <list>",'Filter by status (comma-separated, e.g. "owned,pending_payment")').option("--limit <n>","Truncate to the first N results").option("-C, --cwd <dir>","Site directory used to resolve the org").option("--json","Output as JSON").action(domainsOwnedCommand);var scripts=program.command("scripts",{hidden:!0}).description("Internal/advanced primitives. Most users want `fimo validate`.");scripts.command("sync-schemas").description("Regenerate TypeScript clients for src/schemas/*.json").option("-C, --cwd <dir>","Site directory").action(syncSchemasCommand);scripts.command("sync-forms").description("Regenerate TypeScript clients for src/forms/*.json").option("-C, --cwd <dir>","Site directory").action(syncFormsCommand);scripts.command("validate-route-metadata").description("Cross-validate src/routes.ts against .fimo/config.json#routes (v4)").option("-C, --cwd <dir>","Site directory").action(validateRouteMetadataCommand);scripts.command("extract-translations").description("Legacy local helper: scan src/ for literal t() label keys").option("-C, --cwd <dir>","Site directory").action(extractTranslationsCommand);scripts.command("lint").description("Lint project files (translation keys + oxlint)").argument("[path]","Single file to lint (omit for whole project)").option("-C, --cwd <dir>","Site directory").action(lintCommand);program.command("export-static",{hidden:!0}).description("Post-build: remove dist/server and preserve dist/client assets (after react-router build)").option("-C, --cwd <dir>","Site directory").action(exportStaticCommand);program.command("resolve-routes",{hidden:!0}).description("Map changed files back to affected preview routes").argument("[files...]","Changed files to resolve").option("-C, --cwd <dir>","Site directory").action(resolveRoutesCommand);var branchCmd=program.command("branch").description("List, create, or delete Branches (a Branch = git branch + its own Neon DB + sandbox)").argument("[name]","Branch name (omit to list)").option("-v, --verbose","Include deleted Branches").option("--all","Also list Fimo's own agent Branches (task/*), normally hidden").option("-d, --delete","Delete the named Branch (drops sandbox + Neon branch + R2 prefix)").option("--from <branch>","Parent Branch to fork from when creating (defaults to current)").action(async(name,_options,command)=>{if(!name){await branchListCommand(command);return}if(command.opts().delete){await branchDeleteCommand(name,command);return}await branchCreateCommand(name,command)});program.command("checkout").description("Switch to a Branch (or create + switch with -b)").argument("<name>","Branch name").option("-b, --create","Create the Branch if it does not exist").option("--from <branch>","Parent Branch (only with -b)").action(checkoutCommand);program.command("switch").description("Alias for `fimo checkout` (switch Branches)").argument("<name>","Branch name").action(checkoutCommand);program.command("pull").description("Sync the current Branch's data plane from its parent").option("--from <branch>","Sync from an explicit ancestor (defaults to declared parent)").action(pullCommand);program.command("diff").description("Two-Branch diff across all surfaces").argument("[from]","From Branch (defaults to the current Branch)").argument("[to]","To Branch (defaults to main)").option("-C, --cwd <dir>","Site directory").option("--surface <name>","Limit to a single surface (code | schemas | content | ...)").option("--key <key>","Drill into one item within --surface (W2 \u2014 per-item before/after)").option("--all","Render the full item list, bypassing the per-surface cap").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(diffCommand);program.command("merge").description("Merge another Branch into the current one (multi-surface, atomic, with conflict resolver)").argument("<from>","Source Branch").option("-C, --cwd <dir>","Site directory").option("--allow-direct-merge","Override the main-branch protected-flow gate").option("-y, --yes","Accept parent-wins for every conflict (non-interactive)").option("--resume","Resume an in-flight merge from its persisted draft (W3.6)").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(mergeCommand);var publish=program.command("publish").description("Publish main using a stable Fimo publication ID").option("-C, --cwd <dir>","Site directory").option("--label <text>","Optional human-readable publication label").option("--notes <text>","Optional publication notes (markdown)").option("--skip-validate","Skip the lint + codegen + smoke pre-checks (operator override)").action(publishCommand);addPaginationOptions(publish.command("list").description("Publication attempts for the current site, newest first"),{defaultLimit:20,maxLimit:100,legacyCursor:"before"}).option("-C, --cwd <dir>","Site directory").action(publishListCommand);publish.command("inspect").description("One publication attempt in full, including why it failed").argument("<publicationId>","Fimo publication id").option("-C, --cwd <dir>","Site directory").action(publishInspectCommand);publish.command("logs").description("Read a publication's build log from its hosting provider").argument("<publicationId>","Fimo publication id").option("-C, --cwd <dir>","Site directory").option("--limit <n>","Events to return (1-1000, default 200)").action(publishLogsCommand);program.command("status").description("Multi-surface Branch status \u2014 the showcase command").option("-C, --cwd <dir>","Site directory").option("--short","One-line summary per surface (no bodies)").option("--json","Emit raw JSON instead of the rendered report").option("--vs <branch>","Comparison target (defaults to the parent Branch or main)").option("--no-color","Disable ANSI colour output").option("--code","Limit to the code surface").option("--content","Limit to the content surface").option("--i18n","Limit to the translations surface").option("--assets","Limit to the assets surface").option("--forms","Limit to the forms surface").option("--all","Render the full item list, bypassing the per-surface cap").action(statusCommand2);registerPreviewCommands(program);program.addCommand(new Command("git-credential").argument("<operation>","get | store | erase (git credential protocol)").description("Internal git credential helper (invoked by git)").action(gitCredentialCommand),{hidden:!0});registerGenerate(program);registerMediaTaskCommands(program);var schemas2=program.command("schemas").description("Manage content-type schemas");schemas2.command("list").description("List all registered schemas").option("-C, --cwd <dir>","Site directory").action(schemaListCommand);schemas2.command("get").description("Get a schema by type name").argument("<typeName>","Content type name (e.g. BlogPost)").option("-C, --cwd <dir>","Site directory").action(schemaGetCommand);schemas2.command("push").description("Push schema JSON files to the API (create or update)").argument("[typeName]","Schema name to push (omit to push all)").option("-C, --cwd <dir>","Site directory").option("--rename <from=to>","Preserve a renamed field (repeatable, supports nested paths)",(value,previous)=>[...previous,value],[]).action(schemaPushCommand);schemas2.command("delete").description("Delete a schema by type name").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Site directory").action(schemaDeleteCommand);var entries=program.command("entries").description("Manage content entries");addPaginationOptions(entries.command("list").description("List entries of a content type"),{defaultLimit:20,maxLimit:100,legacyCursor:"offset"}).argument("<typeName>","Content type name").option("-C, --cwd <dir>","Site directory").option("--search <query>","Search query").option("--where <json>",`JSON filter object, e.g. '{"featured":true}'`).option("--sort <field>","Sort field, prefix with - for descending").option("--fields <fields>","Comma-separated fields to return, e.g. slug,title,excerpt").option("--populate <fields>","Comma-separated reference, media, or blocks fields to populate, e.g. author,cover").option("--locale <locale>","Locale to list (default en)").option("--sort-by <field>","Sort field").option("--sort-direction <dir>","Sort direction (asc|desc)").action(entriesListCommand);entries.command("get").description("Get a single entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Site directory").option("--locale <locale>","Entry locale (defaults to the site locale)").option("--populate <fields>","Comma-separated reference, media, or blocks fields to populate, e.g. author,cover").action(entriesGetCommand);entries.command("create").description("Create a new entry").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Site directory").requiredOption("--body <json>","Entry JSON body (slug + data)").option("--locale <locale>","Entry locale (default en)").option("--document-id <id>","Document ID shared by localized variants").action(entriesCreateCommand);entries.command("update").description("Update an existing entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Site directory").requiredOption("--body <json>","Updated entry JSON body").option("--locale <locale>","Entry locale (defaults to the site locale)").action(entriesUpdateCommand);entries.command("delete").description("Delete an entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Site directory").option("--locale <locale>","Entry locale (defaults to the site locale)").action(entriesDeleteCommand);entries.command("query").description("Run a read-only SQL query over the entries table").option("-C, --cwd <dir>","Site directory").option("--sql <query>","SQL SELECT query").option("--file <path>","Read the SQL query from a file").option("--stdin","Read the SQL query from stdin").action(entriesQueryCommand);entries.command("bulk-create").description("Create multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Site directory").option("--body <json>","JSON array of entry bodies").option("--file <path>","Read entry bodies from a JSON file").option("--stdin","Read entry bodies from stdin").option("--upsert-by <field>","Update or create by a stable data field (migration imports prefer slug)").option("--chunk-size <count>","Entries per request (default 100, maximum 1000)").action(entriesBulkCreateCommand);entries.command("bulk-update").description("Update multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Site directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"status":"draft"}'`).option("--body <json>","Updated entry JSON body").option("--file <path>","Read per-entry updates from a JSON file").option("--stdin","Read per-entry updates from stdin").action(entriesBulkUpdateCommand);entries.command("bulk-delete").description("Delete multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Site directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"archived":true}'`).option("--locale <locale>","Entry locale (defaults to the site locale)").action(entriesBulkDeleteCommand);var singles=program.command("singles").description("Manage single content types");singles.command("get").description("Get a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Site directory").option("--locale <locale>","Single locale (defaults to the site locale)").option("--populate <fields>","Comma-separated reference, media, or blocks fields to populate").action(singlesGetCommand);singles.command("update").description("Update a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Site directory").option("--body <json>","Updated Single JSON body").option("--file <path>","Read the updated Single JSON body from a file").option("--stdin","Read the updated Single JSON body from stdin").option("--locale <locale>","Single locale (defaults to the site locale)").action(singlesUpdateCommand);var assets2=program.command("assets").description("Manage media assets");addPaginationOptions(assets2.command("list").description("List assets"),{defaultLimit:20,maxLimit:100,legacyCursor:"offset"}).option("-C, --cwd <dir>","Site directory").option("--parent-id <id>","Filter by parent folder").option("--search <query>","Search across name, alt text, caption, and AI-generated alt / caption (case-insensitive)").option("--type <type>","Filter by entry type (file|folder)").option("--image","Filter to image MIME types (shortcut for --mime-prefix image/)").option("--video","Filter to video MIME types (shortcut for --mime-prefix video/)").option("--audio","Filter to audio MIME types (shortcut for --mime-prefix audio/)").option("--mime-prefix <prefix>",'Filter by MIME type prefix (e.g. "image/png")').option("--sort-by <field>","Sort field").action(assetsListCommand);assets2.command("read").description("Read canonical asset text or ask one targeted question").argument("<id>","Asset ID").option("-C, --cwd <dir>","Site directory").option("--cursor <next-cursor>","Continue an exact read from a previous nextCursor").option("--query <question>","Ask one targeted model-backed question").action(assetsReadCommand);assets2.command("upload").description("Upload a file to the media library").argument("<file>","Path to the file to upload").option("-C, --cwd <dir>","Site directory").option("--name <name>","Asset display name").option("--parent-id <id>","Target folder ID").option("--folder-path <path>","Target folder path, creating missing folders").action(assetsUploadCommand);assets2.command("bulk-upload").description("Upload files from a structured JSON manifest").requiredOption("--file <path>","JSON manifest path").option("-C, --cwd <dir>","Site directory").option("--concurrency <n>","Maximum parallel uploads","4").action(assetsBulkUploadCommand);var modelsCmd=new Command("models").description("Browse available media generation models");program.addCommand(modelsCmd,{hidden:!0});modelsCmd.command("list").description("List Fal models enabled for this site").option("-C, --cwd <dir>","Site directory").option("--modality <m>","Filter by modality (image | video | audio)").option("--search <query>","Search names and descriptions").option("--category <category>","Filter by Fal media category").option("--tag <t>","Filter by tag (repeatable; AND semantics \u2014 model must have every tag)",(value,previous)=>[...previous,value],[]).option("--extended","Per-model card: alias, provider, tags, price, best-for, flags").option("--json","Machine-readable JSON output").action(modelsListCommand);modelsCmd.command("show").description("Show a Fal model and its available flags").argument("<key>","Namespaced model id from `fimo models list`").option("-C, --cwd <dir>","Site directory").option("--json","Machine-readable JSON output (includes the per-model flag list)").action(modelsShowCommand);assets2.command("create-folder").description("Create a folder in the media library").argument("<name>","Folder name").option("-C, --cwd <dir>","Site directory").option("--parent-id <id>","Parent folder ID").action(assetsCreateFolderCommand);assets2.command("move").description("Move an asset to a different folder").argument("<id>","Asset ID").option("-C, --cwd <dir>","Site directory").requiredOption("--parent-id <id>",'Target folder ID (use "null" for root)').action(assetsMoveCommand);assets2.command("usage").description("Check Current, Main, and Live structured-reference impact").argument("<id>","Asset ID").option("-C, --cwd <dir>","Site directory").action(assetsUsageCommand);assets2.command("replace").description("Replace structured references in the Current Branch").argument("<id>","Source asset ID").requiredOption("--with <id>","Replacement asset ID").option("-C, --cwd <dir>","Site directory").action(assetsReplaceCommand);assets2.command("remove").alias("delete").description("Safely remove an asset from the current Branch").argument("<id>","Asset ID").option("-C, --cwd <dir>","Site directory").option("--replace-with <id>","Replace references before removal (Current Branch content and source; every Branch and Live with --permanent)").option("--without-checking","Skip reference guidance before environment removal").option("--permanent","Destroy the asset across the site").option("-y, --yes","Skip confirmation for permanent destruction").action(assetsRemoveCommand);assets2.command("open").description("Fetch asset metadata; optionally download locally or open in default viewer").argument("<id>","Asset ID").option("-C, --cwd <dir>","Site directory").option("--download","Download the asset bytes to a local file and print the path").option("--browser","Open the asset URL in the OS default viewer (open / xdg-open / start)").option("--path <path>","Override download destination (default: <tmpdir>/fimo-assets/<id>.<ext>). Implies --download.").action((id,options,cmd)=>(options.path&&!options.download&&(options.download=!0),assetsOpenCommand(id,options,cmd)));var forms2=program.command("forms").description("Manage forms");forms2.command("list").description("List all forms").option("-C, --cwd <dir>","Site directory").action(formsListCommand);forms2.command("get").description("Get a form by ID").argument("<id>","Form ID").option("-C, --cwd <dir>","Site directory").action(formsGetCommand);forms2.command("push").description("Push form JSON files to the API (create or update, patches id back)").argument("[formName]","Form name to push (omit to push all)").option("-C, --cwd <dir>","Site directory").action(formsPushCommand);forms2.command("delete").description("Delete a form").argument("<id>","Form ID").option("-C, --cwd <dir>","Site directory").action(formsDeleteCommand);var supportedAgentsHelp=`
|
|
985
|
+
`).action(logsCommand);program.command("validate").description("Run all checks and sync local state with the Fimo backend").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--json","Emit structured JSON output (for CI / agents)").action(validateCommand);program.command("update").description("Update this checkout's Fimo packages to an exact release and apply the bundled migrations").argument("<version>","Exact target version, for example 1.0.0").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--dry-run","Show the update plan without writing anything").option("--apply","Apply without prompting (required in --json / non-interactive shells)").option("--allow-dirty","Skip the clean-working-tree check").option("--no-install","Skip dependency installation after applying").option("--no-validate","Skip `fimo validate` after applying").action(updateCommand3);program.command("describe [path]").description("Print a structured snapshot of the current Fimo site (read-only)").option("-C, --cwd <dir>","Run against this directory instead of cwd").option("--depth <n>","Tree depth (default 3). Ignored when --full is set.").option("--full","Disable depth and width truncation (still respects the 10k-entry cap)").option("--json","Emit structured JSON output (for CI / agents)").action(describeCommand);program.command("credits").description("Show the current site credit balance").option("-C, --cwd <dir>","Site directory").option("--project <projectId>","Site ID (defaults to the current site)").option("--json","Emit structured JSON output").action(creditsCommand);program.command("delete").description("Delete the current linked site").option("-C, --cwd <dir>","Site directory").option("-y, --yes","Skip confirmation prompt").action(options=>projectsDeleteCommand(void 0,options));program.command("unpublish").description("Unpublish the current site").option("-C, --cwd <dir>","Site directory").action(options=>projectsUnpublishCommand(void 0,options));program.command("rename").description("Set the display name of the current site").argument("<name>",'New display name (e.g. "Acme Blog")').option("-C, --cwd <dir>","Site directory").action((name,options)=>projectsRenameCommand(name,void 0,options));var orgs=program.command("orgs").description("Manage organizations");orgs.command("list").description("List organizations you belong to").action(orgsListCommand);orgs.command("switch").description("Switch the active organization used by `fimo init`").option("--org <id-or-slug>","Switch to this organization without prompting").action(switchCommand);orgs.command("members").description("List members of an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(orgsMembersCommand);var referral=program.command("referral").description("Share and inspect your referral program tools");referral.command("link").description("Print your referral link").action(referralLinkCommand);referral.command("stats").description("Show your referral stats").action(referralStatsCommand);var projects=program.command("projects").description("Manage sites across an organization");projects.command("list").description("List sites in an organization (defaults to the active org)").option("--org <organizationId>","Organization ID (defaults to active)").action(projectsListCommand);projects.command("unclaimed").description("List sites created without an account on this machine, with their claim links and state").action(projectsUnclaimedCommand);projects.command("create").description("Scaffold a new site (alias of `fimo init`)").argument("[dir]","Target directory").option("--org <organizationId>","Target organization ID (auto if you belong to one)").option("--framework <framework>","Site scaffold: react-router | vite | astro | nextjs | sveltekit (defaults to nextjs)").option("--template-root <path>","Override template directory").option("--package-manager <pm>","Install dependencies with: npm | pnpm | yarn | bun").option("--install","Install dependencies after scaffolding").option("--no-install","Skip dependency installation after scaffolding").action(initCommand);projects.command("clone").description("Clone an existing Fimo site locally").argument("[projectId]","Site ID to clone").argument("[dir]","Target directory (defaults to the site name)").option("--branch <name>","Branch to clone (defaults to main)").action(cloneCommand);projects.command("delete").description("Delete a site (defaults to the current linked site)").argument("[projectId]","Explicit site ID").option("-C, --cwd <dir>","Site directory").option("-y, --yes","Skip confirmation prompt").action(projectsDeleteCommand);projects.command("publish").description("Publish a site (defaults to the current site)").argument("[projectId]","Explicit site ID").option("-C, --cwd <dir>","Site directory").action(projectsPublishCommand);projects.command("unpublish").description("Unpublish a site (defaults to the current site)").argument("[projectId]","Explicit site ID").option("-C, --cwd <dir>","Site directory").action(projectsUnpublishCommand);projects.command("rename").description("Set the display name of a site (defaults to the current site)").argument("<name>",'New display name (e.g. "Acme Blog")').argument("[projectId]","Explicit site ID").option("-C, --cwd <dir>","Site directory").action(projectsRenameCommand);projects.command("transfer").description("Move a site to another organization you administer (defaults to the current site)").argument("[projectId]","Explicit site ID").option("--to <organization>","Destination organization ID or slug").option("-C, --cwd <dir>","Site directory").option("-y, --yes","Skip confirmation prompt").action(projectsTransferCommand);var domains=program.command("domains").description("Manage your default URL and custom domains");domains.command("list").alias("ls").description("Show the default URL and any custom domains").option("--project <projectId>","Site ID (defaults to the current site)").option("-C, --cwd <dir>","Site directory").option("--json","Output as JSON").action(domainsListCommand);domains.command("rename-default").description("Rename your default URL (the <slug>.fimo.site subdomain Fimo provides)").argument("<slug>",'New slug (e.g. "acme-coffee")').option("--project <projectId>","Site ID (defaults to the current site)").option("-C, --cwd <dir>","Site directory").option("--json","Output as JSON").action(domainsRenameDefaultCommand);domains.command("suggest-default").description("Suggest available default URLs; pick one to claim (or list with --json)").option("--base <text>","Override the base text used to generate suggestions (defaults to your site display name)").option("--max <n>","Number of suggestions to fetch (1\u201310, default 5)").option("--pick <slug-or-index>","Non-interactive: claim this suggestion by slug or numeric index").option("--project <projectId>","Site ID (defaults to the current site)").option("-C, --cwd <dir>","Site directory").option("--json","Output as JSON (no prompt, no claim)").action(domainsSuggestDefaultCommand);domains.command("add").description("Attach a custom domain to your site (requires an eligible plan)").argument("<hostname>",'The hostname to attach (e.g. "blog.example.com")').option("--redirect-www","Also configure an apex \u2192 www redirect").option("--wait [duration]","Poll until DNS is verified (e.g. --wait, --wait 10m)").option("--project <projectId>","Site ID (defaults to the current site)").option("-C, --cwd <dir>","Site directory").option("--json","Output the resulting domain record as JSON after instructions").action(domainsAddCommand);domains.command("remove").alias("rm").description("Detach a custom domain by hostname or ID").argument("<hostname-or-id>","Hostname or domain ID").option("-y, --yes","Skip the confirmation prompt").option("--project <projectId>","Site ID (defaults to the current site)").option("-C, --cwd <dir>","Site directory").action(domainsRemoveCommand);domains.command("refresh").description("Re-check DNS and SSL status for a custom domain").argument("<hostname-or-id>","Hostname or domain ID").option("--wait [duration]","Poll until SSL is active (default; pass --no-wait to print one snapshot)").option("--no-wait","Print the refreshed status once and exit").option("--project <projectId>","Site ID (defaults to the current site)").option("-C, --cwd <dir>","Site directory").option("--json","Output the resulting domain record as JSON").action(domainsRefreshCommand);domains.command("search").description("Search for available domain names to buy through Fimo").argument("<keyword>",'Search keyword (e.g. "acme coffee")').option("--tld <list>",'Restrict TLDs (comma-separated, e.g. "com,io,dev")').option("--max-price <amount>","Filter results to this purchase price ceiling (in dollars)").option("--limit <n>","Truncate to the first N results (default 20)").option("--json","Output as JSON").action(domainsSearchCommand);domains.command("pricing").description("Show the price for a specific domain (purchase + renewal)").argument("<domain>",'Domain name (e.g. "example.com")').option("--years <n>","Multiply purchase price by this many years (default 1)").option("--json","Output as JSON").action(domainsPricingCommand);domains.command("buy").description("Buy a domain through Fimo. Creates a checkout invoice; no charge until you pay it in the browser.").argument("<domain>",'Domain name to register (e.g. "example.com")').option("--years <n>","Years to register for (default uses the TLD minimum)").option("--auto-renew","Enable auto-renewal (default)").option("--no-auto-renew","Disable auto-renewal \u2014 domain will not renew automatically").option("-y, --yes","Skip the interactive confirmation prompt").option("--open","Open the checkout URL in your browser after creating the invoice").option("--wait [duration]","Poll until payment completes and registration succeeds").option("--org <organizationId>","Organization ID (defaults to the current site's org)").option("-C, --cwd <dir>","Site directory used to resolve the org").option("--json","Output the resulting invoice record as JSON").action(domainsBuyCommand);domains.command("owned").description("List domains your organization has registered through Fimo").option("--org <organizationId>","Organization ID (defaults to the current site's org)").option("--status <list>",'Filter by status (comma-separated, e.g. "owned,pending_payment")').option("--limit <n>","Truncate to the first N results").option("-C, --cwd <dir>","Site directory used to resolve the org").option("--json","Output as JSON").action(domainsOwnedCommand);var scripts=program.command("scripts",{hidden:!0}).description("Internal/advanced primitives. Most users want `fimo validate`.");scripts.command("sync-schemas").description("Regenerate TypeScript clients for src/schemas/*.json").option("-C, --cwd <dir>","Site directory").action(syncSchemasCommand);scripts.command("sync-forms").description("Regenerate TypeScript clients for src/forms/*.json").option("-C, --cwd <dir>","Site directory").action(syncFormsCommand);scripts.command("validate-route-metadata").description("Cross-validate src/routes.ts against .fimo/config.json#routes (v4)").option("-C, --cwd <dir>","Site directory").action(validateRouteMetadataCommand);scripts.command("extract-translations").description("Legacy local helper: scan src/ for literal t() label keys").option("-C, --cwd <dir>","Site directory").action(extractTranslationsCommand);scripts.command("lint").description("Lint project files (translation keys + oxlint)").argument("[path]","Single file to lint (omit for whole project)").option("-C, --cwd <dir>","Site directory").action(lintCommand);program.command("export-static",{hidden:!0}).description("Post-build: remove dist/server and preserve dist/client assets (after react-router build)").option("-C, --cwd <dir>","Site directory").action(exportStaticCommand);program.command("resolve-routes",{hidden:!0}).description("Map changed files back to affected preview routes").argument("[files...]","Changed files to resolve").option("-C, --cwd <dir>","Site directory").action(resolveRoutesCommand);var branchCmd=program.command("branch").description("List, create, or delete Branches (a Branch = git branch + its own Neon DB + sandbox)").argument("[name]","Branch name (omit to list)").option("-v, --verbose","Include deleted Branches").option("--all","Also list Fimo's own agent Branches (task/*), normally hidden").option("-d, --delete","Delete the named Branch (drops sandbox + Neon branch + R2 prefix)").option("--from <branch>","Parent Branch to fork from when creating (defaults to current)").action(async(name,_options,command)=>{if(!name){await branchListCommand(command);return}if(command.opts().delete){await branchDeleteCommand(name,command);return}await branchCreateCommand(name,command)});program.command("checkout").description("Switch to a Branch (or create + switch with -b)").argument("<name>","Branch name").option("-b, --create","Create the Branch if it does not exist").option("--from <branch>","Parent Branch (only with -b)").action(checkoutCommand);program.command("switch").description("Alias for `fimo checkout` (switch Branches)").argument("<name>","Branch name").action(checkoutCommand);program.command("pull").description("Sync the current Branch's data plane from its parent").option("--from <branch>","Sync from an explicit ancestor (defaults to declared parent)").action(pullCommand);program.command("diff").description("Two-Branch diff across all surfaces").argument("[from]","From Branch (defaults to the current Branch)").argument("[to]","To Branch (defaults to main)").option("-C, --cwd <dir>","Site directory").option("--surface <name>","Limit to a single surface (code | schemas | content | ...)").option("--key <key>","Drill into one item within --surface (W2 \u2014 per-item before/after)").option("--all","Render the full item list, bypassing the per-surface cap").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(diffCommand);program.command("merge").description("Merge another Branch into the current one (multi-surface, atomic, with conflict resolver)").argument("<from>","Source Branch").option("-C, --cwd <dir>","Site directory").option("--allow-direct-merge","Override the main-branch protected-flow gate").option("-y, --yes","Accept parent-wins for every conflict (non-interactive)").option("--resume","Resume an in-flight merge from its persisted draft (W3.6)").option("--json","Emit raw JSON instead of the rendered report").option("--no-color","Disable ANSI colour output").action(mergeCommand);var publish=program.command("publish").description("Publish main using a stable Fimo publication ID").option("-C, --cwd <dir>","Site directory").option("--label <text>","Optional human-readable publication label").option("--notes <text>","Optional publication notes (markdown)").option("--skip-validate","Skip the lint + codegen + smoke pre-checks (operator override)").action(publishCommand);addPaginationOptions(publish.command("list").description("Publication attempts for the current site, newest first"),{defaultLimit:20,maxLimit:100,legacyCursor:"before"}).option("-C, --cwd <dir>","Site directory").action(publishListCommand);publish.command("inspect").description("One publication attempt in full, including why it failed").argument("<publicationId>","Fimo publication id").option("-C, --cwd <dir>","Site directory").action(publishInspectCommand);publish.command("logs").description("Read a publication's build log from its hosting provider").argument("<publicationId>","Fimo publication id").option("-C, --cwd <dir>","Site directory").option("--limit <n>","Events to return (1-1000, default 200)").action(publishLogsCommand);program.command("status").description("Multi-surface Branch status \u2014 the showcase command").option("-C, --cwd <dir>","Site directory").option("--short","One-line summary per surface (no bodies)").option("--json","Emit raw JSON instead of the rendered report").option("--vs <branch>","Comparison target (defaults to the parent Branch or main)").option("--no-color","Disable ANSI colour output").option("--code","Limit to the code surface").option("--content","Limit to the content surface").option("--i18n","Limit to the translations surface").option("--assets","Limit to the assets surface").option("--forms","Limit to the forms surface").option("--all","Render the full item list, bypassing the per-surface cap").action(statusCommand2);registerPreviewCommands(program);program.addCommand(new Command("git-credential").argument("<operation>","get | store | erase (git credential protocol)").description("Internal git credential helper (invoked by git)").action(gitCredentialCommand),{hidden:!0});registerGenerate(program);registerMediaTaskCommands(program);var schemas2=program.command("schemas").description("Manage content-type schemas");schemas2.command("list").description("List all registered schemas").option("-C, --cwd <dir>","Site directory").action(schemaListCommand);schemas2.command("get").description("Get a schema by type name").argument("<typeName>","Content type name (e.g. BlogPost)").option("-C, --cwd <dir>","Site directory").action(schemaGetCommand);schemas2.command("push").description("Push schema JSON files to the API (create or update)").argument("[typeName]","Schema name to push (omit to push all)").option("-C, --cwd <dir>","Site directory").option("--rename <from=to>","Preserve a renamed field (repeatable, supports nested paths)",(value,previous)=>[...previous,value],[]).action(schemaPushCommand);schemas2.command("delete").description("Delete a schema by type name").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Site directory").action(schemaDeleteCommand);var entries=program.command("entries").description("Manage content entries");addPaginationOptions(entries.command("list").description("List entries of a content type"),{defaultLimit:20,maxLimit:100,legacyCursor:"offset"}).argument("<typeName>","Content type name").option("-C, --cwd <dir>","Site directory").option("--search <query>","Search query").option("--where <json>",`JSON filter object, e.g. '{"featured":true}'`).option("--sort <field>","Sort field, prefix with - for descending").option("--fields <fields>","Comma-separated fields to return, e.g. slug,title,excerpt").option("--populate <fields>","Comma-separated reference, media, or blocks fields to populate, e.g. author,cover").option("--locale <locale>","Locale to list (default en)").option("--sort-by <field>","Sort field").option("--sort-direction <dir>","Sort direction (asc|desc)").action(entriesListCommand);entries.command("get").description("Get a single entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Site directory").option("--locale <locale>","Entry locale (defaults to the site locale)").option("--populate <fields>","Comma-separated reference, media, or blocks fields to populate, e.g. author,cover").action(entriesGetCommand);entries.command("create").description("Create a new entry").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Site directory").requiredOption("--body <json>","Entry JSON body (slug + data)").option("--locale <locale>","Entry locale (default en)").option("--document-id <id>","Document ID shared by localized variants").action(entriesCreateCommand);entries.command("update").description("Update an existing entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Site directory").requiredOption("--body <json>","Updated entry JSON body").option("--locale <locale>","Entry locale (defaults to the site locale)").action(entriesUpdateCommand);entries.command("delete").description("Delete an entry").argument("<typeName>","Content type name").argument("<id>","Entry ID").option("-C, --cwd <dir>","Site directory").option("--locale <locale>","Entry locale (defaults to the site locale)").action(entriesDeleteCommand);entries.command("query").description("Run a read-only SQL query over the entries table").option("-C, --cwd <dir>","Site directory").option("--sql <query>","SQL SELECT query").option("--file <path>","Read the SQL query from a file").option("--stdin","Read the SQL query from stdin").action(entriesQueryCommand);entries.command("bulk-create").description("Create multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Site directory").option("--body <json>","JSON array of entry bodies").option("--file <path>","Read entry bodies from a JSON file").option("--stdin","Read entry bodies from stdin").option("--upsert-by <field>","Update or create by a stable data field (migration imports prefer slug)").option("--chunk-size <count>","Entries per request (default 100, maximum 1000)").action(entriesBulkCreateCommand);entries.command("bulk-update").description("Update multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Site directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"status":"draft"}'`).option("--body <json>","Updated entry JSON body").option("--file <path>","Read per-entry updates from a JSON file").option("--stdin","Read per-entry updates from stdin").action(entriesBulkUpdateCommand);entries.command("bulk-delete").description("Delete multiple entries").argument("<typeName>","Content type name").option("-C, --cwd <dir>","Site directory").option("--ids <ids>","Comma-separated IDs").option("--where <json>",`JSON filter object, e.g. '{"archived":true}'`).option("--locale <locale>","Entry locale (defaults to the site locale)").action(entriesBulkDeleteCommand);var singles=program.command("singles").description("Manage single content types");singles.command("get").description("Get a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Site directory").option("--locale <locale>","Single locale (defaults to the site locale)").option("--populate <fields>","Comma-separated reference, media, or blocks fields to populate").action(singlesGetCommand);singles.command("update").description("Update a Single").argument("<typeName>","Single type name").option("-C, --cwd <dir>","Site directory").option("--body <json>","Updated Single JSON body").option("--file <path>","Read the updated Single JSON body from a file").option("--stdin","Read the updated Single JSON body from stdin").option("--locale <locale>","Single locale (defaults to the site locale)").action(singlesUpdateCommand);var assets2=program.command("assets").description("Manage media assets");addPaginationOptions(assets2.command("list").description("List assets"),{defaultLimit:20,maxLimit:100,legacyCursor:"offset"}).option("-C, --cwd <dir>","Site directory").option("--parent-id <id>","Filter by parent folder").option("--search <query>","Search across name, alt text, caption, and AI-generated alt / caption (case-insensitive)").option("--type <type>","Filter by entry type (file|folder)").option("--image","Filter to image MIME types (shortcut for --mime-prefix image/)").option("--video","Filter to video MIME types (shortcut for --mime-prefix video/)").option("--audio","Filter to audio MIME types (shortcut for --mime-prefix audio/)").option("--mime-prefix <prefix>",'Filter by MIME type prefix (e.g. "image/png")').option("--sort-by <field>","Sort field").action(assetsListCommand);assets2.command("read").description("Read canonical asset text or ask one targeted question").argument("<id>","Asset ID").option("-C, --cwd <dir>","Site directory").option("--cursor <next-cursor>","Continue an exact read from a previous nextCursor").option("--query <question>","Ask one targeted model-backed question").action(assetsReadCommand);assets2.command("upload").description("Upload a file to the media library").argument("<file>","Path to the file to upload").option("-C, --cwd <dir>","Site directory").option("--name <name>","Asset display name").option("--parent-id <id>","Target folder ID").option("--folder-path <path>","Target folder path, creating missing folders").action(assetsUploadCommand);assets2.command("bulk-upload").description("Upload files from a structured JSON manifest").requiredOption("--file <path>","JSON manifest path").option("-C, --cwd <dir>","Site directory").option("--concurrency <n>","Maximum parallel uploads","4").action(assetsBulkUploadCommand);var modelsCmd=new Command("models").description("Browse available media generation models");program.addCommand(modelsCmd,{hidden:!0});modelsCmd.command("list").description("List Fal models enabled for this site").option("-C, --cwd <dir>","Site directory").option("--modality <m>","Filter by modality (image | video | audio)").option("--search <query>","Search names and descriptions").option("--category <category>","Filter by Fal media category").option("--tag <t>","Filter by tag (repeatable; AND semantics \u2014 model must have every tag)",(value,previous)=>[...previous,value],[]).option("--extended","Per-model card: alias, provider, tags, price, best-for, flags").option("--json","Machine-readable JSON output").action(modelsListCommand);modelsCmd.command("show").description("Show a Fal model and its available flags").argument("<key>","Namespaced model id from `fimo models list`").option("-C, --cwd <dir>","Site directory").option("--json","Machine-readable JSON output (includes the per-model flag list)").action(modelsShowCommand);assets2.command("create-folder").description("Create a folder in the media library").argument("<name>","Folder name").option("-C, --cwd <dir>","Site directory").option("--parent-id <id>","Parent folder ID").action(assetsCreateFolderCommand);assets2.command("move").description("Move an asset to a different folder").argument("<id>","Asset ID").option("-C, --cwd <dir>","Site directory").requiredOption("--parent-id <id>",'Target folder ID (use "null" for root)').action(assetsMoveCommand);assets2.command("usage").description("Check Current, Main, and Live structured-reference impact").argument("<id>","Asset ID").option("-C, --cwd <dir>","Site directory").action(assetsUsageCommand);assets2.command("replace").description("Replace structured references in the Current Branch").argument("<id>","Source asset ID").requiredOption("--with <id>","Replacement asset ID").option("-C, --cwd <dir>","Site directory").action(assetsReplaceCommand);assets2.command("remove").alias("delete").description("Safely remove an asset from the current Branch").argument("<id>","Asset ID").option("-C, --cwd <dir>","Site directory").option("--replace-with <id>","Replace references before removal (Current Branch content and source; every Branch and Live with --permanent)").option("--without-checking","Skip reference guidance before environment removal").option("--permanent","Destroy the asset across the site").option("-y, --yes","Skip confirmation for permanent destruction").action(assetsRemoveCommand);assets2.command("open").description("Fetch asset metadata; optionally download locally or open in default viewer").argument("<id>","Asset ID").option("-C, --cwd <dir>","Site directory").option("--download","Download the asset bytes to a local file and print the path").option("--browser","Open the asset URL in the OS default viewer (open / xdg-open / start)").option("--path <path>","Override download destination (default: <tmpdir>/fimo-assets/<id>.<ext>). Implies --download.").action((id,options,cmd)=>(options.path&&!options.download&&(options.download=!0),assetsOpenCommand(id,options,cmd)));var forms2=program.command("forms").description("Manage forms");forms2.command("list").description("List all forms").option("-C, --cwd <dir>","Site directory").action(formsListCommand);forms2.command("get").description("Get a form by ID").argument("<id>","Form ID").option("-C, --cwd <dir>","Site directory").action(formsGetCommand);forms2.command("push").description("Push form JSON files to the API (create or update, patches id back)").argument("[formName]","Form name to push (omit to push all)").option("-C, --cwd <dir>","Site directory").action(formsPushCommand);forms2.command("delete").description("Delete a form").argument("<id>","Form ID").option("-C, --cwd <dir>","Site directory").action(formsDeleteCommand);var supportedAgentsHelp=`
|
|
986
986
|
Supported agents:
|
|
987
987
|
Universal (always covered via AGENTS.md, no per-agent file needed):
|
|
988
988
|
Codex, OpenCode, Aider, and other AGENTS.md-native tools
|
|
@@ -995,6 +995,7 @@ Supported agents:
|
|
|
995
995
|
`,skills=program.command("skills").description("Manage Fimo skills for AI coding agents (global + project)");skills.command("install").description("Install the global Fimo skill for selected agents (loads the rest on demand via `skills get`)").option("--agents <list>","Comma-separated list of agent IDs (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev=[])=>[...prev,value]).option("-y, --yes","Reserved (install is prompt-light)").addHelpText("after",supportedAgentsHelp).action(skillsInstallCommand);skills.command("sync").description("Re-ensure the global Fimo skill and clean up stale skills from older versions").option("--agents <list>","Limit the global refresh to this agent list (default: agents that already have the skills)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev=[])=>[...prev,value]).addHelpText("after",supportedAgentsHelp).action(skillsSyncCommand);skills.command("uninstall").description("Remove the global Fimo skills from selected AI agents (project files left untouched)").option("--agents <list>","Comma-separated list of agent IDs (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev=[])=>[...prev,value]).addHelpText("after",supportedAgentsHelp).action(skillsUninstallCommand);skills.command("list").description("List the Fimo skills bundled with this CLI (name, scope, reference count)").action(skillsListCommand);skills.command("get <name>").description("Print a bundled skill's SKILL.md (or a reference doc with --ref)").option("--ref <doc>","Print a reference doc instead (e.g. deploy, integrations/firecrawl)").action(skillsGetCommand);var rules=program.command("rules").description("Manage per-agent rule files for this project (CLAUDE.md, .cursor/rules/, etc.)");rules.command("sync").description("Regenerate per-agent rule files from this project's AGENTS.md (rule files only \u2014 skills live under `fimo skills`)").option("-C, --cwd <dir>","Site directory (defaults to cwd)").option("--agents <list>","Comma-separated list of agent IDs (e.g. claude-code,cursor)").option("-a, --agent <id>","Repeatable: pass once per agent (-a claude-code -a cursor)",(value,prev=[])=>[...prev,value]).addHelpText("after",supportedAgentsHelp).action(rulesSyncCommand);var pages=program.command("pages").description("Manage the site's page registry");pages.command("list").description("List page templates and their binding status").option("-C, --cwd <dir>","Site directory").option("--expand","Materialize dynamic page instances from their bound schemas").action(pagesListCommand);pages.command("set <id>").description("Create or update a page template").option("-C, --cwd <dir>","Site directory").option("--path <path>","Route path in :param syntax, for example /blog/:slug").option("--label <label>","Display label shown in Studio").option("--group <group>","Editorial group shown in the Pages tree; pass an empty value to clear").option("--sources <json>","Named Labels, Single, and Collection sources as a JSON object").option("--clear-sources","Remove every declared source from the page").option("--icon <name>","Kebab-case Lucide icon name; pass an empty value to clear").option("--params <json>",'Bindings from route params to content schemas, or {"<param>":{"type":"external"}} for values the application owns').option("--clear-params","Remove every content param binding from the page").action(pagesSetCommand);pages.command("rename <id> <new-id>").description("Rename a page registry id").option("-C, --cwd <dir>","Site directory").action(pagesRenameCommand);pages.command("delete <id>").description("Delete a page from the registry").option("-C, --cwd <dir>","Site directory").action(pagesDeleteCommand);registerKnowledgeCommands(program);var labels=program.command("labels").description("Manage site labels stored in Fimo");labels.command("list").description("List labels stored in the DB").option("-C, --cwd <dir>","Site directory").option("--locale <locale>","Filter by locale (e.g. en)").action(labelsListCommand);labels.command("set <key> [value]").description("Set one label value").option("-C, --cwd <dir>","Site directory").option("--locale <locale>","Target locale (default en)").option("--value <value>","Label value").option("--stdin","Read the label value from stdin").action(labelsSetCommand);labels.command("set-many").description("Set many label values from JSON").option("-C, --cwd <dir>","Site directory").option("--locale <locale>","Target locale (default en)").option("--file <path>","JSON object map or array of { key, value, locale? } records").option("--data <json>","Inline JSON object map or array of { key, value, locale? } records").action(labelsSetManyCommand);labels.command("delete <key>").alias("unset").description("Delete one label value").option("-C, --cwd <dir>","Site directory").option("--locale <locale>","Target locale (default en)").action(labelsDeleteCommand);var analytics=program.command("analytics").description("Read published-site analytics (defaults to prod; --branch overrides reads; annotation writes use the current Branch)"),rangeOptions=__name(cmd=>(cmd.option("-C, --cwd <dir>","Site directory").option("--preset <preset>","Time range preset (today, yesterday, this_week, this_month, last_7_days, last_30_days, last_90_days, last_week, last_month, last_quarter, last_year, custom)").option("--group-by <unit>","Group by day | week | month | quarter").option("--from <date>","ISO date (YYYY-MM-DD) \u2014 required with --preset custom").option("--to <date>","ISO date (YYYY-MM-DD) \u2014 required with --preset custom").option("--days <n>","Shortcut for last N days (7, 30, or 90)").option("--device <device>","Narrow to one device: bot | desktop | mobile | tablet"),cmd),"rangeOptions");rangeOptions(analytics.command("pageviews").description("Show headline analytics: visitors, pageviews, bounce rate, top breakdowns")).action(analyticsPageviewsCommand);rangeOptions(analytics.command("top").description("Show a single dimension breakdown (pages | browsers | devices | countries | sources)").argument("<dimension>","Which dimension to show").option("--limit <n>","Truncate to the first N results")).action(analyticsTopCommand);var annotations=analytics.command("annotations").description("Manage analytics annotations (per-day notes)");rangeOptions(annotations.command("list").description("List annotations in the site's date range")).action(analyticsAnnotationsListCommand);annotations.command("set").description("Upsert an annotation. Empty content deletes (matches the API).").argument("<date>","YYYY-MM-DD").argument("<content>",'Annotation text (use "" to delete)').option("-C, --cwd <dir>","Site directory").action(analyticsAnnotationsSetCommand);annotations.command("delete").description("Delete an annotation on a given date").argument("<date>","YYYY-MM-DD").option("-C, --cwd <dir>","Site directory").action(analyticsAnnotationsDeleteCommand);var formsSubmissions=forms2.command("submissions").description("Manage submissions intake for a form (list, get, stats, delete)");addPaginationOptions(formsSubmissions.command("list").description("List submissions for a form (newest first by default)"),{defaultLimit:20,maxLimit:100,legacyCursor:"offset"}).argument("<formIdOrName>","Form ID (UUID) or its name").option("-C, --cwd <dir>","Site directory").option("--search <query>","Search query passed to the API").option("--sort <direction>","Sort direction ('asc' or 'desc')").action(formsSubmissionsListCommand);formsSubmissions.command("get").description("Get a single submission").argument("<formIdOrName>","Form ID (UUID) or its name").argument("<submissionId>","Submission ID").option("-C, --cwd <dir>","Site directory").action(formsSubmissionsGetCommand);formsSubmissions.command("stats").description("Aggregate submission counts for a form").argument("<formIdOrName>","Form ID (UUID) or its name").option("-C, --cwd <dir>","Site directory").action(formsSubmissionsStatsCommand);formsSubmissions.command("delete").description("Permanently delete a single submission (cannot be undone)").argument("<formIdOrName>","Form ID (UUID) or its name").argument("<submissionId>","Submission ID").option("-C, --cwd <dir>","Site directory").action(formsSubmissionsDeleteCommand);configureGroupedHelp(program);program.addHelpText("after",`
|
|
996
996
|
Examples:
|
|
997
997
|
fimo init my-site Set up a new site
|
|
998
|
+
fimo new my-site Create a site without an account
|
|
998
999
|
fimo deploy Push to preview
|
|
999
1000
|
fimo deploy --publish Push + go live
|
|
1000
1001
|
fimo projects list List your sites
|
|
@@ -1005,6 +1006,7 @@ Run \`fimo <command> --help\` for command-specific help.
|
|
|
1005
1006
|
`);process.argv.slice(2).length===0&&process.stdout.write(`
|
|
1006
1007
|
Get started:
|
|
1007
1008
|
fimo init Sign in, create or link a site, install deps + skills
|
|
1009
|
+
fimo new Create a site without an account, claim it later
|
|
1008
1010
|
`);var execution;hasRemovedPublishVersion(process.argv)?(initUi({json:process.argv.includes("--json"),noColor:process.argv.includes("--no-color"),ascii:process.argv.includes("--ascii"),jsonEnvVar:"FIMO_OUTPUT"}),rejectRemovedPublishVersion(),execution=Promise.resolve()):execution=program.parseAsync(process.argv);execution.catch(err=>{let command=process.argv[2]??"fimo";if(isCliAuthError(err)){if(currentMode().format==="json")if(err instanceof ProjectUnclaimedError)ui.error({command,code:"PROJECT_UNCLAIMED",message:err.message,details:{feature:err.feature,claim_url:err.claimUrl},hint:unclaimedProjectHint(err.claimUrl)});else if(err instanceof AccountRequiredError)ui.error({command,code:"REQUIRES_ACCOUNT",message:err.message,hint:REQUIRES_ACCOUNT_HINT});else if(err instanceof ProjectTokenRejectedError)ui.error({command,code:"PROJECT_TOKEN_REJECTED",message:err.message,hint:PROJECT_TOKEN_REJECTED_HINT});else if(err instanceof PermissionDeniedError)ui.error({command,code:"PERMISSION_DENIED",message:err.message,hint:err.required.length?`Your role lacks \`${err.required.join(", ")}\` on this site \u2014 ask a site admin for access.`:"Your role does not allow this action on this site \u2014 ask a site admin for access."});else{let isExpired=err instanceof UnauthorizedError;ui.error({command,code:isExpired?"SESSION_EXPIRED":"NOT_AUTHENTICATED",message:err.message,hint:isExpired?"Run `fimo login` to refresh.":"Run `fimo login` to sign in."})}else renderCliAuthError(err);process.exit(1)}err instanceof NotInProjectError&&(ui.error({command,code:"NOT_IN_PROJECT",message:err.message,hint:"Run `fimo init <dir>` or `cd` into a linked Fimo site."}),process.exit(1)),err instanceof GitBranchUndetectedError&&(ui.error({command,code:"GIT_BRANCH_UNDETECTED",message:err.message,hint:"Pass `--branch <name>` explicitly, or check out a branch (e.g. `git checkout main`)."}),process.exit(1)),err instanceof InvalidBranchOverrideError&&(ui.error({command,code:"INVALID_ENV_OVERRIDE",message:err.message,hint:"Branch names must match /^[a-zA-Z0-9._/-]+$/ \u2014 e.g. `main`, `feat/seo`, `release/v1`."}),process.exit(1)),err instanceof BranchNotFoundError&&(ui.error({command,code:"ENV_NOT_FOUND",message:err.message,hint:"Run `fimo branch` to list Branches, or `fimo branch <name>` to create the one you want."}),process.exit(1)),err instanceof SchemaCommandError&&(ui.error({command,code:err.code,message:err.message}),process.exit(1)),err instanceof EntriesInputError&&(ui.error({command,code:"INVALID_ENTRY_INPUT",message:err.message}),process.exit(1)),reportSingleContentTypeError(command,err)&&process.exit(1),err instanceof SinglesInputError&&(ui.error({command,code:"INVALID_SINGLE_INPUT",message:err.message}),process.exit(1)),err instanceof WebhookCommandError&&(ui.error({command,code:err.code,message:err.message}),process.exit(1)),ui.error({command,code:"COMMAND_FAILED",message:formatZodIssues(err)??(err instanceof Error?err.message:String(err))}),process.exit(1)});
|
|
1009
1011
|
/*! Bundled license information:
|
|
1010
1012
|
|