fimo 2.10.1-staging.1 → 2.10.1-staging.3
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 +57 -139
- package/assets/skills/fimo-cli/SKILL.studio.md +42 -0
- package/assets/skills/fimo-cli/references/branches.md +43 -106
- package/assets/skills/fimo-cli/references/content/bulk.md +48 -0
- package/assets/skills/fimo-cli/references/content/entries.md +54 -0
- package/assets/skills/fimo-cli/references/content/localized.md +56 -0
- package/assets/skills/fimo-cli/references/content/schemas.md +29 -0
- package/assets/skills/fimo-cli/references/content/sql.md +57 -0
- package/assets/skills/fimo-cli/references/content.md +33 -272
- package/assets/skills/fimo-cli/references/deploy.md +35 -126
- package/assets/skills/fimo-cli/references/domains.md +38 -131
- package/assets/skills/fimo-cli/references/forms.md +1 -1
- package/assets/skills/fimo-cli/references/init.md +36 -170
- package/assets/skills/fimo-cli/references/locales.md +2 -2
- package/assets/skills/fimo-cli/references/projects.md +1 -1
- package/assets/skills/fimo-code/references/design.md +42 -126
- package/assets/skills/fimo-migration/SKILL.md +114 -408
- package/assets/skills/fimo-migration/references/content-delivery.md +67 -0
- package/assets/skills/fimo-migration/references/frameworks/nextjs.md +1 -1
- package/assets/skills/fimo-migration/references/qa/browser.md +41 -0
- package/assets/skills/fimo-migration/references/qa/guardrails.md +95 -0
- package/assets/skills/fimo-migration/references/qa/results.md +78 -0
- package/assets/skills/fimo-migration/references/qa.md +102 -383
- package/assets/skills/fimo-migration/references/questions-and-improvements.md +77 -168
- package/assets/skills/fimo-migration/references/setup.md +90 -0
- package/assets/skills/fimo-migration/references/workers/validator.md +2 -2
- package/assets/skills/fimo-migration/references/workers.md +1 -1
- package/assets/skills/fimo-migration/references/workflow.md +117 -171
- package/assets/skills/fimo-studio/SKILL.md +12 -11
- package/assets/skills/fimo-studio/references/ai-chat/agents.md +46 -0
- package/assets/skills/fimo-studio/references/ai-chat/default-agents.md +57 -0
- package/assets/skills/fimo-studio/references/ai-chat/routines.md +53 -0
- package/assets/skills/fimo-studio/references/ai-chat.md +39 -76
- package/assets/skills/fimo-studio/references/custom-domains.md +2 -2
- package/assets/skills/fimo-studio/references/publish-and-deploy.md +1 -1
- package/dist/cli/bundle.json +1 -1
- package/dist/cli/index.js +38 -17
- 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
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __fimoCreateRequire } from 'node:module';
|
|
3
3
|
const require = __fimoCreateRequire(import.meta.url);
|
|
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","Starter","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 isProcessControlEnvKey(key){return PROCESS_CONTROL_ENV_KEYS.has(key)||PROCESS_CONTROL_ENV_PREFIXES.some(prefix=>key.startsWith(prefix))}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(projectId2,branch,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId2}-${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,PROCESS_CONTROL_ENV_KEYS,PROCESS_CONTROL_ENV_PREFIXES,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_PREVIEW_PARENT_ORIGIN","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"],PROCESS_CONTROL_ENV_KEYS=new Set(["PATH","HOME","SHELL","BASH_ENV","ENV","PROMPT_COMMAND","USER","TMPDIR","HOST","HOSTNAME","PORT","NODE_ENV","NODE_OPTIONS","NODE_PATH","NODE_EXTRA_CA_CERTS","NODE_TLS_REJECT_UNAUTHORIZED","SSL_CERT_FILE","CURL_CA_BUNDLE","PYTHONPATH","LD_PRELOAD","LD_LIBRARY_PATH","HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","FIMO_VALIDATION_BUILD","FIMO_SKIP_VERSION_CHECK","FIMO_EDITING_METADATA","FIMO_AGENT_TMP_DIR"]),PROCESS_CONTROL_ENV_PREFIXES=["GIT_","NPM_CONFIG_","PNPM_","YARN_","COREPACK_","BUN_","DENO_"];__name(isProcessControlEnvKey,"isProcessControlEnvKey");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,path52){let conditionPath=[...path52,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,path52)=>{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,path52));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path52,fieldName,variant.uid]);else walk(field.schema.fields,[...path52,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path52,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path52,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_agent_trace_budget_wrap_up_read","ops_context_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_memory_health_read","ops_routine_metrics_read","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_agent_runtime_attach","ops_billing_database_compute_attach","ops_billing_cache_invalidate","ops_billing_dispatch_discard","ops_billing_legacy_premium_enroll","ops_billing_legacy_premium_comp","ops_organization_feature_set","ops_billing_plan_transition_notices","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_signal_case_decision","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","ops_operation_plan","project_sync","project_thumbnail_regenerate","project_delete","project_import","organization_delete","credits_topup","credits_burn","user_session_revoke","user_ban","user_unban","user_impersonate","user_role_change","user_sessions_revoke","user_delete","platform_pool_change","platform_maintenance_change","platform_sync","platform_tenant_schema_sync","integration_event_replay","ops_billing_dispatch_retry","ops_billing_plan_projection_reconcile","ops_agent_chat_create","ops_pylon_issue_change","ops_pylon_note_create","ops_pylon_reply_preview","ops_pylon_reply_approve","ops_pylon_reply_send","admin_playground_run","ops_find","ops_project_health_read","ops_migrations_read","ops_operational_read","ops_billing_report_read","ops_users_read","ops_organizations_read","ops_merges_read","ops_platform_read","ops_watch_read","ops_notification_read","ops_audit_read"],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";var ORGANIZATION_FEATURES,AGENT_PLANS,AgentPlanSchema,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=["routine_planner","pro_agents"],AGENT_PLANS=["free","starter","pro"],AgentPlanSchema=z12.enum(AGENT_PLANS),OrganizationFeatureSchema=z12.enum(ORGANIZATION_FEATURES),OrganizationFeaturesDTOSchema=z12.object({features:z12.record(OrganizationFeatureSchema,z12.boolean()),lockedByPlan:z12.array(OrganizationFeatureSchema),agentPlan:AgentPlanSchema}),OrganizationFeaturesDTO=createDTO(OrganizationFeaturesDTOSchema),OrganizationFeatureStateDTOSchema=z12.object({feature:OrganizationFeatureSchema,enabled:z12.boolean(),default:z12.boolean(),lockedByPlan:z12.boolean(),override:z12.boolean().nullable(),reason:z12.string().nullable(),updatedBy:z12.string().nullable(),updatedAt:z12.string().datetime().nullable()}),OrganizationFeatureSetSchema=z12.object({state:z12.enum(["on","off","default"]),reason:z12.string().trim().min(1).max(500),apply:z12.boolean().default(!1),confirmProduction:z12.boolean().default(!1)})}});import{z as z13}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_SUPPORT_PRESET,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,OpsAgentTraceCostliestInputSchema,OpsAgentTraceSpansInputSchema,OpsSpanBodyEdgeSchema,OpsAgentTraceSpanInputSchema,OpsAgentTraceMessagesInputSchema,OpsAgentHealthGroupBySchema,OpsAgentHealthInputSchema,OPS_DATA_USAGE_MAX_WINDOW_MS,OpsDataUsageGroupBySchema,OpsDataUsageInputSchema,OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,OpsContextHealthInputSchema,OPS_MEMORY_HEALTH_MAX_WINDOW_MS,OpsMemoryHealthInputSchema,opsChatHistoryWindow,OpsChatHistoryHealthInputSchema,OpsChatHistoryCallsInputSchema,OpsChatHistoryJudgeInputSchema,OPS_ROUTINE_METRICS_MAX_WINDOW_MS,OpsRoutineMetricsGroupBySchema,OpsRoutineMetricsSortBySchema,OpsRoutineMetricsInputSchema,OpsChatHistoryJudgeCalibrationInputSchema,OpsAgentTraceStatsGroupBySchema,OpsSpanTypeSchema,OpsAgentTraceStatsInputSchema,OpsAgentProviderErrorsInputSchema,OpsBillingCacheInvalidateInputSchema,OpsBillingEntitlementSyncInputSchema,OpsBillingAgentRuntimeAttachInputSchema,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,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_organization_features_dto();init_env();OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z13.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops: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","ops:users:read","ops:users:write","ops:organizations:read","ops:organizations:write","ops:merges:read","ops:merges:write","ops:platform:read","ops:platform:write","ops:project:admin","ops:credits:write"],OpsPermissionSchema=z13.enum(OPS_PERMISSIONS),OPS_SUPPORT_PRESET=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:users:read","ops:organizations:read","ops:merges:read","ops:platform:read","ops:billing:read","ops:support:read","ops:support:write","ops:customers:read","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:validations:read","ops:audit:read","ops:notification:preview"],OPS_PERMISSION_PRESETS={support:OPS_SUPPORT_PRESET,engineer:[...OPS_SUPPORT_PRESET,"ops:project:operate","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:braintrust:read","ops:customers:write","ops:billing:write","ops:organization:features:write","ops:known-issues:write","ops:validations:write","ops:merges:write","ops:platform:write","ops:users:write"],full:[...OPS_PERMISSIONS]},OPS_SERVICE_PERMISSION_PRESETS={support:OPS_PERMISSION_PRESETS.support,engineer:OPS_PERMISSION_PRESETS.engineer,full:OPS_PERMISSION_PRESETS.full.filter(permission=>permission!=="ops:notification:approve")},OpsAccessGrantInputSchema=z13.object({permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),enabled:z13.boolean().default(!0)}),OpsServiceTokenInputSchema=z13.object({name:z13.string().trim().min(1).max(120),permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),expiresAt:z13.coerce.date()}).refine(input=>!input.permissions.includes("ops:notification:approve"),{path:["permissions"],message:"Service credentials cannot approve customer notifications"}).refine(input=>input.expiresAt.getTime()>Date.now(),{path:["expiresAt"],message:"Service credential expiry must be in the future"}),OpsCustomerProjectInputSchema=z13.object({importanceReason:z13.string().trim().min(1).max(1e3),ownerUserId:z13.string().trim().min(1).nullable().optional(),framework:z13.string().trim().max(120).nullable().optional(),packageManager:z13.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z13.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z13.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z13.object({projectId:z13.uuid(),title:z13.string().trim().min(1).max(240),userReport:z13.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z13.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z13.string().trim().max(1e4).nullable().optional(),outcome:z13.string().trim().max(1e4).nullable().optional(),evidence:z13.array(z13.record(z13.string(),z13.unknown())).max(100).optional()}).refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_KNOWN_ISSUE_STATUSES=["open","monitoring","resolved"],OpsKnownIssueStatusSchema=z13.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z13.object({fingerprint:z13.string().trim().min(1).max(240),title:z13.string().trim().min(1).max(240),description:z13.string().trim().min(1).max(1e4),affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z13.array(z13.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z13.string().trim().min(1).max(64).nullable().optional(),workaround:z13.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100),detectionQueries:z13.array(z13.string().trim().min(1).max(2e3)).max(50),status:OpsKnownIssueStatusSchema}).partial().refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_VALIDATION_OUTCOMES=["passed","failed","inconclusive"],OpsValidationOutcomeSchema=z13.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z13.object({changeReference:z13.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z13.string().trim().min(1).max(1e4),evidence:z13.array(z13.record(z13.string(),z13.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z13.object({recipientEmail:z13.email().optional(),subject:z13.string().trim().min(1).max(200).default("An update from Fimo"),message:z13.string().trim().min(1).max(5e3),locale:z13.string().trim().min(2).max(20),reason:z13.string().trim().min(1).max(1e3),acknowledgePolicy:z13.literal(!0)}),OpsPylonIssueIdSchema=z13.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsPylonReasonSchema=z13.string().trim().min(1).max(1e3),OpsPylonMessageSchema=z13.string().trim().min(1).max(5e3),OpsPylonMessageIdSchema=z13.string().trim().min(1).max(255),OpsPylonEmailListSchema=z13.array(z13.email()).max(50).default([]),OpsPylonResolveInputSchema=z13.object({reason:OpsPylonReasonSchema}),OpsPylonNoteInputSchema=z13.object({message:OpsPylonMessageSchema,reason:OpsPylonReasonSchema}),OpsPylonReplyPreviewInputSchema=z13.object({messageId:OpsPylonMessageIdSchema,message:OpsPylonMessageSchema,toEmails:OpsPylonEmailListSchema,ccEmails:OpsPylonEmailListSchema,bccEmails:OpsPylonEmailListSchema,reason:OpsPylonReasonSchema,acknowledgePolicy:z13.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=z13.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsSentryResolveInputSchema=z13.object({reason:z13.string().trim().min(1).max(1e3)}),OpsTraceIdSchema=z13.string().trim().regex(/^[a-fA-F0-9]{32}$/).transform(value=>value.toLowerCase()),OpsTraceReadInputSchema=z13.object({projectId:z13.uuid(),from:z13.coerce.date(),to:z13.coerce.date(),reason:z13.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=z13.string().trim().regex(/^[A-Za-z0-9_-]{1,200}$/),OpsAgentInvocationStatusSchema=z13.enum(["planned","running","finished","cancelled","errored","refused"]),OpsAgentTraceListInputSchema=z13.object({projectId:z13.uuid().optional(),organizationId:z13.string().trim().min(1).max(255).optional(),agentKey:z13.string().trim().min(1).max(120).optional(),threadId:z13.uuid().optional(),status:OpsAgentInvocationStatusSchema.optional(),since:z13.coerce.date().optional(),minCostUsd:z13.coerce.number().min(0).optional(),tracedOnly:z13.coerce.boolean().default(!1),limit:z13.coerce.number().int().min(1).max(100).default(25),reason:z13.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"}),OpsAgentTraceCostliestInputSchema=z13.object({since:z13.coerce.date(),until:z13.coerce.date(),limit:z13.coerce.number().int().min(1).max(50).default(25),reason:z13.string().trim().min(1).max(1e3)}).superRefine((input,ctx)=>{input.until<input.since&&ctx.addIssue({code:"custom",path:["until"],message:"until must be at or after since"}),input.until.getTime()-input.since.getTime()>744*60*60*1e3&&ctx.addIssue({code:"custom",path:["since"],message:"window must not exceed 31 days"})}),OpsAgentTraceSpansInputSchema=z13.object({limit:z13.coerce.number().int().min(1).max(500).default(200),reason:z13.string().trim().min(1).max(1e3)}),OpsSpanBodyEdgeSchema=z13.enum(["start","end"]).default("start"),OpsAgentTraceSpanInputSchema=z13.object({maxChars:z13.coerce.number().int().min(500).max(2e5).default(2e4),edge:OpsSpanBodyEdgeSchema,reason:z13.string().trim().min(1).max(1e3)}),OpsAgentTraceMessagesInputSchema=z13.object({messageIndex:z13.coerce.number().int().min(0).optional(),maxChars:z13.coerce.number().int().min(500).max(2e5).default(2e4),reason:z13.string().trim().min(1).max(1e3)}),OpsAgentHealthGroupBySchema=z13.enum(["agent","status","branch","project","day"]),OpsAgentHealthInputSchema=z13.strictObject({projectId:z13.uuid().optional(),organizationId:z13.string().trim().min(1).max(255).optional(),branch:BranchSchema.optional(),agentKey:z13.string().trim().min(1).max(120).optional(),since:z13.coerce.date(),until:z13.coerce.date().optional(),groupBy:OpsAgentHealthGroupBySchema.default("agent"),includeChildren:z13.coerce.boolean().default(!1),limit:z13.coerce.number().int().min(1).max(200).default(50),reason:z13.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=z13.enum(["operation","provider","day","organization","agent"]),OpsDataUsageInputSchema=z13.strictObject({organizationId:z13.string().trim().min(1).max(255).optional(),since:z13.coerce.date(),until:z13.coerce.date().optional(),groupBy:OpsDataUsageGroupBySchema.default("operation"),limit:z13.coerce.number().int().min(1).max(200).default(50),reason:z13.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=z13.object({projectId:z13.uuid().optional(),since:z13.coerce.date(),until:z13.coerce.date().optional(),limit:z13.coerce.number().int().min(1).max(1e3).default(500),reason:z13.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"}),OPS_MEMORY_HEALTH_MAX_WINDOW_MS=10080*60*1e3,OpsMemoryHealthInputSchema=z13.object({projectId:z13.uuid().optional(),since:z13.coerce.date(),until:z13.coerce.date().optional(),limit:z13.coerce.number().int().min(1).max(1e3).default(200),reason:z13.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_MEMORY_HEALTH_MAX_WINDOW_MS,{path:["since"],message:"memory health window cannot exceed 7 days"}),opsChatHistoryWindow={projectId:z13.uuid().optional(),since:z13.coerce.date(),until:z13.coerce.date().default(()=>new Date),reason:z13.string().trim().min(1).max(1e3)};__name(refineChatHistoryWindow,"refineChatHistoryWindow");OpsChatHistoryHealthInputSchema=refineChatHistoryWindow(z13.strictObject(opsChatHistoryWindow)),OpsChatHistoryCallsInputSchema=refineChatHistoryWindow(z13.strictObject({...opsChatHistoryWindow,limit:z13.coerce.number().int().min(1).max(500).default(100)})),OpsChatHistoryJudgeInputSchema=refineChatHistoryWindow(z13.strictObject({...opsChatHistoryWindow,sample:z13.coerce.number().int().min(1).max(25).default(10)})),OPS_ROUTINE_METRICS_MAX_WINDOW_MS=2160*60*60*1e3,OpsRoutineMetricsGroupBySchema=z13.enum(["routine","plan","day","project"]),OpsRoutineMetricsSortBySchema=z13.enum(["total","jev","runs"]),OpsRoutineMetricsInputSchema=z13.strictObject({projectId:z13.uuid().optional(),organizationId:z13.string().trim().min(1).max(255).optional(),plan:AgentPlanSchema.optional(),routine:z13.string().trim().min(1).max(64).optional(),groupBy:OpsRoutineMetricsGroupBySchema.default("routine"),sortBy:OpsRoutineMetricsSortBySchema.default("total"),burstMinutes:z13.coerce.number().int().min(1).max(120).default(10),since:z13.coerce.date(),until:z13.coerce.date().default(()=>new Date),reason:z13.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()<=OPS_ROUTINE_METRICS_MAX_WINDOW_MS,{path:["since"],message:"routine metrics windows cannot exceed 90 days"}),OpsChatHistoryJudgeCalibrationInputSchema=z13.strictObject({reason:z13.string().trim().min(1).max(1e3)}),OpsAgentTraceStatsGroupBySchema=z13.enum(["model","provider","span","type"]),OpsSpanTypeSchema=z13.enum(["llm","tool","function","task","score","eval"]),OpsAgentTraceStatsInputSchema=z13.object({since:z13.coerce.date(),until:z13.coerce.date().optional(),groupBy:OpsAgentTraceStatsGroupBySchema.default("model"),spanType:OpsSpanTypeSchema.optional(),slowerThanSeconds:z13.coerce.number().min(0).optional(),limit:z13.coerce.number().int().min(1).max(200).default(50),reason:z13.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=z13.object({since:z13.coerce.date(),until:z13.coerce.date().default(()=>new Date),model:z13.string().trim().min(1).max(120).optional(),provider:z13.string().trim().min(1).max(120).optional(),spanType:OpsSpanTypeSchema.optional(),before:z13.coerce.date().optional(),limit:z13.coerce.number().int().min(1).max(1e3).default(500),sampleChars:z13.coerce.number().int().min(200).max(2e4).default(1200),correlateInvocations:z13.boolean().default(!1),correlationLimit:z13.coerce.number().int().min(1).max(100).default(25),reason:z13.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=z13.object({reason:z13.string().trim().min(1).max(1e3)}),OpsBillingEntitlementSyncInputSchema=z13.object({reason:z13.string().trim().min(1).max(500),apply:z13.boolean().default(!1),confirmProduction:z13.boolean().default(!1),cursor:z13.string().min(1).optional(),batchSize:z13.number().int().min(1).max(100).default(50),concurrency:z13.number().int().min(1).max(10).default(2)}),OpsBillingAgentRuntimeAttachInputSchema=z13.object({reason:z13.string().trim().min(1).max(500),apply:z13.boolean().default(!1),confirmProduction:z13.boolean().default(!1),organizationIds:z13.array(z13.string().min(1)).min(1).max(100).optional(),cursor:z13.string().min(1).optional(),batchSize:z13.number().int().min(1).max(100).default(50)}),OPS_PROJECT_OPERATIONS=["runtime.bump","preview.restart","production.publish"],OpsProjectOperationKindSchema=z13.enum(OPS_PROJECT_OPERATIONS),ExactVersionSchema=z13.string().trim().regex(/^\d+\.\d+\.\d+$/,"Expected an exact version such as 0.11.0"),OpsProjectOperationPlanInputSchema=z13.discriminatedUnion("kind",[z13.object({kind:z13.literal("runtime.bump"),targetVersion:ExactVersionSchema}),z13.object({kind:z13.literal("preview.restart")})]),OPS_MIGRATIONS=["project.v3-to-v4"],OpsMigrationIdSchema=z13.enum(OPS_MIGRATIONS),OPS_MIGRATION_PLAN_STATUSES=["applicable","not_applicable","unknown"],OpsMigrationPlanStatusSchema=z13.enum(OPS_MIGRATION_PLAN_STATUSES),OPS_MIGRATION_CHANGE_ACTIONS=["create","rewrite","delete"],OpsMigrationChangeActionSchema=z13.enum(OPS_MIGRATION_CHANGE_ACTIONS),OpsMigrationDryRunInputSchema=z13.object({migrationId:OpsMigrationIdSchema,projectEnv:z13.string().trim().min(1).max(255).default("main"),reason:z13.string().trim().min(1).max(1e3)}),OpsProjectFilePathSchema=z13.string().trim().min(1).max(1024),OpsProjectFileReasonSchema=z13.string().trim().min(1).max(1e3),OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES=["pnpm-lock.yaml","bun.lockb","bun.lock","yarn.lock","package-lock.json"],OpsProjectPackageManagerInspectInputSchema=z13.object({reason:OpsProjectFileReasonSchema}),OpsProjectFileReadInputSchema=z13.object({path:OpsProjectFilePathSchema,reason:OpsProjectFileReasonSchema}),OpsProjectFileGlobInputSchema=z13.object({pattern:z13.string().min(1).max(300).optional(),limit:z13.coerce.number().int().min(1).max(2e3).default(2e3),reason:OpsProjectFileReasonSchema}),OpsProjectFileGrepInputSchema=z13.object({pattern:z13.string().min(1).max(200),include:z13.string().min(1).max(300).optional(),caseInsensitive:z13.boolean().default(!1),maxMatches:z13.coerce.number().int().min(1).max(200).default(100),reason:OpsProjectFileReasonSchema}),OPS_POSTHOG_EVENTS=["didCreateProject","didInitiateProject","didDeploy","didDeployProject","didFirstPublish"],OPS_POSTHOG_QUESTION="project-milestone-counts-v1",OpsPosthogTimestampSchema=z13.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=z13.strictObject({projectId:z13.uuid().transform(value=>value.toLowerCase()),from:OpsPosthogTimestampSchema,to:OpsPosthogTimestampSchema,reason:z13.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=z13.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=z13.strictObject({completeAggregate:z13.boolean(),truncated:z13.boolean().nullable(),sampled:z13.boolean().nullable(),pagination:z13.enum(["not_applicable","unexpected","unknown"]),providerFreshnessKnown:z13.literal(!1),providerAsOf:z13.null(),projectFilter:z13.literal("exact properties.projectId equality"),environmentFilterSupported:z13.literal(!1),excludesMissingProjectId:z13.literal(!0),transport:z13.literal("server"),consentCoverage:z13.literal("server-policy-not-browser-consent"),operationDedupeAvailable:z13.literal(!1)}),OpsPosthogCountsSchema=z13.array(z13.strictObject({event:z13.enum(OPS_POSTHOG_EVENTS),captureCount:z13.number().int().min(0).max(Number.MAX_SAFE_INTEGER)})).length(5).refine(counts=>counts.every((entry,i)=>entry.event===OPS_POSTHOG_EVENTS[i])),OpsPosthogMilestonesResponseSchema=z13.strictObject({schemaVersion:z13.literal(1),questionId:z13.literal(OPS_POSTHOG_QUESTION),backendProfile:OpsBackendProfileSchema,projectId:z13.uuid().nullable(),projectEnvironment:z13.literal("mixed_or_unrecorded"),window:z13.strictObject({from:z13.iso.datetime(),to:z13.iso.datetime(),bounds:z13.literal("[from,to)")}).nullable(),source:z13.literal("posthog"),sourceStatus:z13.enum(["available","unavailable","forbidden"]),failureCode:OpsPosthogFailureCodeSchema.nullable(),queriedAt:z13.iso.datetime(),auditId:z13.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=z13.object({reason:z13.string().trim().min(1).max(1e3),limit:z13.number().int().min(1).max(100).default(25),checkProvider:z13.boolean().default(!1)}),OpsProjectAnalyticsHealthInputSchema=z13.object({branch:z13.string().trim().min(1).max(255),canaryPath:z13.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:z13.iso.datetime({offset:!0}),until:z13.iso.datetime({offset:!0}),reason:z13.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 z14}from"zod";function resolveOpsTime(value,now=new Date){let relative3=RELATIVE_WINDOW.exec(value.trim());if(relative3){let amount=Number(relative3[1]),unit=relative3[2];return new Date(now.getTime()-amount*UNIT_MS[unit]).toISOString()}return new Date(value).toISOString()}function opsHoursSince(value,now=new Date){let start=Date.parse(resolveOpsTime(value,now));return Math.max(1,Math.ceil((now.getTime()-start)/UNIT_MS.h))}var RELATIVE_WINDOW,time,opsArgs,OPS_STANDARD_ARG_KEYS,UNIT_MS,init_args=__esm({"../../packages/api-contracts/dist/esm/ops/args.js"(){"use strict";RELATIVE_WINDOW=/^(\d+)(m|h|d|w)$/,time=z14.string().trim().min(1).max(64).refine(value=>RELATIVE_WINDOW.test(value)||!Number.isNaN(Date.parse(value)),{message:"Expected an ISO timestamp or a relative window such as 30m, 24h, 7d or 2w"}),opsArgs={project:z14.uuid().describe("Fimo project id"),org:z14.string().trim().min(1).max(255).describe("Organization id"),user:z14.string().trim().min(1).max(255).describe("User id"),env:z14.string().trim().min(1).max(255).describe("Project environment (branch), e.g. main or prod"),since:time.describe("Start of the window: ISO timestamp or relative (30m, 24h, 7d, 2w)"),until:time.describe("End of the window: ISO timestamp or relative (defaults to now)"),limit:z14.coerce.number().int().min(1).max(1e3).describe("Maximum results"),cursor:z14.string().trim().min(1).max(2e3).describe("Continue from a previous page"),query:z14.string().trim().min(1).max(200).describe("Free-text search"),reason:z14.string().trim().min(1).max(1e3).describe("Why this is being read or changed; stored in the audit log"),output:z14.string().trim().min(1).max(4096).describe("Write the result to this local file")},OPS_STANDARD_ARG_KEYS=Object.keys(opsArgs),UNIT_MS={m:6e4,h:36e5,d:864e5,w:6048e5};__name(resolveOpsTime,"resolveOpsTime");__name(opsHoursSince,"opsHoursSince")}});import{z as z15}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=z15.iso.datetime({offset:!0}).pipe(z15.coerce.date()),OpsRecentChatInputSchema=z15.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z15.string().trim().min(1).max(255).optional(),limit:z15.coerce.number().int().min(1).max(200).default(100),cursor:z15.string().trim().min(1).max(2e3).optional(),slim:z15.boolean().default(!0),reason:z15.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=z15.object({id:z15.string(),threadId:z15.string(),providerMessageId:z15.string().nullable(),invocationId:z15.string().nullable(),env:z15.string().nullable(),role:z15.string(),parts:z15.array(z15.record(z15.string(),z15.unknown())),metadata:z15.object({status:z15.string().optional(),traceUrl:z15.string().optional(),externalFileChanges:z15.array(z15.unknown()).optional()}),stats:z15.object({toolCount:z15.number().int().nonnegative(),failedToolCount:z15.number().int().nonnegative()}),createdAt:z15.iso.datetime({offset:!0}),project:z15.object({id:z15.string(),name:z15.string(),displayName:z15.string().nullable(),organizationId:z15.string().nullable()})}),OpsRecentChatResponseSchema=z15.object({target:z15.object({backendProfile:OpsBackendProfileSchema,projectEnv:z15.string().nullable()}),window:z15.object({from:z15.iso.datetime({offset:!0}),to:z15.iso.datetime({offset:!0})}),messages:z15.object({items:z15.array(OpsRecentChatMessageSchema),nextCursor:z15.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});var init_types=__esm({"../../packages/api-contracts/dist/esm/ops/types.js"(){"use strict"}});function compact(value){return Object.fromEntries(Object.entries(value).filter(([,entry])=>entry!==void 0))}function time2(value){return value===void 0?void 0:resolveOpsTime(value)}function seg(value){return encodeURIComponent(value)}var init_shared=__esm({"../../packages/api-contracts/dist/esm/ops/commands/shared.js"(){"use strict";init_args();__name(compact,"compact");__name(time2,"time");__name(seg,"seg")}});import{z as z16}from"zod";var invocation,span,OpsChatViewSchema,OpsChatViewsInputSchema,viewIds,ending,toolCallRow,appCallRow,turnRow,turnSlice,viewEnvelope,OpsChatViewsResponseDTO,agentCommands,init_agent=__esm({"../../packages/api-contracts/dist/esm/ops/commands/agent.js"(){"use strict";init_ops_chat_dto();init_ops();init_create_dto();init_args();init_types();init_shared();invocation=z16.string().trim().min(1).max(255).describe("Agent invocation (run) id"),span=z16.string().trim().min(1).max(255).describe("Braintrust span id"),OpsChatViewSchema=z16.enum(["tool-calls","app-calls","turns","slices"]),OpsChatViewsInputSchema=OpsRecentChatInputSchema.safeExtend({view:OpsChatViewSchema}),viewIds=z16.object({threadId:z16.string(),invocationId:z16.string().nullable(),projectId:z16.string(),messageId:z16.string()}),ending={terminal:z16.string(),terminalReason:z16.string().nullable()},toolCallRow=viewIds.extend({tool:z16.string(),subcommand:z16.string().nullable(),state:z16.string().nullable(),failed:z16.boolean(),errorSignature:z16.string().nullable(),position:z16.number().int().nonnegative(),recoveredNext:z16.boolean().nullable()}),appCallRow=viewIds.extend({routineId:z16.string().nullable(),via:z16.string(),integrationId:z16.string().nullable(),appTool:z16.string().nullable(),withApproval:z16.boolean(),outcome:z16.enum(["ok","failed","approval_required","blocked","pending"]),errorSignature:z16.string().nullable(),position:z16.number().int().nonnegative()}),turnRow=viewIds.extend({...ending,userMessageId:z16.string().nullable(),failureCategory:z16.enum(["expected_billing_stop","expected_model_refusal","expected_cancellation","workspace_failure","provider_model_failure","unknown_failure"]).nullable(),changes:z16.string().nullable(),mergeState:z16.string().nullable(),validation:z16.string().nullable(),publication:z16.string().nullable(),stepCount:z16.number().int().nonnegative(),toolCount:z16.number().int().nonnegative(),failedToolCount:z16.number().int().nonnegative(),hasTextReply:z16.boolean(),fimoAuthored:z16.boolean().nullable()}),turnSlice=viewIds.extend({...ending,previousUserAsk:z16.string().max(300),previousAgentWords:z16.string().max(500),userMessage:z16.string().max(1500),agentReply:z16.string().max(1305),failedToolCalls:z16.array(z16.object({tool:z16.string(),errorSignature:z16.string()})).max(6)}),viewEnvelope=z16.object({target:z16.object({backendProfile:OpsBackendProfileSchema,projectEnv:z16.string().nullable()}),window:z16.object({from:z16.iso.datetime({offset:!0}),to:z16.iso.datetime({offset:!0})})}),OpsChatViewsResponseDTO=createDTO(z16.discriminatedUnion("view",[viewEnvelope.extend({view:z16.literal("tool-calls"),messages:z16.object({items:z16.array(toolCallRow),nextCursor:z16.string().nullable()})}),viewEnvelope.extend({view:z16.literal("app-calls"),messages:z16.object({items:z16.array(appCallRow),nextCursor:z16.string().nullable()})}),viewEnvelope.extend({view:z16.literal("turns"),messages:z16.object({items:z16.array(turnRow),nextCursor:z16.string().nullable()})}),viewEnvelope.extend({view:z16.literal("slices"),messages:z16.object({items:z16.array(turnSlice),nextCursor:z16.string().nullable()})})])),agentCommands=[{id:"agent.chats.views",summary:"Read tool calls, app calls, turn outcomes or customer-text slices from a bounded chat window",permission:"ops:project:chat:read",effect:"read",input:z16.object({view:OpsChatViewSchema,since:opsArgs.since,until:opsArgs.until.optional(),env:opsArgs.env.optional(),limit:opsArgs.limit.max(200).default(100).describe("Source messages per page; each may produce several view rows"),cursor:opsArgs.cursor.optional(),reason:opsArgs.reason,output:opsArgs.output.optional().describe("Private JSON file; required for slices")}),request:__name(input=>({method:"POST",path:"/chat/messages/views",body:compact({view:input.view,from:time2(input.since),to:time2(input.until)??new Date().toISOString(),projectEnv:input.env,limit:input.limit,cursor:input.cursor,reason:input.reason})}),"request")},{id:"agent.chats.recent",summary:"Read recent chat messages across every project in a time window",permission:"ops:project:chat:read",effect:"read",input:z16.object({since:opsArgs.since,until:opsArgs.until.optional(),env:opsArgs.env.optional().describe("Only messages from this environment"),limit:opsArgs.limit.max(200).default(100),cursor:opsArgs.cursor.optional(),full:z16.boolean().default(!1).describe("Include complete message parts instead of the slim transcript"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/chat/messages/recent",body:compact({from:time2(input.since),to:time2(input.until)??new Date().toISOString(),projectEnv:input.env,limit:input.limit,cursor:input.cursor,slim:!input.full,reason:input.reason})}),"request")},{id:"agent.chats.create",summary:"Create an agent chat with routines in a customer project, as the organization owner. Validate the spec and confirm intent first: routines run and spend credits",permission:"ops:project:agents:write",effect:"write",risk:"low",input:z16.object({project:opsArgs.project,spec:z16.record(z16.string(),z16.unknown()).describe("JSON spec: { agent: { name, description } | { template }, routines: [...] }")}),cli:{fileArgs:["spec"]}},{id:"agent.traces.list",summary:"List agent runs for a project, organization or thread, with cost and status",permission:"ops:project:read",effect:"read",input:z16.object({project:opsArgs.project.optional(),org:opsArgs.org.optional(),thread:z16.uuid().optional().describe("Chat thread id"),agent:z16.string().trim().min(1).max(120).optional().describe("Agent key, e.g. chat.project"),status:OpsAgentInvocationStatusSchema.optional(),since:opsArgs.since.optional(),minCost:z16.coerce.number().min(0).optional().describe("Only runs costing at least this many USD"),tracedOnly:z16.boolean().default(!1).describe("Only runs that recorded a Braintrust root span"),limit:opsArgs.limit.max(100).default(25),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-traces/list",body:compact({projectId:input.project,organizationId:input.org,threadId:input.thread,agentKey:input.agent,status:input.status,since:time2(input.since),minCostUsd:input.minCost,tracedOnly:input.tracedOnly,limit:input.limit,reason:input.reason})}),"request")},{id:"agent.traces.costliest",summary:"Rank agent runs across projects by recorded cost, without content (maximum 31 days and 50 runs)",permission:"ops:project:read",effect:"read",input:z16.object({since:opsArgs.since,until:opsArgs.until.describe("Inclusive window end: ISO timestamp or relative (required)"),limit:opsArgs.limit.max(50).default(25),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-traces/costliest",body:{since:time2(input.since),until:time2(input.until),limit:input.limit,reason:input.reason}}),"request")},{id:"agent.traces.budget",summary:"List chats whose runs crossed the context budget and had to wrap up (content-free)",permission:"ops:braintrust:read",effect:"read",input:z16.object({since:opsArgs.since,until:opsArgs.until.optional(),limit:opsArgs.limit.max(25).default(25),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-traces/budget-wrap-up",body:compact({since:time2(input.since),until:time2(input.until),limit:input.limit,reason:input.reason})}),"request")},{id:"agent.traces.spans",summary:"List the spans of one agent run",permission:"ops:braintrust:read",effect:"read",input:z16.object({invocation,limit:opsArgs.limit.max(500).default(200),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/agent-traces/${seg(input.invocation)}/spans`,body:{limit:input.limit,reason:input.reason}}),"request")},{id:"agent.traces.span",summary:"Read one span body (input and output) of an agent run",permission:"ops:braintrust:read",effect:"read",input:z16.object({invocation,span,maxChars:z16.coerce.number().int().min(500).max(2e5).default(2e4).describe("Per-field character bound"),tail:z16.boolean().default(!1).describe("Return the end of an over-long body instead of the start"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/agent-traces/${seg(input.invocation)}/spans/${seg(input.span)}`,body:{maxChars:input.maxChars,edge:input.tail?"end":"start",reason:input.reason}}),"request")},{id:"agent.traces.messages",summary:"Read the conversation the model saw in one LLM span",permission:"ops:braintrust:read",effect:"read",input:z16.object({invocation,span,message:z16.coerce.number().int().min(0).optional().describe("Return this one message instead of the index"),maxChars:z16.coerce.number().int().min(500).max(2e5).default(2e4),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/agent-traces/${seg(input.invocation)}/spans/${seg(input.span)}/messages`,body:compact({messageIndex:input.message,maxChars:input.maxChars,reason:input.reason})}),"request")},{id:"agent.traces.stats",summary:"Aggregate agent step latency, tokens and cost by model, provider, span or type",permission:"ops:braintrust:read",effect:"read",input:z16.object({since:opsArgs.since,until:opsArgs.until.optional(),groupBy:OpsAgentTraceStatsGroupBySchema.default("model"),spanType:OpsSpanTypeSchema.optional(),slowerThan:z16.coerce.number().positive().optional().describe("Only steps at least this many seconds slow"),limit:opsArgs.limit.max(200).default(50),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-traces/stats",body:compact({since:time2(input.since),until:time2(input.until),groupBy:input.groupBy,spanType:input.spanType,slowerThanSeconds:input.slowerThan,limit:input.limit,reason:input.reason})}),"request")}]}});import{z as z17}from"zod";var assistantCommands,init_assistant=__esm({"../../packages/api-contracts/dist/esm/ops/commands/assistant.js"(){"use strict";init_args();init_types();init_shared();assistantCommands=[{id:"assistant.threads.list",summary:"List your admin assistant threads, newest activity first",permission:"ops:platform:read",effect:"read",input:z17.object({query:opsArgs.query.optional().describe("Match the thread title"),limit:z17.coerce.number().int().min(1).max(100).optional().describe("Maximum results"),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/assistant/threads",query:{q:input.query,limit:input.limit,cursor:input.cursor}}),"request")},{id:"assistant.threads.get",summary:"Read one admin assistant thread with every message",permission:"ops:platform:read",effect:"read",input:z17.object({thread:z17.uuid().describe("Admin assistant thread id")}),request:__name(input=>({method:"GET",path:`/assistant/threads/${seg(input.thread)}`}),"request")}]}});import{z as z18}from"zod";var day,billingCommands,init_billing=__esm({"../../packages/api-contracts/dist/esm/ops/commands/billing.js"(){"use strict";init_args();init_types();init_shared();day=z18.iso.date().describe("UTC day, YYYY-MM-DD"),billingCommands=[{id:"billing.customer",summary:"Read one Hyperline billing customer",permission:"ops:billing:read",effect:"read",input:z18.object({customer:z18.string().trim().min(1).max(255).describe("Hyperline customer id"),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/billing/customers/${seg(input.customer)}`,query:{reason:input.reason}}),"request")},{id:"billing.org",summary:"Read an organization's billing state: subscription, plan projection, credits and wallet",permission:"ops:billing:read",effect:"read",input:z18.object({org:opsArgs.org,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/billing/organizations/${seg(input.org)}`,query:{reason:input.reason}}),"request")},{id:"billing.bandwidth-contract",summary:"Read an organization's hosting bandwidth contract and current usage",permission:"ops:billing:read",effect:"read",input:z18.object({org:opsArgs.org,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/billing/organizations/${seg(input.org)}/bandwidth-contract`,query:{reason:input.reason}}),"request")},{id:"billing.ledger",summary:"Read an organization's credit ledger: holds, settlements, grants or usage events",permission:"ops:billing:read",effect:"read",input:z18.object({org:opsArgs.org,kind:z18.enum(["holds","settlements","grants","usage-events"]),since:opsArgs.since.optional(),limit:opsArgs.limit.max(200).default(100),cursor:opsArgs.cursor.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/ledger",query:compact({organizationId:input.org,kind:input.kind,since:time2(input.since),limit:input.limit,cursor:input.cursor,reason:input.reason})}),"request")},{id:"billing.plans.report",summary:"Find organizations whose local plan projection is missing or unusable (one page)",permission:"ops:billing:read",effect:"read",input:z18.object({cursor:opsArgs.cursor.optional().describe("Resume after this organization id"),at:z18.iso.datetime({offset:!0}).optional().describe("Reuse evaluatedAt when resuming a scan"),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/plan-projections/report",query:compact({reason:input.reason,at:input.at??new Date().toISOString(),cursor:input.cursor})}),"request")},{id:"billing.plans.reconcile",summary:"Repair organizations' local plan projections from Hyperline",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z18.object({orgs:z18.array(opsArgs.org).min(1).max(100).describe("Organization ids")})},{id:"billing.legacy-premium.report",summary:"Report legacy Premium organizations and where each stands in the Pro transition",permission:"ops:billing:read",effect:"read",input:z18.object({org:opsArgs.org.optional(),limit:opsArgs.limit.max(200).optional(),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/legacy-premium-report",query:compact({reason:input.reason,org:input.org,limit:input.limit})}),"request")},{id:"billing.legacy-premium.enroll",summary:"Record the approved Pro offer for one legacy Premium organization",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z18.object({org:opsArgs.org,deadline:z18.string().trim().min(1).max(64).describe("Decision date exactly 90 calendar days from today")})},{id:"billing.legacy-premium.comp",summary:"Accept an internal organization's Pro offer on its behalf, free through a 100% coupon",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z18.object({org:opsArgs.org,coupon:z18.string().trim().min(1).max(64).describe("Hyperline coupon id: 100% off every product")})},{id:"billing.legacy-premium.notify",summary:"Send the due legacy Premium transition notices for one organization",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z18.object({org:opsArgs.org})},{id:"billing.entitlements.sync",summary:"Reconcile subscription entitlement properties in Hyperline with Fimo's plans (one batch)",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z18.object({batchSize:z18.coerce.number().int().min(1).max(100).default(50),concurrency:z18.coerce.number().int().min(1).max(10).default(2),cursor:opsArgs.cursor.optional().describe("Resume after this organization id")})},{id:"billing.agent-runtime.attach",summary:"Attach the Agent runtime product to PAYG and Pro subscriptions (one batch)",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z18.object({orgs:z18.array(opsArgs.org).min(1).max(100).optional().describe("Only these organizations"),batchSize:z18.coerce.number().int().min(1).max(100).default(25),cursor:opsArgs.cursor.optional().describe("Resume after this organization id")})},{id:"billing.database-compute.attach",summary:"Attach the Database compute product to PAYG, Starter and Pro subscriptions (one batch)",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z18.object({orgs:z18.array(opsArgs.org).min(1).max(100).optional().describe("Only these organizations"),batchSize:z18.coerce.number().int().min(1).max(100).default(25),cursor:opsArgs.cursor.optional().describe("Resume after this organization id")})},{id:"billing.dispatches.list",summary:"List billing usage dispatches to Hyperline by state",permission:"ops:billing:read",effect:"read",input:z18.object({state:z18.enum(["pending","dispatched","dead-lettered","discarded"]),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/billing/dispatches",body:{state:input.state,reason:input.reason}}),"request")},{id:"billing.dispatches.discard",summary:"Discard dead-lettered billing dispatches so they are never sent",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z18.object({dispatches:z18.array(z18.uuid()).min(1).max(100).describe("Dispatch ids")})},{id:"billing.dispatches.retry",summary:"Retry a dead-lettered billing dispatch",permission:"ops:billing:write",effect:"write",risk:"low",input:z18.object({dispatch:z18.uuid().describe("Dispatch id")})},{id:"billing.cache.invalidate",summary:"Clear an organization's cached billing state so the next read goes to Hyperline",permission:"ops:billing:write",effect:"write",risk:"low",input:z18.object({org:opsArgs.org})},{id:"billing.hosting-usage.day",summary:"Read hosting usage recorded for one source, meter and day",permission:"ops:billing:read",effect:"read",input:z18.object({source:z18.string().trim().min(1).max(100),meter:z18.string().trim().min(1).max(100),day,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/hosting-usage",query:{source:input.source,meter:input.meter,day:input.day,reason:input.reason}}),"request")},{id:"billing.hosting-usage.reconciliation",summary:"Compare a project's served traffic with the hosting usage billed for one day",permission:"ops:billing:read",effect:"read",input:z18.object({project:opsArgs.project,day,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/hosting-usage/reconciliation",query:{projectId:input.project,day:input.day,reason:input.reason}}),"request")},{id:"billing.hosting-usage.periods",summary:"List an organization's hosting billing periods",permission:"ops:billing:read",effect:"read",input:z18.object({org:opsArgs.org,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/hosting-usage/customer-periods",query:{organizationId:input.org,reason:input.reason}}),"request")}]}});import{z as z19}from"zod";var coreCommands,init_core=__esm({"../../packages/api-contracts/dist/esm/ops/commands/core.js"(){"use strict";init_args();init_types();init_shared();coreCommands=[{id:"find",summary:"Find projects, organizations or users by name, slug, domain, email or id",permission:"ops:project:read",effect:"read",input:z19.object({query:opsArgs.query,kind:z19.enum(["project","org","user"]).optional().describe("Only this kind of record"),limit:opsArgs.limit.max(100).default(20),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/find",query:compact({q:input.query,kind:input.kind,limit:input.limit,cursor:input.cursor})}),"request"),cli:{positional:"query"}},{id:"audit.list",summary:"List audit log entries, newest first",permission:"ops:audit:read",effect:"read",input:z19.object({project:opsArgs.project.optional(),org:opsArgs.org.optional(),actor:z19.string().trim().min(1).max(255).optional().describe("User or service principal id"),action:z19.string().trim().min(1).max(64).optional().describe("Audit action, e.g. project_takedown"),since:opsArgs.since.optional(),limit:opsArgs.limit.max(200).default(50)}),request:__name(input=>({method:"GET",path:"/audit",query:compact({projectId:input.project,organizationId:input.org,actor:input.actor,action:input.action,since:time2(input.since),limit:input.limit})}),"request")}]}});import{z as z20}from"zod";var window2,healthCommands,init_health=__esm({"../../packages/api-contracts/dist/esm/ops/commands/health.js"(){"use strict";init_organization_features_dto();init_ops();init_args();init_types();init_shared();window2={since:opsArgs.since,until:opsArgs.until.optional()},healthCommands=[{id:"health.overview",summary:"Platform health brief: Sentry, logs, agents, publishing and support in one window",permission:"ops:project:read",effect:"read",input:z20.object({...window2,project:opsArgs.project.optional().describe("Narrow every source that can be narrowed to one project"),limit:opsArgs.limit.max(100).default(25).describe("Maximum findings per source"),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/health",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,limit:input.limit,reason:input.reason})}),"request")},{id:"health.agents",summary:"Agent run outcomes, cost and duration grouped by agent, status, branch, project or day",permission:"ops:project:read",effect:"read",input:z20.object({...window2,project:opsArgs.project.optional(),org:opsArgs.org.optional(),env:opsArgs.env.optional(),agent:z20.string().trim().min(1).max(120).optional().describe("Agent key, e.g. chat.project"),groupBy:OpsAgentHealthGroupBySchema.default("agent"),includeChildren:z20.boolean().default(!1).describe("Count sub-steps too"),limit:opsArgs.limit.max(200).default(50),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-health",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,organizationId:input.org,branch:input.env,agentKey:input.agent,groupBy:input.groupBy,includeChildren:input.includeChildren,limit:input.limit,reason:input.reason})}),"request")},{id:"health.context",summary:"Context-window pressure and compaction facts for agent turns",permission:"ops:project:read",effect:"read",input:z20.object({...window2,project:opsArgs.project.optional(),limit:opsArgs.limit.max(1e3).default(500),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/context-health",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,limit:input.limit,reason:input.reason})}),"request")},{id:"health.memory",summary:"Agent memory health: threads and routines with missing or stale memory",permission:"ops:project:read",effect:"read",input:z20.object({...window2,project:opsArgs.project.optional(),limit:opsArgs.limit.max(1e3).default(200),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/memory-health",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,limit:input.limit,reason:input.reason})}),"request")},{id:"health.providers",summary:"Model provider errors grouped by signature, optionally correlated to agent runs",permission:"ops:braintrust:read",effect:"read",input:z20.object({...window2,model:z20.string().trim().min(1).max(200).optional(),provider:z20.string().trim().min(1).max(120).optional().describe("e.g. gateway or vertex"),spanType:OpsSpanTypeSchema.optional(),before:z20.string().trim().min(1).max(64).optional().describe("Page boundary: nextBefore from the previous page"),limit:opsArgs.limit.max(1e3).default(500).describe("Error spans to scan per page"),correlate:z20.boolean().default(!1).describe("Resolve the newest occurrences to Fimo runs"),correlationLimit:z20.coerce.number().int().min(1).max(100).default(25),sampleChars:z20.coerce.number().int().min(200).max(2e4).default(1200),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-provider-errors",body:compact({since:time2(input.since),until:time2(input.until),model:input.model,provider:input.provider,spanType:input.spanType,before:input.before,limit:input.limit,sampleChars:input.sampleChars,correlateInvocations:input.correlate||void 0,correlationLimit:input.correlate?input.correlationLimit:void 0,reason:input.reason})}),"request")},{id:"health.chat-history.summary",summary:"How often agents call the chatHistory tool and whether it finds what they need",permission:"ops:project:read",effect:"read",input:z20.object({since:opsArgs.since.optional(),until:opsArgs.until.optional(),project:opsArgs.project.optional(),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/chat-history/health",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,reason:input.reason})}),"request")},{id:"health.chat-history.calls",summary:"List chatHistory tool calls; --with-content adds the surrounding messages (needs chat read)",permission:"ops:project:read",effect:"read",input:z20.object({since:opsArgs.since,until:opsArgs.until.optional(),project:opsArgs.project.optional(),limit:opsArgs.limit.max(500).default(100),withContent:z20.boolean().default(!1),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:input.withContent?"/chat-history/calls/content":"/chat-history/calls",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,limit:input.limit,reason:input.reason})}),"request")},{id:"health.chat-history.judge",summary:"Have a model judge a sample of chatHistory calls; --calibrate runs the labelled benchmark",permission:"ops:project:chat:read",effect:"read",input:z20.object({since:opsArgs.since.optional(),until:opsArgs.until.optional(),project:opsArgs.project.optional(),sample:z20.coerce.number().int().min(1).max(25).default(10),calibrate:z20.boolean().default(!1),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>input.calibrate?{method:"POST",path:"/chat-history/judge/calibration",body:{reason:input.reason}}:{method:"POST",path:"/chat-history/judge",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,sample:input.sample,reason:input.reason})},"request")},{id:"health.data-usage",summary:"Data-provider usage (search, scraping, enrichment) grouped by operation, provider, day, org or agent",permission:"ops:project:read",effect:"read",input:z20.object({...window2,org:opsArgs.org.optional(),groupBy:OpsDataUsageGroupBySchema.default("operation"),limit:opsArgs.limit.max(200).default(50),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/data-usage",body:compact({since:time2(input.since),until:time2(input.until),organizationId:input.org,groupBy:input.groupBy,limit:input.limit,reason:input.reason})}),"request")},{id:"health.routines",summary:"Routine runs, event bursts, Jev trigger calls and cost, by routine, plan, day or project",permission:"ops:project:read",effect:"read",input:z20.object({...window2,project:opsArgs.project.optional(),org:opsArgs.org.optional(),plan:AgentPlanSchema.optional().describe("The organization's agent plan now"),routine:z20.string().trim().min(1).max(64).optional().describe("Template routine key, or custom"),groupBy:OpsRoutineMetricsGroupBySchema.default("routine"),sortBy:OpsRoutineMetricsSortBySchema.default("total").describe("Rank buckets by total cost, Jev's trigger cost, or runs"),burstMinutes:z20.coerce.number().int().min(1).max(120).default(10).describe("An event this many minutes or less after the routine's previous one is a burst"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/routine-metrics",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,organizationId:input.org,plan:input.plan,routine:input.routine,groupBy:input.groupBy,sortBy:input.sortBy,burstMinutes:input.burstMinutes,reason:input.reason})}),"request")},{id:"health.analytics",summary:"Whether a project's website analytics are arriving (content-free counts, max 7 days)",permission:"ops:project:read",effect:"read",input:z20.object({project:opsArgs.project,env:opsArgs.env.default("prod").describe("Environment whose traffic to check; prod for published traffic"),...window2,canaryPath:z20.string().max(300).optional().describe("Exact test path ending in ?fimo_monitor=<UUID>"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/projects/${seg(input.project)}/analytics-health`,body:compact({branch:input.env,canaryPath:input.canaryPath,since:time2(input.since),until:time2(input.until)??new Date().toISOString(),reason:input.reason})}),"request")},{id:"health.session",summary:"A project's work-session and database-branch health: cleanup due, unresolved allocations, capacity",permission:"ops:project:read",effect:"read",input:z20.object({project:opsArgs.project,checkProvider:z20.boolean().default(!1).describe("Include one bounded read-only Neon inventory page"),limit:opsArgs.limit.max(100).default(25),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:`/projects/${seg(input.project)}/session-health`,body:{reason:input.reason,limit:input.limit,checkProvider:input.checkProvider}}),"request")},{id:"health.sandbox",summary:"A project environment's sandbox and preview status",permission:"ops:project:read",effect:"read",input:z20.object({project:opsArgs.project,env:opsArgs.env.default("main"),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:`/projects/${seg(input.project)}/sandbox/status`,body:{projectEnv:input.env,reason:input.reason}}),"request")},{id:"health.schedules",summary:"Failed scheduled runs and webhook deliveries",permission:"ops:project:read",effect:"read",input:z20.object({project:opsArgs.project.optional(),env:opsArgs.env.optional(),schedule:z20.uuid().optional().describe("Schedule id"),run:z20.uuid().optional().describe("Schedule run id (needs --project)"),since:opsArgs.since.optional(),until:opsArgs.until.optional(),limit:opsArgs.limit.max(100).optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/schedules/failures",body:compact({projectId:input.project,projectEnv:input.env,scheduleId:input.schedule,runId:input.run,since:time2(input.since),until:time2(input.until),limit:input.limit,reason:input.reason})}),"request")},{id:"health.integrations",summary:"Failing integration connections and inbound events",permission:"ops:project:read",effect:"read",input:z20.object({project:opsArgs.project.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/integrations/failures",body:compact({projectId:input.project,reason:input.reason})}),"request")},{id:"health.domains",summary:"Custom domains with DNS, SSL or provider problems",permission:"ops:project:read",effect:"read",input:z20.object({project:opsArgs.project.optional(),org:opsArgs.org.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/domains/problems",body:compact({projectId:input.project,organizationId:input.org,reason:input.reason})}),"request")}]}});import{z as z21}from"zod";var mergeCommands,init_merge=__esm({"../../packages/api-contracts/dist/esm/ops/commands/merge.js"(){"use strict";init_args();init_types();init_shared();mergeCommands=[{id:"merge.list",summary:"List merges, newest first; --stuck lists only merges that stopped progressing",permission:"ops:merges:read",effect:"read",input:z21.object({project:opsArgs.project.optional(),stuck:z21.boolean().default(!1).describe("Only merges stuck in a non-terminal state"),status:z21.string().trim().min(1).max(64).optional().describe("Only merges in this status"),since:opsArgs.since.optional(),limit:opsArgs.limit.max(200).default(50),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/merges",query:compact({projectId:input.project,stuck:input.stuck||void 0,status:input.status,since:time2(input.since),limit:input.limit,cursor:input.cursor})}),"request")},{id:"merge.get",summary:"Show one merge with its steps, conflicts and release",permission:"ops:merges:read",effect:"read",input:z21.object({merge:z21.uuid().describe("Merge id")}),request:__name(input=>({method:"GET",path:`/merges/${seg(input.merge)}`}),"request")},{id:"merge.unwind",summary:"Force-unwind a stuck merge: reset the target branch to its pre-merge head and reopen the merge",permission:"ops:merges:write",effect:"write",risk:"high",humanOnly:!0,input:z21.object({merge:z21.uuid().describe("Merge id")})},{id:"merge.fail",summary:"Force-fail a stuck merge without touching the target branch",permission:"ops:merges:write",effect:"write",risk:"high",humanOnly:!0,input:z21.object({merge:z21.uuid().describe("Merge id")})}]}});var MONITORING_SEVERITIES,init_admin_monitoring_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin-monitoring.dto.js"(){"use strict";MONITORING_SEVERITIES=["critical","high","medium","low"]}});import{z as z22}from"zod";var OPS_SIGNAL_CASE_STATES,OpsSignalCaseStateSchema,OpsSignatureHashSchema,monitorCommands,init_monitor=__esm({"../../packages/api-contracts/dist/esm/ops/commands/monitor.js"(){"use strict";init_admin_monitoring_dto();init_args();init_types();init_shared();OPS_SIGNAL_CASE_STATES=["open","accepted","snoozed","dismissed","resolved"],OpsSignalCaseStateSchema=z22.enum(OPS_SIGNAL_CASE_STATES),OpsSignatureHashSchema=z22.string().trim().regex(/^[0-9a-f]{16}$/,"Expected a 16-character signature hash"),monitorCommands=[{id:"monitor.checks.list",summary:"List staff checks with their schedule, action and last run",permission:"ops:investigations:read",effect:"read",input:z22.object({}),request:__name(()=>({method:"GET",path:"/monitor/checks"}),"request")},{id:"monitor.checks.try",summary:"Run one code check over a window, read-only, and show what it would open; nothing is stored (Jev and external checks are refused)",permission:"ops:investigations:read",effect:"read",input:z22.object({check:z22.string().trim().min(1).max(160).describe("Check id, e.g. agents/tools/errors/tool-failure-rate"),since:opsArgs.since,until:opsArgs.until.optional()}),request:__name(input=>({method:"POST",path:"/monitor/checks/try",body:compact({checkId:input.check,since:time2(input.since),until:time2(input.until)})}),"request")},{id:"monitor.cases.list",summary:"List cases opened by staff checks, newest activity first",permission:"ops:investigations:read",effect:"read",input:z22.object({state:OpsSignalCaseStateSchema.optional().describe("Only cases in this state"),check:z22.string().trim().min(1).max(160).optional().describe("Only cases from this check id, or from every check under a prefix ending in /"),minSeverity:z22.enum(MONITORING_SEVERITIES).optional().describe("Only cases at least this severe: critical, high, medium or low"),hash:OpsSignatureHashSchema.optional().describe("Only cases about this error signature hash: in the fingerprint or the evidence of the last 7 days"),limit:opsArgs.limit.max(200).default(50)}),request:__name(input=>({method:"POST",path:"/monitor/cases",body:compact({state:input.state,checkId:input.check,minSeverity:input.minSeverity,signatureHash:input.hash,limit:input.limit})}),"request")},{id:"monitor.signature.get",summary:"Resolve an error signature hash from case evidence to its tool, normalized error text, reach and example chats (window up to 7d)",permission:"ops:project:chat:read",effect:"read",input:z22.object({hash:OpsSignatureHashSchema.describe("Signature hash, e.g. from a case evidence signatureHash or topSignatures"),since:opsArgs.since.default("24h"),until:opsArgs.until.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/monitor/signatures",body:compact({hash:input.hash,since:time2(input.since),until:time2(input.until),reason:input.reason})}),"request")},{id:"monitor.cases.get",summary:"Read one case with its latest observations (ids and numbers only)",permission:"ops:investigations:read",effect:"read",input:z22.object({case:z22.uuid().describe("Case id")}),request:__name(input=>({method:"GET",path:`/monitor/cases/${seg(input.case)}`}),"request")},{id:"monitor.cases.update",summary:"Decide on a case: accept with a ceiling, snooze until a date, dismiss, resolve, or reopen",permission:"ops:investigations:write",effect:"write",risk:"low",input:z22.object({case:z22.uuid().describe("Case id"),state:OpsSignalCaseStateSchema.optional(),decisionReason:z22.string().trim().min(1).max(2e3).optional().describe("Why this decision; required to accept, snooze or dismiss. Shown on the finding"),ceiling:z22.number().nonnegative().optional().describe("For accepted: reopen above this metric"),snoozedUntil:z22.iso.datetime().optional().describe("For snoozed: reopen after this time"),linearIssue:z22.string().trim().regex(/^[A-Z]+-\d+$/).optional(),prUrl:z22.url().optional()})}]}});import{z as z23}from"zod";var channel,draft,notifyCommands,init_notify=__esm({"../../packages/api-contracts/dist/esm/ops/commands/notify.js"(){"use strict";init_ops();init_args();init_types();init_shared();channel=z23.enum(["email","pylon"]).describe("email (Resend, to the project owner) or pylon (ticket reply)"),draft=z23.uuid().describe("Draft id"),notifyCommands=[{id:"notify.draft",summary:"Draft a customer-visible message: an email to a project owner or a reply on a Pylon ticket",permission:"ops:notification:preview",effect:"write",risk:"low",input:z23.object({channel,message:z23.string().trim().min(1).max(5e3),project:opsArgs.project.optional().describe("email: the project whose owner receives it"),recipient:z23.email().optional().describe("email: override the recipient"),subject:z23.string().trim().min(1).max(200).optional().describe("email: subject line"),locale:z23.string().trim().min(2).max(20).optional().describe("email: message locale, e.g. en"),issue:OpsPylonIssueIdSchema.optional().describe("pylon: ticket id"),replyTo:z23.string().trim().min(1).max(255).optional().describe("pylon: top-level message id to reply to"),toEmails:z23.array(z23.email()).max(50).optional().describe("pylon: email recipients"),ccEmails:z23.array(z23.email()).max(50).optional(),bccEmails:z23.array(z23.email()).max(50).optional()}),cli:{fileArgs:["message"]}},{id:"notify.show",summary:"Show a drafted customer message and its approval state",permission:"ops:notification:preview",effect:"read",input:z23.object({channel,draft}),request:__name(input=>({method:"GET",path:input.channel==="pylon"?`/support/pylon/replies/${seg(input.draft)}`:`/notifications/${seg(input.draft)}`}),"request")},{id:"notify.approve",summary:"Approve a drafted customer message (a person must approve before it can be sent)",permission:"ops:notification:approve",effect:"write",risk:"low",humanOnly:!0,input:z23.object({channel,draft})},{id:"notify.send",summary:"Send an approved customer message",permission:"ops:notification:send",effect:"write",risk:"high",input:z23.object({channel,draft})}]}});function normalizeSentryIssueReference(reference){let trimmed=reference.trim();if(SENTRY_ISSUE_ID_PATTERN.test(trimmed))return trimmed;let url;try{url=new URL(trimmed)}catch{throw new Error("Expected a Sentry issue id or /issues/<id>/ URL")}let segments=url.pathname.split("/").filter(Boolean),issuesIndex=segments.lastIndexOf("issues"),issueId=issuesIndex>=0&&issuesIndex===segments.length-2?segments[issuesIndex+1]:void 0;if(!issueId||!SENTRY_ISSUE_ID_PATTERN.test(issueId))throw new Error("Expected a Sentry issue id or /issues/<id>/ URL");return issueId}function collectTraceIds(value,candidates,depth=0){if(!(depth>32)){if(typeof value=="string"){TRACE_ID_PATTERN.test(value.trim())&&candidates.add(value.trim().toLowerCase());return}if(Array.isArray(value)){for(let item of value)collectTraceIds(item,candidates,depth+1);return}if(typeof value=="object"&&value!==null)for(let item of Object.values(value))collectTraceIds(item,candidates,depth+1)}}function normalizeTempoTraceReference(reference){let trimmed=reference.trim();if(TRACE_ID_PATTERN.test(trimmed))return trimmed.toLowerCase();let url;try{url=new URL(trimmed)}catch{throw new Error("Expected an exact 32-character trace id or a Grafana trace URL")}let candidates=new Set;for(let segment of url.pathname.split("/"))collectTraceIds(segment,candidates);for(let value of url.searchParams.values()){collectTraceIds(value,candidates);try{collectTraceIds(JSON.parse(value),candidates)}catch{continue}}if(candidates.size!==1)throw new Error(candidates.size===0?"Grafana URL did not contain a trace id":"Grafana URL contained multiple trace ids");return[...candidates][0]}var SENTRY_ISSUE_ID_PATTERN,TRACE_ID_PATTERN,init_references2=__esm({"../../packages/api-contracts/dist/esm/ops/references.js"(){"use strict";SENTRY_ISSUE_ID_PATTERN=/^[a-zA-Z0-9-]{1,100}$/,TRACE_ID_PATTERN=/^[a-fA-F0-9]{32}$/;__name(normalizeSentryIssueReference,"normalizeSentryIssueReference");__name(collectTraceIds,"collectTraceIds");__name(normalizeTempoTraceReference,"normalizeTempoTraceReference")}});import{z as z24}from"zod";function parseWhere(values){if(!(!values||values.length===0))return Object.fromEntries(values.map(value=>{let separator=value.indexOf("=");if(separator<1)throw new Error("--where expects key=value");return[value.slice(0,separator),value.slice(separator+1)]}))}var issue,logFilters,observeCommands,init_observe=__esm({"../../packages/api-contracts/dist/esm/ops/commands/observe.js"(){"use strict";init_args();init_references2();init_types();init_shared();issue=z24.string().trim().min(1).max(500).describe("Sentry issue id or issue URL");__name(parseWhere,"parseWhere");logFilters={project:opsArgs.project,where:z24.array(z24.string().min(3).max(500)).optional().describe("Structured field filter key=value; repeatable"),contains:z24.string().min(1).max(500).optional().describe("Plain-text line filter"),limit:opsArgs.limit.max(1e3).default(100),reason:opsArgs.reason,output:opsArgs.output.optional()},observeCommands=[{id:"observe.logs.query",summary:"Query a project's production logs in a time window",permission:"ops:logs:read",effect:"read",input:z24.object({...logFilters,since:opsArgs.since,until:opsArgs.until.optional()}),request:__name(input=>({method:"POST",path:"/logs/query",body:compact({projectId:input.project,from:time2(input.since),to:time2(input.until)??new Date().toISOString(),limit:input.limit,contains:input.contains,where:parseWhere(input.where),reason:input.reason})}),"request")},{id:"observe.logs.around",summary:"Read a project's production logs a few minutes either side of a moment",permission:"ops:logs:read",effect:"read",input:z24.object({...logFilters,at:z24.iso.datetime({offset:!0}).describe("The moment to center on"),minutes:z24.coerce.number().int().min(1).max(120).default(5).describe("Minutes before and after")}),request:__name(input=>{let at2=Date.parse(input.at);return{method:"POST",path:"/logs/query",body:compact({projectId:input.project,from:new Date(at2-input.minutes*6e4).toISOString(),to:new Date(at2+input.minutes*6e4).toISOString(),limit:input.limit,contains:input.contains,where:parseWhere(input.where),reason:input.reason})}},"request")},{id:"observe.traces.get",summary:"Read one Grafana Tempo trace (id or Grafana URL) for a project",permission:"ops:traces:read",effect:"read",input:z24.object({trace:z24.string().trim().min(1).max(4e3).describe("32-character trace id or Grafana trace URL"),project:opsArgs.project,since:opsArgs.since,until:opsArgs.until.optional(),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/traces/${normalizeTempoTraceReference(input.trace)}`,body:{projectId:input.project,from:resolveOpsTime(input.since),to:time2(input.until)??new Date().toISOString(),reason:input.reason}}),"request")},{id:"observe.sentry.issues",summary:"Search Sentry issues, for one project or every project",permission:"ops:sentry:read",effect:"read",input:z24.object({project:opsArgs.project.optional(),search:z24.string().trim().min(1).max(500).optional().describe('Sentry search, e.g. "is:unresolved"'),period:z24.enum(["1h","24h","7d","14d","30d","90d"]).optional().describe("Stats period (default 14d)"),sort:z24.enum(["date","new","freq","user","trends"]).optional(),limit:opsArgs.limit.max(100).optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/sentry/issues",body:compact({projectId:input.project,query:input.search,statsPeriod:input.period,sort:input.sort,limit:input.limit,reason:input.reason})}),"request")},{id:"observe.sentry.issue",summary:"Read one Sentry issue",permission:"ops:sentry:read",effect:"read",input:z24.object({issue,reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/sentry/issues/${seg(normalizeSentryIssueReference(input.issue))}`,body:{reason:input.reason}}),"request")},{id:"observe.sentry.event",summary:"Read one full Sentry event",permission:"ops:sentry:read",effect:"read",input:z24.object({event:z24.string().trim().min(1).max(100).describe("Sentry event id"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/sentry/events/${seg(input.event)}`,body:{reason:input.reason}}),"request")},{id:"observe.sentry.latest-event",summary:"Read the latest full event of a Sentry issue",permission:"ops:sentry:read",effect:"read",input:z24.object({issue,reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/sentry/issues/${seg(normalizeSentryIssueReference(input.issue))}/events/latest`,body:{reason:input.reason}}),"request")},{id:"observe.sentry.resolve",summary:"Mark a Sentry issue resolved",permission:"ops:sentry:write",effect:"write",risk:"low",input:z24.object({issue})},{id:"observe.posthog.milestones",summary:"Count a project's PostHog lifecycle milestones (create, deploy, first publish) in a window",permission:"ops:posthog:read",effect:"read",input:z24.object({project:opsArgs.project,since:opsArgs.since,until:opsArgs.until.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/posthog/milestones",body:{projectId:input.project,from:resolveOpsTime(input.since),to:time2(input.until)??new Date().toISOString(),reason:input.reason}}),"request")}]}});import{z as z25}from"zod";var orgCommands,init_org=__esm({"../../packages/api-contracts/dist/esm/ops/commands/org.js"(){"use strict";init_organization_features_dto();init_args();init_types();init_shared();orgCommands=[{id:"org.get",summary:"Show an organization: plan, members, projects and subscription summary",permission:"ops:organizations:read",effect:"read",input:z25.object({org:opsArgs.org,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/organizations/${seg(input.org)}`,query:{reason:input.reason}}),"request")},{id:"org.features.list",summary:"List an organization's features and any staff overrides",permission:"ops:customers:read",effect:"read",input:z25.object({org:opsArgs.org}),request:__name(input=>({method:"GET",path:`/organizations/${seg(input.org)}/features`}),"request")},{id:"org.features.set",summary:"Force an organization feature on or off, or clear the override",permission:"ops:organization:features:write",effect:"write",risk:"low",humanOnly:!0,input:z25.object({org:opsArgs.org,feature:z25.enum(ORGANIZATION_FEATURES).describe("Feature name"),state:z25.enum(["on","off","default"]).describe("on, off, or default to clear the override")})},{id:"org.takedown",summary:"Take every project of an organization off Fimo domains and block publishing",permission:"ops:organizations:write",effect:"write",risk:"high",humanOnly:!0,input:z25.object({org:opsArgs.org})},{id:"org.restore",summary:"Lift an organization takedown",permission:"ops:organizations:write",effect:"write",risk:"high",humanOnly:!0,input:z25.object({org:opsArgs.org})},{id:"org.delete",summary:"Delete an organization and everything it owns permanently",permission:"ops:organizations:write",effect:"write",risk:"high",humanOnly:!0,input:z25.object({org:opsArgs.org})},{id:"org.credits.topup",summary:"Grant credits to an organization, free or as a recorded purchase",permission:"ops:credits:write",effect:"write",risk:"high",humanOnly:!0,input:z25.object({org:opsArgs.org,credits:z25.coerce.number().int().positive().describe("Number of credits"),type:z25.enum(["free","purchase"]).default("free"),amountCents:z25.coerce.number().int().positive().optional().describe("Amount paid, required for a purchase"),expiresAt:z25.iso.datetime({offset:!0}).optional().describe("When the credits expire"),message:z25.string().trim().optional().describe("Note shown with the grant")})},{id:"org.credits.burn-zombies",summary:"Burn credits held by abandoned (zombie) holds of one organization since a date",permission:"ops:credits:write",effect:"write",risk:"high",humanOnly:!0,input:z25.object({org:opsArgs.org,since:opsArgs.since})}]}});import{z as z26}from"zod";var OPS_PLATFORM_DASHBOARDS,platformCommands,init_platform=__esm({"../../packages/api-contracts/dist/esm/ops/commands/platform.js"(){"use strict";init_args();init_types();init_shared();OPS_PLATFORM_DASHBOARDS=["agents","money","projects","automation","growth","platform","usage","stats"],platformCommands=[{id:"platform.metrics",summary:"Read an admin dashboard as data: agents, money, projects, automation, growth, platform, usage or stats",permission:"ops:platform:read",effect:"read",input:z26.object({dashboard:z26.enum(OPS_PLATFORM_DASHBOARDS),since:opsArgs.since.default("7d"),until:opsArgs.until.optional()}),request:__name(input=>({method:"GET",path:"/platform/metrics",query:compact({dashboard:input.dashboard,since:time2(input.since),until:time2(input.until)})}),"request")},{id:"platform.pool.status",summary:"Show the warm sandbox pool: size, target, and projects waiting in it",permission:"ops:platform:read",effect:"read",input:z26.object({}),request:__name(()=>({method:"GET",path:"/platform/pool"}),"request")},{id:"platform.pool.refill",summary:"Top the warm sandbox pool up to its target size",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z26.object({})},{id:"platform.pool.flush",summary:"Delete warm sandboxes from the pool, all of them or only the listed ones (new projects start cold until it refills)",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z26.object({pooled:z26.array(z26.uuid()).min(1).max(500).optional().describe("Only these pooled project ids; omit to flush all")})},{id:"platform.maintenance.status",summary:"Show whether maintenance mode is on and its message",permission:"ops:platform:read",effect:"read",input:z26.object({}),request:__name(()=>({method:"GET",path:"/platform/maintenance"}),"request")},{id:"platform.maintenance.enable",summary:"Turn maintenance mode on: Studio shows the message and refuses work",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z26.object({message:z26.string().max(500).optional().describe("Message shown to users")})},{id:"platform.maintenance.disable",summary:"Turn maintenance mode off",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z26.object({})},{id:"platform.maintenance.message",summary:"Change the maintenance message without toggling maintenance mode",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z26.object({message:z26.string().max(500).describe("Message shown to users")})},{id:"platform.sync-all",summary:"Re-sync every project's database records from its repository",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z26.object({})},{id:"platform.sync-tenant-schemas",summary:"Apply pending tenant schema migrations to every project database",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z26.object({})},{id:"platform.integrations.replay",summary:"Replay one failed inbound integration event",permission:"ops:platform:write",effect:"write",risk:"low",input:z26.object({event:z26.string().trim().min(1).max(255).describe("Inbound event id")})},{id:"platform.onboardings.list",summary:"List site onboardings (start from an existing website) with their status",permission:"ops:platform:read",effect:"read",input:z26.object({status:z26.string().trim().min(1).max(64).optional(),since:opsArgs.since.optional(),limit:opsArgs.limit.max(200).default(50),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/platform/onboardings",query:compact({status:input.status,since:time2(input.since),limit:input.limit,cursor:input.cursor})}),"request")},{id:"platform.onboardings.get",summary:"Show one project's site onboarding: questions, answers, refusal and timeline",permission:"ops:platform:read",effect:"read",input:z26.object({project:opsArgs.project,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/platform/onboardings/${seg(input.project)}`,query:{reason:input.reason}}),"request")},{id:"platform.onboardings.lift-refusal",summary:"Lift a site onboarding's Terms refusal so the project can continue",permission:"ops:platform:write",effect:"write",risk:"low",input:z26.object({project:opsArgs.project})},{id:"platform.unclaimed.list",summary:"List unclaimed projects (created without an account) and their claim state",permission:"ops:platform:read",effect:"read",input:z26.object({since:opsArgs.since.optional(),limit:opsArgs.limit.max(200).default(50),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/platform/unclaimed",query:compact({since:time2(input.since),limit:input.limit,cursor:input.cursor})}),"request")},{id:"platform.resources.resolve",summary:"Resolve any id, URL, email or domain to the Fimo record it names",permission:"ops:platform:read",effect:"read",input:z26.object({query:z26.string().trim().min(1).max(512).describe("Id, URL, email or domain")}),request:__name(input=>({method:"GET",path:"/platform/resources/resolve",query:{q:input.query}}),"request"),cli:{positional:"query"}}]}});import{z as z27}from"zod";function files(project,action,env){return`/projects/${seg(project)}/files/${action}?projectEnv=${seg(env)}`}var envMain,projectCommands,init_project=__esm({"../../packages/api-contracts/dist/esm/ops/commands/project.js"(){"use strict";init_args();init_types();init_shared();envMain=opsArgs.env.default("main");__name(files,"files");projectCommands=[{id:"project.get",summary:"Inspect a project: owner, environments, domains, publications, recent runs and logs",permission:"ops:project:read",effect:"read",input:z27.object({project:opsArgs.project,env:envMain,since:opsArgs.since.default("24h"),limit:opsArgs.limit.max(500).default(100).describe("Maximum log entries")}),request:__name(input=>({method:"GET",path:`/projects/${seg(input.project)}/inspect`,query:{projectEnv:input.env,hours:Math.min(168,opsHoursSince(input.since)),logLimit:input.limit}}),"request")},{id:"project.list",summary:"List projects across organizations, newest first: search by name or organization, or find those at their database limit (database quota reached)",permission:"ops:project:read",effect:"read",input:z27.object({query:opsArgs.query.optional().describe("Project name, display name, id or organization name"),databaseQuota:z27.enum(["blocked","refused"]).optional().describe("blocked: the database refuses queries now because the plan's quota is used up; refused: refused at any time, recovered ones included"),since:opsArgs.since.optional().describe("Created since: ISO timestamp or relative (30m, 24h, 7d, 2w)"),limit:opsArgs.limit.max(100).default(50),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/projects",query:compact({search:input.query,databaseQuota:input.databaseQuota,since:time2(input.since),limit:input.limit,cursor:input.cursor})}),"request")},{id:"project.snapshot",summary:"Download a zip snapshot of a project's source and content",permission:"ops:project:snapshot",effect:"read",input:z27.object({project:opsArgs.project,reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/projects/${seg(input.project)}/snapshot`,body:{reason:input.reason}}),"request")},{id:"project.chat",summary:"Read a project's agent chat transcript (the most recently active chat unless --thread is set)",permission:"ops:project:chat:read",effect:"read",input:z27.object({project:opsArgs.project,thread:z27.uuid().optional().describe("One chat or routine run thread id"),env:opsArgs.env.optional().describe("Only turns that targeted this environment"),since:opsArgs.since.optional(),until:opsArgs.until.optional(),limit:opsArgs.limit.max(200).default(100),cursor:opsArgs.cursor.optional(),full:z27.boolean().default(!1).describe("Include tool inputs, outputs and other message parts"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/projects/${seg(input.project)}/chat/messages`,body:compact({projectEnv:input.env,threadId:input.thread,from:time2(input.since),to:time2(input.until),limit:input.limit,cursor:input.cursor,slim:!input.full,reason:input.reason})}),"request")},{id:"project.files.read",summary:"Read one source file from a project environment",permission:"ops:project:snapshot",effect:"read",input:z27.object({project:opsArgs.project,env:envMain,path:z27.string().trim().min(1).max(1024).describe("File path relative to the project root"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:files(input.project,"read",input.env),body:{path:input.path,reason:input.reason}}),"request")},{id:"project.files.glob",summary:"List source file paths in a project environment",permission:"ops:project:snapshot",effect:"read",input:z27.object({project:opsArgs.project,env:envMain,pattern:z27.string().min(1).max(300).optional().describe("Glob pattern, e.g. src/**/*.tsx"),limit:opsArgs.limit.max(2e3).default(2e3),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:files(input.project,"glob",input.env),body:compact({pattern:input.pattern,limit:input.limit,reason:input.reason})}),"request")},{id:"project.files.grep",summary:"Search source files in a project environment with a regular expression",permission:"ops:project:snapshot",effect:"read",input:z27.object({project:opsArgs.project,env:envMain,pattern:z27.string().min(1).max(200).describe("Regular expression"),include:z27.string().min(1).max(300).optional().describe("Only paths matching this glob"),caseInsensitive:z27.boolean().default(!1),limit:opsArgs.limit.max(200).default(100).describe("Maximum matches"),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:files(input.project,"grep",input.env),body:compact({pattern:input.pattern,include:input.include,caseInsensitive:input.caseInsensitive,maxMatches:input.limit,reason:input.reason})}),"request")},{id:"project.files.package-manager",summary:"Report which package manager a project declares and which lockfiles it has",permission:"ops:project:snapshot",effect:"read",input:z27.object({project:opsArgs.project,env:envMain,reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:files(input.project,"package-manager",input.env),body:{reason:input.reason}}),"request")},{id:"project.files.write",summary:"Create or replace one source file in a project environment (commits to its branch)",permission:"ops:project:operate",effect:"write",risk:"high",humanOnly:!0,input:z27.object({project:opsArgs.project,env:envMain,path:z27.string().trim().min(1).max(1024).describe("File path relative to the project root"),content:z27.string().max(256*1024).describe("The exact desired file contents"),overwrite:z27.boolean().default(!1).describe("Allow replacing an existing file")}),cli:{fileArgs:["content"]}},{id:"project.runtime.bump",summary:"Pin the project's fimo runtime packages to an exact version, install, and restart the dev server",permission:"ops:project:operate",effect:"write",risk:"high",humanOnly:!0,input:z27.object({project:opsArgs.project,env:envMain,version:z27.string().trim().min(1).max(64).describe("Exact target version, e.g. 0.11.0")})},{id:"project.preview.restart",summary:"Restart the project's preview dev server",permission:"ops:project:operate",effect:"write",risk:"low",humanOnly:!0,input:z27.object({project:opsArgs.project,env:envMain})},{id:"project.publish",summary:"Publish the customer's site on their behalf. Only when a Fimo admin explicitly asks for it; never on an agent's own initiative",permission:"ops:project:publish",effect:"write",risk:"high",humanOnly:!0,consent:!0,input:z27.object({project:opsArgs.project,env:opsArgs.env.optional().describe("Source environment; defaults to the project's publish source")})},{id:"project.domain.refresh",summary:"Refresh a custom domain's provider and SSL state",permission:"ops:project:operate",effect:"write",risk:"low",humanOnly:!0,input:z27.object({project:opsArgs.project,domain:z27.uuid().describe("Project domain id")})},{id:"project.migrations.dry-run",summary:"Plan a source migration for one project without changing it",permission:"ops:project:read",effect:"read",input:z27.object({project:opsArgs.project,env:envMain,migration:z27.string().trim().min(1).max(120).optional().describe("Migration id (default: the current one)"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/migrations/projects/${seg(input.project)}/dry-run`,body:compact({migrationId:input.migration,projectEnv:input.env,reason:input.reason})}),"request")},{id:"project.sync",summary:"Re-sync a project's database records from its repository",permission:"ops:project:operate",effect:"write",risk:"low",input:z27.object({project:opsArgs.project})},{id:"project.thumbnail.regenerate",summary:"Regenerate a project's dashboard thumbnail",permission:"ops:project:operate",effect:"write",risk:"low",input:z27.object({project:opsArgs.project,type:z27.enum(["dev","published"]).default("dev").describe("dev (the preview) or published (the live site)")})},{id:"project.version.restore",summary:"Restore a project environment to an earlier version (overwrites the current state)",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z27.object({project:opsArgs.project,env:envMain,version:z27.string().trim().min(1).max(255).describe("Version id to restore")})},{id:"project.takedown",summary:"Take a project off Fimo domains and block it from publishing",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z27.object({project:opsArgs.project})},{id:"project.restore",summary:"Lift a project takedown so it can serve and publish again",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z27.object({project:opsArgs.project})},{id:"project.transfer",summary:"Move a project to another organization",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z27.object({project:opsArgs.project,toOrg:opsArgs.org.describe("Destination organization id")})},{id:"project.delete",summary:"Delete a project and its resources permanently",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z27.object({project:opsArgs.project})}]}});import{z as z28}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=z28.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z28.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z28.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z28.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z28.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z28.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z28.enum(["user","agent","system"]),SupportReportTagSchema=z28.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z28.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z28.object({organization:z28.object({id:z28.string().trim().min(1).max(255),name:z28.string().trim().max(240).optional()}),project:z28.object({id:z28.uuid(),name:z28.string().trim().max(240).optional(),createdAt:z28.coerce.date().optional()}).optional(),environment:z28.string().trim().max(255).optional(),clientVersion:z28.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z28.object({message:z28.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("cli"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z28.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z28.string().trim().max(200).optional(),limit:z28.coerce.number().int().min(1).max(100).default(50),offset:z28.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z28.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z28.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z28.uuid().nullable().optional(),note:z28.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=z28.object({message:z28.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z28.object({kind:SupportReportLinkKindSchema,label:z28.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z28.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z28.object({kind:SupportReportActorKindSchema,id:z28.string().nullable(),name:z28.string().nullable()}),SupportReportLinkDTOSchema=z28.object({id:z28.uuid(),kind:SupportReportLinkKindSchema,label:z28.string(),url:SupportReportHttpUrlSchema,externalId:z28.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z28.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z28.object({id:z28.uuid(),kind:SupportReportEventKindSchema,body:z28.string().nullable(),metadata:z28.record(z28.string(),z28.unknown()),actor:SupportReportActorDTOSchema,createdAt:z28.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z28.object({id:z28.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z28.array(z28.string()),source:SupportReportSourceSchema,message:z28.string(),reporter:z28.object({id:z28.string().nullable(),name:z28.string().nullable(),email:z28.string().nullable()}),organization:z28.object({id:z28.string().nullable(),name:z28.string()}),project:z28.object({id:z28.uuid().nullable(),name:z28.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z28.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z28.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z28.string().nullable(),deliveredAt:z28.coerce.date().nullable()}).nullable(),duplicateOfReportId:z28.uuid().nullable(),resolvedAt:z28.coerce.date().nullable(),createdAt:z28.coerce.date(),updatedAt:z28.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z28.string().nullable(),clientVersion:z28.string().nullable(),links:z28.array(SupportReportLinkDTOSchema),events:z28.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z28.object({reports:z28.array(SupportReportSummaryDTOSchema),total:z28.number().int().nonnegative(),statusCounts:z28.object({new:z28.number().int().nonnegative(),in_progress:z28.number().int().nonnegative(),waiting:z28.number().int().nonnegative(),resolved:z28.number().int().nonnegative(),duplicate:z28.number().int().nonnegative(),irrelevant:z28.number().int().nonnegative(),ignored:z28.number().int().nonnegative()}),limit:z28.number().int().positive(),offset:z28.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z28.object({id:z28.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z28.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z29}from"zod";var report,pylonIssue,supportCommands,init_support=__esm({"../../packages/api-contracts/dist/esm/ops/commands/support.js"(){"use strict";init_support_report_dto();init_ops();init_args();init_types();init_shared();report=z29.uuid().describe("Support report id"),pylonIssue=OpsPylonIssueIdSchema.describe("Pylon issue id"),supportCommands=[{id:"support.reports.list",summary:"List Fimo support reports, newest first",permission:"ops:support:read",effect:"read",input:z29.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:z29.string().trim().min(1).max(50).optional(),search:z29.string().trim().min(1).max(200).optional().describe("Text search over the report"),limit:opsArgs.limit.max(200).default(50),offset:z29.coerce.number().int().min(0).default(0),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"GET",path:"/support/reports",query:compact({reason:input.reason,status:input.status,category:input.category,source:input.source,tag:input.tag,query:input.search,limit:input.limit,offset:input.offset})}),"request")},{id:"support.reports.get",summary:"Read one support report with its messages, links and context",permission:"ops:support:read",effect:"read",input:z29.object({report,reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"GET",path:`/support/reports/${seg(input.report)}`,query:{reason:input.reason}}),"request")},{id:"support.reports.claim",summary:"Claim a support report (mark it in progress), optionally with a note",permission:"ops:support:write",effect:"write",risk:"low",input:z29.object({report,note:z29.string().trim().min(1).max(2e4).optional()}),cli:{fileArgs:["note"]}},{id:"support.reports.update",summary:"Change a support report's status, category, tags or duplicate link, optionally with a note",permission:"ops:support:write",effect:"write",risk:"low",input:z29.object({report,status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z29.array(z29.string().trim().min(1).max(50)).max(20).optional(),duplicateOf:z29.uuid().nullable().optional().describe("Report id this one duplicates; null clears it"),note:z29.string().trim().min(1).max(2e4).optional()}),cli:{fileArgs:["note"]}},{id:"support.reports.note",summary:"Add an internal message to a support report",permission:"ops:support:write",effect:"write",risk:"low",input:z29.object({report,message:z29.string().trim().min(1).max(2e4)}),cli:{fileArgs:["message"]}},{id:"support.reports.link",summary:"Link a support report to a Linear issue, Pylon ticket, project, Sentry issue or other URL",permission:"ops:support:write",effect:"write",risk:"low",input:z29.object({report,kind:SupportReportLinkKindSchema,label:z29.string().trim().min(1).max(240),url:z29.url({protocol:/^https?$/}).max(2e3),externalId:z29.string().trim().min(1).max(255).optional()})},{id:"support.reports.unlink",summary:"Remove a link from a support report",permission:"ops:support:write",effect:"write",risk:"low",input:z29.object({report,link:z29.uuid().describe("Link id")})},{id:"support.intake",summary:"Show the support intake receipt: reports received and delivered in a window (max 7 days)",permission:"ops:support:read",effect:"read",input:z29.object({since:opsArgs.since,until:opsArgs.until.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/support/intake/status",query:{since:time2(input.since),until:time2(input.until)??new Date().toISOString(),reason:input.reason}}),"request")},{id:"support.pylon.list",summary:"List Pylon support tickets in a window (max 7 days)",permission:"ops:support:read",effect:"read",input:z29.object({since:opsArgs.since,until:opsArgs.until.optional(),state:z29.enum(["open","closed","all"]).default("open"),limit:opsArgs.limit.max(100).default(50),cursor:opsArgs.cursor.optional(),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"GET",path:"/support/pylon/issues",query:compact({since:time2(input.since),until:time2(input.until)??new Date().toISOString(),state:input.state,limit:input.limit,cursor:input.cursor,reason:input.reason})}),"request")},{id:"support.pylon.thread",summary:"Read the full message thread of a Pylon ticket",permission:"ops:support:read",effect:"read",input:z29.object({issue:pylonIssue,reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/support/issues/${seg(input.issue)}/thread`,body:{reason:input.reason}}),"request")},{id:"support.pylon.resolve",summary:"Close a Pylon ticket",permission:"ops:support:write",effect:"write",risk:"low",input:z29.object({issue:pylonIssue})},{id:"support.pylon.note",summary:"Add an internal note to a Pylon ticket (not visible to the customer)",permission:"ops:support:write",effect:"write",risk:"low",input:z29.object({issue:pylonIssue,message:z29.string().trim().min(1).max(5e3)}),cli:{fileArgs:["message"]}}]}});import{z as z30}from"zod";var userCommands,init_user=__esm({"../../packages/api-contracts/dist/esm/ops/commands/user.js"(){"use strict";init_args();init_types();init_shared();userCommands=[{id:"user.get",summary:"Show a user: profile, role, organizations, recent sessions and usage",permission:"ops:users:read",effect:"read",input:z30.object({user:opsArgs.user,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/users/${seg(input.user)}`,query:{reason:input.reason}}),"request")},{id:"user.sessions",summary:"List sign-in sessions, for one user or across the platform",permission:"ops:users:read",effect:"read",input:z30.object({user:opsArgs.user.optional(),active:z30.boolean().optional().describe("Only sessions that have not expired or been revoked"),limit:opsArgs.limit.max(200).default(50),cursor:opsArgs.cursor.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/sessions",query:compact({userId:input.user,active:input.active,limit:input.limit,cursor:input.cursor,reason:input.reason})}),"request")},{id:"user.session.revoke",summary:"Revoke one sign-in session",permission:"ops:users:write",effect:"write",risk:"low",humanOnly:!0,input:z30.object({session:z30.string().trim().min(1).max(255).describe("Session id")})}]}});import{z as z31}from"zod";var evidence,versions,detectionQueries,watchCommands,init_watch=__esm({"../../packages/api-contracts/dist/esm/ops/commands/watch.js"(){"use strict";init_ops();init_args();init_types();init_shared();evidence=z31.array(z31.record(z31.string(),z31.unknown())).max(100),versions=z31.array(z31.string().trim().min(1).max(120)).max(100),detectionQueries=z31.array(z31.string().trim().min(1).max(2e3)).max(50),watchCommands=[{id:"watch.list",summary:"List watched projects and why each is watched",permission:"ops:customers:read",effect:"read",input:z31.object({}),request:__name(()=>({method:"GET",path:"/customers"}),"request")},{id:"watch.add",summary:"Watch a project (or update why it is watched)",permission:"ops:customers:write",effect:"write",risk:"low",input:z31.object({project:opsArgs.project,importance:z31.string().trim().min(1).max(1e3).describe("Why this project is operationally important"),owner:opsArgs.user.optional().describe("Owner user id"),framework:z31.string().trim().max(120).optional(),packageManager:z31.enum(["npm","pnpm","yarn","bun"]).optional(),notes:z31.string().trim().max(5e3).optional()})},{id:"watch.remove",summary:"Stop watching a project",permission:"ops:customers:write",effect:"write",risk:"low",input:z31.object({project:opsArgs.project})},{id:"watch.validations.list",summary:"List validation runs recorded for a watched project",permission:"ops:validations:read",effect:"read",input:z31.object({project:opsArgs.project}),request:__name(input=>({method:"GET",path:`/customers/${seg(input.project)}/validations`}),"request")},{id:"watch.validations.record",summary:"Record the outcome of validating a release, migration or change against a watched project",permission:"ops:validations:write",effect:"write",risk:"low",input:z31.object({project:opsArgs.project,change:z31.string().trim().min(1).max(500).describe("Release, migration or change that was validated"),outcome:OpsValidationOutcomeSchema,summary:z31.string().trim().min(1).max(1e4),evidence:evidence.default([])}),cli:{fileArgs:["evidence"]}},{id:"watch.investigations.list",summary:"List open and recent investigations",permission:"ops:investigations:read",effect:"read",input:z31.object({}),request:__name(()=>({method:"GET",path:"/investigations"}),"request")},{id:"watch.investigations.create",summary:"Open an investigation into a problem on a project",permission:"ops:investigations:write",effect:"write",risk:"low",input:z31.object({project:opsArgs.project,title:z31.string().trim().min(1).max(240),userReport:z31.string().trim().max(1e4).optional().describe("The customer's own words")})},{id:"watch.investigations.update",summary:"Update an investigation's status, hypothesis, outcome or evidence",permission:"ops:investigations:write",effect:"write",risk:"low",input:z31.object({investigation:z31.uuid().describe("Investigation id"),status:OpsInvestigationStatusSchema.optional(),hypothesis:z31.string().trim().max(1e4).optional(),outcome:z31.string().trim().max(1e4).optional(),evidence:evidence.optional()}),cli:{fileArgs:["evidence"]}},{id:"watch.known-issues.list",summary:"List known issues and their detection queries",permission:"ops:known-issues:read",effect:"read",input:z31.object({}),request:__name(()=>({method:"GET",path:"/known-issues"}),"request")},{id:"watch.known-issues.create",summary:"Record a known issue with how to detect it and any workaround",permission:"ops:known-issues:write",effect:"write",risk:"low",input:z31.object({fingerprint:z31.string().trim().min(1).max(240),title:z31.string().trim().min(1).max(240),description:z31.string().trim().min(1).max(1e4),affectedVersions:versions.default([]),detectionQueries:detectionQueries.default([]),fixedVersion:z31.string().trim().min(1).max(64).optional(),workaround:z31.string().trim().min(1).max(1e4).optional(),status:OpsKnownIssueStatusSchema.default("open")}),cli:{fileArgs:["detectionQueries"]}},{id:"watch.known-issues.update",summary:"Update a known issue",permission:"ops:known-issues:write",effect:"write",risk:"low",input:z31.object({knownIssue:z31.uuid().describe("Known issue id"),title:z31.string().trim().min(1).max(240).optional(),description:z31.string().trim().min(1).max(1e4).optional(),affectedVersions:versions.optional(),detectionQueries:detectionQueries.optional(),fixedVersion:z31.string().trim().min(1).max(64).optional(),workaround:z31.string().trim().min(1).max(1e4).optional(),status:OpsKnownIssueStatusSchema.optional()}),cli:{fileArgs:["detectionQueries"]}}]}});var OPS_COMMANDS,BY_ID,OPS_OPERATION_IDS,init_commands=__esm({"../../packages/api-contracts/dist/esm/ops/commands/index.js"(){"use strict";init_agent();init_agent();init_assistant();init_billing();init_core();init_health();init_merge();init_monitor();init_monitor();init_notify();init_observe();init_org();init_platform();init_platform();init_project();init_support();init_user();init_watch();OPS_COMMANDS=[...coreCommands,...projectCommands,...orgCommands,...userCommands,...mergeCommands,...agentCommands,...healthCommands,...billingCommands,...platformCommands,...observeCommands,...supportCommands,...watchCommands,...monitorCommands,...notifyCommands,...assistantCommands],BY_ID=new Map(OPS_COMMANDS.map(command=>[command.id,command])),OPS_OPERATION_IDS=OPS_COMMANDS.filter(command=>command.effect==="write").map(command=>command.id)}});import{z as z32}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,AgentBlockSchema,ChatDisplayBlockSchema,TextBlockSchema,ChatFormStepIdSchema,CapabilityRequestSchema,CapabilitiesBlockSchema,ChatFormBodySchema,ChatFormStepSchema,CHAT_FORM_INTERNAL_NOTE_MAX,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=z32.object({kind:z32.literal("say"),label:z32.string().trim().min(1).max(40,"Button labels must be 40 characters or fewer."),description:z32.string().min(1).max(240).optional(),message:z32.string().trim().min(1,"Every say button needs the sentence the user is saying by clicking.").max(2e3),style:z32.enum(["primary","default","ghost"]).optional()}),BlockActionSchema=BlockSayActionSchema,BlockAppActionSchema=z32.discriminatedUnion("command",[z32.object({kind:z32.literal("app"),command:z32.literal("publish")}).strict(),z32.object({kind:z32.literal("app"),command:z32.literal("connect"),integrationKey:z32.string().trim().min(1).max(80)}).strict()]),BlockBaseSchema=z32.object({fallback:z32.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z32.string().min(1).max(80).optional()}),ChoicesBlockSchema=BlockBaseSchema.extend({type:z32.literal("choices"),text:z32.string().max(500).optional(),actions:z32.array(BlockActionSchema).min(2,"A choices block needs 2 to 4 buttons.").max(4,"A choices block needs 2 to 4 buttons.")}),TableRowTargetSchema=z32.discriminatedUnion("kind",[z32.object({kind:z32.literal("entry"),collection:z32.string().min(1).max(80),entryId:z32.string().min(1).max(120)}),z32.object({kind:z32.literal("asset"),assetId:z32.string().min(1).max(120)}),z32.object({kind:z32.literal("url"),url:z32.url({protocol:/^https$/}).max(2e3)}),z32.object({kind:z32.literal("routine"),routineId:z32.string().min(1).max(120)})]),TableBlockSchema=BlockBaseSchema.extend({type:z32.literal("table"),columns:z32.array(z32.object({label:z32.string().min(1).max(24)})).min(2).max(4),rows:z32.array(z32.object({cells:z32.array(z32.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:z32.literal("cards"),layout:z32.enum(["rail","stack"]).optional(),items:z32.array(z32.object({title:z32.string().min(1).max(60),subtitle:z32.string().min(1).max(120).optional(),imageUrl:z32.url({protocol:/^https$/}).max(2e3).optional(),action:BlockSayActionSchema.optional()})).min(2).max(6)}),EntryBlockSchema=BlockBaseSchema.extend({type:z32.literal("entry"),label:z32.string().min(1).max(80),collection:z32.string().min(1).max(80),entryId:z32.string().min(1).max(120),path:z32.string().min(1).max(120).optional()}),AssetsBlockSchema=BlockBaseSchema.extend({type:z32.literal("assets"),items:z32.array(z32.object({url:z32.url({protocol:/^https$/}).max(2e3),alt:z32.string().min(1).max(120),label:z32.string().min(1).max(60).optional()})).min(1).max(6)}),CalloutBlockSchema=BlockBaseSchema.extend({type:z32.literal("callout"),title:z32.string().min(1).max(80),text:z32.string().min(1).max(240),action:BlockAppActionSchema}).strict(),StatBlockSchema=BlockBaseSchema.extend({type:z32.literal("stat"),items:z32.array(z32.object({label:z32.string().min(1).max(24),value:z32.string().min(1).max(16),delta:z32.string().min(1).max(12).optional(),tone:z32.enum(["up","down","flat"]).optional()})).min(1).max(4)}),ChartBlockSchema=BlockBaseSchema.extend({type:z32.literal("chart"),unit:z32.string().min(1).max(12).optional(),points:z32.array(z32.object({label:z32.string().min(1).max(12),value:z32.number().finite().min(0).max(1e9)})).min(2).max(12)}),AgentBlockSchema=BlockBaseSchema.extend({type:z32.literal("agent"),agentId:z32.string().uuid(),view:z32.enum(["compact","full"]).optional()}),ChatDisplayBlockSchema=z32.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema]),TextBlockSchema=BlockBaseSchema.extend({type:z32.literal("text"),placeholder:z32.string().min(1).max(120).optional(),multiline:z32.boolean().optional()}).strict(),ChatFormStepIdSchema=z32.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/,"Step ids are lowercase letters, digits, hyphen, or underscore (max 40)."),CapabilityRequestSchema=z32.object({id:ChatFormStepIdSchema,token:z32.string().regex(/^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?$/,"Capability tokens are verb:noun[:qualifier]."),label:z32.string().trim().min(1).max(60),reason:z32.string().trim().min(1).max(240)}).strict(),CapabilitiesBlockSchema=BlockBaseSchema.extend({type:z32.literal("capabilities"),items:z32.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=z32.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,AssetsBlockSchema,TextBlockSchema,CapabilitiesBlockSchema]);__name(getChatFormOptionLabels,"getChatFormOptionLabels");ChatFormStepSchema=z32.object({id:ChatFormStepIdSchema.optional(),question:z32.string().min(1).max(500),header:z32.string().min(1).max(25),body:ChatFormBodySchema,multiSelect:z32.boolean().optional(),recommended:z32.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"})),CHAT_FORM_INTERNAL_NOTE_MAX=1e3,FormBlockSchema=BlockBaseSchema.extend({type:z32.literal("form"),steps:z32.array(ChatFormStepSchema).min(1).max(4),internalNote:z32.string().trim().min(1).max(CHAT_FORM_INTERNAL_NOTE_MAX).optional()}),ChatBlockSchema=z32.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,AgentBlockSchema,FormBlockSchema]),ChatBlockToolInputSchema=z32.object({block:ChatBlockSchema}),ChatFormAnswerItemSchema=z32.object({stepId:ChatFormStepIdSchema.optional(),header:z32.string().min(1).max(25),question:z32.string().min(1).max(500),answer:z32.string().min(1),selectedLabels:z32.array(z32.string().min(1).max(120)).max(8),freeText:z32.string(),skipped:z32.boolean()}),ChatFormAnswerMetadataSchema=z32.object({toolCallId:z32.string().max(255).optional(),shortTitle:z32.string().max(80).optional(),questions:z32.array(ChatFormAnswerItemSchema).max(4)}),QUESTION_FORM_CONTRACT_VERSION=1,QuestionFormSnapshotSchema=z32.object({version:z32.literal(QUESTION_FORM_CONTRACT_VERSION),block:FormBlockSchema}).strict(),QuestionFormAnswerSnapshotSchema=z32.object({version:z32.literal(QUESTION_FORM_CONTRACT_VERSION),answer:ChatFormAnswerMetadataSchema}).strict(),ChatFormResponseSchema=ChatFormAnswerMetadataSchema.extend({toolCallId:z32.string().min(1).max(255),partial:z32.boolean().optional()})}});import{z as z33}from"zod";var BLOCK_CLOSE_OUTCOMES,BlockUpdateResultSchema,BlockCloseResultSchema,init_chat_block_state=__esm({"../../packages/api-contracts/dist/esm/types/chat-block-state.js"(){"use strict";init_chat_block();BLOCK_CLOSE_OUTCOMES=["answered_in_chat","done","no_longer_needed"],BlockUpdateResultSchema=z33.object({rendered:z33.literal(!0),id:z33.string().min(1),block:ChatBlockSchema,reason:z33.string().optional()}),BlockCloseResultSchema=z33.object({closed:z33.literal(!0),ids:z33.array(z33.string().min(1)).min(1),outcome:z33.enum(BLOCK_CLOSE_OUTCOMES),reason:z33.string(),messageId:z33.string().optional()})}});import{z as z34}from"zod";var AdminTargetSchema,AdminToneSchema,AdminStatusSchema,AdminLinkSchema,AdminActionSchema,BlockBaseSchema2,AdminRecordBlockSchema,AdminCardsBlockSchema,AdminTableBlockSchema,AdminTimelineBlockSchema,AdminStatsBlockSchema,AdminExcerptBlockSchema,AdminMediaBlockSchema,AdminActionsBlockSchema,AdminHandoffBlockSchema,AdminChatBlockSchema,AdminChatBlockToolInputSchema,init_admin_chat_block=__esm({"../../packages/api-contracts/dist/esm/types/admin-chat-block.js"(){"use strict";init_chat_block();AdminTargetSchema=z34.union([z34.string().regex(/^\/(?!\/)[^\s]*$/,"Admin paths start with a single slash, e.g. /projects/<id>.").max(500),z34.url({protocol:/^https$/}).max(2e3)]),AdminToneSchema=z34.enum(["ok","warn","bad","neutral"]),AdminStatusSchema=z34.object({label:z34.string().trim().min(1).max(24),tone:AdminToneSchema}),AdminLinkSchema=z34.object({label:z34.string().trim().min(1).max(24),target:AdminTargetSchema}),AdminActionSchema=z34.discriminatedUnion("kind",[BlockSayActionSchema,z34.object({kind:z34.literal("open"),label:z34.string().trim().min(1).max(32),target:AdminTargetSchema}).strict(),z34.object({kind:z34.literal("op"),label:z34.string().trim().min(1).max(32),operation:z34.string().min(1).max(80),input:z34.record(z34.string(),z34.unknown())}).strict(),z34.object({kind:z34.literal("impersonate"),label:z34.string().trim().min(1).max(32),userId:z34.string().min(1).max(120)}).strict(),z34.object({kind:z34.literal("studio"),label:z34.string().trim().min(1).max(32),projectId:z34.string().min(1).max(120)}).strict()]),BlockBaseSchema2=z34.object({fallback:z34.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z34.string().min(1).max(80).optional()}),AdminRecordBlockSchema=BlockBaseSchema2.extend({type:z34.literal("record"),kind:z34.string().trim().min(1).max(24),name:z34.string().trim().min(1).max(80),id:z34.string().min(1).max(120).optional(),status:AdminStatusSchema.optional(),fields:z34.array(z34.object({label:z34.string().trim().min(1).max(24),value:z34.string().min(1).max(80)})).max(4,"A record shows at most 4 fields.").optional(),links:z34.array(AdminLinkSchema).max(2,"A record shows at most 2 links.").optional(),actions:z34.array(AdminActionSchema).max(3).optional()}),AdminCardsBlockSchema=BlockBaseSchema2.extend({type:z34.literal("cards"),items:z34.array(z34.object({name:z34.string().trim().min(1).max(60),subtitle:z34.string().min(1).max(80).optional(),status:AdminStatusSchema.optional(),imageUrl:z34.url({protocol:/^https$/}).max(2e3).optional(),target:AdminTargetSchema.optional()})).min(2).max(6)}),AdminTableBlockSchema=BlockBaseSchema2.extend({type:z34.literal("table"),columns:z34.array(z34.object({label:z34.string().min(1).max(24)})).min(2).max(3,"A table shows at most 3 columns."),rows:z34.array(z34.object({cells:z34.array(z34.string().max(80)).min(2).max(3),tone:AdminToneSchema.optional(),target:AdminTargetSchema.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.`})})}),AdminTimelineBlockSchema=BlockBaseSchema2.extend({type:z34.literal("timeline"),events:z34.array(z34.object({at:z34.string().trim().min(1).max(16),label:z34.string().trim().min(1).max(80),detail:z34.string().min(1).max(80).optional(),tone:AdminToneSchema,target:AdminTargetSchema.optional()})).min(2).max(6)}),AdminStatsBlockSchema=BlockBaseSchema2.extend({type:z34.literal("stats"),items:z34.array(z34.object({label:z34.string().min(1).max(24),value:z34.string().min(1).max(16),delta:z34.string().min(1).max(12).optional()})).min(1).max(4)}),AdminExcerptBlockSchema=BlockBaseSchema2.extend({type:z34.literal("excerpt"),source:z34.string().trim().min(1).max(60),link:AdminTargetSchema.optional(),content:z34.discriminatedUnion("kind",[z34.object({kind:z34.literal("lines"),lines:z34.array(z34.object({text:z34.string().max(200),highlight:z34.boolean().optional()})).min(1).max(5,"An excerpt shows at most 5 lines.")}),z34.object({kind:z34.literal("message"),author:z34.string().trim().min(1).max(60),at:z34.string().max(24).optional(),text:z34.string().trim().min(1).max(600)})])}),AdminMediaBlockSchema=BlockBaseSchema2.extend({type:z34.literal("media"),items:z34.array(z34.object({url:z34.url({protocol:/^https$/}).max(2e3),alt:z34.string().min(1).max(120),label:z34.string().min(1).max(60).optional()})).min(1).max(6)}),AdminActionsBlockSchema=BlockBaseSchema2.extend({type:z34.literal("actions"),actions:z34.array(AdminActionSchema).min(1).max(3)}),AdminHandoffBlockSchema=BlockBaseSchema2.extend({type:z34.literal("handoff"),prompt:z34.string().trim().min(1).max(4e3)}),AdminChatBlockSchema=z34.discriminatedUnion("type",[AdminRecordBlockSchema,AdminCardsBlockSchema,AdminTableBlockSchema,AdminTimelineBlockSchema,AdminStatsBlockSchema,ChartBlockSchema,AdminExcerptBlockSchema,AdminMediaBlockSchema,ChoicesBlockSchema,AdminActionsBlockSchema,FormBlockSchema,AdminHandoffBlockSchema]),AdminChatBlockToolInputSchema=z34.object({block:AdminChatBlockSchema})}});import{z as z35}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=z35.object({shape:z35.enum(CHAT_PORTRAIT_SHAPES),eyes:z35.enum(CHAT_PORTRAIT_EYES),mouth:z35.enum(CHAT_PORTRAIT_MOUTHS),color:z35.enum(CHAT_PORTRAIT_COLORS)})}});import{z as z36}from"zod";function isIanaTimezone(value){try{return new Intl.DateTimeFormat("en-US",{timeZone:value}),!0}catch{return!1}}var ChatRoutineCronSchema,ChatRoutineTimezoneSchema,ChatRoutineScheduleSchema,ChatRoutineNameSchema,ChatRoutineInstructionsSchema,ChatRoutineDescriptionSchema,ChatRoutineModelSchema,ChatRoutineWaitMinutesSchema,ChatRoutineEventTriggerDTOSchema,ChatRoutineEventTriggerInputSchema,ChatRoutineTriggersDTOSchema,ChatRoutineRunOutcomeSchema,ChatRoutineReportSchema,ChatRoutineDTOSchema,ChatRoutineListDTOSchema,AgentHoursUsageDTOSchema,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=z36.string().trim().max(64).regex(/^\S+(?: \S+){4}$/,"A schedule is a five-field cron expression");__name(isIanaTimezone,"isIanaTimezone");ChatRoutineTimezoneSchema=z36.string().trim().min(1).max(64).refine(isIanaTimezone,"Unknown timezone"),ChatRoutineScheduleSchema=z36.object({cron:ChatRoutineCronSchema,timezone:ChatRoutineTimezoneSchema}),ChatRoutineNameSchema=z36.string().trim().min(1).max(120),ChatRoutineInstructionsSchema=z36.string().trim().min(1).max(2e4),ChatRoutineDescriptionSchema=z36.string().trim().min(1).max(500),ChatRoutineModelSchema=z36.string().trim().min(1).max(120),ChatRoutineWaitMinutesSchema=z36.number().int().min(0).max(120),ChatRoutineEventTriggerDTOSchema=z36.object({text:z36.string(),title:z36.string(),explanation:z36.string(),watches:z36.array(z36.object({url:z36.string(),health:z36.enum(["ok","needs_repair","blocked","unstable"]),lastCheckedAt:z36.string().nullable()})).optional()}),ChatRoutineEventTriggerInputSchema=z36.object({text:z36.string().trim().min(1).max(500)}),ChatRoutineTriggersDTOSchema=z36.object({manual:z36.literal(!0),schedule:ChatRoutineScheduleSchema.nullable(),event:ChatRoutineEventTriggerDTOSchema.nullable()}),ChatRoutineRunOutcomeSchema=z36.enum(["quiet","reported","decision","incomplete","failed","running"]),ChatRoutineReportSchema=z36.object({message:z36.string().trim().min(1).max(2e4),decision:z36.boolean().optional(),incomplete:z36.boolean().optional(),remaining:z36.number().int().min(0).optional()}).refine(report2=>!(report2.decision===!0&&report2.incomplete===!0),{message:"A run that could not check asks for no decision: set incomplete or decision, not both."}).refine(report2=>!(report2.incomplete===!0&&(report2.remaining??0)>0),{message:"A run that could not check has nothing left to continue: set incomplete or remaining, not both."}),ChatRoutineDTOSchema=z36.object({id:z36.string().uuid(),threadId:z36.string().uuid(),runThreadId:z36.string().uuid(),name:z36.string(),description:z36.string().nullable(),instructions:z36.string(),template:z36.object({key:z36.string()}).nullable(),triggers:ChatRoutineTriggersDTOSchema,model:z36.string(),modelIsDefault:z36.boolean(),waitMinutes:ChatRoutineWaitMinutesSchema,paused:z36.boolean(),nextRunAt:z36.string().nullable(),lastRunAt:z36.string().nullable(),lastOutcome:ChatRoutineRunOutcomeSchema.nullable(),outOfAgentHoursUntil:z36.string().nullable(),createdAt:z36.string(),updatedAt:z36.string()}),ChatRoutineListDTOSchema=z36.object({routines:z36.array(ChatRoutineDTOSchema)}),AgentHoursUsageDTOSchema=z36.object({usedMs:z36.number().int().min(0),includedMs:z36.number().int().min(0),periodStart:z36.string(),periodEnd:z36.string(),stopsAtIncluded:z36.boolean(),canStart:z36.boolean(),canPayOverage:z36.boolean(),overageRateMicrosPerHour:z36.number().int().nullable(),billedMs:z36.number().int().min(0),billedMicros:z36.number().int().min(0)}),ChatRoutineCreateSchema=z36.object({name:ChatRoutineNameSchema,description:ChatRoutineDescriptionSchema.nullable().optional(),instructions:ChatRoutineInstructionsSchema,schedule:ChatRoutineScheduleSchema.nullable().optional(),event:ChatRoutineEventTriggerInputSchema.nullable().optional(),model:ChatRoutineModelSchema.nullable().optional(),waitMinutes:ChatRoutineWaitMinutesSchema.optional()}),ChatRoutineUpdateSchema=z36.object({name:ChatRoutineNameSchema,description:ChatRoutineDescriptionSchema.nullable(),instructions:ChatRoutineInstructionsSchema,schedule:ChatRoutineScheduleSchema.nullable(),event:ChatRoutineEventTriggerInputSchema.nullable(),model:ChatRoutineModelSchema.nullable(),waitMinutes:ChatRoutineWaitMinutesSchema,paused:z36.boolean()}).partial().refine(update=>Object.values(update).some(value=>value!==void 0),"Change at least one field"),ChatRoutineRefusalReasonSchema=z36.enum(["routine_cadence_too_frequent","routine_schedule_invalid","routine_owner_not_agent","routine_trigger_unsupported","routine_model_unknown","routine_needs_pro","routine_is_default"]),ChatRoutineRefusalDTOSchema=z36.object({message:z36.string(),reason:ChatRoutineRefusalReasonSchema}),ChatRoutineRunStatusSchema=z36.enum(["queued","running","finished","failed","cancelled"]),ChatRoutineRunTriggerSchema=z36.enum(["schedule","hand","event"]),ChatRoutineRunStartedBySchema=z36.object({kind:z36.enum(["person","agent"]),name:z36.string().nullable()}),ChatRoutineRunDTOSchema=z36.object({messageId:z36.string().uuid(),invocationId:z36.string().uuid().nullable(),startedAt:z36.string(),trigger:ChatRoutineRunTriggerSchema,startedBy:ChatRoutineRunStartedBySchema.nullable(),status:ChatRoutineRunStatusSchema,outcome:ChatRoutineRunOutcomeSchema.nullable(),summary:z36.string().nullable(),events:z36.number().int().min(1),durationMs:z36.number().int().min(0).nullable(),credits:z36.number().int().min(0).nullable()}),ChatRoutineRunListDTOSchema=z36.object({runs:z36.array(ChatRoutineRunDTOSchema)}),ChatRoutineRunRequestSchema=z36.object({message:z36.string().trim().min(1).max(2e4).optional()}),ChatRoutineRunOutcomeDTOSchema=z36.object({kind:z36.enum(["published","queued","replay","streaming","busy","refused"]),messageId:z36.string().uuid().nullable()})}});import{z as z37}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.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=z37.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z37.string(),displayName:z37.string().nullable(),subdomain:z37.string().nullable().optional(),subdomainUpdatedAt:z37.date().nullable().optional(),organizationId:z37.string().nullable(),createdBy:z37.string().nullable(),defaultBranch:BranchSchema.default(DEFAULT_BRANCH),productionSourceBranch:BranchSchema.default(DEFAULT_BRANCH),enabledChatModels:z37.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z37.string(),thumbnailUrl:z37.string().nullable(),publishedThumbnailUrl:z37.string().nullable(),category:z37.string().nullable(),snapshotUrl:z37.string().startsWith("/").optional(),appUrl:z37.string().nullable(),lastPublishedAt:z37.coerce.date(),databaseQuotaIncidentId:z37.uuid().nullable().optional(),databaseQuotaLastObservedAt:z37.coerce.date().nullable().optional()}),ProjectDTO=createDTO(ProjectDTOSchema),UpdateProjectSettingsRequestSchema=z37.object({name:z37.string().optional(),enabledChatModels:z37.array(ProjectChatManualModelIdSchema).optional(),productionSourceBranch:BranchSchema.optional(),syncConfig:z37.boolean().optional()}).strict(),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z37.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z37.object({id:z37.uuid(),name:z37.string(),displayName:z37.string().nullable(),thumbnailUrl:z37.string().nullable(),category:z37.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z37.object({id:z37.string(),name:z37.string(),avatar:z37.string().nullable(),color:z37.object({bg:z37.string(),text:z37.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z37.object({path:z37.string(),content:z37.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z37.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z37.object({id:z37.string(),messageId:z37.string(),versionId:z37.string().nullable(),role:ProjectChatMessageRole,parts:z37.array(z37.any()),createdAt:z37.coerce.date()}),MessageUserMetadataSchema=z37.object({id:z37.string(),name:z37.string().nullable().optional(),image:z37.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z37.number(),metadata:z37.object({user:MessageUserMetadataSchema,changeManifest:z37.array(z37.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z37.object({versionId:z37.uuid(),commitHash:z37.string(),name:z37.string(),description:z37.string().nullable(),kind:z37.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z37.object({versionCount:z37.number().int().nonnegative(),snapshotBytes:z37.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z37.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z37.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z37.object({content:z37.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z37.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z37.object({success:z37.boolean(),message:z37.string().optional(),warning:z37.string().optional(),durationMs:z37.number().int().nonnegative().optional()})),PublishUpgradeRequiredSchema=z37.object({code:z37.literal("PUBLISH_UPGRADE_REQUIRED"),message:z37.string(),currentVersion:z37.number().int().positive(),targetVersion:z37.literal(4)}),ProjectLatestPublicationAttemptSchema=z37.object({publicationId:z37.uuid(),status:z37.enum(["queued","building","published","failed","canceled"]),failureCode:z37.string().nullable(),sourceBranch:z37.string(),createdAt:CommonSchemas.timestamp,finishedAt:CommonSchemas.timestamp.nullable()}),ProjectPublicationStateDTOSchema=z37.object({isPublished:z37.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z37.string().nullable(),upgradeRequired:PublishUpgradeRequiredSchema.nullish(),hasActiveRelease:z37.boolean().optional(),latestAttempt:ProjectLatestPublicationAttemptSchema.nullish()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z37.object({label:z37.string().trim().min(1).max(120).optional(),notes:z37.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z37.object({success:z37.boolean(),message:z37.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z37.boolean(),publicationId:z37.string().optional(),url:z37.string().nullable().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z38}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatLiveTurnStateDTOSchema,ChatLiveTurnStateDTO,ChatMessageAuthorDTOSchema,ChatThreadMessageDTOSchema,ChatQueuedMessageDTOSchema,ChatAttentionDTOSchema,ChatThreadMessagesPageDTOSchema,ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema,ChatNonStreamingOutcomeDTOSchema,ProjectChatKindSchema,ProjectChatCreatableKindSchema,ProjectChatRoutinesDTOSchema,ProjectChatDescriptionSchema,ProjectChatInstructionsSchema,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_organization_features_dto();init_project_dto();ChatMessageListDTOSchema=z38.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z38.object({items:z38.array(ProjectMessagePublicDTOSchema),nextCursor:z38.string().nullable()}),ChatLiveTurnDTOSchema=z38.object({invocationId:z38.string(),step:z38.enum(["preparing","working","compacting","merging"]),startedAt:z38.string(),continuesInvocationId:z38.string().nullable().optional()}),ChatLiveTurnStateDTOSchema=z38.object({threadId:z38.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatMessageAuthorDTOSchema=z38.object({kind:z38.enum(["person","agent","routine","system"]),id:z38.string().nullable()}),ChatThreadMessageDTOSchema=z38.object({id:z38.string(),role:z38.enum(["user","assistant"]),parts:z38.array(z38.unknown()),metadata:z38.record(z38.string(),z38.unknown()).nullable(),versionId:z38.string().nullable().optional(),createdAt:z38.date().transform(value=>value.toISOString()),providerMessageId:z38.string().nullable().optional(),author:ChatMessageAuthorDTOSchema,invocationId:z38.string().nullable().optional(),invocationStatus:z38.string().nullable().optional(),invocationTerminalReason:z38.string().nullable().optional()}),ChatQueuedMessageDTOSchema=z38.object({id:z38.string(),parts:z38.array(z38.unknown()),metadata:z38.record(z38.string(),z38.unknown()).nullable(),providerMessageId:z38.string().nullable().optional(),author:ChatMessageAuthorDTOSchema,failed:z38.boolean(),queuedAt:z38.date().transform(value=>value.toISOString())}),ChatAttentionDTOSchema=z38.object({type:z38.literal("merge_conflict"),merge:z38.object({mergeId:z38.string().uuid(),projectId:z38.string(),fromBranch:z38.string(),toBranch:z38.string()}),publishAfterMerge:z38.boolean()}),ChatThreadMessagesPageDTOSchema=z38.object({threadId:z38.string().nullable(),title:z38.string().nullable(),messages:z38.array(ChatThreadMessageDTOSchema),nextCursor:z38.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional(),queue:z38.array(ChatQueuedMessageDTOSchema).optional(),queuePaused:z38.boolean().optional(),queueWaitUntil:z38.string().nullable().optional()}),ChatReplayOutcomeDTOSchema=z38.object({kind:z38.literal("replay"),threadId:z38.string(),userMessageId:z38.string()}),ChatQueuedOutcomeDTOSchema=z38.object({kind:z38.literal("queued"),threadId:z38.string(),userMessageId:z38.string(),blockingRootId:z38.string().optional()}),ChatBusyOutcomeDTOSchema=z38.object({kind:z38.literal("busy"),threadId:z38.string(),userMessageId:z38.string(),blockingRootId:z38.string().optional()}),ChatRefusedOutcomeDTOSchema=z38.object({kind:z38.literal("refused"),threadId:z38.string(),userMessageId:z38.string(),refusedInvocationId:z38.string(),terminalReason:z38.string()}),ChatNonStreamingOutcomeDTOSchema=z38.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ProjectChatKindSchema=z38.enum(["chat","agent","routine","task"]),ProjectChatCreatableKindSchema=z38.enum(["chat","agent"]),ProjectChatRoutinesDTOSchema=z38.object({quietRuns:z38.number().int().nonnegative(),since:z38.string().nullable(),lastOutcome:ChatRoutineRunOutcomeSchema.nullable(),lastRunAt:z38.string().nullable(),nextRunAt:z38.string().nullable(),wakesOnChanges:z38.boolean()}),ProjectChatDescriptionSchema=z38.string().trim().max(2e3),ProjectChatInstructionsSchema=z38.string().trim().max(8e3),ProjectChatDTOSchema=z38.object({id:z38.string().uuid(),kind:ProjectChatKindSchema,title:z38.string().nullable(),description:z38.string().nullable(),instructions:z38.string().nullable(),liveAt:z38.string().nullable(),template:z38.string().nullable(),parentThreadId:z38.string().uuid().nullable(),routines:ProjectChatRoutinesDTOSchema.nullable(),createdAt:z38.string(),lastMessageAt:z38.string().nullable(),preview:z38.string().nullable(),running:z38.boolean(),awaitingAnswer:z38.boolean(),unread:z38.boolean(),pinned:z38.boolean(),archived:z38.boolean(),muted:z38.boolean(),portrait:ChatPortraitSchema.nullable()}),ProjectChatListDTOSchema=z38.object({chats:z38.array(ProjectChatDTOSchema)}),ProjectChatCreatedDTOSchema=z38.object({id:z38.string().uuid()}),ProjectChatTitleSchema=z38.string().trim().min(1).max(120),ProjectChatCreateSchema=z38.object({id:z38.string().uuid(),portrait:ChatPortraitSchema,kind:ProjectChatCreatableKindSchema,title:ProjectChatTitleSchema,description:ProjectChatDescriptionSchema,template:z38.string().min(1).max(64),timezone:ChatRoutineTimezoneSchema,setup:z38.literal(!0),locale:z38.string().trim().min(2).max(16)}).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").refine(create=>create.setup===void 0||create.kind==="agent","Only an agent is set up in its chat"),ProjectChatUpdateSchema=z38.object({title:ProjectChatTitleSchema,description:ProjectChatDescriptionSchema,instructions:ProjectChatInstructionsSchema,portrait:ChatPortraitSchema}).partial().refine(update=>update.title!==void 0||update.description!==void 0||update.instructions!==void 0||update.portrait!==void 0,"Set a title, a description, instructions or a portrait"),ChatTemplateRoutineScheduleDTOSchema=z38.object({cron:z38.string()}),ChatTemplateRoutineDTOSchema=z38.object({name:z38.string(),description:z38.string(),instructions:z38.string(),schedule:ChatTemplateRoutineScheduleDTOSchema.nullable(),plans:z38.array(AgentPlanSchema)}),ChatTemplateDTOSchema=z38.object({id:z38.string(),name:z38.string(),summary:z38.string(),description:z38.string(),greeting:z38.string(),starters:z38.array(z38.string()),portrait:ChatPortraitSchema,plans:z38.array(AgentPlanSchema),routines:z38.array(ChatTemplateRoutineDTOSchema)}),ChatTemplateListDTOSchema=z38.object({templates:z38.array(ChatTemplateDTOSchema)}),ProjectChatStateSchema=z38.object({read:z38.boolean(),pinned:z38.boolean(),archived:z38.boolean(),muted:z38.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 z39}from"zod";var ADMIN_ASSISTANT_BASE_PATH,ADMIN_ASSISTANT_PATHS,ADMIN_ASSISTANT_MESSAGE_MAX_CHARS,ADMIN_ASSISTANT_FORM_NOTE_MAX_CHARS,ADMIN_ASSISTANT_REQUEST_MAX_BYTES,AdminAssistantFormResponseSchema,AdminAssistantOutgoingMessageSchema,AdminAssistantSendRequestSchema,AdminAssistantSendOutcomeSchema,AdminAssistantStreamHeadSchema,AdminAssistantThreadSummarySchema,AdminAssistantThreadListQuerySchema,AdminAssistantThreadListResponseSchema,AdminAssistantThreadResponseSchema,AdminAssistantLiveTurnResponseSchema,AdminAssistantAbortResponseSchema,AdminAssistantThreadUpdateSchema,AdminAssistantThreadDeleteResponseSchema,init_admin_assistant=__esm({"../../packages/api-contracts/dist/esm/types/admin-assistant.js"(){"use strict";init_chat_dto();init_chat_block();ADMIN_ASSISTANT_BASE_PATH="/api/ops/assistant",ADMIN_ASSISTANT_PATHS={chat:`${ADMIN_ASSISTANT_BASE_PATH}/chat`,threads:`${ADMIN_ASSISTANT_BASE_PATH}/threads`,thread:__name(threadId=>`${ADMIN_ASSISTANT_BASE_PATH}/threads/${encodeURIComponent(threadId)}`,"thread"),live:__name(threadId=>`${ADMIN_ASSISTANT_BASE_PATH}/threads/${encodeURIComponent(threadId)}/live`,"live"),stream:__name(threadId=>`${ADMIN_ASSISTANT_BASE_PATH}/threads/${encodeURIComponent(threadId)}/stream`,"stream"),abort:__name(threadId=>`${ADMIN_ASSISTANT_BASE_PATH}/threads/${encodeURIComponent(threadId)}/abort`,"abort")},ADMIN_ASSISTANT_MESSAGE_MAX_CHARS=2e4,ADMIN_ASSISTANT_FORM_NOTE_MAX_CHARS=4e3,ADMIN_ASSISTANT_REQUEST_MAX_BYTES=256*1024,AdminAssistantFormResponseSchema=ChatFormResponseSchema.extend({questions:z39.array(ChatFormAnswerItemSchema.extend({answer:z39.string().min(1).max(ADMIN_ASSISTANT_FORM_NOTE_MAX_CHARS+1200),freeText:z39.string().max(ADMIN_ASSISTANT_FORM_NOTE_MAX_CHARS)})).max(4)}),AdminAssistantOutgoingMessageSchema=z39.object({id:z39.string().min(1).max(255).regex(/^(app|e2e):/,"Message ids from a client start with app:"),text:z39.string().max(ADMIN_ASSISTANT_MESSAGE_MAX_CHARS)}).strict(),AdminAssistantSendRequestSchema=z39.object({threadId:z39.string().uuid().optional(),message:AdminAssistantOutgoingMessageSchema,formResponse:AdminAssistantFormResponseSchema.optional()}).strict().superRefine((body,context)=>{body.message.text.trim().length===0&&!body.formResponse&&context.addIssue({code:"custom",path:["message","text"],message:"A message cannot be empty."})}),AdminAssistantSendOutcomeSchema=z39.discriminatedUnion("kind",[z39.object({kind:z39.literal("replay"),threadId:z39.string(),userMessageId:z39.string()}),z39.object({kind:z39.literal("queued"),threadId:z39.string(),userMessageId:z39.string(),blockingRootId:z39.string().optional()}),z39.object({kind:z39.literal("busy"),threadId:z39.string(),userMessageId:z39.string(),blockingRootId:z39.string().optional()}),z39.object({kind:z39.literal("refused"),threadId:z39.string(),userMessageId:z39.string(),refusedInvocationId:z39.string(),terminalReason:z39.string()})]),AdminAssistantStreamHeadSchema=z39.object({kind:z39.literal("turn"),threadId:z39.string(),userMessageId:z39.string(),invocationId:z39.string()}),AdminAssistantThreadSummarySchema=z39.object({id:z39.string().uuid(),title:z39.string().nullable(),lastMessageAt:z39.string().nullable(),createdAt:z39.string()}),AdminAssistantThreadListQuerySchema=z39.object({q:z39.string().trim().max(200).optional(),cursor:z39.string().max(500).optional(),limit:z39.coerce.number().int().min(1).max(100).optional()}),AdminAssistantThreadListResponseSchema=z39.object({threads:z39.array(AdminAssistantThreadSummarySchema),nextCursor:z39.string().nullable()}),AdminAssistantThreadResponseSchema=z39.object({thread:AdminAssistantThreadSummarySchema.extend({createdBy:z39.string().nullable()}),messages:z39.array(ChatThreadMessageDTOSchema),liveTurn:ChatLiveTurnDTOSchema.nullable()}),AdminAssistantLiveTurnResponseSchema=z39.object({threadId:z39.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),AdminAssistantAbortResponseSchema=z39.object({aborted:z39.boolean()}),AdminAssistantThreadUpdateSchema=z39.object({title:ProjectChatTitleSchema}).strict(),AdminAssistantThreadDeleteResponseSchema=z39.object({deleted:z39.literal(!0)})}});import{z as z40}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=z40.enum(REPORT_TONES),blockCommon={title:z40.string().trim().min(1).max(120).optional(),fallback:z40.string().trim().min(1).max(600).optional()},ReportTextBlockSchema=z40.object({type:z40.literal("text"),...blockCommon,text:z40.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=z40.object({type:z40.literal("metric"),...blockCommon,items:z40.array(z40.object({value:z40.string().trim().min(1).max(24),unit:z40.string().trim().min(1).max(12).optional(),label:z40.string().trim().min(1).max(160),note:z40.string().trim().min(1).max(300).optional()}).strict()).min(1).max(3),spark:z40.array(z40.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=z40.enum(REPORT_VIZ_KINDS),ReportVizBlockSchema=z40.object({type:z40.literal("viz"),...blockCommon,kind:ReportVizKindSchema.describe("bar: compare named quantities. line/area: change across an ordered sequence. composition: parts of one whole."),unit:z40.string().trim().min(1).max(12).optional(),points:z40.array(z40.object({label:z40.string().trim().min(1).max(24),value:z40.number().finite(),highlight:z40.boolean().optional()}).strict()).min(2).max(24),caption:z40.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=z40.object({type:z40.literal("list"),...blockCommon,items:z40.array(z40.object({tone:ReportToneSchema.optional(),label:z40.string().trim().min(1).max(24).optional(),heading:z40.string().trim().min(1).max(160).describe("The human-visible result, action, or consequence, readable on its own."),body:z40.string().trim().min(1).max(1200).optional().describe("One short explanation of why it matters."),evidence:z40.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=z40.object({type:z40.literal("table"),...blockCommon,columns:z40.array(z40.object({label:z40.string().trim().min(1).max(32)}).strict()).min(1).max(6),rows:z40.array(z40.object({cells:z40.array(z40.object({text:z40.string().trim().max(160),tone:ReportToneSchema.optional()}).strict()).min(1).max(6)}).strict()).min(1).max(40),caption:z40.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=z40.object({type:z40.literal("media"),...blockCommon,assetId:z40.uuid(),alt:z40.string().trim().min(1).max(300),caption:z40.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=z40.object({type:z40.literal("links"),...blockCommon,items:z40.array(z40.object({label:z40.string().trim().min(1).max(120),url:z40.url({protocol:/^https$/}).max(2e3),description:z40.string().trim().min(1).max(300).optional()}).strict()).min(1).max(8)}).strict().describe("A destination, evidence source, or next action worth opening."),ReportCodeBlockSchema=z40.object({type:z40.literal("code"),...blockCommon,language:z40.string().regex(/^[a-z0-9+#-]{1,20}$/,"A language is a short lowercase token, e.g. ts, json, bash.").optional(),code:z40.string().min(1).max(REPORT_CODE_MAX_CHARS),caption:z40.string().trim().min(1).max(600).optional()}).strict().describe("An exact snippet that is decisive evidence. Never a log dump."),ReportBlockSchema=z40.discriminatedUnion("type",[ReportTextBlockSchema,ReportMetricBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportVizBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema]),ReportDocumentSchema=z40.object({title:z40.string().trim().min(1).max(REPORT_TITLE_MAX_CHARS),brief:z40.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),details:z40.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=z40.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=z40.preprocess(normalizeStoredBlocks,ReportBriefSchema),StoredReportDocumentSchema=z40.preprocess(normalizeStoredDocument,ReportDocumentSchema);__name(derivedBlockBody,"derivedBlockBody");__name(reportSectionContentLength,"reportSectionContentLength");__name(formatReportNumber,"formatReportNumber");__name(formatReportValue,"formatReportValue")}});import{z as z41}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=z41.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z41.object({dev:z41.string().trim().min(1).optional(),build:z41.string().trim().min(1).optional(),install:z41.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z41.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z41.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z41.object({type:z41.enum(["header","cookie","query","host"]),key:z41.string().min(1).optional(),value:z41.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:z41.array(FimoHostingConditionSchema).min(1).optional(),missing:z41.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z41.object({source:z41.string().min(1),destination:z41.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z41.object({source:z41.string().min(1),destination:z41.string().min(1),permanent:z41.boolean().optional(),statusCode:z41.union([z41.literal(301),z41.literal(302),z41.literal(307),z41.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z41.object({source:z41.string().min(1),headers:z41.array(z41.object({key:z41.string().min(1),value:z41.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z41.object({rewrites:z41.array(FimoHostingRewriteSchema).optional(),redirects:z41.array(FimoHostingRedirectSchema).optional(),headers:z41.array(FimoHostingHeaderSchema).optional(),cleanUrls:z41.boolean().optional(),trailingSlash:z41.boolean().optional()}).strict(),FimoAppConfigSchema=z41.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(path52){return[...path52.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path52,params){return pageRouteParamNames(path52).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 z42}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=z42.enum(["provisioning","active","deleted"]),ProjectBranchKindSchema=z42.enum(["user","agent-session"]),ProjectBranchDTOSchema=BaseEntitySchema.extend({projectId:z42.uuid(),branch:BranchSchema.optional(),status:ProjectBranchStatusSchema,kind:ProjectBranchKindSchema,parentBranch:BranchSchema.nullable().optional(),createdBy:z42.string().nullable(),deletedAt:z42.coerce.date().nullable(),env:BranchSchema,parentEnv:BranchSchema.nullable()}),ProjectBranchDTO=createDTO(ProjectBranchDTOSchema),ResolvedBranchEnvironmentDTOSchema=z42.object({id:z42.union([z42.literal(PREVIEW_ENVIRONMENT_KEY),z42.uuid()]),name:z42.string()}),ProjectBranchListItemDTOSchema=ProjectBranchDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable(),workSession:z42.object({sessionId:z42.uuid(),name:z42.string()}).optional()}),ProjectBranchListItemDTO=createDTO(ProjectBranchListItemDTOSchema),CreateProjectBranchRequestInputSchema=z42.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=z42.object({from:BranchSchema.optional()}),ProjectBranchResponseSchema=createResponseSchema(ProjectBranchDTOSchema),ProjectBranchesListResponseSchema=createResponseSchema(z42.array(ProjectBranchListItemDTOSchema)),BranchSurfaceDiffSchema=z42.object({surface:z42.enum(["code","schemas","content","translations","assets","forms"]),status:z42.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z42.number().int().nonnegative(),conflictCount:z42.number().int().nonnegative()}),BranchDiffResultSchema=z42.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),generatedAt:z42.coerce.date(),surfaces:z42.array(BranchSurfaceDiffSchema),fromEnv:BranchSchema,toEnv:BranchSchema}),BranchDiffResultDTO=createDTO(BranchDiffResultSchema)}});import{z as z43}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=z43.object({projectId:z43.uuid(),name:z43.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z43.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z43.literal("production"),sourceBranch:BranchSchema,isPublished:z43.boolean(),url:z43.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z43.literal(PREVIEW_ENVIRONMENT_KEY),kind:z43.literal("preview"),matchedBranchCount:z43.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z43.literal("custom"),matchedBranchCount:z43.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z43.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z43.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema(z43.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z43.object({deletedId:z43.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema(DeleteProjectEnvironmentResultSchema)}});import{z as z44}from"zod";var ProjectSecretsListQuerySchema,ProjectSecretWriteRequestSchema,CreateProjectSecretRequestSchema,DeleteProjectSecretQuerySchema,ProjectSecretMetadataDTOSchema,ProjectSecretMetadataDTO,ProjectVariableBaseSchema,ProjectVariableDTOSchema,ProjectVariableDTO,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=z44.object({kind:z44.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z44.object({kind:z44.enum(["variable","secret"]),value:z44.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z44.string().min(1).max(255),exposure:z44.enum(["public","private"]).optional()}),DeleteProjectSecretQuerySchema=z44.object({kind:z44.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z44.object({id:z44.uuid(),projectId:z44.uuid(),key:z44.string(),kind:z44.literal("secret"),exposure:z44.literal("private"),environment:EnvironmentKeySchema,maskedValue:z44.string().optional(),createdAt:z44.date().transform(value=>value.toISOString()),updatedAt:z44.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectVariableBaseSchema=z44.object({id:z44.uuid(),projectId:z44.uuid(),key:z44.string(),kind:z44.literal("variable"),environment:EnvironmentKeySchema,managed:z44.boolean(),createdAt:z44.date().transform(value=>value.toISOString()),updatedAt:z44.date().transform(value=>value.toISOString())}),ProjectVariableDTOSchema=z44.discriminatedUnion("exposure",[ProjectVariableBaseSchema.extend({exposure:z44.literal("public"),value:z44.string()}),ProjectVariableBaseSchema.extend({exposure:z44.literal("private"),maskedValue:z44.string().optional()})]),ProjectVariableDTO=createDTO(ProjectVariableDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema(z44.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema(ProjectSecretMetadataDTOSchema)}});import{z as z45}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=z45.object({success:z45.literal(!0),downloadUrl:z45.string(),expiresAt:z45.string(),fileSize:z45.number(),duration:z45.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z45.object({success:z45.literal(!0),projectId:z45.string(),projectName:z45.string(),displayName:z45.string(),projectUrl:z45.string(),duration:z45.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z45.object({contentTypes:z45.number(),entries:z45.number(),assets:z45.number(),translations:z45.number(),forms:z45.number(),codeFiles:z45.number(),assetFiles:z45.number()}),ImportPreviewSurfaceDTOSchema=z45.object({name:z45.string(),included:z45.boolean(),count:z45.number().optional(),note:z45.string().optional()}),ImportPreviewDTOSchema=z45.object({projectName:z45.string(),displayName:z45.string().nullable(),category:z45.string().nullable(),exportedAt:z45.string(),version:z45.string(),envScope:z45.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z45.array(ImportPreviewSurfaceDTOSchema),fileSize:z45.number(),fileName:z45.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z45.object({success:z45.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z46}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,ConflictTargetCommitSchema,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=z46.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z46.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z46.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z46.object({verb:SurfaceDeltaVerbSchema,key:z46.string(),detail:z46.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z46.record(z46.string(),z46.unknown()).optional()}),PerSurfaceDeltaSchema=z46.object({surface:SurfaceNameSchema,status:z46.enum(["ok","timed_out","failed","unchanged"]),durationMs:z46.number().int().nonnegative().optional(),changedCount:z46.number().int().nonnegative(),conflictCount:z46.number().int().nonnegative(),items:z46.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z46.boolean().optional(),error:z46.string().optional()}),CrossSurfaceFindingSchema=z46.object({id:z46.string(),kind:z46.string(),description:z46.string(),severity:z46.enum(["warning","error"]),source:z46.object({surface:SurfaceNameSchema,key:z46.string()}),target:z46.object({surface:SurfaceNameSchema,key:z46.string()}),actions:z46.array(z46.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z46.object({branch:BranchSchema.optional(),env:BranchSchema,vs:BranchSchema,syncState:z46.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z46.coerce.date(),surfaces:z46.array(PerSurfaceDeltaSchema),agents:z46.array(z46.object({id:z46.string(),name:z46.string(),status:z46.enum(["active","paused","failed"]),lastRunAt:z46.coerce.date().nullable()})).optional(),crossSurface:z46.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z46.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,generatedAt:z46.coerce.date(),surfaces:z46.array(PerSurfaceDeltaSchema),crossSurface:z46.array(CrossSurfaceFindingSchema).optional(),fingerprint:z46.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z46.object({path:z46.string(),state:z46.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z46.string(),additions:z46.number().int().nonnegative(),deletions:z46.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z46.object({oid:z46.string().optional(),content:z46.string().optional(),truncated:z46.boolean(),binary:z46.boolean()}),CodeConflictDetailSchema=z46.object({path:z46.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z46.string(),targetTipSha:z46.string(),mergeBaseSha:z46.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z46.object({id:z46.string(),slug:z46.string(),contentType:z46.string(),data:z46.record(z46.string(),z46.unknown()),updatedAt:z46.coerce.date()}),ContentRowDiffSchema=z46.object({collection:z46.string(),rowId:z46.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z46.object({name:z46.string(),label:z46.string(),isSingleton:z46.boolean(),fields:z46.record(z46.string(),z46.unknown())}),SchemaTypeDiffSchema=z46.object({typeName:z46.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z46.object({id:z46.string(),name:z46.string(),type:z46.enum(["file","folder"]),mimeType:z46.string().nullable(),storageKey:z46.string().nullable(),url:z46.string().nullable(),fileSize:z46.number().nullable(),width:z46.number().nullable(),height:z46.number().nullable(),altText:z46.string().nullable(),caption:z46.string().nullable(),createdAt:z46.coerce.date(),updatedAt:z46.coerce.date()}),AssetDiffSchema=z46.object({assetId:z46.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z46.object({locale:z46.string(),key:z46.string(),parent:z46.string().nullable(),child:z46.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z46.object({formName:z46.string(),label:z46.string().nullable(),schemaFingerprint:z46.string(),fields:z46.record(z46.string(),z46.unknown()),settings:z46.record(z46.string(),z46.unknown()).optional()}),FormSchemaDiffSchema=z46.object({formName:z46.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=z46.enum(CONFLICT_KINDS),ConflictTargetCommitSchema=z46.object({sha:z46.string(),subject:z46.string(),body:z46.string().optional(),author:z46.string(),date:z46.string()}),ConflictSchema=z46.object({surface:SurfaceNameSchema,key:z46.string(),kind:ConflictKindSchema.optional(),description:z46.string(),parentValue:z46.unknown().optional(),childValue:z46.unknown().optional(),conflictingFields:z46.array(z46.string()).optional(),code:z46.object({path:z46.string(),unresolvable:z46.boolean().optional(),reason:z46.string().optional(),targetCommits:z46.array(ConflictTargetCommitSchema).optional()}).optional()}),FieldPickSchema=z46.object({field:z46.string(),choice:z46.enum(["parent","child","pick","ai-pick"]),pickedValue:z46.unknown().optional(),aiSessionId:z46.string().optional()}),ConflictResolutionSchema=z46.object({surface:SurfaceNameSchema,key:z46.string(),choice:z46.enum(["parent","child","pick"]),pickedValue:z46.unknown().optional(),fieldPicks:z46.array(FieldPickSchema).optional()}),MergeResultSchema=z46.object({ok:z46.boolean(),mergeId:z46.string().uuid(),fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,applied:z46.array(z46.object({surface:SurfaceNameSchema,count:z46.number().int().nonnegative()})),conflicts:z46.array(ConflictSchema).optional(),summary:z46.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z46.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z46.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z46.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z46.boolean().optional()}),ResolvedStrategySchema=z46.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z46.boolean()}),MergeRequestSchema=z46.object({from:BranchSchema,allowDirectMerge:z46.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z46.object({mergeId:z46.string().uuid(),streamUrl:z46.string(),strategy:ResolvedStrategySchema,acceptedAt:z46.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z46.object({mergeId:z46.string().uuid(),fromEnv:BranchSchema,toEnv:BranchSchema,status:z46.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z46.array(ConflictSchema),draftResolutions:z46.array(ConflictResolutionSchema),lastEditedBy:z46.string().nullable(),lastEditedAt:z46.coerce.date().nullable(),initiator:z46.object({userId:z46.string().nullable(),role:z46.string().nullable(),agentName:z46.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z46.object({resolutions:z46.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z46.object({mergeId:z46.string().uuid(),draftResolutions:z46.array(ConflictResolutionSchema),lastEditedAt:z46.coerce.date(),lastEditedBy:z46.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z46.object({mergeId:z46.string().uuid(),resolutions:z46.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z46.object({mergeId:z46.string().uuid()}),PublishReleaseRequestSchema=z46.object({version:z46.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z46.string().max(2e4).optional()}),PublishReleaseResultSchema=z46.object({releaseTag:z46.string(),sha:z46.string(),publishedAt:z46.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z47}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=z47.enum(["planned","running","finished","cancelled","errored"]),AgentSessionReviewPublicationSchema=z47.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z47.object({capturedAt:z47.coerce.date(),fingerprint:z47.string().min(1).max(256),counts:z47.object({code:z47.number().int().nonnegative(),content:z47.number().int().nonnegative(),schemas:z47.number().int().nonnegative(),labels:z47.number().int().nonnegative(),assets:z47.number().int().nonnegative().optional()}),publication:AgentSessionReviewPublicationSchema,mergeId:z47.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z47.object({diff:DiffReportSchema,code:z47.array(CodeFileDiffSchema.extend({raw:z47.string().max(24576)})).max(200),schemas:z47.array(SchemaTypeDiffSchema).max(200),content:z47.array(z47.object({key:z47.string().min(1).max(512),collection:z47.string().min(1).max(256),slug:z47.string().max(512).optional(),verb:z47.enum(["added","modified","deleted"]),fields:z47.array(z47.object({name:z47.string().min(1).max(256),before:z47.unknown().optional(),after:z47.unknown().optional()})).max(20)})).max(200),labels:z47.array(z47.object({key:z47.string().min(1).max(512),locale:z47.string().min(1).max(64).optional(),before:z47.unknown().nullable(),after:z47.unknown().nullable()})).max(200),assets:z47.array(z47.object({key:z47.string().min(1).max(512),name:z47.string().min(1).max(512),verb:z47.enum(["added","modified","deleted"]),before:AssetSnapshotSchema.nullable(),after:AssetSnapshotSchema.nullable()})).max(200).default([])}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),SessionErrorCodeSchema=z47.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid"])}});import{z as z48}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=z48.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z48.enum(["auto-merge","review-merged","review-discarded"]),WorkSessionReviewSchema=z48.object({sessionId:z48.uuid(),branch:z48.string().min(1),targetBranch:z48.string().min(1),revision:z48.string().min(1),fingerprint:z48.string().min(1),source:z48.enum(["studio","slack","mcp"]),threadId:z48.uuid().nullable(),invocationId:z48.uuid().nullable(),conversationBranch:z48.string().nullable(),capturedAt:z48.string(),surfaces:z48.array(PerSurfaceDeltaSchema).optional(),counts:z48.record(z48.string(),z48.number().int().nonnegative())}),RequestWorkSessionReviewSchema=z48.strictObject({sessionId:z48.uuid(),summary:z48.string().trim().min(1).max(240),targetBranch:z48.string().trim().min(1).optional()}),WorkSessionReviewResultSchema=z48.object({requested:z48.literal(!0),alreadyRequested:z48.boolean(),reviewId:z48.uuid(),reviewUrl:z48.url(),status:z48.literal("pending"),sessionId:z48.uuid(),branch:z48.string(),targetBranch:z48.string(),revision:z48.string(),savedRevision:z48.string(),fingerprint:z48.string(),visibility:z48.literal("user-visible"),retention:z48.literal("durable"),expiresAt:z48.null(),merged:z48.literal(!1),published:z48.literal(!1),links:z48.object({preview:z48.url(),changes:z48.url(),conversation:z48.url().nullable()})}),AgentBranchProposalDTOSchema=z48.object({id:z48.uuid(),envId:z48.uuid(),sessionId:z48.uuid().nullable(),skillName:z48.string().min(1),classification:AgentBranchClassificationSchema,rationale:z48.string().nullable(),summary:z48.string().nullable(),surfaceDeltas:z48.record(z48.string(),z48.unknown()),review:WorkSessionReviewSchema.optional(),createdAt:z48.coerce.date(),decidedAt:z48.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z48.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z48.object({path:z48.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z48.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z48.object({code:z48.literal("merge_conflict"),message:z48.string(),conflicts:z48.record(z48.string(),z48.number().int().nonnegative())})}});import{z as z49}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=z49.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z49.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=z49.object({description:z49.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z49.literal(QUESTION_FORM_CONTRACT_VERSION),sessionIds:z49.array(z49.uuid()).optional()}),AgentQuestionSchema=z49.object({id:z49.uuid(),projectId:z49.uuid(),threadId:z49.uuid(),invocationId:z49.uuid(),agentKey:z49.string().min(1).max(120),anchorEnv:z49.string().min(1).max(64),retainedEnv:z49.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z49.string().min(1).nullable(),continuationInvocationId:z49.uuid().nullable(),askedAt:z49.coerce.date(),expiresAt:z49.coerce.date(),closedAt:z49.coerce.date().nullable()}),AgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z49.object({questionId:z49.uuid(),invocationId:z49.uuid(),askedAt:z49.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema(z49.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z49.object({question:AgentQuestionSchema,continuationInvocationId:z49.uuid(),deduped:z49.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema(AnswerAgentQuestionResultSchema)}});import{z as z50}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=z50.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z50.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z50.enum(["secret_text"]),IntegrationCredentialUsageSchema=z50.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z50.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z50.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z50.object({mode:IntegrationAuthModeSchema,label:z50.string().min(1),description:z50.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z50.object({id:z50.string().min(1),label:z50.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z50.boolean()}),IntegrationToolDefinitionDTOSchema=z50.object({key:z50.string().min(1),name:z50.string().min(1),description:z50.string().min(1),effect:IntegrationToolEffectSchema,input:z50.record(z50.string(),z50.unknown()).optional()}),IntegrationRecipeDTOSchema=z50.object({title:z50.string().min(1),description:z50.string().min(1),command:z50.string().min(1).optional()}),IntegrationInfoDTOSchema=z50.object({key:z50.string().min(1),name:z50.string().min(1),summary:z50.string().min(1),type:z50.enum(["native","mcp"]).optional(),url:z50.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z50.array(IntegrationAuthModeDTOSchema),credentials:z50.array(IntegrationCredentialDefinitionDTOSchema),tools:z50.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z50.enum(["available","unavailable"]).optional(),connectionCapabilities:z50.object({customIdentityCreation:z50.boolean()}).optional(),recipes:z50.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z50.object({projectId:z50.uuid(),integrationKey:z50.string().min(1),name:z50.string().min(1),summary:z50.string().min(1),installed:z50.boolean(),enabled:z50.boolean(),setupState:z50.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z50.string().nullable(),connectionId:z50.uuid().nullable().optional(),connectionAlias:z50.string().min(1).nullable().optional(),connectionStatus:z50.enum(["active","revoked","disconnected"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z50.array(z50.string()),installedAt:z50.coerce.date().nullable(),updatedAt:z50.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z50.object({id:z50.uuid(),projectId:z50.uuid(),integrationKey:z50.string().min(1),enabled:z50.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z50.string(),connectionId:z50.uuid().nullable().optional(),connectionAlias:z50.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z50.array(z50.string()),createdAt:z50.coerce.date(),updatedAt:z50.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z50.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z50.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z50.object({authMode:IntegrationAuthModeSchema}),OrganizationIntegrationConnectionStatusSchema=z50.enum(["active","revoked","disconnected"]),OrganizationIntegrationConnectionDTOSchema=z50.object({id:z50.uuid(),organizationId:z50.string().min(1),integrationKey:z50.string().min(1),registrationId:z50.uuid().nullable(),alias:z50.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z50.string().min(1),externalAccountName:z50.string().nullable(),externalBotUserId:z50.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z50.array(z50.string()),connectedAt:z50.coerce.date(),updatedAt:z50.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionDTOSchema=OrganizationIntegrationConnectionDTOSchema.extend({granted:z50.boolean(),isDefault:z50.boolean()}),ProjectIntegrationConnectionDTO=createDTO(ProjectIntegrationConnectionDTOSchema),McpHeaderNameSchema=z50.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z50.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z50.record(McpHeaderNameSchema,z50.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z50.object({alias:z50.string().min(1).max(120).optional(),token:z50.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z50.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=z50.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),IntegrationCustomIdentitySchema=z50.object({displayName:z50.string().trim().min(1).max(35),backgroundColor:z50.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),iconUrl:z50.string().url().max(2048).optional()}),ConnectProjectIntegrationRequestSchema=z50.discriminatedUnion("mode",[z50.object({mode:z50.literal("personal"),alias:z50.string().min(1).max(120),token:z50.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z50.boolean().optional()}),z50.object({mode:z50.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z50.boolean().optional(),registrationId:z50.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=z50.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z50.union([z50.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z50.object({type:z50.literal("mcp"),name:z50.string().trim().min(1).max(120),url:z50.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z50.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z50.string().min(1).optional(),integrationId:z50.string().min(2).max(80).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=z50.object({integrationKey:z50.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z50.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z50.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z50.literal("oauth"),connectUrl:z50.string().url(),expiresAt:z50.coerce.date()})]),ReusableMcpServerAuthKindSchema=z50.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z50.object({id:z50.uuid(),name:z50.string().min(1),host:z50.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z50.string().min(1),availability:z50.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z50.object({query:z50.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z50.object({serverId:z50.uuid()}),LinearOAuthApplicationDistributionSchema=z50.enum(["private","public"]),OrganizationLinearAppDTOSchema=z50.object({id:z50.uuid(),displayName:z50.string().min(1),description:z50.string().nullable(),iconUrl:z50.string().nullable(),distribution:LinearOAuthApplicationDistributionSchema,status:z50.enum(["active","revoked","disconnected"]),connectionIds:z50.array(z50.uuid()),createdAt:z50.coerce.date(),updatedAt:z50.coerce.date()}),OrganizationLinearAppDTO=createDTO(OrganizationLinearAppDTOSchema),CreateManagedLinearAppRequestSchema=z50.object({appName:z50.string().trim().min(2).max(80),description:z50.string().trim().max(1e3).optional(),iconUrl:z50.string().url().max(2048).optional()}),UpdateManagedLinearAppRequestSchema=CreateManagedLinearAppRequestSchema.partial().refine(input=>Object.keys(input).length>0,"At least one Linear app field is required."),StartManagedLinearConnectRequestSchema=z50.object({projectId:z50.uuid(),registrationId:z50.uuid(),returnTo:ProjectIntegrationReturnPathSchema.optional()}),StartProjectIntegrationConnectResponseSchema=z50.object({integrationKey:z50.string().min(1),connectUrl:z50.string().url(),expiresAt:z50.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z50.discriminatedUnion("mode",[z50.object({mode:z50.literal("personal"),integrationKey:z50.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z50.object({mode:z50.literal("oauth"),integrationKey:z50.string().min(1),connectUrl:z50.string().url(),expiresAt:z50.coerce.date()})]),BindProjectChannelRequestSchema=z50.object({ref:z50.string().min(1),connectionAlias:z50.string().min(1).optional(),agentName:z50.string().min(1).max(160).nullable().optional(),force:z50.boolean().optional()}),ListProjectChannelsQuerySchema=z50.object({integrationKey:z50.string().min(1)}),SearchProjectChannelsQuerySchema=z50.object({integrationKey:z50.string().min(1),connectionAlias:z50.string().min(1),query:z50.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z50.object({id:z50.uuid(),projectId:z50.uuid(),integrationKey:z50.string().min(1),connectionId:z50.uuid(),externalWorkspaceId:z50.string().min(1),externalChannelId:z50.string().min(1),externalChannelName:z50.string().nullable(),agentName:z50.string().nullable(),enabled:z50.boolean(),createdAt:z50.coerce.date(),updatedAt:z50.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z50.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z50.object({id:z50.string().min(1),name:z50.string().min(1),visibility:z50.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z50.string().min(1).nullable(),canMove:z50.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z50.object({markdown:z50.boolean().optional(),summary:z50.boolean().optional(),links:z50.boolean().optional(),branding:z50.boolean().optional(),images:z50.boolean().optional(),html:z50.union([z50.literal("cleaned"),z50.literal("raw"),z50.boolean()]).optional(),json:z50.union([z50.boolean(),z50.object({prompt:z50.string().min(1).max(1e4),schema:z50.record(z50.string(),z50.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z50.object({url:z50.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z50.boolean().optional(),timeoutMs:z50.number().int().positive().max(12e4).optional(),waitForMs:z50.number().int().min(0).max(3e4).optional(),maxAgeMs:z50.number().int().min(0).optional(),minAgeMs:z50.number().int().min(0).optional(),storeInCache:z50.boolean().optional(),proxy:z50.enum(["basic","enhanced","auto"]).optional(),mobile:z50.boolean().optional(),location:z50.object({country:z50.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z50.array(z50.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z50.object({query:z50.string().min(1),maxResults:z50.number().int().positive().max(20).optional(),sources:z50.array(z50.enum(["web","news","images"])).min(1).max(3).optional(),categories:z50.array(z50.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z50.array(z50.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z50.array(z50.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z50.enum(["hour","day","week","month","year"]).optional(),location:z50.string().min(1).max(160).optional(),country:z50.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z50.boolean().optional(),timeoutMs:z50.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z50.object({query:z50.string().min(1).max(500),maxResults:z50.number().int().min(1).max(100).optional(),types:z50.array(z50.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z50.array(z50.string().min(1).max(512)).min(1).max(20).optional(),sources:z50.array(z50.string().min(1).max(512)).min(1).max(20).optional(),passages:z50.number().int().min(1).max(5).optional(),skills:z50.literal("only").optional(),language:z50.string().min(1).optional(),topic:z50.string().min(1).optional(),license:z50.string().min(1).optional(),minStars:z50.number().int().min(0).optional(),maxStars:z50.number().int().min(0).optional(),archived:z50.boolean().optional(),fork:z50.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z50.object({query:z50.string().min(1).max(500),maxResults:z50.number().int().min(1).max(500).optional(),authors:z50.array(z50.string().min(1)).min(1).optional(),categories:z50.array(z50.string().min(1)).min(1).optional(),from:z50.iso.date().optional(),to:z50.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z50.object({paperId:z50.string().min(1).max(512),query:z50.string().min(1).max(500).optional(),maxPassages:z50.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z50.object({paperId:z50.string().min(1).max(512),intent:z50.string().min(1).max(500),mode:z50.enum(["similar","citers","references"]).optional(),maxResults:z50.number().int().min(1).max(500).optional(),rerank:z50.boolean().optional(),anchors:z50.array(z50.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z50.object({url:z50.string().url(),search:z50.string().min(1).optional(),limit:z50.number().int().positive().max(200).optional(),includeSubdomains:z50.boolean().optional(),timeoutMs:z50.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z50.object({url:z50.string().url(),limit:z50.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z50.boolean().optional(),timeoutMs:z50.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z50.object({text:z50.string().min(1).max(200).optional(),cron:z50.string().min(1).max(120).optional(),timezone:z50.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z50.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z50.boolean().optional(),timeoutMs:z50.number().int().positive().max(12e4).optional(),waitForMs:z50.number().int().min(0).max(3e4).optional(),maxAgeMs:z50.number().int().min(0).optional(),minAgeMs:z50.number().int().min(0).optional(),storeInCache:z50.boolean().optional(),proxy:z50.enum(["basic","enhanced","auto"]).optional(),mobile:z50.boolean().optional(),location:z50.object({country:z50.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z50.array(z50.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z50.union([z50.object({type:z50.enum(["scrape","crawl"]).default("scrape"),urls:z50.array(z50.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z50.object({type:z50.literal("search"),queries:z50.array(z50.string().min(1).max(256)).min(1).max(12),searchWindow:z50.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z50.number().int().min(1).max(50).optional(),includeDomains:z50.array(z50.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z50.array(z50.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z50.object({name:z50.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z50.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z50.string().min(1).max(2e3).optional(),judgeEnabled:z50.boolean().optional(),retentionDays:z50.number().int().min(1).max(365).optional(),notification:z50.object({email:z50.object({enabled:z50.boolean().default(!0),recipients:z50.array(z50.string().email()).min(1).max(20),includeDiffs:z50.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=z50.object({monitorId:z50.string().uuid(),name:z50.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z50.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z50.string().min(1).max(2e3).optional(),judgeEnabled:z50.boolean().optional(),retentionDays:z50.number().int().min(1).max(365).optional(),status:z50.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z50.object({monitorId:z50.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z50.string().uuid()}),RunProjectIntegrationToolRequestSchema=z50.object({tool:z50.string().min(1),input:z50.record(z50.string(),z50.unknown()),connectionAlias:z50.string().min(1).optional(),approval:z50.string().min(1).max(4e3).optional()}),ProjectIntegrationToolRunUsageSchema=z50.object({provider:z50.string().min(1),providerCredits:z50.number().nonnegative().optional(),providerCostUsd:z50.number().nonnegative().optional(),requests:z50.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z50.object({credits:z50.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z50.object({url:z50.string(),provider:z50.literal("firecrawl"),title:z50.string().optional(),statusCode:z50.number().optional(),markdown:z50.string().optional(),summary:z50.string().optional(),links:z50.array(z50.string()).optional(),images:z50.array(z50.string()).optional(),html:z50.string().optional(),json:z50.unknown().optional(),branding:z50.record(z50.string(),z50.unknown()).optional(),warning:z50.string().optional()}),FirecrawlSearchToolOutputSchema=z50.object({query:z50.string(),provider:z50.literal("firecrawl"),warning:z50.string().optional(),results:z50.array(z50.object({title:z50.string(),url:z50.string(),snippet:z50.string().optional(),content:z50.string().optional(),score:z50.number().optional(),publishedAt:z50.string().optional()}))}),FirecrawlResearchPaperSchema=z50.object({paperId:z50.string(),primaryId:z50.string().optional(),ids:z50.record(z50.string(),z50.array(z50.string())).optional(),title:z50.string().optional(),abstract:z50.string().optional(),score:z50.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z50.object({text:z50.string(),score:z50.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z50.object({provider:z50.literal("firecrawl"),results:z50.array(z50.object({id:z50.string(),type:z50.string().min(1).optional(),url:z50.string(),title:z50.string().optional(),passages:z50.array(z50.object({text:z50.string()}).passthrough())}).passthrough()),coverage:z50.record(z50.string(),z50.string()).optional(),reranked:z50.boolean().optional(),repos:z50.array(z50.record(z50.string(),z50.unknown())).optional(),sources:z50.array(z50.record(z50.string(),z50.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z50.object({provider:z50.literal("firecrawl"),results:z50.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z50.object({provider:z50.literal("firecrawl"),paper:z50.record(z50.string(),z50.unknown()),paperId:z50.string().optional(),query:z50.string().optional(),passages:z50.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z50.object({provider:z50.literal("firecrawl"),results:z50.array(FirecrawlResearchPaperSchema),poolSize:z50.number().int().nonnegative(),truncated:z50.boolean(),note:z50.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z50.object({url:z50.string(),provider:z50.literal("firecrawl"),count:z50.number(),links:z50.array(z50.object({url:z50.string(),title:z50.string().optional(),description:z50.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z50.object({url:z50.string(),provider:z50.literal("firecrawl"),total:z50.number(),pages:z50.array(z50.object({url:z50.string(),title:z50.string().optional(),statusCode:z50.number().optional(),markdown:z50.string().optional(),summary:z50.string().optional(),links:z50.array(z50.string()).optional(),images:z50.array(z50.string()).optional(),html:z50.string().optional(),warning:z50.string().optional()})),warning:z50.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z50.object({cron:z50.string().optional(),text:z50.string().optional(),timezone:z50.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z50.object({id:z50.string().optional(),type:z50.enum(["scrape","crawl","search"]).optional(),urls:z50.array(z50.string()).optional(),queries:z50.array(z50.string()).optional(),searchWindow:z50.string().optional(),maxResults:z50.number().optional(),includeDomains:z50.array(z50.string()).optional(),excludeDomains:z50.array(z50.string()).optional(),scrapeOptions:z50.record(z50.string(),z50.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z50.object({id:z50.string(),name:z50.string(),status:z50.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z50.string().nullable().optional(),lastRunAt:z50.string().nullable().optional(),currentCheckId:z50.string().nullable().optional(),targets:z50.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z50.string().nullable().optional(),judgeEnabled:z50.boolean().optional(),estimatedCreditsPerMonth:z50.number().optional(),createdAt:z50.string().optional(),updatedAt:z50.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z50.object({id:z50.string(),monitorId:z50.string(),scheduledFor:z50.string().nullable().optional(),startedAt:z50.string().nullable().optional(),finishedAt:z50.string().nullable().optional(),estimatedCredits:z50.number().nullable().optional(),reservedCredits:z50.number().nullable().optional(),actualCredits:z50.number().nullable().optional(),billingStatus:z50.string().nullable().optional(),summary:z50.object({totalPages:z50.number().optional(),same:z50.number().optional(),changed:z50.number().optional(),new:z50.number().optional(),removed:z50.number().optional(),error:z50.number().optional()}).passthrough().optional(),error:z50.string().nullable().optional(),createdAt:z50.string().optional(),updatedAt:z50.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z50.object({provider:z50.literal("firecrawl"),monitors:z50.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z50.object({provider:z50.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z50.object({provider:z50.literal("firecrawl"),monitorId:z50.string(),deleted:z50.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z50.object({provider:z50.literal("firecrawl"),monitorId:z50.string(),checks:z50.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z50.object({provider:z50.literal("firecrawl"),monitorId:z50.string(),check:FirecrawlMonitorCheckOutputSchema,next:z50.string().optional()}),FirecrawlToolKeySchema=z50.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=z50.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z50.object({projectId:z50.uuid(),integrationKey:z50.string().min(1),tool:z50.string().min(1),connectionAlias:z50.string().min(1).nullable().optional(),output:z50.record(z50.string(),z50.unknown()),executedAt:z50.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z50.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z50.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z50.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z50.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z50.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z50.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z50.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z50.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z50.array(ProjectIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema(z50.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z50.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z50.array(ProjectChannelCandidateDTOSchema))}});import{z as z51}from"zod";var IntegrationIdSchema,IntegrationScopeSchema,IntegrationOAuthSchema,IntegrationApiKeySchema,IntegrationProviderAuthSchema,IntegrationMcpAuthSchema,IntegrationAuthSchema,IntegrationRecipeSchema,IntegrationSettingSchema,IntegrationToolsSchema,IntegrationSkillSchema,IntegrationManifestSchema,IntegrationPermissionDTOSchema,IntegrationSettingDefinitionDTOSchema,IntegrationKindSchema,IntegrationSummaryDTOSchema,IntegrationAccountDTOSchema,IntegrationSiteDTOSchema,OrganizationIntegrationDTOSchema,ProjectIntegrationDTOSchema,IntegrationReturnPathSchema,StartIntegrationInstallRequestSchema,StartIntegrationInstallDTOSchema,AddOrganizationMcpServerDTOSchema,ConnectIntegrationKeyRequestSchema,ReplaceIntegrationServerCredentialsRequestSchema,UpdateIntegrationSiteRequestSchema,UpdateIntegrationSitesRequestSchema,UpdateProjectIntegrationSettingsRequestSchema,IntegrationSettingOptionDTOSchema,IntegrationToolMatchDTOSchema,ProjectIntegrationGuideDTOSchema,APPROVAL_TOKEN_MAX,REQUEST_TOKEN_MAX,RunIntegrationToolRequestSchema,IntegrationApprovalCallShape,IntegrationToolRunResultDTOSchema,IntegrationApprovalPreviewRequestSchema,IntegrationApprovalPreviewDTOSchema,RoutineIntegrationApprovalSchema,IntegrationApprovalDecisionSchema,DecideIntegrationApprovalRequestSchema,IntegrationApprovalDecisionDTOSchema,IntegrationAgentAccessDTOSchema,init_integration_catalog_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration-catalog.dto.js"(){"use strict";init_integration_dto();IntegrationIdSchema=z51.string().min(2).max(80).regex(/^[a-z0-9][a-z0-9-]*$/,"App ids use lowercase letters, digits and dashes."),IntegrationScopeSchema=z51.strictObject({scope:z51.string().min(1),reason:z51.string().min(1).max(200)}),IntegrationOAuthSchema=z51.strictObject({id:z51.string().min(1).max(40),label:z51.string().min(1).max(80),kind:z51.literal("oauth"),actor:z51.literal("user").default("user"),authorizationUrl:z51.url(),tokenUrl:z51.url(),revocationUrl:z51.url().optional(),userInfoUrl:z51.url().optional(),client:z51.strictObject({idEnv:z51.string().min(1),secretEnv:z51.string().min(1)}),authorizeParams:z51.record(z51.string(),z51.string()).default({}),scopes:z51.array(IntegrationScopeSchema).min(1)}),IntegrationApiKeySchema=z51.strictObject({id:z51.string().min(1).max(40),label:z51.string().min(1).max(80),kind:z51.literal("apiKey"),keyLabel:z51.string().min(1).max(80),placeholder:z51.string().min(1).max(40).optional(),helpUrl:z51.url()}),IntegrationProviderAuthSchema=z51.strictObject({id:z51.string().min(1).max(40),label:z51.string().min(1).max(80),kind:z51.literal("provider")}),IntegrationMcpAuthSchema=z51.strictObject({id:z51.string().min(1).max(40),label:z51.string().min(1).max(80),kind:z51.literal("mcp"),methods:z51.array(McpIntegrationSetupAuthSchema).min(1),scopes:z51.array(z51.string().min(1)).min(1).optional(),header:z51.object({name:z51.string().min(1).max(80),valuePrefix:z51.string().max(80)}).optional()}),IntegrationAuthSchema=z51.discriminatedUnion("kind",[IntegrationOAuthSchema,IntegrationApiKeySchema,IntegrationProviderAuthSchema,IntegrationMcpAuthSchema]),IntegrationRecipeSchema=z51.strictObject({title:z51.string().min(1).max(80),description:z51.string().min(1).max(300),command:z51.string().min(1).optional()}),IntegrationSettingSchema=z51.strictObject({type:z51.enum(["string","choice"]),label:z51.string().min(1).max(80),description:z51.string().min(1).max(300).optional(),required:z51.boolean().default(!1),optionsFrom:z51.strictObject({tool:z51.string().min(1)}).optional()}),IntegrationToolsSchema=z51.discriminatedUnion("source",[z51.strictObject({source:z51.literal("hosted")}),z51.strictObject({source:z51.literal("mcp"),url:z51.url()})]),IntegrationSkillSchema=z51.strictObject({name:z51.string().min(1).max(64),description:z51.string().min(1).max(300),content:z51.string().min(1)}),IntegrationManifestSchema=z51.strictObject({apiVersion:z51.literal(1),id:IntegrationIdSchema,version:z51.string().regex(/^\d+\.\d+\.\d+$/),listing:z51.strictObject({name:z51.string().min(1).max(60),description:z51.string().min(1).max(200),details:z51.string().min(1).max(1e3),icon:z51.string().min(1),category:z51.enum(["seo","ai-visibility","analytics","communication"]),publisher:z51.string().min(1).max(60),agentReads:z51.strictObject({label:z51.string().min(1).max(80),description:z51.string().min(1).max(200)}).optional()}),auth:z51.array(IntegrationAuthSchema).min(1),identity:z51.strictObject({label:z51.string().min(1)}).optional(),settings:z51.record(z51.string().regex(/^[a-zA-Z][a-zA-Z0-9]*$/),IntegrationSettingSchema).default({}),tools:IntegrationToolsSchema,skills:z51.array(IntegrationSkillSchema).default([]),recipes:z51.array(IntegrationRecipeSchema).default([])}),IntegrationPermissionDTOSchema=z51.object({scope:z51.string(),reason:z51.string()}),IntegrationSettingDefinitionDTOSchema=z51.object({key:z51.string(),type:z51.enum(["string","choice"]),label:z51.string(),description:z51.string().nullable(),required:z51.boolean(),hasOptions:z51.boolean()}),IntegrationKindSchema=z51.enum(["catalog","custom","builtIn"]),IntegrationSummaryDTOSchema=z51.object({id:z51.string(),kind:IntegrationKindSchema,integrationKey:z51.string(),host:z51.string().nullable(),apiKey:z51.object({label:z51.string(),placeholder:z51.string().nullable(),helpUrl:z51.string(),primary:z51.boolean()}).nullable(),mcp:z51.object({url:z51.string(),methods:z51.array(McpIntegrationSetupAuthSchema),header:z51.object({name:z51.string(),valuePrefix:z51.string()}).nullable()}).nullable(),name:z51.string(),description:z51.string(),details:z51.string(),icon:z51.string(),category:z51.string(),publisher:z51.string(),signInLabel:z51.string(),permissions:z51.array(IntegrationPermissionDTOSchema),readOnly:z51.boolean(),settings:z51.array(IntegrationSettingDefinitionDTOSchema)}),IntegrationAccountDTOSchema=z51.object({connectionId:z51.uuid(),alias:z51.string(),accountName:z51.string().nullable(),status:z51.enum(["active","revoked"]),authKind:z51.enum(["oauth","api_key"]),connectedAt:z51.coerce.date()}),IntegrationSiteDTOSchema=z51.object({projectId:z51.uuid(),projectName:z51.string(),enabled:z51.boolean(),granted:z51.boolean(),connectionId:z51.uuid().nullable(),settings:z51.record(z51.string(),z51.string()),missingSettings:z51.array(z51.string())}),OrganizationIntegrationDTOSchema=IntegrationSummaryDTOSchema.extend({installed:z51.boolean(),accounts:z51.array(IntegrationAccountDTOSchema),siteAccess:z51.enum(["all","selected"]),sites:z51.array(IntegrationSiteDTOSchema)}),ProjectIntegrationDTOSchema=IntegrationSummaryDTOSchema.extend({installed:z51.boolean(),enabled:z51.boolean(),granted:z51.boolean(),accountName:z51.string().nullable(),settingsValues:z51.record(z51.string(),z51.string()),missingSettings:z51.array(z51.string()),tools:z51.array(z51.object({key:z51.string(),name:z51.string(),description:z51.string(),effect:IntegrationToolEffectSchema}))}),IntegrationReturnPathSchema=z51.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),StartIntegrationInstallRequestSchema=z51.object({projectId:z51.uuid().optional(),returnTo:IntegrationReturnPathSchema.optional()}),StartIntegrationInstallDTOSchema=z51.object({connectUrl:z51.url().nullable(),expiresAt:z51.coerce.date().nullable()}),AddOrganizationMcpServerDTOSchema=StartIntegrationInstallDTOSchema.extend({integrationId:z51.string()}),ConnectIntegrationKeyRequestSchema=z51.object({key:z51.string().trim().min(1).max(500),projectId:z51.uuid().optional()}),ReplaceIntegrationServerCredentialsRequestSchema=z51.object({token:z51.string().min(1).max(8e3).optional(),secrets:McpSecretMapSchema.optional()}).refine(value=>!!value.token!=!!value.secrets,"Send either a token or the header values."),UpdateIntegrationSiteRequestSchema=z51.object({enabled:z51.boolean(),connectionId:z51.uuid().optional()}),UpdateIntegrationSitesRequestSchema=z51.object({access:z51.enum(["all","selected"]).optional(),projectIds:z51.array(z51.uuid()).max(1e3),connectionId:z51.uuid().optional()}),UpdateProjectIntegrationSettingsRequestSchema=z51.object({settings:z51.record(z51.string(),z51.string().max(500))}),IntegrationSettingOptionDTOSchema=z51.object({value:z51.string(),label:z51.string(),suggested:z51.boolean()}),IntegrationToolMatchDTOSchema=z51.object({integrationId:z51.string(),integrationName:z51.string(),key:z51.string(),name:z51.string(),description:z51.string(),effect:IntegrationToolEffectSchema,input:z51.record(z51.string(),z51.unknown())}),ProjectIntegrationGuideDTOSchema=z51.object({integrationId:z51.string(),name:z51.string(),description:z51.string(),content:z51.string()}),APPROVAL_TOKEN_MAX=4e3,REQUEST_TOKEN_MAX=32e3,RunIntegrationToolRequestSchema=z51.object({tool:z51.string().min(1).max(120),input:z51.record(z51.string(),z51.unknown()).default({}),approval:z51.string().min(1).max(APPROVAL_TOKEN_MAX).optional(),readOnly:z51.boolean().optional()}),IntegrationApprovalCallShape={integration:z51.object({id:z51.string(),name:z51.string()}),tool:z51.object({key:z51.string(),name:z51.string(),effect:IntegrationToolEffectSchema}),input:z51.record(z51.string(),z51.unknown()),reason:z51.string(),canAlwaysAllow:z51.boolean()},IntegrationToolRunResultDTOSchema=z51.discriminatedUnion("status",[z51.object({status:z51.literal("ok"),output:z51.record(z51.string(),z51.unknown())}),z51.object({status:z51.literal("approval_required"),request:z51.string(),approveUrl:z51.string(),...IntegrationApprovalCallShape}),z51.object({status:z51.literal("blocked"),reason:z51.string()})]),IntegrationApprovalPreviewRequestSchema=z51.object({request:z51.string().min(1).max(REQUEST_TOKEN_MAX)}),IntegrationApprovalPreviewDTOSchema=z51.object({...IntegrationApprovalCallShape,allowOnce:z51.boolean(),expiresAt:z51.coerce.date()}),RoutineIntegrationApprovalSchema=IntegrationApprovalPreviewDTOSchema.pick({integration:!0,tool:!0,reason:!0,canAlwaysAllow:!0,allowOnce:!0}).extend({request:z51.string()}),IntegrationApprovalDecisionSchema=z51.enum(["allow","always","decline"]),DecideIntegrationApprovalRequestSchema=z51.object({request:z51.string().min(1).max(REQUEST_TOKEN_MAX),decision:IntegrationApprovalDecisionSchema}),IntegrationApprovalDecisionDTOSchema=z51.object({decision:IntegrationApprovalDecisionSchema,approval:z51.string().optional(),resumed:z51.boolean().optional()}),IntegrationAgentAccessDTOSchema=z51.object({reads:z51.object({label:z51.string(),description:z51.string()}).nullable(),tools:z51.array(z51.object({tool:z51.string(),label:z51.string(),description:z51.string(),allowed:z51.boolean()}))})}});import{z as z52}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=z52.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance","agent_runtime_allowance"],UserManagedNotificationTopicSchema=z52.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z52.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z52.object({userId:z52.string().min(1),name:z52.string(),email:z52.string().min(1),subscribed:z52.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z52.object({maxSubscribers:z52.number().int().positive(),subscriberCount:z52.number().int().nonnegative(),effectiveRecipientCount:z52.number().int().nonnegative(),currentUserSubscribed:z52.boolean(),candidates:z52.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z52.object({userIds:z52.array(z52.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z52.object({topic:UserManagedNotificationTopicSchema,enabled:z52.boolean(),source:z52.enum(["default","explicit"])}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z52.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z52.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z52.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z52.string().nullable(),maskedEmail:z52.string().min(1),applied:z52.boolean(),expiresAt:z52.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z52.object({scheduleId:z52.string().min(1),scheduleName:z52.string(),projectId:z52.string().min(1),projectName:z52.string(),env:z52.string().min(1)}),FollowedSchedulesSchema=z52.object({schedules:z52.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z53}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=z53.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=z53.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z53.uuid(),env:z53.string().min(1),name:z53.string().min(1),cron:z53.string().min(1),command:z53.string().min(1),secretKeys:z53.array(z53.string().min(1)),enabled:z53.boolean(),lastRunAt:z53.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z53.string().nullable(),suspendedAt:z53.coerce.date().nullable().optional(),suspensionReason:z53.string().nullable().optional(),overPolicyReasons:z53.array(z53.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z53.object({name:z53.string().min(1).max(120),cron:z53.string().min(1).max(120),command:z53.string().min(1).max(500),secretKeys:z53.array(ProjectSecretKeySchema).default([]),enabled:z53.boolean().optional()}),UpdateProjectScheduleRequestSchema=z53.object({name:z53.string().min(1).max(120).optional(),cron:z53.string().min(1).max(120).optional(),command:z53.string().min(1).max(500).optional(),secretKeys:z53.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z53.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z53.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z53.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z53.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z53.object({maxRuns:z53.number().int().positive(),retentionDays:z53.number().int().positive().nullable(),outputRetentionDays:z53.number().int().positive(),maxOutputBytes:z53.number().int().positive()}),SchedulePolicyStateSchema=z53.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z53.object({code:z53.enum(["Free","PAYG","Starter","Premium","Pro"]),source:z53.enum(["cached_subscription","free_fallback"]),activeSchedules:z53.object({used:z53.number().int().nonnegative(),limit:z53.number().int().nonnegative()}),minCadenceMinutes:z53.number().int().positive(),maxRunMs:z53.number().int().positive(),concurrency:z53.object({used:z53.number().int().nonnegative(),limit:z53.number().int().positive()}),compute:z53.object({settledMs:z53.number().int().nonnegative(),activeMs:z53.number().int().nonnegative(),reservedMs:z53.number().int().nonnegative().optional(),includedMs:z53.number().int().nonnegative(),remainingMs:z53.number().int().nonnegative(),resetsAt:z53.coerce.date()}),upgrade:z53.object({code:z53.literal("Pro"),activeSchedulesLimit:z53.number().int().positive(),minCadenceMinutes:z53.number().int().positive(),maxRunMs:z53.number().int().positive(),maxConcurrentRuns:z53.number().int().positive(),computeIncludedMs:z53.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z53.array(z53.string())}),ProjectScheduleUsageSchema=z53.object({runCount:z53.number().int().nonnegative(),runsWithOutput:z53.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z53.object({id:z53.uuid(),scheduleId:z53.uuid(),projectId:z53.uuid(),env:z53.string().min(1),scheduleName:z53.string().min(1),command:z53.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z53.object({id:z53.string().min(1),name:z53.string().min(1)}).nullable(),queuedAt:z53.coerce.date(),startedAt:z53.coerce.date().nullable(),finishedAt:z53.coerce.date().nullable(),exitCode:z53.number().int().nullable(),errorCode:z53.string().nullable(),error:z53.string().nullable(),outputBytes:z53.number().int().nonnegative(),outputTruncated:z53.boolean(),outputExpiresAt:z53.coerce.date().nullable(),metadataExpiresAt:z53.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z53.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z53.coerce.date().nullable(),items:z53.array(z53.object({key:z53.string().min(1),updatedAt:z53.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z53.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z53.object({trigger:z53.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z53.object({limit:z53.coerce.number().int().min(1).max(100).default(25),cursor:z53.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z53.object({items:z53.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z53.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z53.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z53.object({items:z53.array(ProjectScheduleRunDTOSchema),nextCursor:z53.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z54}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=z54.enum(WORK_NOTIFICATION_TOPICS),PUBLICATION_NOTIFICATION_TOPICS=["publication_failed"],NOTIFICATION_TOPICS=[...WORK_NOTIFICATION_TOPICS,...PUBLICATION_NOTIFICATION_TOPICS,"database_quota_exceeded"],NotificationTopicSchema=z54.enum(NOTIFICATION_TOPICS),NOTIFICATION_DELIVERY_CADENCES=["immediate","daily","off"],NotificationDeliveryCadenceSchema=z54.enum(NOTIFICATION_DELIVERY_CADENCES),NOTIFICATION_CHANNELS=["email"],NotificationChannelSchema=z54.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z54.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z54.discriminatedUnion("kind",[z54.object({kind:z54.literal("user"),userId:z54.string().min(1)}).strict(),z54.object({kind:z54.literal("agent"),agentKey:z54.string().min(1).max(120),agentId:z54.uuid().optional()}).strict(),z54.object({kind:z54.literal("system")}).strict()]),NotificationSummarySchema=z54.string().trim().min(1).max(1200),ReportBriefPayloadSchema={title:z54.string().trim().min(1).max(120).optional(),brief:StoredReportBriefSchema.optional()},NotificationRunOutcomeSchema=z54.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z54.enum(["review","agent_requested","recovery"]),NotificationWorkSessionSchema=z54.object({sessionId:z54.uuid(),branch:z54.string().min(1),targetBranch:z54.string().min(1),revision:z54.string().min(1),fingerprint:z54.string().min(1)}),NotificationPayloadSchema=z54.discriminatedUnion("topic",[z54.object({topic:z54.literal("database_quota_exceeded"),incidentId:z54.uuid(),observedAt:z54.iso.datetime()}).strict(),z54.object({topic:z54.literal("agent_run_outcome"),threadId:z54.uuid(),invocationId:z54.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z54.object({topic:z54.literal("agent_retained_review"),threadId:z54.uuid().optional(),invocationId:z54.uuid().optional(),proposalId:z54.uuid().optional(),workSession:NotificationWorkSessionSchema.optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z54.object({topic:z54.literal("agent_conflict"),mergeId:z54.uuid(),threadId:z54.uuid().optional(),invocationId:z54.uuid().optional(),summary:NotificationSummarySchema.optional(),...ReportBriefPayloadSchema}).strict(),z54.object({topic:z54.literal("publication_failed"),publicationId:z54.uuid(),sourceBranch:z54.string().trim().min(1).max(120),failureCode:z54.string().trim().min(1).max(64),failedAt:z54.iso.datetime(),firstPublication:z54.boolean()}).strict()]),NotificationEnvelopeSchema=z54.object({id:z54.uuid(),projectId:z54.uuid(),sourceKey:z54.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z54.literal(1),payload:NotificationPayloadSchema,createdAt:z54.coerce.date()}),NotificationDeliveryStateSchema=z54.enum(["pending","deferred","sent","suppressed","failed"]),NotificationDeliverySchema=z54.object({id:z54.uuid(),notificationRecipientId:z54.uuid(),projectId:z54.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z54.number().int().nonnegative(),nextAttemptAt:z54.coerce.date().nullable(),lastAttemptAt:z54.coerce.date().nullable(),sentAt:z54.coerce.date().nullable(),failureCode:z54.string().max(80).nullable(),createdAt:z54.coerce.date(),updatedAt:z54.coerce.date()}),NotificationPreferenceSchema=z54.object({topic:WorkNotificationTopicSchema,channel:z54.literal("email"),enabled:z54.boolean(),cadence:NotificationDeliveryCadenceSchema.exclude(["off"]),effectiveCadence:NotificationDeliveryCadenceSchema,source:z54.enum(["default","explicit"])})}});import{z as z55}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=z55.enum(NOTIFICATION_PREFERENCE_GROUPS),FIMO_TOGGLE_PREFERENCE_ENTRY_IDS=["work_review.agent_conflict","publishing.publication_failed","schedule.schedule_health","schedule.schedule_compute_allowance","schedule.agent_runtime_allowance"],FimoTogglePreferenceEntryIdSchema=z55.enum(FIMO_TOGGLE_PREFERENCE_ENTRY_IDS),FIMO_DELIVERY_PREFERENCE_ENTRY_IDS=["work_review.agent_retained_review","work_review.agent_run_outcome"],FimoDeliveryPreferenceEntryIdSchema=z55.enum(FIMO_DELIVERY_PREFERENCE_ENTRY_IDS),MARKETING_PREFERENCE_ENTRY_PREFIX="marketing.",PreferenceSourceSchema=z55.enum(["default","explicit"]),EmailNotificationProviderSyncSchema=z55.enum(["synced","pending","unavailable"]),EmailNotificationPreferenceSchema=z55.object({enabled:z55.boolean(),source:PreferenceSourceSchema,providerSync:EmailNotificationProviderSyncSchema}).strict(),PROVIDER_SUBSCRIPTION_PLACEMENTS=["reports","product_news"],ProviderSubscriptionPlacementSchema=z55.enum(PROVIDER_SUBSCRIPTION_PLACEMENTS),PROVIDER_SUBSCRIPTION_SEMANTIC_IDS=["weekly_analytics"],ProviderSubscriptionSemanticIdSchema=z55.enum(PROVIDER_SUBSCRIPTION_SEMANTIC_IDS),NotificationPreferenceEntrySchema=z55.discriminatedUnion("kind",[z55.object({kind:z55.literal("toggle"),id:FimoTogglePreferenceEntryIdSchema,group:z55.enum(["work_review","publishing","schedule"]),enabled:z55.boolean(),source:PreferenceSourceSchema}).strict(),z55.object({kind:z55.literal("delivery"),id:FimoDeliveryPreferenceEntryIdSchema,group:z55.literal("work_review"),cadence:NotificationDeliveryCadenceSchema,source:PreferenceSourceSchema}).strict(),z55.object({kind:z55.literal("provider_subscription"),id:z55.string().startsWith(MARKETING_PREFERENCE_ENTRY_PREFIX),group:z55.literal("marketing"),name:z55.string(),description:z55.string().nullable(),placement:ProviderSubscriptionPlacementSchema,semanticId:ProviderSubscriptionSemanticIdSchema.nullable(),enabled:z55.boolean(),source:PreferenceSourceSchema}).strict()]),NotificationPreferenceCatalogSchema=z55.object({email:EmailNotificationPreferenceSchema,entries:z55.array(NotificationPreferenceEntrySchema),unavailableGroups:z55.array(NotificationPreferenceGroupSchema)}),NotificationPreferenceCatalogResponseSchema=createResponseSchema(NotificationPreferenceCatalogSchema),NotificationPreferenceEntryResponseSchema=createResponseSchema(NotificationPreferenceEntrySchema),UpdateEmailNotificationPreferenceRequestSchema=z55.object({enabled:z55.boolean()}).strict(),EmailNotificationPreferenceResponseSchema=createResponseSchema(EmailNotificationPreferenceSchema),UpdateNotificationPreferenceEntryRequestSchema=z55.discriminatedUnion("kind",[z55.object({kind:z55.literal("toggle"),enabled:z55.boolean()}).strict(),z55.object({kind:z55.literal("delivery"),cadence:NotificationDeliveryCadenceSchema}).strict(),z55.object({kind:z55.literal("provider_subscription"),enabled:z55.boolean()}).strict()])}});import{z as z56}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=z56.object({surface:SurfaceNameSchema,key:z56.string(),label:z56.string()}),InlineSchema=z56.object({text:z56.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z56.discriminatedUnion("type",[z56.object({type:z56.literal("paragraph"),content:z56.array(InlineSchema).max(24)}),z56.object({type:z56.literal("preview"),ref:DiffRefSchema,caption:z56.string().optional()}),z56.object({type:z56.literal("code"),code:z56.string(),lang:z56.string().optional(),caption:z56.string().optional()}),z56.object({type:z56.literal("risk"),level:z56.enum(["warning","error"]),content:z56.array(InlineSchema).max(24)}),z56.object({type:z56.literal("list"),items:z56.array(z56.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z56.object({headline:z56.string(),blocks:z56.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z56.object({summary:EnvDiffSummarySchema,fingerprint:z56.string(),generatedAt:z56.coerce.date(),cached:z56.boolean().optional(),credits:z56.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z57}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=z57.object({date:z57.string(),visitors:z57.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z57.object({key:z57.string(),visitors:z57.number().int().nonnegative(),pageviews:z57.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z57.object({path:z57.string(),pageName:z57.string().nullable().optional(),visitors:z57.number().int().nonnegative(),pageviews:z57.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z57.object({preset:z57.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z57.string(),requestedTo:z57.string(),effectiveFrom:z57.string(),effectiveTo:z57.string(),isRetentionLimited:z57.boolean(),groupBy:z57.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z57.object({date:z57.string(),content:z57.string(),updatedAt:z57.string(),updatedByUserId:z57.string()}),PROJECT_ANALYTICS_DEVICE_FILTERS=["bot","desktop","mobile","tablet"],ProjectPageviewAnalyticsDTOSchema=z57.object({range:ProjectAnalyticsRangeDTOSchema,deviceFilter:z57.enum(PROJECT_ANALYTICS_DEVICE_FILTERS).nullable(),visitors:z57.number().int().nonnegative(),pageviews:z57.number().int().nonnegative(),botPageviews:z57.number().int().nonnegative(),botVisitors:z57.number().int().nonnegative(),bounceRate:z57.number().min(0).max(100),viewsPerVisit:z57.number().nonnegative(),averageVisitDurationSeconds:z57.number().nonnegative(),visitorsSeries:z57.array(ProjectDailyVisitorsDTOSchema),topPages:z57.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z57.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z57.array(ProjectAnalyticsBreakdownItemDTOSchema),topBots:z57.array(ProjectAnalyticsBreakdownItemDTOSchema),topAiAssistants:z57.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z57.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z57.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z57.array(ProjectAnalyticsAnnotationDTOSchema)}),PROJECT_ANALYTICS_TRACKING_STATES=["observed","waiting","unavailable"],ProjectAnalyticsTrackingStatusDTOSchema=z57.object({state:z57.enum(PROJECT_ANALYTICS_TRACKING_STATES),lastEventAt:z57.string().nullable()}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsTrackingStatusDTO=createDTO(ProjectAnalyticsTrackingStatusDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z58}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=z58.object({id:z58.string(),email:z58.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z58.coerce.date(),createdAt:z58.coerce.date(),inviterUserId:z58.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z58.object({id:z58.string(),token:z58.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z58.object({success:z58.boolean(),projectId:z58.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z59}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=z59.object({id:z59.string(),name:z59.string(),image:z59.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z59.object({count:z59.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z59.object({counts:z59.object({signed_up:z59.int(),activated:z59.int()}),credits:z59.object({total:z59.int(),earned:z59.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z59.email(),emailVerified:z59.boolean(),createdAt:z59.coerce.date(),updatedAt:z59.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z60}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=z60.object({id:z60.string(),principalType:ProjectPrincipalTypeSchema,principalId:z60.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z60.coerce.date(),expiresAt:z60.coerce.date().nullable(),user:PublicUserDTOSchema.nullable(),organizationAdmin:z60.boolean().default(!1)}),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=z60.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z60.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z60.record(z60.string(),z60.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z60.object({access:z60.array(ProjectAccessItemDTOSchema),invites:z60.array(ProjectInviteDTOSchema),organization:z60.object({name:z60.string().nullable(),logo:z60.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z60.object({success:z60.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z60.object({success:z60.boolean(),projectId:z60.uuid()}))}});import{z as z61}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=z61.object({publicationStatus:PublicationStatusSchema,appUrl:z61.string().nullable(),lastPublishedAt:z61.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z62}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=z62.enum(["queued","building","ready","failed"]),BranchHostedPreviewSchema=z62.object({branch:BranchSchema,revision:z62.string().min(1).max(64).nullable(),generation:z62.string().min(1).max(64),status:BranchHostedPreviewStatusSchema,url:z62.url().nullable()})}});import{z as z63}from"zod";var PreviewUpgradeRequiredSchema,PreviewBridgePackageSchema,PreviewBridgeCapabilitySchema,SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,PreviewInstallApprovalTargetSchema,PreviewInstallRepairSchema,SandboxSessionInstallPolicyErrorSchema,PreviewStartFailureSchema,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=z63.object({code:z63.literal("PREVIEW_UPGRADE_REQUIRED"),message:z63.string(),currentVersion:z63.number().int().positive(),targetVersion:z63.literal(4)}),PreviewBridgePackageSchema=z63.object({name:z63.string().min(1),version:z63.string().min(1)}),PreviewBridgeCapabilitySchema=z63.object({integrated:z63.boolean(),packages:z63.array(PreviewBridgePackageSchema)}),SandboxSessionDTOSchema=z63.object({url:z63.url(),expiresAt:z63.iso.datetime().nullable(),source:z63.enum(["sandbox","hosted"]).optional(),previewBridge:PreviewBridgeCapabilitySchema.optional()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z63.object({name:z63.string().min(1),locator:z63.string().min(1).optional(),source:z63.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z63.object({kind:z63.literal("dependency_build_scripts_blocked"),packageManager:z63.enum(["pnpm","yarn","bun"]),packages:z63.array(z63.string()),targets:z63.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z63.string(),approvalKey:z63.string(),command:z63.string().optional(),approval:z63.object({id:z63.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z63.object({code:z63.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z63.string(),repair:PreviewInstallRepairSchema}),PreviewStartFailureSchema=z63.object({code:z63.literal("PREVIEW_START_FAILED"),message:z63.string(),logTail:z63.array(z63.string()).optional(),logTailTruncated:z63.boolean().optional()}),SandboxPullPhaseSchema=z63.enum(["acquire","pull","sync-env","install","restart","readiness"]),SandboxPullFailureCodeSchema=z63.enum(["sync_failed","readiness_failed","install_policy_blocked"]),SandboxPullFailureSchema=z63.object({message:z63.string(),code:SandboxPullFailureCodeSchema.optional().catch(void 0),phase:SandboxPullPhaseSchema.optional().catch(void 0),exitCode:z63.number().int().optional().catch(void 0),logTail:z63.array(z63.string()).optional().catch(void 0),logTailTruncated:z63.boolean().optional().catch(void 0),repair:PreviewInstallRepairSchema.optional().catch(void 0)}),PreviewInstallPolicyApprovalRequestSchema=z63.object({approvalId:z63.uuid()}),PreviewInstallPolicyApprovalEventSchema=z63.discriminatedUnion("type",[z63.object({type:z63.literal("progress"),step:z63.enum(["approval","install","restart","readiness"]),message:z63.string()}),z63.object({type:z63.literal("approved")}),z63.object({type:z63.literal("complete")}),z63.object({type:z63.literal("error"),code:z63.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z63.string()})])}});import{z as z64}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,OrganizationProjectCapacityDTOSchema,OrganizationProjectCapacityDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z64.string(),slug:z64.string().nullable(),logo:z64.string().nullable(),metadata:z64.record(z64.string(),z64.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z64.object({id:z64.string(),name:z64.string(),email:z64.email(),image:z64.string().nullable()}),OrganizationMemberDTOSchema=z64.object({id:z64.string(),userId:z64.string(),organizationId:z64.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z64.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema),OrganizationProjectCapacityDTOSchema=z64.object({canCreateProject:z64.boolean()}),OrganizationProjectCapacityDTO=createDTO(OrganizationProjectCapacityDTOSchema)}});import{z as z65}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=z65.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z65.object({reason:CancellationReasonCodeSchema,details:z65.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z65.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z65.object({offerVersion:z65.string().trim().min(1),unusedPremiumCreditAmount:z65.number().int().nonnegative(),amountDueNow:z65.number().int().nonnegative(),renewsOn:z65.string()}),PlanMigrationPreviewDTOSchema=z65.object({currency:z65.string().trim().min(1),unusedPremiumCreditAmount:z65.number().int().nonnegative(),amountDueNow:z65.number().int().nonnegative(),startsAt:z65.string(),renewsAt:z65.string(),nextRenewalAmount:z65.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z65.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z65.object({id:z65.string(),organizationId:z65.string(),legacySubscriptionId:z65.string(),offeredPlanCode:z65.string(),offeredPlanName:z65.string(),offeredPriceAmount:z65.number(),offeredCurrency:z65.string(),offerVersion:z65.string(),state:PlanMigrationStateSchema,checkoutToken:z65.string().nullable(),deadlineAt:z65.string(),transitions:z65.array(z65.object({event:z65.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z65.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z65.object({included:z65.number().optional(),unitPrice:z65.number().optional(),dailyCap:z65.number().nullable().optional()}),EntitlementsDTOSchema=z65.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z65.object({retentionDays:z65.number().int().positive(),canUseExtendedDateRanges:z65.boolean()}).optional(),history:z65.object({retentionDays:z65.number().int().positive()}).optional(),members:z65.object({canInvite:z65.boolean(),maxMembers:z65.number().int().positive().nullable()}).optional(),projects:z65.object({maxProjects:z65.number().int().positive().nullable()}).optional(),domains:z65.object({canUseCustomDomains:z65.boolean(),maxDomains:z65.number().int().nonnegative().nullable()}).optional(),media_storage:z65.object({limitBytes:z65.number().int().nonnegative()}).optional()}),MediaStorageUsageDTOSchema=z65.object({usedBytes:z65.number().int().nonnegative().nullable(),limitBytes:z65.number().int().nonnegative().nullable(),state:z65.enum(["ready","unavailable"]),measuredAt:z65.iso.datetime().nullable()}),MediaStorageUsageDTO=createDTO(MediaStorageUsageDTOSchema),PendingPlanChangeDTOSchema=z65.object({toPlanCode:TemplateCodeSchema,effectiveAt:z65.string(),scheduledAt:z65.string().nullable()}),AutomaticSpendStopDTOSchema=z65.object({fromPlanCode:TemplateCodeSchema,toPlanCode:TemplateCodeSchema,cutoffAt:z65.string(),spendStopped:z65.boolean(),settlementEndsAt:z65.string()}),HostingOverageStatusDTOSchema=z65.object({state:z65.enum(["ready","unavailable"]),planCode:z65.string(),overageAvailable:z65.boolean(),overageEnabled:z65.boolean(),monthlyCapUsd:z65.number().int().positive().nullable(),periodStart:z65.iso.datetime().nullable(),periodEnd:z65.iso.datetime().nullable(),usedBytes:z65.number().nonnegative().nullable(),includedBytes:z65.number().nonnegative().nullable(),overageBytes:z65.number().nonnegative(),currentOverageAmountMicros:z65.number().nonnegative().nullable(),totalExtraUsageAmountMicros:z65.number().nonnegative().nullable(),currency:z65.string().nullable(),status:z65.enum(["ok","near_limit","paused"]),databaseCompute:z65.object({includedHoursPerSite:z65.number().nonnegative().nullable(),overageHours:z65.number().nonnegative(),fundedHours:z65.number().nonnegative(),sitesOverAllowance:z65.number().int().nonnegative(),rateMicrosPerHour:z65.number().nonnegative().nullable(),amountMicros:z65.number().nonnegative().nullable(),budgetSpent:z65.boolean()}).nullable()}),HostingOverageStatusDTO=createDTO(HostingOverageStatusDTOSchema),UpdateHostingOverageRequestSchema=z65.object({enabled:z65.boolean(),monthlyCapUsd:z65.number().int().positive().max(1e6).optional()}).refine(value=>!value.enabled||value.monthlyCapUsd!==void 0,{message:"Enabling extra usage requires a monthly budget"}),SubscriptionDTOSchema=z65.object({id:z65.string(),external_id:z65.string(),customerId:z65.string(),planId:z65.string(),planCode:z65.union([TemplateCodeSchema,z65.literal("Unknown")]),currentPeriod:z65.object({start:z65.string(),end:z65.string().nullable()}),cancelAt:z65.string().nullable(),pendingPlanChange:PendingPlanChangeDTOSchema.nullable(),automaticSpendStop:AutomaticSpendStopDTOSchema.nullable(),entitlements:EntitlementsDTOSchema,currency:z65.string(),nextPaymentAt:z65.string().nullable(),baseAmount:z65.number().nullable()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z65.object({totalCap:z65.number(),dailyCap:z65.number(),usedTotal:z65.number()}),CreditBalanceDTOSchema=z65.object({total:z65.number(),base:z65.number(),dailyBase:z65.number(),purchases:z65.number(),awards:z65.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z65.object({total:z65.number(),nearLimit:z65.boolean(),canChat:z65.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z65.object({dailyFreeAvailable:z65.number(),monthlyAvailable:z65.number(),purchasedAvailable:z65.number(),awardedAvailable:z65.number()}),ProjectDailyCreditAllowanceDTOSchema=z65.object({periodCap:z65.number(),dailyGrant:z65.number(),usedThisPeriod:z65.number(),remainingThisPeriod:z65.number()}),ProjectCreditBalanceDTOSchema=z65.object({projectId:z65.uuid(),organizationId:z65.string(),balance:z65.object({totalAvailable:z65.number(),nearLimit:z65.boolean(),canUseAi:z65.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z65.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AutoRefillConfigDTOSchema=z65.discriminatedUnion("enabled",[z65.object({enabled:z65.literal(!0),thresholdUsd:z65.number().nonnegative(),refillAmountUsd:z65.number().nonnegative()}),z65.object({enabled:z65.literal(!1),thresholdUsd:z65.number().nonnegative().nullable(),refillAmountUsd:z65.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z65.discriminatedUnion("enabled",[z65.object({enabled:z65.literal(!0),thresholdUsd:z65.number().min(.01).multipleOf(.01),refillAmountUsd:z65.number().min(.01).multipleOf(.01),expectedRateToken:z65.string().trim().min(1).max(40)}).strict(),z65.object({enabled:z65.literal(!1),thresholdUsd:z65.number().min(.01).multipleOf(.01),expectedRateToken:z65.string().trim().min(1).max(40).optional()}).strict()]),OptionalSpendRefusalSchema=z65.enum(["no_subscription","plan_cannot_fund","pending_plan_exit"]),CreditPurchasePricingDTOSchema=z65.object({planCode:z65.union([TemplateCodeSchema,z65.literal("Unknown")]).nullable(),canPurchase:z65.boolean(),refusalReason:OptionalSpendRefusalSchema.nullable(),creditsPerDollar:z65.number().int().positive(),minAmountUsd:z65.number().positive(),maxAmountUsd:z65.number().positive(),rateToken:z65.string().nullable()}),CreditPurchasePricingDTO=createDTO(CreditPurchasePricingDTOSchema),PurchaseCreditsDTOSchema=z65.object({amountUsd:z65.number(),idempotencyKey:z65.string().trim().min(8).max(120),expectedRateToken:z65.string().trim().min(1).max(40)}).strict(),SuccessfulPurchaseDTOSchema=z65.object({invoiceId:z65.string(),newBalance:z65.int(),creditCount:z65.int(),amountUsd:z65.number(),creditsPerDollar:z65.int()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z65.object({url:z65.string()}),PortalDTO=createDTO(PortalDTOSchema),PaymentRecoveryInvoiceDTOSchema=z65.object({id:z65.string(),number:z65.string().nullable(),status:z65.string(),amountDue:z65.int(),currency:z65.string(),issuedAt:z65.string().nullable(),hostedInvoiceUrl:z65.string().nullable()}),PaymentRecoveryDTOSchema=z65.discriminatedUnion("status",[z65.object({status:z65.literal("eligible"),checkedAt:z65.string()}),z65.object({status:z65.literal("recovery_required"),checkedAt:z65.string(),invoice:PaymentRecoveryInvoiceDTOSchema,outstandingCount:z65.int().min(1)}),z65.object({status:z65.literal("unavailable"),checkedAt:z65.string(),reason:z65.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 z66}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=z66.object({brand:z66.string(),last4:z66.string(),exp:z66.string(),isDefault:z66.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z67}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=z67.string().superRefine((path52,ctx)=>{let segments=path52.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=z67.object({type:z67.literal("renameField"),contentType:z67.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z67.object({enabled:z67.boolean()}).strict(),ContentFieldGroupSchema=z67.object({id:z67.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z67.string().min(1).max(255),default:z67.boolean().optional()}).strict(),ContentTypeDTOSchema=z67.object({id:z67.string(),name:z67.string(),label:z67.string(),isSingleton:z67.boolean(),i18n:ContentTypeI18nSchema,groups:z67.array(ContentFieldGroupSchema).default([]),fields:z67.record(z67.string(),FieldDefinitionSchema),createdAt:z67.string(),updatedAt:z67.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z67.object({contentTypes:z67.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z67.object({id:z67.string(),entryId:z67.string(),documentId:z67.string(),slug:z67.string(),locale:z67.string().optional(),createdAt:z67.string(),updatedAt:z67.string(),__fimo:z67.object({contentType:z67.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z67.object({data:z67.array(EntryDTOSchema),meta:z67.object({limit:z67.number(),offset:z67.number(),total:z67.number(),hasMore:z67.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z67.object({contentType:z67.string(),count:z67.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z67.object({counts:z67.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z67.object({count:z67.number().int().nonnegative(),sourceLocale:z67.string(),targetLocale:z67.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z67.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z67.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z67.union([z67.string(),z67.number(),z67.boolean(),z67.null()]),entryWhereOperatorSchema=z67.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z67.array(entryWhereScalarSchema).optional(),$nin:z67.array(entryWhereScalarSchema).optional(),$contains:z67.string().optional(),$startsWith:z67.string().optional(),$null:z67.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z67.record(z67.string(),z67.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z67.record(z67.string(),z67.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z67.object({data:z67.record(z67.string(),z67.unknown()),locale:z67.string().min(1).optional(),documentId:z67.uuid().optional()}),entryIdsSchema=z67.array(z67.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z67.object({sql:z67.string().min(1)}),BulkCreateEntriesRequestSchema=z67.object({entries:z67.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z67.union([z67.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z67.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z67.object({updates:z67.array(z67.object({id:z67.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z67.union([z67.object({ids:entryIdsSchema,locale:z67.string().min(1).optional()}),z67.object({where:EntryWhereSchema,locale:z67.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z67.object({data:z67.array(z67.record(z67.string(),z67.unknown())),meta:z67.object({rowCount:z67.number().int().nonnegative(),truncated:z67.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z67.object({data:z67.array(EntryDTOSchema),meta:z67.object({created:z67.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z67.object({data:z67.array(EntryDTOSchema),meta:z67.object({updated:z67.number().int().nonnegative(),missing:z67.array(z67.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z67.object({data:z67.array(EntryDTOSchema),meta:z67.object({deleted:z67.number().int().nonnegative(),missing:z67.array(z67.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z68}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z68.object({index:z68.number().int().nonnegative(),contentType:z68.string(),field:z68.string(),value:z68.string(),against:z68.enum(["stored","batch"]),ownerDocumentId:z68.uuid().optional(),ownerIndex:z68.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z68.object({code:z68.literal("unique_conflict"),message:z68.string(),conflicts:z68.array(UniqueConflictSchema),truncated:z68.boolean().optional()})}});import{z as z69}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=z69.object({kind:z69.literal("unique_conflict"),contentType:z69.string(),field:z69.string(),value:z69.string(),documentCount:z69.number().int().positive(),documentIds:z69.array(z69.uuid()),documentIdsTruncated:z69.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z69.object({code:z69.literal("schema_transition_rejected"),message:z69.string(),issues:z69.array(SchemaTransitionIssueSchema),truncated:z69.boolean().optional()})}});import{z as z70}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=z70.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z70.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z70.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z70.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z70.object({field:CmsFieldNameSchema,direction:z70.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z70.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z70.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z70.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z70.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z70.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z71}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=z71.enum(MIGRATION_SOURCE_PLATFORMS)}});import{z as z72}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=z72.enum(CLIENT_TRACKED_EVENTS),TrackProjectEventRequestSchema=z72.object({event:ClientTrackedEventSchema,properties:z72.record(z72.string(),z72.unknown()).default({})})}});import{z as z73}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=z73.object({id:z73.string(),name:z73.string()}),AssetDTOSchema=z73.object({id:z73.string(),name:z73.string(),type:AssetTypeSchema,originalFileName:z73.string().nullable(),parentId:z73.string().nullable(),mimeType:z73.string().nullable(),fileSize:z73.number().nullable(),url:z73.string().nullable(),storageKey:z73.string().nullable(),createdAt:z73.string(),updatedAt:z73.string(),altText:z73.string().nullable().optional(),caption:z73.string().nullable().optional(),aiCaption:z73.string().nullable().optional(),aiAltText:z73.string().nullable().optional(),aiTags:z73.array(z73.string()).nullable().optional(),aiPrimaryColor:z73.string().nullable().optional(),aiProcessingStatus:z73.string().nullable().optional(),width:z73.number().nullable().optional(),height:z73.number().nullable().optional(),path:z73.array(AssetPathItemSchema).optional(),hasChildren:z73.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z73.lazy(()=>z73.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z73.array(AssetDTOSchema)),MediaStorageLimitErrorSchema=z73.object({error:z73.string(),code:z73.literal("media_storage_limit_exceeded"),usedBytes:z73.number().int().nonnegative(),limitBytes:z73.number().int().positive(),incomingBytes:z73.number().int().nonnegative()}),AssetReferenceScopeSchema=z73.enum(["current","main","live"]),ASSET_REFERENCE_IMPACT_FILE_LIMIT=50,AssetReferenceImpactRequestSchema=z73.object({assetIds:z73.array(z73.uuid()).min(1).max(ASSET_REFERENCE_IMPACT_FILE_LIMIT),scopes:z73.array(AssetReferenceScopeSchema).min(1).optional()}),AssetReferenceImpactSelectionDTOSchema=z73.object({totalFiles:z73.number().int().nonnegative(),checkedFiles:z73.number().int().nonnegative(),limit:z73.number().int().positive()}),AssetReferenceFindingDTOSchema=z73.object({assetId:z73.uuid(),entryId:z73.string(),documentId:z73.string(),contentType:z73.string(),locale:z73.string().nullable(),slug:z73.string(),fieldPath:z73.string()}),AssetReferenceScopeResultDTOSchema=z73.object({scope:AssetReferenceScopeSchema,label:z73.string(),state:z73.enum(["available","not-published","failed"]),coverage:z73.enum(["complete","partial","failed"]),referenceCount:z73.number().int().nonnegative().optional(),codeReferenceCount:z73.number().int().nonnegative().optional(),referencedAssetIds:z73.array(z73.uuid()).optional(),references:z73.array(AssetReferenceFindingDTOSchema),reason:z73.enum(["timeout","unavailable"]).optional()}),AssetReferenceScopeResultDTO=createDTO(AssetReferenceScopeResultDTOSchema),AssetReferenceImpactEventDTOSchema=z73.discriminatedUnion("type",[z73.object({type:z73.literal("selection"),data:AssetReferenceImpactSelectionDTOSchema}),z73.object({type:z73.literal("scope"),data:AssetReferenceScopeResultDTOSchema}),z73.object({type:z73.literal("complete")})]),AssetReferenceImpactEventDTO=createDTO(AssetReferenceImpactEventDTOSchema),AssetReferenceReplacementRequestSchema=z73.object({replacementAssetId:z73.uuid()}),AssetReferenceReplacementResultSchema=z73.object({referencesReplaced:z73.number().int().nonnegative(),entriesChanged:z73.number().int().nonnegative()}),AssetReferenceReplacementResponseSchema=createResponseSchema(AssetReferenceReplacementResultSchema),AssetReferenceReplacementPreviewResponseSchema=createResponseSchema(AssetReferenceReplacementResultSchema),AssetCodeReferenceReplacementResultSchema=z73.object({referencesReplaced:z73.number().int().nonnegative(),filesChanged:z73.number().int().nonnegative(),commitSha:z73.string().nullable()}),AssetReferenceReplacementErrorCodeSchema=z73.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=z73.object({error:z73.string(),code:AssetReferenceReplacementErrorCodeSchema}),ASSET_REMOVAL_ASSET_LIMIT=200,AssetRemovalIntentSchema=z73.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=z73.object({intent:AssetRemovalIntentSchema,assetIds:z73.array(z73.uuid()).min(1).max(ASSET_REMOVAL_ASSET_LIMIT),replacementAssetId:z73.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=z73.object({id:z73.uuid(),intent:AssetRemovalIntentSchema,assetIds:z73.array(z73.uuid()),replacementAssetId:z73.uuid().nullable(),expiresAt:z73.iso.datetime(),undoable:z73.boolean(),requestedByMe:z73.boolean()}),AssetRemovalOperationDTO=createDTO(AssetRemovalOperationDTOSchema),AssetRemovalScheduleResultDTOSchema=AssetRemovalOperationDTOSchema.extend({codeReplacement:AssetCodeReferenceReplacementResultSchema.optional()}),AssetRemovalScheduleResultDTO=createDTO(AssetRemovalScheduleResultDTOSchema),AssetRemovalErrorCodeSchema=z73.enum(["asset_removal.asset_not_found","asset_removal.replacement_not_found","asset_removal.already_finalized"]),AssetRemovalErrorSchema=z73.object({error:z73.string(),code:AssetRemovalErrorCodeSchema})}});import{z as z74}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z74.object({key:z74.string(),value:z74.string().optional(),defaultValue:z74.string(),locale:z74.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z75}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=z75.object({id:z75.string(),name:z75.string(),type:z75.enum(["file","folder"]),path:z75.string(),children:z75.lazy(()=>z75.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z75.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z75.object({path:z75.string(),exists:z75.boolean(),type:z75.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z76}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=z76.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),FormFieldValidationSchema=z76.object({minLength:z76.number().optional(),maxLength:z76.number().optional(),min:z76.number().optional(),max:z76.number().optional(),pattern:z76.string().optional(),maxFileSize:z76.number().optional(),accept:z76.array(z76.string()).optional()}),FormFieldSchema=z76.object({type:FormFieldTypeSchema,label:z76.string(),placeholder:z76.string().optional(),required:z76.boolean().optional(),defaultValue:z76.string().optional(),options:z76.array(z76.string()).optional(),validation:FormFieldValidationSchema.optional()}),FormFieldsSchema=z76.record(z76.string(),FormFieldSchema),FormContentSchema=z76.object({name:z76.string().min(1).max(255),label:z76.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 z77}from"zod";var ChatTaskStatusSchema,ChatTaskDTOSchema,ChatTaskListDTOSchema,init_chat_task_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat-task.dto.js"(){"use strict";ChatTaskStatusSchema=z77.enum(["queued","running","finished","failed","cancelled"]),ChatTaskDTOSchema=z77.object({id:z77.string().uuid(),label:z77.string(),status:ChatTaskStatusSchema,startedAt:z77.string(),endedAt:z77.string().nullable(),result:z77.string().nullable()}),ChatTaskListDTOSchema=z77.object({tasks:z77.array(ChatTaskDTOSchema)})}});import{z as z78}from"zod";var AgentPatchSchema,AgentToolRoutineSchema,AgentToolErrorCodeSchema,AgentToolResultSchema,AgentInstructionAuthorSchema,AgentInstructionRevisionDTOSchema,AgentInstructionRevisionListDTOSchema,AgentInstructionRevisionListResponseSchema,AgentInstructionRestoreSchema,init_chat_agent_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat-agent.dto.js"(){"use strict";init_response();init_chat_routine_dto();init_chat_dto();AgentPatchSchema=z78.object({name:z78.string().trim().min(1).max(120).optional(),description:z78.string().trim().min(1).max(300).optional(),instructions:ProjectChatInstructionsSchema.pipe(z78.string().min(1)).optional(),live:z78.literal(!0).optional()}),AgentToolRoutineSchema=z78.object({id:z78.string(),name:z78.string(),schedule:ChatRoutineScheduleSchema.nullable(),trigger:z78.string().nullable()}),AgentToolErrorCodeSchema=z78.enum(["plan_required","not_allowed","default_agent","not_seen","invalid"]),AgentToolResultSchema=z78.discriminatedUnion("ok",[z78.object({ok:z78.literal(!0),agent:z78.object({id:z78.string(),name:z78.string(),live:z78.boolean(),routines:z78.array(AgentToolRoutineSchema)}),revisionId:z78.string().optional()}),z78.object({ok:z78.literal(!1),error:z78.string(),code:AgentToolErrorCodeSchema.optional()})]),AgentInstructionAuthorSchema=z78.object({kind:z78.enum(["person","agent"]),id:z78.string().nullable(),name:z78.string().nullable()}),AgentInstructionRevisionDTOSchema=z78.object({id:z78.string().uuid(),previous:z78.string().nullable(),instructions:z78.string().nullable(),author:AgentInstructionAuthorSchema,createdAt:z78.string()}),AgentInstructionRevisionListDTOSchema=z78.object({revisions:z78.array(AgentInstructionRevisionDTOSchema)}),AgentInstructionRevisionListResponseSchema=createResponseSchema(AgentInstructionRevisionListDTOSchema),AgentInstructionRestoreSchema=z78.object({revisionId:z78.string().uuid()})}});import{z as z79}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=z79.object({url:z79.string().url(),key:z79.string(),size:z79.number(),contentType:z79.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z80}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=z80.object({canAccess:z80.boolean(),permissions:z80.record(z80.string(),z80.boolean()),role:z80.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z81}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:z81.string().trim().default(""),sort:z81.enum(["recent","name","relevance"]).default("recent"),category:z81.string().optional()})}});import{z as z82}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=z82.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z82.enum(["fimo","external"]),PaymentStatusSchema=z82.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z82.object({id:z82.string().uuid(),domain:z82.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z82.boolean(),price:z82.number().int().nullable(),renewalPrice:z82.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z82.string().nullable(),failureReason:z82.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z82.object({domain:z82.string(),available:z82.boolean(),premium:z82.boolean(),price:z82.number().nullable(),renewalPrice:z82.number().nullable(),purchaseType:z82.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z82.object({domain:z82.string(),price:z82.number().nullable(),renewalPrice:z82.number().nullable(),premium:z82.boolean(),allowedYears:z82.array(z82.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z82.object({firstName:z82.string().max(100),lastName:z82.string().max(100),companyName:z82.string().max(100).optional(),address1:z82.string().max(255),address2:z82.string().max(255).optional(),city:z82.string().max(100),state:z82.string().max(100),zip:z82.string().max(20),country:z82.string().max(2),phone:z82.string().max(30),email:z82.union([z82.string().email().max(255),z82.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z82.object({firstName:z82.string().min(1).max(100),lastName:z82.string().min(1).max(100),companyName:z82.string().max(100).optional(),address1:z82.string().min(1).max(255),address2:z82.string().max(255).optional(),city:z82.string().min(1).max(100),state:z82.string().min(1).max(100),zip:z82.string().min(1).max(20),country:z82.string().min(1).max(2),phone:z82.string().min(1).max(30),email:z82.string().email().max(255)}),SearchDomainsRequestSchema=z82.object({keyword:z82.string().min(1).max(100),tldFilter:z82.array(z82.string()).optional()}),CheckAvailabilityRequestSchema=z82.object({domains:z82.array(z82.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=z82.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z82.object({domain:DomainNameSchema,years:z82.number().int().min(1).max(10).optional().default(3),autoRenew:z82.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z82.object({autoRenew:z82.boolean().optional()}),RenewDomainRequestSchema=z82.object({years:z82.number().int().min(1).max(10).optional().default(1),autoRenew:z82.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z82.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z82.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z82.object({verified:z82.boolean(),email:z82.string().nullable(),verifyBy:z82.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z83}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=z83.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=z83.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=z83.object({txtName:z83.string().nullable().optional(),txtValue:z83.string().nullable().optional(),httpUrl:z83.string().nullable().optional(),httpBody:z83.string().nullable().optional(),cname:z83.string().nullable().optional(),cnameTarget:z83.string().nullable().optional()}),SSLValidationErrorSchema=z83.object({message:z83.string()}),OwnershipVerificationSchema=z83.object({type:z83.string(),name:z83.string(),value:z83.string()}),ProjectDomainSSLDTOSchema=z83.object({status:z83.string(),method:z83.string().nullable(),type:z83.string().nullable(),validationRecords:z83.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z83.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z83.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z83.enum(["subdomain","apex"]),RedirectConfigSchema=z83.object({type:z83.enum(["apex_to_www","www_to_apex"]),linkedDomainId:z83.string()}).nullable().optional(),ProjectDomainDTOSchema=z83.object({id:z83.string(),hostname:z83.string(),status:z83.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z83.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z83.string(),scdCnameTarget:z83.string().optional(),apexTargets:z83.array(z83.string()),dnsAutoConfigured:z83.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z83.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z83.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z83.object({hostname:z83.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:z83.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z83.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z83.object({available:z83.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z83.object({success:z83.boolean(),hostname:z83.string()}))}});import{z as z84}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=z84.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z84.object({available:z84.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z84.object({slug:z84.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z84.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z84.object({subdomain:z84.string(),subdomainUpdatedAt:z84.coerce.date()})),SubdomainSuggestionsQuerySchema=z84.object({base:z84.string().max(100).optional(),max:z84.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z84.object({suggestions:z84.array(z84.string())}))}});import{z as z85}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=z85.enum(PROJECT_TRANSFER_BLOCKER_CODES),ProjectTransferBlockerDTO=createDTO(z85.object({code:ProjectTransferBlockerCodeSchema,message:z85.string(),count:z85.number().int().nonnegative().optional()})),TransferProjectRequestSchema=z85.object({targetOrganizationId:z85.string().min(1)}),ProjectTransferResultDTO=createDTO(z85.object({projectId:z85.string(),sourceOrganizationId:z85.string(),targetOrganizationId:z85.string(),movedThreads:z85.number().int().nonnegative(),revokedInvites:z85.number().int().nonnegative(),revokedGrants:z85.number().int().nonnegative(),preservedGrants:z85.number().int().nonnegative(),warnings:z85.array(z85.string())}))}});import{z as z86}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=z86.enum(Object.keys(UNCLAIMED_PLAN.locked)),UNCLAIMED_CLAIM_STATES=["claimable","claimed","expired"],UnclaimedClaimStateSchema=z86.enum(UNCLAIMED_CLAIM_STATES),UNCLAIMED_PROJECT_ERROR_CODES=["project_unclaimed","unclaimed_limit_reached","unclaimed_deploy_limit","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=z86.enum(UNCLAIMED_PROJECT_ERROR_CODES),ProvisionUnclaimedProjectRequestSchema=z86.object({displayName:z86.string().trim().min(1).max(80),machineId:z86.string().trim().min(1).max(128).optional(),cliVersion:z86.string().trim().max(64).optional()}),UnclaimedProjectLimitsSchema=z86.object({ttlHours:z86.number().int().positive(),lockedFeatures:z86.array(UnclaimedLockedFeatureSchema),media:z86.object({totalBytes:z86.number().int().nonnegative(),fileBytes:z86.number().int().positive(),maxFiles:z86.number().int().nonnegative(),mimeTypes:z86.array(z86.string())}),database:z86.object({storageBytes:z86.number().int().positive(),computeSeconds:z86.number().int().positive(),maxComputeUnits:z86.number().positive()})}),UnclaimedProjectClaimSchema=z86.object({url:z86.string().url(),expiresAt:z86.coerce.date()}),ProvisionUnclaimedProjectResponseDTO=createDTO(z86.object({project:ProjectDTOSchema,token:z86.string(),claim:UnclaimedProjectClaimSchema,limits:UnclaimedProjectLimitsSchema})),UnclaimedClaimStatusDTO=createDTO(z86.object({state:UnclaimedClaimStateSchema,displayName:z86.string().nullable(),expiresAt:z86.coerce.date().nullable(),projectId:z86.string().nullable()})),UnclaimedClaimSecretSchema=z86.string().min(1).max(256),UnclaimedClaimStatusRequestSchema=z86.object({secret:UnclaimedClaimSecretSchema}),UnclaimedClaimStatesRequestSchema=z86.object({secrets:z86.array(UnclaimedClaimSecretSchema).min(1).max(20)}),UnclaimedClaimStatesResponseDTO=createDTO(z86.object({claims:z86.array(z86.object({state:UnclaimedClaimStateSchema,expiresAt:z86.coerce.date().nullable()}))})),ClaimUnclaimedProjectRequestSchema=z86.object({secret:UnclaimedClaimSecretSchema,organizationId:z86.string().min(1)}),ClaimUnclaimedProjectResultDTO=createDTO(z86.object({projectId:z86.string(),organizationId:z86.string()})),ProjectTokenSelfDTO=createDTO(z86.object({kind:z86.literal("project_token"),projectId:z86.string(),projectName:z86.string(),displayName:z86.string().nullable(),organizationId:z86.string().nullable(),organizationName:z86.string().nullable(),claimState:UnclaimedClaimStateSchema,expiresAt:z86.coerce.date().nullable(),tokenExpiresAt:z86.coerce.date().nullable()}))}});import{z as z87}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=z87.object({translated:z87.number().int().nonnegative(),total:z87.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z87.object({locale:z87.string(),isDefault:z87.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z87.object({defaultLocale:z87.string(),locales:z87.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z87.object({locale:z87.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z87.object({locale:z87.string().min(1).max(40)}),ProjectLocaleMutationSchema=z87.object({locale:z87.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z87.object({locale:z87.string(),entriesDeleted:z87.number().int().nonnegative(),labelsDeleted:z87.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z88}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=z88.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z88.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=z88.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z88.number(),credits:z88.number().optional(),billingMode:z88.enum(["fimo-credits","provider-account"]).optional(),confidence:z88.enum(["exact","estimated","metered"]),basis:z88.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z89}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=z89.object({options:z89.record(z89.string(),z89.unknown()),name:z89.string().optional(),parentId:z89.string().nullable().optional(),altText:z89.string().optional(),caption:z89.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z89.string().min(1).optional(),model:z89.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=z89.object({jobId:z89.string(),status:z89.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z89.string().nullable().optional(),credits:z89.number().optional(),costUsd:z89.number().optional(),billingMode:z89.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z89.object({error:z89.string(),code:z89.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:z89.array(GenerationTaskIdSchema).optional(),availableModels:z89.array(z89.string()).optional(),issues:z89.array(z89.unknown()).optional()})}});import{z as z90}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=z90.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z90.object({name:z90.string(),key:z90.string(),description:z90.string(),type:FlagTypeSchema,required:z90.boolean(),defaultValue:z90.unknown().optional(),enumValues:z90.array(z90.string()).optional(),isArray:z90.boolean()}),AssetModelPriceSchema=z90.object({unitPrice:z90.number(),unit:z90.string(),confidence:z90.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z90.object({id:z90.string(),shortName:z90.string(),provider:z90.string(),source:z90.string(),modality:z90.enum(["image","video","audio"]),tags:z90.array(z90.string()),displayName:z90.string(),description:z90.string(),flags:z90.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z90.object({model:z90.string(),costUsd:z90.number(),credits:z90.number(),billingMode:z90.enum(["fimo-credits","provider-account"]),confidence:z90.enum(["exact","estimated","metered"]),basis:z90.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z91}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=z91.object({tourId:z91.string(),version:z91.string(),status:z91.string(),completedAt:z91.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z91.array(UserTourDTOSchema))}});import{z as z92}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=z92.object({backendProfile:OpsBackendProfileSchema,provider:z92.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z92.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z92.object({backendProfile:OpsBackendProfileSchema,provider:z92.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z92.literal(!1),reason:z92.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z93}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=z93.object({packageManager:z93.string().trim().min(1).max(200).nullable(),trackedLockfiles:z93.array(z93.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z93.string().trim().min(1)}),OpsProjectPackageManagerSchema=z93.object({target:z93.object({backendProfile:OpsBackendProfileSchema,projectId:z93.uuid(),projectEnv:z93.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z94}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:z94.boolean().optional()}).strict(),OpsAgentChatAgentSpecSchema=z94.union([z94.object({name:z94.string().trim().min(1).max(120),description:z94.string().trim().min(1).max(2e3)}).strict(),z94.object({template:z94.string().trim().min(1).max(64)}).strict()]),OpsAgentChatSpecObjectSchema=z94.object({agent:OpsAgentChatAgentSpecSchema,routines:z94.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:z94.string().trim().min(1).max(1e3),dryRun:z94.boolean().optional()}).refine(uniqueRoutineNames,UNIQUE_ROUTINE_NAMES),OpsAgentChatOutcomeSchema=z94.enum(["created","existing","would_create"]),OpsAgentChatRoutineResultSchema=z94.object({id:z94.string().uuid().nullable(),name:z94.string(),schedule:ChatRoutineScheduleSchema.nullable(),nextRunAt:z94.string().nullable(),paused:z94.boolean(),outcome:z94.enum(["created","would_create"]),source:z94.enum(["spec","template"])}),OpsAgentChatCreateResultSchema=z94.object({target:z94.object({backendProfile:OpsBackendProfileSchema,projectId:z94.string().uuid()}),dryRun:z94.boolean(),applied:z94.boolean(),createdBy:z94.object({userId:z94.string()}),agent:z94.object({id:z94.string().uuid().nullable(),title:z94.string(),template:z94.string().nullable(),outcome:OpsAgentChatOutcomeSchema}),routines:z94.array(OpsAgentChatRoutineResultSchema),skipped:z94.array(z94.object({name:z94.string(),reason:z94.literal("routine_exists")})),refused:z94.array(z94.object({name:z94.string(),reason:ChatRoutineRefusalReasonSchema}))})}});import{z as z95}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=z95.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z95.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z95.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z95.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z95.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),EntryChangedWebhookEventDataSchema=z95.object({reason:WebhookEntryChangeReasonSchema,operationId:z95.string().optional(),batch:z95.object({index:z95.number().int().positive(),total:z95.number().int().positive()}).optional(),changes:z95.array(z95.object({action:WebhookEntryChangeActionSchema,contentType:z95.string(),id:z95.string(),documentId:z95.string(),locale:z95.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z95.object({form:z95.object({id:z95.string(),label:z95.string()}),submission:z95.object({id:z95.string(),data:z95.record(z95.string(),z95.unknown()),submittedAt:z95.string()})}),PublishStartedWebhookEventDataSchema=z95.object({publication:z95.object({status:z95.literal("publishing"),startedAt:z95.string()})}),PublishSucceededWebhookEventDataSchema=z95.object({publication:z95.object({status:z95.literal("published"),url:z95.string(),publishedAt:z95.string(),firstPublish:z95.boolean()})}),PublishFailedWebhookEventDataSchema=z95.object({publication:z95.object({status:z95.literal("failed"),reason:z95.string()})}),PublishUnpublishedWebhookEventDataSchema=z95.object({publication:z95.object({previousUrl:z95.string(),unpublishedAt:z95.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z95.object({report:z95.object({weekStart:z95.string(),weekEnd:z95.string(),pageviews:z95.number(),visitors:z95.number(),previousPageviews:z95.number(),previousVisitors:z95.number()})}),MediaAssetWebhookEventDataSchema=z95.object({id:z95.string().nullable(),name:z95.string().nullable(),type:z95.string(),mimeType:z95.string().nullable(),fileSize:z95.number().nullable()}),MediaUploadedWebhookEventDataSchema=z95.object({asset:MediaAssetWebhookEventDataSchema,operation:z95.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z95.object({asset:MediaAssetWebhookEventDataSchema,operation:z95.literal("updated")}),MediaDeletedWebhookEventDataSchema=z95.object({asset:MediaAssetWebhookEventDataSchema,operation:z95.literal("deleted")}),DomainCreatedWebhookEventDataSchema=z95.object({domain:z95.object({id:z95.string(),hostname:z95.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z95.object({domain:z95.object({id:z95.string(),hostname:z95.string()})}),LabelChangedWebhookEventDataSchema=z95.object({changes:z95.array(z95.object({action:z95.enum(["created","updated","deleted"]),key:z95.string(),locale:z95.string(),value:z95.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z95.object({locale:z95.object({code:z95.string(),isDefault:z95.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z95.object({locale:z95.object({code:z95.string(),previousCode:z95.string()})}),LocaleDeletedWebhookEventDataSchema=z95.object({locale:z95.object({code:z95.string(),entriesDeleted:z95.number().int().nonnegative(),labelsDeleted:z95.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z95.object({environment:z95.object({name:BranchSchema,parent:BranchSchema})}),EnvironmentDeletedWebhookEventDataSchema=z95.object({environment:z95.object({name:BranchSchema})}),EnvironmentMergedWebhookEventDataSchema=z95.object({merge:z95.object({id:z95.string(),from:BranchSchema,to:BranchSchema,applied:z95.array(z95.object({surface:SurfaceNameSchema,count:z95.number().int().nonnegative()}))})}),BranchRestoredWebhookEventDataSchema=z95.object({branch:z95.object({name:BranchSchema}),version:z95.object({versionId:z95.uuid(),name:z95.string()})}),WebhookEventFamilySchema=z95.enum(["entries","forms","publish","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z95.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z95.discriminatedUnion("source",[z95.object({source:z95.literal("literal"),value:z95.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z95.object({source:z95.literal("secret"),key:z95.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z95.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z95.object({name:z95.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z95.object({name:z95.string(),source:z95.enum(["literal","secret"]),secretKey:z95.string().nullable(),secretPrefix:z95.string().nullable(),configured:z95.literal(!0)}),WebhookFilterSchema=z95.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z95.string().min(1).max(255).optional(),mediaType:z95.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z95.string().min(1).max(255).optional(),locale:z95.string().min(1).max(120).optional()}),JsonValueSchema=z95.lazy(()=>z95.union([z95.string(),z95.number(),z95.boolean(),z95.null(),z95.array(JsonValueSchema),z95.record(z95.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z95.object({name:z95.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z95.url(),enabled:z95.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z95.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z95.boolean().optional().default(!0)}),UpdateProjectWebhookRequestSchema=z95.object({name:z95.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z95.url().optional(),enabled:z95.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z95.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z95.boolean().optional()}),TestProjectWebhookRequestSchema=z95.object({eventType:WebhookEventTypeSchema.optional(),data:z95.record(z95.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z95.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z95.uuid(),name:z95.string(),eventType:WebhookEventTypeSchema,enabled:z95.boolean(),destination:z95.object({host:z95.string(),maskedUrl:z95.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z95.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z95.boolean(),lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z95.coerce.date().nullable(),deliveryStats24h:z95.object({succeeded:z95.number().int().nonnegative(),failed:z95.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z95.uuid(),projectId:z95.uuid(),env:BranchSchema,environment:EnvironmentKeySchema,branch:BranchSchema,eventId:z95.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z95.number().int().positive(),test:z95.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z95.number().int().nonnegative(),responseStatus:z95.number().int().nullable(),lastErrorCode:z95.string().nullable(),lastErrorMessage:z95.string().nullable(),payloadAvailable:z95.boolean(),destination:z95.object({host:z95.string(),maskedUrl:z95.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z95.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z95.string().nullable(),qstashMessageId:z95.string().nullable(),deliveredAt:z95.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z95.object({items:z95.array(WebhookDeliveryDTOSchema),pagination:z95.object({page:z95.number().int().positive(),limit:z95.number().int().positive(),total:z95.number().int().nonnegative(),totalPages:z95.number().int().positive(),hasMore:z95.boolean()}),stats:z95.object({total:z95.number().int().nonnegative(),succeeded:z95.number().int().nonnegative(),failed:z95.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z95.object({id:z95.uuid(),deliveryId:z95.uuid(),attempt:z95.number().int().positive(),status:z95.enum(["delivering","succeeded","failed"]),responseStatus:z95.number().int().nullable(),durationMs:z95.number().int().nonnegative(),responseExcerpt:z95.string().nullable(),errorCode:z95.string().nullable(),errorMessage:z95.string().nullable(),createdAt:z95.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z95.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z95.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z96}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=z96.object({key:z96.literal("fimo-2"),enabled:z96.boolean(),dismissed:z96.boolean().default(!1),interacted:z96.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z97}from"zod";var SiteOnboardingStageSchema,SiteScanStatusSchema,SiteCloneStatusSchema,SiteRefusalCodeSchema,SiteRefusalSchema,SiteCheckGroupSchema,SiteScoreSchema,SITE_CHECKS,SiteCheckIdSchema,SiteCheckStatusSchema,SiteCheckEvidenceSchema,SiteCheckResultSchema,SiteReportGroupSchema,SiteRecommendationsSchema,SiteMarketSchema,SitePageViewSchema,SiteSectionStatusSchema,SiteComparisonSchema,SiteReportSchema,SiteTypeSchema,SiteTermsCategorySchema,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=z97.enum(["scanning","interviewing","reporting","open","expired","refused"]),SiteScanStatusSchema=z97.enum(["running","done","failed"]),SiteCloneStatusSchema=z97.enum(["not_started","running","paused","finished","failed"]),SiteRefusalCodeSchema=z97.enum(["invalid","private","not_found","tls","unreachable","redirect","error_page","bot_wall"]),SiteRefusalSchema=z97.object({code:SiteRefusalCodeSchema,suggestedUrl:z97.string().nullable()}),SiteCheckGroupSchema=z97.enum(["discovery","indexing","ai_crawlers","rendering","metadata","content","speed"]),SiteScoreSchema=z97.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=z97.enum(SITE_CHECKS.map(check=>check.id)),SiteCheckStatusSchema=z97.enum(["pass","partial","fail","not_scored"]),SiteCheckEvidenceSchema=z97.record(z97.string(),z97.union([z97.string(),z97.number(),z97.boolean(),z97.array(z97.string())])),SiteCheckResultSchema=z97.object({id:SiteCheckIdSchema,status:SiteCheckStatusSchema,evidence:SiteCheckEvidenceSchema}),SiteReportGroupSchema=z97.object({id:SiteCheckGroupSchema,score:z97.number().int().min(0).max(100).nullable()}),SiteRecommendationsSchema=z97.object({answers:z97.number().int().min(0),domains:z97.record(z97.string(),z97.number().int().min(0))}),SiteMarketSchema=z97.object({domain:z97.string(),competitors:z97.array(z97.string()),rankings:z97.array(z97.object({domain:z97.string(),averagePosition:z97.number().min(1).nullable()})),keywords:z97.array(z97.object({keyword:z97.string(),positions:z97.record(z97.string(),z97.number().int().min(1).nullable())})),recommendations:SiteRecommendationsSchema.optional(),names:z97.record(z97.string(),z97.string()).optional(),fetchedAt:z97.coerce.date()}),SitePageViewSchema=z97.object({url:z97.string(),title:z97.string().nullable(),description:z97.string().nullable(),h1:z97.string().nullable(),structuredData:z97.array(z97.string()),wordCount:z97.number().int().min(0),capturedAt:z97.coerce.date()}),SiteSectionStatusSchema=z97.enum(["pending","ready","failed","skipped"]),SiteComparisonSchema=z97.object({before:SitePageViewSchema.optional(),after:SitePageViewSchema.optional(),beforeStatus:SiteSectionStatusSchema.optional(),afterStatus:SiteSectionStatusSchema.optional(),beforeQueuedAt:z97.coerce.date().optional(),afterQueuedAt:z97.coerce.date().optional()}),SiteReportSchema=z97.object({siteUrl:z97.string(),scannedAt:z97.coerce.date(),seoScore:z97.number().int().min(0).max(100).nullable(),geoScore:z97.number().int().min(0).max(100).nullable(),groups:z97.array(SiteReportGroupSchema),checks:z97.array(SiteCheckResultSchema),blockers:z97.array(SiteCheckIdSchema).default([]),market:SiteMarketSchema.optional(),marketStatus:SiteSectionStatusSchema.optional(),marketQueuedAt:z97.coerce.date().optional(),comparison:SiteComparisonSchema.optional()}),SiteTypeSchema=z97.enum(["business","non_profit","portfolio","hobby","personal"]),SiteTermsCategorySchema=z97.enum(["violence","child_harm","harassment","hate","self_harm","adult","deception","scam"]),SiteUnderstandingSchema=z97.object({name:z97.string(),summary:z97.string(),audience:z97.string(),positioning:z97.string(),homepage:z97.string()}),SiteSuggestionSchema=z97.object({label:z97.string(),url:z97.string().nullable()}),SiteInterviewSuggestionsSchema=z97.record(z97.string(),z97.record(z97.string(),z97.array(SiteSuggestionSchema))),SiteInterviewAnswerSchema=z97.record(z97.string().max(50),z97.union([z97.string().trim().max(2e3),z97.array(z97.string().trim().min(1).max(200)).max(10)])),SiteInterviewSchema=z97.object({status:z97.enum(["waiting","drafting","ready","failed"]),siteType:SiteTypeSchema.nullable(),site:SiteUnderstandingSchema.nullable(),suggestions:SiteInterviewSuggestionsSchema,answers:z97.record(z97.string(),SiteInterviewAnswerSchema)}),AnswerSiteInterviewRequestSchema=z97.object({questionId:z97.string().min(1).max(50),answer:SiteInterviewAnswerSchema}),SiteFixesReportSchema=z97.object({fixes:z97.array(z97.object({checkId:SiteCheckIdSchema,status:z97.enum(["fixed","not_fixed","not_applicable"]),note:z97.string().trim().min(1).max(300)})).min(1).max(40)}),SiteOnboardingResultSchema=z97.object({fixes:SiteFixesReportSchema.nullable(),summary:z97.string().nullable()}),StartSiteOnboardingRequestSchema=z97.object({organizationId:z97.string().min(1),url:z97.string().trim().min(1).max(2048),locale:z97.string().trim().min(2).max(16).default("en")}),StartSiteOnboardingResponseSchema=createResponseSchema(z97.object({projectId:z97.string()})),SiteOnboardingRefusedResponseSchema=z97.object({error:z97.literal("site_refused"),refusal:SiteRefusalSchema}),SiteOnboardingStateSchema=z97.object({projectId:z97.string(),siteUrl:z97.string(),stage:SiteOnboardingStageSchema,scanStatus:SiteScanStatusSchema,cloneStatus:SiteCloneStatusSchema,cloneRetryAvailable:z97.boolean(),budgetExhausted:z97.boolean(),sponsored:z97.boolean(),outOfCredits:z97.boolean(),interview:SiteInterviewSchema.nullable(),cloneThreadId:z97.string().nullable(),welcomeThreadId:z97.string().nullable(),competitors:z97.array(z97.string()),report:SiteReportSchema.nullable(),reportExpiresAt:z97.coerce.date(),openedAt:z97.coerce.date().nullable(),bannerDismissed:z97.boolean()}),SiteOnboardingStateDTO=createDTO(SiteOnboardingStateSchema),SiteOnboardingStateResponseSchema=createResponseSchema(SiteOnboardingStateSchema.nullable()),RetrySiteOnboardingRequestSchema=z97.object({task:z97.enum(["interview","scan","clone"])}),SiteOnboardingOutcomeSchema=z97.enum(["finished","rebuilding","paused","failed","scan_failed","scanning","expired","refused","not_started"]),AdminSiteOnboardingsQuerySchema=z97.object({search:z97.string().trim().max(200).optional(),organizationId:z97.string().trim().min(1).max(200).optional(),startDate:z97.coerce.date().optional(),endDate:z97.coerce.date().optional(),outcomes:z97.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z97.array(SiteOnboardingOutcomeSchema).optional()),siteTypes:z97.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z97.array(SiteTypeSchema).optional()),page:z97.coerce.number().int().min(1).default(1),pageSize:z97.coerce.number().int().min(1).max(100).default(25)}),AdminSiteOnboardingDTOSchema=z97.object({projectId:z97.string(),projectName:z97.string(),organizationId:z97.string(),organizationName:z97.string().nullable(),ownerEmail:z97.string().nullable(),ownerName:z97.string().nullable(),siteUrl:z97.string(),stage:SiteOnboardingStageSchema,scanStatus:SiteScanStatusSchema,cloneStatus:SiteCloneStatusSchema,outcome:SiteOnboardingOutcomeSchema,sponsored:z97.boolean(),cloneRetries:z97.number(),siteType:SiteTypeSchema.nullable(),refusalCategory:SiteTermsCategorySchema.nullable(),interviewAnswers:z97.number(),interviewQuestions:z97.number().nullable(),seoScore:z97.number().nullable(),geoScore:z97.number().nullable(),spentUsd:z97.number(),budgetCapUsd:z97.number(),capReached:z97.boolean(),cloneSeconds:z97.number().nullable(),createdAt:z97.coerce.date(),openedAt:z97.coerce.date().nullable()}),AdminSiteOnboardingDTO=createDTO(AdminSiteOnboardingDTOSchema),AdminSiteOnboardingsResponseSchema=createResponseSchema(z97.object({onboardings:z97.array(AdminSiteOnboardingDTOSchema),page:z97.number(),limit:z97.number(),total:z97.number(),totalPages:z97.number()})),AdminSiteOnboardingStatsSchema=z97.object({total:z97.number(),outcomes:z97.record(SiteOnboardingOutcomeSchema,z97.number()),funnel:z97.object({started:z97.number(),confirmed:z97.number(),finished:z97.number(),opened:z97.number()}),bySiteType:z97.array(z97.object({siteType:SiteTypeSchema,total:z97.number(),finished:z97.number(),opened:z97.number()})),granularity:z97.enum(["hour","day"]),series:z97.array(z97.object({at:z97.coerce.date(),outcomes:z97.record(SiteOnboardingOutcomeSchema,z97.number())})),spentUsd:z97.object({total:z97.number(),average:z97.number().nullable()}),sponsored:z97.number(),paidByOrganization:z97.object({usd:z97.number(),credits:z97.number()}),capReached:z97.number(),cloneSeconds:z97.object({median:z97.number().nullable(),average:z97.number().nullable()})}),AdminSiteOnboardingStatsResponseSchema=createResponseSchema(AdminSiteOnboardingStatsSchema),AdminSiteOnboardingDetailSchema=z97.object({onboarding:AdminSiteOnboardingDTOSchema.extend({locale:z97.string(),cloneThreadId:z97.string().nullable(),paidByOrganizationUsd:z97.number()}),interview:SiteInterviewSchema.extend({invocationIds:z97.array(z97.string())}).nullable(),knowledgeWritten:z97.string().nullable(),knowledgeNow:z97.object({content:z97.string(),updatedAt:z97.coerce.date().nullable(),updatedBy:z97.string().nullable()}),report:SiteReportSchema.nullable()}),AdminSiteOnboardingDetailDTO=createDTO(AdminSiteOnboardingDetailSchema),AdminSiteOnboardingDetailResponseSchema=createResponseSchema(AdminSiteOnboardingDetailSchema)}});import{z as z98}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=z98.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z98.object({total:z98.number(),base:z98.number(),purchases:z98.number(),awards:z98.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z98.object({id:z98.string(),name:z98.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z98.object({type:z98.string(),brand:z98.string().nullable(),last4:z98.string().nullable(),expirationDate:z98.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z98.object({currency:z98.string(),nextPaymentAmount:z98.number().nullable(),nextPaymentAt:z98.string().nullable(),billingInterval:z98.string().nullable(),totalAmount:z98.number().nullable(),discountAmount:z98.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z98.object({id:z98.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z98.string().nullable(),currentPeriodEndsAt:z98.string().nullable(),renewsAt:z98.string().nullable(),cancelAt:z98.string().nullable(),renewAutomatically:z98.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z98.object({type:z98.enum(["low_balance","critical_balance","approaching_limit"]),message:z98.string(),estimatedPromptsRemaining:z98.number().nullable(),avgCostPerPrompt:z98.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z98.object({monthlyCredits:z98.number().nullable(),usedThisPeriod:z98.number(),remainingThisPeriod:z98.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z98.object({organizationId:z98.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z98.string().nullable(),tenureDays:z98.number().int().nonnegative(),capturedAt:z98.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z98.object({hasSubscription:z98.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z98.number().nullable(),alerts:z98.array(CreditAlertDTOSchema),portalUrl:z98.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z98.object({creditCount:z98.number().int().positive(),expiresAt:z98.string().datetime().nullable().optional(),message:z98.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z98.literal("free"),amountCents:z98.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z98.literal("purchase"),amountCents:z98.number().int().positive()}),CreditTopupRequestDTOSchema=z98.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z98.object({success:z98.boolean(),transactionId:z98.string().nullable(),newBalance:z98.number(),creditCount:z98.number(),type:z98.enum(["free","purchase"]),invoiceId:z98.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z99}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=z99.object({totalCredits:z99.number(),totalCostUsd:z99.number(),totalMessages:z99.number(),avgCostPerMessage:z99.number(),periodStart:z99.string().nullable(),periodEnd:z99.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z99.object({projectId:z99.string(),projectName:z99.string(),projectDisplayName:z99.string().nullable(),credits:z99.number(),costUsd:z99.number(),messages:z99.number(),percentage:z99.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z99.object({userId:z99.string(),userName:z99.string().nullable(),userEmail:z99.string().email().nullable(),credits:z99.number(),costUsd:z99.number(),messages:z99.number(),percentage:z99.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z99.object({date:z99.string(),credits:z99.number(),costUsd:z99.number(),messages:z99.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z99.object({userId:z99.string(),userName:z99.string().nullable(),userEmail:z99.string().email().nullable(),credits:z99.number(),costUsd:z99.number(),messages:z99.number(),percentage:z99.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z99.object({projectId:z99.string(),projectName:z99.string(),projectDisplayName:z99.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z99.array(UsageByUserForProjectDTOSchema),timeline:z99.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z99.object({summary:UsageSummaryDTOSchema,byProject:z99.array(UsageByProjectDTOSchema),byUser:z99.array(UsageByUserDTOSchema),timeline:z99.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z100}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=z100.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z100.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z100.object({startDate:z100.string().optional(),endDate:z100.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z100.coerce.number().int().positive().default(1),limit:z100.coerce.number().int().positive().max(100).default(20),sortBy:z100.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z100.string().optional(),activeOnly:z100.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z100.object({totalCredits:z100.number(),totalCostUsd:z100.number(),totalMessages:z100.number(),automatedMessages:z100.number(),avgCostPerMessage:z100.number(),avgCreditsPerMessage:z100.number(),periodStart:z100.string(),periodEnd:z100.string(),creditsChange:z100.number().nullable(),costChange:z100.number().nullable(),messagesChange:z100.number().nullable(),unattributedCredits:z100.number(),unattributedCostUsd:z100.number(),unattributedMessages:z100.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z100.object({date:z100.string(),credits:z100.number(),costUsd:z100.number(),messages:z100.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z100.object({organizationId:z100.string(),organizationName:z100.string(),credits:z100.number(),costUsd:z100.number(),messages:z100.number(),percentage:z100.number(),userCount:z100.number(),projectCount:z100.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z100.object({userId:z100.string(),userName:z100.string().nullable(),userEmail:z100.string().nullable(),userImage:z100.string().nullable(),organizationId:z100.string().nullable(),organizationName:z100.string().nullable(),credits:z100.number(),costUsd:z100.number(),messages:z100.number(),percentage:z100.number(),projectCount:z100.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z100.object({projectId:z100.string(),projectName:z100.string(),projectDisplayName:z100.string().nullable(),organizationId:z100.string(),organizationName:z100.string(),credits:z100.number(),costUsd:z100.number(),messages:z100.number(),percentage:z100.number(),userCount:z100.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z100.object({id:z100.string(),name:z100.string(),value:z100.number(),percentage:z100.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z100.object({day:z100.number(),hour:z100.number(),value:z100.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z100.object({summary:UsageOverviewSummaryDTOSchema,timeline:z100.array(UsageTimelinePointDTOSchema),topOrganizations:z100.array(OrganizationUsageRowDTOSchema),topUsers:z100.array(UserUsageRowDTOSchema),topProjects:z100.array(ProjectUsageRowDTOSchema),creditDistribution:z100.array(UsageDistributionItemDTOSchema),userDistribution:z100.array(UsageDistributionItemDTOSchema),heatmap:z100.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z100.object({page:z100.number(),limit:z100.number(),totalItems:z100.number(),totalPages:z100.number(),hasMore:z100.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z100.object({organizations:z100.array(OrganizationUsageRowDTOSchema),top:z100.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z100.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z100.object({users:z100.array(ExtendedUserUsageRowDTOSchema),top:z100.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z100.string(),ownerName:z100.string().nullable(),ownerEmail:z100.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z100.object({projects:z100.array(ExtendedProjectUsageRowDTOSchema),top:z100.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z100.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z100.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z100.object({credits:z100.number(),costUsd:z100.number(),messages:z100.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z100.object({id:z100.string(),name:z100.string(),createdAt:z100.string(),memberCount:z100.number(),projectCount:z100.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z100.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z100.object({id:z100.string(),name:z100.string().nullable(),email:z100.string(),image:z100.string().nullable(),createdAt:z100.string(),organizationCount:z100.number(),projectCount:z100.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z100.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z100.object({id:z100.string(),name:z100.string(),displayName:z100.string().nullable(),createdAt:z100.string(),organizationId:z100.string(),organizationName:z100.string(),ownerId:z100.string(),ownerName:z100.string().nullable(),ownerEmail:z100.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z100.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z101}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=z101.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z101.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z101.object({command:z101.string().min(1).max(1e4),cwd:z101.string().optional(),projectBranch:BranchSchema.optional(),projectEnv:BranchSchema.optional(),env:z101.record(z101.string(),z101.string()).optional(),name:z101.string().optional(),waitForCompletion:z101.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=z101.object({identifier:z101.string(),status:SandboxProcessStatusSchema,command:z101.string().optional(),startedAt:z101.string().optional(),exitCode:z101.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z101.object({processes:z101.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z101.object({processId:z101.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z101.object({success:z101.boolean(),message:z101.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z102}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=z102.enum(ADMIN_UNCLAIMED_STATES),AdminUnclaimedProjectsQuerySchema=z102.object({search:z102.string().trim().max(200).optional(),startDate:z102.coerce.date().optional(),endDate:z102.coerce.date().optional(),states:z102.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z102.array(AdminUnclaimedStateSchema).optional()),cliVersions:z102.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z102.array(z102.string().max(64)).optional()),page:z102.coerce.number().int().min(1).default(1),pageSize:z102.coerce.number().int().min(1).max(100).default(25)}),AdminUnclaimedProjectDTOSchema=z102.object({projectId:z102.string(),displayName:z102.string().nullable(),state:AdminUnclaimedStateSchema,cliVersion:z102.string().nullable(),createdAt:z102.coerce.date(),expiresAt:z102.coerce.date(),claimedAt:z102.coerce.date().nullable(),claimedOrganizationId:z102.string().nullable(),claimedOrganizationName:z102.string().nullable(),claimedByEmail:z102.string().nullable(),projectExists:z102.boolean(),previewUrl:z102.string().nullable(),hostingCostUsd:z102.number().nullable()}),AdminUnclaimedProjectDTO=createDTO(AdminUnclaimedProjectDTOSchema),AdminUnclaimedProjectsResponseSchema=createResponseSchema(z102.object({projects:z102.array(AdminUnclaimedProjectDTOSchema),page:z102.number(),limit:z102.number(),total:z102.number(),totalPages:z102.number()})),ClaimOutcomesSchema=z102.object({total:z102.number(),claimed:z102.number(),archived:z102.number(),claimRate:z102.number().nullable(),medianTimeToClaimSeconds:z102.number().nullable()}),AdminUnclaimedProjectStatsSchema=ClaimOutcomesSchema.extend({states:z102.record(AdminUnclaimedStateSchema,z102.number()),averageTimeToClaimSeconds:z102.number().nullable(),byCliVersion:z102.array(ClaimOutcomesSchema.extend({cliVersion:z102.string().nullable()})),granularity:z102.enum(["hour","day"]),series:z102.array(z102.object({at:z102.coerce.date(),states:z102.record(AdminUnclaimedStateSchema,z102.number()),alive:z102.number(),hostingCostUsd:z102.number()})),hostingCostUsd:z102.number(),costPerProjectUsd:z102.number().nullable(),leftovers:z102.object({overdue:z102.number(),claiming:z102.number(),archivedNotDeleted:z102.number()})}),AdminUnclaimedProjectStatsResponseSchema=createResponseSchema(AdminUnclaimedProjectStatsSchema)}});import{z as z103}from"zod";var WorkSessionVisibilitySchema,SessionSetRetentionSchema,init_work_sessions=__esm({"../../packages/api-contracts/dist/esm/work-sessions.js"(){"use strict";WorkSessionVisibilitySchema=z103.enum(["internal","user-visible"]),SessionSetRetentionSchema=z103.object({additionalDays:z103.number().int().min(1).max(30)}).strict()}});import{z as z104}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=z104.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=z104.object({content:ProjectKnowledgeContentSchema,updatedAt:z104.string().nullable(),updatedBy:z104.string().nullable()}),ProjectKnowledgeUpdateSchema=z104.object({content:ProjectKnowledgeContentSchema}),ProjectKnowledgeResponseSchema=createResponseSchema(ProjectKnowledgeDTOSchema),ProjectKnowledgeDraftDTOSchema=z104.object({id:z104.uuid(),status:z104.enum(["queued","running","ready","failed"]),content:ProjectKnowledgeContentSchema.nullable(),error:z104.string().nullable()}),ProjectKnowledgeDraftResponseSchema=createResponseSchema(ProjectKnowledgeDraftDTOSchema.nullable()),ProjectKnowledgeDraftStartSchema=z104.object({idempotencyKey:z104.uuid()})}});import{z as z105}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_args();init_commands();init_references2();init_types();init_chat_block();init_chat_block_state();init_admin_chat_block();init_admin_assistant();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_catalog_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_chat_task_dto();init_chat_agent_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();init_admin_monitoring_dto();init_platform();init_monitor();init_agent()}});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_types2=__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)}
|
|
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","Starter","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 isProcessControlEnvKey(key){return PROCESS_CONTROL_ENV_KEYS.has(key)||PROCESS_CONTROL_ENV_PREFIXES.some(prefix=>key.startsWith(prefix))}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(projectId2,branch,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId2}-${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,PROCESS_CONTROL_ENV_KEYS,PROCESS_CONTROL_ENV_PREFIXES,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_PREVIEW_PARENT_ORIGIN","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"],PROCESS_CONTROL_ENV_KEYS=new Set(["PATH","HOME","SHELL","BASH_ENV","ENV","PROMPT_COMMAND","USER","TMPDIR","HOST","HOSTNAME","PORT","NODE_ENV","NODE_OPTIONS","NODE_PATH","NODE_EXTRA_CA_CERTS","NODE_TLS_REJECT_UNAUTHORIZED","SSL_CERT_FILE","CURL_CA_BUNDLE","PYTHONPATH","LD_PRELOAD","LD_LIBRARY_PATH","HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY","FIMO_VALIDATION_BUILD","FIMO_SKIP_VERSION_CHECK","FIMO_EDITING_METADATA","FIMO_AGENT_TMP_DIR"]),PROCESS_CONTROL_ENV_PREFIXES=["GIT_","NPM_CONFIG_","PNPM_","YARN_","COREPACK_","BUN_","DENO_"];__name(isProcessControlEnvKey,"isProcessControlEnvKey");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,path52){let conditionPath=[...path52,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,path52)=>{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,path52));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path52,fieldName,variant.uid]);else walk(field.schema.fields,[...path52,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path52,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path52,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_agent_trace_budget_wrap_up_read","ops_context_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_memory_health_read","ops_routine_metrics_read","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_agent_runtime_attach","ops_billing_database_compute_attach","ops_billing_cache_invalidate","ops_billing_dispatch_discard","ops_billing_legacy_premium_enroll","ops_billing_legacy_premium_comp","ops_organization_feature_set","ops_billing_plan_transition_notices","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_signal_case_decision","ops_watch_save","ops_watch_report","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","ops_operation_plan","project_sync","project_thumbnail_regenerate","project_delete","project_import","organization_delete","credits_topup","credits_burn","user_session_revoke","user_ban","user_unban","user_impersonate","user_role_change","user_sessions_revoke","user_delete","platform_pool_change","platform_maintenance_change","platform_sync","platform_tenant_schema_sync","integration_event_replay","ops_billing_dispatch_retry","ops_billing_plan_projection_reconcile","ops_agent_chat_create","ops_pylon_issue_change","ops_pylon_note_create","ops_pylon_reply_preview","ops_pylon_reply_approve","ops_pylon_reply_send","admin_playground_run","ops_find","ops_project_health_read","ops_migrations_read","ops_operational_read","ops_billing_report_read","ops_users_read","ops_organizations_read","ops_merges_read","ops_platform_read","ops_watch_read","ops_notification_read","ops_audit_read"],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";var ORGANIZATION_FEATURES,AGENT_PLANS,AgentPlanSchema,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=["routine_planner","pro_agents"],AGENT_PLANS=["free","starter","pro"],AgentPlanSchema=z12.enum(AGENT_PLANS),OrganizationFeatureSchema=z12.enum(ORGANIZATION_FEATURES),OrganizationFeaturesDTOSchema=z12.object({features:z12.record(OrganizationFeatureSchema,z12.boolean()),lockedByPlan:z12.array(OrganizationFeatureSchema),agentPlan:AgentPlanSchema}),OrganizationFeaturesDTO=createDTO(OrganizationFeaturesDTOSchema),OrganizationFeatureStateDTOSchema=z12.object({feature:OrganizationFeatureSchema,enabled:z12.boolean(),default:z12.boolean(),lockedByPlan:z12.boolean(),override:z12.boolean().nullable(),reason:z12.string().nullable(),updatedBy:z12.string().nullable(),updatedAt:z12.string().datetime().nullable()}),OrganizationFeatureSetSchema=z12.object({state:z12.enum(["on","off","default"]),reason:z12.string().trim().min(1).max(500),apply:z12.boolean().default(!1),confirmProduction:z12.boolean().default(!1)})}});import{z as z13}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_SUPPORT_PRESET,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,OpsAgentTraceCostliestInputSchema,OpsAgentTraceSpansInputSchema,OpsSpanBodyEdgeSchema,OpsAgentTraceSpanInputSchema,OpsAgentTraceMessagesInputSchema,OpsAgentHealthGroupBySchema,OpsAgentHealthInputSchema,OPS_DATA_USAGE_MAX_WINDOW_MS,OpsDataUsageGroupBySchema,OpsDataUsageInputSchema,OPS_CONTEXT_HEALTH_MAX_WINDOW_MS,OpsContextHealthInputSchema,OPS_MEMORY_HEALTH_MAX_WINDOW_MS,OpsMemoryHealthInputSchema,opsChatHistoryWindow,OpsChatHistoryHealthInputSchema,OpsChatHistoryCallsInputSchema,OpsChatHistoryJudgeInputSchema,OPS_ROUTINE_METRICS_MAX_WINDOW_MS,OpsRoutineMetricsGroupBySchema,OpsRoutineMetricsSortBySchema,OpsRoutineMetricsInputSchema,OpsChatHistoryJudgeCalibrationInputSchema,OpsAgentTraceStatsGroupBySchema,OpsSpanTypeSchema,OpsAgentTraceStatsInputSchema,OpsAgentProviderErrorsInputSchema,OpsBillingCacheInvalidateInputSchema,OpsBillingEntitlementSyncInputSchema,OpsBillingAgentRuntimeAttachInputSchema,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,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_organization_features_dto();init_env();OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z13.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops: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","ops:users:read","ops:users:write","ops:organizations:read","ops:organizations:write","ops:merges:read","ops:merges:write","ops:platform:read","ops:platform:write","ops:project:admin","ops:credits:write"],OpsPermissionSchema=z13.enum(OPS_PERMISSIONS),OPS_SUPPORT_PRESET=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:users:read","ops:organizations:read","ops:merges:read","ops:platform:read","ops:billing:read","ops:support:read","ops:support:write","ops:customers:read","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:validations:read","ops:audit:read","ops:notification:preview"],OPS_PERMISSION_PRESETS={support:OPS_SUPPORT_PRESET,engineer:[...OPS_SUPPORT_PRESET,"ops:project:operate","ops:sentry:read","ops:sentry:write","ops:logs:read","ops:traces:read","ops:braintrust:read","ops:customers:write","ops:billing:write","ops:organization:features:write","ops:known-issues:write","ops:validations:write","ops:merges:write","ops:platform:write","ops:users:write"],full:[...OPS_PERMISSIONS]},OPS_SERVICE_PERMISSION_PRESETS={support:OPS_PERMISSION_PRESETS.support,engineer:OPS_PERMISSION_PRESETS.engineer,full:OPS_PERMISSION_PRESETS.full.filter(permission=>permission!=="ops:notification:approve")},OpsAccessGrantInputSchema=z13.object({permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),enabled:z13.boolean().default(!0)}),OpsServiceTokenInputSchema=z13.object({name:z13.string().trim().min(1).max(120),permissions:z13.array(OpsPermissionSchema).min(1),backendProfiles:z13.array(OpsBackendProfileSchema).min(1),expiresAt:z13.coerce.date()}).refine(input=>!input.permissions.includes("ops:notification:approve"),{path:["permissions"],message:"Service credentials cannot approve customer notifications"}).refine(input=>input.expiresAt.getTime()>Date.now(),{path:["expiresAt"],message:"Service credential expiry must be in the future"}),OpsCustomerProjectInputSchema=z13.object({importanceReason:z13.string().trim().min(1).max(1e3),ownerUserId:z13.string().trim().min(1).nullable().optional(),framework:z13.string().trim().max(120).nullable().optional(),packageManager:z13.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z13.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z13.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z13.object({projectId:z13.uuid(),title:z13.string().trim().min(1).max(240),userReport:z13.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z13.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z13.string().trim().max(1e4).nullable().optional(),outcome:z13.string().trim().max(1e4).nullable().optional(),evidence:z13.array(z13.record(z13.string(),z13.unknown())).max(100).optional()}).refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_KNOWN_ISSUE_STATUSES=["open","monitoring","resolved"],OpsKnownIssueStatusSchema=z13.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z13.object({fingerprint:z13.string().trim().min(1).max(240),title:z13.string().trim().min(1).max(240),description:z13.string().trim().min(1).max(1e4),affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z13.array(z13.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z13.string().trim().min(1).max(64).nullable().optional(),workaround:z13.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z13.array(z13.string().trim().min(1).max(120)).max(100),detectionQueries:z13.array(z13.string().trim().min(1).max(2e3)).max(50),status:OpsKnownIssueStatusSchema}).partial().refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_VALIDATION_OUTCOMES=["passed","failed","inconclusive"],OpsValidationOutcomeSchema=z13.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z13.object({changeReference:z13.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z13.string().trim().min(1).max(1e4),evidence:z13.array(z13.record(z13.string(),z13.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z13.object({recipientEmail:z13.email().optional(),subject:z13.string().trim().min(1).max(200).default("An update from Fimo"),message:z13.string().trim().min(1).max(5e3),locale:z13.string().trim().min(2).max(20),reason:z13.string().trim().min(1).max(1e3),acknowledgePolicy:z13.literal(!0)}),OpsPylonIssueIdSchema=z13.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsPylonReasonSchema=z13.string().trim().min(1).max(1e3),OpsPylonMessageSchema=z13.string().trim().min(1).max(5e3),OpsPylonMessageIdSchema=z13.string().trim().min(1).max(255),OpsPylonEmailListSchema=z13.array(z13.email()).max(50).default([]),OpsPylonResolveInputSchema=z13.object({reason:OpsPylonReasonSchema}),OpsPylonNoteInputSchema=z13.object({message:OpsPylonMessageSchema,reason:OpsPylonReasonSchema}),OpsPylonReplyPreviewInputSchema=z13.object({messageId:OpsPylonMessageIdSchema,message:OpsPylonMessageSchema,toEmails:OpsPylonEmailListSchema,ccEmails:OpsPylonEmailListSchema,bccEmails:OpsPylonEmailListSchema,reason:OpsPylonReasonSchema,acknowledgePolicy:z13.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=z13.string().trim().regex(/^[a-zA-Z0-9-]+$/).max(100),OpsSentryResolveInputSchema=z13.object({reason:z13.string().trim().min(1).max(1e3)}),OpsTraceIdSchema=z13.string().trim().regex(/^[a-fA-F0-9]{32}$/).transform(value=>value.toLowerCase()),OpsTraceReadInputSchema=z13.object({projectId:z13.uuid(),from:z13.coerce.date(),to:z13.coerce.date(),reason:z13.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=z13.string().trim().regex(/^[A-Za-z0-9_-]{1,200}$/),OpsAgentInvocationStatusSchema=z13.enum(["planned","running","finished","cancelled","errored","refused"]),OpsAgentTraceListInputSchema=z13.object({projectId:z13.uuid().optional(),organizationId:z13.string().trim().min(1).max(255).optional(),agentKey:z13.string().trim().min(1).max(120).optional(),threadId:z13.uuid().optional(),status:OpsAgentInvocationStatusSchema.optional(),since:z13.coerce.date().optional(),minCostUsd:z13.coerce.number().min(0).optional(),tracedOnly:z13.coerce.boolean().default(!1),limit:z13.coerce.number().int().min(1).max(100).default(25),reason:z13.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"}),OpsAgentTraceCostliestInputSchema=z13.object({since:z13.coerce.date(),until:z13.coerce.date(),limit:z13.coerce.number().int().min(1).max(50).default(25),reason:z13.string().trim().min(1).max(1e3)}).superRefine((input,ctx)=>{input.until<input.since&&ctx.addIssue({code:"custom",path:["until"],message:"until must be at or after since"}),input.until.getTime()-input.since.getTime()>744*60*60*1e3&&ctx.addIssue({code:"custom",path:["since"],message:"window must not exceed 31 days"})}),OpsAgentTraceSpansInputSchema=z13.object({limit:z13.coerce.number().int().min(1).max(500).default(200),reason:z13.string().trim().min(1).max(1e3)}),OpsSpanBodyEdgeSchema=z13.enum(["start","end"]).default("start"),OpsAgentTraceSpanInputSchema=z13.object({maxChars:z13.coerce.number().int().min(500).max(2e5).default(2e4),edge:OpsSpanBodyEdgeSchema,reason:z13.string().trim().min(1).max(1e3)}),OpsAgentTraceMessagesInputSchema=z13.object({messageIndex:z13.coerce.number().int().min(0).optional(),maxChars:z13.coerce.number().int().min(500).max(2e5).default(2e4),reason:z13.string().trim().min(1).max(1e3)}),OpsAgentHealthGroupBySchema=z13.enum(["agent","status","branch","project","day"]),OpsAgentHealthInputSchema=z13.strictObject({projectId:z13.uuid().optional(),organizationId:z13.string().trim().min(1).max(255).optional(),branch:BranchSchema.optional(),agentKey:z13.string().trim().min(1).max(120).optional(),since:z13.coerce.date(),until:z13.coerce.date().optional(),groupBy:OpsAgentHealthGroupBySchema.default("agent"),includeChildren:z13.coerce.boolean().default(!1),limit:z13.coerce.number().int().min(1).max(200).default(50),reason:z13.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=z13.enum(["operation","provider","day","organization","agent"]),OpsDataUsageInputSchema=z13.strictObject({organizationId:z13.string().trim().min(1).max(255).optional(),since:z13.coerce.date(),until:z13.coerce.date().optional(),groupBy:OpsDataUsageGroupBySchema.default("operation"),limit:z13.coerce.number().int().min(1).max(200).default(50),reason:z13.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=z13.object({projectId:z13.uuid().optional(),since:z13.coerce.date(),until:z13.coerce.date().optional(),limit:z13.coerce.number().int().min(1).max(1e3).default(500),reason:z13.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"}),OPS_MEMORY_HEALTH_MAX_WINDOW_MS=10080*60*1e3,OpsMemoryHealthInputSchema=z13.object({projectId:z13.uuid().optional(),since:z13.coerce.date(),until:z13.coerce.date().optional(),limit:z13.coerce.number().int().min(1).max(1e3).default(200),reason:z13.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_MEMORY_HEALTH_MAX_WINDOW_MS,{path:["since"],message:"memory health window cannot exceed 7 days"}),opsChatHistoryWindow={projectId:z13.uuid().optional(),since:z13.coerce.date(),until:z13.coerce.date().default(()=>new Date),reason:z13.string().trim().min(1).max(1e3)};__name(refineChatHistoryWindow,"refineChatHistoryWindow");OpsChatHistoryHealthInputSchema=refineChatHistoryWindow(z13.strictObject(opsChatHistoryWindow)),OpsChatHistoryCallsInputSchema=refineChatHistoryWindow(z13.strictObject({...opsChatHistoryWindow,limit:z13.coerce.number().int().min(1).max(500).default(100)})),OpsChatHistoryJudgeInputSchema=refineChatHistoryWindow(z13.strictObject({...opsChatHistoryWindow,sample:z13.coerce.number().int().min(1).max(25).default(10)})),OPS_ROUTINE_METRICS_MAX_WINDOW_MS=2160*60*60*1e3,OpsRoutineMetricsGroupBySchema=z13.enum(["routine","plan","day","project"]),OpsRoutineMetricsSortBySchema=z13.enum(["total","jev","runs"]),OpsRoutineMetricsInputSchema=z13.strictObject({projectId:z13.uuid().optional(),organizationId:z13.string().trim().min(1).max(255).optional(),plan:AgentPlanSchema.optional(),routine:z13.string().trim().min(1).max(64).optional(),groupBy:OpsRoutineMetricsGroupBySchema.default("routine"),sortBy:OpsRoutineMetricsSortBySchema.default("total"),burstMinutes:z13.coerce.number().int().min(1).max(120).default(10),since:z13.coerce.date(),until:z13.coerce.date().default(()=>new Date),reason:z13.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()<=OPS_ROUTINE_METRICS_MAX_WINDOW_MS,{path:["since"],message:"routine metrics windows cannot exceed 90 days"}),OpsChatHistoryJudgeCalibrationInputSchema=z13.strictObject({reason:z13.string().trim().min(1).max(1e3)}),OpsAgentTraceStatsGroupBySchema=z13.enum(["model","provider","span","type"]),OpsSpanTypeSchema=z13.enum(["llm","tool","function","task","score","eval"]),OpsAgentTraceStatsInputSchema=z13.object({since:z13.coerce.date(),until:z13.coerce.date().optional(),groupBy:OpsAgentTraceStatsGroupBySchema.default("model"),spanType:OpsSpanTypeSchema.optional(),slowerThanSeconds:z13.coerce.number().min(0).optional(),limit:z13.coerce.number().int().min(1).max(200).default(50),reason:z13.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=z13.object({since:z13.coerce.date(),until:z13.coerce.date().default(()=>new Date),model:z13.string().trim().min(1).max(120).optional(),provider:z13.string().trim().min(1).max(120).optional(),spanType:OpsSpanTypeSchema.optional(),before:z13.coerce.date().optional(),limit:z13.coerce.number().int().min(1).max(1e3).default(500),sampleChars:z13.coerce.number().int().min(200).max(2e4).default(1200),correlateInvocations:z13.boolean().default(!1),correlationLimit:z13.coerce.number().int().min(1).max(100).default(25),reason:z13.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=z13.object({reason:z13.string().trim().min(1).max(1e3)}),OpsBillingEntitlementSyncInputSchema=z13.object({reason:z13.string().trim().min(1).max(500),apply:z13.boolean().default(!1),confirmProduction:z13.boolean().default(!1),cursor:z13.string().min(1).optional(),batchSize:z13.number().int().min(1).max(100).default(50),concurrency:z13.number().int().min(1).max(10).default(2)}),OpsBillingAgentRuntimeAttachInputSchema=z13.object({reason:z13.string().trim().min(1).max(500),apply:z13.boolean().default(!1),confirmProduction:z13.boolean().default(!1),organizationIds:z13.array(z13.string().min(1)).min(1).max(100).optional(),cursor:z13.string().min(1).optional(),batchSize:z13.number().int().min(1).max(100).default(50)}),OPS_PROJECT_OPERATIONS=["runtime.bump","preview.restart","production.publish"],OpsProjectOperationKindSchema=z13.enum(OPS_PROJECT_OPERATIONS),ExactVersionSchema=z13.string().trim().regex(/^\d+\.\d+\.\d+$/,"Expected an exact version such as 0.11.0"),OpsProjectOperationPlanInputSchema=z13.discriminatedUnion("kind",[z13.object({kind:z13.literal("runtime.bump"),targetVersion:ExactVersionSchema}),z13.object({kind:z13.literal("preview.restart")})]),OPS_MIGRATIONS=["project.v3-to-v4"],OpsMigrationIdSchema=z13.enum(OPS_MIGRATIONS),OPS_MIGRATION_PLAN_STATUSES=["applicable","not_applicable","unknown"],OpsMigrationPlanStatusSchema=z13.enum(OPS_MIGRATION_PLAN_STATUSES),OPS_MIGRATION_CHANGE_ACTIONS=["create","rewrite","delete"],OpsMigrationChangeActionSchema=z13.enum(OPS_MIGRATION_CHANGE_ACTIONS),OpsMigrationDryRunInputSchema=z13.object({migrationId:OpsMigrationIdSchema,projectEnv:z13.string().trim().min(1).max(255).default("main"),reason:z13.string().trim().min(1).max(1e3)}),OpsProjectFilePathSchema=z13.string().trim().min(1).max(1024),OpsProjectFileReasonSchema=z13.string().trim().min(1).max(1e3),OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES=["pnpm-lock.yaml","bun.lockb","bun.lock","yarn.lock","package-lock.json"],OpsProjectPackageManagerInspectInputSchema=z13.object({reason:OpsProjectFileReasonSchema}),OpsProjectFileReadInputSchema=z13.object({path:OpsProjectFilePathSchema,reason:OpsProjectFileReasonSchema}),OpsProjectFileGlobInputSchema=z13.object({pattern:z13.string().min(1).max(300).optional(),limit:z13.coerce.number().int().min(1).max(2e3).default(2e3),reason:OpsProjectFileReasonSchema}),OpsProjectFileGrepInputSchema=z13.object({pattern:z13.string().min(1).max(200),include:z13.string().min(1).max(300).optional(),caseInsensitive:z13.boolean().default(!1),maxMatches:z13.coerce.number().int().min(1).max(200).default(100),reason:OpsProjectFileReasonSchema}),OPS_POSTHOG_EVENTS=["didCreateProject","didInitiateProject","didDeploy","didDeployProject","didFirstPublish"],OPS_POSTHOG_QUESTION="project-milestone-counts-v1",OpsPosthogTimestampSchema=z13.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=z13.strictObject({projectId:z13.uuid().transform(value=>value.toLowerCase()),from:OpsPosthogTimestampSchema,to:OpsPosthogTimestampSchema,reason:z13.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=z13.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=z13.strictObject({completeAggregate:z13.boolean(),truncated:z13.boolean().nullable(),sampled:z13.boolean().nullable(),pagination:z13.enum(["not_applicable","unexpected","unknown"]),providerFreshnessKnown:z13.literal(!1),providerAsOf:z13.null(),projectFilter:z13.literal("exact properties.projectId equality"),environmentFilterSupported:z13.literal(!1),excludesMissingProjectId:z13.literal(!0),transport:z13.literal("server"),consentCoverage:z13.literal("server-policy-not-browser-consent"),operationDedupeAvailable:z13.literal(!1)}),OpsPosthogCountsSchema=z13.array(z13.strictObject({event:z13.enum(OPS_POSTHOG_EVENTS),captureCount:z13.number().int().min(0).max(Number.MAX_SAFE_INTEGER)})).length(5).refine(counts=>counts.every((entry,i)=>entry.event===OPS_POSTHOG_EVENTS[i])),OpsPosthogMilestonesResponseSchema=z13.strictObject({schemaVersion:z13.literal(1),questionId:z13.literal(OPS_POSTHOG_QUESTION),backendProfile:OpsBackendProfileSchema,projectId:z13.uuid().nullable(),projectEnvironment:z13.literal("mixed_or_unrecorded"),window:z13.strictObject({from:z13.iso.datetime(),to:z13.iso.datetime(),bounds:z13.literal("[from,to)")}).nullable(),source:z13.literal("posthog"),sourceStatus:z13.enum(["available","unavailable","forbidden"]),failureCode:OpsPosthogFailureCodeSchema.nullable(),queriedAt:z13.iso.datetime(),auditId:z13.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=z13.object({reason:z13.string().trim().min(1).max(1e3),limit:z13.number().int().min(1).max(100).default(25),checkProvider:z13.boolean().default(!1)}),OpsProjectAnalyticsHealthInputSchema=z13.object({branch:z13.string().trim().min(1).max(255),canaryPath:z13.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:z13.iso.datetime({offset:!0}),until:z13.iso.datetime({offset:!0}),reason:z13.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 z14}from"zod";function resolveOpsTime(value,now=new Date){let relative3=RELATIVE_WINDOW.exec(value.trim());if(relative3){let amount=Number(relative3[1]),unit=relative3[2];return new Date(now.getTime()-amount*UNIT_MS[unit]).toISOString()}return new Date(value).toISOString()}function opsHoursSince(value,now=new Date){let start=Date.parse(resolveOpsTime(value,now));return Math.max(1,Math.ceil((now.getTime()-start)/UNIT_MS.h))}var RELATIVE_WINDOW,time,opsArgs,OPS_STANDARD_ARG_KEYS,UNIT_MS,init_args=__esm({"../../packages/api-contracts/dist/esm/ops/args.js"(){"use strict";RELATIVE_WINDOW=/^(\d+)(m|h|d|w)$/,time=z14.string().trim().min(1).max(64).refine(value=>RELATIVE_WINDOW.test(value)||!Number.isNaN(Date.parse(value)),{message:"Expected an ISO timestamp or a relative window such as 30m, 24h, 7d or 2w"}),opsArgs={project:z14.uuid().describe("Fimo project id"),org:z14.string().trim().min(1).max(255).describe("Organization id"),user:z14.string().trim().min(1).max(255).describe("User id"),env:z14.string().trim().min(1).max(255).describe("Project environment (branch), e.g. main or prod"),since:time.describe("Start of the window: ISO timestamp or relative (30m, 24h, 7d, 2w)"),until:time.describe("End of the window: ISO timestamp or relative (defaults to now)"),limit:z14.coerce.number().int().min(1).max(1e3).describe("Maximum results"),cursor:z14.string().trim().min(1).max(2e3).describe("Continue from a previous page"),query:z14.string().trim().min(1).max(200).describe("Free-text search"),reason:z14.string().trim().min(1).max(1e3).describe("Why this is being read or changed; stored in the audit log"),output:z14.string().trim().min(1).max(4096).describe("Write the result to this local file")},OPS_STANDARD_ARG_KEYS=Object.keys(opsArgs),UNIT_MS={m:6e4,h:36e5,d:864e5,w:6048e5};__name(resolveOpsTime,"resolveOpsTime");__name(opsHoursSince,"opsHoursSince")}});import{z as z15}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=z15.iso.datetime({offset:!0}).pipe(z15.coerce.date()),OpsRecentChatInputSchema=z15.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z15.string().trim().min(1).max(255).optional(),limit:z15.coerce.number().int().min(1).max(200).default(100),cursor:z15.string().trim().min(1).max(2e3).optional(),slim:z15.boolean().default(!0),reason:z15.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=z15.object({id:z15.string(),threadId:z15.string(),providerMessageId:z15.string().nullable(),invocationId:z15.string().nullable(),env:z15.string().nullable(),role:z15.string(),parts:z15.array(z15.record(z15.string(),z15.unknown())),metadata:z15.object({status:z15.string().optional(),traceUrl:z15.string().optional(),externalFileChanges:z15.array(z15.unknown()).optional()}),stats:z15.object({toolCount:z15.number().int().nonnegative(),failedToolCount:z15.number().int().nonnegative()}),createdAt:z15.iso.datetime({offset:!0}),project:z15.object({id:z15.string(),name:z15.string(),displayName:z15.string().nullable(),organizationId:z15.string().nullable()})}),OpsRecentChatResponseSchema=z15.object({target:z15.object({backendProfile:OpsBackendProfileSchema,projectEnv:z15.string().nullable()}),window:z15.object({from:z15.iso.datetime({offset:!0}),to:z15.iso.datetime({offset:!0})}),messages:z15.object({items:z15.array(OpsRecentChatMessageSchema),nextCursor:z15.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});var init_types=__esm({"../../packages/api-contracts/dist/esm/ops/types.js"(){"use strict"}});function compact(value){return Object.fromEntries(Object.entries(value).filter(([,entry])=>entry!==void 0))}function time2(value){return value===void 0?void 0:resolveOpsTime(value)}function seg(value){return encodeURIComponent(value)}var init_shared=__esm({"../../packages/api-contracts/dist/esm/ops/commands/shared.js"(){"use strict";init_args();__name(compact,"compact");__name(time2,"time");__name(seg,"seg")}});import{z as z16}from"zod";var invocation,span,OpsChatViewSchema,OpsChatViewsInputSchema,viewIds,ending,toolCallRow,appCallRow,turnRow,turnSlice,viewEnvelope,OpsChatViewsResponseDTO,agentCommands,init_agent=__esm({"../../packages/api-contracts/dist/esm/ops/commands/agent.js"(){"use strict";init_ops_chat_dto();init_ops();init_create_dto();init_args();init_types();init_shared();invocation=z16.string().trim().min(1).max(255).describe("Agent invocation (run) id"),span=z16.string().trim().min(1).max(255).describe("Braintrust span id"),OpsChatViewSchema=z16.enum(["tool-calls","app-calls","turns","slices"]),OpsChatViewsInputSchema=OpsRecentChatInputSchema.safeExtend({view:OpsChatViewSchema}),viewIds=z16.object({threadId:z16.string(),invocationId:z16.string().nullable(),projectId:z16.string(),messageId:z16.string()}),ending={terminal:z16.string(),terminalReason:z16.string().nullable()},toolCallRow=viewIds.extend({tool:z16.string(),subcommand:z16.string().nullable(),state:z16.string().nullable(),failed:z16.boolean(),errorSignature:z16.string().nullable(),position:z16.number().int().nonnegative(),recoveredNext:z16.boolean().nullable()}),appCallRow=viewIds.extend({routineId:z16.string().nullable(),via:z16.string(),integrationId:z16.string().nullable(),appTool:z16.string().nullable(),withApproval:z16.boolean(),outcome:z16.enum(["ok","failed","approval_required","blocked","pending"]),errorSignature:z16.string().nullable(),position:z16.number().int().nonnegative()}),turnRow=viewIds.extend({...ending,userMessageId:z16.string().nullable(),failureCategory:z16.enum(["expected_billing_stop","expected_model_refusal","expected_cancellation","workspace_failure","provider_model_failure","unknown_failure"]).nullable(),changes:z16.string().nullable(),mergeState:z16.string().nullable(),validation:z16.string().nullable(),publication:z16.string().nullable(),stepCount:z16.number().int().nonnegative(),toolCount:z16.number().int().nonnegative(),failedToolCount:z16.number().int().nonnegative(),hasTextReply:z16.boolean(),fimoAuthored:z16.boolean().nullable()}),turnSlice=viewIds.extend({...ending,previousUserAsk:z16.string().max(300),previousAgentWords:z16.string().max(500),userMessage:z16.string().max(1500),agentReply:z16.string().max(1305),failedToolCalls:z16.array(z16.object({tool:z16.string(),errorSignature:z16.string()})).max(6)}),viewEnvelope=z16.object({target:z16.object({backendProfile:OpsBackendProfileSchema,projectEnv:z16.string().nullable()}),window:z16.object({from:z16.iso.datetime({offset:!0}),to:z16.iso.datetime({offset:!0})})}),OpsChatViewsResponseDTO=createDTO(z16.discriminatedUnion("view",[viewEnvelope.extend({view:z16.literal("tool-calls"),messages:z16.object({items:z16.array(toolCallRow),nextCursor:z16.string().nullable()})}),viewEnvelope.extend({view:z16.literal("app-calls"),messages:z16.object({items:z16.array(appCallRow),nextCursor:z16.string().nullable()})}),viewEnvelope.extend({view:z16.literal("turns"),messages:z16.object({items:z16.array(turnRow),nextCursor:z16.string().nullable()})}),viewEnvelope.extend({view:z16.literal("slices"),messages:z16.object({items:z16.array(turnSlice),nextCursor:z16.string().nullable()})})])),agentCommands=[{id:"agent.chats.views",summary:"Read tool calls, app calls, turn outcomes or customer-text slices from a bounded chat window",permission:"ops:project:chat:read",effect:"read",input:z16.object({view:OpsChatViewSchema,since:opsArgs.since,until:opsArgs.until.optional(),env:opsArgs.env.optional(),limit:opsArgs.limit.max(200).default(100).describe("Source messages per page; each may produce several view rows"),cursor:opsArgs.cursor.optional(),reason:opsArgs.reason,output:opsArgs.output.optional().describe("Private JSON file; required for slices")}),request:__name(input=>({method:"POST",path:"/chat/messages/views",body:compact({view:input.view,from:time2(input.since),to:time2(input.until)??new Date().toISOString(),projectEnv:input.env,limit:input.limit,cursor:input.cursor,reason:input.reason})}),"request")},{id:"agent.chats.recent",summary:"Read recent chat messages across every project in a time window",permission:"ops:project:chat:read",effect:"read",input:z16.object({since:opsArgs.since,until:opsArgs.until.optional(),env:opsArgs.env.optional().describe("Only messages from this environment"),limit:opsArgs.limit.max(200).default(100),cursor:opsArgs.cursor.optional(),full:z16.boolean().default(!1).describe("Include complete message parts instead of the slim transcript"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/chat/messages/recent",body:compact({from:time2(input.since),to:time2(input.until)??new Date().toISOString(),projectEnv:input.env,limit:input.limit,cursor:input.cursor,slim:!input.full,reason:input.reason})}),"request")},{id:"agent.chats.create",summary:"Create an agent chat with routines in a customer project, as the organization owner. Validate the spec and confirm intent first: routines run and spend credits",permission:"ops:project:agents:write",effect:"write",risk:"low",input:z16.object({project:opsArgs.project,spec:z16.record(z16.string(),z16.unknown()).describe("JSON spec: { agent: { name, description } | { template }, routines: [...] }")}),cli:{fileArgs:["spec"]}},{id:"agent.traces.list",summary:"List agent runs for a project, organization or thread, with cost and status",permission:"ops:project:read",effect:"read",input:z16.object({project:opsArgs.project.optional(),org:opsArgs.org.optional(),thread:z16.uuid().optional().describe("Chat thread id"),agent:z16.string().trim().min(1).max(120).optional().describe("Agent key, e.g. chat.project"),status:OpsAgentInvocationStatusSchema.optional(),since:opsArgs.since.optional(),minCost:z16.coerce.number().min(0).optional().describe("Only runs costing at least this many USD"),tracedOnly:z16.boolean().default(!1).describe("Only runs that recorded a Braintrust root span"),limit:opsArgs.limit.max(100).default(25),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-traces/list",body:compact({projectId:input.project,organizationId:input.org,threadId:input.thread,agentKey:input.agent,status:input.status,since:time2(input.since),minCostUsd:input.minCost,tracedOnly:input.tracedOnly,limit:input.limit,reason:input.reason})}),"request")},{id:"agent.traces.costliest",summary:"Rank agent runs across projects by recorded cost, without content (maximum 31 days and 50 runs)",permission:"ops:project:read",effect:"read",input:z16.object({since:opsArgs.since,until:opsArgs.until.describe("Inclusive window end: ISO timestamp or relative (required)"),limit:opsArgs.limit.max(50).default(25),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-traces/costliest",body:{since:time2(input.since),until:time2(input.until),limit:input.limit,reason:input.reason}}),"request")},{id:"agent.traces.budget",summary:"List chats whose runs crossed the context budget and had to wrap up (content-free)",permission:"ops:braintrust:read",effect:"read",input:z16.object({since:opsArgs.since,until:opsArgs.until.optional(),limit:opsArgs.limit.max(25).default(25),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-traces/budget-wrap-up",body:compact({since:time2(input.since),until:time2(input.until),limit:input.limit,reason:input.reason})}),"request")},{id:"agent.traces.spans",summary:"List the spans of one agent run",permission:"ops:braintrust:read",effect:"read",input:z16.object({invocation,limit:opsArgs.limit.max(500).default(200),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/agent-traces/${seg(input.invocation)}/spans`,body:{limit:input.limit,reason:input.reason}}),"request")},{id:"agent.traces.span",summary:"Read one span body (input and output) of an agent run",permission:"ops:braintrust:read",effect:"read",input:z16.object({invocation,span,maxChars:z16.coerce.number().int().min(500).max(2e5).default(2e4).describe("Per-field character bound"),tail:z16.boolean().default(!1).describe("Return the end of an over-long body instead of the start"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/agent-traces/${seg(input.invocation)}/spans/${seg(input.span)}`,body:{maxChars:input.maxChars,edge:input.tail?"end":"start",reason:input.reason}}),"request")},{id:"agent.traces.messages",summary:"Read the conversation the model saw in one LLM span",permission:"ops:braintrust:read",effect:"read",input:z16.object({invocation,span,message:z16.coerce.number().int().min(0).optional().describe("Return this one message instead of the index"),maxChars:z16.coerce.number().int().min(500).max(2e5).default(2e4),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/agent-traces/${seg(input.invocation)}/spans/${seg(input.span)}/messages`,body:compact({messageIndex:input.message,maxChars:input.maxChars,reason:input.reason})}),"request")},{id:"agent.traces.stats",summary:"Aggregate agent step latency, tokens and cost by model, provider, span or type",permission:"ops:braintrust:read",effect:"read",input:z16.object({since:opsArgs.since,until:opsArgs.until.optional(),groupBy:OpsAgentTraceStatsGroupBySchema.default("model"),spanType:OpsSpanTypeSchema.optional(),slowerThan:z16.coerce.number().positive().optional().describe("Only steps at least this many seconds slow"),limit:opsArgs.limit.max(200).default(50),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-traces/stats",body:compact({since:time2(input.since),until:time2(input.until),groupBy:input.groupBy,spanType:input.spanType,slowerThanSeconds:input.slowerThan,limit:input.limit,reason:input.reason})}),"request")}]}});import{z as z17}from"zod";var assistantCommands,init_assistant=__esm({"../../packages/api-contracts/dist/esm/ops/commands/assistant.js"(){"use strict";init_args();init_types();init_shared();assistantCommands=[{id:"assistant.threads.list",summary:"List your admin assistant threads, newest activity first",permission:"ops:platform:read",effect:"read",input:z17.object({query:opsArgs.query.optional().describe("Match the thread title"),limit:z17.coerce.number().int().min(1).max(100).optional().describe("Maximum results"),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/assistant/threads",query:{q:input.query,limit:input.limit,cursor:input.cursor}}),"request")},{id:"assistant.threads.get",summary:"Read one admin assistant thread with every message",permission:"ops:platform:read",effect:"read",input:z17.object({thread:z17.uuid().describe("Admin assistant thread id")}),request:__name(input=>({method:"GET",path:`/assistant/threads/${seg(input.thread)}`}),"request")}]}});import{z as z18}from"zod";var day,billingCommands,init_billing=__esm({"../../packages/api-contracts/dist/esm/ops/commands/billing.js"(){"use strict";init_args();init_types();init_shared();day=z18.iso.date().describe("UTC day, YYYY-MM-DD"),billingCommands=[{id:"billing.customer",summary:"Read one Hyperline billing customer",permission:"ops:billing:read",effect:"read",input:z18.object({customer:z18.string().trim().min(1).max(255).describe("Hyperline customer id"),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/billing/customers/${seg(input.customer)}`,query:{reason:input.reason}}),"request")},{id:"billing.org",summary:"Read an organization's billing state: subscription, plan projection, credits and wallet",permission:"ops:billing:read",effect:"read",input:z18.object({org:opsArgs.org,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/billing/organizations/${seg(input.org)}`,query:{reason:input.reason}}),"request")},{id:"billing.bandwidth-contract",summary:"Read an organization's hosting bandwidth contract and current usage",permission:"ops:billing:read",effect:"read",input:z18.object({org:opsArgs.org,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/billing/organizations/${seg(input.org)}/bandwidth-contract`,query:{reason:input.reason}}),"request")},{id:"billing.ledger",summary:"Read an organization's credit ledger: holds, settlements, grants or usage events",permission:"ops:billing:read",effect:"read",input:z18.object({org:opsArgs.org,kind:z18.enum(["holds","settlements","grants","usage-events"]),since:opsArgs.since.optional(),limit:opsArgs.limit.max(200).default(100),cursor:opsArgs.cursor.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/ledger",query:compact({organizationId:input.org,kind:input.kind,since:time2(input.since),limit:input.limit,cursor:input.cursor,reason:input.reason})}),"request")},{id:"billing.plans.report",summary:"Find organizations whose local plan projection is missing or unusable (one page)",permission:"ops:billing:read",effect:"read",input:z18.object({cursor:opsArgs.cursor.optional().describe("Resume after this organization id"),at:z18.iso.datetime({offset:!0}).optional().describe("Reuse evaluatedAt when resuming a scan"),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/plan-projections/report",query:compact({reason:input.reason,at:input.at??new Date().toISOString(),cursor:input.cursor})}),"request")},{id:"billing.plans.reconcile",summary:"Repair organizations' local plan projections from Hyperline",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z18.object({orgs:z18.array(opsArgs.org).min(1).max(100).describe("Organization ids")})},{id:"billing.legacy-premium.report",summary:"Report legacy Premium organizations and where each stands in the Pro transition",permission:"ops:billing:read",effect:"read",input:z18.object({org:opsArgs.org.optional(),limit:opsArgs.limit.max(200).optional(),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/legacy-premium-report",query:compact({reason:input.reason,org:input.org,limit:input.limit})}),"request")},{id:"billing.legacy-premium.enroll",summary:"Record the approved Pro offer for one legacy Premium organization",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z18.object({org:opsArgs.org,deadline:z18.string().trim().min(1).max(64).describe("Decision date exactly 90 calendar days from today")})},{id:"billing.legacy-premium.comp",summary:"Accept an internal organization's Pro offer on its behalf, free through a 100% coupon",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z18.object({org:opsArgs.org,coupon:z18.string().trim().min(1).max(64).describe("Hyperline coupon id: 100% off every product")})},{id:"billing.legacy-premium.notify",summary:"Send the due legacy Premium transition notices for one organization",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z18.object({org:opsArgs.org})},{id:"billing.entitlements.sync",summary:"Reconcile subscription entitlement properties in Hyperline with Fimo's plans (one batch)",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z18.object({batchSize:z18.coerce.number().int().min(1).max(100).default(50),concurrency:z18.coerce.number().int().min(1).max(10).default(2),cursor:opsArgs.cursor.optional().describe("Resume after this organization id")})},{id:"billing.agent-runtime.attach",summary:"Attach the Agent runtime product to PAYG and Pro subscriptions (one batch)",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z18.object({orgs:z18.array(opsArgs.org).min(1).max(100).optional().describe("Only these organizations"),batchSize:z18.coerce.number().int().min(1).max(100).default(25),cursor:opsArgs.cursor.optional().describe("Resume after this organization id")})},{id:"billing.database-compute.attach",summary:"Attach the Database compute product to PAYG, Starter and Pro subscriptions (one batch)",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z18.object({orgs:z18.array(opsArgs.org).min(1).max(100).optional().describe("Only these organizations"),batchSize:z18.coerce.number().int().min(1).max(100).default(25),cursor:opsArgs.cursor.optional().describe("Resume after this organization id")})},{id:"billing.dispatches.list",summary:"List billing usage dispatches to Hyperline by state",permission:"ops:billing:read",effect:"read",input:z18.object({state:z18.enum(["pending","dispatched","dead-lettered","discarded"]),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/billing/dispatches",body:{state:input.state,reason:input.reason}}),"request")},{id:"billing.dispatches.discard",summary:"Discard dead-lettered billing dispatches so they are never sent",permission:"ops:billing:write",effect:"write",risk:"high",humanOnly:!0,input:z18.object({dispatches:z18.array(z18.uuid()).min(1).max(100).describe("Dispatch ids")})},{id:"billing.dispatches.retry",summary:"Retry a dead-lettered billing dispatch",permission:"ops:billing:write",effect:"write",risk:"low",input:z18.object({dispatch:z18.uuid().describe("Dispatch id")})},{id:"billing.cache.invalidate",summary:"Clear an organization's cached billing state so the next read goes to Hyperline",permission:"ops:billing:write",effect:"write",risk:"low",input:z18.object({org:opsArgs.org})},{id:"billing.hosting-usage.day",summary:"Read hosting usage recorded for one source, meter and day",permission:"ops:billing:read",effect:"read",input:z18.object({source:z18.string().trim().min(1).max(100),meter:z18.string().trim().min(1).max(100),day,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/hosting-usage",query:{source:input.source,meter:input.meter,day:input.day,reason:input.reason}}),"request")},{id:"billing.hosting-usage.reconciliation",summary:"Compare a project's served traffic with the hosting usage billed for one day",permission:"ops:billing:read",effect:"read",input:z18.object({project:opsArgs.project,day,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/hosting-usage/reconciliation",query:{projectId:input.project,day:input.day,reason:input.reason}}),"request")},{id:"billing.hosting-usage.periods",summary:"List an organization's hosting billing periods",permission:"ops:billing:read",effect:"read",input:z18.object({org:opsArgs.org,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/billing/hosting-usage/customer-periods",query:{organizationId:input.org,reason:input.reason}}),"request")}]}});import{z as z19}from"zod";var coreCommands,init_core=__esm({"../../packages/api-contracts/dist/esm/ops/commands/core.js"(){"use strict";init_args();init_types();init_shared();coreCommands=[{id:"find",summary:"Find projects, organizations or users by name, slug, domain, email or id",permission:"ops:project:read",effect:"read",input:z19.object({query:opsArgs.query,kind:z19.enum(["project","org","user"]).optional().describe("Only this kind of record"),limit:opsArgs.limit.max(100).default(20),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/find",query:compact({q:input.query,kind:input.kind,limit:input.limit,cursor:input.cursor})}),"request"),cli:{positional:"query"}},{id:"audit.list",summary:"List audit log entries, newest first",permission:"ops:audit:read",effect:"read",input:z19.object({project:opsArgs.project.optional(),org:opsArgs.org.optional(),actor:z19.string().trim().min(1).max(255).optional().describe("User or service principal id"),action:z19.string().trim().min(1).max(64).optional().describe("Audit action, e.g. project_takedown"),since:opsArgs.since.optional(),limit:opsArgs.limit.max(200).default(50)}),request:__name(input=>({method:"GET",path:"/audit",query:compact({projectId:input.project,organizationId:input.org,actor:input.actor,action:input.action,since:time2(input.since),limit:input.limit})}),"request")}]}});import{z as z20}from"zod";var window2,healthCommands,init_health=__esm({"../../packages/api-contracts/dist/esm/ops/commands/health.js"(){"use strict";init_organization_features_dto();init_ops();init_args();init_types();init_shared();window2={since:opsArgs.since,until:opsArgs.until.optional()},healthCommands=[{id:"health.overview",summary:"Platform health brief: Sentry, logs, agents, publishing and support in one window",permission:"ops:project:read",effect:"read",input:z20.object({...window2,project:opsArgs.project.optional().describe("Narrow every source that can be narrowed to one project"),limit:opsArgs.limit.max(100).default(25).describe("Maximum findings per source"),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/health",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,limit:input.limit,reason:input.reason})}),"request")},{id:"health.agents",summary:"Agent run outcomes, cost and duration grouped by agent, status, branch, project or day",permission:"ops:project:read",effect:"read",input:z20.object({...window2,project:opsArgs.project.optional(),org:opsArgs.org.optional(),env:opsArgs.env.optional(),agent:z20.string().trim().min(1).max(120).optional().describe("Agent key, e.g. chat.project"),groupBy:OpsAgentHealthGroupBySchema.default("agent"),includeChildren:z20.boolean().default(!1).describe("Count sub-steps too"),limit:opsArgs.limit.max(200).default(50),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-health",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,organizationId:input.org,branch:input.env,agentKey:input.agent,groupBy:input.groupBy,includeChildren:input.includeChildren,limit:input.limit,reason:input.reason})}),"request")},{id:"health.context",summary:"Context-window pressure and compaction facts for agent turns",permission:"ops:project:read",effect:"read",input:z20.object({...window2,project:opsArgs.project.optional(),limit:opsArgs.limit.max(1e3).default(500),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/context-health",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,limit:input.limit,reason:input.reason})}),"request")},{id:"health.memory",summary:"Agent memory health: threads and routines with missing or stale memory",permission:"ops:project:read",effect:"read",input:z20.object({...window2,project:opsArgs.project.optional(),limit:opsArgs.limit.max(1e3).default(200),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/memory-health",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,limit:input.limit,reason:input.reason})}),"request")},{id:"health.providers",summary:"Model provider errors grouped by signature, optionally correlated to agent runs",permission:"ops:braintrust:read",effect:"read",input:z20.object({...window2,model:z20.string().trim().min(1).max(200).optional(),provider:z20.string().trim().min(1).max(120).optional().describe("e.g. gateway or vertex"),spanType:OpsSpanTypeSchema.optional(),before:z20.string().trim().min(1).max(64).optional().describe("Page boundary: nextBefore from the previous page"),limit:opsArgs.limit.max(1e3).default(500).describe("Error spans to scan per page"),correlate:z20.boolean().default(!1).describe("Resolve the newest occurrences to Fimo runs"),correlationLimit:z20.coerce.number().int().min(1).max(100).default(25),sampleChars:z20.coerce.number().int().min(200).max(2e4).default(1200),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/agent-provider-errors",body:compact({since:time2(input.since),until:time2(input.until),model:input.model,provider:input.provider,spanType:input.spanType,before:input.before,limit:input.limit,sampleChars:input.sampleChars,correlateInvocations:input.correlate||void 0,correlationLimit:input.correlate?input.correlationLimit:void 0,reason:input.reason})}),"request")},{id:"health.chat-history.summary",summary:"How often agents call the chatHistory tool and whether it finds what they need",permission:"ops:project:read",effect:"read",input:z20.object({since:opsArgs.since.optional(),until:opsArgs.until.optional(),project:opsArgs.project.optional(),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/chat-history/health",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,reason:input.reason})}),"request")},{id:"health.chat-history.calls",summary:"List chatHistory tool calls; --with-content adds the surrounding messages (needs chat read)",permission:"ops:project:read",effect:"read",input:z20.object({since:opsArgs.since,until:opsArgs.until.optional(),project:opsArgs.project.optional(),limit:opsArgs.limit.max(500).default(100),withContent:z20.boolean().default(!1),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:input.withContent?"/chat-history/calls/content":"/chat-history/calls",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,limit:input.limit,reason:input.reason})}),"request")},{id:"health.chat-history.judge",summary:"Have a model judge a sample of chatHistory calls; --calibrate runs the labelled benchmark",permission:"ops:project:chat:read",effect:"read",input:z20.object({since:opsArgs.since.optional(),until:opsArgs.until.optional(),project:opsArgs.project.optional(),sample:z20.coerce.number().int().min(1).max(25).default(10),calibrate:z20.boolean().default(!1),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>input.calibrate?{method:"POST",path:"/chat-history/judge/calibration",body:{reason:input.reason}}:{method:"POST",path:"/chat-history/judge",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,sample:input.sample,reason:input.reason})},"request")},{id:"health.data-usage",summary:"Data-provider usage (search, scraping, enrichment) grouped by operation, provider, day, org or agent",permission:"ops:project:read",effect:"read",input:z20.object({...window2,org:opsArgs.org.optional(),groupBy:OpsDataUsageGroupBySchema.default("operation"),limit:opsArgs.limit.max(200).default(50),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/data-usage",body:compact({since:time2(input.since),until:time2(input.until),organizationId:input.org,groupBy:input.groupBy,limit:input.limit,reason:input.reason})}),"request")},{id:"health.routines",summary:"Routine runs, event bursts, Jev trigger calls and cost, by routine, plan, day or project",permission:"ops:project:read",effect:"read",input:z20.object({...window2,project:opsArgs.project.optional(),org:opsArgs.org.optional(),plan:AgentPlanSchema.optional().describe("The organization's agent plan now"),routine:z20.string().trim().min(1).max(64).optional().describe("Template routine key, or custom"),groupBy:OpsRoutineMetricsGroupBySchema.default("routine"),sortBy:OpsRoutineMetricsSortBySchema.default("total").describe("Rank buckets by total cost, Jev's trigger cost, or runs"),burstMinutes:z20.coerce.number().int().min(1).max(120).default(10).describe("An event this many minutes or less after the routine's previous one is a burst"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:"/routine-metrics",body:compact({since:time2(input.since),until:time2(input.until),projectId:input.project,organizationId:input.org,plan:input.plan,routine:input.routine,groupBy:input.groupBy,sortBy:input.sortBy,burstMinutes:input.burstMinutes,reason:input.reason})}),"request")},{id:"health.analytics",summary:"Whether a project's website analytics are arriving (content-free counts, max 7 days)",permission:"ops:project:read",effect:"read",input:z20.object({project:opsArgs.project,env:opsArgs.env.default("prod").describe("Environment whose traffic to check; prod for published traffic"),...window2,canaryPath:z20.string().max(300).optional().describe("Exact test path ending in ?fimo_monitor=<UUID>"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/projects/${seg(input.project)}/analytics-health`,body:compact({branch:input.env,canaryPath:input.canaryPath,since:time2(input.since),until:time2(input.until)??new Date().toISOString(),reason:input.reason})}),"request")},{id:"health.session",summary:"A project's work-session and database-branch health: cleanup due, unresolved allocations, capacity",permission:"ops:project:read",effect:"read",input:z20.object({project:opsArgs.project,checkProvider:z20.boolean().default(!1).describe("Include one bounded read-only Neon inventory page"),limit:opsArgs.limit.max(100).default(25),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:`/projects/${seg(input.project)}/session-health`,body:{reason:input.reason,limit:input.limit,checkProvider:input.checkProvider}}),"request")},{id:"health.sandbox",summary:"A project environment's sandbox and preview status",permission:"ops:project:read",effect:"read",input:z20.object({project:opsArgs.project,env:opsArgs.env.default("main"),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:`/projects/${seg(input.project)}/sandbox/status`,body:{projectEnv:input.env,reason:input.reason}}),"request")},{id:"health.schedules",summary:"Failed scheduled runs and webhook deliveries",permission:"ops:project:read",effect:"read",input:z20.object({project:opsArgs.project.optional(),env:opsArgs.env.optional(),schedule:z20.uuid().optional().describe("Schedule id"),run:z20.uuid().optional().describe("Schedule run id (needs --project)"),since:opsArgs.since.optional(),until:opsArgs.until.optional(),limit:opsArgs.limit.max(100).optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/schedules/failures",body:compact({projectId:input.project,projectEnv:input.env,scheduleId:input.schedule,runId:input.run,since:time2(input.since),until:time2(input.until),limit:input.limit,reason:input.reason})}),"request")},{id:"health.integrations",summary:"Failing integration connections and inbound events",permission:"ops:project:read",effect:"read",input:z20.object({project:opsArgs.project.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/integrations/failures",body:compact({projectId:input.project,reason:input.reason})}),"request")},{id:"health.domains",summary:"Custom domains with DNS, SSL or provider problems",permission:"ops:project:read",effect:"read",input:z20.object({project:opsArgs.project.optional(),org:opsArgs.org.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/domains/problems",body:compact({projectId:input.project,organizationId:input.org,reason:input.reason})}),"request")}]}});import{z as z21}from"zod";var mergeCommands,init_merge=__esm({"../../packages/api-contracts/dist/esm/ops/commands/merge.js"(){"use strict";init_args();init_types();init_shared();mergeCommands=[{id:"merge.list",summary:"List merges, newest first; --stuck lists only merges that stopped progressing",permission:"ops:merges:read",effect:"read",input:z21.object({project:opsArgs.project.optional(),stuck:z21.boolean().default(!1).describe("Only merges stuck in a non-terminal state"),status:z21.string().trim().min(1).max(64).optional().describe("Only merges in this status"),since:opsArgs.since.optional(),limit:opsArgs.limit.max(200).default(50),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/merges",query:compact({projectId:input.project,stuck:input.stuck||void 0,status:input.status,since:time2(input.since),limit:input.limit,cursor:input.cursor})}),"request")},{id:"merge.get",summary:"Show one merge with its steps, conflicts and release",permission:"ops:merges:read",effect:"read",input:z21.object({merge:z21.uuid().describe("Merge id")}),request:__name(input=>({method:"GET",path:`/merges/${seg(input.merge)}`}),"request")},{id:"merge.unwind",summary:"Force-unwind a stuck merge: reset the target branch to its pre-merge head and reopen the merge",permission:"ops:merges:write",effect:"write",risk:"high",humanOnly:!0,input:z21.object({merge:z21.uuid().describe("Merge id")})},{id:"merge.fail",summary:"Force-fail a stuck merge without touching the target branch",permission:"ops:merges:write",effect:"write",risk:"high",humanOnly:!0,input:z21.object({merge:z21.uuid().describe("Merge id")})}]}});var MONITORING_SEVERITIES,init_admin_monitoring_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin-monitoring.dto.js"(){"use strict";MONITORING_SEVERITIES=["critical","high","medium","low"]}});import{z as z22}from"zod";var OPS_SIGNAL_CASE_STATES,OpsSignalCaseStateSchema,OpsSignatureHashSchema,OPS_WATCH_STATES,OPS_WATCH_CLOSED_STATES,OPS_WATCH_CADENCES,OPS_WATCH_RESULTS,OPS_WATCH_MODELS,OPS_WATCH_EFFORTS,OpsWatchStateSchema,OpsWatchCadenceSchema,OpsWatchResultSchema,OpsWatchModelSchema,OpsWatchEffortSchema,OpsWatchSlugSchema,day2,watchText,watchRef,monitorCommands,init_monitor=__esm({"../../packages/api-contracts/dist/esm/ops/commands/monitor.js"(){"use strict";init_admin_monitoring_dto();init_args();init_types();init_shared();OPS_SIGNAL_CASE_STATES=["open","accepted","snoozed","dismissed","resolved"],OpsSignalCaseStateSchema=z22.enum(OPS_SIGNAL_CASE_STATES),OpsSignatureHashSchema=z22.string().trim().regex(/^[0-9a-f]{16}$/,"Expected a 16-character signature hash"),OPS_WATCH_STATES=["active","paused","met","missed","stopped"],OPS_WATCH_CLOSED_STATES=["met","missed","stopped"],OPS_WATCH_CADENCES=["daily","nightly","weekly"],OPS_WATCH_RESULTS=["on_track","problem","unknown"],OPS_WATCH_MODELS=["claude-opus-5-5","claude-fable-5-1","claude-sonnet-5-5","claude-haiku-5-5","gpt-6-astra","gpt-5.6-sol","gpt-5.6-luna"],OPS_WATCH_EFFORTS=["low","medium","high","xhigh","max"],OpsWatchStateSchema=z22.enum(OPS_WATCH_STATES),OpsWatchCadenceSchema=z22.enum(OPS_WATCH_CADENCES),OpsWatchResultSchema=z22.enum(OPS_WATCH_RESULTS),OpsWatchModelSchema=z22.enum(OPS_WATCH_MODELS),OpsWatchEffortSchema=z22.enum(OPS_WATCH_EFFORTS),OpsWatchSlugSchema=z22.string().trim().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"Expected a kebab-case slug").max(80),day2=z22.iso.date(),watchText=__name(max=>z22.string().trim().min(1).max(max),"watchText"),watchRef=z22.string().trim().min(1).max(80).describe("Watch slug or id"),monitorCommands=[{id:"monitor.checks.list",summary:"List staff checks with their schedule, action and last run",permission:"ops:investigations:read",effect:"read",input:z22.object({}),request:__name(()=>({method:"GET",path:"/monitor/checks"}),"request")},{id:"monitor.checks.try",summary:"Run one code check over a window, read-only, and show what it would open; nothing is stored (Jev and external checks are refused)",permission:"ops:investigations:read",effect:"read",input:z22.object({check:z22.string().trim().min(1).max(160).describe("Check id, e.g. agents/tools/errors/tool-failure-rate"),since:opsArgs.since,until:opsArgs.until.optional()}),request:__name(input=>({method:"POST",path:"/monitor/checks/try",body:compact({checkId:input.check,since:time2(input.since),until:time2(input.until)})}),"request")},{id:"monitor.cases.list",summary:"List cases opened by staff checks, newest activity first",permission:"ops:investigations:read",effect:"read",input:z22.object({state:OpsSignalCaseStateSchema.optional().describe("Only cases in this state"),check:z22.string().trim().min(1).max(160).optional().describe("Only cases from this check id, or from every check under a prefix ending in /"),minSeverity:z22.enum(MONITORING_SEVERITIES).optional().describe("Only cases at least this severe: critical, high, medium or low"),hash:OpsSignatureHashSchema.optional().describe("Only cases about this error signature hash: in the fingerprint or the evidence of the last 7 days"),limit:opsArgs.limit.max(200).default(50)}),request:__name(input=>({method:"POST",path:"/monitor/cases",body:compact({state:input.state,checkId:input.check,minSeverity:input.minSeverity,signatureHash:input.hash,limit:input.limit})}),"request")},{id:"monitor.signature.get",summary:"Resolve an error signature hash from case evidence to its tool, normalized error text, reach and example chats (window up to 7d)",permission:"ops:project:chat:read",effect:"read",input:z22.object({hash:OpsSignatureHashSchema.describe("Signature hash, e.g. from a case evidence signatureHash or topSignatures"),since:opsArgs.since.default("24h"),until:opsArgs.until.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/monitor/signatures",body:compact({hash:input.hash,since:time2(input.since),until:time2(input.until),reason:input.reason})}),"request")},{id:"monitor.cases.get",summary:"Read one case with its latest observations (ids and numbers only)",permission:"ops:investigations:read",effect:"read",input:z22.object({case:z22.uuid().describe("Case id")}),request:__name(input=>({method:"GET",path:`/monitor/cases/${seg(input.case)}`}),"request")},{id:"monitor.cases.update",summary:"Decide on a case: accept with a ceiling, snooze until a date, dismiss, resolve, or reopen",permission:"ops:investigations:write",effect:"write",risk:"low",input:z22.object({case:z22.uuid().describe("Case id"),state:OpsSignalCaseStateSchema.optional(),decisionReason:z22.string().trim().min(1).max(2e3).optional().describe("Why this decision; required to accept, snooze or dismiss. Shown on the finding"),ceiling:z22.number().nonnegative().optional().describe("For accepted: reopen above this metric"),snoozedUntil:z22.iso.datetime().optional().describe("For snoozed: reopen after this time"),linearIssue:z22.string().trim().regex(/^[A-Z]+-\d+$/).optional(),prUrl:z22.url().optional()})},{id:"monitor.watches.list",summary:"List watches with their model, effort, schedule, last result and next due time",permission:"ops:investigations:read",effect:"read",input:z22.object({state:z22.enum(["open","closed","all"]).default("open").describe("open: active and paused (default)")}),request:__name(input=>({method:"GET",path:"/monitor/watches",query:{state:input.state}}),"request")},{id:"monitor.watches.due",summary:"The active watches whose next run is due, each with its questions, reads, model and effort; `final` marks the run after the end date",permission:"ops:investigations:read",effect:"read",input:z22.object({}),request:__name(()=>({method:"GET",path:"/monitor/watches/due"}),"request")},{id:"monitor.watches.get",summary:"Read one watch with its definition and its latest runs",permission:"ops:investigations:read",effect:"read",input:z22.object({watch:watchRef}),request:__name(input=>({method:"GET",path:`/monitor/watches/${seg(input.watch)}`}),"request")},{id:"monitor.watches.save",summary:"Create a watch, or update the watch with this slug: its questions, reads, schedule, end date, model and effort, or pause, resume or stop it",permission:"ops:investigations:write",effect:"write",risk:"low",cli:{fileArgs:["change","rightAndWrong","ifWrong"]},input:z22.object({slug:OpsWatchSlugSchema.describe("Stable name, e.g. fimo-3175-app-calls"),title:watchText(240).optional().describe("The question in plain words. Required to create"),change:watchText(4e3).optional().describe('What changes for users and in which PR, or "standing" and the recurring question. Required to create'),questions:z22.array(watchText(1e3)).min(1).max(20).optional().describe("The calls to judge, asked both ways (repeatable). Required to create"),reads:z22.array(watchText(1e3)).min(1).max(20).optional().describe("What the run reads or needs (repeatable). Required to create"),rightAndWrong:watchText(4e3).optional().describe("What each verdict means, one example of each"),metWhen:watchText(1e3).optional().describe("For a temporary watch: when it is met"),ifWrong:watchText(4e3).optional().describe("The files a fix would change, and the eval or test that proves it"),cadence:OpsWatchCadenceSchema.optional().describe("Required to create"),startsOn:day2.optional().describe("First day it can run, YYYY-MM-DD (default today)"),endsOn:day2.optional().describe("Last day for a temporary watch, YYYY-MM-DD; without it the watch is standing"),standing:z22.boolean().optional().describe("Remove the end date: the watch runs until someone stops it"),model:OpsWatchModelSchema.optional().describe("The model that runs it (default claude-opus-5-5)"),effort:OpsWatchEffortSchema.optional().describe("Its reasoning effort (default high; max is Claude only)"),linearIssue:z22.string().trim().regex(/^[A-Z]+-\d+$/).optional().describe("The issue that owns the watch"),prUrls:z22.array(z22.url()).max(20).optional().describe("The PRs it watches (repeatable)"),state:z22.enum(["active","paused","stopped"]).optional().describe("Pause or resume it, or stop it with --close-reason"),closeReason:watchText(2e3).optional().describe("Why it stopped"),nextDueAt:z22.iso.datetime().optional().describe("Make it due at this time instead of its next slot")})},{id:"monitor.watches.report",summary:"Write one watch run's result: on_track, problem or unknown, with counts and alert ids; a final run closes it met or missed",permission:"ops:investigations:write",effect:"write",risk:"low",cli:{fileArgs:["summary"]},input:z22.object({watch:watchRef,result:OpsWatchResultSchema,summary:watchText(4e3).describe("What the run found, with counts and their denominator. No customer text"),judged:z22.number().int().nonnegative().optional().describe("Cases judged"),right:z22.number().int().nonnegative().optional(),wrong:z22.number().int().nonnegative().optional(),unclear:z22.number().int().nonnegative().optional(),caseIds:z22.array(z22.uuid()).max(50).optional().describe("Alerts the run opened or linked (repeatable)"),links:z22.array(z22.url()).max(20).optional().describe("Linear issues, PRs or receipts (repeatable)"),model:OpsWatchModelSchema.optional().describe("The model that ran it (default the watch's)"),effort:OpsWatchEffortSchema.optional().describe("Its effort (default the watch's)"),costUsd:z22.number().nonnegative().optional().describe("What the run cost at list price"),close:z22.enum(OPS_WATCH_CLOSED_STATES).optional().describe("Close the watch: met, missed, or stopped (reverted or replaced)"),closeReason:watchText(2e3).optional().describe("Why it closed; required with --close")})}]}});import{z as z23}from"zod";var channel,draft,notifyCommands,init_notify=__esm({"../../packages/api-contracts/dist/esm/ops/commands/notify.js"(){"use strict";init_ops();init_args();init_types();init_shared();channel=z23.enum(["email","pylon"]).describe("email (Resend, to the project owner) or pylon (ticket reply)"),draft=z23.uuid().describe("Draft id"),notifyCommands=[{id:"notify.draft",summary:"Draft a customer-visible message: an email to a project owner or a reply on a Pylon ticket",permission:"ops:notification:preview",effect:"write",risk:"low",input:z23.object({channel,message:z23.string().trim().min(1).max(5e3),project:opsArgs.project.optional().describe("email: the project whose owner receives it"),recipient:z23.email().optional().describe("email: override the recipient"),subject:z23.string().trim().min(1).max(200).optional().describe("email: subject line"),locale:z23.string().trim().min(2).max(20).optional().describe("email: message locale, e.g. en"),issue:OpsPylonIssueIdSchema.optional().describe("pylon: ticket id"),replyTo:z23.string().trim().min(1).max(255).optional().describe("pylon: top-level message id to reply to"),toEmails:z23.array(z23.email()).max(50).optional().describe("pylon: email recipients"),ccEmails:z23.array(z23.email()).max(50).optional(),bccEmails:z23.array(z23.email()).max(50).optional()}),cli:{fileArgs:["message"]}},{id:"notify.show",summary:"Show a drafted customer message and its approval state",permission:"ops:notification:preview",effect:"read",input:z23.object({channel,draft}),request:__name(input=>({method:"GET",path:input.channel==="pylon"?`/support/pylon/replies/${seg(input.draft)}`:`/notifications/${seg(input.draft)}`}),"request")},{id:"notify.approve",summary:"Approve a drafted customer message (a person must approve before it can be sent)",permission:"ops:notification:approve",effect:"write",risk:"low",humanOnly:!0,input:z23.object({channel,draft})},{id:"notify.send",summary:"Send an approved customer message",permission:"ops:notification:send",effect:"write",risk:"high",input:z23.object({channel,draft})}]}});function normalizeSentryIssueReference(reference){let trimmed=reference.trim();if(SENTRY_ISSUE_ID_PATTERN.test(trimmed))return trimmed;let url;try{url=new URL(trimmed)}catch{throw new Error("Expected a Sentry issue id or /issues/<id>/ URL")}let segments=url.pathname.split("/").filter(Boolean),issuesIndex=segments.lastIndexOf("issues"),issueId=issuesIndex>=0&&issuesIndex===segments.length-2?segments[issuesIndex+1]:void 0;if(!issueId||!SENTRY_ISSUE_ID_PATTERN.test(issueId))throw new Error("Expected a Sentry issue id or /issues/<id>/ URL");return issueId}function collectTraceIds(value,candidates,depth=0){if(!(depth>32)){if(typeof value=="string"){TRACE_ID_PATTERN.test(value.trim())&&candidates.add(value.trim().toLowerCase());return}if(Array.isArray(value)){for(let item of value)collectTraceIds(item,candidates,depth+1);return}if(typeof value=="object"&&value!==null)for(let item of Object.values(value))collectTraceIds(item,candidates,depth+1)}}function normalizeTempoTraceReference(reference){let trimmed=reference.trim();if(TRACE_ID_PATTERN.test(trimmed))return trimmed.toLowerCase();let url;try{url=new URL(trimmed)}catch{throw new Error("Expected an exact 32-character trace id or a Grafana trace URL")}let candidates=new Set;for(let segment of url.pathname.split("/"))collectTraceIds(segment,candidates);for(let value of url.searchParams.values()){collectTraceIds(value,candidates);try{collectTraceIds(JSON.parse(value),candidates)}catch{continue}}if(candidates.size!==1)throw new Error(candidates.size===0?"Grafana URL did not contain a trace id":"Grafana URL contained multiple trace ids");return[...candidates][0]}var SENTRY_ISSUE_ID_PATTERN,TRACE_ID_PATTERN,init_references2=__esm({"../../packages/api-contracts/dist/esm/ops/references.js"(){"use strict";SENTRY_ISSUE_ID_PATTERN=/^[a-zA-Z0-9-]{1,100}$/,TRACE_ID_PATTERN=/^[a-fA-F0-9]{32}$/;__name(normalizeSentryIssueReference,"normalizeSentryIssueReference");__name(collectTraceIds,"collectTraceIds");__name(normalizeTempoTraceReference,"normalizeTempoTraceReference")}});import{z as z24}from"zod";function parseWhere(values){if(!(!values||values.length===0))return Object.fromEntries(values.map(value=>{let separator=value.indexOf("=");if(separator<1)throw new Error("--where expects key=value");return[value.slice(0,separator),value.slice(separator+1)]}))}var issue,logFilters,observeCommands,init_observe=__esm({"../../packages/api-contracts/dist/esm/ops/commands/observe.js"(){"use strict";init_args();init_references2();init_types();init_shared();issue=z24.string().trim().min(1).max(500).describe("Sentry issue id or issue URL");__name(parseWhere,"parseWhere");logFilters={project:opsArgs.project,where:z24.array(z24.string().min(3).max(500)).optional().describe("Structured field filter key=value; repeatable"),contains:z24.string().min(1).max(500).optional().describe("Plain-text line filter"),limit:opsArgs.limit.max(1e3).default(100),reason:opsArgs.reason,output:opsArgs.output.optional()},observeCommands=[{id:"observe.logs.query",summary:"Query a project's production logs in a time window",permission:"ops:logs:read",effect:"read",input:z24.object({...logFilters,since:opsArgs.since,until:opsArgs.until.optional()}),request:__name(input=>({method:"POST",path:"/logs/query",body:compact({projectId:input.project,from:time2(input.since),to:time2(input.until)??new Date().toISOString(),limit:input.limit,contains:input.contains,where:parseWhere(input.where),reason:input.reason})}),"request")},{id:"observe.logs.around",summary:"Read a project's production logs a few minutes either side of a moment",permission:"ops:logs:read",effect:"read",input:z24.object({...logFilters,at:z24.iso.datetime({offset:!0}).describe("The moment to center on"),minutes:z24.coerce.number().int().min(1).max(120).default(5).describe("Minutes before and after")}),request:__name(input=>{let at2=Date.parse(input.at);return{method:"POST",path:"/logs/query",body:compact({projectId:input.project,from:new Date(at2-input.minutes*6e4).toISOString(),to:new Date(at2+input.minutes*6e4).toISOString(),limit:input.limit,contains:input.contains,where:parseWhere(input.where),reason:input.reason})}},"request")},{id:"observe.traces.get",summary:"Read one Grafana Tempo trace (id or Grafana URL) for a project",permission:"ops:traces:read",effect:"read",input:z24.object({trace:z24.string().trim().min(1).max(4e3).describe("32-character trace id or Grafana trace URL"),project:opsArgs.project,since:opsArgs.since,until:opsArgs.until.optional(),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/traces/${normalizeTempoTraceReference(input.trace)}`,body:{projectId:input.project,from:resolveOpsTime(input.since),to:time2(input.until)??new Date().toISOString(),reason:input.reason}}),"request")},{id:"observe.sentry.issues",summary:"Search Sentry issues, for one project or every project",permission:"ops:sentry:read",effect:"read",input:z24.object({project:opsArgs.project.optional(),search:z24.string().trim().min(1).max(500).optional().describe('Sentry search, e.g. "is:unresolved"'),period:z24.enum(["1h","24h","7d","14d","30d","90d"]).optional().describe("Stats period (default 14d)"),sort:z24.enum(["date","new","freq","user","trends"]).optional(),limit:opsArgs.limit.max(100).optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/sentry/issues",body:compact({projectId:input.project,query:input.search,statsPeriod:input.period,sort:input.sort,limit:input.limit,reason:input.reason})}),"request")},{id:"observe.sentry.issue",summary:"Read one Sentry issue",permission:"ops:sentry:read",effect:"read",input:z24.object({issue,reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/sentry/issues/${seg(normalizeSentryIssueReference(input.issue))}`,body:{reason:input.reason}}),"request")},{id:"observe.sentry.event",summary:"Read one full Sentry event",permission:"ops:sentry:read",effect:"read",input:z24.object({event:z24.string().trim().min(1).max(100).describe("Sentry event id"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/sentry/events/${seg(input.event)}`,body:{reason:input.reason}}),"request")},{id:"observe.sentry.latest-event",summary:"Read the latest full event of a Sentry issue",permission:"ops:sentry:read",effect:"read",input:z24.object({issue,reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/sentry/issues/${seg(normalizeSentryIssueReference(input.issue))}/events/latest`,body:{reason:input.reason}}),"request")},{id:"observe.sentry.resolve",summary:"Mark a Sentry issue resolved",permission:"ops:sentry:write",effect:"write",risk:"low",input:z24.object({issue})},{id:"observe.posthog.milestones",summary:"Count a project's PostHog lifecycle milestones (create, deploy, first publish) in a window",permission:"ops:posthog:read",effect:"read",input:z24.object({project:opsArgs.project,since:opsArgs.since,until:opsArgs.until.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:"/posthog/milestones",body:{projectId:input.project,from:resolveOpsTime(input.since),to:time2(input.until)??new Date().toISOString(),reason:input.reason}}),"request")}]}});import{z as z25}from"zod";var orgCommands,init_org=__esm({"../../packages/api-contracts/dist/esm/ops/commands/org.js"(){"use strict";init_organization_features_dto();init_args();init_types();init_shared();orgCommands=[{id:"org.get",summary:"Show an organization: plan, members, projects and subscription summary",permission:"ops:organizations:read",effect:"read",input:z25.object({org:opsArgs.org,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/organizations/${seg(input.org)}`,query:{reason:input.reason}}),"request")},{id:"org.features.list",summary:"List an organization's features and any staff overrides",permission:"ops:customers:read",effect:"read",input:z25.object({org:opsArgs.org}),request:__name(input=>({method:"GET",path:`/organizations/${seg(input.org)}/features`}),"request")},{id:"org.features.set",summary:"Force an organization feature on or off, or clear the override",permission:"ops:organization:features:write",effect:"write",risk:"low",humanOnly:!0,input:z25.object({org:opsArgs.org,feature:z25.enum(ORGANIZATION_FEATURES).describe("Feature name"),state:z25.enum(["on","off","default"]).describe("on, off, or default to clear the override")})},{id:"org.takedown",summary:"Take every project of an organization off Fimo domains and block publishing",permission:"ops:organizations:write",effect:"write",risk:"high",humanOnly:!0,input:z25.object({org:opsArgs.org})},{id:"org.restore",summary:"Lift an organization takedown",permission:"ops:organizations:write",effect:"write",risk:"high",humanOnly:!0,input:z25.object({org:opsArgs.org})},{id:"org.delete",summary:"Delete an organization and everything it owns permanently",permission:"ops:organizations:write",effect:"write",risk:"high",humanOnly:!0,input:z25.object({org:opsArgs.org})},{id:"org.credits.topup",summary:"Grant credits to an organization, free or as a recorded purchase",permission:"ops:credits:write",effect:"write",risk:"high",humanOnly:!0,input:z25.object({org:opsArgs.org,credits:z25.coerce.number().int().positive().describe("Number of credits"),type:z25.enum(["free","purchase"]).default("free"),amountCents:z25.coerce.number().int().positive().optional().describe("Amount paid, required for a purchase"),expiresAt:z25.iso.datetime({offset:!0}).optional().describe("When the credits expire"),message:z25.string().trim().optional().describe("Note shown with the grant")})},{id:"org.credits.burn-zombies",summary:"Burn credits held by abandoned (zombie) holds of one organization since a date",permission:"ops:credits:write",effect:"write",risk:"high",humanOnly:!0,input:z25.object({org:opsArgs.org,since:opsArgs.since})}]}});import{z as z26}from"zod";var OPS_PLATFORM_DASHBOARDS,platformCommands,init_platform=__esm({"../../packages/api-contracts/dist/esm/ops/commands/platform.js"(){"use strict";init_args();init_types();init_shared();OPS_PLATFORM_DASHBOARDS=["agents","money","projects","automation","growth","platform","usage","stats"],platformCommands=[{id:"platform.metrics",summary:"Read an admin dashboard as data: agents, money, projects, automation, growth, platform, usage or stats",permission:"ops:platform:read",effect:"read",input:z26.object({dashboard:z26.enum(OPS_PLATFORM_DASHBOARDS),since:opsArgs.since.default("7d"),until:opsArgs.until.optional()}),request:__name(input=>({method:"GET",path:"/platform/metrics",query:compact({dashboard:input.dashboard,since:time2(input.since),until:time2(input.until)})}),"request")},{id:"platform.pool.status",summary:"Show the warm sandbox pool: size, target, and projects waiting in it",permission:"ops:platform:read",effect:"read",input:z26.object({}),request:__name(()=>({method:"GET",path:"/platform/pool"}),"request")},{id:"platform.pool.refill",summary:"Top the warm sandbox pool up to its target size",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z26.object({})},{id:"platform.pool.flush",summary:"Delete warm sandboxes from the pool, all of them or only the listed ones (new projects start cold until it refills)",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z26.object({pooled:z26.array(z26.uuid()).min(1).max(500).optional().describe("Only these pooled project ids; omit to flush all")})},{id:"platform.maintenance.status",summary:"Show whether maintenance mode is on and its message",permission:"ops:platform:read",effect:"read",input:z26.object({}),request:__name(()=>({method:"GET",path:"/platform/maintenance"}),"request")},{id:"platform.maintenance.enable",summary:"Turn maintenance mode on: Studio shows the message and refuses work",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z26.object({message:z26.string().max(500).optional().describe("Message shown to users")})},{id:"platform.maintenance.disable",summary:"Turn maintenance mode off",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z26.object({})},{id:"platform.maintenance.message",summary:"Change the maintenance message without toggling maintenance mode",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z26.object({message:z26.string().max(500).describe("Message shown to users")})},{id:"platform.sync-all",summary:"Re-sync every project's database records from its repository",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z26.object({})},{id:"platform.sync-tenant-schemas",summary:"Apply pending tenant schema migrations to every project database",permission:"ops:platform:write",effect:"write",risk:"high",humanOnly:!0,input:z26.object({})},{id:"platform.integrations.replay",summary:"Replay one failed inbound integration event",permission:"ops:platform:write",effect:"write",risk:"low",input:z26.object({event:z26.string().trim().min(1).max(255).describe("Inbound event id")})},{id:"platform.onboardings.list",summary:"List site onboardings (start from an existing website) with their status",permission:"ops:platform:read",effect:"read",input:z26.object({status:z26.string().trim().min(1).max(64).optional(),since:opsArgs.since.optional(),limit:opsArgs.limit.max(200).default(50),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/platform/onboardings",query:compact({status:input.status,since:time2(input.since),limit:input.limit,cursor:input.cursor})}),"request")},{id:"platform.onboardings.get",summary:"Show one project's site onboarding: questions, answers, refusal and timeline",permission:"ops:platform:read",effect:"read",input:z26.object({project:opsArgs.project,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/platform/onboardings/${seg(input.project)}`,query:{reason:input.reason}}),"request")},{id:"platform.onboardings.lift-refusal",summary:"Lift a site onboarding's Terms refusal so the project can continue",permission:"ops:platform:write",effect:"write",risk:"low",input:z26.object({project:opsArgs.project})},{id:"platform.unclaimed.list",summary:"List unclaimed projects (created without an account) and their claim state",permission:"ops:platform:read",effect:"read",input:z26.object({since:opsArgs.since.optional(),limit:opsArgs.limit.max(200).default(50),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/platform/unclaimed",query:compact({since:time2(input.since),limit:input.limit,cursor:input.cursor})}),"request")},{id:"platform.resources.resolve",summary:"Resolve any id, URL, email or domain to the Fimo record it names",permission:"ops:platform:read",effect:"read",input:z26.object({query:z26.string().trim().min(1).max(512).describe("Id, URL, email or domain")}),request:__name(input=>({method:"GET",path:"/platform/resources/resolve",query:{q:input.query}}),"request"),cli:{positional:"query"}}]}});import{z as z27}from"zod";function files(project,action,env){return`/projects/${seg(project)}/files/${action}?projectEnv=${seg(env)}`}var envMain,projectCommands,init_project=__esm({"../../packages/api-contracts/dist/esm/ops/commands/project.js"(){"use strict";init_args();init_types();init_shared();envMain=opsArgs.env.default("main");__name(files,"files");projectCommands=[{id:"project.get",summary:"Inspect a project: owner, environments, domains, publications, recent runs and logs",permission:"ops:project:read",effect:"read",input:z27.object({project:opsArgs.project,env:envMain,since:opsArgs.since.default("24h"),limit:opsArgs.limit.max(500).default(100).describe("Maximum log entries")}),request:__name(input=>({method:"GET",path:`/projects/${seg(input.project)}/inspect`,query:{projectEnv:input.env,hours:Math.min(168,opsHoursSince(input.since)),logLimit:input.limit}}),"request")},{id:"project.list",summary:"List projects across organizations, newest first: search by name or organization, or find those at their database limit (database quota reached)",permission:"ops:project:read",effect:"read",input:z27.object({query:opsArgs.query.optional().describe("Project name, display name, id or organization name"),databaseQuota:z27.enum(["blocked","refused"]).optional().describe("blocked: the database refuses queries now because the plan's quota is used up; refused: refused at any time, recovered ones included"),since:opsArgs.since.optional().describe("Created since: ISO timestamp or relative (30m, 24h, 7d, 2w)"),limit:opsArgs.limit.max(100).default(50),cursor:opsArgs.cursor.optional()}),request:__name(input=>({method:"GET",path:"/projects",query:compact({search:input.query,databaseQuota:input.databaseQuota,since:time2(input.since),limit:input.limit,cursor:input.cursor})}),"request")},{id:"project.snapshot",summary:"Download a zip snapshot of a project's source and content",permission:"ops:project:snapshot",effect:"read",input:z27.object({project:opsArgs.project,reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/projects/${seg(input.project)}/snapshot`,body:{reason:input.reason}}),"request")},{id:"project.chat",summary:"Read a project's agent chat transcript (the most recently active chat unless --thread is set)",permission:"ops:project:chat:read",effect:"read",input:z27.object({project:opsArgs.project,thread:z27.uuid().optional().describe("One chat or routine run thread id"),env:opsArgs.env.optional().describe("Only turns that targeted this environment"),since:opsArgs.since.optional(),until:opsArgs.until.optional(),limit:opsArgs.limit.max(200).default(100),cursor:opsArgs.cursor.optional(),full:z27.boolean().default(!1).describe("Include tool inputs, outputs and other message parts"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/projects/${seg(input.project)}/chat/messages`,body:compact({projectEnv:input.env,threadId:input.thread,from:time2(input.since),to:time2(input.until),limit:input.limit,cursor:input.cursor,slim:!input.full,reason:input.reason})}),"request")},{id:"project.files.read",summary:"Read one source file from a project environment",permission:"ops:project:snapshot",effect:"read",input:z27.object({project:opsArgs.project,env:envMain,path:z27.string().trim().min(1).max(1024).describe("File path relative to the project root"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:files(input.project,"read",input.env),body:{path:input.path,reason:input.reason}}),"request")},{id:"project.files.glob",summary:"List source file paths in a project environment",permission:"ops:project:snapshot",effect:"read",input:z27.object({project:opsArgs.project,env:envMain,pattern:z27.string().min(1).max(300).optional().describe("Glob pattern, e.g. src/**/*.tsx"),limit:opsArgs.limit.max(2e3).default(2e3),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:files(input.project,"glob",input.env),body:compact({pattern:input.pattern,limit:input.limit,reason:input.reason})}),"request")},{id:"project.files.grep",summary:"Search source files in a project environment with a regular expression",permission:"ops:project:snapshot",effect:"read",input:z27.object({project:opsArgs.project,env:envMain,pattern:z27.string().min(1).max(200).describe("Regular expression"),include:z27.string().min(1).max(300).optional().describe("Only paths matching this glob"),caseInsensitive:z27.boolean().default(!1),limit:opsArgs.limit.max(200).default(100).describe("Maximum matches"),reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:files(input.project,"grep",input.env),body:compact({pattern:input.pattern,include:input.include,caseInsensitive:input.caseInsensitive,maxMatches:input.limit,reason:input.reason})}),"request")},{id:"project.files.package-manager",summary:"Report which package manager a project declares and which lockfiles it has",permission:"ops:project:snapshot",effect:"read",input:z27.object({project:opsArgs.project,env:envMain,reason:opsArgs.reason}),request:__name(input=>({method:"POST",path:files(input.project,"package-manager",input.env),body:{reason:input.reason}}),"request")},{id:"project.files.write",summary:"Create or replace one source file in a project environment (commits to its branch)",permission:"ops:project:operate",effect:"write",risk:"high",humanOnly:!0,input:z27.object({project:opsArgs.project,env:envMain,path:z27.string().trim().min(1).max(1024).describe("File path relative to the project root"),content:z27.string().max(256*1024).describe("The exact desired file contents"),overwrite:z27.boolean().default(!1).describe("Allow replacing an existing file")}),cli:{fileArgs:["content"]}},{id:"project.runtime.bump",summary:"Pin the project's fimo runtime packages to an exact version, install, and restart the dev server",permission:"ops:project:operate",effect:"write",risk:"high",humanOnly:!0,input:z27.object({project:opsArgs.project,env:envMain,version:z27.string().trim().min(1).max(64).describe("Exact target version, e.g. 0.11.0")})},{id:"project.preview.restart",summary:"Restart the project's preview dev server",permission:"ops:project:operate",effect:"write",risk:"low",humanOnly:!0,input:z27.object({project:opsArgs.project,env:envMain})},{id:"project.publish",summary:"Publish the customer's site on their behalf. Only when a Fimo admin explicitly asks for it; never on an agent's own initiative",permission:"ops:project:publish",effect:"write",risk:"high",humanOnly:!0,consent:!0,input:z27.object({project:opsArgs.project,env:opsArgs.env.optional().describe("Source environment; defaults to the project's publish source")})},{id:"project.domain.refresh",summary:"Refresh a custom domain's provider and SSL state",permission:"ops:project:operate",effect:"write",risk:"low",humanOnly:!0,input:z27.object({project:opsArgs.project,domain:z27.uuid().describe("Project domain id")})},{id:"project.migrations.dry-run",summary:"Plan a source migration for one project without changing it",permission:"ops:project:read",effect:"read",input:z27.object({project:opsArgs.project,env:envMain,migration:z27.string().trim().min(1).max(120).optional().describe("Migration id (default: the current one)"),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/migrations/projects/${seg(input.project)}/dry-run`,body:compact({migrationId:input.migration,projectEnv:input.env,reason:input.reason})}),"request")},{id:"project.sync",summary:"Re-sync a project's database records from its repository",permission:"ops:project:operate",effect:"write",risk:"low",input:z27.object({project:opsArgs.project})},{id:"project.thumbnail.regenerate",summary:"Regenerate a project's dashboard thumbnail",permission:"ops:project:operate",effect:"write",risk:"low",input:z27.object({project:opsArgs.project,type:z27.enum(["dev","published"]).default("dev").describe("dev (the preview) or published (the live site)")})},{id:"project.version.restore",summary:"Restore a project environment to an earlier version (overwrites the current state)",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z27.object({project:opsArgs.project,env:envMain,version:z27.string().trim().min(1).max(255).describe("Version id to restore")})},{id:"project.takedown",summary:"Take a project off Fimo domains and block it from publishing",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z27.object({project:opsArgs.project})},{id:"project.restore",summary:"Lift a project takedown so it can serve and publish again",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z27.object({project:opsArgs.project})},{id:"project.transfer",summary:"Move a project to another organization",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z27.object({project:opsArgs.project,toOrg:opsArgs.org.describe("Destination organization id")})},{id:"project.delete",summary:"Delete a project and its resources permanently",permission:"ops:project:admin",effect:"write",risk:"high",humanOnly:!0,input:z27.object({project:opsArgs.project})}]}});import{z as z28}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=z28.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z28.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z28.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z28.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z28.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z28.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z28.enum(["user","agent","system"]),SupportReportTagSchema=z28.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z28.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z28.object({organization:z28.object({id:z28.string().trim().min(1).max(255),name:z28.string().trim().max(240).optional()}),project:z28.object({id:z28.uuid(),name:z28.string().trim().max(240).optional(),createdAt:z28.coerce.date().optional()}).optional(),environment:z28.string().trim().max(255).optional(),clientVersion:z28.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z28.object({message:z28.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("cli"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z28.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z28.string().trim().max(200).optional(),limit:z28.coerce.number().int().min(1).max(100).default(50),offset:z28.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z28.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z28.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z28.uuid().nullable().optional(),note:z28.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=z28.object({message:z28.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z28.object({kind:SupportReportLinkKindSchema,label:z28.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z28.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z28.object({kind:SupportReportActorKindSchema,id:z28.string().nullable(),name:z28.string().nullable()}),SupportReportLinkDTOSchema=z28.object({id:z28.uuid(),kind:SupportReportLinkKindSchema,label:z28.string(),url:SupportReportHttpUrlSchema,externalId:z28.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z28.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z28.object({id:z28.uuid(),kind:SupportReportEventKindSchema,body:z28.string().nullable(),metadata:z28.record(z28.string(),z28.unknown()),actor:SupportReportActorDTOSchema,createdAt:z28.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z28.object({id:z28.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z28.array(z28.string()),source:SupportReportSourceSchema,message:z28.string(),reporter:z28.object({id:z28.string().nullable(),name:z28.string().nullable(),email:z28.string().nullable()}),organization:z28.object({id:z28.string().nullable(),name:z28.string()}),project:z28.object({id:z28.uuid().nullable(),name:z28.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z28.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z28.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z28.string().nullable(),deliveredAt:z28.coerce.date().nullable()}).nullable(),duplicateOfReportId:z28.uuid().nullable(),resolvedAt:z28.coerce.date().nullable(),createdAt:z28.coerce.date(),updatedAt:z28.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z28.string().nullable(),clientVersion:z28.string().nullable(),links:z28.array(SupportReportLinkDTOSchema),events:z28.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z28.object({reports:z28.array(SupportReportSummaryDTOSchema),total:z28.number().int().nonnegative(),statusCounts:z28.object({new:z28.number().int().nonnegative(),in_progress:z28.number().int().nonnegative(),waiting:z28.number().int().nonnegative(),resolved:z28.number().int().nonnegative(),duplicate:z28.number().int().nonnegative(),irrelevant:z28.number().int().nonnegative(),ignored:z28.number().int().nonnegative()}),limit:z28.number().int().positive(),offset:z28.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z28.object({id:z28.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z28.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z29}from"zod";var report,pylonIssue,supportCommands,init_support=__esm({"../../packages/api-contracts/dist/esm/ops/commands/support.js"(){"use strict";init_support_report_dto();init_ops();init_args();init_types();init_shared();report=z29.uuid().describe("Support report id"),pylonIssue=OpsPylonIssueIdSchema.describe("Pylon issue id"),supportCommands=[{id:"support.reports.list",summary:"List Fimo support reports, newest first",permission:"ops:support:read",effect:"read",input:z29.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:z29.string().trim().min(1).max(50).optional(),search:z29.string().trim().min(1).max(200).optional().describe("Text search over the report"),limit:opsArgs.limit.max(200).default(50),offset:z29.coerce.number().int().min(0).default(0),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"GET",path:"/support/reports",query:compact({reason:input.reason,status:input.status,category:input.category,source:input.source,tag:input.tag,query:input.search,limit:input.limit,offset:input.offset})}),"request")},{id:"support.reports.get",summary:"Read one support report with its messages, links and context",permission:"ops:support:read",effect:"read",input:z29.object({report,reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"GET",path:`/support/reports/${seg(input.report)}`,query:{reason:input.reason}}),"request")},{id:"support.reports.claim",summary:"Claim a support report (mark it in progress), optionally with a note",permission:"ops:support:write",effect:"write",risk:"low",input:z29.object({report,note:z29.string().trim().min(1).max(2e4).optional()}),cli:{fileArgs:["note"]}},{id:"support.reports.update",summary:"Change a support report's status, category, tags or duplicate link, optionally with a note",permission:"ops:support:write",effect:"write",risk:"low",input:z29.object({report,status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z29.array(z29.string().trim().min(1).max(50)).max(20).optional(),duplicateOf:z29.uuid().nullable().optional().describe("Report id this one duplicates; null clears it"),note:z29.string().trim().min(1).max(2e4).optional()}),cli:{fileArgs:["note"]}},{id:"support.reports.note",summary:"Add an internal message to a support report",permission:"ops:support:write",effect:"write",risk:"low",input:z29.object({report,message:z29.string().trim().min(1).max(2e4)}),cli:{fileArgs:["message"]}},{id:"support.reports.link",summary:"Link a support report to a Linear issue, Pylon ticket, project, Sentry issue or other URL",permission:"ops:support:write",effect:"write",risk:"low",input:z29.object({report,kind:SupportReportLinkKindSchema,label:z29.string().trim().min(1).max(240),url:z29.url({protocol:/^https?$/}).max(2e3),externalId:z29.string().trim().min(1).max(255).optional()})},{id:"support.reports.unlink",summary:"Remove a link from a support report",permission:"ops:support:write",effect:"write",risk:"low",input:z29.object({report,link:z29.uuid().describe("Link id")})},{id:"support.intake",summary:"Show the support intake receipt: reports received and delivered in a window (max 7 days)",permission:"ops:support:read",effect:"read",input:z29.object({since:opsArgs.since,until:opsArgs.until.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/support/intake/status",query:{since:time2(input.since),until:time2(input.until)??new Date().toISOString(),reason:input.reason}}),"request")},{id:"support.pylon.list",summary:"List Pylon support tickets in a window (max 7 days)",permission:"ops:support:read",effect:"read",input:z29.object({since:opsArgs.since,until:opsArgs.until.optional(),state:z29.enum(["open","closed","all"]).default("open"),limit:opsArgs.limit.max(100).default(50),cursor:opsArgs.cursor.optional(),reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"GET",path:"/support/pylon/issues",query:compact({since:time2(input.since),until:time2(input.until)??new Date().toISOString(),state:input.state,limit:input.limit,cursor:input.cursor,reason:input.reason})}),"request")},{id:"support.pylon.thread",summary:"Read the full message thread of a Pylon ticket",permission:"ops:support:read",effect:"read",input:z29.object({issue:pylonIssue,reason:opsArgs.reason,output:opsArgs.output.optional()}),request:__name(input=>({method:"POST",path:`/support/issues/${seg(input.issue)}/thread`,body:{reason:input.reason}}),"request")},{id:"support.pylon.resolve",summary:"Close a Pylon ticket",permission:"ops:support:write",effect:"write",risk:"low",input:z29.object({issue:pylonIssue})},{id:"support.pylon.note",summary:"Add an internal note to a Pylon ticket (not visible to the customer)",permission:"ops:support:write",effect:"write",risk:"low",input:z29.object({issue:pylonIssue,message:z29.string().trim().min(1).max(5e3)}),cli:{fileArgs:["message"]}}]}});import{z as z30}from"zod";var userCommands,init_user=__esm({"../../packages/api-contracts/dist/esm/ops/commands/user.js"(){"use strict";init_args();init_types();init_shared();userCommands=[{id:"user.get",summary:"Show a user: profile, role, organizations, recent sessions and usage",permission:"ops:users:read",effect:"read",input:z30.object({user:opsArgs.user,reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:`/users/${seg(input.user)}`,query:{reason:input.reason}}),"request")},{id:"user.sessions",summary:"List sign-in sessions, for one user or across the platform",permission:"ops:users:read",effect:"read",input:z30.object({user:opsArgs.user.optional(),active:z30.boolean().optional().describe("Only sessions that have not expired or been revoked"),limit:opsArgs.limit.max(200).default(50),cursor:opsArgs.cursor.optional(),reason:opsArgs.reason}),request:__name(input=>({method:"GET",path:"/sessions",query:compact({userId:input.user,active:input.active,limit:input.limit,cursor:input.cursor,reason:input.reason})}),"request")},{id:"user.session.revoke",summary:"Revoke one sign-in session",permission:"ops:users:write",effect:"write",risk:"low",humanOnly:!0,input:z30.object({session:z30.string().trim().min(1).max(255).describe("Session id")})}]}});import{z as z31}from"zod";var evidence,versions,detectionQueries,watchCommands,init_watch=__esm({"../../packages/api-contracts/dist/esm/ops/commands/watch.js"(){"use strict";init_ops();init_args();init_types();init_shared();evidence=z31.array(z31.record(z31.string(),z31.unknown())).max(100),versions=z31.array(z31.string().trim().min(1).max(120)).max(100),detectionQueries=z31.array(z31.string().trim().min(1).max(2e3)).max(50),watchCommands=[{id:"watch.list",summary:"List watched projects and why each is watched",permission:"ops:customers:read",effect:"read",input:z31.object({}),request:__name(()=>({method:"GET",path:"/customers"}),"request")},{id:"watch.add",summary:"Watch a project (or update why it is watched)",permission:"ops:customers:write",effect:"write",risk:"low",input:z31.object({project:opsArgs.project,importance:z31.string().trim().min(1).max(1e3).describe("Why this project is operationally important"),owner:opsArgs.user.optional().describe("Owner user id"),framework:z31.string().trim().max(120).optional(),packageManager:z31.enum(["npm","pnpm","yarn","bun"]).optional(),notes:z31.string().trim().max(5e3).optional()})},{id:"watch.remove",summary:"Stop watching a project",permission:"ops:customers:write",effect:"write",risk:"low",input:z31.object({project:opsArgs.project})},{id:"watch.validations.list",summary:"List validation runs recorded for a watched project",permission:"ops:validations:read",effect:"read",input:z31.object({project:opsArgs.project}),request:__name(input=>({method:"GET",path:`/customers/${seg(input.project)}/validations`}),"request")},{id:"watch.validations.record",summary:"Record the outcome of validating a release, migration or change against a watched project",permission:"ops:validations:write",effect:"write",risk:"low",input:z31.object({project:opsArgs.project,change:z31.string().trim().min(1).max(500).describe("Release, migration or change that was validated"),outcome:OpsValidationOutcomeSchema,summary:z31.string().trim().min(1).max(1e4),evidence:evidence.default([])}),cli:{fileArgs:["evidence"]}},{id:"watch.investigations.list",summary:"List open and recent investigations",permission:"ops:investigations:read",effect:"read",input:z31.object({}),request:__name(()=>({method:"GET",path:"/investigations"}),"request")},{id:"watch.investigations.create",summary:"Open an investigation into a problem on a project",permission:"ops:investigations:write",effect:"write",risk:"low",input:z31.object({project:opsArgs.project,title:z31.string().trim().min(1).max(240),userReport:z31.string().trim().max(1e4).optional().describe("The customer's own words")})},{id:"watch.investigations.update",summary:"Update an investigation's status, hypothesis, outcome or evidence",permission:"ops:investigations:write",effect:"write",risk:"low",input:z31.object({investigation:z31.uuid().describe("Investigation id"),status:OpsInvestigationStatusSchema.optional(),hypothesis:z31.string().trim().max(1e4).optional(),outcome:z31.string().trim().max(1e4).optional(),evidence:evidence.optional()}),cli:{fileArgs:["evidence"]}},{id:"watch.known-issues.list",summary:"List known issues and their detection queries",permission:"ops:known-issues:read",effect:"read",input:z31.object({}),request:__name(()=>({method:"GET",path:"/known-issues"}),"request")},{id:"watch.known-issues.create",summary:"Record a known issue with how to detect it and any workaround",permission:"ops:known-issues:write",effect:"write",risk:"low",input:z31.object({fingerprint:z31.string().trim().min(1).max(240),title:z31.string().trim().min(1).max(240),description:z31.string().trim().min(1).max(1e4),affectedVersions:versions.default([]),detectionQueries:detectionQueries.default([]),fixedVersion:z31.string().trim().min(1).max(64).optional(),workaround:z31.string().trim().min(1).max(1e4).optional(),status:OpsKnownIssueStatusSchema.default("open")}),cli:{fileArgs:["detectionQueries"]}},{id:"watch.known-issues.update",summary:"Update a known issue",permission:"ops:known-issues:write",effect:"write",risk:"low",input:z31.object({knownIssue:z31.uuid().describe("Known issue id"),title:z31.string().trim().min(1).max(240).optional(),description:z31.string().trim().min(1).max(1e4).optional(),affectedVersions:versions.optional(),detectionQueries:detectionQueries.optional(),fixedVersion:z31.string().trim().min(1).max(64).optional(),workaround:z31.string().trim().min(1).max(1e4).optional(),status:OpsKnownIssueStatusSchema.optional()}),cli:{fileArgs:["detectionQueries"]}}]}});var OPS_COMMANDS,BY_ID,OPS_OPERATION_IDS,init_commands=__esm({"../../packages/api-contracts/dist/esm/ops/commands/index.js"(){"use strict";init_agent();init_agent();init_assistant();init_billing();init_core();init_health();init_merge();init_monitor();init_monitor();init_notify();init_observe();init_org();init_platform();init_platform();init_project();init_support();init_user();init_watch();OPS_COMMANDS=[...coreCommands,...projectCommands,...orgCommands,...userCommands,...mergeCommands,...agentCommands,...healthCommands,...billingCommands,...platformCommands,...observeCommands,...supportCommands,...watchCommands,...monitorCommands,...notifyCommands,...assistantCommands],BY_ID=new Map(OPS_COMMANDS.map(command=>[command.id,command])),OPS_OPERATION_IDS=OPS_COMMANDS.filter(command=>command.effect==="write").map(command=>command.id)}});import{z as z32}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,AgentBlockSchema,ChatDisplayBlockSchema,TextBlockSchema,ChatFormStepIdSchema,CapabilityRequestSchema,CapabilitiesBlockSchema,ChatFormBodySchema,ChatFormStepSchema,CHAT_FORM_INTERNAL_NOTE_MAX,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=z32.object({kind:z32.literal("say"),label:z32.string().trim().min(1).max(40,"Button labels must be 40 characters or fewer."),description:z32.string().min(1).max(240).optional(),message:z32.string().trim().min(1,"Every say button needs the sentence the user is saying by clicking.").max(2e3),style:z32.enum(["primary","default","ghost"]).optional()}),BlockActionSchema=BlockSayActionSchema,BlockAppActionSchema=z32.discriminatedUnion("command",[z32.object({kind:z32.literal("app"),command:z32.literal("publish")}).strict(),z32.object({kind:z32.literal("app"),command:z32.literal("connect"),integrationKey:z32.string().trim().min(1).max(80)}).strict()]),BlockBaseSchema=z32.object({fallback:z32.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z32.string().min(1).max(80).optional()}),ChoicesBlockSchema=BlockBaseSchema.extend({type:z32.literal("choices"),text:z32.string().max(500).optional(),actions:z32.array(BlockActionSchema).min(2,"A choices block needs 2 to 4 buttons.").max(4,"A choices block needs 2 to 4 buttons.")}),TableRowTargetSchema=z32.discriminatedUnion("kind",[z32.object({kind:z32.literal("entry"),collection:z32.string().min(1).max(80),entryId:z32.string().min(1).max(120)}),z32.object({kind:z32.literal("asset"),assetId:z32.string().min(1).max(120)}),z32.object({kind:z32.literal("url"),url:z32.url({protocol:/^https$/}).max(2e3)}),z32.object({kind:z32.literal("routine"),routineId:z32.string().min(1).max(120)})]),TableBlockSchema=BlockBaseSchema.extend({type:z32.literal("table"),columns:z32.array(z32.object({label:z32.string().min(1).max(24)})).min(2).max(4),rows:z32.array(z32.object({cells:z32.array(z32.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:z32.literal("cards"),layout:z32.enum(["rail","stack"]).optional(),items:z32.array(z32.object({title:z32.string().min(1).max(60),subtitle:z32.string().min(1).max(120).optional(),imageUrl:z32.url({protocol:/^https$/}).max(2e3).optional(),action:BlockSayActionSchema.optional()})).min(2).max(6)}),EntryBlockSchema=BlockBaseSchema.extend({type:z32.literal("entry"),label:z32.string().min(1).max(80),collection:z32.string().min(1).max(80),entryId:z32.string().min(1).max(120),path:z32.string().min(1).max(120).optional()}),AssetsBlockSchema=BlockBaseSchema.extend({type:z32.literal("assets"),items:z32.array(z32.object({url:z32.url({protocol:/^https$/}).max(2e3),alt:z32.string().min(1).max(120),label:z32.string().min(1).max(60).optional()})).min(1).max(6)}),CalloutBlockSchema=BlockBaseSchema.extend({type:z32.literal("callout"),title:z32.string().min(1).max(80),text:z32.string().min(1).max(240),action:BlockAppActionSchema}).strict(),StatBlockSchema=BlockBaseSchema.extend({type:z32.literal("stat"),items:z32.array(z32.object({label:z32.string().min(1).max(24),value:z32.string().min(1).max(16),delta:z32.string().min(1).max(12).optional(),tone:z32.enum(["up","down","flat"]).optional()})).min(1).max(4)}),ChartBlockSchema=BlockBaseSchema.extend({type:z32.literal("chart"),unit:z32.string().min(1).max(12).optional(),points:z32.array(z32.object({label:z32.string().min(1).max(12),value:z32.number().finite().min(0).max(1e9)})).min(2).max(12)}),AgentBlockSchema=BlockBaseSchema.extend({type:z32.literal("agent"),agentId:z32.string().uuid(),view:z32.enum(["compact","full"]).optional()}),ChatDisplayBlockSchema=z32.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema]),TextBlockSchema=BlockBaseSchema.extend({type:z32.literal("text"),placeholder:z32.string().min(1).max(120).optional(),multiline:z32.boolean().optional()}).strict(),ChatFormStepIdSchema=z32.string().regex(/^[a-z0-9][a-z0-9_-]{0,39}$/,"Step ids are lowercase letters, digits, hyphen, or underscore (max 40)."),CapabilityRequestSchema=z32.object({id:ChatFormStepIdSchema,token:z32.string().regex(/^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?$/,"Capability tokens are verb:noun[:qualifier]."),label:z32.string().trim().min(1).max(60),reason:z32.string().trim().min(1).max(240)}).strict(),CapabilitiesBlockSchema=BlockBaseSchema.extend({type:z32.literal("capabilities"),items:z32.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=z32.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,AssetsBlockSchema,TextBlockSchema,CapabilitiesBlockSchema]);__name(getChatFormOptionLabels,"getChatFormOptionLabels");ChatFormStepSchema=z32.object({id:ChatFormStepIdSchema.optional(),question:z32.string().min(1).max(500),header:z32.string().min(1).max(25),body:ChatFormBodySchema,multiSelect:z32.boolean().optional(),recommended:z32.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"})),CHAT_FORM_INTERNAL_NOTE_MAX=1e3,FormBlockSchema=BlockBaseSchema.extend({type:z32.literal("form"),steps:z32.array(ChatFormStepSchema).min(1).max(4),internalNote:z32.string().trim().min(1).max(CHAT_FORM_INTERNAL_NOTE_MAX).optional()}),ChatBlockSchema=z32.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,AgentBlockSchema,FormBlockSchema]),ChatBlockToolInputSchema=z32.object({block:ChatBlockSchema}),ChatFormAnswerItemSchema=z32.object({stepId:ChatFormStepIdSchema.optional(),header:z32.string().min(1).max(25),question:z32.string().min(1).max(500),answer:z32.string().min(1),selectedLabels:z32.array(z32.string().min(1).max(120)).max(8),freeText:z32.string(),skipped:z32.boolean()}),ChatFormAnswerMetadataSchema=z32.object({toolCallId:z32.string().max(255).optional(),shortTitle:z32.string().max(80).optional(),questions:z32.array(ChatFormAnswerItemSchema).max(4)}),QUESTION_FORM_CONTRACT_VERSION=1,QuestionFormSnapshotSchema=z32.object({version:z32.literal(QUESTION_FORM_CONTRACT_VERSION),block:FormBlockSchema}).strict(),QuestionFormAnswerSnapshotSchema=z32.object({version:z32.literal(QUESTION_FORM_CONTRACT_VERSION),answer:ChatFormAnswerMetadataSchema}).strict(),ChatFormResponseSchema=ChatFormAnswerMetadataSchema.extend({toolCallId:z32.string().min(1).max(255),partial:z32.boolean().optional()})}});import{z as z33}from"zod";var BLOCK_CLOSE_OUTCOMES,BlockUpdateResultSchema,BlockCloseResultSchema,init_chat_block_state=__esm({"../../packages/api-contracts/dist/esm/types/chat-block-state.js"(){"use strict";init_chat_block();BLOCK_CLOSE_OUTCOMES=["answered_in_chat","done","no_longer_needed"],BlockUpdateResultSchema=z33.object({rendered:z33.literal(!0),id:z33.string().min(1),block:ChatBlockSchema,reason:z33.string().optional()}),BlockCloseResultSchema=z33.object({closed:z33.literal(!0),ids:z33.array(z33.string().min(1)).min(1),outcome:z33.enum(BLOCK_CLOSE_OUTCOMES),reason:z33.string(),messageId:z33.string().optional()})}});import{z as z34}from"zod";var AdminTargetSchema,AdminToneSchema,AdminStatusSchema,AdminLinkSchema,AdminActionSchema,BlockBaseSchema2,AdminRecordBlockSchema,AdminCardsBlockSchema,AdminTableBlockSchema,AdminTimelineBlockSchema,AdminStatsBlockSchema,AdminExcerptBlockSchema,AdminMediaBlockSchema,AdminActionsBlockSchema,AdminHandoffBlockSchema,AdminChatBlockSchema,AdminChatBlockToolInputSchema,init_admin_chat_block=__esm({"../../packages/api-contracts/dist/esm/types/admin-chat-block.js"(){"use strict";init_chat_block();AdminTargetSchema=z34.union([z34.string().regex(/^\/(?!\/)[^\s]*$/,"Admin paths start with a single slash, e.g. /projects/<id>.").max(500),z34.url({protocol:/^https$/}).max(2e3)]),AdminToneSchema=z34.enum(["ok","warn","bad","neutral"]),AdminStatusSchema=z34.object({label:z34.string().trim().min(1).max(24),tone:AdminToneSchema}),AdminLinkSchema=z34.object({label:z34.string().trim().min(1).max(24),target:AdminTargetSchema}),AdminActionSchema=z34.discriminatedUnion("kind",[BlockSayActionSchema,z34.object({kind:z34.literal("open"),label:z34.string().trim().min(1).max(32),target:AdminTargetSchema}).strict(),z34.object({kind:z34.literal("op"),label:z34.string().trim().min(1).max(32),operation:z34.string().min(1).max(80),input:z34.record(z34.string(),z34.unknown())}).strict(),z34.object({kind:z34.literal("impersonate"),label:z34.string().trim().min(1).max(32),userId:z34.string().min(1).max(120)}).strict(),z34.object({kind:z34.literal("studio"),label:z34.string().trim().min(1).max(32),projectId:z34.string().min(1).max(120)}).strict()]),BlockBaseSchema2=z34.object({fallback:z34.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z34.string().min(1).max(80).optional()}),AdminRecordBlockSchema=BlockBaseSchema2.extend({type:z34.literal("record"),kind:z34.string().trim().min(1).max(24),name:z34.string().trim().min(1).max(80),id:z34.string().min(1).max(120).optional(),status:AdminStatusSchema.optional(),fields:z34.array(z34.object({label:z34.string().trim().min(1).max(24),value:z34.string().min(1).max(80)})).max(4,"A record shows at most 4 fields.").optional(),links:z34.array(AdminLinkSchema).max(2,"A record shows at most 2 links.").optional(),actions:z34.array(AdminActionSchema).max(3).optional()}),AdminCardsBlockSchema=BlockBaseSchema2.extend({type:z34.literal("cards"),items:z34.array(z34.object({name:z34.string().trim().min(1).max(60),subtitle:z34.string().min(1).max(80).optional(),status:AdminStatusSchema.optional(),imageUrl:z34.url({protocol:/^https$/}).max(2e3).optional(),target:AdminTargetSchema.optional()})).min(2).max(6)}),AdminTableBlockSchema=BlockBaseSchema2.extend({type:z34.literal("table"),columns:z34.array(z34.object({label:z34.string().min(1).max(24)})).min(2).max(3,"A table shows at most 3 columns."),rows:z34.array(z34.object({cells:z34.array(z34.string().max(80)).min(2).max(3),tone:AdminToneSchema.optional(),target:AdminTargetSchema.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.`})})}),AdminTimelineBlockSchema=BlockBaseSchema2.extend({type:z34.literal("timeline"),events:z34.array(z34.object({at:z34.string().trim().min(1).max(16),label:z34.string().trim().min(1).max(80),detail:z34.string().min(1).max(80).optional(),tone:AdminToneSchema,target:AdminTargetSchema.optional()})).min(2).max(6)}),AdminStatsBlockSchema=BlockBaseSchema2.extend({type:z34.literal("stats"),items:z34.array(z34.object({label:z34.string().min(1).max(24),value:z34.string().min(1).max(16),delta:z34.string().min(1).max(12).optional()})).min(1).max(4)}),AdminExcerptBlockSchema=BlockBaseSchema2.extend({type:z34.literal("excerpt"),source:z34.string().trim().min(1).max(60),link:AdminTargetSchema.optional(),content:z34.discriminatedUnion("kind",[z34.object({kind:z34.literal("lines"),lines:z34.array(z34.object({text:z34.string().max(200),highlight:z34.boolean().optional()})).min(1).max(5,"An excerpt shows at most 5 lines.")}),z34.object({kind:z34.literal("message"),author:z34.string().trim().min(1).max(60),at:z34.string().max(24).optional(),text:z34.string().trim().min(1).max(600)})])}),AdminMediaBlockSchema=BlockBaseSchema2.extend({type:z34.literal("media"),items:z34.array(z34.object({url:z34.url({protocol:/^https$/}).max(2e3),alt:z34.string().min(1).max(120),label:z34.string().min(1).max(60).optional()})).min(1).max(6)}),AdminActionsBlockSchema=BlockBaseSchema2.extend({type:z34.literal("actions"),actions:z34.array(AdminActionSchema).min(1).max(3)}),AdminHandoffBlockSchema=BlockBaseSchema2.extend({type:z34.literal("handoff"),prompt:z34.string().trim().min(1).max(4e3)}),AdminChatBlockSchema=z34.discriminatedUnion("type",[AdminRecordBlockSchema,AdminCardsBlockSchema,AdminTableBlockSchema,AdminTimelineBlockSchema,AdminStatsBlockSchema,ChartBlockSchema,AdminExcerptBlockSchema,AdminMediaBlockSchema,ChoicesBlockSchema,AdminActionsBlockSchema,FormBlockSchema,AdminHandoffBlockSchema]),AdminChatBlockToolInputSchema=z34.object({block:AdminChatBlockSchema})}});import{z as z35}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=z35.object({shape:z35.enum(CHAT_PORTRAIT_SHAPES),eyes:z35.enum(CHAT_PORTRAIT_EYES),mouth:z35.enum(CHAT_PORTRAIT_MOUTHS),color:z35.enum(CHAT_PORTRAIT_COLORS)})}});import{z as z36}from"zod";function isIanaTimezone(value){try{return new Intl.DateTimeFormat("en-US",{timeZone:value}),!0}catch{return!1}}var ChatRoutineCronSchema,ChatRoutineTimezoneSchema,ChatRoutineScheduleSchema,ChatRoutineNameSchema,ChatRoutineInstructionsSchema,ChatRoutineDescriptionSchema,ChatRoutineModelSchema,ChatRoutineWaitMinutesSchema,ChatRoutineEventTriggerDTOSchema,ChatRoutineEventTriggerInputSchema,ChatRoutineTriggersDTOSchema,ChatRoutineRunOutcomeSchema,ChatRoutineReportSchema,ChatRoutineDTOSchema,ChatRoutineListDTOSchema,AgentHoursUsageDTOSchema,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=z36.string().trim().max(64).regex(/^\S+(?: \S+){4}$/,"A schedule is a five-field cron expression");__name(isIanaTimezone,"isIanaTimezone");ChatRoutineTimezoneSchema=z36.string().trim().min(1).max(64).refine(isIanaTimezone,"Unknown timezone"),ChatRoutineScheduleSchema=z36.object({cron:ChatRoutineCronSchema,timezone:ChatRoutineTimezoneSchema}),ChatRoutineNameSchema=z36.string().trim().min(1).max(120),ChatRoutineInstructionsSchema=z36.string().trim().min(1).max(2e4),ChatRoutineDescriptionSchema=z36.string().trim().min(1).max(500),ChatRoutineModelSchema=z36.string().trim().min(1).max(120),ChatRoutineWaitMinutesSchema=z36.number().int().min(0).max(120),ChatRoutineEventTriggerDTOSchema=z36.object({text:z36.string(),title:z36.string(),explanation:z36.string(),watches:z36.array(z36.object({url:z36.string(),health:z36.enum(["ok","needs_repair","blocked","unstable"]),lastCheckedAt:z36.string().nullable()})).optional()}),ChatRoutineEventTriggerInputSchema=z36.object({text:z36.string().trim().min(1).max(500)}),ChatRoutineTriggersDTOSchema=z36.object({manual:z36.literal(!0),schedule:ChatRoutineScheduleSchema.nullable(),event:ChatRoutineEventTriggerDTOSchema.nullable()}),ChatRoutineRunOutcomeSchema=z36.enum(["quiet","reported","decision","incomplete","failed","running"]),ChatRoutineReportSchema=z36.object({message:z36.string().trim().min(1).max(2e4),decision:z36.boolean().optional(),incomplete:z36.boolean().optional(),remaining:z36.number().int().min(0).optional()}).refine(report2=>!(report2.decision===!0&&report2.incomplete===!0),{message:"A run that could not check asks for no decision: set incomplete or decision, not both."}).refine(report2=>!(report2.incomplete===!0&&(report2.remaining??0)>0),{message:"A run that could not check has nothing left to continue: set incomplete or remaining, not both."}),ChatRoutineDTOSchema=z36.object({id:z36.string().uuid(),threadId:z36.string().uuid(),runThreadId:z36.string().uuid(),name:z36.string(),description:z36.string().nullable(),instructions:z36.string(),template:z36.object({key:z36.string()}).nullable(),triggers:ChatRoutineTriggersDTOSchema,model:z36.string(),modelIsDefault:z36.boolean(),waitMinutes:ChatRoutineWaitMinutesSchema,paused:z36.boolean(),nextRunAt:z36.string().nullable(),lastRunAt:z36.string().nullable(),lastOutcome:ChatRoutineRunOutcomeSchema.nullable(),outOfAgentHoursUntil:z36.string().nullable(),createdAt:z36.string(),updatedAt:z36.string()}),ChatRoutineListDTOSchema=z36.object({routines:z36.array(ChatRoutineDTOSchema)}),AgentHoursUsageDTOSchema=z36.object({usedMs:z36.number().int().min(0),includedMs:z36.number().int().min(0),periodStart:z36.string(),periodEnd:z36.string(),stopsAtIncluded:z36.boolean(),canStart:z36.boolean(),canPayOverage:z36.boolean(),overageRateMicrosPerHour:z36.number().int().nullable(),billedMs:z36.number().int().min(0),billedMicros:z36.number().int().min(0)}),ChatRoutineCreateSchema=z36.object({name:ChatRoutineNameSchema,description:ChatRoutineDescriptionSchema.nullable().optional(),instructions:ChatRoutineInstructionsSchema,schedule:ChatRoutineScheduleSchema.nullable().optional(),event:ChatRoutineEventTriggerInputSchema.nullable().optional(),model:ChatRoutineModelSchema.nullable().optional(),waitMinutes:ChatRoutineWaitMinutesSchema.optional()}),ChatRoutineUpdateSchema=z36.object({name:ChatRoutineNameSchema,description:ChatRoutineDescriptionSchema.nullable(),instructions:ChatRoutineInstructionsSchema,schedule:ChatRoutineScheduleSchema.nullable(),event:ChatRoutineEventTriggerInputSchema.nullable(),model:ChatRoutineModelSchema.nullable(),waitMinutes:ChatRoutineWaitMinutesSchema,paused:z36.boolean()}).partial().refine(update=>Object.values(update).some(value=>value!==void 0),"Change at least one field"),ChatRoutineRefusalReasonSchema=z36.enum(["routine_cadence_too_frequent","routine_schedule_invalid","routine_owner_not_agent","routine_trigger_unsupported","routine_model_unknown","routine_needs_pro","routine_is_default"]),ChatRoutineRefusalDTOSchema=z36.object({message:z36.string(),reason:ChatRoutineRefusalReasonSchema}),ChatRoutineRunStatusSchema=z36.enum(["queued","running","finished","failed","cancelled"]),ChatRoutineRunTriggerSchema=z36.enum(["schedule","hand","event"]),ChatRoutineRunStartedBySchema=z36.object({kind:z36.enum(["person","agent"]),name:z36.string().nullable()}),ChatRoutineRunDTOSchema=z36.object({messageId:z36.string().uuid(),invocationId:z36.string().uuid().nullable(),startedAt:z36.string(),trigger:ChatRoutineRunTriggerSchema,startedBy:ChatRoutineRunStartedBySchema.nullable(),status:ChatRoutineRunStatusSchema,outcome:ChatRoutineRunOutcomeSchema.nullable(),summary:z36.string().nullable(),events:z36.number().int().min(1),durationMs:z36.number().int().min(0).nullable(),credits:z36.number().int().min(0).nullable()}),ChatRoutineRunListDTOSchema=z36.object({runs:z36.array(ChatRoutineRunDTOSchema)}),ChatRoutineRunRequestSchema=z36.object({message:z36.string().trim().min(1).max(2e4).optional()}),ChatRoutineRunOutcomeDTOSchema=z36.object({kind:z36.enum(["published","queued","replay","streaming","busy","refused"]),messageId:z36.string().uuid().nullable()})}});import{z as z37}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.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=z37.enum(PROJECT_CHAT_MANUAL_MODEL_IDS),ProjectDTOSchema=BaseEntitySchema.extend({name:z37.string(),displayName:z37.string().nullable(),subdomain:z37.string().nullable().optional(),subdomainUpdatedAt:z37.date().nullable().optional(),organizationId:z37.string().nullable(),createdBy:z37.string().nullable(),defaultBranch:BranchSchema.default(DEFAULT_BRANCH),productionSourceBranch:BranchSchema.default(DEFAULT_BRANCH),enabledChatModels:z37.array(ProjectChatManualModelIdSchema).nullable().default(null),status:ProjectStatusSchema,creationStatus:z37.string(),thumbnailUrl:z37.string().nullable(),publishedThumbnailUrl:z37.string().nullable(),category:z37.string().nullable(),snapshotUrl:z37.string().startsWith("/").optional(),appUrl:z37.string().nullable(),lastPublishedAt:z37.coerce.date(),databaseQuotaIncidentId:z37.uuid().nullable().optional(),databaseQuotaLastObservedAt:z37.coerce.date().nullable().optional()}),ProjectDTO=createDTO(ProjectDTOSchema),UpdateProjectSettingsRequestSchema=z37.object({name:z37.string().optional(),enabledChatModels:z37.array(ProjectChatManualModelIdSchema).optional(),productionSourceBranch:BranchSchema.optional(),syncConfig:z37.boolean().optional()}).strict(),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z37.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z37.object({id:z37.uuid(),name:z37.string(),displayName:z37.string().nullable(),thumbnailUrl:z37.string().nullable(),category:z37.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z37.object({id:z37.string(),name:z37.string(),avatar:z37.string().nullable(),color:z37.object({bg:z37.string(),text:z37.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z37.object({path:z37.string(),content:z37.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z37.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z37.object({id:z37.string(),messageId:z37.string(),versionId:z37.string().nullable(),role:ProjectChatMessageRole,parts:z37.array(z37.any()),createdAt:z37.coerce.date()}),MessageUserMetadataSchema=z37.object({id:z37.string(),name:z37.string().nullable().optional(),image:z37.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z37.number(),metadata:z37.object({user:MessageUserMetadataSchema,changeManifest:z37.array(z37.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z37.object({versionId:z37.uuid(),commitHash:z37.string(),name:z37.string(),description:z37.string().nullable(),kind:z37.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z37.object({versionCount:z37.number().int().nonnegative(),snapshotBytes:z37.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z37.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z37.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z37.object({content:z37.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z37.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z37.object({success:z37.boolean(),message:z37.string().optional(),warning:z37.string().optional(),durationMs:z37.number().int().nonnegative().optional()})),PublishUpgradeRequiredSchema=z37.object({code:z37.literal("PUBLISH_UPGRADE_REQUIRED"),message:z37.string(),currentVersion:z37.number().int().positive(),targetVersion:z37.literal(4)}),ProjectLatestPublicationAttemptSchema=z37.object({publicationId:z37.uuid(),status:z37.enum(["queued","building","published","failed","canceled"]),failureCode:z37.string().nullable(),sourceBranch:z37.string(),createdAt:CommonSchemas.timestamp,finishedAt:CommonSchemas.timestamp.nullable()}),ProjectPublicationStateDTOSchema=z37.object({isPublished:z37.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z37.string().nullable(),upgradeRequired:PublishUpgradeRequiredSchema.nullish(),hasActiveRelease:z37.boolean().optional(),latestAttempt:ProjectLatestPublicationAttemptSchema.nullish()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublishProjectRequestSchema=z37.object({label:z37.string().trim().min(1).max(120).optional(),notes:z37.string().max(2e4).optional()}).strict(),PublicationMutationDTOSchema=z37.object({success:z37.boolean(),message:z37.string().optional(),publishedAt:CommonSchemas.timestamp.optional(),firstPublish:z37.boolean(),publicationId:z37.string().optional(),url:z37.string().nullable().optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z38}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatLiveTurnStateDTOSchema,ChatLiveTurnStateDTO,ChatMessageAuthorDTOSchema,ChatThreadMessageDTOSchema,ChatQueuedMessageDTOSchema,ChatAttentionDTOSchema,ChatThreadMessagesPageDTOSchema,ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema,ChatNonStreamingOutcomeDTOSchema,ProjectChatKindSchema,ProjectChatCreatableKindSchema,ProjectChatRoutinesDTOSchema,ProjectChatDescriptionSchema,ProjectChatInstructionsSchema,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_organization_features_dto();init_project_dto();ChatMessageListDTOSchema=z38.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z38.object({items:z38.array(ProjectMessagePublicDTOSchema),nextCursor:z38.string().nullable()}),ChatLiveTurnDTOSchema=z38.object({invocationId:z38.string(),step:z38.enum(["preparing","working","compacting","merging"]),startedAt:z38.string(),continuesInvocationId:z38.string().nullable().optional()}),ChatLiveTurnStateDTOSchema=z38.object({threadId:z38.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),ChatLiveTurnStateDTO=createDTO(ChatLiveTurnStateDTOSchema),ChatMessageAuthorDTOSchema=z38.object({kind:z38.enum(["person","agent","routine","system"]),id:z38.string().nullable()}),ChatThreadMessageDTOSchema=z38.object({id:z38.string(),role:z38.enum(["user","assistant"]),parts:z38.array(z38.unknown()),metadata:z38.record(z38.string(),z38.unknown()).nullable(),versionId:z38.string().nullable().optional(),createdAt:z38.date().transform(value=>value.toISOString()),providerMessageId:z38.string().nullable().optional(),author:ChatMessageAuthorDTOSchema,invocationId:z38.string().nullable().optional(),invocationStatus:z38.string().nullable().optional(),invocationTerminalReason:z38.string().nullable().optional()}),ChatQueuedMessageDTOSchema=z38.object({id:z38.string(),parts:z38.array(z38.unknown()),metadata:z38.record(z38.string(),z38.unknown()).nullable(),providerMessageId:z38.string().nullable().optional(),author:ChatMessageAuthorDTOSchema,failed:z38.boolean(),queuedAt:z38.date().transform(value=>value.toISOString())}),ChatAttentionDTOSchema=z38.object({type:z38.literal("merge_conflict"),merge:z38.object({mergeId:z38.string().uuid(),projectId:z38.string(),fromBranch:z38.string(),toBranch:z38.string()}),publishAfterMerge:z38.boolean()}),ChatThreadMessagesPageDTOSchema=z38.object({threadId:z38.string().nullable(),title:z38.string().nullable(),messages:z38.array(ChatThreadMessageDTOSchema),nextCursor:z38.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional(),queue:z38.array(ChatQueuedMessageDTOSchema).optional(),queuePaused:z38.boolean().optional(),queueWaitUntil:z38.string().nullable().optional()}),ChatReplayOutcomeDTOSchema=z38.object({kind:z38.literal("replay"),threadId:z38.string(),userMessageId:z38.string()}),ChatQueuedOutcomeDTOSchema=z38.object({kind:z38.literal("queued"),threadId:z38.string(),userMessageId:z38.string(),blockingRootId:z38.string().optional()}),ChatBusyOutcomeDTOSchema=z38.object({kind:z38.literal("busy"),threadId:z38.string(),userMessageId:z38.string(),blockingRootId:z38.string().optional()}),ChatRefusedOutcomeDTOSchema=z38.object({kind:z38.literal("refused"),threadId:z38.string(),userMessageId:z38.string(),refusedInvocationId:z38.string(),terminalReason:z38.string()}),ChatNonStreamingOutcomeDTOSchema=z38.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ProjectChatKindSchema=z38.enum(["chat","agent","routine","task"]),ProjectChatCreatableKindSchema=z38.enum(["chat","agent"]),ProjectChatRoutinesDTOSchema=z38.object({quietRuns:z38.number().int().nonnegative(),since:z38.string().nullable(),lastOutcome:ChatRoutineRunOutcomeSchema.nullable(),lastRunAt:z38.string().nullable(),nextRunAt:z38.string().nullable(),wakesOnChanges:z38.boolean()}),ProjectChatDescriptionSchema=z38.string().trim().max(2e3),ProjectChatInstructionsSchema=z38.string().trim().max(8e3),ProjectChatDTOSchema=z38.object({id:z38.string().uuid(),kind:ProjectChatKindSchema,title:z38.string().nullable(),description:z38.string().nullable(),instructions:z38.string().nullable(),liveAt:z38.string().nullable(),template:z38.string().nullable(),parentThreadId:z38.string().uuid().nullable(),routines:ProjectChatRoutinesDTOSchema.nullable(),createdAt:z38.string(),lastMessageAt:z38.string().nullable(),preview:z38.string().nullable(),running:z38.boolean(),awaitingAnswer:z38.boolean(),unread:z38.boolean(),pinned:z38.boolean(),archived:z38.boolean(),muted:z38.boolean(),portrait:ChatPortraitSchema.nullable()}),ProjectChatListDTOSchema=z38.object({chats:z38.array(ProjectChatDTOSchema)}),ProjectChatCreatedDTOSchema=z38.object({id:z38.string().uuid()}),ProjectChatTitleSchema=z38.string().trim().min(1).max(120),ProjectChatCreateSchema=z38.object({id:z38.string().uuid(),portrait:ChatPortraitSchema,kind:ProjectChatCreatableKindSchema,title:ProjectChatTitleSchema,description:ProjectChatDescriptionSchema,template:z38.string().min(1).max(64),timezone:ChatRoutineTimezoneSchema,setup:z38.literal(!0),locale:z38.string().trim().min(2).max(16)}).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").refine(create=>create.setup===void 0||create.kind==="agent","Only an agent is set up in its chat"),ProjectChatUpdateSchema=z38.object({title:ProjectChatTitleSchema,description:ProjectChatDescriptionSchema,instructions:ProjectChatInstructionsSchema,portrait:ChatPortraitSchema}).partial().refine(update=>update.title!==void 0||update.description!==void 0||update.instructions!==void 0||update.portrait!==void 0,"Set a title, a description, instructions or a portrait"),ChatTemplateRoutineScheduleDTOSchema=z38.object({cron:z38.string()}),ChatTemplateRoutineDTOSchema=z38.object({name:z38.string(),description:z38.string(),instructions:z38.string(),schedule:ChatTemplateRoutineScheduleDTOSchema.nullable(),plans:z38.array(AgentPlanSchema)}),ChatTemplateDTOSchema=z38.object({id:z38.string(),name:z38.string(),summary:z38.string(),description:z38.string(),greeting:z38.string(),starters:z38.array(z38.string()),portrait:ChatPortraitSchema,plans:z38.array(AgentPlanSchema),routines:z38.array(ChatTemplateRoutineDTOSchema)}),ChatTemplateListDTOSchema=z38.object({templates:z38.array(ChatTemplateDTOSchema)}),ProjectChatStateSchema=z38.object({read:z38.boolean(),pinned:z38.boolean(),archived:z38.boolean(),muted:z38.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 z39}from"zod";var ADMIN_ASSISTANT_BASE_PATH,ADMIN_ASSISTANT_PATHS,ADMIN_ASSISTANT_MESSAGE_MAX_CHARS,ADMIN_ASSISTANT_FORM_NOTE_MAX_CHARS,ADMIN_ASSISTANT_REQUEST_MAX_BYTES,AdminAssistantFormResponseSchema,AdminAssistantOutgoingMessageSchema,AdminAssistantSendRequestSchema,AdminAssistantSendOutcomeSchema,AdminAssistantStreamHeadSchema,AdminAssistantThreadSummarySchema,AdminAssistantThreadListQuerySchema,AdminAssistantThreadListResponseSchema,AdminAssistantThreadResponseSchema,AdminAssistantLiveTurnResponseSchema,AdminAssistantAbortResponseSchema,AdminAssistantThreadUpdateSchema,AdminAssistantThreadDeleteResponseSchema,init_admin_assistant=__esm({"../../packages/api-contracts/dist/esm/types/admin-assistant.js"(){"use strict";init_chat_dto();init_chat_block();ADMIN_ASSISTANT_BASE_PATH="/api/ops/assistant",ADMIN_ASSISTANT_PATHS={chat:`${ADMIN_ASSISTANT_BASE_PATH}/chat`,threads:`${ADMIN_ASSISTANT_BASE_PATH}/threads`,thread:__name(threadId=>`${ADMIN_ASSISTANT_BASE_PATH}/threads/${encodeURIComponent(threadId)}`,"thread"),live:__name(threadId=>`${ADMIN_ASSISTANT_BASE_PATH}/threads/${encodeURIComponent(threadId)}/live`,"live"),stream:__name(threadId=>`${ADMIN_ASSISTANT_BASE_PATH}/threads/${encodeURIComponent(threadId)}/stream`,"stream"),abort:__name(threadId=>`${ADMIN_ASSISTANT_BASE_PATH}/threads/${encodeURIComponent(threadId)}/abort`,"abort")},ADMIN_ASSISTANT_MESSAGE_MAX_CHARS=2e4,ADMIN_ASSISTANT_FORM_NOTE_MAX_CHARS=4e3,ADMIN_ASSISTANT_REQUEST_MAX_BYTES=256*1024,AdminAssistantFormResponseSchema=ChatFormResponseSchema.extend({questions:z39.array(ChatFormAnswerItemSchema.extend({answer:z39.string().min(1).max(ADMIN_ASSISTANT_FORM_NOTE_MAX_CHARS+1200),freeText:z39.string().max(ADMIN_ASSISTANT_FORM_NOTE_MAX_CHARS)})).max(4)}),AdminAssistantOutgoingMessageSchema=z39.object({id:z39.string().min(1).max(255).regex(/^(app|e2e):/,"Message ids from a client start with app:"),text:z39.string().max(ADMIN_ASSISTANT_MESSAGE_MAX_CHARS)}).strict(),AdminAssistantSendRequestSchema=z39.object({threadId:z39.string().uuid().optional(),message:AdminAssistantOutgoingMessageSchema,formResponse:AdminAssistantFormResponseSchema.optional()}).strict().superRefine((body,context)=>{body.message.text.trim().length===0&&!body.formResponse&&context.addIssue({code:"custom",path:["message","text"],message:"A message cannot be empty."})}),AdminAssistantSendOutcomeSchema=z39.discriminatedUnion("kind",[z39.object({kind:z39.literal("replay"),threadId:z39.string(),userMessageId:z39.string()}),z39.object({kind:z39.literal("queued"),threadId:z39.string(),userMessageId:z39.string(),blockingRootId:z39.string().optional()}),z39.object({kind:z39.literal("busy"),threadId:z39.string(),userMessageId:z39.string(),blockingRootId:z39.string().optional()}),z39.object({kind:z39.literal("refused"),threadId:z39.string(),userMessageId:z39.string(),refusedInvocationId:z39.string(),terminalReason:z39.string()})]),AdminAssistantStreamHeadSchema=z39.object({kind:z39.literal("turn"),threadId:z39.string(),userMessageId:z39.string(),invocationId:z39.string()}),AdminAssistantThreadSummarySchema=z39.object({id:z39.string().uuid(),title:z39.string().nullable(),lastMessageAt:z39.string().nullable(),createdAt:z39.string()}),AdminAssistantThreadListQuerySchema=z39.object({q:z39.string().trim().max(200).optional(),cursor:z39.string().max(500).optional(),limit:z39.coerce.number().int().min(1).max(100).optional()}),AdminAssistantThreadListResponseSchema=z39.object({threads:z39.array(AdminAssistantThreadSummarySchema),nextCursor:z39.string().nullable()}),AdminAssistantThreadResponseSchema=z39.object({thread:AdminAssistantThreadSummarySchema.extend({createdBy:z39.string().nullable()}),messages:z39.array(ChatThreadMessageDTOSchema),liveTurn:ChatLiveTurnDTOSchema.nullable()}),AdminAssistantLiveTurnResponseSchema=z39.object({threadId:z39.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable()}),AdminAssistantAbortResponseSchema=z39.object({aborted:z39.boolean()}),AdminAssistantThreadUpdateSchema=z39.object({title:ProjectChatTitleSchema}).strict(),AdminAssistantThreadDeleteResponseSchema=z39.object({deleted:z39.literal(!0)})}});import{z as z40}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=z40.enum(REPORT_TONES),blockCommon={title:z40.string().trim().min(1).max(120).optional(),fallback:z40.string().trim().min(1).max(600).optional()},ReportTextBlockSchema=z40.object({type:z40.literal("text"),...blockCommon,text:z40.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=z40.object({type:z40.literal("metric"),...blockCommon,items:z40.array(z40.object({value:z40.string().trim().min(1).max(24),unit:z40.string().trim().min(1).max(12).optional(),label:z40.string().trim().min(1).max(160),note:z40.string().trim().min(1).max(300).optional()}).strict()).min(1).max(3),spark:z40.array(z40.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=z40.enum(REPORT_VIZ_KINDS),ReportVizBlockSchema=z40.object({type:z40.literal("viz"),...blockCommon,kind:ReportVizKindSchema.describe("bar: compare named quantities. line/area: change across an ordered sequence. composition: parts of one whole."),unit:z40.string().trim().min(1).max(12).optional(),points:z40.array(z40.object({label:z40.string().trim().min(1).max(24),value:z40.number().finite(),highlight:z40.boolean().optional()}).strict()).min(2).max(24),caption:z40.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=z40.object({type:z40.literal("list"),...blockCommon,items:z40.array(z40.object({tone:ReportToneSchema.optional(),label:z40.string().trim().min(1).max(24).optional(),heading:z40.string().trim().min(1).max(160).describe("The human-visible result, action, or consequence, readable on its own."),body:z40.string().trim().min(1).max(1200).optional().describe("One short explanation of why it matters."),evidence:z40.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=z40.object({type:z40.literal("table"),...blockCommon,columns:z40.array(z40.object({label:z40.string().trim().min(1).max(32)}).strict()).min(1).max(6),rows:z40.array(z40.object({cells:z40.array(z40.object({text:z40.string().trim().max(160),tone:ReportToneSchema.optional()}).strict()).min(1).max(6)}).strict()).min(1).max(40),caption:z40.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=z40.object({type:z40.literal("media"),...blockCommon,assetId:z40.uuid(),alt:z40.string().trim().min(1).max(300),caption:z40.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=z40.object({type:z40.literal("links"),...blockCommon,items:z40.array(z40.object({label:z40.string().trim().min(1).max(120),url:z40.url({protocol:/^https$/}).max(2e3),description:z40.string().trim().min(1).max(300).optional()}).strict()).min(1).max(8)}).strict().describe("A destination, evidence source, or next action worth opening."),ReportCodeBlockSchema=z40.object({type:z40.literal("code"),...blockCommon,language:z40.string().regex(/^[a-z0-9+#-]{1,20}$/,"A language is a short lowercase token, e.g. ts, json, bash.").optional(),code:z40.string().min(1).max(REPORT_CODE_MAX_CHARS),caption:z40.string().trim().min(1).max(600).optional()}).strict().describe("An exact snippet that is decisive evidence. Never a log dump."),ReportBlockSchema=z40.discriminatedUnion("type",[ReportTextBlockSchema,ReportMetricBlockSchema,ReportListBlockSchema,ReportTableBlockSchema,ReportVizBlockSchema,ReportMediaBlockSchema,ReportLinksBlockSchema,ReportCodeBlockSchema]),ReportDocumentSchema=z40.object({title:z40.string().trim().min(1).max(REPORT_TITLE_MAX_CHARS),brief:z40.array(ReportBlockSchema).min(1).max(REPORT_BRIEF_MAX_BLOCKS),details:z40.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=z40.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=z40.preprocess(normalizeStoredBlocks,ReportBriefSchema),StoredReportDocumentSchema=z40.preprocess(normalizeStoredDocument,ReportDocumentSchema);__name(derivedBlockBody,"derivedBlockBody");__name(reportSectionContentLength,"reportSectionContentLength");__name(formatReportNumber,"formatReportNumber");__name(formatReportValue,"formatReportValue")}});import{z as z41}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=z41.enum(["astro","nextjs","nuxtjs","react-router","remix","sveltekit","vite","vue"]),FimoRuntimeCommandsSchema=z41.object({dev:z41.string().trim().min(1).optional(),build:z41.string().trim().min(1).optional(),install:z41.string().trim().min(1).optional()}).strict(),FimoRuntimeConfigSchema=z41.object({framework:FimoFrameworkSchema.optional(),outputDirectory:z41.string().trim().min(1).optional(),commands:FimoRuntimeCommandsSchema.optional()}).strict(),FimoHostingConditionSchema=z41.object({type:z41.enum(["header","cookie","query","host"]),key:z41.string().min(1).optional(),value:z41.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:z41.array(FimoHostingConditionSchema).min(1).optional(),missing:z41.array(FimoHostingConditionSchema).min(1).optional()},FimoHostingRewriteSchema=z41.object({source:z41.string().min(1),destination:z41.string().min(1),...conditionFields}),FimoHostingRedirectSchema=z41.object({source:z41.string().min(1),destination:z41.string().min(1),permanent:z41.boolean().optional(),statusCode:z41.union([z41.literal(301),z41.literal(302),z41.literal(307),z41.literal(308)]).optional(),...conditionFields}),FimoHostingHeaderSchema=z41.object({source:z41.string().min(1),headers:z41.array(z41.object({key:z41.string().min(1),value:z41.string()})).min(1),...conditionFields}),FimoHostingConfigSchema=z41.object({rewrites:z41.array(FimoHostingRewriteSchema).optional(),redirects:z41.array(FimoHostingRedirectSchema).optional(),headers:z41.array(FimoHostingHeaderSchema).optional(),cleanUrls:z41.boolean().optional(),trailingSlash:z41.boolean().optional()}).strict(),FimoAppConfigSchema=z41.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(path52){return[...path52.matchAll(/:([^/*]+)\*?/g)].map(match=>match[1])}function pageContentParamNames(path52,params){return pageRouteParamNames(path52).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 z42}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=z42.enum(["provisioning","active","deleted"]),ProjectBranchKindSchema=z42.enum(["user","agent-session"]),ProjectBranchDTOSchema=BaseEntitySchema.extend({projectId:z42.uuid(),branch:BranchSchema.optional(),status:ProjectBranchStatusSchema,kind:ProjectBranchKindSchema,parentBranch:BranchSchema.nullable().optional(),createdBy:z42.string().nullable(),deletedAt:z42.coerce.date().nullable(),env:BranchSchema,parentEnv:BranchSchema.nullable()}),ProjectBranchDTO=createDTO(ProjectBranchDTOSchema),ResolvedBranchEnvironmentDTOSchema=z42.object({id:z42.union([z42.literal(PREVIEW_ENVIRONMENT_KEY),z42.uuid()]),name:z42.string()}),ProjectBranchListItemDTOSchema=ProjectBranchDTOSchema.extend({resolvedEnvironment:ResolvedBranchEnvironmentDTOSchema.nullable(),workSession:z42.object({sessionId:z42.uuid(),name:z42.string()}).optional()}),ProjectBranchListItemDTO=createDTO(ProjectBranchListItemDTOSchema),CreateProjectBranchRequestInputSchema=z42.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=z42.object({from:BranchSchema.optional()}),ProjectBranchResponseSchema=createResponseSchema(ProjectBranchDTOSchema),ProjectBranchesListResponseSchema=createResponseSchema(z42.array(ProjectBranchListItemDTOSchema)),BranchSurfaceDiffSchema=z42.object({surface:z42.enum(["code","schemas","content","translations","assets","forms"]),status:z42.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z42.number().int().nonnegative(),conflictCount:z42.number().int().nonnegative()}),BranchDiffResultSchema=z42.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),generatedAt:z42.coerce.date(),surfaces:z42.array(BranchSurfaceDiffSchema),fromEnv:BranchSchema,toEnv:BranchSchema}),BranchDiffResultDTO=createDTO(BranchDiffResultSchema)}});import{z as z43}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=z43.object({projectId:z43.uuid(),name:z43.string()}),ProductionEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z43.literal(PRODUCTION_ENVIRONMENT_KEY),kind:z43.literal("production"),sourceBranch:BranchSchema,isPublished:z43.boolean(),url:z43.string().nullable()}),PreviewEnvironmentDTOSchema=ProjectEnvironmentBaseSchema.extend({id:z43.literal(PREVIEW_ENVIRONMENT_KEY),kind:z43.literal("preview"),matchedBranchCount:z43.number().int().nonnegative()}),CustomProjectEnvironmentDTOSchema=CustomEnvironmentSchema.extend({kind:z43.literal("custom"),matchedBranchCount:z43.number().int().nonnegative()}),ProjectEnvironmentDTOSchema=z43.discriminatedUnion("kind",[ProductionEnvironmentDTOSchema,PreviewEnvironmentDTOSchema,CustomProjectEnvironmentDTOSchema]),ProjectEnvironmentDTO=createDTO(ProjectEnvironmentDTOSchema),CreateProjectEnvironmentRequestSchema=CustomEnvironmentSchema.pick({name:!0,branchPatterns:!0,description:!0}).extend({description:z43.string().trim().max(255).nullable().optional().default(null)}),ProjectEnvironmentsListResponseSchema=createResponseSchema(z43.array(ProjectEnvironmentDTOSchema)),ProjectEnvironmentResponseSchema=createResponseSchema(ProjectEnvironmentDTOSchema),DeleteProjectEnvironmentResultSchema=z43.object({deletedId:z43.uuid()}),DeleteProjectEnvironmentResponseSchema=createResponseSchema(DeleteProjectEnvironmentResultSchema)}});import{z as z44}from"zod";var ProjectSecretsListQuerySchema,ProjectSecretWriteRequestSchema,CreateProjectSecretRequestSchema,DeleteProjectSecretQuerySchema,ProjectSecretMetadataDTOSchema,ProjectSecretMetadataDTO,ProjectVariableBaseSchema,ProjectVariableDTOSchema,ProjectVariableDTO,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=z44.object({kind:z44.enum(["variable","secret"]).optional(),environment:EnvironmentKeySchema}),ProjectSecretWriteRequestSchema=z44.object({kind:z44.enum(["variable","secret"]),value:z44.string(),environment:EnvironmentKeySchema}),CreateProjectSecretRequestSchema=ProjectSecretWriteRequestSchema.extend({key:z44.string().min(1).max(255),exposure:z44.enum(["public","private"]).optional()}),DeleteProjectSecretQuerySchema=z44.object({kind:z44.enum(["variable","secret"]),environment:EnvironmentKeySchema}),ProjectSecretMetadataDTOSchema=z44.object({id:z44.uuid(),projectId:z44.uuid(),key:z44.string(),kind:z44.literal("secret"),exposure:z44.literal("private"),environment:EnvironmentKeySchema,maskedValue:z44.string().optional(),createdAt:z44.date().transform(value=>value.toISOString()),updatedAt:z44.date().transform(value=>value.toISOString())}),ProjectSecretMetadataDTO=createDTO(ProjectSecretMetadataDTOSchema),ProjectVariableBaseSchema=z44.object({id:z44.uuid(),projectId:z44.uuid(),key:z44.string(),kind:z44.literal("variable"),environment:EnvironmentKeySchema,managed:z44.boolean(),createdAt:z44.date().transform(value=>value.toISOString()),updatedAt:z44.date().transform(value=>value.toISOString())}),ProjectVariableDTOSchema=z44.discriminatedUnion("exposure",[ProjectVariableBaseSchema.extend({exposure:z44.literal("public"),value:z44.string()}),ProjectVariableBaseSchema.extend({exposure:z44.literal("private"),maskedValue:z44.string().optional()})]),ProjectVariableDTO=createDTO(ProjectVariableDTOSchema),ProjectSecretsListResponseSchema=createResponseSchema(z44.array(ProjectSecretMetadataDTOSchema)),ProjectSecretResponseSchema=createResponseSchema(ProjectSecretMetadataDTOSchema)}});import{z as z45}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=z45.object({success:z45.literal(!0),downloadUrl:z45.string(),expiresAt:z45.string(),fileSize:z45.number(),duration:z45.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z45.object({success:z45.literal(!0),projectId:z45.string(),projectName:z45.string(),displayName:z45.string(),projectUrl:z45.string(),duration:z45.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z45.object({contentTypes:z45.number(),entries:z45.number(),assets:z45.number(),translations:z45.number(),forms:z45.number(),codeFiles:z45.number(),assetFiles:z45.number()}),ImportPreviewSurfaceDTOSchema=z45.object({name:z45.string(),included:z45.boolean(),count:z45.number().optional(),note:z45.string().optional()}),ImportPreviewDTOSchema=z45.object({projectName:z45.string(),displayName:z45.string().nullable(),category:z45.string().nullable(),exportedAt:z45.string(),version:z45.string(),envScope:z45.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z45.array(ImportPreviewSurfaceDTOSchema),fileSize:z45.number(),fileName:z45.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z45.object({success:z45.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z46}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,ConflictTargetCommitSchema,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=z46.enum(["code","schemas","content","translations","assets","forms"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms"],SurfaceDeltaVerbSchema=z46.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z46.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z46.object({verb:SurfaceDeltaVerbSchema,key:z46.string(),detail:z46.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z46.record(z46.string(),z46.unknown()).optional()}),PerSurfaceDeltaSchema=z46.object({surface:SurfaceNameSchema,status:z46.enum(["ok","timed_out","failed","unchanged"]),durationMs:z46.number().int().nonnegative().optional(),changedCount:z46.number().int().nonnegative(),conflictCount:z46.number().int().nonnegative(),items:z46.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z46.boolean().optional(),error:z46.string().optional()}),CrossSurfaceFindingSchema=z46.object({id:z46.string(),kind:z46.string(),description:z46.string(),severity:z46.enum(["warning","error"]),source:z46.object({surface:SurfaceNameSchema,key:z46.string()}),target:z46.object({surface:SurfaceNameSchema,key:z46.string()}),actions:z46.array(z46.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z46.object({branch:BranchSchema.optional(),env:BranchSchema,vs:BranchSchema,syncState:z46.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z46.coerce.date(),surfaces:z46.array(PerSurfaceDeltaSchema),agents:z46.array(z46.object({id:z46.string(),name:z46.string(),status:z46.enum(["active","paused","failed"]),lastRunAt:z46.coerce.date().nullable()})).optional(),crossSurface:z46.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z46.object({fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,generatedAt:z46.coerce.date(),surfaces:z46.array(PerSurfaceDeltaSchema),crossSurface:z46.array(CrossSurfaceFindingSchema).optional(),fingerprint:z46.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z46.object({path:z46.string(),state:z46.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z46.string(),additions:z46.number().int().nonnegative(),deletions:z46.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z46.object({oid:z46.string().optional(),content:z46.string().optional(),truncated:z46.boolean(),binary:z46.boolean()}),CodeConflictDetailSchema=z46.object({path:z46.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z46.string(),targetTipSha:z46.string(),mergeBaseSha:z46.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z46.object({id:z46.string(),slug:z46.string(),contentType:z46.string(),data:z46.record(z46.string(),z46.unknown()),updatedAt:z46.coerce.date()}),ContentRowDiffSchema=z46.object({collection:z46.string(),rowId:z46.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z46.object({name:z46.string(),label:z46.string(),isSingleton:z46.boolean(),fields:z46.record(z46.string(),z46.unknown())}),SchemaTypeDiffSchema=z46.object({typeName:z46.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z46.object({id:z46.string(),name:z46.string(),type:z46.enum(["file","folder"]),mimeType:z46.string().nullable(),storageKey:z46.string().nullable(),url:z46.string().nullable(),fileSize:z46.number().nullable(),width:z46.number().nullable(),height:z46.number().nullable(),altText:z46.string().nullable(),caption:z46.string().nullable(),createdAt:z46.coerce.date(),updatedAt:z46.coerce.date()}),AssetDiffSchema=z46.object({assetId:z46.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z46.object({locale:z46.string(),key:z46.string(),parent:z46.string().nullable(),child:z46.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z46.object({formName:z46.string(),label:z46.string().nullable(),schemaFingerprint:z46.string(),fields:z46.record(z46.string(),z46.unknown()),settings:z46.record(z46.string(),z46.unknown()).optional()}),FormSchemaDiffSchema=z46.object({formName:z46.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=z46.enum(CONFLICT_KINDS),ConflictTargetCommitSchema=z46.object({sha:z46.string(),subject:z46.string(),body:z46.string().optional(),author:z46.string(),date:z46.string()}),ConflictSchema=z46.object({surface:SurfaceNameSchema,key:z46.string(),kind:ConflictKindSchema.optional(),description:z46.string(),parentValue:z46.unknown().optional(),childValue:z46.unknown().optional(),conflictingFields:z46.array(z46.string()).optional(),code:z46.object({path:z46.string(),unresolvable:z46.boolean().optional(),reason:z46.string().optional(),targetCommits:z46.array(ConflictTargetCommitSchema).optional()}).optional()}),FieldPickSchema=z46.object({field:z46.string(),choice:z46.enum(["parent","child","pick","ai-pick"]),pickedValue:z46.unknown().optional(),aiSessionId:z46.string().optional()}),ConflictResolutionSchema=z46.object({surface:SurfaceNameSchema,key:z46.string(),choice:z46.enum(["parent","child","pick"]),pickedValue:z46.unknown().optional(),fieldPicks:z46.array(FieldPickSchema).optional()}),MergeResultSchema=z46.object({ok:z46.boolean(),mergeId:z46.string().uuid(),fromBranch:BranchSchema.optional(),toBranch:BranchSchema.optional(),fromEnv:BranchSchema,toEnv:BranchSchema,applied:z46.array(z46.object({surface:SurfaceNameSchema,count:z46.number().int().nonnegative()})),conflicts:z46.array(ConflictSchema).optional(),summary:z46.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z46.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z46.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z46.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z46.boolean().optional()}),ResolvedStrategySchema=z46.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z46.boolean()}),MergeRequestSchema=z46.object({from:BranchSchema,allowDirectMerge:z46.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z46.object({mergeId:z46.string().uuid(),streamUrl:z46.string(),strategy:ResolvedStrategySchema,acceptedAt:z46.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z46.object({mergeId:z46.string().uuid(),fromEnv:BranchSchema,toEnv:BranchSchema,status:z46.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z46.array(ConflictSchema),draftResolutions:z46.array(ConflictResolutionSchema),lastEditedBy:z46.string().nullable(),lastEditedAt:z46.coerce.date().nullable(),initiator:z46.object({userId:z46.string().nullable(),role:z46.string().nullable(),agentName:z46.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z46.object({resolutions:z46.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z46.object({mergeId:z46.string().uuid(),draftResolutions:z46.array(ConflictResolutionSchema),lastEditedAt:z46.coerce.date(),lastEditedBy:z46.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z46.object({mergeId:z46.string().uuid(),resolutions:z46.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z46.object({mergeId:z46.string().uuid()}),PublishReleaseRequestSchema=z46.object({version:z46.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z46.string().max(2e4).optional()}),PublishReleaseResultSchema=z46.object({releaseTag:z46.string(),sha:z46.string(),publishedAt:z46.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z47}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=z47.enum(["planned","running","finished","cancelled","errored"]),AgentSessionReviewPublicationSchema=z47.enum(["pending","merged","conflict","not_published"]),AgentSessionReviewSummarySchema=z47.object({capturedAt:z47.coerce.date(),fingerprint:z47.string().min(1).max(256),counts:z47.object({code:z47.number().int().nonnegative(),content:z47.number().int().nonnegative(),schemas:z47.number().int().nonnegative(),labels:z47.number().int().nonnegative(),assets:z47.number().int().nonnegative().optional()}),publication:AgentSessionReviewPublicationSchema,mergeId:z47.uuid().nullable()}),AgentSessionReviewSummaryDTO=createDTO(AgentSessionReviewSummarySchema),AgentSessionReviewPayloadSchema=z47.object({diff:DiffReportSchema,code:z47.array(CodeFileDiffSchema.extend({raw:z47.string().max(24576)})).max(200),schemas:z47.array(SchemaTypeDiffSchema).max(200),content:z47.array(z47.object({key:z47.string().min(1).max(512),collection:z47.string().min(1).max(256),slug:z47.string().max(512).optional(),verb:z47.enum(["added","modified","deleted"]),fields:z47.array(z47.object({name:z47.string().min(1).max(256),before:z47.unknown().optional(),after:z47.unknown().optional()})).max(20)})).max(200),labels:z47.array(z47.object({key:z47.string().min(1).max(512),locale:z47.string().min(1).max(64).optional(),before:z47.unknown().nullable(),after:z47.unknown().nullable()})).max(200),assets:z47.array(z47.object({key:z47.string().min(1).max(512),name:z47.string().min(1).max(512),verb:z47.enum(["added","modified","deleted"]),before:AssetSnapshotSchema.nullable(),after:AssetSnapshotSchema.nullable()})).max(200).default([])}),AgentSessionReviewPayloadDTO=createDTO(AgentSessionReviewPayloadSchema),AgentSessionReviewPayloadResponseSchema=createResponseSchema(AgentSessionReviewPayloadSchema),SessionErrorCodeSchema=z47.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid"])}});import{z as z48}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=z48.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z48.enum(["auto-merge","review-merged","review-discarded"]),WorkSessionReviewSchema=z48.object({sessionId:z48.uuid(),branch:z48.string().min(1),targetBranch:z48.string().min(1),revision:z48.string().min(1),fingerprint:z48.string().min(1),source:z48.enum(["studio","slack","mcp"]),threadId:z48.uuid().nullable(),invocationId:z48.uuid().nullable(),conversationBranch:z48.string().nullable(),capturedAt:z48.string(),surfaces:z48.array(PerSurfaceDeltaSchema).optional(),counts:z48.record(z48.string(),z48.number().int().nonnegative())}),RequestWorkSessionReviewSchema=z48.strictObject({sessionId:z48.uuid(),summary:z48.string().trim().min(1).max(240),targetBranch:z48.string().trim().min(1).optional()}),WorkSessionReviewResultSchema=z48.object({requested:z48.literal(!0),alreadyRequested:z48.boolean(),reviewId:z48.uuid(),reviewUrl:z48.url(),status:z48.literal("pending"),sessionId:z48.uuid(),branch:z48.string(),targetBranch:z48.string(),revision:z48.string(),savedRevision:z48.string(),fingerprint:z48.string(),visibility:z48.literal("user-visible"),retention:z48.literal("durable"),expiresAt:z48.null(),merged:z48.literal(!1),published:z48.literal(!1),links:z48.object({preview:z48.url(),changes:z48.url(),conversation:z48.url().nullable()})}),AgentBranchProposalDTOSchema=z48.object({id:z48.uuid(),envId:z48.uuid(),sessionId:z48.uuid().nullable(),skillName:z48.string().min(1),classification:AgentBranchClassificationSchema,rationale:z48.string().nullable(),summary:z48.string().nullable(),surfaceDeltas:z48.record(z48.string(),z48.unknown()),review:WorkSessionReviewSchema.optional(),createdAt:z48.coerce.date(),decidedAt:z48.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z48.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z48.object({path:z48.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z48.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z48.object({code:z48.literal("merge_conflict"),message:z48.string(),conflicts:z48.record(z48.string(),z48.number().int().nonnegative())})}});import{z as z49}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=z49.enum(AGENT_QUESTION_STATES),AgentQuestionFormSchema=FormBlockSchema.extend({title:z49.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=z49.object({description:z49.string().trim().min(1).max(240),block:AgentQuestionFormSchema}).strict(),AgentQuestionRequestSchema=AgentQuestionAskSchema.extend({version:z49.literal(QUESTION_FORM_CONTRACT_VERSION),sessionIds:z49.array(z49.uuid()).optional()}),AgentQuestionSchema=z49.object({id:z49.uuid(),projectId:z49.uuid(),threadId:z49.uuid(),invocationId:z49.uuid(),agentKey:z49.string().min(1).max(120),anchorEnv:z49.string().min(1).max(64),retainedEnv:z49.string().min(1).max(64),state:AgentQuestionStateSchema,request:AgentQuestionRequestSchema,answer:QuestionFormAnswerSnapshotSchema.nullable(),answeredByUserId:z49.string().min(1).nullable(),continuationInvocationId:z49.uuid().nullable(),askedAt:z49.coerce.date(),expiresAt:z49.coerce.date(),closedAt:z49.coerce.date().nullable()}),AgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema),RunAgentQuestionResponseSchema=createResponseSchema(AgentQuestionSchema.nullable()),AgentQuestionAttentionSchema=z49.object({questionId:z49.uuid(),invocationId:z49.uuid(),askedAt:z49.coerce.date()}),OpenAgentQuestionsResponseSchema=createResponseSchema(z49.array(AgentQuestionAttentionSchema)),AnswerAgentQuestionResultSchema=z49.object({question:AgentQuestionSchema,continuationInvocationId:z49.uuid(),deduped:z49.boolean()}),AnswerAgentQuestionResponseSchema=createResponseSchema(AnswerAgentQuestionResultSchema)}});import{z as z50}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=z50.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z50.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z50.enum(["secret_text"]),IntegrationCredentialUsageSchema=z50.enum(["http_bearer","api_key"]),IntegrationToolEffectSchema=z50.enum(["read","write","delete","financial"]),ProjectIntegrationCredentialStatusSchema=z50.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z50.object({mode:IntegrationAuthModeSchema,label:z50.string().min(1),description:z50.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z50.object({id:z50.string().min(1),label:z50.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z50.boolean()}),IntegrationToolDefinitionDTOSchema=z50.object({key:z50.string().min(1),name:z50.string().min(1),description:z50.string().min(1),effect:IntegrationToolEffectSchema,input:z50.record(z50.string(),z50.unknown()).optional()}),IntegrationRecipeDTOSchema=z50.object({title:z50.string().min(1),description:z50.string().min(1),command:z50.string().min(1).optional()}),IntegrationInfoDTOSchema=z50.object({key:z50.string().min(1),name:z50.string().min(1),summary:z50.string().min(1),type:z50.enum(["native","mcp"]).optional(),url:z50.string().url().optional(),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z50.array(IntegrationAuthModeDTOSchema),credentials:z50.array(IntegrationCredentialDefinitionDTOSchema),tools:z50.array(IntegrationToolDefinitionDTOSchema),liveToolsStatus:z50.enum(["available","unavailable"]).optional(),connectionCapabilities:z50.object({customIdentityCreation:z50.boolean()}).optional(),recipes:z50.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z50.object({projectId:z50.uuid(),integrationKey:z50.string().min(1),name:z50.string().min(1),summary:z50.string().min(1),installed:z50.boolean(),enabled:z50.boolean(),setupState:z50.enum(["setup_required","ready","attention"]),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z50.string().nullable(),connectionId:z50.uuid().nullable().optional(),connectionAlias:z50.string().min(1).nullable().optional(),connectionStatus:z50.enum(["active","revoked","disconnected"]).nullable(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z50.array(z50.string()),installedAt:z50.coerce.date().nullable(),updatedAt:z50.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z50.object({id:z50.uuid(),projectId:z50.uuid(),integrationKey:z50.string().min(1),enabled:z50.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z50.string(),connectionId:z50.uuid().nullable().optional(),connectionAlias:z50.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z50.array(z50.string()),createdAt:z50.coerce.date(),updatedAt:z50.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z50.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z50.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z50.object({authMode:IntegrationAuthModeSchema}),OrganizationIntegrationConnectionStatusSchema=z50.enum(["active","revoked","disconnected"]),OrganizationIntegrationConnectionDTOSchema=z50.object({id:z50.uuid(),organizationId:z50.string().min(1),integrationKey:z50.string().min(1),registrationId:z50.uuid().nullable(),alias:z50.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z50.string().min(1),externalAccountName:z50.string().nullable(),externalBotUserId:z50.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z50.array(z50.string()),connectedAt:z50.coerce.date(),updatedAt:z50.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionDTOSchema=OrganizationIntegrationConnectionDTOSchema.extend({granted:z50.boolean(),isDefault:z50.boolean()}),ProjectIntegrationConnectionDTO=createDTO(ProjectIntegrationConnectionDTOSchema),McpHeaderNameSchema=z50.string().trim().min(1).max(120).regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,"Header name is invalid."),McpHeaderDefinitionSchema=z50.object({name:McpHeaderNameSchema}),McpSecretMapSchema=z50.record(McpHeaderNameSchema,z50.string().min(1)),ConnectOrganizationIntegrationRequestSchema=z50.object({alias:z50.string().min(1).max(120).optional(),token:z50.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z50.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=z50.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),IntegrationCustomIdentitySchema=z50.object({displayName:z50.string().trim().min(1).max(35),backgroundColor:z50.string().regex(/^#[0-9a-fA-F]{6}$/).optional(),iconUrl:z50.string().url().max(2048).optional()}),ConnectProjectIntegrationRequestSchema=z50.discriminatedUnion("mode",[z50.object({mode:z50.literal("personal"),alias:z50.string().min(1).max(120),token:z50.string().min(1).optional(),secrets:McpSecretMapSchema.optional(),rotate:z50.boolean().optional()}),z50.object({mode:z50.literal("oauth"),returnTo:ProjectIntegrationReturnPathSchema.optional(),reconnect:z50.boolean().optional(),registrationId:z50.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=z50.enum(["none","bearer","header"]),McpIntegrationSetupAuthSchema=z50.union([z50.literal("auto"),McpIntegrationAuthSchema]),AddProjectMcpIntegrationRequestSchema=z50.object({type:z50.literal("mcp"),name:z50.string().trim().min(1).max(120),url:z50.string().url(),auth:McpIntegrationSetupAuthSchema.default("auto"),returnTo:ProjectIntegrationReturnPathSchema.optional(),headers:z50.array(McpHeaderDefinitionSchema).min(1).max(20).optional(),secrets:McpSecretMapSchema.optional(),headerName:McpHeaderNameSchema.optional(),token:z50.string().min(1).optional(),integrationId:z50.string().min(2).max(80).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=z50.object({integrationKey:z50.string().min(1),status:ProjectIntegrationStatusDTOSchema,info:IntegrationInfoDTOSchema}),AddProjectMcpIntegrationResponseSchema=z50.discriminatedUnion("mode",[AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z50.literal("connected")}),AddProjectMcpIntegrationResponseBaseSchema.extend({mode:z50.literal("oauth"),connectUrl:z50.string().url(),expiresAt:z50.coerce.date()})]),ReusableMcpServerAuthKindSchema=z50.enum(["none","bearer","header","oauth"]),ReusableMcpServerDTOSchema=z50.object({id:z50.uuid(),name:z50.string().min(1),host:z50.string().min(1),authKind:ReusableMcpServerAuthKindSchema,sourceProjectName:z50.string().min(1),availability:z50.enum(["available","unavailable"])}),ReusableMcpServerDTO=createDTO(ReusableMcpServerDTOSchema),SearchReusableMcpServersQuerySchema=z50.object({query:z50.string().trim().max(120).optional()}),ReuseProjectMcpIntegrationRequestSchema=z50.object({serverId:z50.uuid()}),LinearOAuthApplicationDistributionSchema=z50.enum(["private","public"]),OrganizationLinearAppDTOSchema=z50.object({id:z50.uuid(),displayName:z50.string().min(1),description:z50.string().nullable(),iconUrl:z50.string().nullable(),distribution:LinearOAuthApplicationDistributionSchema,status:z50.enum(["active","revoked","disconnected"]),connectionIds:z50.array(z50.uuid()),createdAt:z50.coerce.date(),updatedAt:z50.coerce.date()}),OrganizationLinearAppDTO=createDTO(OrganizationLinearAppDTOSchema),CreateManagedLinearAppRequestSchema=z50.object({appName:z50.string().trim().min(2).max(80),description:z50.string().trim().max(1e3).optional(),iconUrl:z50.string().url().max(2048).optional()}),UpdateManagedLinearAppRequestSchema=CreateManagedLinearAppRequestSchema.partial().refine(input=>Object.keys(input).length>0,"At least one Linear app field is required."),StartManagedLinearConnectRequestSchema=z50.object({projectId:z50.uuid(),registrationId:z50.uuid(),returnTo:ProjectIntegrationReturnPathSchema.optional()}),StartProjectIntegrationConnectResponseSchema=z50.object({integrationKey:z50.string().min(1),connectUrl:z50.string().url(),expiresAt:z50.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),ProjectIntegrationConnectResponseSchema=z50.discriminatedUnion("mode",[z50.object({mode:z50.literal("personal"),integrationKey:z50.string().min(1),connection:OrganizationIntegrationConnectionDTOSchema}),z50.object({mode:z50.literal("oauth"),integrationKey:z50.string().min(1),connectUrl:z50.string().url(),expiresAt:z50.coerce.date()})]),BindProjectChannelRequestSchema=z50.object({ref:z50.string().min(1),connectionAlias:z50.string().min(1).optional(),agentName:z50.string().min(1).max(160).nullable().optional(),force:z50.boolean().optional()}),ListProjectChannelsQuerySchema=z50.object({integrationKey:z50.string().min(1)}),SearchProjectChannelsQuerySchema=z50.object({integrationKey:z50.string().min(1),connectionAlias:z50.string().min(1),query:z50.string().max(160).optional()}),ProjectChannelBindingDTOSchema=z50.object({id:z50.uuid(),projectId:z50.uuid(),integrationKey:z50.string().min(1),connectionId:z50.uuid(),externalWorkspaceId:z50.string().min(1),externalChannelId:z50.string().min(1),externalChannelName:z50.string().nullable(),agentName:z50.string().nullable(),enabled:z50.boolean(),createdAt:z50.coerce.date(),updatedAt:z50.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),ProjectChannelCandidateAvailabilitySchema=z50.enum(["available","selected","used_by_project","unavailable"]),ProjectChannelCandidateDTOSchema=z50.object({id:z50.string().min(1),name:z50.string().min(1),visibility:z50.enum(["public","private"]),availability:ProjectChannelCandidateAvailabilitySchema,projectName:z50.string().min(1).nullable(),canMove:z50.boolean()}),ProjectChannelCandidateDTO=createDTO(ProjectChannelCandidateDTOSchema),FirecrawlScrapeFormatsSchema=z50.object({markdown:z50.boolean().optional(),summary:z50.boolean().optional(),links:z50.boolean().optional(),branding:z50.boolean().optional(),images:z50.boolean().optional(),html:z50.union([z50.literal("cleaned"),z50.literal("raw"),z50.boolean()]).optional(),json:z50.union([z50.boolean(),z50.object({prompt:z50.string().min(1).max(1e4),schema:z50.record(z50.string(),z50.unknown()).optional()})]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z50.object({url:z50.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z50.boolean().optional(),timeoutMs:z50.number().int().positive().max(12e4).optional(),waitForMs:z50.number().int().min(0).max(3e4).optional(),maxAgeMs:z50.number().int().min(0).optional(),minAgeMs:z50.number().int().min(0).optional(),storeInCache:z50.boolean().optional(),proxy:z50.enum(["basic","enhanced","auto"]).optional(),mobile:z50.boolean().optional(),location:z50.object({country:z50.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z50.array(z50.string().min(1).max(35)).min(1).max(10).optional()}).optional()}),FirecrawlSearchToolInputSchema=z50.object({query:z50.string().min(1),maxResults:z50.number().int().positive().max(20).optional(),sources:z50.array(z50.enum(["web","news","images"])).min(1).max(3).optional(),categories:z50.array(z50.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z50.array(z50.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z50.array(z50.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z50.enum(["hour","day","week","month","year"]).optional(),location:z50.string().min(1).max(160).optional(),country:z50.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z50.boolean().optional(),timeoutMs:z50.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlDeveloperSearchToolInputSchema=z50.object({query:z50.string().min(1).max(500),maxResults:z50.number().int().min(1).max(100).optional(),types:z50.array(z50.enum(["doc","issue","pull_request","readme"])).min(1).max(4).optional(),repos:z50.array(z50.string().min(1).max(512)).min(1).max(20).optional(),sources:z50.array(z50.string().min(1).max(512)).min(1).max(20).optional(),passages:z50.number().int().min(1).max(5).optional(),skills:z50.literal("only").optional(),language:z50.string().min(1).optional(),topic:z50.string().min(1).optional(),license:z50.string().min(1).optional(),minStars:z50.number().int().min(0).optional(),maxStars:z50.number().int().min(0).optional(),archived:z50.boolean().optional(),fork:z50.boolean().optional()}).refine(value=>value.minStars===void 0||value.maxStars===void 0||value.minStars<=value.maxStars,{message:"minStars must not exceed maxStars."}),FirecrawlResearchSearchToolInputSchema=z50.object({query:z50.string().min(1).max(500),maxResults:z50.number().int().min(1).max(500).optional(),authors:z50.array(z50.string().min(1)).min(1).optional(),categories:z50.array(z50.string().min(1)).min(1).optional(),from:z50.iso.date().optional(),to:z50.iso.date().optional()}),FirecrawlResearchPaperToolInputSchema=z50.object({paperId:z50.string().min(1).max(512),query:z50.string().min(1).max(500).optional(),maxPassages:z50.number().int().min(1).max(50).optional()}).refine(value=>value.query!==void 0||value.maxPassages===void 0,{message:"maxPassages requires query."}),FirecrawlResearchRelatedToolInputSchema=z50.object({paperId:z50.string().min(1).max(512),intent:z50.string().min(1).max(500),mode:z50.enum(["similar","citers","references"]).optional(),maxResults:z50.number().int().min(1).max(500).optional(),rerank:z50.boolean().optional(),anchors:z50.array(z50.string().min(1).max(512)).min(1).optional()}),FirecrawlMapToolInputSchema=z50.object({url:z50.string().url(),search:z50.string().min(1).optional(),limit:z50.number().int().positive().max(200).optional(),includeSubdomains:z50.boolean().optional(),timeoutMs:z50.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z50.object({url:z50.string().url(),limit:z50.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z50.boolean().optional(),timeoutMs:z50.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z50.object({text:z50.string().min(1).max(200).optional(),cron:z50.string().min(1).max(120).optional(),timezone:z50.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorScrapeOptionsInputSchema=z50.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z50.boolean().optional(),timeoutMs:z50.number().int().positive().max(12e4).optional(),waitForMs:z50.number().int().min(0).max(3e4).optional(),maxAgeMs:z50.number().int().min(0).optional(),minAgeMs:z50.number().int().min(0).optional(),storeInCache:z50.boolean().optional(),proxy:z50.enum(["basic","enhanced","auto"]).optional(),mobile:z50.boolean().optional(),location:z50.object({country:z50.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code."),languages:z50.array(z50.string().min(1).max(35)).min(1).max(10).optional()}).optional()}).optional(),FirecrawlMonitorTargetInputSchema=z50.union([z50.object({type:z50.enum(["scrape","crawl"]).default("scrape"),urls:z50.array(z50.string().url()).min(1).max(50),scrapeOptions:FirecrawlMonitorScrapeOptionsInputSchema}),z50.object({type:z50.literal("search"),queries:z50.array(z50.string().min(1).max(256)).min(1).max(12),searchWindow:z50.enum(["5m","15m","1h","6h","24h","7d"]).optional(),maxResults:z50.number().int().min(1).max(50).optional(),includeDomains:z50.array(z50.string().min(1).max(253)).min(1).max(50).optional(),excludeDomains:z50.array(z50.string().min(1).max(253)).min(1).max(50).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."})]),FirecrawlMonitorCreateToolInputSchema=z50.object({name:z50.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z50.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z50.string().min(1).max(2e3).optional(),judgeEnabled:z50.boolean().optional(),retentionDays:z50.number().int().min(1).max(365).optional(),notification:z50.object({email:z50.object({enabled:z50.boolean().default(!0),recipients:z50.array(z50.string().email()).min(1).max(20),includeDiffs:z50.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=z50.object({monitorId:z50.string().uuid(),name:z50.string().min(1).max(256).optional(),schedule:FirecrawlMonitorScheduleInputSchema.optional(),targets:z50.array(FirecrawlMonitorTargetInputSchema).min(1).max(50).optional(),goal:z50.string().min(1).max(2e3).optional(),judgeEnabled:z50.boolean().optional(),retentionDays:z50.number().int().min(1).max(365).optional(),status:z50.enum(["active","paused"]).optional()}).refine(value=>Object.keys(value).some(key=>key!=="monitorId"),"Monitor update needs a changed field."),FirecrawlMonitorIdToolInputSchema=z50.object({monitorId:z50.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z50.string().uuid()}),RunProjectIntegrationToolRequestSchema=z50.object({tool:z50.string().min(1),input:z50.record(z50.string(),z50.unknown()),connectionAlias:z50.string().min(1).optional(),approval:z50.string().min(1).max(4e3).optional()}),ProjectIntegrationToolRunUsageSchema=z50.object({provider:z50.string().min(1),providerCredits:z50.number().nonnegative().optional(),providerCostUsd:z50.number().nonnegative().optional(),requests:z50.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z50.object({credits:z50.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z50.object({url:z50.string(),provider:z50.literal("firecrawl"),title:z50.string().optional(),statusCode:z50.number().optional(),markdown:z50.string().optional(),summary:z50.string().optional(),links:z50.array(z50.string()).optional(),images:z50.array(z50.string()).optional(),html:z50.string().optional(),json:z50.unknown().optional(),branding:z50.record(z50.string(),z50.unknown()).optional(),warning:z50.string().optional()}),FirecrawlSearchToolOutputSchema=z50.object({query:z50.string(),provider:z50.literal("firecrawl"),warning:z50.string().optional(),results:z50.array(z50.object({title:z50.string(),url:z50.string(),snippet:z50.string().optional(),content:z50.string().optional(),score:z50.number().optional(),publishedAt:z50.string().optional()}))}),FirecrawlResearchPaperSchema=z50.object({paperId:z50.string(),primaryId:z50.string().optional(),ids:z50.record(z50.string(),z50.array(z50.string())).optional(),title:z50.string().optional(),abstract:z50.string().optional(),score:z50.number().optional()}).passthrough(),FirecrawlResearchPassageSchema=z50.object({text:z50.string(),score:z50.number().optional()}).passthrough(),FirecrawlDeveloperSearchToolOutputSchema=z50.object({provider:z50.literal("firecrawl"),results:z50.array(z50.object({id:z50.string(),type:z50.string().min(1).optional(),url:z50.string(),title:z50.string().optional(),passages:z50.array(z50.object({text:z50.string()}).passthrough())}).passthrough()),coverage:z50.record(z50.string(),z50.string()).optional(),reranked:z50.boolean().optional(),repos:z50.array(z50.record(z50.string(),z50.unknown())).optional(),sources:z50.array(z50.record(z50.string(),z50.unknown())).optional()}),FirecrawlResearchSearchToolOutputSchema=z50.object({provider:z50.literal("firecrawl"),results:z50.array(FirecrawlResearchPaperSchema)}),FirecrawlResearchPaperToolOutputSchema=z50.object({provider:z50.literal("firecrawl"),paper:z50.record(z50.string(),z50.unknown()),paperId:z50.string().optional(),query:z50.string().optional(),passages:z50.array(FirecrawlResearchPassageSchema).optional()}),FirecrawlResearchRelatedToolOutputSchema=z50.object({provider:z50.literal("firecrawl"),results:z50.array(FirecrawlResearchPaperSchema),poolSize:z50.number().int().nonnegative(),truncated:z50.boolean(),note:z50.string().nullable().optional()}),FirecrawlMapToolOutputSchema=z50.object({url:z50.string(),provider:z50.literal("firecrawl"),count:z50.number(),links:z50.array(z50.object({url:z50.string(),title:z50.string().optional(),description:z50.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z50.object({url:z50.string(),provider:z50.literal("firecrawl"),total:z50.number(),pages:z50.array(z50.object({url:z50.string(),title:z50.string().optional(),statusCode:z50.number().optional(),markdown:z50.string().optional(),summary:z50.string().optional(),links:z50.array(z50.string()).optional(),images:z50.array(z50.string()).optional(),html:z50.string().optional(),warning:z50.string().optional()})),warning:z50.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z50.object({cron:z50.string().optional(),text:z50.string().optional(),timezone:z50.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z50.object({id:z50.string().optional(),type:z50.enum(["scrape","crawl","search"]).optional(),urls:z50.array(z50.string()).optional(),queries:z50.array(z50.string()).optional(),searchWindow:z50.string().optional(),maxResults:z50.number().optional(),includeDomains:z50.array(z50.string()).optional(),excludeDomains:z50.array(z50.string()).optional(),scrapeOptions:z50.record(z50.string(),z50.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z50.object({id:z50.string(),name:z50.string(),status:z50.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z50.string().nullable().optional(),lastRunAt:z50.string().nullable().optional(),currentCheckId:z50.string().nullable().optional(),targets:z50.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z50.string().nullable().optional(),judgeEnabled:z50.boolean().optional(),estimatedCreditsPerMonth:z50.number().optional(),createdAt:z50.string().optional(),updatedAt:z50.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z50.object({id:z50.string(),monitorId:z50.string(),scheduledFor:z50.string().nullable().optional(),startedAt:z50.string().nullable().optional(),finishedAt:z50.string().nullable().optional(),estimatedCredits:z50.number().nullable().optional(),reservedCredits:z50.number().nullable().optional(),actualCredits:z50.number().nullable().optional(),billingStatus:z50.string().nullable().optional(),summary:z50.object({totalPages:z50.number().optional(),same:z50.number().optional(),changed:z50.number().optional(),new:z50.number().optional(),removed:z50.number().optional(),error:z50.number().optional()}).passthrough().optional(),error:z50.string().nullable().optional(),createdAt:z50.string().optional(),updatedAt:z50.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z50.object({provider:z50.literal("firecrawl"),monitors:z50.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z50.object({provider:z50.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z50.object({provider:z50.literal("firecrawl"),monitorId:z50.string(),deleted:z50.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z50.object({provider:z50.literal("firecrawl"),monitorId:z50.string(),checks:z50.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z50.object({provider:z50.literal("firecrawl"),monitorId:z50.string(),check:FirecrawlMonitorCheckOutputSchema,next:z50.string().optional()}),FirecrawlToolKeySchema=z50.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=z50.union([FirecrawlSearchToolOutputSchema,FirecrawlDeveloperSearchToolOutputSchema,FirecrawlResearchSearchToolOutputSchema,FirecrawlResearchPaperToolOutputSchema,FirecrawlResearchRelatedToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z50.object({projectId:z50.uuid(),integrationKey:z50.string().min(1),tool:z50.string().min(1),connectionAlias:z50.string().min(1).nullable().optional(),output:z50.record(z50.string(),z50.unknown()),executedAt:z50.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z50.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z50.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z50.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z50.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z50.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z50.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z50.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z50.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectIntegrationConnectionsResponseSchema=createResponseSchema(z50.array(ProjectIntegrationConnectionDTOSchema)),ProjectIntegrationConnectResponseResponseSchema=createResponseSchema(ProjectIntegrationConnectResponseSchema),AddProjectMcpIntegrationResponseResponseSchema=createResponseSchema(AddProjectMcpIntegrationResponseSchema),ReusableMcpServersResponseSchema=createResponseSchema(z50.array(ReusableMcpServerDTOSchema)),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema),ProjectChannelBindingsResponseSchema=createResponseSchema(z50.array(ProjectChannelBindingDTOSchema)),ProjectChannelCandidatesResponseSchema=createResponseSchema(z50.array(ProjectChannelCandidateDTOSchema))}});import{z as z51}from"zod";var IntegrationIdSchema,IntegrationScopeSchema,IntegrationOAuthSchema,IntegrationApiKeySchema,IntegrationProviderAuthSchema,IntegrationMcpAuthSchema,IntegrationAuthSchema,IntegrationRecipeSchema,IntegrationSettingSchema,IntegrationToolsSchema,IntegrationSkillSchema,IntegrationManifestSchema,IntegrationPermissionDTOSchema,IntegrationSettingDefinitionDTOSchema,IntegrationKindSchema,IntegrationSummaryDTOSchema,IntegrationAccountDTOSchema,IntegrationSiteDTOSchema,OrganizationIntegrationDTOSchema,ProjectIntegrationDTOSchema,IntegrationReturnPathSchema,StartIntegrationInstallRequestSchema,StartIntegrationInstallDTOSchema,AddOrganizationMcpServerDTOSchema,ConnectIntegrationKeyRequestSchema,ReplaceIntegrationServerCredentialsRequestSchema,UpdateIntegrationSiteRequestSchema,UpdateIntegrationSitesRequestSchema,UpdateProjectIntegrationSettingsRequestSchema,IntegrationSettingOptionDTOSchema,IntegrationToolMatchDTOSchema,ProjectIntegrationGuideDTOSchema,APPROVAL_TOKEN_MAX,REQUEST_TOKEN_MAX,RunIntegrationToolRequestSchema,IntegrationApprovalCallShape,IntegrationToolRunResultDTOSchema,IntegrationApprovalPreviewRequestSchema,IntegrationApprovalPreviewDTOSchema,RoutineIntegrationApprovalSchema,IntegrationApprovalDecisionSchema,DecideIntegrationApprovalRequestSchema,IntegrationApprovalDecisionDTOSchema,IntegrationAgentAccessDTOSchema,init_integration_catalog_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration-catalog.dto.js"(){"use strict";init_integration_dto();IntegrationIdSchema=z51.string().min(2).max(80).regex(/^[a-z0-9][a-z0-9-]*$/,"App ids use lowercase letters, digits and dashes."),IntegrationScopeSchema=z51.strictObject({scope:z51.string().min(1),reason:z51.string().min(1).max(200)}),IntegrationOAuthSchema=z51.strictObject({id:z51.string().min(1).max(40),label:z51.string().min(1).max(80),kind:z51.literal("oauth"),actor:z51.literal("user").default("user"),authorizationUrl:z51.url(),tokenUrl:z51.url(),revocationUrl:z51.url().optional(),userInfoUrl:z51.url().optional(),client:z51.strictObject({idEnv:z51.string().min(1),secretEnv:z51.string().min(1)}),authorizeParams:z51.record(z51.string(),z51.string()).default({}),scopes:z51.array(IntegrationScopeSchema).min(1)}),IntegrationApiKeySchema=z51.strictObject({id:z51.string().min(1).max(40),label:z51.string().min(1).max(80),kind:z51.literal("apiKey"),keyLabel:z51.string().min(1).max(80),placeholder:z51.string().min(1).max(40).optional(),helpUrl:z51.url()}),IntegrationProviderAuthSchema=z51.strictObject({id:z51.string().min(1).max(40),label:z51.string().min(1).max(80),kind:z51.literal("provider")}),IntegrationMcpAuthSchema=z51.strictObject({id:z51.string().min(1).max(40),label:z51.string().min(1).max(80),kind:z51.literal("mcp"),methods:z51.array(McpIntegrationSetupAuthSchema).min(1),scopes:z51.array(z51.string().min(1)).min(1).optional(),header:z51.object({name:z51.string().min(1).max(80),valuePrefix:z51.string().max(80)}).optional()}),IntegrationAuthSchema=z51.discriminatedUnion("kind",[IntegrationOAuthSchema,IntegrationApiKeySchema,IntegrationProviderAuthSchema,IntegrationMcpAuthSchema]),IntegrationRecipeSchema=z51.strictObject({title:z51.string().min(1).max(80),description:z51.string().min(1).max(300),command:z51.string().min(1).optional()}),IntegrationSettingSchema=z51.strictObject({type:z51.enum(["string","choice"]),label:z51.string().min(1).max(80),description:z51.string().min(1).max(300).optional(),required:z51.boolean().default(!1),optionsFrom:z51.strictObject({tool:z51.string().min(1)}).optional()}),IntegrationToolsSchema=z51.discriminatedUnion("source",[z51.strictObject({source:z51.literal("hosted")}),z51.strictObject({source:z51.literal("mcp"),url:z51.url()})]),IntegrationSkillSchema=z51.strictObject({name:z51.string().min(1).max(64),description:z51.string().min(1).max(300),content:z51.string().min(1)}),IntegrationManifestSchema=z51.strictObject({apiVersion:z51.literal(1),id:IntegrationIdSchema,version:z51.string().regex(/^\d+\.\d+\.\d+$/),listing:z51.strictObject({name:z51.string().min(1).max(60),description:z51.string().min(1).max(200),details:z51.string().min(1).max(1e3),icon:z51.string().min(1),category:z51.enum(["seo","ai-visibility","analytics","communication"]),publisher:z51.string().min(1).max(60),agentReads:z51.strictObject({label:z51.string().min(1).max(80),description:z51.string().min(1).max(200)}).optional()}),auth:z51.array(IntegrationAuthSchema).min(1),identity:z51.strictObject({label:z51.string().min(1)}).optional(),settings:z51.record(z51.string().regex(/^[a-zA-Z][a-zA-Z0-9]*$/),IntegrationSettingSchema).default({}),tools:IntegrationToolsSchema,skills:z51.array(IntegrationSkillSchema).default([]),recipes:z51.array(IntegrationRecipeSchema).default([])}),IntegrationPermissionDTOSchema=z51.object({scope:z51.string(),reason:z51.string()}),IntegrationSettingDefinitionDTOSchema=z51.object({key:z51.string(),type:z51.enum(["string","choice"]),label:z51.string(),description:z51.string().nullable(),required:z51.boolean(),hasOptions:z51.boolean()}),IntegrationKindSchema=z51.enum(["catalog","custom","builtIn"]),IntegrationSummaryDTOSchema=z51.object({id:z51.string(),kind:IntegrationKindSchema,integrationKey:z51.string(),host:z51.string().nullable(),apiKey:z51.object({label:z51.string(),placeholder:z51.string().nullable(),helpUrl:z51.string(),primary:z51.boolean()}).nullable(),mcp:z51.object({url:z51.string(),methods:z51.array(McpIntegrationSetupAuthSchema),header:z51.object({name:z51.string(),valuePrefix:z51.string()}).nullable()}).nullable(),name:z51.string(),description:z51.string(),details:z51.string(),icon:z51.string(),category:z51.string(),publisher:z51.string(),signInLabel:z51.string(),permissions:z51.array(IntegrationPermissionDTOSchema),readOnly:z51.boolean(),settings:z51.array(IntegrationSettingDefinitionDTOSchema)}),IntegrationAccountDTOSchema=z51.object({connectionId:z51.uuid(),alias:z51.string(),accountName:z51.string().nullable(),status:z51.enum(["active","revoked"]),authKind:z51.enum(["oauth","api_key"]),connectedAt:z51.coerce.date()}),IntegrationSiteDTOSchema=z51.object({projectId:z51.uuid(),projectName:z51.string(),enabled:z51.boolean(),granted:z51.boolean(),connectionId:z51.uuid().nullable(),settings:z51.record(z51.string(),z51.string()),missingSettings:z51.array(z51.string())}),OrganizationIntegrationDTOSchema=IntegrationSummaryDTOSchema.extend({installed:z51.boolean(),accounts:z51.array(IntegrationAccountDTOSchema),siteAccess:z51.enum(["all","selected"]),sites:z51.array(IntegrationSiteDTOSchema)}),ProjectIntegrationDTOSchema=IntegrationSummaryDTOSchema.extend({installed:z51.boolean(),enabled:z51.boolean(),granted:z51.boolean(),accountName:z51.string().nullable(),settingsValues:z51.record(z51.string(),z51.string()),missingSettings:z51.array(z51.string()),tools:z51.array(z51.object({key:z51.string(),name:z51.string(),description:z51.string(),effect:IntegrationToolEffectSchema}))}),IntegrationReturnPathSchema=z51.string().min(1).max(500).refine(value=>value.startsWith("/app/")&&!value.startsWith("//"),"Return path must be inside the Fimo app."),StartIntegrationInstallRequestSchema=z51.object({projectId:z51.uuid().optional(),returnTo:IntegrationReturnPathSchema.optional()}),StartIntegrationInstallDTOSchema=z51.object({connectUrl:z51.url().nullable(),expiresAt:z51.coerce.date().nullable()}),AddOrganizationMcpServerDTOSchema=StartIntegrationInstallDTOSchema.extend({integrationId:z51.string()}),ConnectIntegrationKeyRequestSchema=z51.object({key:z51.string().trim().min(1).max(500),projectId:z51.uuid().optional()}),ReplaceIntegrationServerCredentialsRequestSchema=z51.object({token:z51.string().min(1).max(8e3).optional(),secrets:McpSecretMapSchema.optional()}).refine(value=>!!value.token!=!!value.secrets,"Send either a token or the header values."),UpdateIntegrationSiteRequestSchema=z51.object({enabled:z51.boolean(),connectionId:z51.uuid().optional()}),UpdateIntegrationSitesRequestSchema=z51.object({access:z51.enum(["all","selected"]).optional(),projectIds:z51.array(z51.uuid()).max(1e3),connectionId:z51.uuid().optional()}),UpdateProjectIntegrationSettingsRequestSchema=z51.object({settings:z51.record(z51.string(),z51.string().max(500))}),IntegrationSettingOptionDTOSchema=z51.object({value:z51.string(),label:z51.string(),suggested:z51.boolean()}),IntegrationToolMatchDTOSchema=z51.object({integrationId:z51.string(),integrationName:z51.string(),key:z51.string(),name:z51.string(),description:z51.string(),effect:IntegrationToolEffectSchema,input:z51.record(z51.string(),z51.unknown())}),ProjectIntegrationGuideDTOSchema=z51.object({integrationId:z51.string(),name:z51.string(),description:z51.string(),content:z51.string()}),APPROVAL_TOKEN_MAX=4e3,REQUEST_TOKEN_MAX=32e3,RunIntegrationToolRequestSchema=z51.object({tool:z51.string().min(1).max(120),input:z51.record(z51.string(),z51.unknown()).default({}),approval:z51.string().min(1).max(APPROVAL_TOKEN_MAX).optional(),readOnly:z51.boolean().optional()}),IntegrationApprovalCallShape={integration:z51.object({id:z51.string(),name:z51.string()}),tool:z51.object({key:z51.string(),name:z51.string(),effect:IntegrationToolEffectSchema}),input:z51.record(z51.string(),z51.unknown()),reason:z51.string(),canAlwaysAllow:z51.boolean()},IntegrationToolRunResultDTOSchema=z51.discriminatedUnion("status",[z51.object({status:z51.literal("ok"),output:z51.record(z51.string(),z51.unknown())}),z51.object({status:z51.literal("approval_required"),request:z51.string(),approveUrl:z51.string(),...IntegrationApprovalCallShape}),z51.object({status:z51.literal("blocked"),reason:z51.string()})]),IntegrationApprovalPreviewRequestSchema=z51.object({request:z51.string().min(1).max(REQUEST_TOKEN_MAX)}),IntegrationApprovalPreviewDTOSchema=z51.object({...IntegrationApprovalCallShape,allowOnce:z51.boolean(),expiresAt:z51.coerce.date()}),RoutineIntegrationApprovalSchema=IntegrationApprovalPreviewDTOSchema.pick({integration:!0,tool:!0,reason:!0,canAlwaysAllow:!0,allowOnce:!0}).extend({request:z51.string()}),IntegrationApprovalDecisionSchema=z51.enum(["allow","always","decline"]),DecideIntegrationApprovalRequestSchema=z51.object({request:z51.string().min(1).max(REQUEST_TOKEN_MAX),decision:IntegrationApprovalDecisionSchema}),IntegrationApprovalDecisionDTOSchema=z51.object({decision:IntegrationApprovalDecisionSchema,approval:z51.string().optional(),resumed:z51.boolean().optional()}),IntegrationAgentAccessDTOSchema=z51.object({reads:z51.object({label:z51.string(),description:z51.string()}).nullable(),tools:z51.array(z51.object({tool:z51.string(),label:z51.string(),description:z51.string(),allowed:z51.boolean()}))})}});import{z as z52}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=z52.enum(SCHEDULE_NOTIFICATION_TOPICS),USER_MANAGED_NOTIFICATION_TOPICS=["schedule_health","schedule_compute_allowance","agent_runtime_allowance"],UserManagedNotificationTopicSchema=z52.enum(USER_MANAGED_NOTIFICATION_TOPICS),MAX_SCHEDULE_SUBSCRIBERS=5,ScheduleSubscriberDeliveryStateSchema=z52.enum(["deliverable","suppressed"]),ScheduleSubscriberCandidateSchema=z52.object({userId:z52.string().min(1),name:z52.string(),email:z52.string().min(1),subscribed:z52.boolean(),deliveryState:ScheduleSubscriberDeliveryStateSchema}),ScheduleNotificationSettingsSchema=z52.object({maxSubscribers:z52.number().int().positive(),subscriberCount:z52.number().int().nonnegative(),effectiveRecipientCount:z52.number().int().nonnegative(),currentUserSubscribed:z52.boolean(),candidates:z52.array(ScheduleSubscriberCandidateSchema).optional()}),ScheduleNotificationSettingsResponseSchema=createResponseSchema(ScheduleNotificationSettingsSchema),UpdateScheduleSubscribersRequestSchema=z52.object({userIds:z52.array(z52.string().min(1)).max(MAX_SCHEDULE_SUBSCRIBERS).refine(userIds=>new Set(userIds).size===userIds.length,"Follower ids must be unique.")}),UserNotificationPreferenceSchema=z52.object({topic:UserManagedNotificationTopicSchema,enabled:z52.boolean(),source:z52.enum(["default","explicit"])}),SCHEDULE_OPT_OUT_LINK_ACTIONS=["unfollow_schedule","disable_topic"],ScheduleOptOutLinkActionSchema=z52.enum(SCHEDULE_OPT_OUT_LINK_ACTIONS),SCHEDULE_OPT_OUT_ACTIONS=["unfollow_schedule","unfollow_all_schedules","disable_topic"],ScheduleOptOutActionSchema=z52.enum(SCHEDULE_OPT_OUT_ACTIONS),ScheduleOptOutStateSchema=z52.object({action:ScheduleOptOutActionSchema,topic:ScheduleNotificationTopicSchema,scheduleName:z52.string().nullable(),maskedEmail:z52.string().min(1),applied:z52.boolean(),expiresAt:z52.coerce.date()}),ScheduleOptOutResponseSchema=createResponseSchema(ScheduleOptOutStateSchema),FollowedScheduleSchema=z52.object({scheduleId:z52.string().min(1),scheduleName:z52.string(),projectId:z52.string().min(1),projectName:z52.string(),env:z52.string().min(1)}),FollowedSchedulesSchema=z52.object({schedules:z52.array(FollowedScheduleSchema)}),FollowedSchedulesResponseSchema=createResponseSchema(FollowedSchedulesSchema)}});import{z as z53}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=z53.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=z53.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z53.uuid(),env:z53.string().min(1),name:z53.string().min(1),cron:z53.string().min(1),command:z53.string().min(1),secretKeys:z53.array(z53.string().min(1)),enabled:z53.boolean(),lastRunAt:z53.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z53.string().nullable(),suspendedAt:z53.coerce.date().nullable().optional(),suspensionReason:z53.string().nullable().optional(),overPolicyReasons:z53.array(z53.string()).optional()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z53.object({name:z53.string().min(1).max(120),cron:z53.string().min(1).max(120),command:z53.string().min(1).max(500),secretKeys:z53.array(ProjectSecretKeySchema).default([]),enabled:z53.boolean().optional()}),UpdateProjectScheduleRequestSchema=z53.object({name:z53.string().min(1).max(120).optional(),cron:z53.string().min(1).max(120).optional(),command:z53.string().min(1).max(500).optional(),secretKeys:z53.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z53.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z53.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z53.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z53.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z53.object({maxRuns:z53.number().int().positive(),retentionDays:z53.number().int().positive().nullable(),outputRetentionDays:z53.number().int().positive(),maxOutputBytes:z53.number().int().positive()}),SchedulePolicyStateSchema=z53.enum(["ok","near_limit","exhausted","over_policy"]),ProjectSchedulePlanSnapshotSchema=z53.object({code:z53.enum(["Free","PAYG","Starter","Premium","Pro"]),source:z53.enum(["cached_subscription","free_fallback"]),activeSchedules:z53.object({used:z53.number().int().nonnegative(),limit:z53.number().int().nonnegative()}),minCadenceMinutes:z53.number().int().positive(),maxRunMs:z53.number().int().positive(),concurrency:z53.object({used:z53.number().int().nonnegative(),limit:z53.number().int().positive()}),compute:z53.object({settledMs:z53.number().int().nonnegative(),activeMs:z53.number().int().nonnegative(),reservedMs:z53.number().int().nonnegative().optional(),includedMs:z53.number().int().nonnegative(),remainingMs:z53.number().int().nonnegative(),resetsAt:z53.coerce.date()}),upgrade:z53.object({code:z53.literal("Pro"),activeSchedulesLimit:z53.number().int().positive(),minCadenceMinutes:z53.number().int().positive(),maxRunMs:z53.number().int().positive(),maxConcurrentRuns:z53.number().int().positive(),computeIncludedMs:z53.number().int().positive()}).optional(),state:SchedulePolicyStateSchema,overPolicyReasons:z53.array(z53.string())}),ProjectScheduleUsageSchema=z53.object({runCount:z53.number().int().nonnegative(),runsWithOutput:z53.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z53.object({id:z53.uuid(),scheduleId:z53.uuid(),projectId:z53.uuid(),env:z53.string().min(1),scheduleName:z53.string().min(1),command:z53.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z53.object({id:z53.string().min(1),name:z53.string().min(1)}).nullable(),queuedAt:z53.coerce.date(),startedAt:z53.coerce.date().nullable(),finishedAt:z53.coerce.date().nullable(),exitCode:z53.number().int().nullable(),errorCode:z53.string().nullable(),error:z53.string().nullable(),outputBytes:z53.number().int().nonnegative(),outputTruncated:z53.boolean(),outputExpiresAt:z53.coerce.date().nullable(),metadataExpiresAt:z53.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z53.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z53.coerce.date().nullable(),items:z53.array(z53.object({key:z53.string().min(1),updatedAt:z53.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z53.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z53.object({trigger:z53.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z53.object({limit:z53.coerce.number().int().min(1).max(100).default(25),cursor:z53.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z53.object({items:z53.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z53.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z53.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema,notifications:ScheduleNotificationSettingsSchema.optional()}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z53.object({items:z53.array(ProjectScheduleRunDTOSchema),nextCursor:z53.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema,plan:ProjectSchedulePlanSnapshotSchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z54}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=z54.enum(WORK_NOTIFICATION_TOPICS),PUBLICATION_NOTIFICATION_TOPICS=["publication_failed"],NOTIFICATION_TOPICS=[...WORK_NOTIFICATION_TOPICS,...PUBLICATION_NOTIFICATION_TOPICS,"database_quota_exceeded"],NotificationTopicSchema=z54.enum(NOTIFICATION_TOPICS),NOTIFICATION_DELIVERY_CADENCES=["immediate","daily","off"],NotificationDeliveryCadenceSchema=z54.enum(NOTIFICATION_DELIVERY_CADENCES),NOTIFICATION_CHANNELS=["email"],NotificationChannelSchema=z54.enum(NOTIFICATION_CHANNELS),NOTIFICATION_ACTOR_KINDS=["user","agent","system"],NotificationActorKindSchema=z54.enum(NOTIFICATION_ACTOR_KINDS),NotificationActorSchema=z54.discriminatedUnion("kind",[z54.object({kind:z54.literal("user"),userId:z54.string().min(1)}).strict(),z54.object({kind:z54.literal("agent"),agentKey:z54.string().min(1).max(120),agentId:z54.uuid().optional()}).strict(),z54.object({kind:z54.literal("system")}).strict()]),NotificationSummarySchema=z54.string().trim().min(1).max(1200),ReportBriefPayloadSchema={title:z54.string().trim().min(1).max(120).optional(),brief:StoredReportBriefSchema.optional()},NotificationRunOutcomeSchema=z54.enum(["completed","failed","cancelled"]),NotificationRetainedReasonSchema=z54.enum(["review","agent_requested","recovery"]),NotificationWorkSessionSchema=z54.object({sessionId:z54.uuid(),branch:z54.string().min(1),targetBranch:z54.string().min(1),revision:z54.string().min(1),fingerprint:z54.string().min(1)}),NotificationPayloadSchema=z54.discriminatedUnion("topic",[z54.object({topic:z54.literal("database_quota_exceeded"),incidentId:z54.uuid(),observedAt:z54.iso.datetime()}).strict(),z54.object({topic:z54.literal("agent_run_outcome"),threadId:z54.uuid(),invocationId:z54.uuid(),outcome:NotificationRunOutcomeSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z54.object({topic:z54.literal("agent_retained_review"),threadId:z54.uuid().optional(),invocationId:z54.uuid().optional(),proposalId:z54.uuid().optional(),workSession:NotificationWorkSessionSchema.optional(),reason:NotificationRetainedReasonSchema,summary:NotificationSummarySchema,...ReportBriefPayloadSchema}).strict(),z54.object({topic:z54.literal("agent_conflict"),mergeId:z54.uuid(),threadId:z54.uuid().optional(),invocationId:z54.uuid().optional(),summary:NotificationSummarySchema.optional(),...ReportBriefPayloadSchema}).strict(),z54.object({topic:z54.literal("publication_failed"),publicationId:z54.uuid(),sourceBranch:z54.string().trim().min(1).max(120),failureCode:z54.string().trim().min(1).max(64),failedAt:z54.iso.datetime(),firstPublication:z54.boolean()}).strict()]),NotificationEnvelopeSchema=z54.object({id:z54.uuid(),projectId:z54.uuid(),sourceKey:z54.string().min(1).max(255),actor:NotificationActorSchema,payloadVersion:z54.literal(1),payload:NotificationPayloadSchema,createdAt:z54.coerce.date()}),NotificationDeliveryStateSchema=z54.enum(["pending","deferred","sent","suppressed","failed"]),NotificationDeliverySchema=z54.object({id:z54.uuid(),notificationRecipientId:z54.uuid(),projectId:z54.uuid(),channel:NotificationChannelSchema,state:NotificationDeliveryStateSchema,attemptCount:z54.number().int().nonnegative(),nextAttemptAt:z54.coerce.date().nullable(),lastAttemptAt:z54.coerce.date().nullable(),sentAt:z54.coerce.date().nullable(),failureCode:z54.string().max(80).nullable(),createdAt:z54.coerce.date(),updatedAt:z54.coerce.date()}),NotificationPreferenceSchema=z54.object({topic:WorkNotificationTopicSchema,channel:z54.literal("email"),enabled:z54.boolean(),cadence:NotificationDeliveryCadenceSchema.exclude(["off"]),effectiveCadence:NotificationDeliveryCadenceSchema,source:z54.enum(["default","explicit"])})}});import{z as z55}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=z55.enum(NOTIFICATION_PREFERENCE_GROUPS),FIMO_TOGGLE_PREFERENCE_ENTRY_IDS=["work_review.agent_conflict","publishing.publication_failed","schedule.schedule_health","schedule.schedule_compute_allowance","schedule.agent_runtime_allowance"],FimoTogglePreferenceEntryIdSchema=z55.enum(FIMO_TOGGLE_PREFERENCE_ENTRY_IDS),FIMO_DELIVERY_PREFERENCE_ENTRY_IDS=["work_review.agent_retained_review","work_review.agent_run_outcome"],FimoDeliveryPreferenceEntryIdSchema=z55.enum(FIMO_DELIVERY_PREFERENCE_ENTRY_IDS),MARKETING_PREFERENCE_ENTRY_PREFIX="marketing.",PreferenceSourceSchema=z55.enum(["default","explicit"]),EmailNotificationProviderSyncSchema=z55.enum(["synced","pending","unavailable"]),EmailNotificationPreferenceSchema=z55.object({enabled:z55.boolean(),source:PreferenceSourceSchema,providerSync:EmailNotificationProviderSyncSchema}).strict(),PROVIDER_SUBSCRIPTION_PLACEMENTS=["reports","product_news"],ProviderSubscriptionPlacementSchema=z55.enum(PROVIDER_SUBSCRIPTION_PLACEMENTS),PROVIDER_SUBSCRIPTION_SEMANTIC_IDS=["weekly_analytics"],ProviderSubscriptionSemanticIdSchema=z55.enum(PROVIDER_SUBSCRIPTION_SEMANTIC_IDS),NotificationPreferenceEntrySchema=z55.discriminatedUnion("kind",[z55.object({kind:z55.literal("toggle"),id:FimoTogglePreferenceEntryIdSchema,group:z55.enum(["work_review","publishing","schedule"]),enabled:z55.boolean(),source:PreferenceSourceSchema}).strict(),z55.object({kind:z55.literal("delivery"),id:FimoDeliveryPreferenceEntryIdSchema,group:z55.literal("work_review"),cadence:NotificationDeliveryCadenceSchema,source:PreferenceSourceSchema}).strict(),z55.object({kind:z55.literal("provider_subscription"),id:z55.string().startsWith(MARKETING_PREFERENCE_ENTRY_PREFIX),group:z55.literal("marketing"),name:z55.string(),description:z55.string().nullable(),placement:ProviderSubscriptionPlacementSchema,semanticId:ProviderSubscriptionSemanticIdSchema.nullable(),enabled:z55.boolean(),source:PreferenceSourceSchema}).strict()]),NotificationPreferenceCatalogSchema=z55.object({email:EmailNotificationPreferenceSchema,entries:z55.array(NotificationPreferenceEntrySchema),unavailableGroups:z55.array(NotificationPreferenceGroupSchema)}),NotificationPreferenceCatalogResponseSchema=createResponseSchema(NotificationPreferenceCatalogSchema),NotificationPreferenceEntryResponseSchema=createResponseSchema(NotificationPreferenceEntrySchema),UpdateEmailNotificationPreferenceRequestSchema=z55.object({enabled:z55.boolean()}).strict(),EmailNotificationPreferenceResponseSchema=createResponseSchema(EmailNotificationPreferenceSchema),UpdateNotificationPreferenceEntryRequestSchema=z55.discriminatedUnion("kind",[z55.object({kind:z55.literal("toggle"),enabled:z55.boolean()}).strict(),z55.object({kind:z55.literal("delivery"),cadence:NotificationDeliveryCadenceSchema}).strict(),z55.object({kind:z55.literal("provider_subscription"),enabled:z55.boolean()}).strict()])}});import{z as z56}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=z56.object({surface:SurfaceNameSchema,key:z56.string(),label:z56.string()}),InlineSchema=z56.object({text:z56.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z56.discriminatedUnion("type",[z56.object({type:z56.literal("paragraph"),content:z56.array(InlineSchema).max(24)}),z56.object({type:z56.literal("preview"),ref:DiffRefSchema,caption:z56.string().optional()}),z56.object({type:z56.literal("code"),code:z56.string(),lang:z56.string().optional(),caption:z56.string().optional()}),z56.object({type:z56.literal("risk"),level:z56.enum(["warning","error"]),content:z56.array(InlineSchema).max(24)}),z56.object({type:z56.literal("list"),items:z56.array(z56.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z56.object({headline:z56.string(),blocks:z56.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z56.object({summary:EnvDiffSummarySchema,fingerprint:z56.string(),generatedAt:z56.coerce.date(),cached:z56.boolean().optional(),credits:z56.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z57}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=z57.object({date:z57.string(),visitors:z57.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z57.object({key:z57.string(),visitors:z57.number().int().nonnegative(),pageviews:z57.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z57.object({path:z57.string(),pageName:z57.string().nullable().optional(),visitors:z57.number().int().nonnegative(),pageviews:z57.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z57.object({preset:z57.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z57.string(),requestedTo:z57.string(),effectiveFrom:z57.string(),effectiveTo:z57.string(),isRetentionLimited:z57.boolean(),groupBy:z57.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z57.object({date:z57.string(),content:z57.string(),updatedAt:z57.string(),updatedByUserId:z57.string()}),PROJECT_ANALYTICS_DEVICE_FILTERS=["bot","desktop","mobile","tablet"],ProjectPageviewAnalyticsDTOSchema=z57.object({range:ProjectAnalyticsRangeDTOSchema,deviceFilter:z57.enum(PROJECT_ANALYTICS_DEVICE_FILTERS).nullable(),visitors:z57.number().int().nonnegative(),pageviews:z57.number().int().nonnegative(),botPageviews:z57.number().int().nonnegative(),botVisitors:z57.number().int().nonnegative(),bounceRate:z57.number().min(0).max(100),viewsPerVisit:z57.number().nonnegative(),averageVisitDurationSeconds:z57.number().nonnegative(),visitorsSeries:z57.array(ProjectDailyVisitorsDTOSchema),topPages:z57.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z57.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z57.array(ProjectAnalyticsBreakdownItemDTOSchema),topBots:z57.array(ProjectAnalyticsBreakdownItemDTOSchema),topAiAssistants:z57.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z57.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z57.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z57.array(ProjectAnalyticsAnnotationDTOSchema)}),PROJECT_ANALYTICS_TRACKING_STATES=["observed","waiting","unavailable"],ProjectAnalyticsTrackingStatusDTOSchema=z57.object({state:z57.enum(PROJECT_ANALYTICS_TRACKING_STATES),lastEventAt:z57.string().nullable()}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsTrackingStatusDTO=createDTO(ProjectAnalyticsTrackingStatusDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z58}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=z58.object({id:z58.string(),email:z58.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z58.coerce.date(),createdAt:z58.coerce.date(),inviterUserId:z58.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z58.object({id:z58.string(),token:z58.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z58.object({success:z58.boolean(),projectId:z58.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z59}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=z59.object({id:z59.string(),name:z59.string(),image:z59.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z59.object({count:z59.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z59.object({counts:z59.object({signed_up:z59.int(),activated:z59.int()}),credits:z59.object({total:z59.int(),earned:z59.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z59.email(),emailVerified:z59.boolean(),createdAt:z59.coerce.date(),updatedAt:z59.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z60}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=z60.object({id:z60.string(),principalType:ProjectPrincipalTypeSchema,principalId:z60.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z60.coerce.date(),expiresAt:z60.coerce.date().nullable(),user:PublicUserDTOSchema.nullable(),organizationAdmin:z60.boolean().default(!1)}),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","locale:add","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=z60.enum(PROJECT_PERMISSION_KEYS),ProjectPermissionsDTOSchema=z60.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z60.record(z60.string(),z60.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z60.object({access:z60.array(ProjectAccessItemDTOSchema),invites:z60.array(ProjectInviteDTOSchema),organization:z60.object({name:z60.string().nullable(),logo:z60.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z60.object({success:z60.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z60.object({success:z60.boolean(),projectId:z60.uuid()}))}});import{z as z61}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=z61.object({publicationStatus:PublicationStatusSchema,appUrl:z61.string().nullable(),lastPublishedAt:z61.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z62}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=z62.enum(["queued","building","ready","failed"]),BranchHostedPreviewSchema=z62.object({branch:BranchSchema,revision:z62.string().min(1).max(64).nullable(),generation:z62.string().min(1).max(64),status:BranchHostedPreviewStatusSchema,url:z62.url().nullable()})}});import{z as z63}from"zod";var PreviewUpgradeRequiredSchema,PreviewBridgePackageSchema,PreviewBridgeCapabilitySchema,SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,PreviewInstallApprovalTargetSchema,PreviewInstallRepairSchema,SandboxSessionInstallPolicyErrorSchema,PreviewStartFailureSchema,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=z63.object({code:z63.literal("PREVIEW_UPGRADE_REQUIRED"),message:z63.string(),currentVersion:z63.number().int().positive(),targetVersion:z63.literal(4)}),PreviewBridgePackageSchema=z63.object({name:z63.string().min(1),version:z63.string().min(1)}),PreviewBridgeCapabilitySchema=z63.object({integrated:z63.boolean(),packages:z63.array(PreviewBridgePackageSchema)}),SandboxSessionDTOSchema=z63.object({url:z63.url(),expiresAt:z63.iso.datetime().nullable(),source:z63.enum(["sandbox","hosted"]).optional(),previewBridge:PreviewBridgeCapabilitySchema.optional()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema),PreviewInstallApprovalTargetSchema=z63.object({name:z63.string().min(1),locator:z63.string().min(1).optional(),source:z63.enum(["registry","tarball","unsupported"])}).refine(target=>target.source==="tarball"==(target.locator!==void 0),{message:"locator is present exactly when source is tarball"}),PreviewInstallRepairSchema=z63.object({kind:z63.literal("dependency_build_scripts_blocked"),packageManager:z63.enum(["pnpm","yarn","bun"]),packages:z63.array(z63.string()),targets:z63.array(PreviewInstallApprovalTargetSchema).optional(),configFile:z63.string(),approvalKey:z63.string(),command:z63.string().optional(),approval:z63.object({id:z63.uuid()}).optional()}),SandboxSessionInstallPolicyErrorSchema=z63.object({code:z63.literal("PREVIEW_INSTALL_POLICY_BLOCKED"),message:z63.string(),repair:PreviewInstallRepairSchema}),PreviewStartFailureSchema=z63.object({code:z63.literal("PREVIEW_START_FAILED"),message:z63.string(),logTail:z63.array(z63.string()).optional(),logTailTruncated:z63.boolean().optional()}),SandboxPullPhaseSchema=z63.enum(["acquire","pull","sync-env","install","restart","readiness"]),SandboxPullFailureCodeSchema=z63.enum(["sync_failed","readiness_failed","install_policy_blocked"]),SandboxPullFailureSchema=z63.object({message:z63.string(),code:SandboxPullFailureCodeSchema.optional().catch(void 0),phase:SandboxPullPhaseSchema.optional().catch(void 0),exitCode:z63.number().int().optional().catch(void 0),logTail:z63.array(z63.string()).optional().catch(void 0),logTailTruncated:z63.boolean().optional().catch(void 0),repair:PreviewInstallRepairSchema.optional().catch(void 0)}),PreviewInstallPolicyApprovalRequestSchema=z63.object({approvalId:z63.uuid()}),PreviewInstallPolicyApprovalEventSchema=z63.discriminatedUnion("type",[z63.object({type:z63.literal("progress"),step:z63.enum(["approval","install","restart","readiness"]),message:z63.string()}),z63.object({type:z63.literal("approved")}),z63.object({type:z63.literal("complete")}),z63.object({type:z63.literal("error"),code:z63.enum(["stale_approval","approval_failed","install_failed","restart_failed"]),message:z63.string()})])}});import{z as z64}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,OrganizationProjectCapacityDTOSchema,OrganizationProjectCapacityDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z64.string(),slug:z64.string().nullable(),logo:z64.string().nullable(),metadata:z64.record(z64.string(),z64.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z64.object({id:z64.string(),name:z64.string(),email:z64.email(),image:z64.string().nullable()}),OrganizationMemberDTOSchema=z64.object({id:z64.string(),userId:z64.string(),organizationId:z64.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z64.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema),OrganizationProjectCapacityDTOSchema=z64.object({canCreateProject:z64.boolean()}),OrganizationProjectCapacityDTO=createDTO(OrganizationProjectCapacityDTOSchema)}});import{z as z65}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=z65.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z65.object({reason:CancellationReasonCodeSchema,details:z65.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z65.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),PlanMigrationAcceptDTOSchema=z65.object({offerVersion:z65.string().trim().min(1),unusedPremiumCreditAmount:z65.number().int().nonnegative(),amountDueNow:z65.number().int().nonnegative(),renewsOn:z65.string()}),PlanMigrationPreviewDTOSchema=z65.object({currency:z65.string().trim().min(1),unusedPremiumCreditAmount:z65.number().int().nonnegative(),amountDueNow:z65.number().int().nonnegative(),startsAt:z65.string(),renewsAt:z65.string(),nextRenewalAmount:z65.number().int().nonnegative()}),PlanMigrationPreviewDTO=createDTO(PlanMigrationPreviewDTOSchema),PlanMigrationStateSchema=z65.enum(["legacy_active","notified","accepting","accepted","declining","free","expired","canceled"]),PlanMigrationOfferDTOSchema=z65.object({id:z65.string(),organizationId:z65.string(),legacySubscriptionId:z65.string(),offeredPlanCode:z65.string(),offeredPlanName:z65.string(),offeredPriceAmount:z65.number(),offeredCurrency:z65.string(),offerVersion:z65.string(),state:PlanMigrationStateSchema,checkoutToken:z65.string().nullable(),deadlineAt:z65.string(),transitions:z65.array(z65.object({event:z65.string(),fromState:PlanMigrationStateSchema,toState:PlanMigrationStateSchema,createdAt:z65.string()}))}),PlanMigrationOfferDTO=createDTO(PlanMigrationOfferDTOSchema),AiCreditsEntitlementSchema=z65.object({included:z65.number().optional(),unitPrice:z65.number().optional(),dailyCap:z65.number().nullable().optional()}),EntitlementsDTOSchema=z65.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z65.object({retentionDays:z65.number().int().positive(),canUseExtendedDateRanges:z65.boolean()}).optional(),history:z65.object({retentionDays:z65.number().int().positive()}).optional(),members:z65.object({canInvite:z65.boolean(),maxMembers:z65.number().int().positive().nullable()}).optional(),projects:z65.object({maxProjects:z65.number().int().positive().nullable()}).optional(),domains:z65.object({canUseCustomDomains:z65.boolean(),maxDomains:z65.number().int().nonnegative().nullable()}).optional(),media_storage:z65.object({limitBytes:z65.number().int().nonnegative()}).optional()}),MediaStorageUsageDTOSchema=z65.object({usedBytes:z65.number().int().nonnegative().nullable(),limitBytes:z65.number().int().nonnegative().nullable(),state:z65.enum(["ready","unavailable"]),measuredAt:z65.iso.datetime().nullable()}),MediaStorageUsageDTO=createDTO(MediaStorageUsageDTOSchema),PendingPlanChangeDTOSchema=z65.object({toPlanCode:TemplateCodeSchema,effectiveAt:z65.string(),scheduledAt:z65.string().nullable()}),AutomaticSpendStopDTOSchema=z65.object({fromPlanCode:TemplateCodeSchema,toPlanCode:TemplateCodeSchema,cutoffAt:z65.string(),spendStopped:z65.boolean(),settlementEndsAt:z65.string()}),HostingOverageStatusDTOSchema=z65.object({state:z65.enum(["ready","unavailable"]),planCode:z65.string(),overageAvailable:z65.boolean(),overageEnabled:z65.boolean(),monthlyCapUsd:z65.number().int().positive().nullable(),periodStart:z65.iso.datetime().nullable(),periodEnd:z65.iso.datetime().nullable(),usedBytes:z65.number().nonnegative().nullable(),includedBytes:z65.number().nonnegative().nullable(),overageBytes:z65.number().nonnegative(),currentOverageAmountMicros:z65.number().nonnegative().nullable(),totalExtraUsageAmountMicros:z65.number().nonnegative().nullable(),currency:z65.string().nullable(),status:z65.enum(["ok","near_limit","paused"]),databaseCompute:z65.object({includedHoursPerSite:z65.number().nonnegative().nullable(),overageHours:z65.number().nonnegative(),fundedHours:z65.number().nonnegative(),sitesOverAllowance:z65.number().int().nonnegative(),rateMicrosPerHour:z65.number().nonnegative().nullable(),amountMicros:z65.number().nonnegative().nullable(),budgetSpent:z65.boolean()}).nullable()}),HostingOverageStatusDTO=createDTO(HostingOverageStatusDTOSchema),UpdateHostingOverageRequestSchema=z65.object({enabled:z65.boolean(),monthlyCapUsd:z65.number().int().positive().max(1e6).optional()}).refine(value=>!value.enabled||value.monthlyCapUsd!==void 0,{message:"Enabling extra usage requires a monthly budget"}),SubscriptionDTOSchema=z65.object({id:z65.string(),external_id:z65.string(),customerId:z65.string(),planId:z65.string(),planCode:z65.union([TemplateCodeSchema,z65.literal("Unknown")]),currentPeriod:z65.object({start:z65.string(),end:z65.string().nullable()}),cancelAt:z65.string().nullable(),pendingPlanChange:PendingPlanChangeDTOSchema.nullable(),automaticSpendStop:AutomaticSpendStopDTOSchema.nullable(),entitlements:EntitlementsDTOSchema,currency:z65.string(),nextPaymentAt:z65.string().nullable(),baseAmount:z65.number().nullable()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z65.object({totalCap:z65.number(),dailyCap:z65.number(),usedTotal:z65.number()}),CreditBalanceDTOSchema=z65.object({total:z65.number(),base:z65.number(),dailyBase:z65.number(),purchases:z65.number(),awards:z65.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z65.object({total:z65.number(),nearLimit:z65.boolean(),canChat:z65.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z65.object({dailyFreeAvailable:z65.number(),monthlyAvailable:z65.number(),purchasedAvailable:z65.number(),awardedAvailable:z65.number()}),ProjectDailyCreditAllowanceDTOSchema=z65.object({periodCap:z65.number(),dailyGrant:z65.number(),usedThisPeriod:z65.number(),remainingThisPeriod:z65.number()}),ProjectCreditBalanceDTOSchema=z65.object({projectId:z65.uuid(),organizationId:z65.string(),balance:z65.object({totalAvailable:z65.number(),nearLimit:z65.boolean(),canUseAi:z65.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z65.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),AutoRefillConfigDTOSchema=z65.discriminatedUnion("enabled",[z65.object({enabled:z65.literal(!0),thresholdUsd:z65.number().nonnegative(),refillAmountUsd:z65.number().nonnegative()}),z65.object({enabled:z65.literal(!1),thresholdUsd:z65.number().nonnegative().nullable(),refillAmountUsd:z65.null()})]),AutoRefillConfigDTO=createDTO(AutoRefillConfigDTOSchema),UpdateAutoRefillDTOSchema=z65.discriminatedUnion("enabled",[z65.object({enabled:z65.literal(!0),thresholdUsd:z65.number().min(.01).multipleOf(.01),refillAmountUsd:z65.number().min(.01).multipleOf(.01),expectedRateToken:z65.string().trim().min(1).max(40)}).strict(),z65.object({enabled:z65.literal(!1),thresholdUsd:z65.number().min(.01).multipleOf(.01),expectedRateToken:z65.string().trim().min(1).max(40).optional()}).strict()]),OptionalSpendRefusalSchema=z65.enum(["no_subscription","plan_cannot_fund","pending_plan_exit"]),CreditPurchasePricingDTOSchema=z65.object({planCode:z65.union([TemplateCodeSchema,z65.literal("Unknown")]).nullable(),canPurchase:z65.boolean(),refusalReason:OptionalSpendRefusalSchema.nullable(),creditsPerDollar:z65.number().int().positive(),minAmountUsd:z65.number().positive(),maxAmountUsd:z65.number().positive(),rateToken:z65.string().nullable()}),CreditPurchasePricingDTO=createDTO(CreditPurchasePricingDTOSchema),PurchaseCreditsDTOSchema=z65.object({amountUsd:z65.number(),idempotencyKey:z65.string().trim().min(8).max(120),expectedRateToken:z65.string().trim().min(1).max(40)}).strict(),SuccessfulPurchaseDTOSchema=z65.object({invoiceId:z65.string(),newBalance:z65.int(),creditCount:z65.int(),amountUsd:z65.number(),creditsPerDollar:z65.int()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z65.object({url:z65.string()}),PortalDTO=createDTO(PortalDTOSchema),PaymentRecoveryInvoiceDTOSchema=z65.object({id:z65.string(),number:z65.string().nullable(),status:z65.string(),amountDue:z65.int(),currency:z65.string(),issuedAt:z65.string().nullable(),hostedInvoiceUrl:z65.string().nullable()}),PaymentRecoveryDTOSchema=z65.discriminatedUnion("status",[z65.object({status:z65.literal("eligible"),checkedAt:z65.string()}),z65.object({status:z65.literal("recovery_required"),checkedAt:z65.string(),invoice:PaymentRecoveryInvoiceDTOSchema,outstandingCount:z65.int().min(1)}),z65.object({status:z65.literal("unavailable"),checkedAt:z65.string(),reason:z65.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 z66}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=z66.object({brand:z66.string(),last4:z66.string(),exp:z66.string(),isDefault:z66.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z67}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=z67.string().superRefine((path52,ctx)=>{let segments=path52.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=z67.object({type:z67.literal("renameField"),contentType:z67.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z67.object({enabled:z67.boolean()}).strict(),ContentFieldGroupSchema=z67.object({id:z67.string().regex(CONTENT_FIELD_NAME_PATTERN),label:z67.string().min(1).max(255),default:z67.boolean().optional()}).strict(),ContentTypeDTOSchema=z67.object({id:z67.string(),name:z67.string(),label:z67.string(),isSingleton:z67.boolean(),i18n:ContentTypeI18nSchema,groups:z67.array(ContentFieldGroupSchema).default([]),fields:z67.record(z67.string(),FieldDefinitionSchema),createdAt:z67.string(),updatedAt:z67.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z67.object({contentTypes:z67.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z67.object({id:z67.string(),entryId:z67.string(),documentId:z67.string(),slug:z67.string(),locale:z67.string().optional(),createdAt:z67.string(),updatedAt:z67.string(),__fimo:z67.object({contentType:z67.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z67.object({data:z67.array(EntryDTOSchema),meta:z67.object({limit:z67.number(),offset:z67.number(),total:z67.number(),hasMore:z67.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z67.object({contentType:z67.string(),count:z67.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z67.object({counts:z67.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z67.object({count:z67.number().int().nonnegative(),sourceLocale:z67.string(),targetLocale:z67.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z67.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z67.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z67.union([z67.string(),z67.number(),z67.boolean(),z67.null()]),entryWhereOperatorSchema=z67.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z67.array(entryWhereScalarSchema).optional(),$nin:z67.array(entryWhereScalarSchema).optional(),$contains:z67.string().optional(),$startsWith:z67.string().optional(),$null:z67.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z67.record(z67.string(),z67.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z67.record(z67.string(),z67.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z67.object({data:z67.record(z67.string(),z67.unknown()),locale:z67.string().min(1).optional(),documentId:z67.uuid().optional()}),entryIdsSchema=z67.array(z67.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z67.object({sql:z67.string().min(1)}),BulkCreateEntriesRequestSchema=z67.object({entries:z67.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z67.union([z67.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z67.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z67.object({updates:z67.array(z67.object({id:z67.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z67.union([z67.object({ids:entryIdsSchema,locale:z67.string().min(1).optional()}),z67.object({where:EntryWhereSchema,locale:z67.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z67.object({data:z67.array(z67.record(z67.string(),z67.unknown())),meta:z67.object({rowCount:z67.number().int().nonnegative(),truncated:z67.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z67.object({data:z67.array(EntryDTOSchema),meta:z67.object({created:z67.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z67.object({data:z67.array(EntryDTOSchema),meta:z67.object({updated:z67.number().int().nonnegative(),missing:z67.array(z67.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z67.object({data:z67.array(EntryDTOSchema),meta:z67.object({deleted:z67.number().int().nonnegative(),missing:z67.array(z67.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z68}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z68.object({index:z68.number().int().nonnegative(),contentType:z68.string(),field:z68.string(),value:z68.string(),against:z68.enum(["stored","batch"]),ownerDocumentId:z68.uuid().optional(),ownerIndex:z68.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z68.object({code:z68.literal("unique_conflict"),message:z68.string(),conflicts:z68.array(UniqueConflictSchema),truncated:z68.boolean().optional()})}});import{z as z69}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=z69.object({kind:z69.literal("unique_conflict"),contentType:z69.string(),field:z69.string(),value:z69.string(),documentCount:z69.number().int().positive(),documentIds:z69.array(z69.uuid()),documentIdsTruncated:z69.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z69.object({code:z69.literal("schema_transition_rejected"),message:z69.string(),issues:z69.array(SchemaTransitionIssueSchema),truncated:z69.boolean().optional()})}});import{z as z70}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=z70.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z70.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z70.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z70.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z70.object({field:CmsFieldNameSchema,direction:z70.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z70.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z70.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z70.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z70.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z70.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z71}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=z71.enum(MIGRATION_SOURCE_PLATFORMS)}});import{z as z72}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=z72.enum(CLIENT_TRACKED_EVENTS),TrackProjectEventRequestSchema=z72.object({event:ClientTrackedEventSchema,properties:z72.record(z72.string(),z72.unknown()).default({})})}});import{z as z73}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=z73.object({id:z73.string(),name:z73.string()}),AssetDTOSchema=z73.object({id:z73.string(),name:z73.string(),type:AssetTypeSchema,originalFileName:z73.string().nullable(),parentId:z73.string().nullable(),mimeType:z73.string().nullable(),fileSize:z73.number().nullable(),url:z73.string().nullable(),storageKey:z73.string().nullable(),createdAt:z73.string(),updatedAt:z73.string(),altText:z73.string().nullable().optional(),caption:z73.string().nullable().optional(),aiCaption:z73.string().nullable().optional(),aiAltText:z73.string().nullable().optional(),aiTags:z73.array(z73.string()).nullable().optional(),aiPrimaryColor:z73.string().nullable().optional(),aiProcessingStatus:z73.string().nullable().optional(),width:z73.number().nullable().optional(),height:z73.number().nullable().optional(),path:z73.array(AssetPathItemSchema).optional(),hasChildren:z73.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z73.lazy(()=>z73.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z73.array(AssetDTOSchema)),MediaStorageLimitErrorSchema=z73.object({error:z73.string(),code:z73.literal("media_storage_limit_exceeded"),usedBytes:z73.number().int().nonnegative(),limitBytes:z73.number().int().positive(),incomingBytes:z73.number().int().nonnegative()}),AssetReferenceScopeSchema=z73.enum(["current","main","live"]),ASSET_REFERENCE_IMPACT_FILE_LIMIT=50,AssetReferenceImpactRequestSchema=z73.object({assetIds:z73.array(z73.uuid()).min(1).max(ASSET_REFERENCE_IMPACT_FILE_LIMIT),scopes:z73.array(AssetReferenceScopeSchema).min(1).optional()}),AssetReferenceImpactSelectionDTOSchema=z73.object({totalFiles:z73.number().int().nonnegative(),checkedFiles:z73.number().int().nonnegative(),limit:z73.number().int().positive()}),AssetReferenceFindingDTOSchema=z73.object({assetId:z73.uuid(),entryId:z73.string(),documentId:z73.string(),contentType:z73.string(),locale:z73.string().nullable(),slug:z73.string(),fieldPath:z73.string()}),AssetReferenceScopeResultDTOSchema=z73.object({scope:AssetReferenceScopeSchema,label:z73.string(),state:z73.enum(["available","not-published","failed"]),coverage:z73.enum(["complete","partial","failed"]),referenceCount:z73.number().int().nonnegative().optional(),codeReferenceCount:z73.number().int().nonnegative().optional(),referencedAssetIds:z73.array(z73.uuid()).optional(),references:z73.array(AssetReferenceFindingDTOSchema),reason:z73.enum(["timeout","unavailable"]).optional()}),AssetReferenceScopeResultDTO=createDTO(AssetReferenceScopeResultDTOSchema),AssetReferenceImpactEventDTOSchema=z73.discriminatedUnion("type",[z73.object({type:z73.literal("selection"),data:AssetReferenceImpactSelectionDTOSchema}),z73.object({type:z73.literal("scope"),data:AssetReferenceScopeResultDTOSchema}),z73.object({type:z73.literal("complete")})]),AssetReferenceImpactEventDTO=createDTO(AssetReferenceImpactEventDTOSchema),AssetReferenceReplacementRequestSchema=z73.object({replacementAssetId:z73.uuid()}),AssetReferenceReplacementResultSchema=z73.object({referencesReplaced:z73.number().int().nonnegative(),entriesChanged:z73.number().int().nonnegative()}),AssetReferenceReplacementResponseSchema=createResponseSchema(AssetReferenceReplacementResultSchema),AssetReferenceReplacementPreviewResponseSchema=createResponseSchema(AssetReferenceReplacementResultSchema),AssetCodeReferenceReplacementResultSchema=z73.object({referencesReplaced:z73.number().int().nonnegative(),filesChanged:z73.number().int().nonnegative(),commitSha:z73.string().nullable()}),AssetReferenceReplacementErrorCodeSchema=z73.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=z73.object({error:z73.string(),code:AssetReferenceReplacementErrorCodeSchema}),ASSET_REMOVAL_ASSET_LIMIT=200,AssetRemovalIntentSchema=z73.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=z73.object({intent:AssetRemovalIntentSchema,assetIds:z73.array(z73.uuid()).min(1).max(ASSET_REMOVAL_ASSET_LIMIT),replacementAssetId:z73.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=z73.object({id:z73.uuid(),intent:AssetRemovalIntentSchema,assetIds:z73.array(z73.uuid()),replacementAssetId:z73.uuid().nullable(),expiresAt:z73.iso.datetime(),undoable:z73.boolean(),requestedByMe:z73.boolean()}),AssetRemovalOperationDTO=createDTO(AssetRemovalOperationDTOSchema),AssetRemovalScheduleResultDTOSchema=AssetRemovalOperationDTOSchema.extend({codeReplacement:AssetCodeReferenceReplacementResultSchema.optional()}),AssetRemovalScheduleResultDTO=createDTO(AssetRemovalScheduleResultDTOSchema),AssetRemovalErrorCodeSchema=z73.enum(["asset_removal.asset_not_found","asset_removal.replacement_not_found","asset_removal.already_finalized"]),AssetRemovalErrorSchema=z73.object({error:z73.string(),code:AssetRemovalErrorCodeSchema})}});import{z as z74}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z74.object({key:z74.string(),value:z74.string().optional(),defaultValue:z74.string(),locale:z74.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z75}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=z75.object({id:z75.string(),name:z75.string(),type:z75.enum(["file","folder"]),path:z75.string(),children:z75.lazy(()=>z75.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z75.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z75.object({path:z75.string(),exists:z75.boolean(),type:z75.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z76}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=z76.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),FormFieldValidationSchema=z76.object({minLength:z76.number().optional(),maxLength:z76.number().optional(),min:z76.number().optional(),max:z76.number().optional(),pattern:z76.string().optional(),maxFileSize:z76.number().optional(),accept:z76.array(z76.string()).optional()}),FormFieldSchema=z76.object({type:FormFieldTypeSchema,label:z76.string(),placeholder:z76.string().optional(),required:z76.boolean().optional(),defaultValue:z76.string().optional(),options:z76.array(z76.string()).optional(),validation:FormFieldValidationSchema.optional()}),FormFieldsSchema=z76.record(z76.string(),FormFieldSchema),FormContentSchema=z76.object({name:z76.string().min(1).max(255),label:z76.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 z77}from"zod";var ChatTaskStatusSchema,ChatTaskDTOSchema,ChatTaskListDTOSchema,init_chat_task_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat-task.dto.js"(){"use strict";ChatTaskStatusSchema=z77.enum(["queued","running","finished","failed","cancelled"]),ChatTaskDTOSchema=z77.object({id:z77.string().uuid(),label:z77.string(),status:ChatTaskStatusSchema,startedAt:z77.string(),endedAt:z77.string().nullable(),result:z77.string().nullable()}),ChatTaskListDTOSchema=z77.object({tasks:z77.array(ChatTaskDTOSchema)})}});import{z as z78}from"zod";var AgentPatchSchema,AgentToolRoutineSchema,AgentToolErrorCodeSchema,AgentToolResultSchema,AgentInstructionAuthorSchema,AgentInstructionRevisionDTOSchema,AgentInstructionRevisionListDTOSchema,AgentInstructionRevisionListResponseSchema,AgentInstructionRestoreSchema,init_chat_agent_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat-agent.dto.js"(){"use strict";init_response();init_chat_routine_dto();init_chat_dto();AgentPatchSchema=z78.object({name:z78.string().trim().min(1).max(120).optional(),description:z78.string().trim().min(1).max(300).optional(),instructions:ProjectChatInstructionsSchema.pipe(z78.string().min(1)).optional(),live:z78.literal(!0).optional()}),AgentToolRoutineSchema=z78.object({id:z78.string(),name:z78.string(),schedule:ChatRoutineScheduleSchema.nullable(),trigger:z78.string().nullable()}),AgentToolErrorCodeSchema=z78.enum(["plan_required","not_allowed","default_agent","not_seen","invalid"]),AgentToolResultSchema=z78.discriminatedUnion("ok",[z78.object({ok:z78.literal(!0),agent:z78.object({id:z78.string(),name:z78.string(),live:z78.boolean(),routines:z78.array(AgentToolRoutineSchema)}),revisionId:z78.string().optional()}),z78.object({ok:z78.literal(!1),error:z78.string(),code:AgentToolErrorCodeSchema.optional()})]),AgentInstructionAuthorSchema=z78.object({kind:z78.enum(["person","agent"]),id:z78.string().nullable(),name:z78.string().nullable()}),AgentInstructionRevisionDTOSchema=z78.object({id:z78.string().uuid(),previous:z78.string().nullable(),instructions:z78.string().nullable(),author:AgentInstructionAuthorSchema,createdAt:z78.string()}),AgentInstructionRevisionListDTOSchema=z78.object({revisions:z78.array(AgentInstructionRevisionDTOSchema)}),AgentInstructionRevisionListResponseSchema=createResponseSchema(AgentInstructionRevisionListDTOSchema),AgentInstructionRestoreSchema=z78.object({revisionId:z78.string().uuid()})}});import{z as z79}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=z79.object({url:z79.string().url(),key:z79.string(),size:z79.number(),contentType:z79.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z80}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=z80.object({canAccess:z80.boolean(),permissions:z80.record(z80.string(),z80.boolean()),role:z80.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z81}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:z81.string().trim().default(""),sort:z81.enum(["recent","name","relevance"]).default("recent"),category:z81.string().optional()})}});import{z as z82}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=z82.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z82.enum(["fimo","external"]),PaymentStatusSchema=z82.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z82.object({id:z82.string().uuid(),domain:z82.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z82.boolean(),price:z82.number().int().nullable(),renewalPrice:z82.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z82.string().nullable(),failureReason:z82.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z82.object({domain:z82.string(),available:z82.boolean(),premium:z82.boolean(),price:z82.number().nullable(),renewalPrice:z82.number().nullable(),purchaseType:z82.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z82.object({domain:z82.string(),price:z82.number().nullable(),renewalPrice:z82.number().nullable(),premium:z82.boolean(),allowedYears:z82.array(z82.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z82.object({firstName:z82.string().max(100),lastName:z82.string().max(100),companyName:z82.string().max(100).optional(),address1:z82.string().max(255),address2:z82.string().max(255).optional(),city:z82.string().max(100),state:z82.string().max(100),zip:z82.string().max(20),country:z82.string().max(2),phone:z82.string().max(30),email:z82.union([z82.string().email().max(255),z82.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z82.object({firstName:z82.string().min(1).max(100),lastName:z82.string().min(1).max(100),companyName:z82.string().max(100).optional(),address1:z82.string().min(1).max(255),address2:z82.string().max(255).optional(),city:z82.string().min(1).max(100),state:z82.string().min(1).max(100),zip:z82.string().min(1).max(20),country:z82.string().min(1).max(2),phone:z82.string().min(1).max(30),email:z82.string().email().max(255)}),SearchDomainsRequestSchema=z82.object({keyword:z82.string().min(1).max(100),tldFilter:z82.array(z82.string()).optional()}),CheckAvailabilityRequestSchema=z82.object({domains:z82.array(z82.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=z82.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z82.object({domain:DomainNameSchema,years:z82.number().int().min(1).max(10).optional().default(3),autoRenew:z82.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z82.object({autoRenew:z82.boolean().optional()}),RenewDomainRequestSchema=z82.object({years:z82.number().int().min(1).max(10).optional().default(1),autoRenew:z82.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z82.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z82.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z82.object({verified:z82.boolean(),email:z82.string().nullable(),verifyBy:z82.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z83}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=z83.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=z83.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=z83.object({txtName:z83.string().nullable().optional(),txtValue:z83.string().nullable().optional(),httpUrl:z83.string().nullable().optional(),httpBody:z83.string().nullable().optional(),cname:z83.string().nullable().optional(),cnameTarget:z83.string().nullable().optional()}),SSLValidationErrorSchema=z83.object({message:z83.string()}),OwnershipVerificationSchema=z83.object({type:z83.string(),name:z83.string(),value:z83.string()}),ProjectDomainSSLDTOSchema=z83.object({status:z83.string(),method:z83.string().nullable(),type:z83.string().nullable(),validationRecords:z83.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z83.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z83.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z83.enum(["subdomain","apex"]),RedirectConfigSchema=z83.object({type:z83.enum(["apex_to_www","www_to_apex"]),linkedDomainId:z83.string()}).nullable().optional(),ProjectDomainDTOSchema=z83.object({id:z83.string(),hostname:z83.string(),status:z83.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z83.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z83.string(),scdCnameTarget:z83.string().optional(),apexTargets:z83.array(z83.string()),dnsAutoConfigured:z83.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z83.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z83.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z83.object({hostname:z83.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:z83.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z83.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z83.object({available:z83.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z83.object({success:z83.boolean(),hostname:z83.string()}))}});import{z as z84}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=z84.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z84.object({available:z84.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z84.object({slug:z84.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z84.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z84.object({subdomain:z84.string(),subdomainUpdatedAt:z84.coerce.date()})),SubdomainSuggestionsQuerySchema=z84.object({base:z84.string().max(100).optional(),max:z84.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z84.object({suggestions:z84.array(z84.string())}))}});import{z as z85}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=z85.enum(PROJECT_TRANSFER_BLOCKER_CODES),ProjectTransferBlockerDTO=createDTO(z85.object({code:ProjectTransferBlockerCodeSchema,message:z85.string(),count:z85.number().int().nonnegative().optional()})),TransferProjectRequestSchema=z85.object({targetOrganizationId:z85.string().min(1)}),ProjectTransferResultDTO=createDTO(z85.object({projectId:z85.string(),sourceOrganizationId:z85.string(),targetOrganizationId:z85.string(),movedThreads:z85.number().int().nonnegative(),revokedInvites:z85.number().int().nonnegative(),revokedGrants:z85.number().int().nonnegative(),preservedGrants:z85.number().int().nonnegative(),warnings:z85.array(z85.string())}))}});import{z as z86}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=z86.enum(Object.keys(UNCLAIMED_PLAN.locked)),UNCLAIMED_CLAIM_STATES=["claimable","claimed","expired"],UnclaimedClaimStateSchema=z86.enum(UNCLAIMED_CLAIM_STATES),UNCLAIMED_PROJECT_ERROR_CODES=["project_unclaimed","unclaimed_limit_reached","unclaimed_deploy_limit","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=z86.enum(UNCLAIMED_PROJECT_ERROR_CODES),ProvisionUnclaimedProjectRequestSchema=z86.object({displayName:z86.string().trim().min(1).max(80),machineId:z86.string().trim().min(1).max(128).optional(),cliVersion:z86.string().trim().max(64).optional()}),UnclaimedProjectLimitsSchema=z86.object({ttlHours:z86.number().int().positive(),lockedFeatures:z86.array(UnclaimedLockedFeatureSchema),media:z86.object({totalBytes:z86.number().int().nonnegative(),fileBytes:z86.number().int().positive(),maxFiles:z86.number().int().nonnegative(),mimeTypes:z86.array(z86.string())}),database:z86.object({storageBytes:z86.number().int().positive(),computeSeconds:z86.number().int().positive(),maxComputeUnits:z86.number().positive()})}),UnclaimedProjectClaimSchema=z86.object({url:z86.string().url(),expiresAt:z86.coerce.date()}),ProvisionUnclaimedProjectResponseDTO=createDTO(z86.object({project:ProjectDTOSchema,token:z86.string(),claim:UnclaimedProjectClaimSchema,limits:UnclaimedProjectLimitsSchema})),UnclaimedClaimStatusDTO=createDTO(z86.object({state:UnclaimedClaimStateSchema,displayName:z86.string().nullable(),expiresAt:z86.coerce.date().nullable(),projectId:z86.string().nullable()})),UnclaimedClaimSecretSchema=z86.string().min(1).max(256),UnclaimedClaimStatusRequestSchema=z86.object({secret:UnclaimedClaimSecretSchema}),UnclaimedClaimStatesRequestSchema=z86.object({secrets:z86.array(UnclaimedClaimSecretSchema).min(1).max(20)}),UnclaimedClaimStatesResponseDTO=createDTO(z86.object({claims:z86.array(z86.object({state:UnclaimedClaimStateSchema,expiresAt:z86.coerce.date().nullable()}))})),ClaimUnclaimedProjectRequestSchema=z86.object({secret:UnclaimedClaimSecretSchema,organizationId:z86.string().min(1)}),ClaimUnclaimedProjectResultDTO=createDTO(z86.object({projectId:z86.string(),organizationId:z86.string()})),ProjectTokenSelfDTO=createDTO(z86.object({kind:z86.literal("project_token"),projectId:z86.string(),projectName:z86.string(),displayName:z86.string().nullable(),organizationId:z86.string().nullable(),organizationName:z86.string().nullable(),claimState:UnclaimedClaimStateSchema,expiresAt:z86.coerce.date().nullable(),tokenExpiresAt:z86.coerce.date().nullable()}))}});import{z as z87}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=z87.object({translated:z87.number().int().nonnegative(),total:z87.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z87.object({locale:z87.string(),isDefault:z87.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z87.object({defaultLocale:z87.string(),locales:z87.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z87.object({locale:z87.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z87.object({locale:z87.string().min(1).max(40)}),ProjectLocaleMutationSchema=z87.object({locale:z87.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z87.object({locale:z87.string(),entriesDeleted:z87.number().int().nonnegative(),labelsDeleted:z87.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z88}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=z88.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z88.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=z88.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z88.number(),credits:z88.number().optional(),billingMode:z88.enum(["fimo-credits","provider-account"]).optional(),confidence:z88.enum(["exact","estimated","metered"]),basis:z88.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z89}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=z89.object({options:z89.record(z89.string(),z89.unknown()),name:z89.string().optional(),parentId:z89.string().nullable().optional(),altText:z89.string().optional(),caption:z89.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z89.string().min(1).optional(),model:z89.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=z89.object({jobId:z89.string(),status:z89.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z89.string().nullable().optional(),credits:z89.number().optional(),costUsd:z89.number().optional(),billingMode:z89.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z89.object({error:z89.string(),code:z89.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:z89.array(GenerationTaskIdSchema).optional(),availableModels:z89.array(z89.string()).optional(),issues:z89.array(z89.unknown()).optional()})}});import{z as z90}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=z90.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z90.object({name:z90.string(),key:z90.string(),description:z90.string(),type:FlagTypeSchema,required:z90.boolean(),defaultValue:z90.unknown().optional(),enumValues:z90.array(z90.string()).optional(),isArray:z90.boolean()}),AssetModelPriceSchema=z90.object({unitPrice:z90.number(),unit:z90.string(),confidence:z90.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z90.object({id:z90.string(),shortName:z90.string(),provider:z90.string(),source:z90.string(),modality:z90.enum(["image","video","audio"]),tags:z90.array(z90.string()),displayName:z90.string(),description:z90.string(),flags:z90.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z90.object({model:z90.string(),costUsd:z90.number(),credits:z90.number(),billingMode:z90.enum(["fimo-credits","provider-account"]),confidence:z90.enum(["exact","estimated","metered"]),basis:z90.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z91}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=z91.object({tourId:z91.string(),version:z91.string(),status:z91.string(),completedAt:z91.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z91.array(UserTourDTOSchema))}});import{z as z92}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=z92.object({backendProfile:OpsBackendProfileSchema,provider:z92.literal("sentry"),issueId:OpsSentryIssueIdSchema,status:z92.literal("resolved")}),OpsSentryIssueResolutionResponseDTO=createDTO(OpsSentryIssueResolutionResponseSchema),OpsSentryIssueResolutionErrorResponseSchema=z92.object({backendProfile:OpsBackendProfileSchema,provider:z92.literal("sentry"),issueId:OpsSentryIssueIdSchema,resolved:z92.literal(!1),reason:z92.string()}),OpsSentryIssueResolutionErrorResponseDTO=createDTO(OpsSentryIssueResolutionErrorResponseSchema)}});import{z as z93}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=z93.object({packageManager:z93.string().trim().min(1).max(200).nullable(),trackedLockfiles:z93.array(z93.enum(OPS_PROJECT_PACKAGE_MANAGER_LOCKFILES)),sourceRevision:z93.string().trim().min(1)}),OpsProjectPackageManagerSchema=z93.object({target:z93.object({backendProfile:OpsBackendProfileSchema,projectId:z93.uuid(),projectEnv:z93.string().trim().min(1).max(255)}),...OpsProjectPackageManagerSummarySchema.shape}),OpsProjectPackageManagerDTO=createDTO(OpsProjectPackageManagerSchema)}});import{z as z94}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:z94.boolean().optional()}).strict(),OpsAgentChatAgentSpecSchema=z94.union([z94.object({name:z94.string().trim().min(1).max(120),description:z94.string().trim().min(1).max(2e3)}).strict(),z94.object({template:z94.string().trim().min(1).max(64)}).strict()]),OpsAgentChatSpecObjectSchema=z94.object({agent:OpsAgentChatAgentSpecSchema,routines:z94.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:z94.string().trim().min(1).max(1e3),dryRun:z94.boolean().optional()}).refine(uniqueRoutineNames,UNIQUE_ROUTINE_NAMES),OpsAgentChatOutcomeSchema=z94.enum(["created","existing","would_create"]),OpsAgentChatRoutineResultSchema=z94.object({id:z94.string().uuid().nullable(),name:z94.string(),schedule:ChatRoutineScheduleSchema.nullable(),nextRunAt:z94.string().nullable(),paused:z94.boolean(),outcome:z94.enum(["created","would_create"]),source:z94.enum(["spec","template"])}),OpsAgentChatCreateResultSchema=z94.object({target:z94.object({backendProfile:OpsBackendProfileSchema,projectId:z94.string().uuid()}),dryRun:z94.boolean(),applied:z94.boolean(),createdBy:z94.object({userId:z94.string()}),agent:z94.object({id:z94.string().uuid().nullable(),title:z94.string(),template:z94.string().nullable(),outcome:OpsAgentChatOutcomeSchema}),routines:z94.array(OpsAgentChatRoutineResultSchema),skipped:z94.array(z94.object({name:z94.string(),reason:z94.literal("routine_exists")})),refused:z94.array(z94.object({name:z94.string(),reason:ChatRoutineRefusalReasonSchema}))})}});import{z as z95}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=z95.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z95.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z95.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z95.enum(["main","all"]),WebhookEnvironmentSelectorSchema=z95.union([WebhookEnvironmentScopeSchema,EnvironmentKeySchema]),EntryChangedWebhookEventDataSchema=z95.object({reason:WebhookEntryChangeReasonSchema,operationId:z95.string().optional(),batch:z95.object({index:z95.number().int().positive(),total:z95.number().int().positive()}).optional(),changes:z95.array(z95.object({action:WebhookEntryChangeActionSchema,contentType:z95.string(),id:z95.string(),documentId:z95.string(),locale:z95.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z95.object({form:z95.object({id:z95.string(),label:z95.string()}),submission:z95.object({id:z95.string(),data:z95.record(z95.string(),z95.unknown()),submittedAt:z95.string()})}),PublishStartedWebhookEventDataSchema=z95.object({publication:z95.object({status:z95.literal("publishing"),startedAt:z95.string()})}),PublishSucceededWebhookEventDataSchema=z95.object({publication:z95.object({status:z95.literal("published"),url:z95.string(),publishedAt:z95.string(),firstPublish:z95.boolean()})}),PublishFailedWebhookEventDataSchema=z95.object({publication:z95.object({status:z95.literal("failed"),reason:z95.string()})}),PublishUnpublishedWebhookEventDataSchema=z95.object({publication:z95.object({previousUrl:z95.string(),unpublishedAt:z95.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z95.object({report:z95.object({weekStart:z95.string(),weekEnd:z95.string(),pageviews:z95.number(),visitors:z95.number(),previousPageviews:z95.number(),previousVisitors:z95.number()})}),MediaAssetWebhookEventDataSchema=z95.object({id:z95.string().nullable(),name:z95.string().nullable(),type:z95.string(),mimeType:z95.string().nullable(),fileSize:z95.number().nullable()}),MediaUploadedWebhookEventDataSchema=z95.object({asset:MediaAssetWebhookEventDataSchema,operation:z95.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z95.object({asset:MediaAssetWebhookEventDataSchema,operation:z95.literal("updated")}),MediaDeletedWebhookEventDataSchema=z95.object({asset:MediaAssetWebhookEventDataSchema,operation:z95.literal("deleted")}),DomainCreatedWebhookEventDataSchema=z95.object({domain:z95.object({id:z95.string(),hostname:z95.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z95.object({domain:z95.object({id:z95.string(),hostname:z95.string()})}),LabelChangedWebhookEventDataSchema=z95.object({changes:z95.array(z95.object({action:z95.enum(["created","updated","deleted"]),key:z95.string(),locale:z95.string(),value:z95.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z95.object({locale:z95.object({code:z95.string(),isDefault:z95.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z95.object({locale:z95.object({code:z95.string(),previousCode:z95.string()})}),LocaleDeletedWebhookEventDataSchema=z95.object({locale:z95.object({code:z95.string(),entriesDeleted:z95.number().int().nonnegative(),labelsDeleted:z95.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z95.object({environment:z95.object({name:BranchSchema,parent:BranchSchema})}),EnvironmentDeletedWebhookEventDataSchema=z95.object({environment:z95.object({name:BranchSchema})}),EnvironmentMergedWebhookEventDataSchema=z95.object({merge:z95.object({id:z95.string(),from:BranchSchema,to:BranchSchema,applied:z95.array(z95.object({surface:SurfaceNameSchema,count:z95.number().int().nonnegative()}))})}),BranchRestoredWebhookEventDataSchema=z95.object({branch:z95.object({name:BranchSchema}),version:z95.object({versionId:z95.uuid(),name:z95.string()})}),WebhookEventFamilySchema=z95.enum(["entries","forms","publish","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z95.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z95.discriminatedUnion("source",[z95.object({source:z95.literal("literal"),value:z95.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z95.object({source:z95.literal("secret"),key:z95.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z95.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z95.object({name:z95.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z95.object({name:z95.string(),source:z95.enum(["literal","secret"]),secretKey:z95.string().nullable(),secretPrefix:z95.string().nullable(),configured:z95.literal(!0)}),WebhookFilterSchema=z95.object({environment:WebhookEnvironmentSelectorSchema.optional(),formId:z95.string().min(1).max(255).optional(),mediaType:z95.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z95.string().min(1).max(255).optional(),locale:z95.string().min(1).max(120).optional()}),JsonValueSchema=z95.lazy(()=>z95.union([z95.string(),z95.number(),z95.boolean(),z95.null(),z95.array(JsonValueSchema),z95.record(z95.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z95.object({name:z95.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z95.url(),enabled:z95.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z95.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z95.boolean().optional().default(!0)}),UpdateProjectWebhookRequestSchema=z95.object({name:z95.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z95.url().optional(),enabled:z95.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z95.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z95.boolean().optional()}),TestProjectWebhookRequestSchema=z95.object({eventType:WebhookEventTypeSchema.optional(),data:z95.record(z95.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z95.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z95.uuid(),name:z95.string(),eventType:WebhookEventTypeSchema,enabled:z95.boolean(),destination:z95.object({host:z95.string(),maskedUrl:z95.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z95.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z95.boolean(),lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z95.coerce.date().nullable(),deliveryStats24h:z95.object({succeeded:z95.number().int().nonnegative(),failed:z95.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z95.uuid(),projectId:z95.uuid(),env:BranchSchema,environment:EnvironmentKeySchema,branch:BranchSchema,eventId:z95.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z95.number().int().positive(),test:z95.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z95.number().int().nonnegative(),responseStatus:z95.number().int().nullable(),lastErrorCode:z95.string().nullable(),lastErrorMessage:z95.string().nullable(),payloadAvailable:z95.boolean(),destination:z95.object({host:z95.string(),maskedUrl:z95.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z95.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z95.string().nullable(),qstashMessageId:z95.string().nullable(),deliveredAt:z95.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z95.object({items:z95.array(WebhookDeliveryDTOSchema),pagination:z95.object({page:z95.number().int().positive(),limit:z95.number().int().positive(),total:z95.number().int().nonnegative(),totalPages:z95.number().int().positive(),hasMore:z95.boolean()}),stats:z95.object({total:z95.number().int().nonnegative(),succeeded:z95.number().int().nonnegative(),failed:z95.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z95.object({id:z95.uuid(),deliveryId:z95.uuid(),attempt:z95.number().int().positive(),status:z95.enum(["delivering","succeeded","failed"]),responseStatus:z95.number().int().nullable(),durationMs:z95.number().int().nonnegative(),responseExcerpt:z95.string().nullable(),errorCode:z95.string().nullable(),errorMessage:z95.string().nullable(),createdAt:z95.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z95.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z95.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z96}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=z96.object({key:z96.literal("fimo-2"),enabled:z96.boolean(),dismissed:z96.boolean().default(!1),interacted:z96.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema)}});import{z as z97}from"zod";var SiteOnboardingStageSchema,SiteScanStatusSchema,SiteCloneStatusSchema,SiteRefusalCodeSchema,SiteRefusalSchema,SiteCheckGroupSchema,SiteScoreSchema,SITE_CHECKS,SiteCheckIdSchema,SiteCheckStatusSchema,SiteCheckEvidenceSchema,SiteCheckResultSchema,SiteReportGroupSchema,SiteRecommendationsSchema,SiteMarketSchema,SitePageViewSchema,SiteSectionStatusSchema,SiteComparisonSchema,SiteReportSchema,SiteTypeSchema,SiteTermsCategorySchema,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=z97.enum(["scanning","interviewing","reporting","open","expired","refused"]),SiteScanStatusSchema=z97.enum(["running","done","failed"]),SiteCloneStatusSchema=z97.enum(["not_started","running","paused","finished","failed"]),SiteRefusalCodeSchema=z97.enum(["invalid","private","not_found","tls","unreachable","redirect","error_page","bot_wall"]),SiteRefusalSchema=z97.object({code:SiteRefusalCodeSchema,suggestedUrl:z97.string().nullable()}),SiteCheckGroupSchema=z97.enum(["discovery","indexing","ai_crawlers","rendering","metadata","content","speed"]),SiteScoreSchema=z97.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=z97.enum(SITE_CHECKS.map(check=>check.id)),SiteCheckStatusSchema=z97.enum(["pass","partial","fail","not_scored"]),SiteCheckEvidenceSchema=z97.record(z97.string(),z97.union([z97.string(),z97.number(),z97.boolean(),z97.array(z97.string())])),SiteCheckResultSchema=z97.object({id:SiteCheckIdSchema,status:SiteCheckStatusSchema,evidence:SiteCheckEvidenceSchema}),SiteReportGroupSchema=z97.object({id:SiteCheckGroupSchema,score:z97.number().int().min(0).max(100).nullable()}),SiteRecommendationsSchema=z97.object({answers:z97.number().int().min(0),domains:z97.record(z97.string(),z97.number().int().min(0))}),SiteMarketSchema=z97.object({domain:z97.string(),competitors:z97.array(z97.string()),rankings:z97.array(z97.object({domain:z97.string(),averagePosition:z97.number().min(1).nullable()})),keywords:z97.array(z97.object({keyword:z97.string(),positions:z97.record(z97.string(),z97.number().int().min(1).nullable())})),recommendations:SiteRecommendationsSchema.optional(),names:z97.record(z97.string(),z97.string()).optional(),fetchedAt:z97.coerce.date()}),SitePageViewSchema=z97.object({url:z97.string(),title:z97.string().nullable(),description:z97.string().nullable(),h1:z97.string().nullable(),structuredData:z97.array(z97.string()),wordCount:z97.number().int().min(0),capturedAt:z97.coerce.date()}),SiteSectionStatusSchema=z97.enum(["pending","ready","failed","skipped"]),SiteComparisonSchema=z97.object({before:SitePageViewSchema.optional(),after:SitePageViewSchema.optional(),beforeStatus:SiteSectionStatusSchema.optional(),afterStatus:SiteSectionStatusSchema.optional(),beforeQueuedAt:z97.coerce.date().optional(),afterQueuedAt:z97.coerce.date().optional()}),SiteReportSchema=z97.object({siteUrl:z97.string(),scannedAt:z97.coerce.date(),seoScore:z97.number().int().min(0).max(100).nullable(),geoScore:z97.number().int().min(0).max(100).nullable(),groups:z97.array(SiteReportGroupSchema),checks:z97.array(SiteCheckResultSchema),blockers:z97.array(SiteCheckIdSchema).default([]),market:SiteMarketSchema.optional(),marketStatus:SiteSectionStatusSchema.optional(),marketQueuedAt:z97.coerce.date().optional(),comparison:SiteComparisonSchema.optional()}),SiteTypeSchema=z97.enum(["business","non_profit","portfolio","hobby","personal"]),SiteTermsCategorySchema=z97.enum(["violence","child_harm","harassment","hate","self_harm","adult","deception","scam"]),SiteUnderstandingSchema=z97.object({name:z97.string(),summary:z97.string(),audience:z97.string(),positioning:z97.string(),homepage:z97.string()}),SiteSuggestionSchema=z97.object({label:z97.string(),url:z97.string().nullable()}),SiteInterviewSuggestionsSchema=z97.record(z97.string(),z97.record(z97.string(),z97.array(SiteSuggestionSchema))),SiteInterviewAnswerSchema=z97.record(z97.string().max(50),z97.union([z97.string().trim().max(2e3),z97.array(z97.string().trim().min(1).max(200)).max(10)])),SiteInterviewSchema=z97.object({status:z97.enum(["waiting","drafting","ready","failed"]),siteType:SiteTypeSchema.nullable(),site:SiteUnderstandingSchema.nullable(),suggestions:SiteInterviewSuggestionsSchema,answers:z97.record(z97.string(),SiteInterviewAnswerSchema)}),AnswerSiteInterviewRequestSchema=z97.object({questionId:z97.string().min(1).max(50),answer:SiteInterviewAnswerSchema}),SiteFixesReportSchema=z97.object({fixes:z97.array(z97.object({checkId:SiteCheckIdSchema,status:z97.enum(["fixed","not_fixed","not_applicable"]),note:z97.string().trim().min(1).max(300)})).min(1).max(40)}),SiteOnboardingResultSchema=z97.object({fixes:SiteFixesReportSchema.nullable(),summary:z97.string().nullable()}),StartSiteOnboardingRequestSchema=z97.object({organizationId:z97.string().min(1),url:z97.string().trim().min(1).max(2048),locale:z97.string().trim().min(2).max(16).default("en")}),StartSiteOnboardingResponseSchema=createResponseSchema(z97.object({projectId:z97.string()})),SiteOnboardingRefusedResponseSchema=z97.object({error:z97.literal("site_refused"),refusal:SiteRefusalSchema}),SiteOnboardingStateSchema=z97.object({projectId:z97.string(),siteUrl:z97.string(),stage:SiteOnboardingStageSchema,scanStatus:SiteScanStatusSchema,cloneStatus:SiteCloneStatusSchema,cloneRetryAvailable:z97.boolean(),budgetExhausted:z97.boolean(),sponsored:z97.boolean(),outOfCredits:z97.boolean(),interview:SiteInterviewSchema.nullable(),cloneThreadId:z97.string().nullable(),welcomeThreadId:z97.string().nullable(),competitors:z97.array(z97.string()),report:SiteReportSchema.nullable(),reportExpiresAt:z97.coerce.date(),openedAt:z97.coerce.date().nullable(),bannerDismissed:z97.boolean()}),SiteOnboardingStateDTO=createDTO(SiteOnboardingStateSchema),SiteOnboardingStateResponseSchema=createResponseSchema(SiteOnboardingStateSchema.nullable()),RetrySiteOnboardingRequestSchema=z97.object({task:z97.enum(["interview","scan","clone"])}),SiteOnboardingOutcomeSchema=z97.enum(["finished","rebuilding","paused","failed","scan_failed","scanning","expired","refused","not_started"]),AdminSiteOnboardingsQuerySchema=z97.object({search:z97.string().trim().max(200).optional(),organizationId:z97.string().trim().min(1).max(200).optional(),startDate:z97.coerce.date().optional(),endDate:z97.coerce.date().optional(),outcomes:z97.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z97.array(SiteOnboardingOutcomeSchema).optional()),siteTypes:z97.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z97.array(SiteTypeSchema).optional()),page:z97.coerce.number().int().min(1).default(1),pageSize:z97.coerce.number().int().min(1).max(100).default(25)}),AdminSiteOnboardingDTOSchema=z97.object({projectId:z97.string(),projectName:z97.string(),organizationId:z97.string(),organizationName:z97.string().nullable(),ownerEmail:z97.string().nullable(),ownerName:z97.string().nullable(),siteUrl:z97.string(),stage:SiteOnboardingStageSchema,scanStatus:SiteScanStatusSchema,cloneStatus:SiteCloneStatusSchema,outcome:SiteOnboardingOutcomeSchema,sponsored:z97.boolean(),cloneRetries:z97.number(),siteType:SiteTypeSchema.nullable(),refusalCategory:SiteTermsCategorySchema.nullable(),interviewAnswers:z97.number(),interviewQuestions:z97.number().nullable(),seoScore:z97.number().nullable(),geoScore:z97.number().nullable(),spentUsd:z97.number(),budgetCapUsd:z97.number(),capReached:z97.boolean(),cloneSeconds:z97.number().nullable(),createdAt:z97.coerce.date(),openedAt:z97.coerce.date().nullable()}),AdminSiteOnboardingDTO=createDTO(AdminSiteOnboardingDTOSchema),AdminSiteOnboardingsResponseSchema=createResponseSchema(z97.object({onboardings:z97.array(AdminSiteOnboardingDTOSchema),page:z97.number(),limit:z97.number(),total:z97.number(),totalPages:z97.number()})),AdminSiteOnboardingStatsSchema=z97.object({total:z97.number(),outcomes:z97.record(SiteOnboardingOutcomeSchema,z97.number()),funnel:z97.object({started:z97.number(),confirmed:z97.number(),finished:z97.number(),opened:z97.number()}),bySiteType:z97.array(z97.object({siteType:SiteTypeSchema,total:z97.number(),finished:z97.number(),opened:z97.number()})),granularity:z97.enum(["hour","day"]),series:z97.array(z97.object({at:z97.coerce.date(),outcomes:z97.record(SiteOnboardingOutcomeSchema,z97.number())})),spentUsd:z97.object({total:z97.number(),average:z97.number().nullable()}),sponsored:z97.number(),paidByOrganization:z97.object({usd:z97.number(),credits:z97.number()}),capReached:z97.number(),cloneSeconds:z97.object({median:z97.number().nullable(),average:z97.number().nullable()})}),AdminSiteOnboardingStatsResponseSchema=createResponseSchema(AdminSiteOnboardingStatsSchema),AdminSiteOnboardingDetailSchema=z97.object({onboarding:AdminSiteOnboardingDTOSchema.extend({locale:z97.string(),cloneThreadId:z97.string().nullable(),paidByOrganizationUsd:z97.number()}),interview:SiteInterviewSchema.extend({invocationIds:z97.array(z97.string())}).nullable(),knowledgeWritten:z97.string().nullable(),knowledgeNow:z97.object({content:z97.string(),updatedAt:z97.coerce.date().nullable(),updatedBy:z97.string().nullable()}),report:SiteReportSchema.nullable()}),AdminSiteOnboardingDetailDTO=createDTO(AdminSiteOnboardingDetailSchema),AdminSiteOnboardingDetailResponseSchema=createResponseSchema(AdminSiteOnboardingDetailSchema)}});import{z as z98}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=z98.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z98.object({total:z98.number(),base:z98.number(),purchases:z98.number(),awards:z98.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z98.object({id:z98.string(),name:z98.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z98.object({type:z98.string(),brand:z98.string().nullable(),last4:z98.string().nullable(),expirationDate:z98.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z98.object({currency:z98.string(),nextPaymentAmount:z98.number().nullable(),nextPaymentAt:z98.string().nullable(),billingInterval:z98.string().nullable(),totalAmount:z98.number().nullable(),discountAmount:z98.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z98.object({id:z98.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z98.string().nullable(),currentPeriodEndsAt:z98.string().nullable(),renewsAt:z98.string().nullable(),cancelAt:z98.string().nullable(),renewAutomatically:z98.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z98.object({type:z98.enum(["low_balance","critical_balance","approaching_limit"]),message:z98.string(),estimatedPromptsRemaining:z98.number().nullable(),avgCostPerPrompt:z98.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z98.object({monthlyCredits:z98.number().nullable(),usedThisPeriod:z98.number(),remainingThisPeriod:z98.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z98.object({organizationId:z98.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z98.string().nullable(),tenureDays:z98.number().int().nonnegative(),capturedAt:z98.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z98.object({hasSubscription:z98.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z98.number().nullable(),alerts:z98.array(CreditAlertDTOSchema),portalUrl:z98.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z98.object({creditCount:z98.number().int().positive(),expiresAt:z98.string().datetime().nullable().optional(),message:z98.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z98.literal("free"),amountCents:z98.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z98.literal("purchase"),amountCents:z98.number().int().positive()}),CreditTopupRequestDTOSchema=z98.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z98.object({success:z98.boolean(),transactionId:z98.string().nullable(),newBalance:z98.number(),creditCount:z98.number(),type:z98.enum(["free","purchase"]),invoiceId:z98.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z99}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=z99.object({totalCredits:z99.number(),totalCostUsd:z99.number(),totalMessages:z99.number(),avgCostPerMessage:z99.number(),periodStart:z99.string().nullable(),periodEnd:z99.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z99.object({projectId:z99.string(),projectName:z99.string(),projectDisplayName:z99.string().nullable(),credits:z99.number(),costUsd:z99.number(),messages:z99.number(),percentage:z99.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z99.object({userId:z99.string(),userName:z99.string().nullable(),userEmail:z99.string().email().nullable(),credits:z99.number(),costUsd:z99.number(),messages:z99.number(),percentage:z99.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z99.object({date:z99.string(),credits:z99.number(),costUsd:z99.number(),messages:z99.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z99.object({userId:z99.string(),userName:z99.string().nullable(),userEmail:z99.string().email().nullable(),credits:z99.number(),costUsd:z99.number(),messages:z99.number(),percentage:z99.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z99.object({projectId:z99.string(),projectName:z99.string(),projectDisplayName:z99.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z99.array(UsageByUserForProjectDTOSchema),timeline:z99.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z99.object({summary:UsageSummaryDTOSchema,byProject:z99.array(UsageByProjectDTOSchema),byUser:z99.array(UsageByUserDTOSchema),timeline:z99.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z100}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=z100.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z100.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z100.object({startDate:z100.string().optional(),endDate:z100.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z100.coerce.number().int().positive().default(1),limit:z100.coerce.number().int().positive().max(100).default(20),sortBy:z100.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z100.string().optional(),activeOnly:z100.stringbool().optional().default(!0)}),UsageOverviewSummaryDTOSchema=z100.object({totalCredits:z100.number(),totalCostUsd:z100.number(),totalMessages:z100.number(),automatedMessages:z100.number(),avgCostPerMessage:z100.number(),avgCreditsPerMessage:z100.number(),periodStart:z100.string(),periodEnd:z100.string(),creditsChange:z100.number().nullable(),costChange:z100.number().nullable(),messagesChange:z100.number().nullable(),unattributedCredits:z100.number(),unattributedCostUsd:z100.number(),unattributedMessages:z100.number()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z100.object({date:z100.string(),credits:z100.number(),costUsd:z100.number(),messages:z100.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z100.object({organizationId:z100.string(),organizationName:z100.string(),credits:z100.number(),costUsd:z100.number(),messages:z100.number(),percentage:z100.number(),userCount:z100.number(),projectCount:z100.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z100.object({userId:z100.string(),userName:z100.string().nullable(),userEmail:z100.string().nullable(),userImage:z100.string().nullable(),organizationId:z100.string().nullable(),organizationName:z100.string().nullable(),credits:z100.number(),costUsd:z100.number(),messages:z100.number(),percentage:z100.number(),projectCount:z100.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z100.object({projectId:z100.string(),projectName:z100.string(),projectDisplayName:z100.string().nullable(),organizationId:z100.string(),organizationName:z100.string(),credits:z100.number(),costUsd:z100.number(),messages:z100.number(),percentage:z100.number(),userCount:z100.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z100.object({id:z100.string(),name:z100.string(),value:z100.number(),percentage:z100.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z100.object({day:z100.number(),hour:z100.number(),value:z100.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z100.object({summary:UsageOverviewSummaryDTOSchema,timeline:z100.array(UsageTimelinePointDTOSchema),topOrganizations:z100.array(OrganizationUsageRowDTOSchema),topUsers:z100.array(UserUsageRowDTOSchema),topProjects:z100.array(ProjectUsageRowDTOSchema),creditDistribution:z100.array(UsageDistributionItemDTOSchema),userDistribution:z100.array(UsageDistributionItemDTOSchema),heatmap:z100.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z100.object({page:z100.number(),limit:z100.number(),totalItems:z100.number(),totalPages:z100.number(),hasMore:z100.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z100.object({organizations:z100.array(OrganizationUsageRowDTOSchema),top:z100.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z100.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z100.object({users:z100.array(ExtendedUserUsageRowDTOSchema),top:z100.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z100.string(),ownerName:z100.string().nullable(),ownerEmail:z100.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z100.object({projects:z100.array(ExtendedProjectUsageRowDTOSchema),top:z100.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z100.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z100.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z100.object({credits:z100.number(),costUsd:z100.number(),messages:z100.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z100.object({id:z100.string(),name:z100.string(),createdAt:z100.string(),memberCount:z100.number(),projectCount:z100.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z100.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z100.object({id:z100.string(),name:z100.string().nullable(),email:z100.string(),image:z100.string().nullable(),createdAt:z100.string(),organizationCount:z100.number(),projectCount:z100.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z100.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z100.object({id:z100.string(),name:z100.string(),displayName:z100.string().nullable(),createdAt:z100.string(),organizationId:z100.string(),organizationName:z100.string(),ownerId:z100.string(),ownerName:z100.string().nullable(),ownerEmail:z100.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z100.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z101}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=z101.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z101.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z101.object({command:z101.string().min(1).max(1e4),cwd:z101.string().optional(),projectBranch:BranchSchema.optional(),projectEnv:BranchSchema.optional(),env:z101.record(z101.string(),z101.string()).optional(),name:z101.string().optional(),waitForCompletion:z101.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=z101.object({identifier:z101.string(),status:SandboxProcessStatusSchema,command:z101.string().optional(),startedAt:z101.string().optional(),exitCode:z101.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z101.object({processes:z101.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z101.object({processId:z101.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z101.object({success:z101.boolean(),message:z101.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z102}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=z102.enum(ADMIN_UNCLAIMED_STATES),AdminUnclaimedProjectsQuerySchema=z102.object({search:z102.string().trim().max(200).optional(),startDate:z102.coerce.date().optional(),endDate:z102.coerce.date().optional(),states:z102.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z102.array(AdminUnclaimedStateSchema).optional()),cliVersions:z102.string().optional().transform(value=>value?value.split(",").filter(Boolean):void 0).pipe(z102.array(z102.string().max(64)).optional()),page:z102.coerce.number().int().min(1).default(1),pageSize:z102.coerce.number().int().min(1).max(100).default(25)}),AdminUnclaimedProjectDTOSchema=z102.object({projectId:z102.string(),displayName:z102.string().nullable(),state:AdminUnclaimedStateSchema,cliVersion:z102.string().nullable(),createdAt:z102.coerce.date(),expiresAt:z102.coerce.date(),claimedAt:z102.coerce.date().nullable(),claimedOrganizationId:z102.string().nullable(),claimedOrganizationName:z102.string().nullable(),claimedByEmail:z102.string().nullable(),projectExists:z102.boolean(),previewUrl:z102.string().nullable(),hostingCostUsd:z102.number().nullable()}),AdminUnclaimedProjectDTO=createDTO(AdminUnclaimedProjectDTOSchema),AdminUnclaimedProjectsResponseSchema=createResponseSchema(z102.object({projects:z102.array(AdminUnclaimedProjectDTOSchema),page:z102.number(),limit:z102.number(),total:z102.number(),totalPages:z102.number()})),ClaimOutcomesSchema=z102.object({total:z102.number(),claimed:z102.number(),archived:z102.number(),claimRate:z102.number().nullable(),medianTimeToClaimSeconds:z102.number().nullable()}),AdminUnclaimedProjectStatsSchema=ClaimOutcomesSchema.extend({states:z102.record(AdminUnclaimedStateSchema,z102.number()),averageTimeToClaimSeconds:z102.number().nullable(),byCliVersion:z102.array(ClaimOutcomesSchema.extend({cliVersion:z102.string().nullable()})),granularity:z102.enum(["hour","day"]),series:z102.array(z102.object({at:z102.coerce.date(),states:z102.record(AdminUnclaimedStateSchema,z102.number()),alive:z102.number(),hostingCostUsd:z102.number()})),hostingCostUsd:z102.number(),costPerProjectUsd:z102.number().nullable(),leftovers:z102.object({overdue:z102.number(),claiming:z102.number(),archivedNotDeleted:z102.number()})}),AdminUnclaimedProjectStatsResponseSchema=createResponseSchema(AdminUnclaimedProjectStatsSchema)}});import{z as z103}from"zod";var WorkSessionVisibilitySchema,SessionSetRetentionSchema,init_work_sessions=__esm({"../../packages/api-contracts/dist/esm/work-sessions.js"(){"use strict";WorkSessionVisibilitySchema=z103.enum(["internal","user-visible"]),SessionSetRetentionSchema=z103.object({additionalDays:z103.number().int().min(1).max(30)}).strict()}});import{z as z104}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=z104.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=z104.object({content:ProjectKnowledgeContentSchema,updatedAt:z104.string().nullable(),updatedBy:z104.string().nullable()}),ProjectKnowledgeUpdateSchema=z104.object({content:ProjectKnowledgeContentSchema}),ProjectKnowledgeResponseSchema=createResponseSchema(ProjectKnowledgeDTOSchema),ProjectKnowledgeDraftDTOSchema=z104.object({id:z104.uuid(),status:z104.enum(["queued","running","ready","failed"]),content:ProjectKnowledgeContentSchema.nullable(),error:z104.string().nullable()}),ProjectKnowledgeDraftResponseSchema=createResponseSchema(ProjectKnowledgeDraftDTOSchema.nullable()),ProjectKnowledgeDraftStartSchema=z104.object({idempotencyKey:z104.uuid()})}});import{z as z105}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_args();init_commands();init_references2();init_types();init_chat_block();init_chat_block_state();init_admin_chat_block();init_admin_assistant();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_catalog_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_chat_task_dto();init_chat_agent_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();init_admin_monitoring_dto();init_platform();init_monitor();init_agent()}});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_types2=__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=path52.basename(filename,path52.extname(filename)),this}executableDir(path53){return path53===void 0?this._executableDir:(this._executableDir=path53,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")}});import{z as z106}from"zod";function createResponseSchema2(dataSchema){return z106.object({data:dataSchema})}function encodeBranchPathSegment2(branch){return encodeURIComponent(branch.replaceAll("/","--"))}function managementProjectPath(projectId2,suffix){return`/management/projects/${encodeURIComponent(projectId2)}${suffix}`}function managementBranchPath(projectId2,branch,suffix){return managementProjectPath(projectId2,`/branches/${encodeBranchPathSegment2(branch)}${suffix}`)}function tenantPath(projectId2,branch,suffix){return`/tenant/${encodeURIComponent(projectId2)}/branches/${encodeBranchPathSegment2(branch)}${suffix}`}function addQuery(path52,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?`${path52}?${queryString}`:path52}function withoutUndefined(values){return Object.fromEntries(Object.entries(values).filter(([,value])=>value!==void 0))}function utf8Text(maxBytes,message){return z106.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 z106.object({items:z106.array(itemSchema),nextCursor:z106.string().nullable(),total:z106.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(projectId2,branch,sessionId,suffix){return sessionId?managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/files${suffix}`):managementBranchPath(projectId2,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=z106.uuid(),sessionStatusSchema=z106.enum(["provisioning","ready","closing","merged","discarded","expired","failed"]),surfaceNameSchema=z106.enum(["code","schemas","content","labels","assets","forms"]),branchSurfaceSchema=z106.enum(["code","schemas","content","labels","assets","forms"]),backendSurfaceSchema=z106.enum(["code","schemas","content","translations","assets","forms"]),branchNameSchema=z106.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=z106.object({sessionId:uuidSchema,projectId:uuidSchema,status:sessionStatusSchema,name:z106.string().nullable().optional(),goal:z106.string().nullable().optional(),provenance:z106.object({source:z106.enum(["studio","slack","mcp"]),creator:z106.object({kind:z106.enum(["user","slack","agent","oauth","conversation"]),id:z106.string()}),conversationId:z106.string().nullable(),runId:z106.string().nullable()}).nullable().optional(),createdBy:z106.string().optional(),createdAt:z106.iso.datetime().optional(),savedRevision:z106.string().nullable().optional(),targetBranch:z106.object({id:uuidSchema.nullable(),name:branchNameSchema,sha:z106.string().min(1)}),workingBranch:z106.object({id:uuidSchema,name:branchNameSchema}).nullable(),preview:z106.url().nullable(),lastActivityAt:z106.iso.datetime(),expiresAt:z106.iso.datetime().nullable(),retention:z106.enum(["temporary","durable"]).optional(),visibility:z106.enum(["internal","user-visible"]).optional(),onExpire:z106.enum(["discard","keep"]),nextOperations:z106.array(z106.string())}),paginationShape={limit:z106.number().int().min(1).max(100).optional(),cursor:z106.string().min(1).nullable().optional().describe("Opaque nextCursor from the previous page. Omit or use null for the first page."),offset:z106.number().int().min(0).optional()};__name(paginationRefinement,"paginationRefinement");__name(encodePaginationCursor,"encodePaginationCursor");__name(decodePaginationCursor,"decodePaginationCursor");__name(paginationOffset,"paginationOffset");numberedPaginationShape={page:z106.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=z106.object({data:z106.array(z106.unknown()),meta:z106.object({limit:z106.number().int().positive(),offset:z106.number().int().nonnegative(),total:z106.number().int().nonnegative(),hasMore:z106.boolean()})});__name(projectOffsetPage,"projectOffsetPage");__name(projectDetail,"projectDetail");__name(requiredBranch,"requiredBranch");__name(projectFilesPath,"projectFilesPath")}});import{z as z107}from"zod";var agent,chats,routines,routineRuns,agentsOperations,init_agents=__esm({"../../packages/sdk/dist/operations/agents.js"(){"use strict";init_common2();agent=z107.object({id:uuidSchema,kind:z107.string(),title:z107.string().nullable(),description:z107.string().nullable()}),chats=z107.object({chats:z107.array(agent)}),routines=z107.object({routines:z107.array(z107.object({id:uuidSchema,name:z107.string(),instructions:z107.string(),paused:z107.boolean(),triggers:z107.object({schedule:z107.object({cron:z107.string(),timezone:z107.string()}).nullable(),event:z107.object({text:z107.string()}).nullable()}),nextRunAt:z107.string().nullable(),lastRunAt:z107.string().nullable(),lastOutcome:z107.string().nullable(),outOfAgentHoursUntil:z107.string().nullable()}))}),routineRuns=z107.object({runs:z107.array(z107.object({startedAt:z107.string(),trigger:z107.enum(["schedule","hand","event"]),startedBy:z107.object({kind:z107.enum(["person","agent"]),name:z107.string().nullable()}).nullable(),status:z107.enum(["queued","running","finished","failed","cancelled"]),outcome:z107.string().nullable(),summary:z107.string().nullable(),durationMs:z107.number().nullable()}))}),agentsOperations={"agents.list":{domain:"agents",summary:"Read the project agents.",accessScope:"read",effect:"read",inputSchema:z107.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:chats,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",context:{branch},path:addQuery("/chat/project/threads",{projectId:projectId2})}),"buildRequest"),projectOutput:__name(body=>({chats:chats.parse(body).chats.filter(chat=>chat.kind==="agent")}),"projectOutput")},"agents.routines":{domain:"agents",summary:"Read an agent\u2019s routine instructions and schedules.",accessScope:"read",effect:"read",inputSchema:z107.object({projectId:uuidSchema,branch:branchNameSchema,threadId:uuidSchema}).strict(),outputSchema:routines,buildRequest:__name(({projectId:projectId2,branch,threadId})=>({method:"GET",context:{branch},path:addQuery(`/chat/project/threads/${threadId}/routines`,{projectId:projectId2})}),"buildRequest")},"agents.routineRuns":{domain:"agents",summary:"Read a routine\u2019s newest runs: when each started, what started it and how it ended.",accessScope:"read",effect:"read",inputSchema:z107.object({projectId:uuidSchema,branch:branchNameSchema,threadId:uuidSchema,routineId:uuidSchema}).strict(),outputSchema:routineRuns,buildRequest:__name(({projectId:projectId2,branch,threadId,routineId})=>({method:"GET",context:{branch},path:addQuery(`/chat/project/threads/${threadId}/routines/${routineId}/runs`,{projectId:projectId2})}),"buildRequest")}}}});import{z as z108}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=z108.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=z108.enum(["day","week","month","quarter"]),analyticsDeviceSchema=z108.enum(["bot","desktop","mobile","tablet"]),analyticsRangeShape={preset:analyticsPresetSchema.optional(),device:analyticsDeviceSchema.optional(),groupBy:analyticsGroupBySchema.optional(),from:z108.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),to:z108.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),days:z108.union([z108.literal(7),z108.literal(30),z108.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=z108.object({date:z108.string(),content:z108.string(),updatedAt:z108.string(),updatedByUserId:z108.string()}),analyticsBreakdownSchema=z108.object({key:z108.string(),visitors:z108.number().int().nonnegative(),pageviews:z108.number().int().nonnegative()}),analyticsPageBreakdownSchema=z108.object({path:z108.string(),pageName:z108.string().nullable().optional(),visitors:z108.number().int().nonnegative(),pageviews:z108.number().int().nonnegative()}),analyticsPageviewsSchema=z108.object({range:z108.object({preset:analyticsPresetSchema,requestedFrom:z108.string(),requestedTo:z108.string(),effectiveFrom:z108.string(),effectiveTo:z108.string(),isRetentionLimited:z108.boolean(),groupBy:analyticsGroupBySchema}),deviceFilter:analyticsDeviceSchema.nullable().default(null),visitors:z108.number().int().nonnegative(),pageviews:z108.number().int().nonnegative(),botPageviews:z108.number().int().nonnegative().default(0),botVisitors:z108.number().int().nonnegative().default(0),bounceRate:z108.number().min(0).max(100),viewsPerVisit:z108.number().nonnegative(),averageVisitDurationSeconds:z108.number().nonnegative(),visitorsSeries:z108.array(z108.object({date:z108.string(),visitors:z108.number().int().nonnegative()})),topPages:z108.array(analyticsPageBreakdownSchema),topBrowsers:z108.array(analyticsBreakdownSchema),topDevices:z108.array(analyticsBreakdownSchema),topBots:z108.array(analyticsBreakdownSchema).default([]),topAiAssistants:z108.array(analyticsBreakdownSchema).default([]),topCountries:z108.array(analyticsBreakdownSchema),topSources:z108.array(analyticsBreakdownSchema),annotations:z108.array(analyticsAnnotationSchema)}),analyticsApiResponseSchema=createResponseSchema2(analyticsPageviewsSchema),analyticsPageviewsResponseSchema=createResponseSchema2(analyticsPageviewsSchema.extend({branch:branchNameSchema})),analyticsDimensionSchema=z108.enum(["pages","browsers","devices","countries","sources"]),analyticsTopOutputSchema=z108.object({branch:branchNameSchema,dimension:analyticsDimensionSchema,items:z108.array(z108.union([analyticsPageBreakdownSchema,analyticsBreakdownSchema]))}),analyticsAnnotationsOutputSchema=z108.object({branch:branchNameSchema,annotations:z108.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:z108.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:projectId2,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,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:z108.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,dimension:analyticsDimensionSchema,limit:z108.number().int().min(1).max(100).optional(),...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsTopOutputSchema,buildRequest:__name(({projectId:projectId2,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,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:z108.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsAnnotationsOutputSchema,buildRequest:__name(({projectId:projectId2,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,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:z108.object({projectId:uuidSchema,branch:branchNameSchema,date:z108.string().regex(/^\d{4}-\d{2}-\d{2}$/),content:z108.string().max(500)}).strict(),outputSchema:z108.union([analyticsAnnotationResponseSchema,z108.null()]),buildRequest:__name(({projectId:projectId2,branch,date,content:content2})=>({method:"PUT",path:managementBranchPath(projectId2,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:z108.object({projectId:uuidSchema,branch:branchNameSchema,date:z108.string().regex(/^\d{4}-\d{2}-\d{2}$/)}).strict(),outputSchema:z108.null(),buildRequest:__name(({projectId:projectId2,branch,date})=>({method:"PUT",path:managementBranchPath(projectId2,branch,`/analytics/annotations/${encodeURIComponent(date)}`),body:{content:""}}),"buildRequest"),projectOutput:__name(()=>null,"projectOutput")}}}});import{z as z109}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=z109.object({id:z109.string(),name:z109.string()}),AssetDTOSchema2=z109.object({id:z109.string(),name:z109.string(),type:z109.enum(["file","folder"]),originalFileName:z109.string().nullable(),parentId:z109.string().nullable(),mimeType:z109.string().nullable(),fileSize:z109.number().nullable(),url:z109.string().nullable(),storageKey:z109.string().nullable(),slug:z109.string(),tags:z109.array(z109.string()).nullable().optional(),createdAt:z109.string().nullable(),updatedAt:z109.string().nullable(),altText:z109.string().nullable().optional(),caption:z109.string().nullable().optional(),aiCaption:z109.string().nullable().optional(),aiAltText:z109.string().nullable().optional(),aiTags:z109.array(z109.string()).nullable().optional(),aiPrimaryColor:z109.string().nullable().optional(),aiProcessingStatus:z109.string().nullable().optional(),width:z109.number().nullable().optional(),height:z109.number().nullable().optional(),path:z109.array(assetPathItemSchema).optional(),hasChildren:z109.boolean().optional()}),AssetResponseSchema2=createResponseSchema2(AssetDTOSchema2),AssetReadRequestSchema2=z109.object({cursor:z109.string().nullable().optional(),query:z109.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=z109.object({url:z109.url(),mediaType:z109.string(),filename:z109.string()}),assetReadBaseSchema=z109.object({assetId:z109.uuid(),filename:z109.string(),mediaType:z109.string(),representation:z109.enum(["text","table","document","archive","image","transcript","video","model"]),content:z109.string(),derivedFiles:z109.array(assetDerivedFileSchema).optional()}),AssetReadResultSchema2=z109.discriminatedUnion("mode",[assetReadBaseSchema.extend({mode:z109.literal("page"),start:z109.number().int().nonnegative(),end:z109.number().int().nonnegative(),total:z109.number().int().nonnegative(),nextCursor:z109.string().nullable(),complete:z109.boolean()}),assetReadBaseSchema.extend({mode:z109.literal("query"),query:z109.string(),source:z109.enum(["original-file","canonical-text","derived-files"]),truncated:z109.boolean()})]),GenerateResponseSchema2=createResponseSchema2(z109.object({jobId:z109.string(),status:z109.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema2.optional(),error:z109.string().nullable().optional(),credits:z109.number().optional(),costUsd:z109.number().optional(),billingMode:z109.enum(["fimo-credits","provider-account"]).optional(),task:z109.enum(["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"]).optional(),quality:z109.enum(["draft","standard","premium"]).optional()})),assetPageSchema=pageSchema(AssetDTOSchema2),successMessageResponseSchema=z109.object({data:z109.object({message:z109.literal("success")})}),assetGenerationInputSchema=z109.object({projectId:uuidSchema,branch:branchNameSchema,task:z109.string().min(1).optional(),model:z109.string().min(1).optional(),options:z109.record(z109.string(),z109.unknown()),name:z109.string().min(1).max(255).optional(),parentId:uuidSchema.nullable().optional(),altText:z109.string().max(2e3).optional(),caption:z109.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=z109.object({projectId:uuidSchema,sessionId:uuidSchema,url:z109.url().max(4096).refine(url=>url.startsWith("https://")||url.startsWith("http://"),"URL must use HTTP or HTTPS"),filename:z109.string().trim().min(1).max(255).refine(filename=>!filename.includes("/")&&!filename.includes("\\"),"Filename must not contain a path").optional(),name:z109.string().trim().min(1).max(255).optional(),parentId:uuidSchema.nullable().optional(),folderPath:z109.string().max(1024).refine(path52=>path52.split("/").some(segment=>segment.trim()),"Folder path must contain a folder name").refine(path52=>path52.split("/").every(segment=>![".",".."].includes(segment.trim())),"Folder path cannot contain . or .. segments").optional(),altText:z109.string().max(2e3).optional(),caption:z109.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:z109.object({projectId:uuidSchema,branch:branchNameSchema,parentId:uuidSchema.optional(),search:z109.string().max(200).optional(),type:z109.enum(["file","folder"]).optional(),mimePrefix:z109.string().max(50).optional(),sortBy:z109.enum(["name","createdAt","updatedAt","fileSize","type"]).optional(),sortDirection:z109.enum(["asc","desc"]).optional(),includePath:z109.boolean().optional(),excludeHidden:z109.boolean().optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:assetPageSchema,buildRequest:__name(({projectId:projectId2,branch,parentId,search,type,mimePrefix,sortBy,sortDirection,includePath,excludeHidden,limit,cursor,offset})=>({method:"GET",path:addQuery(tenantPath(projectId2,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:z109.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:AssetResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,id})=>({method:"GET",path:tenantPath(projectId2,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:z109.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:projectId2,branch,id,cursor,query})=>({method:"POST",path:tenantPath(projectId2,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:projectId2,branch,task,model,options,name,parentId,altText,caption})=>({method:"POST",path:tenantPath(projectId2,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:projectId2,sessionId,...upload})=>({method:"POST",path:managementProjectPath(projectId2,`/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:z109.object({projectId:uuidSchema,branch:branchNameSchema,name:z109.string().min(1).max(255),parentId:uuidSchema.nullable().optional()}).strict(),outputSchema:AssetResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,name,parentId})=>({method:"POST",path:tenantPath(projectId2,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:z109.object({projectId:uuidSchema,branch:branchNameSchema,sourceAssetId:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z109.record(z109.string(),z109.unknown()),buildRequest:__name(({projectId:projectId2,branch,sourceAssetId,replacementAssetId})=>({method:"POST",path:tenantPath(projectId2,branch,`/assets/${encodeURIComponent(sourceAssetId)}/replace-references`),body:{replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z109.object({data:z109.record(z109.string(),z109.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:z109.object({projectId:uuidSchema,branch:branchNameSchema,sourceAssetId:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z109.record(z109.string(),z109.unknown()),buildRequest:__name(({projectId:projectId2,branch,sourceAssetId,replacementAssetId})=>({method:"POST",path:tenantPath(projectId2,branch,"/assets/removals"),body:{intent:"replace-and-remove",assetIds:[sourceAssetId],replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z109.object({data:z109.record(z109.string(),z109.unknown())}).parse(body).data,"projectOutput")},"assets.destroy":{domain:"assets",summary:"Permanently destroy an asset on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z109.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:z109.unknown(),buildRequest:__name(({projectId:projectId2,branch,id})=>({method:"DELETE",path:tenantPath(projectId2,branch,`/assets/${encodeURIComponent(id)}/permanent`)}),"buildRequest"),projectOutput:__name(body=>z109.object({data:z109.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:z109.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z109.record(z109.string(),z109.unknown()),buildRequest:__name(({projectId:projectId2,branch,id,replacementAssetId})=>({method:"POST",path:tenantPath(projectId2,branch,`/assets/${encodeURIComponent(id)}/replace-and-destroy`),body:{replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z109.object({data:z109.record(z109.string(),z109.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:z109.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,parentId:uuidSchema.nullable()}).strict(),outputSchema:AssetResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,id,parentId})=>({method:"POST",path:tenantPath(projectId2,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:z109.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:successMessageResponseSchema,buildRequest:__name(({projectId:projectId2,branch,id})=>({method:"DELETE",path:tenantPath(projectId2,branch,`/assets/${encodeURIComponent(id)}`)}),"buildRequest")}}}});import{z as z110}from"zod";var creditBalanceOutputSchema,billingOperations,init_billing2=__esm({"../../packages/sdk/dist/operations/billing.js"(){"use strict";init_common2();creditBalanceOutputSchema=z110.object({projectId:uuidSchema,organizationId:z110.string(),balance:z110.object({totalAvailable:z110.number(),nearLimit:z110.boolean(),canUseAi:z110.boolean(),buckets:z110.object({dailyFreeAvailable:z110.number(),monthlyAvailable:z110.number(),purchasedAvailable:z110.number(),awardedAvailable:z110.number()})}),allowances:z110.object({dailyCredits:z110.object({periodCap:z110.number(),dailyGrant:z110.number(),usedThisPeriod:z110.number(),remainingThisPeriod:z110.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:z110.object({projectId:uuidSchema}).strict(),outputSchema:creditBalanceOutputSchema,buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/billing/credits")}),"buildRequest"),projectOutput:__name(body=>creditBalanceOutputSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z111}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=z111.object({ok:z111.boolean(),mergeId:uuidSchema,fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),fromEnv:branchNameSchema,toEnv:branchNameSchema,applied:z111.array(z111.object({surface:backendSurfaceSchema,count:z111.number().int().nonnegative()})),conflicts:z111.array(backendConflictSchema).optional(),summary:z111.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=z111.object({mergeId:uuidSchema,conflicts:z111.array(backendConflictSchema),draftResolutions:z111.array(conflictResolutionSchema.extend({surface:backendSurfaceSchema})),status:z111.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 z111.object({data:z111.array(branchSchema)}).parse({data})}function projectBranchStatus(body){if(branchStatusOutputSchema.safeParse(body).success)return branchStatusOutputSchema.parse(body);let report2=z111.object({branch:branchNameSchema.optional(),env:branchNameSchema,vs:branchNameSchema,syncState:z111.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:isoTimestampSchema,surfaces:z111.array(backendSurfaceDeltaSchema).max(6),crossSurface:z111.array(backendCrossSurfaceFindingSchema).max(1e3).optional()}).parse(responseData(body));return branchStatusOutputSchema.parse(withoutUndefined({branch:report2.branch??report2.env,against:report2.vs,state:report2.syncState==="in-sync"?"clean":"changed",syncState:report2.syncState,generatedAt:report2.generatedAt,surfaces:report2.surfaces.map(({surface,status,changedCount,conflictCount,items,truncated,error})=>withoutUndefined({surface:publicSurface(surface),status,changedCount,conflictCount,items,truncated,error})),crossSurface:report2.crossSurface?.map(projectCrossSurfaceFinding)}))}function projectBranchDiff(body){if(branchDiffOutputSchema.safeParse(body).success)return branchDiffOutputSchema.parse(body);let report2=z111.object({fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),fromEnv:branchNameSchema,toEnv:branchNameSchema,generatedAt:isoTimestampSchema,fingerprint:z111.string().min(1),surfaces:z111.array(backendSurfaceDeltaSchema).max(6),crossSurface:z111.array(backendCrossSurfaceFindingSchema).max(1e3).optional()}).parse(responseData(body));return branchDiffOutputSchema.parse({branch:report2.fromBranch??report2.fromEnv,against:report2.toBranch??report2.toEnv,generatedAt:report2.generatedAt,fingerprint:report2.fingerprint,surfaces:report2.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:report2.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,resolvedMergeStrategySchema,mergeAcceptedSchema,mergeStatusSchema,mergeHydrationSchema,codeConflictBlobSchema,codeConflictDetailOutputSchema,branchesOperations,init_branches=__esm({"../../packages/sdk/dist/operations/branches.js"(){"use strict";init_common2();branchSchema=z111.object({id:uuidSchema,projectId:uuidSchema,branch:branchNameSchema,parentBranch:branchNameSchema.nullable().optional(),status:z111.enum(["provisioning","active","deleted"]),kind:z111.enum(["user","agent-session"]),createdAt:z111.string().optional(),updatedAt:z111.string().optional(),createdBy:z111.string().nullable().optional(),deletedAt:z111.string().nullable().optional()}).passthrough(),branchResponseSchema=z111.object({data:branchSchema}),branchSurfaceStatusSchema=z111.enum(["ok","timed_out","failed","unchanged"]),branchDeltaVerbSchema=z111.enum(["added","removed","changed","conflict"]),isoTimestampSchema=z111.iso.datetime(),backendCrossSurfaceFindingSchema=z111.object({id:z111.string(),kind:z111.string(),description:z111.string(),severity:z111.enum(["warning","error"]),source:z111.object({surface:backendSurfaceSchema,key:z111.string()}),target:z111.object({surface:backendSurfaceSchema,key:z111.string()}),actions:z111.array(z111.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=z111.object({surface:backendSurfaceSchema,status:branchSurfaceStatusSchema,changedCount:z111.number().int().nonnegative(),conflictCount:z111.number().int().nonnegative(),items:z111.array(z111.object({verb:branchDeltaVerbSchema,key:z111.string(),detail:z111.string().optional(),origin:z111.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z111.record(z111.string(),z111.unknown()).optional()})).max(1e3).optional(),truncated:z111.boolean().optional(),error:z111.string().optional()}),branchSurfaceSummarySchema=z111.object({surface:branchSurfaceSchema,status:branchSurfaceStatusSchema,changedCount:z111.number().int().nonnegative(),conflictCount:z111.number().int().nonnegative(),error:z111.string().optional(),items:z111.array(z111.object({verb:branchDeltaVerbSchema,key:z111.string(),detail:z111.string().optional(),origin:z111.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z111.record(z111.string(),z111.unknown()).optional()})).optional(),truncated:z111.boolean().optional()}),branchStatusOutputSchema=z111.object({branch:branchNameSchema,against:branchNameSchema,state:z111.enum(["clean","changed"]),syncState:z111.enum(["in-sync","ahead","behind","diverged","unknown"]).optional(),generatedAt:isoTimestampSchema,surfaces:z111.array(branchSurfaceSummarySchema).max(6),crossSurface:z111.array(crossSurfaceFindingSchema).max(1e3).optional()}),branchDiffItemSchema=z111.object({verb:branchDeltaVerbSchema,key:z111.string(),detail:z111.string().optional(),meta:z111.record(z111.string(),z111.unknown()).optional()}),branchDiffOutputSchema=branchStatusOutputSchema.omit({state:!0}).extend({fingerprint:z111.string().min(1),surfaces:z111.array(branchSurfaceSummarySchema.extend({truncated:z111.boolean(),items:z111.array(branchDiffItemSchema).max(1e3)})).max(6)}),codeFileDiffOutputSchema=z111.object({path:z111.string(),state:z111.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z111.string(),additions:z111.number().int().nonnegative(),deletions:z111.number().int().nonnegative()}),contentSnapshotSchema=z111.object({id:z111.string(),slug:z111.string(),contentType:z111.string(),data:z111.record(z111.string(),z111.unknown()),updatedAt:isoTimestampSchema}),contentEntryDiffOutputSchema=z111.object({collection:z111.string(),rowId:z111.string(),parent:contentSnapshotSchema.nullable(),child:contentSnapshotSchema.nullable()}),schemaSnapshotSchema=z111.object({name:z111.string(),label:z111.string(),isSingleton:z111.boolean(),fields:z111.record(z111.string(),z111.unknown())}),schemaDiffOutputSchema=z111.object({typeName:z111.string(),parent:schemaSnapshotSchema.nullable(),child:schemaSnapshotSchema.nullable()}),assetSnapshotSchema=z111.object({id:z111.string(),name:z111.string(),type:z111.enum(["file","folder"]),mimeType:z111.string().nullable(),storageKey:z111.string().nullable(),url:z111.string().nullable(),fileSize:z111.number().nullable(),width:z111.number().nullable(),height:z111.number().nullable(),altText:z111.string().nullable(),caption:z111.string().nullable(),createdAt:isoTimestampSchema,updatedAt:isoTimestampSchema}),assetDiffOutputSchema=z111.object({assetId:z111.string(),parent:assetSnapshotSchema.nullable(),child:assetSnapshotSchema.nullable()}),labelDiffOutputSchema=z111.object({locale:z111.string(),key:z111.string(),parent:z111.string().nullable(),child:z111.string().nullable()}),formSnapshotSchema=z111.object({formName:z111.string(),label:z111.string().nullable(),schemaFingerprint:z111.string(),fields:z111.record(z111.string(),z111.unknown())}),formDiffOutputSchema=z111.object({formName:z111.string(),parent:formSnapshotSchema.nullable(),child:formSnapshotSchema.nullable()}),backendConflictSchema=z111.object({surface:backendSurfaceSchema,key:z111.string(),kind:z111.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"]).optional(),description:z111.string(),parentValue:z111.unknown().optional(),childValue:z111.unknown().optional(),conflictingFields:z111.array(z111.string()).optional(),code:z111.object({path:z111.string(),unresolvable:z111.boolean().optional(),reason:z111.string().optional()}).optional()}),conflictSchema=backendConflictSchema.extend({surface:branchSurfaceSchema}),fieldPickSchema=z111.object({field:z111.string(),choice:z111.enum(["parent","child","pick","ai-pick"]),pickedValue:z111.unknown().optional(),aiSessionId:z111.string().optional()}),conflictResolutionSchema=z111.object({surface:branchSurfaceSchema,key:z111.string(),choice:z111.enum(["parent","child","pick"]),pickedValue:z111.unknown().optional(),fieldPicks:z111.array(fieldPickSchema).optional()}),mergeResultSchema=z111.object({ok:z111.boolean(),mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,applied:z111.array(z111.object({surface:branchSurfaceSchema,count:z111.number().int().nonnegative()})),conflicts:z111.array(conflictSchema).optional(),summary:z111.string().optional()}),resolvedMergeStrategySchema=z111.object({engine:z111.enum(["ff-only","auto","theirs","ours","manual"]),vendor:z111.enum(["ff_only","ff_prefer","merge"]),squash:z111.boolean()}),mergeAcceptedSchema=z111.object({mergeId:uuidSchema,streamUrl:z111.string(),strategy:resolvedMergeStrategySchema,acceptedAt:isoTimestampSchema}),mergeStatusSchema=z111.object({mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,status:z111.enum(["in_progress","complete","failed","rolled_back","conflicts"]),summary:z111.string().nullable(),error:z111.string().nullable()}),mergeHydrationSchema=z111.object({mergeId:uuidSchema,conflicts:z111.array(conflictSchema),draftResolutions:z111.array(conflictResolutionSchema),status:z111.string()}).passthrough();__name(projectConflict,"projectConflict");__name(backendResolution,"backendResolution");__name(projectMergeResult,"projectMergeResult");__name(projectMergeHydration,"projectMergeHydration");codeConflictBlobSchema=z111.object({content:z111.string(),sha:z111.string().nullable().optional()}).passthrough(),codeConflictDetailOutputSchema=z111.object({path:z111.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:z111.object({projectId:uuidSchema,includeDeleted:z111.boolean().optional(),includeAgentBranches:z111.boolean().optional()}).strict(),outputSchema:z111.object({data:z111.array(branchSchema)}),buildRequest:__name(({projectId:projectId2,includeDeleted,includeAgentBranches})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,"/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:z111.object({projectId:uuidSchema,from:branchNameSchema.optional(),name:branchNameSchema}).strict(),outputSchema:branchResponseSchema,buildRequest:__name(({projectId:projectId2,from,name})=>({method:"POST",path:managementProjectPath(projectId2,"/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:z111.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:branchSchema,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:managementBranchPath(projectId2,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:z111.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema.optional()}).strict(),outputSchema:z111.object({branch:branchSchema,conflicts:z111.number().int().nonnegative()}),buildRequest:__name(({projectId:projectId2,branch,from})=>({method:"POST",path:managementBranchPath(projectId2,branch,"/sync"),body:withoutUndefined({from})}),"buildRequest"),projectOutput:__name(body=>{let data=z111.object({branch:branchSchema.optional(),env:branchSchema.optional(),conflicts:z111.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:z111.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:z111.unknown(),buildRequest:__name(({projectId:projectId2,branch})=>({method:"DELETE",path:managementBranchPath(projectId2,branch,"")}),"buildRequest")},"branches.status":{domain:"branches",summary:"Summarize bounded differences between two durable Branches.",accessScope:"read",effect:"read",inputSchema:z111.object({projectId:uuidSchema,branch:branchNameSchema,against:branchNameSchema.optional(),surfaces:z111.array(branchSurfaceSchema).min(1).max(6).optional()}).strict(),outputSchema:branchStatusOutputSchema,buildRequest:__name(({projectId:projectId2,branch,against,surfaces})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,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:z111.object({projectId:uuidSchema,branch:branchNameSchema,against:branchNameSchema.optional(),surfaces:z111.array(branchSurfaceSchema).min(1).max(6).optional()}).strict(),outputSchema:branchDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,against,surfaces})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,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:z111.object({projectId:uuidSchema,branch:branchNameSchema,path:z111.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:codeFileDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,path:path52,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,"/diff/code/file"),{path:path52,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:z111.object({projectId:uuidSchema,branch:branchNameSchema,collection:z111.string().min(1),rowId:z111.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:contentEntryDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,collection,rowId,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,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:z111.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z111.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:schemaDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,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:z111.object({projectId:uuidSchema,branch:branchNameSchema,assetId:z111.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:assetDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,assetId,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,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:z111.object({projectId:uuidSchema,branch:branchNameSchema,locale:z111.string().min(1),key:z111.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:labelDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,locale,key,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,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:z111.object({projectId:uuidSchema,branch:branchNameSchema,formName:z111.string().min(1).max(255),against:branchNameSchema.optional()}).strict(),outputSchema:formDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,formName,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,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:z111.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,allowDirectMerge:z111.boolean().optional()}).strict(),outputSchema:mergeResultSchema,buildRequest:__name(({projectId:projectId2,branch,from,allowDirectMerge})=>({method:"POST",path:managementBranchPath(projectId2,branch,"/merge"),body:withoutUndefined({from,allowDirectMerge})}),"buildRequest"),projectOutput:projectMergeResult},"branches.resolveMerge":{domain:"branches",summary:"Resume a parked durable Branch merge with operator resolutions and start its successor merge.",accessScope:"code",effect:"mutation",inputSchema:z111.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,mergeId:uuidSchema,resolutions:z111.array(conflictResolutionSchema)}).strict(),outputSchema:mergeAcceptedSchema,buildRequest:__name(({projectId:projectId2,branch,from,mergeId,resolutions})=>({method:"POST",path:managementBranchPath(projectId2,branch,`/merge/${encodeURIComponent(from)}/resolve`),body:{mergeId,resolutions:resolutions.map(backendResolution)}}),"buildRequest"),projectOutput:projectDetail(mergeAcceptedSchema)},"branches.mergeStatus":{domain:"branches",summary:"Read the current status of one durable Branch merge.",accessScope:"read",effect:"read",inputSchema:z111.object({projectId:uuidSchema,mergeId:uuidSchema}).strict(),outputSchema:mergeStatusSchema,buildRequest:__name(({projectId:projectId2,mergeId})=>({method:"GET",path:managementProjectPath(projectId2,`/merges/${encodeURIComponent(mergeId)}`)}),"buildRequest"),projectOutput:projectDetail(mergeStatusSchema)},"branches.cancelMerge":{domain:"branches",summary:"Cancel a parked durable Branch merge.",accessScope:"code",effect:"mutation",inputSchema:z111.object({projectId:uuidSchema,branch:branchNameSchema,mergeId:uuidSchema}).strict(),outputSchema:z111.object({ok:z111.boolean()}),buildRequest:__name(({projectId:projectId2,branch,mergeId})=>({method:"POST",path:managementBranchPath(projectId2,branch,"/merge/cancel"),body:{mergeId}}),"buildRequest"),projectOutput:__name(body=>z111.object({ok:z111.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:z111.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema}).strict(),outputSchema:mergeHydrationSchema,buildRequest:__name(({projectId:projectId2,branch,from})=>({method:"GET",path:managementBranchPath(projectId2,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:z111.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,mergeId:uuidSchema,resolutions:z111.array(conflictResolutionSchema)}).strict(),outputSchema:z111.object({mergeId:uuidSchema,lastEditedAt:z111.string()}),buildRequest:__name(({projectId:projectId2,branch,from,mergeId,resolutions})=>({method:"PUT",path:managementBranchPath(projectId2,branch,`/merge/${encodeURIComponent(from)}/resolve/draft`),body:{mergeId,resolutions:resolutions.map(backendResolution)}}),"buildRequest"),projectOutput:__name(body=>z111.object({mergeId:uuidSchema,lastEditedAt:z111.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:z111.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,path:z111.string().min(1)}).strict(),outputSchema:codeConflictDetailOutputSchema,buildRequest:__name(({projectId:projectId2,branch,from,path:path52})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,`/merge/${encodeURIComponent(from)}/conflict/code`),{path:path52})}),"buildRequest"),projectOutput:projectDetail(codeConflictDetailOutputSchema)}}}});import{z as z112}from"zod";var projectDomainSchema,registeredDomainSchema,domainSearchResultSchema,domainPricingSchema,projectPath,forbidden,domainsOperations,init_domains=__esm({"../../packages/sdk/dist/operations/domains.js"(){"use strict";init_common2();projectDomainSchema=z112.object({id:z112.string(),hostname:z112.string(),status:z112.string(),ssl:z112.record(z112.string(),z112.unknown()),cnameTarget:z112.string(),apexTargets:z112.array(z112.string()),dnsAutoConfigured:z112.boolean(),createdAt:z112.unknown(),provider:z112.enum(["cloudflare","saas_custom_domains"]),domainType:z112.enum(["subdomain","apex"])}).passthrough(),registeredDomainSchema=z112.object({id:uuidSchema,domain:z112.string(),status:z112.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),source:z112.enum(["fimo","external"]),autoRenew:z112.boolean(),paymentStatus:z112.enum(["pending","paid","failed","refunded"]).nullable(),checkoutUrl:z112.string().nullable()}).passthrough(),domainSearchResultSchema=z112.object({domain:z112.string(),available:z112.boolean(),premium:z112.boolean(),price:z112.number().nullable(),renewalPrice:z112.number().nullable(),purchaseType:z112.string().nullable()}).passthrough(),domainPricingSchema=z112.object({domain:z112.string(),price:z112.number().nullable(),renewalPrice:z112.number().nullable(),premium:z112.boolean(),allowedYears:z112.array(z112.number().int().positive())}).passthrough(),projectPath=__name((projectId2,suffix)=>`/management/projects/${encodeURIComponent(projectId2)}${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:z112.object({}).strict(),outputSchema:z112.object({domainPurchaseEnabled:z112.boolean(),publicationDomain:z112.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:z112.object({projectId:uuidSchema,slug:z112.string().min(1).max(63)}).strict(),outputSchema:z112.object({subdomain:z112.string(),subdomainUpdatedAt:z112.string()}),buildRequest:__name(({projectId:projectId2,slug})=>({method:"PATCH",path:projectPath(projectId2,"/subdomain"),body:{slug}}),"buildRequest"),projectOutput:responseData},"domains.suggestSubdomains":{domain:"domains",summary:"Suggest available built-in subdomains for a site.",accessScope:"read",effect:"read",inputSchema:z112.object({projectId:uuidSchema,base:z112.string().min(1).max(63).optional(),max:z112.number().int().positive().optional()}).strict(),outputSchema:z112.array(z112.string()),buildRequest:__name(({projectId:projectId2,base,max})=>({method:"GET",path:addQuery(projectPath(projectId2,"/subdomain/suggestions"),{base,max})}),"buildRequest"),projectOutput:__name(body=>z112.object({data:z112.object({suggestions:z112.array(z112.string())})}).parse(body).data.suggestions,"projectOutput")},"domains.list":{domain:"domains",summary:"List custom domains attached to a site.",accessScope:"read",effect:"read",inputSchema:z112.object({projectId:uuidSchema}).strict(),outputSchema:z112.array(projectDomainSchema),buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:projectPath(projectId2,"/domains"),...forbidden}),"buildRequest"),projectOutput:responseData},"domains.add":{domain:"domains",summary:"Attach a custom domain to a site.",accessScope:"write",effect:"mutation",inputSchema:z112.object({projectId:uuidSchema,hostname:z112.string().min(1).max(255),redirectToWww:z112.boolean().optional()}).strict(),outputSchema:projectDomainSchema,buildRequest:__name(({projectId:projectId2,hostname,redirectToWww})=>({method:"POST",path:projectPath(projectId2,"/domains"),body:{hostname,redirectToWww},...forbidden}),"buildRequest"),projectOutput:responseData},"domains.refresh":{domain:"domains",summary:"Refresh custom-domain verification state.",accessScope:"write",effect:"mutation",inputSchema:z112.object({projectId:uuidSchema,domainId:z112.string().min(1)}).strict(),outputSchema:projectDomainSchema,buildRequest:__name(({projectId:projectId2,domainId})=>({method:"POST",path:projectPath(projectId2,`/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:z112.object({projectId:uuidSchema,domainId:z112.string().min(1)}).strict(),outputSchema:z112.unknown(),buildRequest:__name(({projectId:projectId2,domainId})=>({method:"DELETE",path:projectPath(projectId2,`/domains/${encodeURIComponent(domainId)}`),...forbidden}),"buildRequest")},"registeredDomains.search":{domain:"domains",summary:"Search domain-registration availability.",accessScope:"read",effect:"read",inputSchema:z112.object({keyword:z112.string().min(1).max(100),tldFilter:z112.array(z112.string().min(1)).optional()}).strict(),outputSchema:z112.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:z112.object({domain:z112.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:z112.object({organizationId:z112.string().min(1)}).strict(),outputSchema:z112.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:z112.object({organizationId:z112.string().min(1),domain:z112.string().min(1).max(255),years:z112.number().int().min(1).max(10).optional(),autoRenew:z112.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:z112.object({organizationId:z112.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 z113}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=z113.object({id:z113.string(),entryId:z113.string(),documentId:z113.string(),slug:z113.string(),locale:z113.string().optional(),createdAt:z113.string(),updatedAt:z113.string(),__fimo:z113.object({contentType:z113.string()})}).passthrough(),PaginatedEntriesDTOSchema2=z113.object({data:z113.array(EntryDTOSchema2),meta:z113.object({limit:z113.number(),offset:z113.number(),total:z113.number(),hasMore:z113.boolean()})}),EntryResponseSchema2=createResponseSchema2(EntryDTOSchema2),MAX_BULK_ENTRIES2=1e3,entryWhereScalarSchema2=z113.union([z113.string(),z113.number(),z113.boolean(),z113.null()]),entryWhereOperatorSchema2=z113.object({$eq:entryWhereScalarSchema2.optional(),$ne:entryWhereScalarSchema2.optional(),$gt:entryWhereScalarSchema2.optional(),$gte:entryWhereScalarSchema2.optional(),$lt:entryWhereScalarSchema2.optional(),$lte:entryWhereScalarSchema2.optional(),$in:z113.array(entryWhereScalarSchema2).optional(),$nin:z113.array(entryWhereScalarSchema2).optional(),$contains:z113.string().optional(),$startsWith:z113.string().optional(),$null:z113.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema2=z113.record(z113.string(),z113.union([entryWhereScalarSchema2,entryWhereOperatorSchema2])),EntryWhereSchema2=z113.record(z113.string(),z113.union([entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2])),EntryMutationBodySchema2=z113.object({data:z113.record(z113.string(),z113.unknown()),locale:z113.string().min(1).optional(),documentId:z113.uuid().optional()}),BulkCreateEntriesResponseSchema2=z113.object({data:z113.array(EntryDTOSchema2),meta:z113.object({created:z113.number().int().nonnegative()})}),BulkUpdateEntriesResponseSchema2=z113.object({data:z113.array(EntryDTOSchema2),meta:z113.object({updated:z113.number().int().nonnegative(),missing:z113.array(z113.string())})}),BulkDeleteEntriesResponseSchema2=z113.object({data:z113.array(EntryDTOSchema2),meta:z113.object({deleted:z113.number().int().nonnegative(),missing:z113.array(z113.string())})});__name(projectEntriesPage,"projectEntriesPage");entriesPageSchema=pageSchema(EntryDTOSchema2),typeNameSchema=z113.string().min(1).max(255),localeSchema=z113.string().min(1),populateSchema=z113.array(z113.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:z113.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,locale:localeSchema.optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:entriesPageSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,locale,limit,cursor,offset})=>({method:"GET",path:addQuery(tenantPath(projectId2,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:z113.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional(),populate:populateSchema,localeFallbacks:z113.boolean().optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,id,locale,populate,localeFallbacks})=>({method:"GET",path:addQuery(tenantPath(projectId2,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:z113.object({projectId:uuidSchema,branch:branchNameSchema,search:z113.string().min(1).optional(),locale:localeSchema.optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:entriesPageSchema,buildRequest:__name(({projectId:projectId2,branch,search,locale,limit,cursor,offset})=>({method:"GET",path:addQuery(tenantPath(projectId2,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:z113.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z113.string().min(1).max(255),data:entryDataSchema,locale:z113.string().min(1).optional(),documentId:z113.string().min(1).optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,data,locale,documentId})=>({method:"POST",path:tenantPath(projectId2,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:z113.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z113.string().min(1).max(255),id:uuidSchema,data:entryDataSchema,locale:z113.string().min(1).optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,id,data,locale})=>({method:"PUT",path:addQuery(tenantPath(projectId2,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:z113.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional(),fields:z113.record(z113.string(),z113.unknown())}).strict(),outputSchema:z113.unknown(),buildRequest:__name(({projectId:projectId2,branch,typeName,id,locale,fields})=>({method:"PUT",path:addQuery(tenantPath(projectId2,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale}),body:fields}),"buildRequest"),projectOutput:__name(body=>z113.object({data:z113.unknown()}).parse(body).data,"projectOutput")},"entries.querySql":{domain:"entries",summary:"Run a read-only SQL query against Branch content.",accessScope:"read",effect:"read",inputSchema:z113.object({projectId:uuidSchema,branch:branchNameSchema,sql:z113.string().min(1)}).strict(),outputSchema:z113.object({data:z113.array(z113.record(z113.string(),z113.unknown())),meta:z113.object({rowCount:z113.number().int().nonnegative(),truncated:z113.boolean()})}),buildRequest:__name(({projectId:projectId2,branch,sql})=>({method:"POST",path:tenantPath(projectId2,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:z113.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,id,locale})=>({method:"DELETE",path:addQuery(tenantPath(projectId2,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:z113.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,entries:z113.array(z113.unknown()).max(MAX_BULK_ENTRIES2)}).strict(),outputSchema:BulkCreateEntriesResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,typeName,entries:entries2})=>({method:"POST",path:tenantPath(projectId2,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:z113.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,selection:z113.union([z113.object({ids:z113.array(uuidSchema).min(1).max(MAX_BULK_ENTRIES2)}),z113.object({where:EntryWhereSchema2}),z113.object({updates:z113.array(z113.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:projectId2,branch,typeName,selection,body})=>({method:"POST",path:tenantPath(projectId2,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:z113.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,selection:z113.union([z113.object({ids:z113.array(uuidSchema).min(1).max(MAX_BULK_ENTRIES2)}),z113.object({where:EntryWhereSchema2})]),locale:localeSchema.optional()}).strict(),outputSchema:BulkDeleteEntriesResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,typeName,selection,locale})=>({method:"POST",path:tenantPath(projectId2,branch,`/entries/${encodeURIComponent(typeName)}/bulk-delete`),body:{...selection,locale}}),"buildRequest")}}}});import{z as z114}from"zod";var productionEnvironmentSchema,previewEnvironmentSchema,customEnvironmentSchema,environmentSchema,environmentWriteShape,environmentsOperations,init_environments=__esm({"../../packages/sdk/dist/operations/environments.js"(){"use strict";init_common2();productionEnvironmentSchema=z114.object({id:z114.literal("production"),projectId:uuidSchema,name:z114.string(),kind:z114.literal("production"),sourceBranch:z114.string().min(1),isPublished:z114.boolean(),url:z114.string().nullable()}),previewEnvironmentSchema=z114.object({id:z114.literal("preview"),projectId:uuidSchema,name:z114.string(),kind:z114.literal("preview"),matchedBranchCount:z114.number().int().nonnegative()}),customEnvironmentSchema=z114.object({id:uuidSchema,projectId:uuidSchema,name:z114.string().min(1).max(64),branchPatterns:z114.array(z114.string().min(1).max(255)).min(1),description:z114.string().max(255).nullable(),kind:z114.literal("custom"),matchedBranchCount:z114.number().int().nonnegative()}),environmentSchema=z114.discriminatedUnion("kind",[productionEnvironmentSchema,previewEnvironmentSchema,customEnvironmentSchema]),environmentWriteShape={name:z114.string().trim().min(1).max(64),branchPatterns:z114.array(z114.string().min(1).max(255)).min(1),description:z114.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:z114.object({projectId:uuidSchema}).strict(),outputSchema:z114.array(environmentSchema),buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/environments")}),"buildRequest"),projectOutput:__name(body=>z114.array(environmentSchema).parse(responseData(body)),"projectOutput")},"environments.create":{domain:"environments",summary:"Create a custom compatibility Environment for one site.",accessScope:"write",effect:"mutation",inputSchema:z114.object({projectId:uuidSchema,...environmentWriteShape}).strict(),outputSchema:environmentSchema,buildRequest:__name(({projectId:projectId2,...body})=>({method:"POST",path:managementProjectPath(projectId2,"/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:z114.object({projectId:uuidSchema,environmentId:z114.string().min(1),...environmentWriteShape}).strict(),outputSchema:environmentSchema,buildRequest:__name(({projectId:projectId2,environmentId,...body})=>({method:"PATCH",path:managementProjectPath(projectId2,`/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:z114.object({projectId:uuidSchema,environmentId:z114.string().min(1)}).strict(),outputSchema:z114.object({deletedId:uuidSchema}),buildRequest:__name(({projectId:projectId2,environmentId})=>({method:"DELETE",path:managementProjectPath(projectId2,`/environments/${encodeURIComponent(environmentId)}`),preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>z114.object({deletedId:uuidSchema}).parse(responseData(body)),"projectOutput")}}}});import{z as z115}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=z115.object({data:z115.object({path:z115.string(),content:z115.string(),totalLines:z115.number().int().nonnegative()}).passthrough()}),fileGlobOutputSchema=z115.object({data:z115.object({paths:z115.array(z115.string().min(1)).max(2e3),truncated:z115.boolean()})}),fileGrepOutputSchema=z115.object({data:z115.object({matches:z115.array(z115.object({path:z115.string().min(1),line:z115.number().int().positive(),text:z115.string()})).max(200),truncated:z115.boolean()})}),fileWriteInputSchema=z115.object({projectId:uuidSchema,sessionId:uuidSchema,path:z115.string().min(1).max(1024),content:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES2,`Content exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES2}-byte write limit.`),overwrite:z115.boolean().optional()}).strict(),fileEditInputSchema=z115.object({projectId:uuidSchema,sessionId:uuidSchema,path:z115.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:z115.boolean().optional()}).strict(),fileWriteOutputSchema=sessionEnvelopeSchema.extend({file:z115.object({path:z115.string(),created:z115.boolean(),tip:z115.string().min(1)}).passthrough()}),fileWriteManyInputSchema=z115.object({projectId:uuidSchema,sessionId:uuidSchema,files:z115.array(z115.object({path:z115.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(files2=>files2.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:z115.array(z115.object({path:z115.string(),created:z115.boolean()}).passthrough()),tip:z115.string().min(1)}),fileEditOutputSchema=sessionEnvelopeSchema.extend({file:z115.object({path:z115.string(),replacements:z115.number().int().nonnegative(),tip:z115.string().min(1)}).passthrough()}),fileDeleteOutputSchema=sessionEnvelopeSchema.extend({file:z115.object({path:z115.string(),deleted:z115.literal(!0),tip:z115.string().min(1)})}),fileSearchInputShape={projectId:uuidSchema,branch:branchNameSchema.optional(),sessionId:uuidSchema.optional()};__name(requireBranchOrSession,"requireBranchOrSession");fileReadInputSchema=z115.object({projectId:uuidSchema,branch:branchNameSchema.optional(),sessionId:uuidSchema.optional(),path:z115.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:projectId2,branch,sessionId,path:path52})=>({method:"GET",path:addQuery(projectFilesPath(projectId2,branch,sessionId,"/file"),{path:path52})}),"buildRequest")},"files.glob":{domain:"files",summary:"List bounded safe site file paths from a Branch or owned work session.",accessScope:"read",effect:"read",inputSchema:z115.object({...fileSearchInputShape,pattern:z115.string().min(1).max(300).optional(),limit:z115.number().int().min(1).max(2e3).optional()}).strict().superRefine(requireBranchOrSession),outputSchema:fileGlobOutputSchema,buildRequest:__name(({projectId:projectId2,branch,sessionId,pattern,limit})=>({method:"GET",path:addQuery(projectFilesPath(projectId2,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:z115.object({...fileSearchInputShape,pattern:z115.string().min(1).max(200),include:z115.string().min(1).max(300).optional(),caseInsensitive:z115.boolean().optional(),maxMatches:z115.number().int().min(1).max(200).optional()}).strict().superRefine(requireBranchOrSession),outputSchema:fileGrepOutputSchema,buildRequest:__name(({projectId:projectId2,branch,sessionId,pattern,include,caseInsensitive,maxMatches})=>({method:"GET",path:addQuery(projectFilesPath(projectId2,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:projectId2,sessionId,path:path52,content:content2,overwrite})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/files/write`),body:withoutUndefined({path:path52,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:projectId2,sessionId,files:files2})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/files/write-many`),body:{files:files2}}),"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:projectId2,sessionId,path:path52,oldString,newString,replaceAll})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/files/edit`),body:withoutUndefined({path:path52,oldString,newString,replaceAll})}),"buildRequest")},"files.delete":{domain:"files",summary:"Delete one safe site file in an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z115.object({projectId:uuidSchema,sessionId:uuidSchema,path:z115.string().min(1).max(1024)}).strict(),outputSchema:fileDeleteOutputSchema,buildRequest:__name(({projectId:projectId2,sessionId,path:path52})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/files/delete`),body:{path:path52}}),"buildRequest")}}}});import{z as z116}from"zod";function projectFormResponse(body){return formResponseSchema.parse(body)}function projectFormDetail(body){return formResponseSchema.parse(body).data}function projectFormList(body){return z116.object({data:z116.array(formSchema)}).parse(body).data}function projectFormSubmissionsPage(body,input){let page=z116.object({data:z116.array(formSubmissionSchema),total:z116.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=z116.object({type:z116.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),label:z116.string(),placeholder:z116.string().optional(),required:z116.boolean().optional(),defaultValue:z116.string().optional(),options:z116.array(z116.string()).optional(),validation:z116.object({minLength:z116.number().optional(),maxLength:z116.number().optional(),min:z116.number().optional(),max:z116.number().optional(),pattern:z116.string().optional(),maxFileSize:z116.number().optional(),accept:z116.array(z116.string()).optional()}).optional()}),FormContentSchema2=z116.object({name:z116.string().min(1).max(255),label:z116.string().min(1).max(255),fields:z116.record(z116.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=z116.object({id:uuidSchema,name:FormContentSchema2.shape.name,label:FormContentSchema2.shape.label,fields:FormContentSchema2.shape.fields,settings:z116.record(z116.string(),z116.unknown()).nullable().optional(),createdAt:z116.string(),updatedAt:z116.string()}).passthrough(),formSchema=rawFormSchema,formResponseSchema=z116.object({data:formSchema}),formSubmissionSchema=z116.object({id:uuidSchema,formId:uuidSchema,projectId:uuidSchema,branch:branchNameSchema,data:z116.record(z116.string(),z116.unknown()),submittedAt:z116.string()}),formSubmissionResponseSchema=z116.object({data:formSubmissionSchema}),formSubmissionsPageSchema=pageSchema(formSubmissionSchema),formSubmissionStatsResponseSchema=z116.object({data:z116.object({total:z116.number().int().nonnegative(),dailyCounts:z116.array(z116.object({date:z116.string(),count:z116.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:z116.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:z116.array(formSchema),buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:tenantPath(projectId2,branch,"/forms")}),"buildRequest"),projectOutput:projectFormList},"forms.get":{domain:"forms",summary:"Read one form definition from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z116.object({projectId:uuidSchema,branch:branchNameSchema,id:z116.string().min(1).max(255)}).strict(),outputSchema:formSchema,buildRequest:__name(({projectId:projectId2,branch,id})=>({method:"GET",path:tenantPath(projectId2,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:z116.object({projectId:uuidSchema,branch:branchNameSchema,...FormContentSchema2.shape}).strict(),outputSchema:formResponseSchema,buildRequest:__name(({projectId:projectId2,branch,name,label,fields})=>({method:"POST",path:tenantPath(projectId2,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:z116.object({projectId:uuidSchema,branch:branchNameSchema,id:z116.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 issue2 of update.error.issues)context.addIssue({...issue2,path:issue2.path})}),outputSchema:formResponseSchema,buildRequest:__name(({projectId:projectId2,branch,id,name,label,fields})=>({method:"PUT",path:tenantPath(projectId2,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:z116.object({projectId:uuidSchema,branch:branchNameSchema,id:z116.string().min(1).max(255)}).strict(),outputSchema:formResponseSchema,buildRequest:__name(({projectId:projectId2,branch,id})=>({method:"DELETE",path:tenantPath(projectId2,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:z116.object({projectId:uuidSchema,branch:branchNameSchema,id:z116.string().min(1).max(255),...paginationShape,searchQuery:z116.string().max(200).optional(),sortDirection:z116.enum(["asc","desc"]).optional()}).strict().superRefine(paginationRefinement),outputSchema:formSubmissionsPageSchema,buildRequest:__name(({projectId:projectId2,branch,id,limit,cursor,offset,searchQuery,sortDirection})=>({method:"GET",path:addQuery(tenantPath(projectId2,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:z116.object({projectId:uuidSchema,branch:branchNameSchema,id:z116.string().min(1).max(255),submissionId:z116.string().min(1).max(255)}).strict(),outputSchema:formSubmissionSchema,buildRequest:__name(({projectId:projectId2,branch,id,submissionId})=>({method:"GET",path:tenantPath(projectId2,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:z116.object({projectId:uuidSchema,branch:branchNameSchema,id:z116.string().min(1).max(255)}).strict(),outputSchema:formSubmissionStatsResponseSchema.shape.data,buildRequest:__name(({projectId:projectId2,branch,id})=>({method:"GET",path:tenantPath(projectId2,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:z116.object({projectId:uuidSchema,branch:branchNameSchema,id:z116.string().min(1).max(255),submissionId:z116.string().min(1).max(255)}).strict(),outputSchema:formSubmissionSchema,buildRequest:__name(({projectId:projectId2,branch,id,submissionId})=>({method:"DELETE",path:tenantPath(projectId2,branch,`/forms/${encodeURIComponent(id)}/submissions/${encodeURIComponent(submissionId)}`)}),"buildRequest"),projectOutput:__name(body=>formSubmissionResponseSchema.parse(body).data,"projectOutput")}}}});import{z as z117}from"zod";var estimateSchema,generationOperations,init_generation=__esm({"../../packages/sdk/dist/operations/generation.js"(){"use strict";init_common2();estimateSchema=z117.object({costUsd:z117.number(),credits:z117.number().optional(),billingMode:z117.enum(["fimo-credits","provider-account"]).optional(),confidence:z117.enum(["exact","estimated","metered"]),basis:z117.string()}).passthrough(),generationOperations={"generation.estimateModel":{domain:"generation",summary:"Estimate one generation request against an enabled provider model.",accessScope:"read",effect:"read",inputSchema:z117.object({projectId:uuidSchema,model:z117.string().min(1),options:z117.record(z117.string(),z117.unknown())}).strict(),outputSchema:estimateSchema,buildRequest:__name(({projectId:projectId2,model,options})=>({method:"POST",path:`/management/projects/${encodeURIComponent(projectId2)}/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:z117.object({projectId:uuidSchema,branch:branchNameSchema,task:z117.string().min(1),options:z117.record(z117.string(),z117.unknown())}).strict(),outputSchema:estimateSchema,buildRequest:__name(({projectId:projectId2,branch,task,options})=>({method:"POST",path:tenantPath(projectId2,branch,"/assets/generate/estimate"),body:{task,options}}),"buildRequest"),projectOutput:responseData}}}});import{z as z118}from"zod";var historyKindSchema,projectVersionSchema,projectVersionPageSchema,historySummarySchema,restoreResultSchema,historyOperations,init_history=__esm({"../../packages/sdk/dist/operations/history.js"(){"use strict";init_common2();historyKindSchema=z118.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),projectVersionSchema=z118.object({versionId:uuidSchema,commitHash:z118.string(),name:z118.string(),description:z118.string().nullable(),kind:historyKindSchema,createdAt:z118.iso.datetime(),expiresAt:z118.iso.datetime()}),projectVersionPageSchema=z118.object({items:z118.array(projectVersionSchema),nextCursor:z118.string().nullable()}),historySummarySchema=z118.object({usage:z118.object({versionCount:z118.number().int().nonnegative(),snapshotBytes:z118.number().int().nonnegative()}),retentionDays:z118.number().int().positive()}),restoreResultSchema=z118.object({durationMs:z118.number().nonnegative().optional(),warning:z118.string().optional()}),historyOperations={"history.list":{domain:"history",summary:"List restore points for one Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z118.object({projectId:uuidSchema,branch:branchNameSchema,limit:z118.number().int().min(1).max(100),cursor:paginationShape.cursor}).strict(),outputSchema:projectVersionPageSchema,buildRequest:__name(({projectId:projectId2,branch,limit,cursor})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,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:z118.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:historySummarySchema,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:managementBranchPath(projectId2,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:z118.object({projectId:uuidSchema,branch:branchNameSchema,versionId:uuidSchema}).strict(),outputSchema:projectVersionSchema,buildRequest:__name(({projectId:projectId2,branch,versionId})=>({method:"GET",path:managementBranchPath(projectId2,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:z118.object({projectId:uuidSchema,branch:branchNameSchema,name:z118.string().min(1),description:z118.string().optional()}).strict(),outputSchema:projectVersionSchema,buildRequest:__name(({projectId:projectId2,branch,name,description})=>({method:"POST",path:managementBranchPath(projectId2,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:z118.object({projectId:uuidSchema,branch:branchNameSchema,versionId:uuidSchema}).strict(),outputSchema:restoreResultSchema,buildRequest:__name(({projectId:projectId2,branch,versionId})=>({method:"POST",path:managementBranchPath(projectId2,branch,`/versions/${encodeURIComponent(versionId)}/restore`)}),"buildRequest"),projectOutput:__name(body=>restoreResultSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z119}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=z119.number().int().min(1).max(LOG_TAIL_MAX_LIMIT).optional(),publicationStateOutputSchema=z119.object({isPublished:z119.boolean(),publishedAt:z119.iso.datetime().nullable(),publishedVersion:z119.string().nullable()}),publicationOutputSchema=z119.object({id:uuidSchema,status:z119.enum(["queued","building","published","failed","canceled"]),label:z119.string().nullable(),notes:z119.string().nullable(),source:z119.object({branch:branchNameSchema,targetBranch:branchNameSchema,configVersion:z119.string().nullable(),framework:z119.string().nullable(),commit:z119.string().nullable()}),createdAt:z119.iso.datetime(),finishedAt:z119.iso.datetime().nullable(),url:z119.string().nullable(),failureCode:z119.string().nullable()}),publicationsPageOutputSchema=z119.object({items:z119.array(publicationOutputSchema),nextCursor:z119.string().nullable(),retention:z119.object({scope:z119.literal("publication_attempt_record"),records:z119.literal("project_lifetime")})}),publicationLogsOutputSchema=z119.object({status:z119.enum(["ok","unavailable"]),publicationId:uuidSchema,reason:z119.enum(["pending","no_deployment","provider_unavailable"]).nullable(),message:z119.string().nullable(),items:z119.array(z119.object({timestamp:z119.iso.datetime(),phase:z119.enum(["build","deploy"]),stream:z119.enum(["command","stdout","stderr","status","error"]),message:z119.string()}))}),sandboxLogsOutputSchema=z119.object({status:z119.enum(["ok","unavailable"]),reason:z119.enum(["no_sandbox","sandbox_expired","provider_unsupported"]).nullable(),message:z119.string().nullable(),items:z119.array(z119.object({id:z119.string(),timestamp:z119.iso.datetime().nullable(),source:z119.enum(["install","dev-server"]),phase:z119.string(),stream:z119.enum(["combined","stdout","stderr"]),message:z119.string()})),nextCursor:z119.string().nullable(),retention:z119.object({scope:z119.literal("sandbox_process_snapshot"),timestamps:z119.literal("process_start"),droppedOldest:z119.boolean(),phases:z119.array(z119.object({phase:z119.string(),source:z119.enum(["install","dev-server"]),status:z119.string(),startedAt:z119.iso.datetime().nullable(),exitCode:z119.number().int().nullable(),events:z119.number().int().nonnegative()}))}).nullable()}),previewLocationOutputSchema=z119.object({url:z119.string(),branch:branchNameSchema}),previewOpenOutputSchema=z119.object({url:z119.url(),expiresAt:z119.iso.datetime().nullable()}),publishOutputSchema=z119.object({success:z119.boolean(),message:z119.string().optional(),firstPublish:z119.boolean(),publicationId:z119.string().optional(),url:z119.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:z119.object({projectId:uuidSchema}).strict(),outputSchema:publicationStateOutputSchema,buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/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:z119.object({projectId:uuidSchema,limit:z119.number().int().min(1).max(100).optional(),cursor:paginationShape.cursor}).strict(),outputSchema:publicationsPageOutputSchema,buildRequest:__name(({projectId:projectId2,limit,cursor})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,"/publications"),{limit,before:cursor})}),"buildRequest"),projectOutput:projectPublicationsPage},"publications.get":{domain:"publications",summary:"Read one durable publication attempt.",accessScope:"read",effect:"read",inputSchema:z119.object({projectId:uuidSchema,publicationId:z119.string().min(1)}).strict(),outputSchema:publicationOutputSchema,buildRequest:__name(({projectId:projectId2,publicationId})=>({method:"GET",path:managementProjectPath(projectId2,`/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:z119.object({projectId:uuidSchema,label:z119.string().trim().min(1).max(120).optional(),notes:z119.string().max(2e4).optional()}).strict(),outputSchema:publishOutputSchema,buildRequest:__name(({projectId:projectId2,label,notes})=>({method:"POST",path:managementProjectPath(projectId2,"/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:z119.object({projectId:uuidSchema,publicationId:z119.string().min(1),limit:logTailLimitSchema}).strict(),outputSchema:publicationLogsOutputSchema,buildRequest:__name(({projectId:projectId2,publicationId,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,`/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:z119.object({projectId:uuidSchema,branch:branchNameSchema,limit:logTailLimitSchema,cursor:paginationShape.cursor}).strict(),outputSchema:sandboxLogsOutputSchema,buildRequest:__name(({projectId:projectId2,branch,limit,cursor})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,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:z119.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:previewLocationOutputSchema,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:managementBranchPath(projectId2,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:z119.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:previewOpenOutputSchema,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:managementBranchPath(projectId2,branch,"/sandbox")}),"buildRequest"),projectOutput:__name(body=>previewOpenOutputSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z120}from"zod";var integrationIdSchema,toolEffectSchema,integrationSchema,integrationToolSchema,integrationGuideSchema,integrationRunResultSchema,runInputShape,integrationsOperations,init_integrations=__esm({"../../packages/sdk/dist/operations/integrations.js"(){"use strict";init_common2();integrationIdSchema=z120.string().min(2).max(120).regex(/^[a-z0-9][a-z0-9_-]*$/),toolEffectSchema=z120.enum(["read","write","delete","financial"]),integrationSchema=z120.object({id:z120.string(),kind:z120.enum(["catalog","custom","builtIn"]),name:z120.string(),description:z120.string(),host:z120.string().nullable(),readOnly:z120.boolean(),installed:z120.boolean(),enabled:z120.boolean(),accountName:z120.string().nullable(),settings:z120.array(z120.object({key:z120.string(),label:z120.string(),description:z120.string().nullable(),required:z120.boolean()})),settingsValues:z120.record(z120.string(),z120.string()),missingSettings:z120.array(z120.string())}),integrationToolSchema=z120.object({integrationId:z120.string(),integrationName:z120.string(),key:z120.string(),name:z120.string(),description:z120.string(),effect:toolEffectSchema,input:z120.record(z120.string(),z120.unknown()).optional()}),integrationGuideSchema=z120.object({integrationId:z120.string(),name:z120.string(),description:z120.string(),content:z120.string()}),integrationRunResultSchema=z120.discriminatedUnion("status",[z120.object({status:z120.literal("ok"),output:z120.record(z120.string(),z120.unknown())}),z120.object({status:z120.literal("approval_required"),request:z120.string(),approveUrl:z120.string(),reason:z120.string(),integration:z120.object({id:z120.string(),name:z120.string()}),tool:z120.object({key:z120.string(),name:z120.string(),effect:toolEffectSchema}),input:z120.record(z120.string(),z120.unknown()),canAlwaysAllow:z120.boolean()}),z120.object({status:z120.literal("blocked"),reason:z120.string()})]),runInputShape={projectId:uuidSchema,integrationId:integrationIdSchema,tool:z120.string().min(1).max(120),input:z120.record(z120.string(),z120.unknown()).default({})},integrationsOperations={"integrations.list":{domain:"integrations",summary:"List the integrations this site can use, such as Google Search Console: whether each is on for the site, its connected account, and settings it still needs.",accessScope:"read",effect:"read",inputSchema:z120.object({projectId:uuidSchema}).strict(),outputSchema:z120.array(integrationSchema),buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/integrations/catalog")}),"buildRequest"),projectOutput:__name(body=>z120.array(integrationSchema).parse(responseData(body)),"projectOutput")},"integrations.tools":{domain:"integrations",summary:`Find the tools of the integrations on for this site by what you need, in plain words ("clicks by page", "sitemap"): the best matches, each with its key, the start of what it does and whether it reads or changes data. Pass a tool key to get that tool's input JSON schema, before you run it.`,accessScope:"read",effect:"read",inputSchema:z120.object({projectId:uuidSchema,search:z120.string().max(200).optional(),integrationId:integrationIdSchema.optional(),tool:z120.string().min(1).max(120).optional()}).strict(),outputSchema:z120.array(integrationToolSchema),buildRequest:__name(({projectId:projectId2,search,integrationId,tool})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,"/integrations/tools"),{search,integration:integrationId,tool})}),"buildRequest"),projectOutput:__name(body=>z120.array(integrationToolSchema).parse(responseData(body)),"projectOutput")},"integrations.guide":{domain:"integrations",summary:"Read an integration's guide before running its tools the first time: which tool answers which question, and how to read its numbers.",accessScope:"read",effect:"read",inputSchema:z120.object({projectId:uuidSchema,integrationId:integrationIdSchema}).strict(),outputSchema:integrationGuideSchema,buildRequest:__name(({projectId:projectId2,integrationId})=>({method:"GET",path:managementProjectPath(projectId2,`/integrations/${encodeURIComponent(integrationId)}/guide`)}),"buildRequest"),projectOutput:__name(body=>integrationGuideSchema.parse(responseData(body)),"projectOutput")},"integrations.run":{domain:"integrations",summary:"Run an integration tool that reads data, with the input its JSON schema describes. Tools that change data in the outside service run with integrations.write.",accessScope:"read",effect:"read",inputSchema:z120.object(runInputShape).strict(),outputSchema:integrationRunResultSchema,buildRequest:__name(({projectId:projectId2,integrationId,tool,input})=>({method:"POST",path:managementProjectPath(projectId2,`/integrations/${encodeURIComponent(integrationId)}/call`),body:{tool,input,readOnly:!0}}),"buildRequest"),projectOutput:__name(body=>integrationRunResultSchema.parse(responseData(body)),"projectOutput")},"integrations.write":{domain:"integrations",summary:"Run an integration tool that changes data in the outside service, such as submitting a sitemap to Google, only when the user asked for that change. Unless the site always allows the tool, the answer is approval_required with an approveUrl to give the user; once they allowed it in Fimo, call again with the exact same tool and input plus the approval code they paste back. A code works for one hour.",accessScope:"write",effect:"mutation",inputSchema:z120.object({...runInputShape,approval:z120.string().min(1).max(4e3).optional()}).strict(),outputSchema:integrationRunResultSchema,buildRequest:__name(({projectId:projectId2,integrationId,tool,input,approval})=>({method:"POST",path:managementProjectPath(projectId2,`/integrations/${encodeURIComponent(integrationId)}/call`),body:withoutUndefined({tool,input,approval})}),"buildRequest"),projectOutput:__name(body=>integrationRunResultSchema.parse(responseData(body)),"projectOutput")},"integrations.setEnabled":{domain:"integrations",summary:"Turn an integration on or off for this site. Turning one on may need its account connected first.",accessScope:"write",effect:"mutation",inputSchema:z120.object({projectId:uuidSchema,integrationId:integrationIdSchema,enabled:z120.boolean()}).strict(),outputSchema:z120.object({ok:z120.literal(!0)}),buildRequest:__name(({projectId:projectId2,integrationId,enabled})=>({method:"PUT",path:managementProjectPath(projectId2,`/integrations/${encodeURIComponent(integrationId)}`),body:{enabled}}),"buildRequest"),projectOutput:__name(()=>({ok:!0}),"projectOutput")},"integrations.updateSettings":{domain:"integrations",summary:"Change an integration's settings for this site. A choice must be one the connected account offers.",accessScope:"write",effect:"mutation",inputSchema:z120.object({projectId:uuidSchema,integrationId:integrationIdSchema,settings:z120.record(z120.string(),z120.string().max(500))}).strict(),outputSchema:z120.object({ok:z120.literal(!0)}),buildRequest:__name(({projectId:projectId2,integrationId,settings})=>({method:"PUT",path:managementProjectPath(projectId2,`/integrations/${encodeURIComponent(integrationId)}/settings`),body:{settings}}),"buildRequest"),projectOutput:__name(()=>({ok:!0}),"projectOutput")}}}});import{z as z121}from"zod";var knowledgeSchema,knowledgeOperations,init_knowledge=__esm({"../../packages/sdk/dist/operations/knowledge.js"(){"use strict";init_common2();knowledgeSchema=z121.object({content:z121.string(),updatedAt:z121.string().nullable(),updatedBy:z121.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:z121.object({projectId:uuidSchema}).strict(),outputSchema:knowledgeSchema,buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/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:z121.object({projectId:uuidSchema,content:z121.string()}).strict(),outputSchema:knowledgeSchema,buildRequest:__name(({projectId:projectId2,content:content2})=>({method:"PUT",path:managementProjectPath(projectId2,"/knowledge"),body:{content:content2}}),"buildRequest"),projectOutput:__name(body=>knowledgeSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z122}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=z122.object({key:z122.string(),value:z122.string().optional(),defaultValue:z122.string(),locale:z122.string()}),labelResponseSchema=createResponseSchema2(TranslationDTOSchema2),labelListOutputSchema=z122.object({data:z122.array(z122.union([TranslationDTOSchema2,z122.object({key:z122.string(),values:z122.record(z122.string(),z122.string())})]))}),labelUpsertOutputSchema=z122.object({created:z122.number().int().nonnegative(),updated:z122.number().int().nonnegative(),deleted:z122.number().int().nonnegative(),defaultLocale:z122.string(),locales:z122.array(z122.string())}),labelDeleteOutputSchema=z122.object({key:z122.string(),locale:z122.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:z122.object({projectId:uuidSchema,branch:branchNameSchema,locale:localeSchema.optional()}).strict(),outputSchema:labelListOutputSchema,buildRequest:__name(({projectId:projectId2,branch,locale})=>({method:"GET",path:addQuery(tenantPath(projectId2,branch,"/labels"),{locale})}),"buildRequest")},"labels.get":{domain:"labels",summary:"Read one localized label by locale and key.",accessScope:"read",effect:"read",inputSchema:z122.object({projectId:uuidSchema,branch:branchNameSchema,locale:localeSchema,key:z122.string().min(1).max(255)}).strict(),outputSchema:labelResponseSchema,buildRequest:__name(({projectId:projectId2,branch,locale,key})=>({method:"GET",path:tenantPath(projectId2,branch,`/labels/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`)}),"buildRequest")},"labels.set":{domain:"labels",summary:"Create or set one localized label.",accessScope:"write",effect:"mutation",inputSchema:z122.object({projectId:uuidSchema,branch:branchNameSchema,key:z122.string(),value:z122.string(),locale:z122.string().optional()}).strict(),outputSchema:TranslationDTOSchema2,buildRequest:__name(({projectId:projectId2,branch,key,value,locale})=>({method:"POST",path:tenantPath(projectId2,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:z122.object({projectId:uuidSchema,branch:branchNameSchema,records:z122.array(z122.object({key:z122.string(),value:z122.string(),locale:z122.string().optional()}))}).strict(),outputSchema:labelUpsertOutputSchema,buildRequest:__name(({projectId:projectId2,branch,records})=>({method:"POST",path:tenantPath(projectId2,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:z122.object({projectId:uuidSchema,branch:branchNameSchema,locale:z122.string().optional(),key:z122.string()}).strict(),outputSchema:labelDeleteOutputSchema,buildRequest:__name(({projectId:projectId2,branch,locale,key})=>({method:"DELETE",path:tenantPath(projectId2,branch,locale?`/labels/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`:`/labels/${encodeURIComponent(key)}`)}),"buildRequest"),projectOutput:__name(body=>responseValue(labelDeleteOutputSchema,body),"projectOutput")}}}});import{z as z123}from"zod";var projectLocaleCoverageSchema,ProjectLocaleStatsResponseSchema2,projectLocaleInputSchema,ProjectLocaleMutationResponseSchema2,RemoveProjectLocaleResponseSchema2,localesOperations,init_locales=__esm({"../../packages/sdk/dist/operations/locales.js"(){"use strict";init_common2();projectLocaleCoverageSchema=z123.object({translated:z123.number().int().nonnegative(),total:z123.number().int().nonnegative()}),ProjectLocaleStatsResponseSchema2=createResponseSchema2(z123.object({defaultLocale:z123.string(),locales:z123.array(z123.object({locale:z123.string(),isDefault:z123.boolean(),entries:projectLocaleCoverageSchema,labels:projectLocaleCoverageSchema}))})),projectLocaleInputSchema=z123.string().min(1).max(40),ProjectLocaleMutationResponseSchema2=createResponseSchema2(z123.object({locale:z123.string()})),RemoveProjectLocaleResponseSchema2=createResponseSchema2(z123.object({locale:z123.string(),entriesDeleted:z123.number().int().nonnegative(),labelsDeleted:z123.number().int().nonnegative()})),localesOperations={"locales.list":{domain:"locales",summary:"List configured locales and content coverage on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z123.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:ProjectLocaleStatsResponseSchema2,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:managementBranchPath(projectId2,branch,"/locales/stats")}),"buildRequest")},"locales.add":{domain:"locales",summary:"Add a configured locale to a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z123.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:ProjectLocaleMutationResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,locale})=>({method:"POST",path:managementBranchPath(projectId2,branch,"/locales"),body:{locale}}),"buildRequest")},"locales.setDefault":{domain:"locales",summary:"Set the default configured locale on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z123.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:ProjectLocaleMutationResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,locale})=>({method:"PUT",path:managementBranchPath(projectId2,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:z123.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:RemoveProjectLocaleResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,locale})=>({method:"DELETE",path:managementBranchPath(projectId2,branch,`/locales/${encodeURIComponent(locale)}`)}),"buildRequest")}}}});import{z as z124}from"zod";var organizationSchema,organizationMemberSchema,organizationInvitationSchema,referralSummarySchema,organizationsOperations,init_organizations=__esm({"../../packages/sdk/dist/operations/organizations.js"(){"use strict";init_common2();organizationSchema=z124.object({id:z124.string().min(1),name:z124.string(),slug:z124.string()}),organizationMemberSchema=z124.object({id:z124.string().min(1),role:z124.string(),createdAt:z124.string().optional(),user:z124.object({id:z124.string().min(1),name:z124.string().nullable().optional(),email:z124.string().nullable().optional()}).optional()}),organizationInvitationSchema=z124.object({id:z124.string().min(1),email:z124.email(),role:z124.string(),organizationId:z124.string().min(1),inviterId:z124.string().min(1),status:z124.string(),expiresAt:z124.string(),createdAt:z124.string()}).passthrough(),referralSummarySchema=z124.object({counts:z124.object({signed_up:z124.number().int(),activated:z124.number().int()}),credits:z124.object({total:z124.number().int(),earned:z124.number().int().optional()})}),organizationsOperations={"organizations.list":{domain:"organizations",summary:"List organizations the authenticated user belongs to.",accessScope:"read",effect:"read",inputSchema:z124.object({}).strict(),outputSchema:createResponseSchema2(z124.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:z124.object({organizationId:z124.string().min(1)}).strict(),outputSchema:z124.array(organizationMemberSchema),buildRequest:__name(({organizationId})=>({method:"GET",path:`/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`}),"buildRequest"),projectOutput:__name(body=>z124.object({members:z124.array(organizationMemberSchema)}).nullable().parse(body)?.members??[],"projectOutput")},"organizations.invite":{domain:"organizations",summary:"Invite a user to an organization.",accessScope:"write",effect:"mutation",inputSchema:z124.object({organizationId:z124.string().min(1),email:z124.email(),role:z124.enum(["owner","admin","member"]),resend:z124.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:z124.object({userId:z124.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 z125}from"zod";var projectSchema,projectResponseSchema,transferResultSchema,projectsOperations,init_projects=__esm({"../../packages/sdk/dist/operations/projects.js"(){"use strict";init_common2();projectSchema=z125.object({id:uuidSchema,name:z125.string(),displayName:z125.string().nullable(),organizationId:z125.string().nullable(),defaultBranch:branchNameSchema.optional(),productionSourceBranch:branchNameSchema.optional(),status:z125.string().optional(),appUrl:z125.string().nullable().optional()}).passthrough(),projectResponseSchema=z125.object({data:projectSchema}),transferResultSchema=z125.object({projectId:z125.string(),sourceOrganizationId:z125.string(),targetOrganizationId:z125.string(),movedThreads:z125.number().int().nonnegative(),revokedInvites:z125.number().int().nonnegative(),revokedGrants:z125.number().int().nonnegative(),preservedGrants:z125.number().int().nonnegative(),warnings:z125.array(z125.string())}),projectsOperations={"projects.list":{domain:"projects",summary:"List the Fimo sites the authenticated user can access.",accessScope:"read",effect:"read",inputSchema:z125.object({organizationId:z125.string().min(1).optional()}).strict(),outputSchema:z125.object({data:z125.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:z125.object({projectId:uuidSchema}).strict(),outputSchema:projectResponseSchema,buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"")}),"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:z125.object({organizationId:z125.string().min(1),displayName:z125.string().min(1).optional(),origin:z125.enum(["scratch","migration"]).optional(),starter:z125.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:z125.object({projectId:uuidSchema,targetOrganizationId:z125.string().min(1)}).strict(),outputSchema:transferResultSchema,buildRequest:__name(({projectId:projectId2,targetOrganizationId})=>({method:"POST",path:managementProjectPath(projectId2,"/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:z125.object({projectId:uuidSchema,email:z125.email(),role:z125.enum(["full","edit","comment","view"])}).strict(),outputSchema:z125.object({id:z125.string().min(1)}),buildRequest:__name(({projectId:projectId2,email,role})=>({method:"POST",path:managementProjectPath(projectId2,"/invites"),body:{email,roleKey:role}}),"buildRequest"),projectOutput:__name(body=>({id:z125.object({id:z125.string().min(1)}).parse(responseData(body)).id}),"projectOutput")},"projects.delete":{domain:"projects",summary:"Permanently delete a Fimo site.",accessScope:"write",effect:"mutation",inputSchema:z125.object({projectId:uuidSchema}).strict(),outputSchema:z125.unknown(),buildRequest:__name(({projectId:projectId2})=>({method:"DELETE",path:managementProjectPath(projectId2,""),body:{}}),"buildRequest")}}}});import{z as z126}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=z126.iso.datetime(),scheduleStatusSchema=z126.enum(["ok","failed"]),runStatusSchema=z126.enum(["queued","running","succeeded","failed","skipped"]),scheduleSchema=z126.object({id:uuidSchema,createdAt:dateSchema,updatedAt:dateSchema,projectId:uuidSchema,branch:z126.string().min(1),name:z126.string().min(1),cron:z126.string().min(1),command:z126.string().min(1),secretKeys:z126.array(z126.string().min(1)),enabled:z126.boolean(),lastRunAt:dateSchema.nullable(),lastStatus:scheduleStatusSchema.nullable(),lastError:z126.string().nullable(),overPolicyReasons:z126.array(z126.string()).optional()}).passthrough(),usageSchema=z126.object({runCount:z126.number().int().nonnegative(),runsWithOutput:z126.number().int().nonnegative()}),policySchema=z126.object({maxRuns:z126.number().int().positive(),retentionDays:z126.number().int().positive().nullable(),outputRetentionDays:z126.number().int().positive(),maxOutputBytes:z126.number().int().positive()}).passthrough(),planSchema=z126.object({code:z126.enum(["Free","PAYG","Starter","Premium","Pro"]),source:z126.enum(["cached_subscription","free_fallback"]),activeSchedules:z126.object({used:z126.number().int().nonnegative(),limit:z126.number().int().positive()}),minCadenceMinutes:z126.number().int().positive(),maxRunMs:z126.number().int().positive(),concurrency:z126.object({used:z126.number().int().nonnegative(),limit:z126.number().int().positive()}),compute:z126.object({settledMs:z126.number().int().nonnegative(),activeMs:z126.number().int().nonnegative(),reservedMs:z126.number().int().nonnegative().optional(),includedMs:z126.number().int().positive(),remainingMs:z126.number().int().nonnegative(),resetsAt:dateSchema}),state:z126.enum(["ok","near_limit","exhausted","over_policy"]),overPolicyReasons:z126.array(z126.string())}).passthrough(),runSchema=z126.object({id:uuidSchema,scheduleId:uuidSchema,projectId:uuidSchema,branch:z126.string().min(1),scheduleName:z126.string().min(1),command:z126.string().min(1),status:runStatusSchema,trigger:z126.enum(["cron","ui","cli"]),triggeredBy:z126.object({id:z126.string().min(1),name:z126.string().min(1)}).nullable(),queuedAt:dateSchema,startedAt:dateSchema.nullable(),finishedAt:dateSchema.nullable(),exitCode:z126.number().int().nullable(),errorCode:z126.string().nullable(),error:z126.string().nullable(),outputBytes:z126.number().int().nonnegative(),outputTruncated:z126.boolean(),outputExpiresAt:dateSchema.nullable(),metadataExpiresAt:dateSchema.nullable()}).passthrough(),runDetailSchema=runSchema.extend({output:z126.string().nullable(),secretSnapshot:z126.object({state:z126.enum(["pending","resolved","failed"]),capturedAt:dateSchema.nullable(),items:z126.array(z126.object({key:z126.string().min(1),updatedAt:dateSchema.nullable(),resolution:z126.enum(["resolved","missing","deleted","recreated","rotated"])}))})}),overviewSchema=z126.object({items:z126.array(scheduleSchema),usage:usageSchema,policy:policySchema,plan:planSchema}),detailSchema=z126.object({schedule:scheduleSchema,usage:usageSchema,policy:policySchema,plan:planSchema}).passthrough(),runsPageSchema=z126.object({items:z126.array(runSchema),nextCursor:z126.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:z126.string().min(1).max(120),cron:z126.string().min(1).max(120),command:z126.string().min(1).max(500),secretKeys:z126.array(z126.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:z126.object({...scheduleContextShape}).strict(),outputSchema:z126.array(scheduleSchema),buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",context:{branch},path:managementProjectPath(projectId2,"/schedules")}),"buildRequest"),projectOutput:__name(body=>z126.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:z126.object({...scheduleContextShape}).strict(),outputSchema:overviewSchema,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",context:{branch},path:managementProjectPath(projectId2,"/schedules/overview")}),"buildRequest"),projectOutput:projectOverview},"schedules.get":{domain:"schedules",summary:"Read one schedule with usage and plan limits.",accessScope:"read",effect:"read",inputSchema:z126.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:detailSchema,buildRequest:__name(({projectId:projectId2,branch,scheduleId})=>({method:"GET",context:{branch},path:managementProjectPath(projectId2,`/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:z126.object({...scheduleContextShape,...scheduleWriteShape,enabled:z126.boolean().optional()}).strict(),outputSchema:scheduleSchema,buildRequest:__name(({projectId:projectId2,branch,...body})=>({method:"POST",context:{branch},path:managementProjectPath(projectId2,"/schedules"),body}),"buildRequest"),projectOutput:projectSchedule},"schedules.update":{domain:"schedules",summary:"Update a recurring command schedule.",accessScope:"agents",effect:"mutation",inputSchema:z126.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:projectId2,branch,scheduleId,...update})=>({method:"PATCH",context:{branch},path:managementProjectPath(projectId2,`/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:z126.object({...scheduleContextShape,scheduleId:uuidSchema,enabled:z126.boolean()}).strict(),outputSchema:scheduleSchema,buildRequest:__name(({projectId:projectId2,branch,scheduleId,enabled})=>({method:"POST",context:{branch},path:managementProjectPath(projectId2,`/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:z126.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:runSchema,buildRequest:__name(({projectId:projectId2,branch,scheduleId})=>({method:"POST",context:{branch},path:managementProjectPath(projectId2,`/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:z126.object({...scheduleContextShape,scheduleId:uuidSchema,limit:z126.number().int().min(1).max(100).optional(),cursor:paginationShape.cursor,status:runStatusSchema.optional()}).strict(),outputSchema:runsPageSchema,buildRequest:__name(({projectId:projectId2,branch,scheduleId,limit,cursor,status})=>({method:"GET",context:{branch},path:addQuery(managementProjectPath(projectId2,`/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:z126.object({...scheduleContextShape,runId:uuidSchema}).strict(),outputSchema:runDetailSchema,buildRequest:__name(({projectId:projectId2,branch,runId})=>({method:"GET",context:{branch},path:managementProjectPath(projectId2,`/schedules/runs/${encodeURIComponent(runId)}`)}),"buildRequest"),projectOutput:projectRunDetail},"schedules.delete":{domain:"schedules",summary:"Delete one site schedule.",accessScope:"agents",effect:"mutation",inputSchema:z126.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:z126.object({ok:z126.literal(!0)}),buildRequest:__name(({projectId:projectId2,branch,scheduleId})=>({method:"DELETE",context:{branch},path:managementProjectPath(projectId2,`/schedules/${encodeURIComponent(scheduleId)}`)}),"buildRequest"),projectOutput:__name(body=>z126.object({ok:z126.literal(!0)}).parse(responseData(body)),"projectOutput")}}}});import{z as z127}from"zod";function projectSchemaDefinition(body){return z127.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=z127.object({id:z127.string(),name:z127.string(),label:z127.string(),isSingleton:z127.boolean(),slugUnique:z127.boolean(),i18n:z127.record(z127.string(),z127.unknown()),groups:z127.array(z127.record(z127.string(),z127.unknown())),fields:z127.record(z127.string(),z127.unknown()),createdAt:z127.string(),updatedAt:z127.string()}).passthrough(),schemaListOutputSchema=z127.object({contentTypes:z127.array(contentTypeSchema)}),schemaMutationOutputSchema=sessionEnvelopeSchema.extend({schema:z127.object({typeName:z127.string().min(1).max(255),generatedPaths:z127.array(z127.string().min(1)).max(1e3),tip:z127.string().min(1)})}),schemaDefinitionInputSchema=z127.record(z127.string(),z127.unknown());__name(projectSchemaDefinition,"projectSchemaDefinition");schemasOperations={"schemas.list":{domain:"schemas",summary:"List content schemas on a durable Branch.",accessScope:"read",effect:"read",inputSchema:z127.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:schemaListOutputSchema,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:tenantPath(projectId2,branch,"/schema")}),"buildRequest")},"schemas.get":{domain:"schemas",summary:"Get one complete content schema from a durable Branch.",accessScope:"read",effect:"read",inputSchema:z127.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z127.string().min(1).max(255)}).strict(),outputSchema:contentTypeSchema,buildRequest:__name(({projectId:projectId2,branch,typeName})=>({method:"GET",path:tenantPath(projectId2,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:z127.object({projectId:uuidSchema,branch:branchNameSchema,contentTypes:z127.array(schemaDefinitionInputSchema).min(1).max(100),operations:z127.array(z127.record(z127.string(),z127.unknown())).optional()}).strict(),outputSchema:z127.array(z127.unknown()),buildRequest:__name(({projectId:projectId2,branch,contentTypes,operations})=>({method:"POST",path:tenantPath(projectId2,branch,"/schema/batch"),body:withoutUndefined({contentTypes,operations:operations?.length?operations:void 0})}),"buildRequest"),projectOutput:__name(body=>z127.object({data:z127.array(z127.unknown())}).parse(body).data,"projectOutput")},"schemas.deleteFromBranch":{domain:"schemas",summary:"Delete a content schema directly from a Fimo Branch.",accessScope:"code",effect:"mutation",inputSchema:z127.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z127.string().min(1).max(255)}).strict(),outputSchema:z127.unknown(),buildRequest:__name(({projectId:projectId2,branch,typeName})=>({method:"DELETE",path:tenantPath(projectId2,branch,`/schema/types/${encodeURIComponent(typeName)}`)}),"buildRequest"),projectOutput:__name(body=>z127.object({data:z127.unknown()}).parse(body).data,"projectOutput")},"schemas.create":{domain:"schemas",summary:"Create a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z127.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z127.string().min(1).max(255),definition:schemaDefinitionInputSchema}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId:projectId2,sessionId,typeName,definition})=>({method:"POST",path:managementProjectPath(projectId2,`/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:z127.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z127.string().min(1).max(255),definition:schemaDefinitionInputSchema,renameFrom:z127.string().max(255).optional()}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId:projectId2,sessionId,typeName,definition,renameFrom})=>({method:"POST",path:managementProjectPath(projectId2,`/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:z127.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z127.string().min(1).max(255)}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId:projectId2,sessionId,typeName})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/schema`),body:{kind:"delete",typeName}}),"buildRequest")}}}});import{z as z128}from"zod";var environmentSchema2,secretKindSchema,projectSecretSchema,secretWriteInputSchema,secretsOperations,init_secrets=__esm({"../../packages/sdk/dist/operations/secrets.js"(){"use strict";init_common2();environmentSchema2=z128.union([z128.literal("production"),z128.literal("preview"),uuidSchema]),secretKindSchema=z128.enum(["variable","secret"]),projectSecretSchema=z128.object({id:z128.string().min(1),projectId:z128.string().min(1),key:z128.string().min(1),kind:secretKindSchema,exposure:z128.enum(["public","private"]),environment:environmentSchema2,value:z128.string().optional(),maskedValue:z128.string().optional(),createdAt:z128.string(),updatedAt:z128.string()}),secretWriteInputSchema=z128.object({projectId:uuidSchema,key:z128.string().min(1).max(255),kind:secretKindSchema,value:z128.string(),environment:environmentSchema2}),secretsOperations={"secrets.list":{domain:"secrets",summary:"List public variables or masked secrets for one site Environment.",accessScope:"read",effect:"read",inputSchema:z128.object({projectId:uuidSchema,environment:environmentSchema2,kind:secretKindSchema.optional()}).strict(),outputSchema:z128.array(projectSecretSchema),buildRequest:__name(({projectId:projectId2,environment,kind})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,"/secrets"),{environment,kind})}),"buildRequest"),projectOutput:__name(body=>z128.array(projectSecretSchema).parse(responseData(body)),"projectOutput")},"secrets.create":{domain:"secrets",summary:"Create a public variable, private variable, or secret for one site Environment.",accessScope:"write",effect:"mutation",inputSchema:secretWriteInputSchema.extend({exposure:z128.enum(["public","private"]).optional()}).strict(),outputSchema:projectSecretSchema,buildRequest:__name(({projectId:projectId2,...body})=>({method:"POST",path:managementProjectPath(projectId2,"/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:projectId2,key,...body})=>({method:"PATCH",path:managementProjectPath(projectId2,`/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:z128.object({projectId:uuidSchema,key:z128.string().min(1),kind:secretKindSchema,environment:environmentSchema2}).strict(),outputSchema:z128.unknown(),buildRequest:__name(({projectId:projectId2,key,kind,environment})=>({method:"DELETE",path:addQuery(managementProjectPath(projectId2,`/secrets/${encodeURIComponent(key)}`),{kind,environment})}),"buildRequest")},"environments.resolve":{domain:"environments",summary:"Resolve which compatibility Environment receives one site Branch.",accessScope:"read",effect:"read",inputSchema:z128.object({projectId:uuidSchema,branch:z128.string().min(1)}).strict(),outputSchema:z128.object({branch:z128.string().min(1),environment:environmentSchema2}),buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,"/branches"),{includeAgentEnvs:!0})}),"buildRequest"),projectOutput:__name((body,input)=>{let branches=z128.array(z128.object({branch:z128.string().optional(),env:z128.string().optional(),parentBranch:z128.string().nullable().optional(),parentEnv:z128.string().nullable().optional(),resolvedEnvironment:z128.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 z129}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,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=z129.object({status:z129.literal("passed")}).passthrough(),sessionConflictSummarySchema=z129.object({surface:surfaceNameSchema,key:z129.string().min(1),kind:z129.string().optional(),description:z129.string(),path:z129.string().optional()}).passthrough(),surfaceDeltaItemSchema=z129.object({verb:z129.enum(["added","removed","changed","conflict"]),key:z129.string(),detail:z129.string().optional(),origin:z129.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z129.record(z129.string(),z129.unknown()).optional()}).passthrough(),perSurfaceDeltaSchema=z129.object({surface:surfaceNameSchema,status:z129.enum(["ok","timed_out","failed","unchanged"]),durationMs:z129.number().int().nonnegative().optional(),changedCount:z129.number().int().nonnegative(),conflictCount:z129.number().int().nonnegative(),items:z129.array(surfaceDeltaItemSchema).max(1e3).optional(),truncated:z129.boolean().optional(),error:z129.string().optional()}).passthrough(),sessionChangesSchema=z129.object({fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),generatedAt:z129.iso.datetime(),surfaces:z129.array(perSurfaceDeltaSchema),crossSurface:z129.array(crossSurfaceFindingSchema).optional(),fingerprint:z129.string()}).passthrough(),projectScriptStatusSchema=z129.enum(["passed","failed","unavailable"]),sessionOperationResultSchema=z129.discriminatedUnion("operation",[z129.object({operation:z129.literal("dependencies_install"),repairedInstallPolicy:z129.boolean(),tip:z129.string()}),z129.object({operation:z129.literal("schemas_sync"),tip:z129.string()}),z129.object({operation:z129.literal("typecheck"),status:projectScriptStatusSchema,output:z129.string()}),z129.object({operation:z129.literal("lint"),status:projectScriptStatusSchema,output:z129.string()})]),conflictSchema2=z129.object({surface:surfaceNameSchema,key:z129.string(),kind:z129.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"]).optional(),description:z129.string(),parentValue:z129.unknown().optional(),childValue:z129.unknown().optional(),conflictingFields:z129.array(z129.string()).optional(),code:z129.object({path:z129.string(),unresolvable:z129.boolean().optional(),reason:z129.string().optional(),targetCommits:z129.array(z129.object({sha:z129.string(),subject:z129.string(),body:z129.string().optional(),author:z129.string(),date:z129.string()})).optional()}).optional()}).passthrough(),codeConflictBlobSchema2=z129.object({oid:z129.string().optional(),content:z129.string().optional(),truncated:z129.boolean(),binary:z129.boolean()}),codeConflictDetailSchema=z129.object({path:z129.string(),base:codeConflictBlobSchema2,ours:codeConflictBlobSchema2,theirs:codeConflictBlobSchema2,result:codeConflictBlobSchema2,sourceTipSha:z129.string(),targetTipSha:z129.string(),mergeBaseSha:z129.string().optional()}),resolutionChoiceSchema=z129.enum(["parent","child","pick"]),conflictResolutionSchema2=z129.object({surface:surfaceNameSchema,key:z129.string().min(1),choice:resolutionChoiceSchema,pickedValue:z129.unknown().optional(),fieldPicks:z129.array(z129.object({field:z129.string().min(1),choice:resolutionChoiceSchema,pickedValue:z129.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"]})})}),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:z129.object({projectId:uuidSchema,targetBranch:branchNameSchema.optional(),name:z129.string().trim().min(1).max(120).optional(),goal:z129.string().trim().min(1).max(500).optional()}).strict(),outputSchema:z129.object({session:sessionEnvelopeSchema,adopted:z129.boolean()}),buildRequest:__name(({projectId:projectId2,targetBranch,name,goal})=>({method:"POST",path:managementProjectPath(projectId2,"/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:z129.object({projectId:uuidSchema,sessionId:uuidSchema}).strict(),outputSchema:sessionEnvelopeSchema,buildRequest:__name(({projectId:projectId2,sessionId})=>({method:"GET",path:managementProjectPath(projectId2,`/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:z129.object({projectId:uuidSchema,status:sessionStatusSchema.optional(),scope:z129.enum(["mine","project"]).optional(),cursor:paginationShape.cursor,limit:z129.number().int().min(1).max(100).optional()}).strict(),outputSchema:z129.object({items:z129.array(sessionEnvelopeSchema),nextCursor:z129.string().nullable()}),buildRequest:__name(({projectId:projectId2,status,cursor,limit,scope:scope2})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,"/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:z129.object({projectId:uuidSchema,sessionId:uuidSchema,detail:z129.boolean().optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({changes:sessionChangesSchema}),buildRequest:__name(({projectId:projectId2,sessionId,detail})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,`/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:z129.object({projectId:uuidSchema,sessionId:uuidSchema,summary:z129.string().trim().min(1).max(240),targetBranch:branchNameSchema.optional()}).strict(),outputSchema:z129.object({requested:z129.literal(!0),alreadyRequested:z129.boolean(),reviewId:uuidSchema,reviewUrl:z129.url(),status:z129.literal("pending"),sessionId:uuidSchema,branch:branchNameSchema,targetBranch:branchNameSchema,revision:z129.string().min(1),savedRevision:z129.string().min(1),fingerprint:z129.string().min(1),visibility:z129.literal("user-visible"),retention:z129.literal("durable"),expiresAt:z129.null(),merged:z129.literal(!1),published:z129.literal(!1),links:z129.object({preview:z129.url(),changes:z129.url(),conversation:z129.url().nullable()})}),buildRequest:__name(({projectId:projectId2,sessionId,summary:summary2,targetBranch})=>({method:"POST",path:managementProjectPath(projectId2,`/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:z129.object({projectId:uuidSchema,sessionId:uuidSchema,additionalDays:z129.number().int().min(1).max(30)}).strict(),outputSchema:sessionEnvelopeSchema.extend({retention:z129.literal("temporary"),visibility:z129.enum(["internal","user-visible"]),expiresAt:z129.iso.datetime()}),buildRequest:__name(({projectId:projectId2,sessionId,additionalDays})=>({method:"POST",path:managementProjectPath(projectId2,`/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:z129.object({projectId:uuidSchema,sessionId:uuidSchema}).strict(),outputSchema:sessionEnvelopeSchema.extend({validation:sessionValidationSchema}),buildRequest:__name(({projectId:projectId2,sessionId})=>({method:"POST",path:managementProjectPath(projectId2,`/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:z129.object({projectId:uuidSchema,sessionId:uuidSchema,operation:z129.string().min(1).max(100),args:z129.record(z129.string(),z129.unknown()).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({operation:sessionOperationResultSchema}),buildRequest:__name(({projectId:projectId2,sessionId,operation,args})=>({method:"POST",path:managementProjectPath(projectId2,`/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:z129.object({projectId:uuidSchema,sessionId:uuidSchema,action:z129.enum(["merge","discard"]),message:z129.string().max(1e3).optional(),description:z129.string().max(2e3).optional().describe("Why the work changed. Becomes the body of the merge commit.")}).strict(),outputSchema:sessionEnvelopeSchema.extend({outcome:z129.enum(["merged","no_changes","discarded","conflicts","failed"]),closed:z129.boolean(),mergeId:uuidSchema.optional(),conflictCount:z129.number().int().nonnegative().optional(),conflicts:z129.array(sessionConflictSummarySchema).optional(),parentAdvanced:z129.boolean().optional(),code:z129.string().optional(),summary:z129.string().nullable().optional()}),buildRequest:__name(({projectId:projectId2,sessionId,action,message,description})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/close`),body:withoutUndefined({action,message,description})}),"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:z129.object({projectId:uuidSchema,sessionId:uuidSchema,mergeId:uuidSchema.optional(),cursor:paginationShape.cursor,limit:z129.number().int().min(1).max(100).optional(),codePath:z129.string().min(1).max(1024).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({merge:z129.object({mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,status:z129.enum(["in_progress","complete","failed","rolled_back","conflicts"]),conflictCount:z129.number().int().nonnegative(),error:z129.string().nullable()}),conflicts:z129.array(conflictSchema2).max(100),nextCursor:z129.string().nullable(),codeDetail:codeConflictDetailSchema.nullable().optional()}),buildRequest:__name(({projectId:projectId2,sessionId,mergeId,cursor,limit,codePath})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,`/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:z129.object({projectId:uuidSchema,sessionId:uuidSchema,mergeId:uuidSchema,resolutions:z129.array(conflictResolutionSchema2).min(1).max(500)}).strict(),outputSchema:sessionEnvelopeSchema.extend({outcome:z129.literal("resolving"),mergeId:uuidSchema,supersededMergeId:uuidSchema,strategy:resolvedMergeStrategySchema,acceptedAt:z129.iso.datetime()}),buildRequest:__name(({projectId:projectId2,sessionId,mergeId,resolutions})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/resolve`),body:{mergeId,resolutions:backendConflictResolutions(resolutions)}}),"buildRequest")}}}});import{z as z130}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:z130.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,locale:localeSchema.optional(),populate:populateSchema}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,locale,populate})=>({method:"GET",path:addQuery(tenantPath(projectId2,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:z130.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,data:entryDataSchema,locale:localeSchema.optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,data,locale})=>({method:"PUT",path:addQuery(tenantPath(projectId2,branch,`/documents/${encodeURIComponent(typeName)}`),{locale}),body:{data}}),"buildRequest")}}}});import{z as z131}from"zod";var supportReportInputSchema,supportReportResultSchema,supportOperations,init_support2=__esm({"../../packages/sdk/dist/operations/support.js"(){"use strict";init_common2();supportReportInputSchema=z131.object({message:z131.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=z131.object({id:uuidSchema,deliveryStatus:z131.enum(["pending","delivered","failed"]),message:z131.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:z131.object({data:supportReportResultSchema}),buildRequest:__name(({message,projectId:projectId2,branch})=>({method:"POST",path:"/support/issues/agent",body:withoutUndefined({message,projectId:projectId2,branch})}),"buildRequest")}}}});import{z as z132}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=z132.record(z132.string(),z132.unknown()),deliveryStatusSchema=z132.enum(["pending","delivering","retrying","succeeded","failed"]),webhookSchema=z132.object({id:uuidSchema,projectId:uuidSchema,name:z132.string(),eventType:z132.string().min(1),enabled:z132.boolean(),destination:z132.object({host:z132.string(),maskedUrl:z132.string(),kind:z132.string()}),filter:jsonObjectSchema,headers:z132.array(jsonObjectSchema),bodyTemplate:z132.unknown().nullable(),signingEnabled:z132.boolean(),lastDeliveryStatus:deliveryStatusSchema.nullable()}).passthrough(),deliverySchema=z132.object({id:uuidSchema,webhookId:uuidSchema,projectId:uuidSchema,eventType:z132.string().min(1),status:deliveryStatusSchema,attemptCount:z132.number().int().nonnegative(),responseStatus:z132.number().int().nullable(),createdAt:z132.iso.datetime()}).passthrough(),attemptSchema=z132.object({id:uuidSchema,deliveryId:uuidSchema,attempt:z132.number().int().positive(),status:z132.enum(["delivering","succeeded","failed"]),createdAt:z132.iso.datetime()}).passthrough(),deliveriesPageSchema=z132.object({items:z132.array(deliverySchema),pagination:z132.object({page:z132.number().int().positive(),limit:z132.number().int().positive(),total:z132.number().int().nonnegative(),totalPages:z132.number().int().positive(),hasMore:z132.boolean()}),stats:z132.object({total:z132.number().int().nonnegative(),succeeded:z132.number().int().nonnegative(),failed:z132.number().int().nonnegative()})}),eventSchema=z132.object({type:z132.string().min(1),family:z132.string(),description:z132.string(),variables:z132.array(z132.string()),data:z132.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:z132.object({projectId:uuidSchema}).strict(),outputSchema:z132.array(eventSchema),buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/webhooks/events")}),"buildRequest"),projectOutput:__name(body=>z132.array(eventSchema).parse(responseData(body)),"projectOutput")},"webhooks.list":{domain:"webhooks",summary:"List outbound webhooks configured for one site.",accessScope:"read",effect:"read",inputSchema:z132.object({projectId:uuidSchema}).strict(),outputSchema:z132.array(webhookSchema),buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/webhooks")}),"buildRequest"),projectOutput:__name(body=>z132.array(webhookSchema).parse(responseData(body)),"projectOutput")},"webhooks.get":{domain:"webhooks",summary:"Read one outbound site webhook.",accessScope:"read",effect:"read",inputSchema:z132.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:webhookSchema,buildRequest:__name(({projectId:projectId2,webhookId})=>({method:"GET",path:managementProjectPath(projectId2,`/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:z132.object({projectId:uuidSchema,webhook:webhookWriteSchema}).strict(),outputSchema:z132.object({webhook:webhookSchema,signingSecret:z132.string().min(1)}),buildRequest:__name(({projectId:projectId2,webhook})=>({method:"POST",path:managementProjectPath(projectId2,"/webhooks"),body:webhook}),"buildRequest"),projectOutput:__name(body=>z132.object({webhook:webhookSchema,signingSecret:z132.string().min(1)}).parse(responseData(body)),"projectOutput")},"webhooks.update":{domain:"webhooks",summary:"Update one outbound site webhook.",accessScope:"write",effect:"mutation",inputSchema:z132.object({projectId:uuidSchema,webhookId:uuidSchema,webhook:webhookWriteSchema}).strict(),outputSchema:webhookSchema,buildRequest:__name(({projectId:projectId2,webhookId,webhook})=>({method:"PATCH",path:managementProjectPath(projectId2,`/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:z132.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:z132.unknown(),buildRequest:__name(({projectId:projectId2,webhookId})=>({method:"DELETE",path:managementProjectPath(projectId2,`/webhooks/${encodeURIComponent(webhookId)}`)}),"buildRequest")},"webhooks.rotateSecret":{domain:"webhooks",summary:"Rotate and reveal the signing secret for one site webhook.",accessScope:"write",effect:"mutation",inputSchema:z132.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:z132.string().min(1),buildRequest:__name(({projectId:projectId2,webhookId})=>({method:"POST",path:managementProjectPath(projectId2,`/webhooks/${encodeURIComponent(webhookId)}/rotate-signing-secret`)}),"buildRequest"),projectOutput:__name(body=>z132.object({signingSecret:z132.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:z132.object({projectId:uuidSchema,webhookId:uuidSchema,data:jsonObjectSchema.optional()}).strict(),outputSchema:deliverySchema,buildRequest:__name(({projectId:projectId2,webhookId,data})=>({method:"POST",path:managementProjectPath(projectId2,`/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:z132.object({projectId:uuidSchema,webhookId:uuidSchema,...numberedPaginationShape,limit:z132.number().int().min(1).max(100).optional()}).strict().superRefine(numberedPaginationRefinement),outputSchema:deliveriesPageSchema.extend({nextCursor:z132.string().nullable()}),buildRequest:__name(({projectId:projectId2,webhookId,page,cursor,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,`/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:z132.object({projectId:uuidSchema,webhookId:uuidSchema,deliveryId:uuidSchema}).strict(),outputSchema:z132.object({delivery:deliverySchema,attempts:z132.array(attemptSchema)}),buildRequest:__name(({projectId:projectId2,webhookId,deliveryId})=>({method:"GET",path:managementProjectPath(projectId2,`/webhooks/${encodeURIComponent(webhookId)}/deliveries/${encodeURIComponent(deliveryId)}`)}),"buildRequest"),projectOutput:__name(body=>z132.object({delivery:deliverySchema,attempts:z132.array(attemptSchema)}).parse(responseData(body)),"projectOutput")},"webhooks.retryDelivery":{domain:"webhooks",summary:"Retry one failed webhook delivery.",accessScope:"write",effect:"mutation",inputSchema:z132.object({projectId:uuidSchema,webhookId:uuidSchema,deliveryId:uuidSchema}).strict(),outputSchema:deliverySchema,buildRequest:__name(({projectId:projectId2,webhookId,deliveryId})=>({method:"POST",path:managementProjectPath(projectId2,`/webhooks/${encodeURIComponent(webhookId)}/deliveries/${encodeURIComponent(deliveryId)}/retry`)}),"buildRequest"),projectOutput:__name(body=>deliverySchema.parse(responseData(body)),"projectOutput")}}}});import{z as z133}from"zod";var fimoOperations,fimoOperationManifestEntrySchema,fimoOperationManifestSchema,fimoOperationManifest,init_operations=__esm({"../../packages/sdk/dist/operations.js"(){"use strict";init_agents();init_analytics();init_assets();init_billing2();init_branches();init_domains();init_entries();init_environments();init_files();init_forms();init_generation();init_history();init_hosting();init_integrations();init_knowledge();init_labels();init_locales();init_organizations();init_projects();init_schedules();init_schemas();init_secrets();init_sessions();init_singles();init_support2();init_webhooks();fimoOperations={...projectsOperations,...organizationsOperations,...domainsOperations,...generationOperations,...historyOperations,...environmentsOperations,...secretsOperations,...schedulesOperations,...webhooksOperations,...branchesOperations,...schemasOperations,...supportOperations,...sessionsOperations,...entriesOperations,...singlesOperations,...knowledgeOperations,...agentsOperations,...labelsOperations,...localesOperations,...assetsOperations,...formsOperations,...hostingOperations,...analyticsOperations,...integrationsOperations,...filesOperations,...billingOperations},fimoOperationManifestEntrySchema=z133.object({id:z133.string().regex(/^[a-zA-Z_$][\w$]*\.[a-zA-Z_$][\w$]*$/),domain:z133.string().min(1),summary:z133.string().min(1),accessScope:z133.enum(["read","write","code","agents"]),effect:z133.enum(["read","mutation"]),inputJsonSchema:z133.record(z133.string(),z133.unknown()),outputJsonSchema:z133.record(z133.string(),z133.unknown())}).strict(),fimoOperationManifestSchema=z133.array(fimoOperationManifestEntrySchema),fimoOperationManifest=Object.entries(fimoOperations).map(([id,operation])=>({id,domain:operation.domain,summary:operation.summary,accessScope:operation.accessScope,effect:operation.effect,inputJsonSchema:z133.toJSONSchema(operation.inputSchema,{target:"draft-7",io:"input"}),outputJsonSchema:z133.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 fs3 from"node:fs";import path3 from"node:path";import{setTimeout as sleep}from"node:timers/promises";function isPublishedInstall(cliRoot=CLI_ROOT){return fs3.existsSync(path3.join(cliRoot,"release.json"))}function buildSkipsVersionCheck(cliRoot=CLI_ROOT,readFile6=defaultReadFile){try{return JSON.parse(readFile6(path3.join(cliRoot,"release.json"))).skipVersionCheck===!0}catch{return!1}}function defaultReadFile(file){return fs3.readFileSync(file,"utf8")}function resolveGlobalFimoRoot(){let result=spawnSync("npm",["root","-g"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:GLOBAL_ROOT_TIMEOUT_MS});return result.error||result.status!==0||typeof result.stdout!="string"||result.stdout.trim().length===0?null:path3.resolve(result.stdout.trim(),"fimo")}function normalizedPath(input){try{return fs3.realpathSync(input)}catch{return path3.resolve(input)}}function autoUpgradeEnabled(options={}){let usesDefaults=Object.keys(options).length===0;if(usesDefaults&&defaultEligibility!==void 0)return defaultEligibility;let env=options.env??process.env,cliRoot=options.cliRoot??CLI_ROOT,published=options.published??isPublishedInstall(cliRoot);if(env.FIMO_AUTO_UPGRADE!=="1"||!published||buildSkipsVersionCheck(cliRoot))return usesDefaults&&(defaultEligibility=!1),!1;let globalFimoRoot=options.globalFimoRoot===void 0?resolveGlobalFimoRoot():options.globalFimoRoot;if(!globalFimoRoot)return usesDefaults&&(defaultEligibility=!1),!1;let eligible=normalizedPath(cliRoot)===normalizedPath(globalFimoRoot);return usesDefaults&&(defaultEligibility=eligible),eligible}async function acquireLock(lockDir){let deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{fs3.mkdirSync(lockDir);return}catch(error){if(error.code!=="EEXIST")throw error}let stale=!1;try{stale=Date.now()-fs3.statSync(lockDir).mtimeMs>LOCK_STALE_MS}catch{continue}if(stale){try{fs3.rmdirSync(lockDir)}catch{}continue}if(Date.now()>=deadline)throw new Error("auto-upgrade lock timeout");await sleep(LOCK_POLL_MS)}}function readGlobalFimoVersion(){let root=resolveGlobalFimoRoot();if(!root)return null;try{let pkg=JSON.parse(fs3.readFileSync(path3.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=path3.join(loadConfig().configDir,"auto-upgrade.lock");try{fs3.mkdirSync(path3.dirname(lockDir),{recursive:!0}),await acquireLock(lockDir)}catch{return!1}try{if(readGlobalFimoVersion()===latest)return!0;let install=spawnSync("npm",["install","-g",`fimo@${latest}`],{stdio:["ignore","ignore","inherit"],timeout:INSTALL_TIMEOUT_MS});return install.error||install.status!==0?!1:readGlobalFimoVersion()===latest}finally{try{fs3.rmdirSync(lockDir)}catch{}}}var INSTALL_TIMEOUT_MS,GLOBAL_ROOT_TIMEOUT_MS,LOCK_WAIT_MS,LOCK_STALE_MS,LOCK_POLL_MS,VERSION_PATTERN,defaultEligibility,init_auto_upgrade=__esm({"src/cli/auto-upgrade.ts"(){init_config();INSTALL_TIMEOUT_MS=12e4,GLOBAL_ROOT_TIMEOUT_MS=5e3,LOCK_WAIT_MS=18e4,LOCK_STALE_MS=3e5,LOCK_POLL_MS=500,VERSION_PATTERN=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;__name(isPublishedInstall,"isPublishedInstall");__name(buildSkipsVersionCheck,"buildSkipsVersionCheck");__name(defaultReadFile,"defaultReadFile");__name(resolveGlobalFimoRoot,"resolveGlobalFimoRoot");__name(normalizedPath,"normalizedPath");__name(autoUpgradeEnabled,"autoUpgradeEnabled");__name(acquireLock,"acquireLock");__name(readGlobalFimoVersion,"readGlobalFimoVersion");__name(autoUpgradeGlobal,"autoUpgradeGlobal")}});import fs4 from"node:fs";import path4 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";function getCliVersion(){try{let raw=fs4.readFileSync(PACKAGE_JSON_PATH,"utf8");return JSON.parse(raw).version??"0.0.0"}catch{return"0.0.0"}}var THIS_FILE2,CLI_ROOT2,PACKAGE_JSON_PATH,init_version=__esm({"src/cli/version.ts"(){THIS_FILE2=fileURLToPath2(import.meta.url),CLI_ROOT2=path4.resolve(path4.dirname(THIS_FILE2),"..",".."),PACKAGE_JSON_PATH=path4.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(issue2=>{let{path:path52,message}=issue2;return`${Array.isArray(path52)&&path52.length>0?`${path52.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),server.body=body}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(path52,init={},defaultJsonContentType=!0)=>fimoFetch(`${cfg.apiUrl}${path52}`,{...init,headers:authHeaders(init,defaultJsonContentType)}),"send");return{async request(path52,init={},options={}){let response=await send(path52,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",path52,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()},async response(path52,init={}){let response=await send(path52,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",path52,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,path52,status,detail,code2,body){super(`API ${method} ${path52} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path52,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;body;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,this.body=server.body}},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")}});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 files2=new Set(Array.from(paths,file=>file.replace(/\\/g,"/").replace(/^\.\//,"")));return(layout??detectProjectLayout(files2)??"current")==="current"?CURRENT_PROJECT_LAYOUT.config:files2.has(LEGACY_AGENT_POLICY_PATH)&&!files2.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(projectId2,branch,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId2}-${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 fs5 from"node:fs";import path5 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=path5.join(root,file);fs5.existsSync(filePath)&&Object.assign(values,parseEnv(fs5.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=path5.resolve(start);for(;;){if(fs5.existsSync(path5.join(dir,CURRENT_PROJECT_LAYOUT.project))||fs5.existsSync(path5.join(dir,LEGACY_PROJECT_LAYOUT.project)))return dir;let parent=path5.dirname(dir);if(parent===dir)return null;dir=parent}}function readProjectLink(root){for(let layout of[CURRENT_PROJECT_LAYOUT,LEGACY_PROJECT_LAYOUT]){let file=path5.join(root,layout.project);if(fs5.existsSync(file))try{let parsed=JSON.parse(fs5.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{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 gitCommit(cwd,message,description){let identity2=await hasGitIdentity(cwd)?[]:["-c",`user.name=${FALLBACK_GIT_IDENTITY.name}`,"-c",`user.email=${FALLBACK_GIT_IDENTITY.email}`];await runGit([...identity2,"commit","-m",message,...description?["-m",description]:[]],cwd)}async function hasGitIdentity(cwd){try{return await runGit(["var","GIT_AUTHOR_IDENT"],cwd),await runGit(["var","GIT_COMMITTER_IDENT"],cwd),!0}catch{return!1}}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")}});import{z as z106}from"zod";function createResponseSchema2(dataSchema){return z106.object({data:dataSchema})}function encodeBranchPathSegment2(branch){return encodeURIComponent(branch.replaceAll("/","--"))}function managementProjectPath(projectId2,suffix){return`/management/projects/${encodeURIComponent(projectId2)}${suffix}`}function managementBranchPath(projectId2,branch,suffix){return managementProjectPath(projectId2,`/branches/${encodeBranchPathSegment2(branch)}${suffix}`)}function tenantPath(projectId2,branch,suffix){return`/tenant/${encodeURIComponent(projectId2)}/branches/${encodeBranchPathSegment2(branch)}${suffix}`}function addQuery(path52,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?`${path52}?${queryString}`:path52}function withoutUndefined(values){return Object.fromEntries(Object.entries(values).filter(([,value])=>value!==void 0))}function utf8Text(maxBytes,message){return z106.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 z106.object({items:z106.array(itemSchema),nextCursor:z106.string().nullable(),total:z106.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(projectId2,branch,sessionId,suffix){return sessionId?managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/files${suffix}`):managementBranchPath(projectId2,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=z106.uuid(),sessionStatusSchema=z106.enum(["provisioning","ready","closing","merged","discarded","expired","failed"]),surfaceNameSchema=z106.enum(["code","schemas","content","labels","assets","forms"]),branchSurfaceSchema=z106.enum(["code","schemas","content","labels","assets","forms"]),backendSurfaceSchema=z106.enum(["code","schemas","content","translations","assets","forms"]),branchNameSchema=z106.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=z106.object({sessionId:uuidSchema,projectId:uuidSchema,status:sessionStatusSchema,name:z106.string().nullable().optional(),goal:z106.string().nullable().optional(),provenance:z106.object({source:z106.enum(["studio","slack","mcp"]),creator:z106.object({kind:z106.enum(["user","slack","agent","oauth","conversation"]),id:z106.string()}),conversationId:z106.string().nullable(),runId:z106.string().nullable()}).nullable().optional(),createdBy:z106.string().optional(),createdAt:z106.iso.datetime().optional(),savedRevision:z106.string().nullable().optional(),targetBranch:z106.object({id:uuidSchema.nullable(),name:branchNameSchema,sha:z106.string().min(1)}),workingBranch:z106.object({id:uuidSchema,name:branchNameSchema}).nullable(),preview:z106.url().nullable(),lastActivityAt:z106.iso.datetime(),expiresAt:z106.iso.datetime().nullable(),retention:z106.enum(["temporary","durable"]).optional(),visibility:z106.enum(["internal","user-visible"]).optional(),onExpire:z106.enum(["discard","keep"]),nextOperations:z106.array(z106.string())}),paginationShape={limit:z106.number().int().min(1).max(100).optional(),cursor:z106.string().min(1).nullable().optional().describe("Opaque nextCursor from the previous page. Omit or use null for the first page."),offset:z106.number().int().min(0).optional()};__name(paginationRefinement,"paginationRefinement");__name(encodePaginationCursor,"encodePaginationCursor");__name(decodePaginationCursor,"decodePaginationCursor");__name(paginationOffset,"paginationOffset");numberedPaginationShape={page:z106.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=z106.object({data:z106.array(z106.unknown()),meta:z106.object({limit:z106.number().int().positive(),offset:z106.number().int().nonnegative(),total:z106.number().int().nonnegative(),hasMore:z106.boolean()})});__name(projectOffsetPage,"projectOffsetPage");__name(projectDetail,"projectDetail");__name(requiredBranch,"requiredBranch");__name(projectFilesPath,"projectFilesPath")}});import{z as z107}from"zod";var agent,chats,routines,routineRuns,agentsOperations,init_agents=__esm({"../../packages/sdk/dist/operations/agents.js"(){"use strict";init_common2();agent=z107.object({id:uuidSchema,kind:z107.string(),title:z107.string().nullable(),description:z107.string().nullable()}),chats=z107.object({chats:z107.array(agent)}),routines=z107.object({routines:z107.array(z107.object({id:uuidSchema,name:z107.string(),instructions:z107.string(),paused:z107.boolean(),triggers:z107.object({schedule:z107.object({cron:z107.string(),timezone:z107.string()}).nullable(),event:z107.object({text:z107.string()}).nullable()}),nextRunAt:z107.string().nullable(),lastRunAt:z107.string().nullable(),lastOutcome:z107.string().nullable(),outOfAgentHoursUntil:z107.string().nullable()}))}),routineRuns=z107.object({runs:z107.array(z107.object({startedAt:z107.string(),trigger:z107.enum(["schedule","hand","event"]),startedBy:z107.object({kind:z107.enum(["person","agent"]),name:z107.string().nullable()}).nullable(),status:z107.enum(["queued","running","finished","failed","cancelled"]),outcome:z107.string().nullable(),summary:z107.string().nullable(),durationMs:z107.number().nullable()}))}),agentsOperations={"agents.list":{domain:"agents",summary:"Read the project agents.",accessScope:"read",effect:"read",inputSchema:z107.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:chats,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",context:{branch},path:addQuery("/chat/project/threads",{projectId:projectId2})}),"buildRequest"),projectOutput:__name(body=>({chats:chats.parse(body).chats.filter(chat=>chat.kind==="agent")}),"projectOutput")},"agents.routines":{domain:"agents",summary:"Read an agent\u2019s routine instructions and schedules.",accessScope:"read",effect:"read",inputSchema:z107.object({projectId:uuidSchema,branch:branchNameSchema,threadId:uuidSchema}).strict(),outputSchema:routines,buildRequest:__name(({projectId:projectId2,branch,threadId})=>({method:"GET",context:{branch},path:addQuery(`/chat/project/threads/${threadId}/routines`,{projectId:projectId2})}),"buildRequest")},"agents.routineRuns":{domain:"agents",summary:"Read a routine\u2019s newest runs: when each started, what started it and how it ended.",accessScope:"read",effect:"read",inputSchema:z107.object({projectId:uuidSchema,branch:branchNameSchema,threadId:uuidSchema,routineId:uuidSchema}).strict(),outputSchema:routineRuns,buildRequest:__name(({projectId:projectId2,branch,threadId,routineId})=>({method:"GET",context:{branch},path:addQuery(`/chat/project/threads/${threadId}/routines/${routineId}/runs`,{projectId:projectId2})}),"buildRequest")}}}});import{z as z108}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=z108.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=z108.enum(["day","week","month","quarter"]),analyticsDeviceSchema=z108.enum(["bot","desktop","mobile","tablet"]),analyticsRangeShape={preset:analyticsPresetSchema.optional(),device:analyticsDeviceSchema.optional(),groupBy:analyticsGroupBySchema.optional(),from:z108.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),to:z108.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),days:z108.union([z108.literal(7),z108.literal(30),z108.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=z108.object({date:z108.string(),content:z108.string(),updatedAt:z108.string(),updatedByUserId:z108.string()}),analyticsBreakdownSchema=z108.object({key:z108.string(),visitors:z108.number().int().nonnegative(),pageviews:z108.number().int().nonnegative()}),analyticsPageBreakdownSchema=z108.object({path:z108.string(),pageName:z108.string().nullable().optional(),visitors:z108.number().int().nonnegative(),pageviews:z108.number().int().nonnegative()}),analyticsPageviewsSchema=z108.object({range:z108.object({preset:analyticsPresetSchema,requestedFrom:z108.string(),requestedTo:z108.string(),effectiveFrom:z108.string(),effectiveTo:z108.string(),isRetentionLimited:z108.boolean(),groupBy:analyticsGroupBySchema}),deviceFilter:analyticsDeviceSchema.nullable().default(null),visitors:z108.number().int().nonnegative(),pageviews:z108.number().int().nonnegative(),botPageviews:z108.number().int().nonnegative().default(0),botVisitors:z108.number().int().nonnegative().default(0),bounceRate:z108.number().min(0).max(100),viewsPerVisit:z108.number().nonnegative(),averageVisitDurationSeconds:z108.number().nonnegative(),visitorsSeries:z108.array(z108.object({date:z108.string(),visitors:z108.number().int().nonnegative()})),topPages:z108.array(analyticsPageBreakdownSchema),topBrowsers:z108.array(analyticsBreakdownSchema),topDevices:z108.array(analyticsBreakdownSchema),topBots:z108.array(analyticsBreakdownSchema).default([]),topAiAssistants:z108.array(analyticsBreakdownSchema).default([]),topCountries:z108.array(analyticsBreakdownSchema),topSources:z108.array(analyticsBreakdownSchema),annotations:z108.array(analyticsAnnotationSchema)}),analyticsApiResponseSchema=createResponseSchema2(analyticsPageviewsSchema),analyticsPageviewsResponseSchema=createResponseSchema2(analyticsPageviewsSchema.extend({branch:branchNameSchema})),analyticsDimensionSchema=z108.enum(["pages","browsers","devices","countries","sources"]),analyticsTopOutputSchema=z108.object({branch:branchNameSchema,dimension:analyticsDimensionSchema,items:z108.array(z108.union([analyticsPageBreakdownSchema,analyticsBreakdownSchema]))}),analyticsAnnotationsOutputSchema=z108.object({branch:branchNameSchema,annotations:z108.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:z108.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:projectId2,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,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:z108.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,dimension:analyticsDimensionSchema,limit:z108.number().int().min(1).max(100).optional(),...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsTopOutputSchema,buildRequest:__name(({projectId:projectId2,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,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:z108.object({projectId:uuidSchema,branch:analyticsReadBranchSchema,...analyticsRangeShape}).strict().superRefine(analyticsRangeRefinement),outputSchema:analyticsAnnotationsOutputSchema,buildRequest:__name(({projectId:projectId2,branch,preset,groupBy,from,to,days,device})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,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:z108.object({projectId:uuidSchema,branch:branchNameSchema,date:z108.string().regex(/^\d{4}-\d{2}-\d{2}$/),content:z108.string().max(500)}).strict(),outputSchema:z108.union([analyticsAnnotationResponseSchema,z108.null()]),buildRequest:__name(({projectId:projectId2,branch,date,content:content2})=>({method:"PUT",path:managementBranchPath(projectId2,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:z108.object({projectId:uuidSchema,branch:branchNameSchema,date:z108.string().regex(/^\d{4}-\d{2}-\d{2}$/)}).strict(),outputSchema:z108.null(),buildRequest:__name(({projectId:projectId2,branch,date})=>({method:"PUT",path:managementBranchPath(projectId2,branch,`/analytics/annotations/${encodeURIComponent(date)}`),body:{content:""}}),"buildRequest"),projectOutput:__name(()=>null,"projectOutput")}}}});import{z as z109}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=z109.object({id:z109.string(),name:z109.string()}),AssetDTOSchema2=z109.object({id:z109.string(),name:z109.string(),type:z109.enum(["file","folder"]),originalFileName:z109.string().nullable(),parentId:z109.string().nullable(),mimeType:z109.string().nullable(),fileSize:z109.number().nullable(),url:z109.string().nullable(),storageKey:z109.string().nullable(),slug:z109.string(),tags:z109.array(z109.string()).nullable().optional(),createdAt:z109.string().nullable(),updatedAt:z109.string().nullable(),altText:z109.string().nullable().optional(),caption:z109.string().nullable().optional(),aiCaption:z109.string().nullable().optional(),aiAltText:z109.string().nullable().optional(),aiTags:z109.array(z109.string()).nullable().optional(),aiPrimaryColor:z109.string().nullable().optional(),aiProcessingStatus:z109.string().nullable().optional(),width:z109.number().nullable().optional(),height:z109.number().nullable().optional(),path:z109.array(assetPathItemSchema).optional(),hasChildren:z109.boolean().optional()}),AssetResponseSchema2=createResponseSchema2(AssetDTOSchema2),AssetReadRequestSchema2=z109.object({cursor:z109.string().nullable().optional(),query:z109.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=z109.object({url:z109.url(),mediaType:z109.string(),filename:z109.string()}),assetReadBaseSchema=z109.object({assetId:z109.uuid(),filename:z109.string(),mediaType:z109.string(),representation:z109.enum(["text","table","document","archive","image","transcript","video","model"]),content:z109.string(),derivedFiles:z109.array(assetDerivedFileSchema).optional()}),AssetReadResultSchema2=z109.discriminatedUnion("mode",[assetReadBaseSchema.extend({mode:z109.literal("page"),start:z109.number().int().nonnegative(),end:z109.number().int().nonnegative(),total:z109.number().int().nonnegative(),nextCursor:z109.string().nullable(),complete:z109.boolean()}),assetReadBaseSchema.extend({mode:z109.literal("query"),query:z109.string(),source:z109.enum(["original-file","canonical-text","derived-files"]),truncated:z109.boolean()})]),GenerateResponseSchema2=createResponseSchema2(z109.object({jobId:z109.string(),status:z109.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema2.optional(),error:z109.string().nullable().optional(),credits:z109.number().optional(),costUsd:z109.number().optional(),billingMode:z109.enum(["fimo-credits","provider-account"]).optional(),task:z109.enum(["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"]).optional(),quality:z109.enum(["draft","standard","premium"]).optional()})),assetPageSchema=pageSchema(AssetDTOSchema2),successMessageResponseSchema=z109.object({data:z109.object({message:z109.literal("success")})}),assetGenerationInputSchema=z109.object({projectId:uuidSchema,branch:branchNameSchema,task:z109.string().min(1).optional(),model:z109.string().min(1).optional(),options:z109.record(z109.string(),z109.unknown()),name:z109.string().min(1).max(255).optional(),parentId:uuidSchema.nullable().optional(),altText:z109.string().max(2e3).optional(),caption:z109.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=z109.object({projectId:uuidSchema,sessionId:uuidSchema,url:z109.url().max(4096).refine(url=>url.startsWith("https://")||url.startsWith("http://"),"URL must use HTTP or HTTPS"),filename:z109.string().trim().min(1).max(255).refine(filename=>!filename.includes("/")&&!filename.includes("\\"),"Filename must not contain a path").optional(),name:z109.string().trim().min(1).max(255).optional(),parentId:uuidSchema.nullable().optional(),folderPath:z109.string().max(1024).refine(path52=>path52.split("/").some(segment=>segment.trim()),"Folder path must contain a folder name").refine(path52=>path52.split("/").every(segment=>![".",".."].includes(segment.trim())),"Folder path cannot contain . or .. segments").optional(),altText:z109.string().max(2e3).optional(),caption:z109.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:z109.object({projectId:uuidSchema,branch:branchNameSchema,parentId:uuidSchema.optional(),search:z109.string().max(200).optional(),type:z109.enum(["file","folder"]).optional(),mimePrefix:z109.string().max(50).optional(),sortBy:z109.enum(["name","createdAt","updatedAt","fileSize","type"]).optional(),sortDirection:z109.enum(["asc","desc"]).optional(),includePath:z109.boolean().optional(),excludeHidden:z109.boolean().optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:assetPageSchema,buildRequest:__name(({projectId:projectId2,branch,parentId,search,type,mimePrefix,sortBy,sortDirection,includePath,excludeHidden,limit,cursor,offset})=>({method:"GET",path:addQuery(tenantPath(projectId2,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:z109.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:AssetResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,id})=>({method:"GET",path:tenantPath(projectId2,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:z109.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:projectId2,branch,id,cursor,query})=>({method:"POST",path:tenantPath(projectId2,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:projectId2,branch,task,model,options,name,parentId,altText,caption})=>({method:"POST",path:tenantPath(projectId2,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:projectId2,sessionId,...upload})=>({method:"POST",path:managementProjectPath(projectId2,`/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:z109.object({projectId:uuidSchema,branch:branchNameSchema,name:z109.string().min(1).max(255),parentId:uuidSchema.nullable().optional()}).strict(),outputSchema:AssetResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,name,parentId})=>({method:"POST",path:tenantPath(projectId2,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:z109.object({projectId:uuidSchema,branch:branchNameSchema,sourceAssetId:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z109.record(z109.string(),z109.unknown()),buildRequest:__name(({projectId:projectId2,branch,sourceAssetId,replacementAssetId})=>({method:"POST",path:tenantPath(projectId2,branch,`/assets/${encodeURIComponent(sourceAssetId)}/replace-references`),body:{replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z109.object({data:z109.record(z109.string(),z109.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:z109.object({projectId:uuidSchema,branch:branchNameSchema,sourceAssetId:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z109.record(z109.string(),z109.unknown()),buildRequest:__name(({projectId:projectId2,branch,sourceAssetId,replacementAssetId})=>({method:"POST",path:tenantPath(projectId2,branch,"/assets/removals"),body:{intent:"replace-and-remove",assetIds:[sourceAssetId],replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z109.object({data:z109.record(z109.string(),z109.unknown())}).parse(body).data,"projectOutput")},"assets.destroy":{domain:"assets",summary:"Permanently destroy an asset on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z109.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:z109.unknown(),buildRequest:__name(({projectId:projectId2,branch,id})=>({method:"DELETE",path:tenantPath(projectId2,branch,`/assets/${encodeURIComponent(id)}/permanent`)}),"buildRequest"),projectOutput:__name(body=>z109.object({data:z109.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:z109.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,replacementAssetId:uuidSchema}).strict(),outputSchema:z109.record(z109.string(),z109.unknown()),buildRequest:__name(({projectId:projectId2,branch,id,replacementAssetId})=>({method:"POST",path:tenantPath(projectId2,branch,`/assets/${encodeURIComponent(id)}/replace-and-destroy`),body:{replacementAssetId}}),"buildRequest"),projectOutput:__name(body=>z109.object({data:z109.record(z109.string(),z109.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:z109.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema,parentId:uuidSchema.nullable()}).strict(),outputSchema:AssetResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,id,parentId})=>({method:"POST",path:tenantPath(projectId2,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:z109.object({projectId:uuidSchema,branch:branchNameSchema,id:uuidSchema}).strict(),outputSchema:successMessageResponseSchema,buildRequest:__name(({projectId:projectId2,branch,id})=>({method:"DELETE",path:tenantPath(projectId2,branch,`/assets/${encodeURIComponent(id)}`)}),"buildRequest")}}}});import{z as z110}from"zod";var creditBalanceOutputSchema,billingOperations,init_billing2=__esm({"../../packages/sdk/dist/operations/billing.js"(){"use strict";init_common2();creditBalanceOutputSchema=z110.object({projectId:uuidSchema,organizationId:z110.string(),balance:z110.object({totalAvailable:z110.number(),nearLimit:z110.boolean(),canUseAi:z110.boolean(),buckets:z110.object({dailyFreeAvailable:z110.number(),monthlyAvailable:z110.number(),purchasedAvailable:z110.number(),awardedAvailable:z110.number()})}),allowances:z110.object({dailyCredits:z110.object({periodCap:z110.number(),dailyGrant:z110.number(),usedThisPeriod:z110.number(),remainingThisPeriod:z110.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:z110.object({projectId:uuidSchema}).strict(),outputSchema:creditBalanceOutputSchema,buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/billing/credits")}),"buildRequest"),projectOutput:__name(body=>creditBalanceOutputSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z111}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=z111.object({ok:z111.boolean(),mergeId:uuidSchema,fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),fromEnv:branchNameSchema,toEnv:branchNameSchema,applied:z111.array(z111.object({surface:backendSurfaceSchema,count:z111.number().int().nonnegative()})),conflicts:z111.array(backendConflictSchema).optional(),summary:z111.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=z111.object({mergeId:uuidSchema,conflicts:z111.array(backendConflictSchema),draftResolutions:z111.array(conflictResolutionSchema.extend({surface:backendSurfaceSchema})),status:z111.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 z111.object({data:z111.array(branchSchema)}).parse({data})}function projectBranchStatus(body){if(branchStatusOutputSchema.safeParse(body).success)return branchStatusOutputSchema.parse(body);let report2=z111.object({branch:branchNameSchema.optional(),env:branchNameSchema,vs:branchNameSchema,syncState:z111.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:isoTimestampSchema,surfaces:z111.array(backendSurfaceDeltaSchema).max(6),crossSurface:z111.array(backendCrossSurfaceFindingSchema).max(1e3).optional()}).parse(responseData(body));return branchStatusOutputSchema.parse(withoutUndefined({branch:report2.branch??report2.env,against:report2.vs,state:report2.syncState==="in-sync"?"clean":"changed",syncState:report2.syncState,generatedAt:report2.generatedAt,surfaces:report2.surfaces.map(({surface,status,changedCount,conflictCount,items,truncated,error})=>withoutUndefined({surface:publicSurface(surface),status,changedCount,conflictCount,items,truncated,error})),crossSurface:report2.crossSurface?.map(projectCrossSurfaceFinding)}))}function projectBranchDiff(body){if(branchDiffOutputSchema.safeParse(body).success)return branchDiffOutputSchema.parse(body);let report2=z111.object({fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),fromEnv:branchNameSchema,toEnv:branchNameSchema,generatedAt:isoTimestampSchema,fingerprint:z111.string().min(1),surfaces:z111.array(backendSurfaceDeltaSchema).max(6),crossSurface:z111.array(backendCrossSurfaceFindingSchema).max(1e3).optional()}).parse(responseData(body));return branchDiffOutputSchema.parse({branch:report2.fromBranch??report2.fromEnv,against:report2.toBranch??report2.toEnv,generatedAt:report2.generatedAt,fingerprint:report2.fingerprint,surfaces:report2.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:report2.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,resolvedMergeStrategySchema,mergeAcceptedSchema,mergeStatusSchema,mergeHydrationSchema,codeConflictBlobSchema,codeConflictDetailOutputSchema,branchesOperations,init_branches=__esm({"../../packages/sdk/dist/operations/branches.js"(){"use strict";init_common2();branchSchema=z111.object({id:uuidSchema,projectId:uuidSchema,branch:branchNameSchema,parentBranch:branchNameSchema.nullable().optional(),status:z111.enum(["provisioning","active","deleted"]),kind:z111.enum(["user","agent-session"]),createdAt:z111.string().optional(),updatedAt:z111.string().optional(),createdBy:z111.string().nullable().optional(),deletedAt:z111.string().nullable().optional()}).passthrough(),branchResponseSchema=z111.object({data:branchSchema}),branchSurfaceStatusSchema=z111.enum(["ok","timed_out","failed","unchanged"]),branchDeltaVerbSchema=z111.enum(["added","removed","changed","conflict"]),isoTimestampSchema=z111.iso.datetime(),backendCrossSurfaceFindingSchema=z111.object({id:z111.string(),kind:z111.string(),description:z111.string(),severity:z111.enum(["warning","error"]),source:z111.object({surface:backendSurfaceSchema,key:z111.string()}),target:z111.object({surface:backendSurfaceSchema,key:z111.string()}),actions:z111.array(z111.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=z111.object({surface:backendSurfaceSchema,status:branchSurfaceStatusSchema,changedCount:z111.number().int().nonnegative(),conflictCount:z111.number().int().nonnegative(),items:z111.array(z111.object({verb:branchDeltaVerbSchema,key:z111.string(),detail:z111.string().optional(),origin:z111.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z111.record(z111.string(),z111.unknown()).optional()})).max(1e3).optional(),truncated:z111.boolean().optional(),error:z111.string().optional()}),branchSurfaceSummarySchema=z111.object({surface:branchSurfaceSchema,status:branchSurfaceStatusSchema,changedCount:z111.number().int().nonnegative(),conflictCount:z111.number().int().nonnegative(),error:z111.string().optional(),items:z111.array(z111.object({verb:branchDeltaVerbSchema,key:z111.string(),detail:z111.string().optional(),origin:z111.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z111.record(z111.string(),z111.unknown()).optional()})).optional(),truncated:z111.boolean().optional()}),branchStatusOutputSchema=z111.object({branch:branchNameSchema,against:branchNameSchema,state:z111.enum(["clean","changed"]),syncState:z111.enum(["in-sync","ahead","behind","diverged","unknown"]).optional(),generatedAt:isoTimestampSchema,surfaces:z111.array(branchSurfaceSummarySchema).max(6),crossSurface:z111.array(crossSurfaceFindingSchema).max(1e3).optional()}),branchDiffItemSchema=z111.object({verb:branchDeltaVerbSchema,key:z111.string(),detail:z111.string().optional(),meta:z111.record(z111.string(),z111.unknown()).optional()}),branchDiffOutputSchema=branchStatusOutputSchema.omit({state:!0}).extend({fingerprint:z111.string().min(1),surfaces:z111.array(branchSurfaceSummarySchema.extend({truncated:z111.boolean(),items:z111.array(branchDiffItemSchema).max(1e3)})).max(6)}),codeFileDiffOutputSchema=z111.object({path:z111.string(),state:z111.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z111.string(),additions:z111.number().int().nonnegative(),deletions:z111.number().int().nonnegative()}),contentSnapshotSchema=z111.object({id:z111.string(),slug:z111.string(),contentType:z111.string(),data:z111.record(z111.string(),z111.unknown()),updatedAt:isoTimestampSchema}),contentEntryDiffOutputSchema=z111.object({collection:z111.string(),rowId:z111.string(),parent:contentSnapshotSchema.nullable(),child:contentSnapshotSchema.nullable()}),schemaSnapshotSchema=z111.object({name:z111.string(),label:z111.string(),isSingleton:z111.boolean(),fields:z111.record(z111.string(),z111.unknown())}),schemaDiffOutputSchema=z111.object({typeName:z111.string(),parent:schemaSnapshotSchema.nullable(),child:schemaSnapshotSchema.nullable()}),assetSnapshotSchema=z111.object({id:z111.string(),name:z111.string(),type:z111.enum(["file","folder"]),mimeType:z111.string().nullable(),storageKey:z111.string().nullable(),url:z111.string().nullable(),fileSize:z111.number().nullable(),width:z111.number().nullable(),height:z111.number().nullable(),altText:z111.string().nullable(),caption:z111.string().nullable(),createdAt:isoTimestampSchema,updatedAt:isoTimestampSchema}),assetDiffOutputSchema=z111.object({assetId:z111.string(),parent:assetSnapshotSchema.nullable(),child:assetSnapshotSchema.nullable()}),labelDiffOutputSchema=z111.object({locale:z111.string(),key:z111.string(),parent:z111.string().nullable(),child:z111.string().nullable()}),formSnapshotSchema=z111.object({formName:z111.string(),label:z111.string().nullable(),schemaFingerprint:z111.string(),fields:z111.record(z111.string(),z111.unknown())}),formDiffOutputSchema=z111.object({formName:z111.string(),parent:formSnapshotSchema.nullable(),child:formSnapshotSchema.nullable()}),backendConflictSchema=z111.object({surface:backendSurfaceSchema,key:z111.string(),kind:z111.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"]).optional(),description:z111.string(),parentValue:z111.unknown().optional(),childValue:z111.unknown().optional(),conflictingFields:z111.array(z111.string()).optional(),code:z111.object({path:z111.string(),unresolvable:z111.boolean().optional(),reason:z111.string().optional()}).optional()}),conflictSchema=backendConflictSchema.extend({surface:branchSurfaceSchema}),fieldPickSchema=z111.object({field:z111.string(),choice:z111.enum(["parent","child","pick","ai-pick"]),pickedValue:z111.unknown().optional(),aiSessionId:z111.string().optional()}),conflictResolutionSchema=z111.object({surface:branchSurfaceSchema,key:z111.string(),choice:z111.enum(["parent","child","pick"]),pickedValue:z111.unknown().optional(),fieldPicks:z111.array(fieldPickSchema).optional()}),mergeResultSchema=z111.object({ok:z111.boolean(),mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,applied:z111.array(z111.object({surface:branchSurfaceSchema,count:z111.number().int().nonnegative()})),conflicts:z111.array(conflictSchema).optional(),summary:z111.string().optional()}),resolvedMergeStrategySchema=z111.object({engine:z111.enum(["ff-only","auto","theirs","ours","manual"]),vendor:z111.enum(["ff_only","ff_prefer","merge"]),squash:z111.boolean()}),mergeAcceptedSchema=z111.object({mergeId:uuidSchema,streamUrl:z111.string(),strategy:resolvedMergeStrategySchema,acceptedAt:isoTimestampSchema}),mergeStatusSchema=z111.object({mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,status:z111.enum(["in_progress","complete","failed","rolled_back","conflicts"]),summary:z111.string().nullable(),error:z111.string().nullable()}),mergeHydrationSchema=z111.object({mergeId:uuidSchema,conflicts:z111.array(conflictSchema),draftResolutions:z111.array(conflictResolutionSchema),status:z111.string()}).passthrough();__name(projectConflict,"projectConflict");__name(backendResolution,"backendResolution");__name(projectMergeResult,"projectMergeResult");__name(projectMergeHydration,"projectMergeHydration");codeConflictBlobSchema=z111.object({content:z111.string(),sha:z111.string().nullable().optional()}).passthrough(),codeConflictDetailOutputSchema=z111.object({path:z111.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:z111.object({projectId:uuidSchema,includeDeleted:z111.boolean().optional(),includeAgentBranches:z111.boolean().optional()}).strict(),outputSchema:z111.object({data:z111.array(branchSchema)}),buildRequest:__name(({projectId:projectId2,includeDeleted,includeAgentBranches})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,"/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:z111.object({projectId:uuidSchema,from:branchNameSchema.optional(),name:branchNameSchema}).strict(),outputSchema:branchResponseSchema,buildRequest:__name(({projectId:projectId2,from,name})=>({method:"POST",path:managementProjectPath(projectId2,"/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:z111.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:branchSchema,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:managementBranchPath(projectId2,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:z111.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema.optional()}).strict(),outputSchema:z111.object({branch:branchSchema,conflicts:z111.number().int().nonnegative()}),buildRequest:__name(({projectId:projectId2,branch,from})=>({method:"POST",path:managementBranchPath(projectId2,branch,"/sync"),body:withoutUndefined({from})}),"buildRequest"),projectOutput:__name(body=>{let data=z111.object({branch:branchSchema.optional(),env:branchSchema.optional(),conflicts:z111.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:z111.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:z111.unknown(),buildRequest:__name(({projectId:projectId2,branch})=>({method:"DELETE",path:managementBranchPath(projectId2,branch,"")}),"buildRequest")},"branches.status":{domain:"branches",summary:"Summarize bounded differences between two durable Branches.",accessScope:"read",effect:"read",inputSchema:z111.object({projectId:uuidSchema,branch:branchNameSchema,against:branchNameSchema.optional(),surfaces:z111.array(branchSurfaceSchema).min(1).max(6).optional()}).strict(),outputSchema:branchStatusOutputSchema,buildRequest:__name(({projectId:projectId2,branch,against,surfaces})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,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:z111.object({projectId:uuidSchema,branch:branchNameSchema,against:branchNameSchema.optional(),surfaces:z111.array(branchSurfaceSchema).min(1).max(6).optional()}).strict(),outputSchema:branchDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,against,surfaces})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,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:z111.object({projectId:uuidSchema,branch:branchNameSchema,path:z111.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:codeFileDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,path:path52,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,"/diff/code/file"),{path:path52,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:z111.object({projectId:uuidSchema,branch:branchNameSchema,collection:z111.string().min(1),rowId:z111.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:contentEntryDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,collection,rowId,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,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:z111.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z111.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:schemaDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,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:z111.object({projectId:uuidSchema,branch:branchNameSchema,assetId:z111.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:assetDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,assetId,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,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:z111.object({projectId:uuidSchema,branch:branchNameSchema,locale:z111.string().min(1),key:z111.string().min(1),against:branchNameSchema.optional()}).strict(),outputSchema:labelDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,locale,key,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,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:z111.object({projectId:uuidSchema,branch:branchNameSchema,formName:z111.string().min(1).max(255),against:branchNameSchema.optional()}).strict(),outputSchema:formDiffOutputSchema,buildRequest:__name(({projectId:projectId2,branch,formName,against})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,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:z111.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,allowDirectMerge:z111.boolean().optional()}).strict(),outputSchema:mergeResultSchema,buildRequest:__name(({projectId:projectId2,branch,from,allowDirectMerge})=>({method:"POST",path:managementBranchPath(projectId2,branch,"/merge"),body:withoutUndefined({from,allowDirectMerge})}),"buildRequest"),projectOutput:projectMergeResult},"branches.resolveMerge":{domain:"branches",summary:"Resume a parked durable Branch merge with operator resolutions and start its successor merge.",accessScope:"code",effect:"mutation",inputSchema:z111.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,mergeId:uuidSchema,resolutions:z111.array(conflictResolutionSchema)}).strict(),outputSchema:mergeAcceptedSchema,buildRequest:__name(({projectId:projectId2,branch,from,mergeId,resolutions})=>({method:"POST",path:managementBranchPath(projectId2,branch,`/merge/${encodeURIComponent(from)}/resolve`),body:{mergeId,resolutions:resolutions.map(backendResolution)}}),"buildRequest"),projectOutput:projectDetail(mergeAcceptedSchema)},"branches.mergeStatus":{domain:"branches",summary:"Read the current status of one durable Branch merge.",accessScope:"read",effect:"read",inputSchema:z111.object({projectId:uuidSchema,mergeId:uuidSchema}).strict(),outputSchema:mergeStatusSchema,buildRequest:__name(({projectId:projectId2,mergeId})=>({method:"GET",path:managementProjectPath(projectId2,`/merges/${encodeURIComponent(mergeId)}`)}),"buildRequest"),projectOutput:projectDetail(mergeStatusSchema)},"branches.cancelMerge":{domain:"branches",summary:"Cancel a parked durable Branch merge.",accessScope:"code",effect:"mutation",inputSchema:z111.object({projectId:uuidSchema,branch:branchNameSchema,mergeId:uuidSchema}).strict(),outputSchema:z111.object({ok:z111.boolean()}),buildRequest:__name(({projectId:projectId2,branch,mergeId})=>({method:"POST",path:managementBranchPath(projectId2,branch,"/merge/cancel"),body:{mergeId}}),"buildRequest"),projectOutput:__name(body=>z111.object({ok:z111.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:z111.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema}).strict(),outputSchema:mergeHydrationSchema,buildRequest:__name(({projectId:projectId2,branch,from})=>({method:"GET",path:managementBranchPath(projectId2,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:z111.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,mergeId:uuidSchema,resolutions:z111.array(conflictResolutionSchema)}).strict(),outputSchema:z111.object({mergeId:uuidSchema,lastEditedAt:z111.string()}),buildRequest:__name(({projectId:projectId2,branch,from,mergeId,resolutions})=>({method:"PUT",path:managementBranchPath(projectId2,branch,`/merge/${encodeURIComponent(from)}/resolve/draft`),body:{mergeId,resolutions:resolutions.map(backendResolution)}}),"buildRequest"),projectOutput:__name(body=>z111.object({mergeId:uuidSchema,lastEditedAt:z111.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:z111.object({projectId:uuidSchema,branch:branchNameSchema,from:branchNameSchema,path:z111.string().min(1)}).strict(),outputSchema:codeConflictDetailOutputSchema,buildRequest:__name(({projectId:projectId2,branch,from,path:path52})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,branch,`/merge/${encodeURIComponent(from)}/conflict/code`),{path:path52})}),"buildRequest"),projectOutput:projectDetail(codeConflictDetailOutputSchema)}}}});import{z as z112}from"zod";var projectDomainSchema,registeredDomainSchema,domainSearchResultSchema,domainPricingSchema,projectPath,forbidden,domainsOperations,init_domains=__esm({"../../packages/sdk/dist/operations/domains.js"(){"use strict";init_common2();projectDomainSchema=z112.object({id:z112.string(),hostname:z112.string(),status:z112.string(),ssl:z112.record(z112.string(),z112.unknown()),cnameTarget:z112.string(),apexTargets:z112.array(z112.string()),dnsAutoConfigured:z112.boolean(),createdAt:z112.unknown(),provider:z112.enum(["cloudflare","saas_custom_domains"]),domainType:z112.enum(["subdomain","apex"])}).passthrough(),registeredDomainSchema=z112.object({id:uuidSchema,domain:z112.string(),status:z112.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),source:z112.enum(["fimo","external"]),autoRenew:z112.boolean(),paymentStatus:z112.enum(["pending","paid","failed","refunded"]).nullable(),checkoutUrl:z112.string().nullable()}).passthrough(),domainSearchResultSchema=z112.object({domain:z112.string(),available:z112.boolean(),premium:z112.boolean(),price:z112.number().nullable(),renewalPrice:z112.number().nullable(),purchaseType:z112.string().nullable()}).passthrough(),domainPricingSchema=z112.object({domain:z112.string(),price:z112.number().nullable(),renewalPrice:z112.number().nullable(),premium:z112.boolean(),allowedYears:z112.array(z112.number().int().positive())}).passthrough(),projectPath=__name((projectId2,suffix)=>`/management/projects/${encodeURIComponent(projectId2)}${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:z112.object({}).strict(),outputSchema:z112.object({domainPurchaseEnabled:z112.boolean(),publicationDomain:z112.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:z112.object({projectId:uuidSchema,slug:z112.string().min(1).max(63)}).strict(),outputSchema:z112.object({subdomain:z112.string(),subdomainUpdatedAt:z112.string()}),buildRequest:__name(({projectId:projectId2,slug})=>({method:"PATCH",path:projectPath(projectId2,"/subdomain"),body:{slug}}),"buildRequest"),projectOutput:responseData},"domains.suggestSubdomains":{domain:"domains",summary:"Suggest available built-in subdomains for a site.",accessScope:"read",effect:"read",inputSchema:z112.object({projectId:uuidSchema,base:z112.string().min(1).max(63).optional(),max:z112.number().int().positive().optional()}).strict(),outputSchema:z112.array(z112.string()),buildRequest:__name(({projectId:projectId2,base,max})=>({method:"GET",path:addQuery(projectPath(projectId2,"/subdomain/suggestions"),{base,max})}),"buildRequest"),projectOutput:__name(body=>z112.object({data:z112.object({suggestions:z112.array(z112.string())})}).parse(body).data.suggestions,"projectOutput")},"domains.list":{domain:"domains",summary:"List custom domains attached to a site.",accessScope:"read",effect:"read",inputSchema:z112.object({projectId:uuidSchema}).strict(),outputSchema:z112.array(projectDomainSchema),buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:projectPath(projectId2,"/domains"),...forbidden}),"buildRequest"),projectOutput:responseData},"domains.add":{domain:"domains",summary:"Attach a custom domain to a site.",accessScope:"write",effect:"mutation",inputSchema:z112.object({projectId:uuidSchema,hostname:z112.string().min(1).max(255),redirectToWww:z112.boolean().optional()}).strict(),outputSchema:projectDomainSchema,buildRequest:__name(({projectId:projectId2,hostname,redirectToWww})=>({method:"POST",path:projectPath(projectId2,"/domains"),body:{hostname,redirectToWww},...forbidden}),"buildRequest"),projectOutput:responseData},"domains.refresh":{domain:"domains",summary:"Refresh custom-domain verification state.",accessScope:"write",effect:"mutation",inputSchema:z112.object({projectId:uuidSchema,domainId:z112.string().min(1)}).strict(),outputSchema:projectDomainSchema,buildRequest:__name(({projectId:projectId2,domainId})=>({method:"POST",path:projectPath(projectId2,`/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:z112.object({projectId:uuidSchema,domainId:z112.string().min(1)}).strict(),outputSchema:z112.unknown(),buildRequest:__name(({projectId:projectId2,domainId})=>({method:"DELETE",path:projectPath(projectId2,`/domains/${encodeURIComponent(domainId)}`),...forbidden}),"buildRequest")},"registeredDomains.search":{domain:"domains",summary:"Search domain-registration availability.",accessScope:"read",effect:"read",inputSchema:z112.object({keyword:z112.string().min(1).max(100),tldFilter:z112.array(z112.string().min(1)).optional()}).strict(),outputSchema:z112.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:z112.object({domain:z112.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:z112.object({organizationId:z112.string().min(1)}).strict(),outputSchema:z112.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:z112.object({organizationId:z112.string().min(1),domain:z112.string().min(1).max(255),years:z112.number().int().min(1).max(10).optional(),autoRenew:z112.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:z112.object({organizationId:z112.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 z113}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=z113.object({id:z113.string(),entryId:z113.string(),documentId:z113.string(),slug:z113.string(),locale:z113.string().optional(),createdAt:z113.string(),updatedAt:z113.string(),__fimo:z113.object({contentType:z113.string()})}).passthrough(),PaginatedEntriesDTOSchema2=z113.object({data:z113.array(EntryDTOSchema2),meta:z113.object({limit:z113.number(),offset:z113.number(),total:z113.number(),hasMore:z113.boolean()})}),EntryResponseSchema2=createResponseSchema2(EntryDTOSchema2),MAX_BULK_ENTRIES2=1e3,entryWhereScalarSchema2=z113.union([z113.string(),z113.number(),z113.boolean(),z113.null()]),entryWhereOperatorSchema2=z113.object({$eq:entryWhereScalarSchema2.optional(),$ne:entryWhereScalarSchema2.optional(),$gt:entryWhereScalarSchema2.optional(),$gte:entryWhereScalarSchema2.optional(),$lt:entryWhereScalarSchema2.optional(),$lte:entryWhereScalarSchema2.optional(),$in:z113.array(entryWhereScalarSchema2).optional(),$nin:z113.array(entryWhereScalarSchema2).optional(),$contains:z113.string().optional(),$startsWith:z113.string().optional(),$null:z113.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema2=z113.record(z113.string(),z113.union([entryWhereScalarSchema2,entryWhereOperatorSchema2])),EntryWhereSchema2=z113.record(z113.string(),z113.union([entryWhereScalarSchema2,entryWhereOperatorSchema2,nestedEntryWhereSchema2])),EntryMutationBodySchema2=z113.object({data:z113.record(z113.string(),z113.unknown()),locale:z113.string().min(1).optional(),documentId:z113.uuid().optional()}),BulkCreateEntriesResponseSchema2=z113.object({data:z113.array(EntryDTOSchema2),meta:z113.object({created:z113.number().int().nonnegative()})}),BulkUpdateEntriesResponseSchema2=z113.object({data:z113.array(EntryDTOSchema2),meta:z113.object({updated:z113.number().int().nonnegative(),missing:z113.array(z113.string())})}),BulkDeleteEntriesResponseSchema2=z113.object({data:z113.array(EntryDTOSchema2),meta:z113.object({deleted:z113.number().int().nonnegative(),missing:z113.array(z113.string())})});__name(projectEntriesPage,"projectEntriesPage");entriesPageSchema=pageSchema(EntryDTOSchema2),typeNameSchema=z113.string().min(1).max(255),localeSchema=z113.string().min(1),populateSchema=z113.array(z113.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:z113.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,locale:localeSchema.optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:entriesPageSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,locale,limit,cursor,offset})=>({method:"GET",path:addQuery(tenantPath(projectId2,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:z113.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional(),populate:populateSchema,localeFallbacks:z113.boolean().optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,id,locale,populate,localeFallbacks})=>({method:"GET",path:addQuery(tenantPath(projectId2,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:z113.object({projectId:uuidSchema,branch:branchNameSchema,search:z113.string().min(1).optional(),locale:localeSchema.optional(),...paginationShape}).strict().superRefine(paginationRefinement),outputSchema:entriesPageSchema,buildRequest:__name(({projectId:projectId2,branch,search,locale,limit,cursor,offset})=>({method:"GET",path:addQuery(tenantPath(projectId2,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:z113.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z113.string().min(1).max(255),data:entryDataSchema,locale:z113.string().min(1).optional(),documentId:z113.string().min(1).optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,data,locale,documentId})=>({method:"POST",path:tenantPath(projectId2,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:z113.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z113.string().min(1).max(255),id:uuidSchema,data:entryDataSchema,locale:z113.string().min(1).optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,id,data,locale})=>({method:"PUT",path:addQuery(tenantPath(projectId2,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:z113.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional(),fields:z113.record(z113.string(),z113.unknown())}).strict(),outputSchema:z113.unknown(),buildRequest:__name(({projectId:projectId2,branch,typeName,id,locale,fields})=>({method:"PUT",path:addQuery(tenantPath(projectId2,branch,`/entries/${encodeURIComponent(typeName)}/${encodeURIComponent(id)}`),{locale}),body:fields}),"buildRequest"),projectOutput:__name(body=>z113.object({data:z113.unknown()}).parse(body).data,"projectOutput")},"entries.querySql":{domain:"entries",summary:"Run a read-only SQL query against Branch content.",accessScope:"read",effect:"read",inputSchema:z113.object({projectId:uuidSchema,branch:branchNameSchema,sql:z113.string().min(1)}).strict(),outputSchema:z113.object({data:z113.array(z113.record(z113.string(),z113.unknown())),meta:z113.object({rowCount:z113.number().int().nonnegative(),truncated:z113.boolean()})}),buildRequest:__name(({projectId:projectId2,branch,sql})=>({method:"POST",path:tenantPath(projectId2,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:z113.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,id:uuidSchema,locale:localeSchema.optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,id,locale})=>({method:"DELETE",path:addQuery(tenantPath(projectId2,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:z113.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,entries:z113.array(z113.unknown()).max(MAX_BULK_ENTRIES2)}).strict(),outputSchema:BulkCreateEntriesResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,typeName,entries:entries2})=>({method:"POST",path:tenantPath(projectId2,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:z113.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,selection:z113.union([z113.object({ids:z113.array(uuidSchema).min(1).max(MAX_BULK_ENTRIES2)}),z113.object({where:EntryWhereSchema2}),z113.object({updates:z113.array(z113.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:projectId2,branch,typeName,selection,body})=>({method:"POST",path:tenantPath(projectId2,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:z113.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,selection:z113.union([z113.object({ids:z113.array(uuidSchema).min(1).max(MAX_BULK_ENTRIES2)}),z113.object({where:EntryWhereSchema2})]),locale:localeSchema.optional()}).strict(),outputSchema:BulkDeleteEntriesResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,typeName,selection,locale})=>({method:"POST",path:tenantPath(projectId2,branch,`/entries/${encodeURIComponent(typeName)}/bulk-delete`),body:{...selection,locale}}),"buildRequest")}}}});import{z as z114}from"zod";var productionEnvironmentSchema,previewEnvironmentSchema,customEnvironmentSchema,environmentSchema,environmentWriteShape,environmentsOperations,init_environments=__esm({"../../packages/sdk/dist/operations/environments.js"(){"use strict";init_common2();productionEnvironmentSchema=z114.object({id:z114.literal("production"),projectId:uuidSchema,name:z114.string(),kind:z114.literal("production"),sourceBranch:z114.string().min(1),isPublished:z114.boolean(),url:z114.string().nullable()}),previewEnvironmentSchema=z114.object({id:z114.literal("preview"),projectId:uuidSchema,name:z114.string(),kind:z114.literal("preview"),matchedBranchCount:z114.number().int().nonnegative()}),customEnvironmentSchema=z114.object({id:uuidSchema,projectId:uuidSchema,name:z114.string().min(1).max(64),branchPatterns:z114.array(z114.string().min(1).max(255)).min(1),description:z114.string().max(255).nullable(),kind:z114.literal("custom"),matchedBranchCount:z114.number().int().nonnegative()}),environmentSchema=z114.discriminatedUnion("kind",[productionEnvironmentSchema,previewEnvironmentSchema,customEnvironmentSchema]),environmentWriteShape={name:z114.string().trim().min(1).max(64),branchPatterns:z114.array(z114.string().min(1).max(255)).min(1),description:z114.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:z114.object({projectId:uuidSchema}).strict(),outputSchema:z114.array(environmentSchema),buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/environments")}),"buildRequest"),projectOutput:__name(body=>z114.array(environmentSchema).parse(responseData(body)),"projectOutput")},"environments.create":{domain:"environments",summary:"Create a custom compatibility Environment for one site.",accessScope:"write",effect:"mutation",inputSchema:z114.object({projectId:uuidSchema,...environmentWriteShape}).strict(),outputSchema:environmentSchema,buildRequest:__name(({projectId:projectId2,...body})=>({method:"POST",path:managementProjectPath(projectId2,"/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:z114.object({projectId:uuidSchema,environmentId:z114.string().min(1),...environmentWriteShape}).strict(),outputSchema:environmentSchema,buildRequest:__name(({projectId:projectId2,environmentId,...body})=>({method:"PATCH",path:managementProjectPath(projectId2,`/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:z114.object({projectId:uuidSchema,environmentId:z114.string().min(1)}).strict(),outputSchema:z114.object({deletedId:uuidSchema}),buildRequest:__name(({projectId:projectId2,environmentId})=>({method:"DELETE",path:managementProjectPath(projectId2,`/environments/${encodeURIComponent(environmentId)}`),preserveForbidden:!0}),"buildRequest"),projectOutput:__name(body=>z114.object({deletedId:uuidSchema}).parse(responseData(body)),"projectOutput")}}}});import{z as z115}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=z115.object({data:z115.object({path:z115.string(),content:z115.string(),totalLines:z115.number().int().nonnegative()}).passthrough()}),fileGlobOutputSchema=z115.object({data:z115.object({paths:z115.array(z115.string().min(1)).max(2e3),truncated:z115.boolean()})}),fileGrepOutputSchema=z115.object({data:z115.object({matches:z115.array(z115.object({path:z115.string().min(1),line:z115.number().int().positive(),text:z115.string()})).max(200),truncated:z115.boolean()})}),fileWriteInputSchema=z115.object({projectId:uuidSchema,sessionId:uuidSchema,path:z115.string().min(1).max(1024),content:utf8Text(PROJECT_FILE_WRITE_LIMIT_BYTES2,`Content exceeds the ${PROJECT_FILE_WRITE_LIMIT_BYTES2}-byte write limit.`),overwrite:z115.boolean().optional()}).strict(),fileEditInputSchema=z115.object({projectId:uuidSchema,sessionId:uuidSchema,path:z115.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:z115.boolean().optional()}).strict(),fileWriteOutputSchema=sessionEnvelopeSchema.extend({file:z115.object({path:z115.string(),created:z115.boolean(),tip:z115.string().min(1)}).passthrough()}),fileWriteManyInputSchema=z115.object({projectId:uuidSchema,sessionId:uuidSchema,files:z115.array(z115.object({path:z115.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(files2=>files2.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:z115.array(z115.object({path:z115.string(),created:z115.boolean()}).passthrough()),tip:z115.string().min(1)}),fileEditOutputSchema=sessionEnvelopeSchema.extend({file:z115.object({path:z115.string(),replacements:z115.number().int().nonnegative(),tip:z115.string().min(1)}).passthrough()}),fileDeleteOutputSchema=sessionEnvelopeSchema.extend({file:z115.object({path:z115.string(),deleted:z115.literal(!0),tip:z115.string().min(1)})}),fileSearchInputShape={projectId:uuidSchema,branch:branchNameSchema.optional(),sessionId:uuidSchema.optional()};__name(requireBranchOrSession,"requireBranchOrSession");fileReadInputSchema=z115.object({projectId:uuidSchema,branch:branchNameSchema.optional(),sessionId:uuidSchema.optional(),path:z115.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:projectId2,branch,sessionId,path:path52})=>({method:"GET",path:addQuery(projectFilesPath(projectId2,branch,sessionId,"/file"),{path:path52})}),"buildRequest")},"files.glob":{domain:"files",summary:"List bounded safe site file paths from a Branch or owned work session.",accessScope:"read",effect:"read",inputSchema:z115.object({...fileSearchInputShape,pattern:z115.string().min(1).max(300).optional(),limit:z115.number().int().min(1).max(2e3).optional()}).strict().superRefine(requireBranchOrSession),outputSchema:fileGlobOutputSchema,buildRequest:__name(({projectId:projectId2,branch,sessionId,pattern,limit})=>({method:"GET",path:addQuery(projectFilesPath(projectId2,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:z115.object({...fileSearchInputShape,pattern:z115.string().min(1).max(200),include:z115.string().min(1).max(300).optional(),caseInsensitive:z115.boolean().optional(),maxMatches:z115.number().int().min(1).max(200).optional()}).strict().superRefine(requireBranchOrSession),outputSchema:fileGrepOutputSchema,buildRequest:__name(({projectId:projectId2,branch,sessionId,pattern,include,caseInsensitive,maxMatches})=>({method:"GET",path:addQuery(projectFilesPath(projectId2,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:projectId2,sessionId,path:path52,content:content2,overwrite})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/files/write`),body:withoutUndefined({path:path52,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:projectId2,sessionId,files:files2})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/files/write-many`),body:{files:files2}}),"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:projectId2,sessionId,path:path52,oldString,newString,replaceAll})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/files/edit`),body:withoutUndefined({path:path52,oldString,newString,replaceAll})}),"buildRequest")},"files.delete":{domain:"files",summary:"Delete one safe site file in an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z115.object({projectId:uuidSchema,sessionId:uuidSchema,path:z115.string().min(1).max(1024)}).strict(),outputSchema:fileDeleteOutputSchema,buildRequest:__name(({projectId:projectId2,sessionId,path:path52})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/files/delete`),body:{path:path52}}),"buildRequest")}}}});import{z as z116}from"zod";function projectFormResponse(body){return formResponseSchema.parse(body)}function projectFormDetail(body){return formResponseSchema.parse(body).data}function projectFormList(body){return z116.object({data:z116.array(formSchema)}).parse(body).data}function projectFormSubmissionsPage(body,input){let page=z116.object({data:z116.array(formSubmissionSchema),total:z116.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=z116.object({type:z116.enum(["text","email","textarea","number","phone","url","select","checkbox","date","hidden","file"]),label:z116.string(),placeholder:z116.string().optional(),required:z116.boolean().optional(),defaultValue:z116.string().optional(),options:z116.array(z116.string()).optional(),validation:z116.object({minLength:z116.number().optional(),maxLength:z116.number().optional(),min:z116.number().optional(),max:z116.number().optional(),pattern:z116.string().optional(),maxFileSize:z116.number().optional(),accept:z116.array(z116.string()).optional()}).optional()}),FormContentSchema2=z116.object({name:z116.string().min(1).max(255),label:z116.string().min(1).max(255),fields:z116.record(z116.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=z116.object({id:uuidSchema,name:FormContentSchema2.shape.name,label:FormContentSchema2.shape.label,fields:FormContentSchema2.shape.fields,settings:z116.record(z116.string(),z116.unknown()).nullable().optional(),createdAt:z116.string(),updatedAt:z116.string()}).passthrough(),formSchema=rawFormSchema,formResponseSchema=z116.object({data:formSchema}),formSubmissionSchema=z116.object({id:uuidSchema,formId:uuidSchema,projectId:uuidSchema,branch:branchNameSchema,data:z116.record(z116.string(),z116.unknown()),submittedAt:z116.string()}),formSubmissionResponseSchema=z116.object({data:formSubmissionSchema}),formSubmissionsPageSchema=pageSchema(formSubmissionSchema),formSubmissionStatsResponseSchema=z116.object({data:z116.object({total:z116.number().int().nonnegative(),dailyCounts:z116.array(z116.object({date:z116.string(),count:z116.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:z116.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:z116.array(formSchema),buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:tenantPath(projectId2,branch,"/forms")}),"buildRequest"),projectOutput:projectFormList},"forms.get":{domain:"forms",summary:"Read one form definition from a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z116.object({projectId:uuidSchema,branch:branchNameSchema,id:z116.string().min(1).max(255)}).strict(),outputSchema:formSchema,buildRequest:__name(({projectId:projectId2,branch,id})=>({method:"GET",path:tenantPath(projectId2,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:z116.object({projectId:uuidSchema,branch:branchNameSchema,...FormContentSchema2.shape}).strict(),outputSchema:formResponseSchema,buildRequest:__name(({projectId:projectId2,branch,name,label,fields})=>({method:"POST",path:tenantPath(projectId2,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:z116.object({projectId:uuidSchema,branch:branchNameSchema,id:z116.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 issue2 of update.error.issues)context.addIssue({...issue2,path:issue2.path})}),outputSchema:formResponseSchema,buildRequest:__name(({projectId:projectId2,branch,id,name,label,fields})=>({method:"PUT",path:tenantPath(projectId2,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:z116.object({projectId:uuidSchema,branch:branchNameSchema,id:z116.string().min(1).max(255)}).strict(),outputSchema:formResponseSchema,buildRequest:__name(({projectId:projectId2,branch,id})=>({method:"DELETE",path:tenantPath(projectId2,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:z116.object({projectId:uuidSchema,branch:branchNameSchema,id:z116.string().min(1).max(255),...paginationShape,searchQuery:z116.string().max(200).optional(),sortDirection:z116.enum(["asc","desc"]).optional()}).strict().superRefine(paginationRefinement),outputSchema:formSubmissionsPageSchema,buildRequest:__name(({projectId:projectId2,branch,id,limit,cursor,offset,searchQuery,sortDirection})=>({method:"GET",path:addQuery(tenantPath(projectId2,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:z116.object({projectId:uuidSchema,branch:branchNameSchema,id:z116.string().min(1).max(255),submissionId:z116.string().min(1).max(255)}).strict(),outputSchema:formSubmissionSchema,buildRequest:__name(({projectId:projectId2,branch,id,submissionId})=>({method:"GET",path:tenantPath(projectId2,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:z116.object({projectId:uuidSchema,branch:branchNameSchema,id:z116.string().min(1).max(255)}).strict(),outputSchema:formSubmissionStatsResponseSchema.shape.data,buildRequest:__name(({projectId:projectId2,branch,id})=>({method:"GET",path:tenantPath(projectId2,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:z116.object({projectId:uuidSchema,branch:branchNameSchema,id:z116.string().min(1).max(255),submissionId:z116.string().min(1).max(255)}).strict(),outputSchema:formSubmissionSchema,buildRequest:__name(({projectId:projectId2,branch,id,submissionId})=>({method:"DELETE",path:tenantPath(projectId2,branch,`/forms/${encodeURIComponent(id)}/submissions/${encodeURIComponent(submissionId)}`)}),"buildRequest"),projectOutput:__name(body=>formSubmissionResponseSchema.parse(body).data,"projectOutput")}}}});import{z as z117}from"zod";var estimateSchema,generationOperations,init_generation=__esm({"../../packages/sdk/dist/operations/generation.js"(){"use strict";init_common2();estimateSchema=z117.object({costUsd:z117.number(),credits:z117.number().optional(),billingMode:z117.enum(["fimo-credits","provider-account"]).optional(),confidence:z117.enum(["exact","estimated","metered"]),basis:z117.string()}).passthrough(),generationOperations={"generation.estimateModel":{domain:"generation",summary:"Estimate one generation request against an enabled provider model.",accessScope:"read",effect:"read",inputSchema:z117.object({projectId:uuidSchema,model:z117.string().min(1),options:z117.record(z117.string(),z117.unknown())}).strict(),outputSchema:estimateSchema,buildRequest:__name(({projectId:projectId2,model,options})=>({method:"POST",path:`/management/projects/${encodeURIComponent(projectId2)}/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:z117.object({projectId:uuidSchema,branch:branchNameSchema,task:z117.string().min(1),options:z117.record(z117.string(),z117.unknown())}).strict(),outputSchema:estimateSchema,buildRequest:__name(({projectId:projectId2,branch,task,options})=>({method:"POST",path:tenantPath(projectId2,branch,"/assets/generate/estimate"),body:{task,options}}),"buildRequest"),projectOutput:responseData}}}});import{z as z118}from"zod";var historyKindSchema,projectVersionSchema,projectVersionPageSchema,historySummarySchema,restoreResultSchema,historyOperations,init_history=__esm({"../../packages/sdk/dist/operations/history.js"(){"use strict";init_common2();historyKindSchema=z118.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),projectVersionSchema=z118.object({versionId:uuidSchema,commitHash:z118.string(),name:z118.string(),description:z118.string().nullable(),kind:historyKindSchema,createdAt:z118.iso.datetime(),expiresAt:z118.iso.datetime()}),projectVersionPageSchema=z118.object({items:z118.array(projectVersionSchema),nextCursor:z118.string().nullable()}),historySummarySchema=z118.object({usage:z118.object({versionCount:z118.number().int().nonnegative(),snapshotBytes:z118.number().int().nonnegative()}),retentionDays:z118.number().int().positive()}),restoreResultSchema=z118.object({durationMs:z118.number().nonnegative().optional(),warning:z118.string().optional()}),historyOperations={"history.list":{domain:"history",summary:"List restore points for one Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z118.object({projectId:uuidSchema,branch:branchNameSchema,limit:z118.number().int().min(1).max(100),cursor:paginationShape.cursor}).strict(),outputSchema:projectVersionPageSchema,buildRequest:__name(({projectId:projectId2,branch,limit,cursor})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,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:z118.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:historySummarySchema,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:managementBranchPath(projectId2,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:z118.object({projectId:uuidSchema,branch:branchNameSchema,versionId:uuidSchema}).strict(),outputSchema:projectVersionSchema,buildRequest:__name(({projectId:projectId2,branch,versionId})=>({method:"GET",path:managementBranchPath(projectId2,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:z118.object({projectId:uuidSchema,branch:branchNameSchema,name:z118.string().min(1),description:z118.string().optional()}).strict(),outputSchema:projectVersionSchema,buildRequest:__name(({projectId:projectId2,branch,name,description})=>({method:"POST",path:managementBranchPath(projectId2,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:z118.object({projectId:uuidSchema,branch:branchNameSchema,versionId:uuidSchema}).strict(),outputSchema:restoreResultSchema,buildRequest:__name(({projectId:projectId2,branch,versionId})=>({method:"POST",path:managementBranchPath(projectId2,branch,`/versions/${encodeURIComponent(versionId)}/restore`)}),"buildRequest"),projectOutput:__name(body=>restoreResultSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z119}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=z119.number().int().min(1).max(LOG_TAIL_MAX_LIMIT).optional(),publicationStateOutputSchema=z119.object({isPublished:z119.boolean(),publishedAt:z119.iso.datetime().nullable(),publishedVersion:z119.string().nullable()}),publicationOutputSchema=z119.object({id:uuidSchema,status:z119.enum(["queued","building","published","failed","canceled"]),label:z119.string().nullable(),notes:z119.string().nullable(),source:z119.object({branch:branchNameSchema,targetBranch:branchNameSchema,configVersion:z119.string().nullable(),framework:z119.string().nullable(),commit:z119.string().nullable()}),createdAt:z119.iso.datetime(),finishedAt:z119.iso.datetime().nullable(),url:z119.string().nullable(),failureCode:z119.string().nullable()}),publicationsPageOutputSchema=z119.object({items:z119.array(publicationOutputSchema),nextCursor:z119.string().nullable(),retention:z119.object({scope:z119.literal("publication_attempt_record"),records:z119.literal("project_lifetime")})}),publicationLogsOutputSchema=z119.object({status:z119.enum(["ok","unavailable"]),publicationId:uuidSchema,reason:z119.enum(["pending","no_deployment","provider_unavailable"]).nullable(),message:z119.string().nullable(),items:z119.array(z119.object({timestamp:z119.iso.datetime(),phase:z119.enum(["build","deploy"]),stream:z119.enum(["command","stdout","stderr","status","error"]),message:z119.string()}))}),sandboxLogsOutputSchema=z119.object({status:z119.enum(["ok","unavailable"]),reason:z119.enum(["no_sandbox","sandbox_expired","provider_unsupported"]).nullable(),message:z119.string().nullable(),items:z119.array(z119.object({id:z119.string(),timestamp:z119.iso.datetime().nullable(),source:z119.enum(["install","dev-server"]),phase:z119.string(),stream:z119.enum(["combined","stdout","stderr"]),message:z119.string()})),nextCursor:z119.string().nullable(),retention:z119.object({scope:z119.literal("sandbox_process_snapshot"),timestamps:z119.literal("process_start"),droppedOldest:z119.boolean(),phases:z119.array(z119.object({phase:z119.string(),source:z119.enum(["install","dev-server"]),status:z119.string(),startedAt:z119.iso.datetime().nullable(),exitCode:z119.number().int().nullable(),events:z119.number().int().nonnegative()}))}).nullable()}),previewLocationOutputSchema=z119.object({url:z119.string(),branch:branchNameSchema}),previewOpenOutputSchema=z119.object({url:z119.url(),expiresAt:z119.iso.datetime().nullable()}),publishOutputSchema=z119.object({success:z119.boolean(),message:z119.string().optional(),firstPublish:z119.boolean(),publicationId:z119.string().optional(),url:z119.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:z119.object({projectId:uuidSchema}).strict(),outputSchema:publicationStateOutputSchema,buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/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:z119.object({projectId:uuidSchema,limit:z119.number().int().min(1).max(100).optional(),cursor:paginationShape.cursor}).strict(),outputSchema:publicationsPageOutputSchema,buildRequest:__name(({projectId:projectId2,limit,cursor})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,"/publications"),{limit,before:cursor})}),"buildRequest"),projectOutput:projectPublicationsPage},"publications.get":{domain:"publications",summary:"Read one durable publication attempt.",accessScope:"read",effect:"read",inputSchema:z119.object({projectId:uuidSchema,publicationId:z119.string().min(1)}).strict(),outputSchema:publicationOutputSchema,buildRequest:__name(({projectId:projectId2,publicationId})=>({method:"GET",path:managementProjectPath(projectId2,`/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:z119.object({projectId:uuidSchema,label:z119.string().trim().min(1).max(120).optional(),notes:z119.string().max(2e4).optional()}).strict(),outputSchema:publishOutputSchema,buildRequest:__name(({projectId:projectId2,label,notes})=>({method:"POST",path:managementProjectPath(projectId2,"/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:z119.object({projectId:uuidSchema,publicationId:z119.string().min(1),limit:logTailLimitSchema}).strict(),outputSchema:publicationLogsOutputSchema,buildRequest:__name(({projectId:projectId2,publicationId,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,`/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:z119.object({projectId:uuidSchema,branch:branchNameSchema,limit:logTailLimitSchema,cursor:paginationShape.cursor}).strict(),outputSchema:sandboxLogsOutputSchema,buildRequest:__name(({projectId:projectId2,branch,limit,cursor})=>({method:"GET",path:addQuery(managementBranchPath(projectId2,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:z119.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:previewLocationOutputSchema,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:managementBranchPath(projectId2,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:z119.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:previewOpenOutputSchema,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:managementBranchPath(projectId2,branch,"/sandbox")}),"buildRequest"),projectOutput:__name(body=>previewOpenOutputSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z120}from"zod";var integrationIdSchema,toolEffectSchema,integrationSchema,integrationToolSchema,integrationGuideSchema,integrationRunResultSchema,runInputShape,integrationsOperations,init_integrations=__esm({"../../packages/sdk/dist/operations/integrations.js"(){"use strict";init_common2();integrationIdSchema=z120.string().min(2).max(120).regex(/^[a-z0-9][a-z0-9_-]*$/),toolEffectSchema=z120.enum(["read","write","delete","financial"]),integrationSchema=z120.object({id:z120.string(),kind:z120.enum(["catalog","custom","builtIn"]),name:z120.string(),description:z120.string(),host:z120.string().nullable(),readOnly:z120.boolean(),installed:z120.boolean(),enabled:z120.boolean(),accountName:z120.string().nullable(),settings:z120.array(z120.object({key:z120.string(),label:z120.string(),description:z120.string().nullable(),required:z120.boolean()})),settingsValues:z120.record(z120.string(),z120.string()),missingSettings:z120.array(z120.string())}),integrationToolSchema=z120.object({integrationId:z120.string(),integrationName:z120.string(),key:z120.string(),name:z120.string(),description:z120.string(),effect:toolEffectSchema,input:z120.record(z120.string(),z120.unknown()).optional()}),integrationGuideSchema=z120.object({integrationId:z120.string(),name:z120.string(),description:z120.string(),content:z120.string()}),integrationRunResultSchema=z120.discriminatedUnion("status",[z120.object({status:z120.literal("ok"),output:z120.record(z120.string(),z120.unknown())}),z120.object({status:z120.literal("approval_required"),request:z120.string(),approveUrl:z120.string(),reason:z120.string(),integration:z120.object({id:z120.string(),name:z120.string()}),tool:z120.object({key:z120.string(),name:z120.string(),effect:toolEffectSchema}),input:z120.record(z120.string(),z120.unknown()),canAlwaysAllow:z120.boolean()}),z120.object({status:z120.literal("blocked"),reason:z120.string()})]),runInputShape={projectId:uuidSchema,integrationId:integrationIdSchema,tool:z120.string().min(1).max(120),input:z120.record(z120.string(),z120.unknown()).default({})},integrationsOperations={"integrations.list":{domain:"integrations",summary:"List the integrations this site can use, such as Google Search Console: whether each is on for the site, its connected account, and settings it still needs.",accessScope:"read",effect:"read",inputSchema:z120.object({projectId:uuidSchema}).strict(),outputSchema:z120.array(integrationSchema),buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/integrations/catalog")}),"buildRequest"),projectOutput:__name(body=>z120.array(integrationSchema).parse(responseData(body)),"projectOutput")},"integrations.tools":{domain:"integrations",summary:`Find the tools of the integrations on for this site by what you need, in plain words ("clicks by page", "sitemap"): the best matches, each with its key, the start of what it does and whether it reads or changes data. Pass a tool key to get that tool's input JSON schema, before you run it.`,accessScope:"read",effect:"read",inputSchema:z120.object({projectId:uuidSchema,search:z120.string().max(200).optional(),integrationId:integrationIdSchema.optional(),tool:z120.string().min(1).max(120).optional()}).strict(),outputSchema:z120.array(integrationToolSchema),buildRequest:__name(({projectId:projectId2,search,integrationId,tool})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,"/integrations/tools"),{search,integration:integrationId,tool})}),"buildRequest"),projectOutput:__name(body=>z120.array(integrationToolSchema).parse(responseData(body)),"projectOutput")},"integrations.guide":{domain:"integrations",summary:"Read an integration's guide before running its tools the first time: which tool answers which question, and how to read its numbers.",accessScope:"read",effect:"read",inputSchema:z120.object({projectId:uuidSchema,integrationId:integrationIdSchema}).strict(),outputSchema:integrationGuideSchema,buildRequest:__name(({projectId:projectId2,integrationId})=>({method:"GET",path:managementProjectPath(projectId2,`/integrations/${encodeURIComponent(integrationId)}/guide`)}),"buildRequest"),projectOutput:__name(body=>integrationGuideSchema.parse(responseData(body)),"projectOutput")},"integrations.run":{domain:"integrations",summary:"Run an integration tool that reads data, with the input its JSON schema describes. Tools that change data in the outside service run with integrations.write.",accessScope:"read",effect:"read",inputSchema:z120.object(runInputShape).strict(),outputSchema:integrationRunResultSchema,buildRequest:__name(({projectId:projectId2,integrationId,tool,input})=>({method:"POST",path:managementProjectPath(projectId2,`/integrations/${encodeURIComponent(integrationId)}/call`),body:{tool,input,readOnly:!0}}),"buildRequest"),projectOutput:__name(body=>integrationRunResultSchema.parse(responseData(body)),"projectOutput")},"integrations.write":{domain:"integrations",summary:"Run an integration tool that changes data in the outside service, such as submitting a sitemap to Google, only when the user asked for that change. Unless the site always allows the tool, the answer is approval_required with an approveUrl to give the user; once they allowed it in Fimo, call again with the exact same tool and input plus the approval code they paste back. A code works for one hour.",accessScope:"write",effect:"mutation",inputSchema:z120.object({...runInputShape,approval:z120.string().min(1).max(4e3).optional()}).strict(),outputSchema:integrationRunResultSchema,buildRequest:__name(({projectId:projectId2,integrationId,tool,input,approval})=>({method:"POST",path:managementProjectPath(projectId2,`/integrations/${encodeURIComponent(integrationId)}/call`),body:withoutUndefined({tool,input,approval})}),"buildRequest"),projectOutput:__name(body=>integrationRunResultSchema.parse(responseData(body)),"projectOutput")},"integrations.setEnabled":{domain:"integrations",summary:"Turn an integration on or off for this site. Turning one on may need its account connected first.",accessScope:"write",effect:"mutation",inputSchema:z120.object({projectId:uuidSchema,integrationId:integrationIdSchema,enabled:z120.boolean()}).strict(),outputSchema:z120.object({ok:z120.literal(!0)}),buildRequest:__name(({projectId:projectId2,integrationId,enabled})=>({method:"PUT",path:managementProjectPath(projectId2,`/integrations/${encodeURIComponent(integrationId)}`),body:{enabled}}),"buildRequest"),projectOutput:__name(()=>({ok:!0}),"projectOutput")},"integrations.updateSettings":{domain:"integrations",summary:"Change an integration's settings for this site. A choice must be one the connected account offers.",accessScope:"write",effect:"mutation",inputSchema:z120.object({projectId:uuidSchema,integrationId:integrationIdSchema,settings:z120.record(z120.string(),z120.string().max(500))}).strict(),outputSchema:z120.object({ok:z120.literal(!0)}),buildRequest:__name(({projectId:projectId2,integrationId,settings})=>({method:"PUT",path:managementProjectPath(projectId2,`/integrations/${encodeURIComponent(integrationId)}/settings`),body:{settings}}),"buildRequest"),projectOutput:__name(()=>({ok:!0}),"projectOutput")}}}});import{z as z121}from"zod";var knowledgeSchema,knowledgeOperations,init_knowledge=__esm({"../../packages/sdk/dist/operations/knowledge.js"(){"use strict";init_common2();knowledgeSchema=z121.object({content:z121.string(),updatedAt:z121.string().nullable(),updatedBy:z121.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:z121.object({projectId:uuidSchema}).strict(),outputSchema:knowledgeSchema,buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/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:z121.object({projectId:uuidSchema,content:z121.string()}).strict(),outputSchema:knowledgeSchema,buildRequest:__name(({projectId:projectId2,content:content2})=>({method:"PUT",path:managementProjectPath(projectId2,"/knowledge"),body:{content:content2}}),"buildRequest"),projectOutput:__name(body=>knowledgeSchema.parse(responseData(body)),"projectOutput")}}}});import{z as z122}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=z122.object({key:z122.string(),value:z122.string().optional(),defaultValue:z122.string(),locale:z122.string()}),labelResponseSchema=createResponseSchema2(TranslationDTOSchema2),labelListOutputSchema=z122.object({data:z122.array(z122.union([TranslationDTOSchema2,z122.object({key:z122.string(),values:z122.record(z122.string(),z122.string())})]))}),labelUpsertOutputSchema=z122.object({created:z122.number().int().nonnegative(),updated:z122.number().int().nonnegative(),deleted:z122.number().int().nonnegative(),defaultLocale:z122.string(),locales:z122.array(z122.string())}),labelDeleteOutputSchema=z122.object({key:z122.string(),locale:z122.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:z122.object({projectId:uuidSchema,branch:branchNameSchema,locale:localeSchema.optional()}).strict(),outputSchema:labelListOutputSchema,buildRequest:__name(({projectId:projectId2,branch,locale})=>({method:"GET",path:addQuery(tenantPath(projectId2,branch,"/labels"),{locale})}),"buildRequest")},"labels.get":{domain:"labels",summary:"Read one localized label by locale and key.",accessScope:"read",effect:"read",inputSchema:z122.object({projectId:uuidSchema,branch:branchNameSchema,locale:localeSchema,key:z122.string().min(1).max(255)}).strict(),outputSchema:labelResponseSchema,buildRequest:__name(({projectId:projectId2,branch,locale,key})=>({method:"GET",path:tenantPath(projectId2,branch,`/labels/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`)}),"buildRequest")},"labels.set":{domain:"labels",summary:"Create or set one localized label.",accessScope:"write",effect:"mutation",inputSchema:z122.object({projectId:uuidSchema,branch:branchNameSchema,key:z122.string(),value:z122.string(),locale:z122.string().optional()}).strict(),outputSchema:TranslationDTOSchema2,buildRequest:__name(({projectId:projectId2,branch,key,value,locale})=>({method:"POST",path:tenantPath(projectId2,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:z122.object({projectId:uuidSchema,branch:branchNameSchema,records:z122.array(z122.object({key:z122.string(),value:z122.string(),locale:z122.string().optional()}))}).strict(),outputSchema:labelUpsertOutputSchema,buildRequest:__name(({projectId:projectId2,branch,records})=>({method:"POST",path:tenantPath(projectId2,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:z122.object({projectId:uuidSchema,branch:branchNameSchema,locale:z122.string().optional(),key:z122.string()}).strict(),outputSchema:labelDeleteOutputSchema,buildRequest:__name(({projectId:projectId2,branch,locale,key})=>({method:"DELETE",path:tenantPath(projectId2,branch,locale?`/labels/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`:`/labels/${encodeURIComponent(key)}`)}),"buildRequest"),projectOutput:__name(body=>responseValue(labelDeleteOutputSchema,body),"projectOutput")}}}});import{z as z123}from"zod";var projectLocaleCoverageSchema,ProjectLocaleStatsResponseSchema2,projectLocaleInputSchema,ProjectLocaleMutationResponseSchema2,RemoveProjectLocaleResponseSchema2,localesOperations,init_locales=__esm({"../../packages/sdk/dist/operations/locales.js"(){"use strict";init_common2();projectLocaleCoverageSchema=z123.object({translated:z123.number().int().nonnegative(),total:z123.number().int().nonnegative()}),ProjectLocaleStatsResponseSchema2=createResponseSchema2(z123.object({defaultLocale:z123.string(),locales:z123.array(z123.object({locale:z123.string(),isDefault:z123.boolean(),entries:projectLocaleCoverageSchema,labels:projectLocaleCoverageSchema}))})),projectLocaleInputSchema=z123.string().min(1).max(40),ProjectLocaleMutationResponseSchema2=createResponseSchema2(z123.object({locale:z123.string()})),RemoveProjectLocaleResponseSchema2=createResponseSchema2(z123.object({locale:z123.string(),entriesDeleted:z123.number().int().nonnegative(),labelsDeleted:z123.number().int().nonnegative()})),localesOperations={"locales.list":{domain:"locales",summary:"List configured locales and content coverage on a Fimo Branch.",accessScope:"read",effect:"read",inputSchema:z123.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:ProjectLocaleStatsResponseSchema2,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:managementBranchPath(projectId2,branch,"/locales/stats")}),"buildRequest")},"locales.add":{domain:"locales",summary:"Add a configured locale to a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z123.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:ProjectLocaleMutationResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,locale})=>({method:"POST",path:managementBranchPath(projectId2,branch,"/locales"),body:{locale}}),"buildRequest")},"locales.setDefault":{domain:"locales",summary:"Set the default configured locale on a Fimo Branch.",accessScope:"write",effect:"mutation",inputSchema:z123.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:ProjectLocaleMutationResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,locale})=>({method:"PUT",path:managementBranchPath(projectId2,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:z123.object({projectId:uuidSchema,branch:branchNameSchema,locale:projectLocaleInputSchema}).strict(),outputSchema:RemoveProjectLocaleResponseSchema2,buildRequest:__name(({projectId:projectId2,branch,locale})=>({method:"DELETE",path:managementBranchPath(projectId2,branch,`/locales/${encodeURIComponent(locale)}`)}),"buildRequest")}}}});import{z as z124}from"zod";var organizationSchema,organizationMemberSchema,organizationInvitationSchema,referralSummarySchema,organizationsOperations,init_organizations=__esm({"../../packages/sdk/dist/operations/organizations.js"(){"use strict";init_common2();organizationSchema=z124.object({id:z124.string().min(1),name:z124.string(),slug:z124.string()}),organizationMemberSchema=z124.object({id:z124.string().min(1),role:z124.string(),createdAt:z124.string().optional(),user:z124.object({id:z124.string().min(1),name:z124.string().nullable().optional(),email:z124.string().nullable().optional()}).optional()}),organizationInvitationSchema=z124.object({id:z124.string().min(1),email:z124.email(),role:z124.string(),organizationId:z124.string().min(1),inviterId:z124.string().min(1),status:z124.string(),expiresAt:z124.string(),createdAt:z124.string()}).passthrough(),referralSummarySchema=z124.object({counts:z124.object({signed_up:z124.number().int(),activated:z124.number().int()}),credits:z124.object({total:z124.number().int(),earned:z124.number().int().optional()})}),organizationsOperations={"organizations.list":{domain:"organizations",summary:"List organizations the authenticated user belongs to.",accessScope:"read",effect:"read",inputSchema:z124.object({}).strict(),outputSchema:createResponseSchema2(z124.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:z124.object({organizationId:z124.string().min(1)}).strict(),outputSchema:z124.array(organizationMemberSchema),buildRequest:__name(({organizationId})=>({method:"GET",path:`/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`}),"buildRequest"),projectOutput:__name(body=>z124.object({members:z124.array(organizationMemberSchema)}).nullable().parse(body)?.members??[],"projectOutput")},"organizations.invite":{domain:"organizations",summary:"Invite a user to an organization.",accessScope:"write",effect:"mutation",inputSchema:z124.object({organizationId:z124.string().min(1),email:z124.email(),role:z124.enum(["owner","admin","member"]),resend:z124.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:z124.object({userId:z124.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 z125}from"zod";var projectSchema,projectResponseSchema,transferResultSchema,projectsOperations,init_projects=__esm({"../../packages/sdk/dist/operations/projects.js"(){"use strict";init_common2();projectSchema=z125.object({id:uuidSchema,name:z125.string(),displayName:z125.string().nullable(),organizationId:z125.string().nullable(),defaultBranch:branchNameSchema.optional(),productionSourceBranch:branchNameSchema.optional(),status:z125.string().optional(),appUrl:z125.string().nullable().optional()}).passthrough(),projectResponseSchema=z125.object({data:projectSchema}),transferResultSchema=z125.object({projectId:z125.string(),sourceOrganizationId:z125.string(),targetOrganizationId:z125.string(),movedThreads:z125.number().int().nonnegative(),revokedInvites:z125.number().int().nonnegative(),revokedGrants:z125.number().int().nonnegative(),preservedGrants:z125.number().int().nonnegative(),warnings:z125.array(z125.string())}),projectsOperations={"projects.list":{domain:"projects",summary:"List the Fimo sites the authenticated user can access.",accessScope:"read",effect:"read",inputSchema:z125.object({organizationId:z125.string().min(1).optional()}).strict(),outputSchema:z125.object({data:z125.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:z125.object({projectId:uuidSchema}).strict(),outputSchema:projectResponseSchema,buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"")}),"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:z125.object({organizationId:z125.string().min(1),displayName:z125.string().min(1).optional(),origin:z125.enum(["scratch","migration"]).optional(),starter:z125.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:z125.object({projectId:uuidSchema,targetOrganizationId:z125.string().min(1)}).strict(),outputSchema:transferResultSchema,buildRequest:__name(({projectId:projectId2,targetOrganizationId})=>({method:"POST",path:managementProjectPath(projectId2,"/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:z125.object({projectId:uuidSchema,email:z125.email(),role:z125.enum(["full","edit","comment","view"])}).strict(),outputSchema:z125.object({id:z125.string().min(1)}),buildRequest:__name(({projectId:projectId2,email,role})=>({method:"POST",path:managementProjectPath(projectId2,"/invites"),body:{email,roleKey:role}}),"buildRequest"),projectOutput:__name(body=>({id:z125.object({id:z125.string().min(1)}).parse(responseData(body)).id}),"projectOutput")},"projects.delete":{domain:"projects",summary:"Permanently delete a Fimo site.",accessScope:"write",effect:"mutation",inputSchema:z125.object({projectId:uuidSchema}).strict(),outputSchema:z125.unknown(),buildRequest:__name(({projectId:projectId2})=>({method:"DELETE",path:managementProjectPath(projectId2,""),body:{}}),"buildRequest")}}}});import{z as z126}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=z126.iso.datetime(),scheduleStatusSchema=z126.enum(["ok","failed"]),runStatusSchema=z126.enum(["queued","running","succeeded","failed","skipped"]),scheduleSchema=z126.object({id:uuidSchema,createdAt:dateSchema,updatedAt:dateSchema,projectId:uuidSchema,branch:z126.string().min(1),name:z126.string().min(1),cron:z126.string().min(1),command:z126.string().min(1),secretKeys:z126.array(z126.string().min(1)),enabled:z126.boolean(),lastRunAt:dateSchema.nullable(),lastStatus:scheduleStatusSchema.nullable(),lastError:z126.string().nullable(),overPolicyReasons:z126.array(z126.string()).optional()}).passthrough(),usageSchema=z126.object({runCount:z126.number().int().nonnegative(),runsWithOutput:z126.number().int().nonnegative()}),policySchema=z126.object({maxRuns:z126.number().int().positive(),retentionDays:z126.number().int().positive().nullable(),outputRetentionDays:z126.number().int().positive(),maxOutputBytes:z126.number().int().positive()}).passthrough(),planSchema=z126.object({code:z126.enum(["Free","PAYG","Starter","Premium","Pro"]),source:z126.enum(["cached_subscription","free_fallback"]),activeSchedules:z126.object({used:z126.number().int().nonnegative(),limit:z126.number().int().positive()}),minCadenceMinutes:z126.number().int().positive(),maxRunMs:z126.number().int().positive(),concurrency:z126.object({used:z126.number().int().nonnegative(),limit:z126.number().int().positive()}),compute:z126.object({settledMs:z126.number().int().nonnegative(),activeMs:z126.number().int().nonnegative(),reservedMs:z126.number().int().nonnegative().optional(),includedMs:z126.number().int().positive(),remainingMs:z126.number().int().nonnegative(),resetsAt:dateSchema}),state:z126.enum(["ok","near_limit","exhausted","over_policy"]),overPolicyReasons:z126.array(z126.string())}).passthrough(),runSchema=z126.object({id:uuidSchema,scheduleId:uuidSchema,projectId:uuidSchema,branch:z126.string().min(1),scheduleName:z126.string().min(1),command:z126.string().min(1),status:runStatusSchema,trigger:z126.enum(["cron","ui","cli"]),triggeredBy:z126.object({id:z126.string().min(1),name:z126.string().min(1)}).nullable(),queuedAt:dateSchema,startedAt:dateSchema.nullable(),finishedAt:dateSchema.nullable(),exitCode:z126.number().int().nullable(),errorCode:z126.string().nullable(),error:z126.string().nullable(),outputBytes:z126.number().int().nonnegative(),outputTruncated:z126.boolean(),outputExpiresAt:dateSchema.nullable(),metadataExpiresAt:dateSchema.nullable()}).passthrough(),runDetailSchema=runSchema.extend({output:z126.string().nullable(),secretSnapshot:z126.object({state:z126.enum(["pending","resolved","failed"]),capturedAt:dateSchema.nullable(),items:z126.array(z126.object({key:z126.string().min(1),updatedAt:dateSchema.nullable(),resolution:z126.enum(["resolved","missing","deleted","recreated","rotated"])}))})}),overviewSchema=z126.object({items:z126.array(scheduleSchema),usage:usageSchema,policy:policySchema,plan:planSchema}),detailSchema=z126.object({schedule:scheduleSchema,usage:usageSchema,policy:policySchema,plan:planSchema}).passthrough(),runsPageSchema=z126.object({items:z126.array(runSchema),nextCursor:z126.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:z126.string().min(1).max(120),cron:z126.string().min(1).max(120),command:z126.string().min(1).max(500),secretKeys:z126.array(z126.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:z126.object({...scheduleContextShape}).strict(),outputSchema:z126.array(scheduleSchema),buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",context:{branch},path:managementProjectPath(projectId2,"/schedules")}),"buildRequest"),projectOutput:__name(body=>z126.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:z126.object({...scheduleContextShape}).strict(),outputSchema:overviewSchema,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",context:{branch},path:managementProjectPath(projectId2,"/schedules/overview")}),"buildRequest"),projectOutput:projectOverview},"schedules.get":{domain:"schedules",summary:"Read one schedule with usage and plan limits.",accessScope:"read",effect:"read",inputSchema:z126.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:detailSchema,buildRequest:__name(({projectId:projectId2,branch,scheduleId})=>({method:"GET",context:{branch},path:managementProjectPath(projectId2,`/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:z126.object({...scheduleContextShape,...scheduleWriteShape,enabled:z126.boolean().optional()}).strict(),outputSchema:scheduleSchema,buildRequest:__name(({projectId:projectId2,branch,...body})=>({method:"POST",context:{branch},path:managementProjectPath(projectId2,"/schedules"),body}),"buildRequest"),projectOutput:projectSchedule},"schedules.update":{domain:"schedules",summary:"Update a recurring command schedule.",accessScope:"agents",effect:"mutation",inputSchema:z126.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:projectId2,branch,scheduleId,...update})=>({method:"PATCH",context:{branch},path:managementProjectPath(projectId2,`/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:z126.object({...scheduleContextShape,scheduleId:uuidSchema,enabled:z126.boolean()}).strict(),outputSchema:scheduleSchema,buildRequest:__name(({projectId:projectId2,branch,scheduleId,enabled})=>({method:"POST",context:{branch},path:managementProjectPath(projectId2,`/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:z126.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:runSchema,buildRequest:__name(({projectId:projectId2,branch,scheduleId})=>({method:"POST",context:{branch},path:managementProjectPath(projectId2,`/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:z126.object({...scheduleContextShape,scheduleId:uuidSchema,limit:z126.number().int().min(1).max(100).optional(),cursor:paginationShape.cursor,status:runStatusSchema.optional()}).strict(),outputSchema:runsPageSchema,buildRequest:__name(({projectId:projectId2,branch,scheduleId,limit,cursor,status})=>({method:"GET",context:{branch},path:addQuery(managementProjectPath(projectId2,`/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:z126.object({...scheduleContextShape,runId:uuidSchema}).strict(),outputSchema:runDetailSchema,buildRequest:__name(({projectId:projectId2,branch,runId})=>({method:"GET",context:{branch},path:managementProjectPath(projectId2,`/schedules/runs/${encodeURIComponent(runId)}`)}),"buildRequest"),projectOutput:projectRunDetail},"schedules.delete":{domain:"schedules",summary:"Delete one site schedule.",accessScope:"agents",effect:"mutation",inputSchema:z126.object({...scheduleContextShape,scheduleId:uuidSchema}).strict(),outputSchema:z126.object({ok:z126.literal(!0)}),buildRequest:__name(({projectId:projectId2,branch,scheduleId})=>({method:"DELETE",context:{branch},path:managementProjectPath(projectId2,`/schedules/${encodeURIComponent(scheduleId)}`)}),"buildRequest"),projectOutput:__name(body=>z126.object({ok:z126.literal(!0)}).parse(responseData(body)),"projectOutput")}}}});import{z as z127}from"zod";function projectSchemaDefinition(body){return z127.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=z127.object({id:z127.string(),name:z127.string(),label:z127.string(),isSingleton:z127.boolean(),slugUnique:z127.boolean(),i18n:z127.record(z127.string(),z127.unknown()),groups:z127.array(z127.record(z127.string(),z127.unknown())),fields:z127.record(z127.string(),z127.unknown()),createdAt:z127.string(),updatedAt:z127.string()}).passthrough(),schemaListOutputSchema=z127.object({contentTypes:z127.array(contentTypeSchema)}),schemaMutationOutputSchema=sessionEnvelopeSchema.extend({schema:z127.object({typeName:z127.string().min(1).max(255),generatedPaths:z127.array(z127.string().min(1)).max(1e3),tip:z127.string().min(1)})}),schemaDefinitionInputSchema=z127.record(z127.string(),z127.unknown());__name(projectSchemaDefinition,"projectSchemaDefinition");schemasOperations={"schemas.list":{domain:"schemas",summary:"List content schemas on a durable Branch.",accessScope:"read",effect:"read",inputSchema:z127.object({projectId:uuidSchema,branch:branchNameSchema}).strict(),outputSchema:schemaListOutputSchema,buildRequest:__name(({projectId:projectId2,branch})=>({method:"GET",path:tenantPath(projectId2,branch,"/schema")}),"buildRequest")},"schemas.get":{domain:"schemas",summary:"Get one complete content schema from a durable Branch.",accessScope:"read",effect:"read",inputSchema:z127.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z127.string().min(1).max(255)}).strict(),outputSchema:contentTypeSchema,buildRequest:__name(({projectId:projectId2,branch,typeName})=>({method:"GET",path:tenantPath(projectId2,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:z127.object({projectId:uuidSchema,branch:branchNameSchema,contentTypes:z127.array(schemaDefinitionInputSchema).min(1).max(100),operations:z127.array(z127.record(z127.string(),z127.unknown())).optional()}).strict(),outputSchema:z127.array(z127.unknown()),buildRequest:__name(({projectId:projectId2,branch,contentTypes,operations})=>({method:"POST",path:tenantPath(projectId2,branch,"/schema/batch"),body:withoutUndefined({contentTypes,operations:operations?.length?operations:void 0})}),"buildRequest"),projectOutput:__name(body=>z127.object({data:z127.array(z127.unknown())}).parse(body).data,"projectOutput")},"schemas.deleteFromBranch":{domain:"schemas",summary:"Delete a content schema directly from a Fimo Branch.",accessScope:"code",effect:"mutation",inputSchema:z127.object({projectId:uuidSchema,branch:branchNameSchema,typeName:z127.string().min(1).max(255)}).strict(),outputSchema:z127.unknown(),buildRequest:__name(({projectId:projectId2,branch,typeName})=>({method:"DELETE",path:tenantPath(projectId2,branch,`/schema/types/${encodeURIComponent(typeName)}`)}),"buildRequest"),projectOutput:__name(body=>z127.object({data:z127.unknown()}).parse(body).data,"projectOutput")},"schemas.create":{domain:"schemas",summary:"Create a content schema inside an owned work session.",accessScope:"code",effect:"mutation",inputSchema:z127.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z127.string().min(1).max(255),definition:schemaDefinitionInputSchema}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId:projectId2,sessionId,typeName,definition})=>({method:"POST",path:managementProjectPath(projectId2,`/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:z127.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z127.string().min(1).max(255),definition:schemaDefinitionInputSchema,renameFrom:z127.string().max(255).optional()}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId:projectId2,sessionId,typeName,definition,renameFrom})=>({method:"POST",path:managementProjectPath(projectId2,`/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:z127.object({projectId:uuidSchema,sessionId:uuidSchema,typeName:z127.string().min(1).max(255)}).strict(),outputSchema:schemaMutationOutputSchema,buildRequest:__name(({projectId:projectId2,sessionId,typeName})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/schema`),body:{kind:"delete",typeName}}),"buildRequest")}}}});import{z as z128}from"zod";var environmentSchema2,secretKindSchema,projectSecretSchema,secretWriteInputSchema,secretsOperations,init_secrets=__esm({"../../packages/sdk/dist/operations/secrets.js"(){"use strict";init_common2();environmentSchema2=z128.union([z128.literal("production"),z128.literal("preview"),uuidSchema]),secretKindSchema=z128.enum(["variable","secret"]),projectSecretSchema=z128.object({id:z128.string().min(1),projectId:z128.string().min(1),key:z128.string().min(1),kind:secretKindSchema,exposure:z128.enum(["public","private"]),environment:environmentSchema2,value:z128.string().optional(),maskedValue:z128.string().optional(),createdAt:z128.string(),updatedAt:z128.string()}),secretWriteInputSchema=z128.object({projectId:uuidSchema,key:z128.string().min(1).max(255),kind:secretKindSchema,value:z128.string(),environment:environmentSchema2}),secretsOperations={"secrets.list":{domain:"secrets",summary:"List public variables or masked secrets for one site Environment.",accessScope:"read",effect:"read",inputSchema:z128.object({projectId:uuidSchema,environment:environmentSchema2,kind:secretKindSchema.optional()}).strict(),outputSchema:z128.array(projectSecretSchema),buildRequest:__name(({projectId:projectId2,environment,kind})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,"/secrets"),{environment,kind})}),"buildRequest"),projectOutput:__name(body=>z128.array(projectSecretSchema).parse(responseData(body)),"projectOutput")},"secrets.create":{domain:"secrets",summary:"Create a public variable, private variable, or secret for one site Environment.",accessScope:"write",effect:"mutation",inputSchema:secretWriteInputSchema.extend({exposure:z128.enum(["public","private"]).optional()}).strict(),outputSchema:projectSecretSchema,buildRequest:__name(({projectId:projectId2,...body})=>({method:"POST",path:managementProjectPath(projectId2,"/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:projectId2,key,...body})=>({method:"PATCH",path:managementProjectPath(projectId2,`/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:z128.object({projectId:uuidSchema,key:z128.string().min(1),kind:secretKindSchema,environment:environmentSchema2}).strict(),outputSchema:z128.unknown(),buildRequest:__name(({projectId:projectId2,key,kind,environment})=>({method:"DELETE",path:addQuery(managementProjectPath(projectId2,`/secrets/${encodeURIComponent(key)}`),{kind,environment})}),"buildRequest")},"environments.resolve":{domain:"environments",summary:"Resolve which compatibility Environment receives one site Branch.",accessScope:"read",effect:"read",inputSchema:z128.object({projectId:uuidSchema,branch:z128.string().min(1)}).strict(),outputSchema:z128.object({branch:z128.string().min(1),environment:environmentSchema2}),buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,"/branches"),{includeAgentEnvs:!0})}),"buildRequest"),projectOutput:__name((body,input)=>{let branches=z128.array(z128.object({branch:z128.string().optional(),env:z128.string().optional(),parentBranch:z128.string().nullable().optional(),parentEnv:z128.string().nullable().optional(),resolvedEnvironment:z128.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 z129}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,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=z129.object({status:z129.literal("passed")}).passthrough(),sessionConflictSummarySchema=z129.object({surface:surfaceNameSchema,key:z129.string().min(1),kind:z129.string().optional(),description:z129.string(),path:z129.string().optional()}).passthrough(),surfaceDeltaItemSchema=z129.object({verb:z129.enum(["added","removed","changed","conflict"]),key:z129.string(),detail:z129.string().optional(),origin:z129.enum(["committed-ahead","local-uncommitted"]).optional(),meta:z129.record(z129.string(),z129.unknown()).optional()}).passthrough(),perSurfaceDeltaSchema=z129.object({surface:surfaceNameSchema,status:z129.enum(["ok","timed_out","failed","unchanged"]),durationMs:z129.number().int().nonnegative().optional(),changedCount:z129.number().int().nonnegative(),conflictCount:z129.number().int().nonnegative(),items:z129.array(surfaceDeltaItemSchema).max(1e3).optional(),truncated:z129.boolean().optional(),error:z129.string().optional()}).passthrough(),sessionChangesSchema=z129.object({fromBranch:branchNameSchema.optional(),toBranch:branchNameSchema.optional(),generatedAt:z129.iso.datetime(),surfaces:z129.array(perSurfaceDeltaSchema),crossSurface:z129.array(crossSurfaceFindingSchema).optional(),fingerprint:z129.string()}).passthrough(),projectScriptStatusSchema=z129.enum(["passed","failed","unavailable"]),sessionOperationResultSchema=z129.discriminatedUnion("operation",[z129.object({operation:z129.literal("dependencies_install"),repairedInstallPolicy:z129.boolean(),tip:z129.string()}),z129.object({operation:z129.literal("schemas_sync"),tip:z129.string()}),z129.object({operation:z129.literal("typecheck"),status:projectScriptStatusSchema,output:z129.string()}),z129.object({operation:z129.literal("lint"),status:projectScriptStatusSchema,output:z129.string()})]),conflictSchema2=z129.object({surface:surfaceNameSchema,key:z129.string(),kind:z129.enum(["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"]).optional(),description:z129.string(),parentValue:z129.unknown().optional(),childValue:z129.unknown().optional(),conflictingFields:z129.array(z129.string()).optional(),code:z129.object({path:z129.string(),unresolvable:z129.boolean().optional(),reason:z129.string().optional(),targetCommits:z129.array(z129.object({sha:z129.string(),subject:z129.string(),body:z129.string().optional(),author:z129.string(),date:z129.string()})).optional()}).optional()}).passthrough(),codeConflictBlobSchema2=z129.object({oid:z129.string().optional(),content:z129.string().optional(),truncated:z129.boolean(),binary:z129.boolean()}),codeConflictDetailSchema=z129.object({path:z129.string(),base:codeConflictBlobSchema2,ours:codeConflictBlobSchema2,theirs:codeConflictBlobSchema2,result:codeConflictBlobSchema2,sourceTipSha:z129.string(),targetTipSha:z129.string(),mergeBaseSha:z129.string().optional()}),resolutionChoiceSchema=z129.enum(["parent","child","pick"]),conflictResolutionSchema2=z129.object({surface:surfaceNameSchema,key:z129.string().min(1),choice:resolutionChoiceSchema,pickedValue:z129.unknown().optional(),fieldPicks:z129.array(z129.object({field:z129.string().min(1),choice:resolutionChoiceSchema,pickedValue:z129.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"]})})}),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:z129.object({projectId:uuidSchema,targetBranch:branchNameSchema.optional(),name:z129.string().trim().min(1).max(120).optional(),goal:z129.string().trim().min(1).max(500).optional()}).strict(),outputSchema:z129.object({session:sessionEnvelopeSchema,adopted:z129.boolean()}),buildRequest:__name(({projectId:projectId2,targetBranch,name,goal})=>({method:"POST",path:managementProjectPath(projectId2,"/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:z129.object({projectId:uuidSchema,sessionId:uuidSchema}).strict(),outputSchema:sessionEnvelopeSchema,buildRequest:__name(({projectId:projectId2,sessionId})=>({method:"GET",path:managementProjectPath(projectId2,`/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:z129.object({projectId:uuidSchema,status:sessionStatusSchema.optional(),scope:z129.enum(["mine","project"]).optional(),cursor:paginationShape.cursor,limit:z129.number().int().min(1).max(100).optional()}).strict(),outputSchema:z129.object({items:z129.array(sessionEnvelopeSchema),nextCursor:z129.string().nullable()}),buildRequest:__name(({projectId:projectId2,status,cursor,limit,scope:scope2})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,"/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:z129.object({projectId:uuidSchema,sessionId:uuidSchema,detail:z129.boolean().optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({changes:sessionChangesSchema}),buildRequest:__name(({projectId:projectId2,sessionId,detail})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,`/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:z129.object({projectId:uuidSchema,sessionId:uuidSchema,summary:z129.string().trim().min(1).max(240),targetBranch:branchNameSchema.optional()}).strict(),outputSchema:z129.object({requested:z129.literal(!0),alreadyRequested:z129.boolean(),reviewId:uuidSchema,reviewUrl:z129.url(),status:z129.literal("pending"),sessionId:uuidSchema,branch:branchNameSchema,targetBranch:branchNameSchema,revision:z129.string().min(1),savedRevision:z129.string().min(1),fingerprint:z129.string().min(1),visibility:z129.literal("user-visible"),retention:z129.literal("durable"),expiresAt:z129.null(),merged:z129.literal(!1),published:z129.literal(!1),links:z129.object({preview:z129.url(),changes:z129.url(),conversation:z129.url().nullable()})}),buildRequest:__name(({projectId:projectId2,sessionId,summary:summary2,targetBranch})=>({method:"POST",path:managementProjectPath(projectId2,`/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:z129.object({projectId:uuidSchema,sessionId:uuidSchema,additionalDays:z129.number().int().min(1).max(30)}).strict(),outputSchema:sessionEnvelopeSchema.extend({retention:z129.literal("temporary"),visibility:z129.enum(["internal","user-visible"]),expiresAt:z129.iso.datetime()}),buildRequest:__name(({projectId:projectId2,sessionId,additionalDays})=>({method:"POST",path:managementProjectPath(projectId2,`/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:z129.object({projectId:uuidSchema,sessionId:uuidSchema}).strict(),outputSchema:sessionEnvelopeSchema.extend({validation:sessionValidationSchema}),buildRequest:__name(({projectId:projectId2,sessionId})=>({method:"POST",path:managementProjectPath(projectId2,`/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:z129.object({projectId:uuidSchema,sessionId:uuidSchema,operation:z129.string().min(1).max(100),args:z129.record(z129.string(),z129.unknown()).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({operation:sessionOperationResultSchema}),buildRequest:__name(({projectId:projectId2,sessionId,operation,args})=>({method:"POST",path:managementProjectPath(projectId2,`/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:z129.object({projectId:uuidSchema,sessionId:uuidSchema,action:z129.enum(["merge","discard"]),message:z129.string().max(1e3).optional(),description:z129.string().max(2e3).optional().describe("Why the work changed. Becomes the body of the merge commit.")}).strict(),outputSchema:sessionEnvelopeSchema.extend({outcome:z129.enum(["merged","no_changes","discarded","conflicts","failed"]),closed:z129.boolean(),mergeId:uuidSchema.optional(),conflictCount:z129.number().int().nonnegative().optional(),conflicts:z129.array(sessionConflictSummarySchema).optional(),parentAdvanced:z129.boolean().optional(),code:z129.string().optional(),summary:z129.string().nullable().optional()}),buildRequest:__name(({projectId:projectId2,sessionId,action,message,description})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/close`),body:withoutUndefined({action,message,description})}),"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:z129.object({projectId:uuidSchema,sessionId:uuidSchema,mergeId:uuidSchema.optional(),cursor:paginationShape.cursor,limit:z129.number().int().min(1).max(100).optional(),codePath:z129.string().min(1).max(1024).optional()}).strict(),outputSchema:sessionEnvelopeSchema.extend({merge:z129.object({mergeId:uuidSchema,fromBranch:branchNameSchema,toBranch:branchNameSchema,status:z129.enum(["in_progress","complete","failed","rolled_back","conflicts"]),conflictCount:z129.number().int().nonnegative(),error:z129.string().nullable()}),conflicts:z129.array(conflictSchema2).max(100),nextCursor:z129.string().nullable(),codeDetail:codeConflictDetailSchema.nullable().optional()}),buildRequest:__name(({projectId:projectId2,sessionId,mergeId,cursor,limit,codePath})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,`/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:z129.object({projectId:uuidSchema,sessionId:uuidSchema,mergeId:uuidSchema,resolutions:z129.array(conflictResolutionSchema2).min(1).max(500)}).strict(),outputSchema:sessionEnvelopeSchema.extend({outcome:z129.literal("resolving"),mergeId:uuidSchema,supersededMergeId:uuidSchema,strategy:resolvedMergeStrategySchema,acceptedAt:z129.iso.datetime()}),buildRequest:__name(({projectId:projectId2,sessionId,mergeId,resolutions})=>({method:"POST",path:managementProjectPath(projectId2,`/sessions/${encodeURIComponent(sessionId)}/resolve`),body:{mergeId,resolutions:backendConflictResolutions(resolutions)}}),"buildRequest")}}}});import{z as z130}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:z130.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,locale:localeSchema.optional(),populate:populateSchema}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,locale,populate})=>({method:"GET",path:addQuery(tenantPath(projectId2,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:z130.object({projectId:uuidSchema,branch:branchNameSchema,typeName:typeNameSchema,data:entryDataSchema,locale:localeSchema.optional()}).strict(),outputSchema:entryResponseSchema,buildRequest:__name(({projectId:projectId2,branch,typeName,data,locale})=>({method:"PUT",path:addQuery(tenantPath(projectId2,branch,`/documents/${encodeURIComponent(typeName)}`),{locale}),body:{data}}),"buildRequest")}}}});import{z as z131}from"zod";var supportReportInputSchema,supportReportResultSchema,supportOperations,init_support2=__esm({"../../packages/sdk/dist/operations/support.js"(){"use strict";init_common2();supportReportInputSchema=z131.object({message:z131.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=z131.object({id:uuidSchema,deliveryStatus:z131.enum(["pending","delivered","failed"]),message:z131.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:z131.object({data:supportReportResultSchema}),buildRequest:__name(({message,projectId:projectId2,branch})=>({method:"POST",path:"/support/issues/agent",body:withoutUndefined({message,projectId:projectId2,branch})}),"buildRequest")}}}});import{z as z132}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=z132.record(z132.string(),z132.unknown()),deliveryStatusSchema=z132.enum(["pending","delivering","retrying","succeeded","failed"]),webhookSchema=z132.object({id:uuidSchema,projectId:uuidSchema,name:z132.string(),eventType:z132.string().min(1),enabled:z132.boolean(),destination:z132.object({host:z132.string(),maskedUrl:z132.string(),kind:z132.string()}),filter:jsonObjectSchema,headers:z132.array(jsonObjectSchema),bodyTemplate:z132.unknown().nullable(),signingEnabled:z132.boolean(),lastDeliveryStatus:deliveryStatusSchema.nullable()}).passthrough(),deliverySchema=z132.object({id:uuidSchema,webhookId:uuidSchema,projectId:uuidSchema,eventType:z132.string().min(1),status:deliveryStatusSchema,attemptCount:z132.number().int().nonnegative(),responseStatus:z132.number().int().nullable(),createdAt:z132.iso.datetime()}).passthrough(),attemptSchema=z132.object({id:uuidSchema,deliveryId:uuidSchema,attempt:z132.number().int().positive(),status:z132.enum(["delivering","succeeded","failed"]),createdAt:z132.iso.datetime()}).passthrough(),deliveriesPageSchema=z132.object({items:z132.array(deliverySchema),pagination:z132.object({page:z132.number().int().positive(),limit:z132.number().int().positive(),total:z132.number().int().nonnegative(),totalPages:z132.number().int().positive(),hasMore:z132.boolean()}),stats:z132.object({total:z132.number().int().nonnegative(),succeeded:z132.number().int().nonnegative(),failed:z132.number().int().nonnegative()})}),eventSchema=z132.object({type:z132.string().min(1),family:z132.string(),description:z132.string(),variables:z132.array(z132.string()),data:z132.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:z132.object({projectId:uuidSchema}).strict(),outputSchema:z132.array(eventSchema),buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/webhooks/events")}),"buildRequest"),projectOutput:__name(body=>z132.array(eventSchema).parse(responseData(body)),"projectOutput")},"webhooks.list":{domain:"webhooks",summary:"List outbound webhooks configured for one site.",accessScope:"read",effect:"read",inputSchema:z132.object({projectId:uuidSchema}).strict(),outputSchema:z132.array(webhookSchema),buildRequest:__name(({projectId:projectId2})=>({method:"GET",path:managementProjectPath(projectId2,"/webhooks")}),"buildRequest"),projectOutput:__name(body=>z132.array(webhookSchema).parse(responseData(body)),"projectOutput")},"webhooks.get":{domain:"webhooks",summary:"Read one outbound site webhook.",accessScope:"read",effect:"read",inputSchema:z132.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:webhookSchema,buildRequest:__name(({projectId:projectId2,webhookId})=>({method:"GET",path:managementProjectPath(projectId2,`/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:z132.object({projectId:uuidSchema,webhook:webhookWriteSchema}).strict(),outputSchema:z132.object({webhook:webhookSchema,signingSecret:z132.string().min(1)}),buildRequest:__name(({projectId:projectId2,webhook})=>({method:"POST",path:managementProjectPath(projectId2,"/webhooks"),body:webhook}),"buildRequest"),projectOutput:__name(body=>z132.object({webhook:webhookSchema,signingSecret:z132.string().min(1)}).parse(responseData(body)),"projectOutput")},"webhooks.update":{domain:"webhooks",summary:"Update one outbound site webhook.",accessScope:"write",effect:"mutation",inputSchema:z132.object({projectId:uuidSchema,webhookId:uuidSchema,webhook:webhookWriteSchema}).strict(),outputSchema:webhookSchema,buildRequest:__name(({projectId:projectId2,webhookId,webhook})=>({method:"PATCH",path:managementProjectPath(projectId2,`/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:z132.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:z132.unknown(),buildRequest:__name(({projectId:projectId2,webhookId})=>({method:"DELETE",path:managementProjectPath(projectId2,`/webhooks/${encodeURIComponent(webhookId)}`)}),"buildRequest")},"webhooks.rotateSecret":{domain:"webhooks",summary:"Rotate and reveal the signing secret for one site webhook.",accessScope:"write",effect:"mutation",inputSchema:z132.object({projectId:uuidSchema,webhookId:uuidSchema}).strict(),outputSchema:z132.string().min(1),buildRequest:__name(({projectId:projectId2,webhookId})=>({method:"POST",path:managementProjectPath(projectId2,`/webhooks/${encodeURIComponent(webhookId)}/rotate-signing-secret`)}),"buildRequest"),projectOutput:__name(body=>z132.object({signingSecret:z132.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:z132.object({projectId:uuidSchema,webhookId:uuidSchema,data:jsonObjectSchema.optional()}).strict(),outputSchema:deliverySchema,buildRequest:__name(({projectId:projectId2,webhookId,data})=>({method:"POST",path:managementProjectPath(projectId2,`/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:z132.object({projectId:uuidSchema,webhookId:uuidSchema,...numberedPaginationShape,limit:z132.number().int().min(1).max(100).optional()}).strict().superRefine(numberedPaginationRefinement),outputSchema:deliveriesPageSchema.extend({nextCursor:z132.string().nullable()}),buildRequest:__name(({projectId:projectId2,webhookId,page,cursor,limit})=>({method:"GET",path:addQuery(managementProjectPath(projectId2,`/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:z132.object({projectId:uuidSchema,webhookId:uuidSchema,deliveryId:uuidSchema}).strict(),outputSchema:z132.object({delivery:deliverySchema,attempts:z132.array(attemptSchema)}),buildRequest:__name(({projectId:projectId2,webhookId,deliveryId})=>({method:"GET",path:managementProjectPath(projectId2,`/webhooks/${encodeURIComponent(webhookId)}/deliveries/${encodeURIComponent(deliveryId)}`)}),"buildRequest"),projectOutput:__name(body=>z132.object({delivery:deliverySchema,attempts:z132.array(attemptSchema)}).parse(responseData(body)),"projectOutput")},"webhooks.retryDelivery":{domain:"webhooks",summary:"Retry one failed webhook delivery.",accessScope:"write",effect:"mutation",inputSchema:z132.object({projectId:uuidSchema,webhookId:uuidSchema,deliveryId:uuidSchema}).strict(),outputSchema:deliverySchema,buildRequest:__name(({projectId:projectId2,webhookId,deliveryId})=>({method:"POST",path:managementProjectPath(projectId2,`/webhooks/${encodeURIComponent(webhookId)}/deliveries/${encodeURIComponent(deliveryId)}/retry`)}),"buildRequest"),projectOutput:__name(body=>deliverySchema.parse(responseData(body)),"projectOutput")}}}});import{z as z133}from"zod";var fimoOperations,fimoOperationManifestEntrySchema,fimoOperationManifestSchema,fimoOperationManifest,init_operations=__esm({"../../packages/sdk/dist/operations.js"(){"use strict";init_agents();init_analytics();init_assets();init_billing2();init_branches();init_domains();init_entries();init_environments();init_files();init_forms();init_generation();init_history();init_hosting();init_integrations();init_knowledge();init_labels();init_locales();init_organizations();init_projects();init_schedules();init_schemas();init_secrets();init_sessions();init_singles();init_support2();init_webhooks();fimoOperations={...projectsOperations,...organizationsOperations,...domainsOperations,...generationOperations,...historyOperations,...environmentsOperations,...secretsOperations,...schedulesOperations,...webhooksOperations,...branchesOperations,...schemasOperations,...supportOperations,...sessionsOperations,...entriesOperations,...singlesOperations,...knowledgeOperations,...agentsOperations,...labelsOperations,...localesOperations,...assetsOperations,...formsOperations,...hostingOperations,...analyticsOperations,...integrationsOperations,...filesOperations,...billingOperations},fimoOperationManifestEntrySchema=z133.object({id:z133.string().regex(/^[a-zA-Z_$][\w$]*\.[a-zA-Z_$][\w$]*$/),domain:z133.string().min(1),summary:z133.string().min(1),accessScope:z133.enum(["read","write","code","agents"]),effect:z133.enum(["read","mutation"]),inputJsonSchema:z133.record(z133.string(),z133.unknown()),outputJsonSchema:z133.record(z133.string(),z133.unknown())}).strict(),fimoOperationManifestSchema=z133.array(fimoOperationManifestEntrySchema),fimoOperationManifest=Object.entries(fimoOperations).map(([id,operation])=>({id,domain:operation.domain,summary:operation.summary,accessScope:operation.accessScope,effect:operation.effect,inputJsonSchema:z133.toJSONSchema(operation.inputSchema,{target:"draft-7",io:"input"}),outputJsonSchema:z133.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 fs3 from"node:fs";import path3 from"node:path";import{setTimeout as sleep}from"node:timers/promises";function isPublishedInstall(cliRoot=CLI_ROOT){return fs3.existsSync(path3.join(cliRoot,"release.json"))}function buildSkipsVersionCheck(cliRoot=CLI_ROOT,readFile6=defaultReadFile){try{return JSON.parse(readFile6(path3.join(cliRoot,"release.json"))).skipVersionCheck===!0}catch{return!1}}function defaultReadFile(file){return fs3.readFileSync(file,"utf8")}function resolveGlobalFimoRoot(){let result=spawnSync("npm",["root","-g"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:GLOBAL_ROOT_TIMEOUT_MS});return result.error||result.status!==0||typeof result.stdout!="string"||result.stdout.trim().length===0?null:path3.resolve(result.stdout.trim(),"fimo")}function normalizedPath(input){try{return fs3.realpathSync(input)}catch{return path3.resolve(input)}}function autoUpgradeEnabled(options={}){let usesDefaults=Object.keys(options).length===0;if(usesDefaults&&defaultEligibility!==void 0)return defaultEligibility;let env=options.env??process.env,cliRoot=options.cliRoot??CLI_ROOT,published=options.published??isPublishedInstall(cliRoot);if(env.FIMO_AUTO_UPGRADE!=="1"||!published||buildSkipsVersionCheck(cliRoot))return usesDefaults&&(defaultEligibility=!1),!1;let globalFimoRoot=options.globalFimoRoot===void 0?resolveGlobalFimoRoot():options.globalFimoRoot;if(!globalFimoRoot)return usesDefaults&&(defaultEligibility=!1),!1;let eligible=normalizedPath(cliRoot)===normalizedPath(globalFimoRoot);return usesDefaults&&(defaultEligibility=eligible),eligible}async function acquireLock(lockDir){let deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{fs3.mkdirSync(lockDir);return}catch(error){if(error.code!=="EEXIST")throw error}let stale=!1;try{stale=Date.now()-fs3.statSync(lockDir).mtimeMs>LOCK_STALE_MS}catch{continue}if(stale){try{fs3.rmdirSync(lockDir)}catch{}continue}if(Date.now()>=deadline)throw new Error("auto-upgrade lock timeout");await sleep(LOCK_POLL_MS)}}function readGlobalFimoVersion(){let root=resolveGlobalFimoRoot();if(!root)return null;try{let pkg=JSON.parse(fs3.readFileSync(path3.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=path3.join(loadConfig().configDir,"auto-upgrade.lock");try{fs3.mkdirSync(path3.dirname(lockDir),{recursive:!0}),await acquireLock(lockDir)}catch{return!1}try{if(readGlobalFimoVersion()===latest)return!0;let install=spawnSync("npm",["install","-g",`fimo@${latest}`],{stdio:["ignore","ignore","inherit"],timeout:INSTALL_TIMEOUT_MS});return install.error||install.status!==0?!1:readGlobalFimoVersion()===latest}finally{try{fs3.rmdirSync(lockDir)}catch{}}}var INSTALL_TIMEOUT_MS,GLOBAL_ROOT_TIMEOUT_MS,LOCK_WAIT_MS,LOCK_STALE_MS,LOCK_POLL_MS,VERSION_PATTERN,defaultEligibility,init_auto_upgrade=__esm({"src/cli/auto-upgrade.ts"(){init_config();INSTALL_TIMEOUT_MS=12e4,GLOBAL_ROOT_TIMEOUT_MS=5e3,LOCK_WAIT_MS=18e4,LOCK_STALE_MS=3e5,LOCK_POLL_MS=500,VERSION_PATTERN=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;__name(isPublishedInstall,"isPublishedInstall");__name(buildSkipsVersionCheck,"buildSkipsVersionCheck");__name(defaultReadFile,"defaultReadFile");__name(resolveGlobalFimoRoot,"resolveGlobalFimoRoot");__name(normalizedPath,"normalizedPath");__name(autoUpgradeEnabled,"autoUpgradeEnabled");__name(acquireLock,"acquireLock");__name(readGlobalFimoVersion,"readGlobalFimoVersion");__name(autoUpgradeGlobal,"autoUpgradeGlobal")}});import fs4 from"node:fs";import path4 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";function getCliVersion(){try{let raw=fs4.readFileSync(PACKAGE_JSON_PATH,"utf8");return JSON.parse(raw).version??"0.0.0"}catch{return"0.0.0"}}var THIS_FILE2,CLI_ROOT2,PACKAGE_JSON_PATH,init_version=__esm({"src/cli/version.ts"(){THIS_FILE2=fileURLToPath2(import.meta.url),CLI_ROOT2=path4.resolve(path4.dirname(THIS_FILE2),"..",".."),PACKAGE_JSON_PATH=path4.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(issue2=>{let{path:path52,message}=issue2;return`${Array.isArray(path52)&&path52.length>0?`${path52.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 formatFieldErrors(parsed){if(!Array.isArray(parsed.errors))return null;let fields=parsed.errors.flatMap(error=>{if(!error||typeof error!="object")return[];let{path:path52,message}=error;return typeof message!="string"||!message?[]:[typeof path52=="string"&&path52?`${path52}: ${message}`:message]});return fields.length>0?fields.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 fields=formatFieldErrors(parsed),message=fields?`${parsed.message}: ${fields}`:parsed.message,partial=formatPartialResult(parsed);return partial?`${message} ${partial}`: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),server.body=body}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(path52,init={},defaultJsonContentType=!0)=>fimoFetch(`${cfg.apiUrl}${path52}`,{...init,headers:authHeaders(init,defaultJsonContentType)}),"send");return{async request(path52,init={},options={}){let response=await send(path52,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",path52,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()},async response(path52,init={}){let response=await send(path52,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",path52,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,path52,status,detail,code2,body){super(`API ${method} ${path52} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path52,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;body;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,this.body=server.body}},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(formatFieldErrors,"formatFieldErrors");__name(formatError,"formatError");__name(parseError,"parseError");__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");__name(createCliHttpTransport,"createCliHttpTransport");__name(createCliFimoClient,"createCliFimoClient");__name(requiredPermissions,"requiredPermissions")}});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 files2=new Set(Array.from(paths,file=>file.replace(/\\/g,"/").replace(/^\.\//,"")));return(layout??detectProjectLayout(files2)??"current")==="current"?CURRENT_PROJECT_LAYOUT.config:files2.has(LEGACY_AGENT_POLICY_PATH)&&!files2.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(projectId2,branch,tenantApiBaseUrl){let url=new URL(tenantApiBaseUrl);return url.hostname=`${projectId2}-${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 fs5 from"node:fs";import path5 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=path5.join(root,file);fs5.existsSync(filePath)&&Object.assign(values,parseEnv(fs5.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=path5.resolve(start);for(;;){if(fs5.existsSync(path5.join(dir,CURRENT_PROJECT_LAYOUT.project))||fs5.existsSync(path5.join(dir,LEGACY_PROJECT_LAYOUT.project)))return dir;let parent=path5.dirname(dir);if(parent===dir)return null;dir=parent}}function readProjectLink(root){for(let layout of[CURRENT_PROJECT_LAYOUT,LEGACY_PROJECT_LAYOUT]){let file=path5.join(root,layout.project);if(fs5.existsSync(file))try{let parsed=JSON.parse(fs5.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{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 gitCommit(cwd,message,description){let identity2=await hasGitIdentity(cwd)?[]:["-c",`user.name=${FALLBACK_GIT_IDENTITY.name}`,"-c",`user.email=${FALLBACK_GIT_IDENTITY.email}`];await runGit([...identity2,"commit","-m",message,...description?["-m",description]:[]],cwd)}async function hasGitIdentity(cwd){try{return await runGit(["var","GIT_AUTHOR_IDENT"],cwd),await runGit(["var","GIT_COMMITTER_IDENT"],cwd),!0}catch{return!1}}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 gitErrorOutput(error){return extractStderr(error).trim().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,FALLBACK_GIT_IDENTITY,init_git=__esm({"src/cli/utils/git.ts"(){execFileAsync=promisify(execFile);__name(runGit,"runGit");__name(isGitRepo,"isGitRepo");__name(hasUncommittedChanges,"hasUncommittedChanges");FALLBACK_GIT_IDENTITY={name:"Fimo",email:"cli@users.noreply.fimo.ai"};__name(gitCommit,"gitCommit");__name(hasGitIdentity,"hasGitIdentity");__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(gitErrorOutput,"gitErrorOutput");__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 files2=existingLayoutPaths(cwd);return path6.join(cwd,selectProjectConfigPath(files2,detectProjectLayout(files2)))}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_project2=__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")}});import path7 from"node:path";function projectSettingsFromEnv(){let projectId2=process.env.FIMO_PROJECT_ID?.trim();return projectId2?{projectId:projectId2,organizationId:process.env.FIMO_ORGANIZATION_ID?.trim()??"",name:process.env.FIMO_PROJECT_NAME?.trim()??projectId2,apiUrl:process.env.FIMO_API_URL?.trim()??loadConfig().apiUrl}:null}function resolveProjectSettings(cwd){let fromEnv=projectSettingsFromEnv(),linked;try{linked=loadProjectSettings(cwd)}catch{return fromEnv}if(!fromEnv||fromEnv.projectId===linked.projectId)return linked;let linkPath=path7.relative(cwd,resolveProjectSettingsPath(cwd));return process.env.FIMO_API_TOKEN?.trim()?(ui.warn({command:"project",message:`${linkPath} names project ${linked.projectId}, but this run is bound to project ${fromEnv.projectId} (FIMO_PROJECT_ID). Using ${fromEnv.projectId}. The link file was probably copied from another project; set its projectId to ${fromEnv.projectId}.`}),fromEnv):(ui.warn({command:"project",message:`FIMO_PROJECT_ID is ${fromEnv.projectId}, but ${linkPath} names project ${linked.projectId}. Using ${linked.projectId} from the link file.`}),linked)}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=resolveProjectSettings(cwd);if(!settings)throw new NotInProjectError;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_dist();init_local_runtime_env();init_config();init_sdk_transport();init_git();init_project2();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");__name(resolveProjectSettings,"resolveProjectSettings");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_src=__commonJS({"../../node_modules/.pnpm/sisteransi@1.0.5/node_modules/sisteransi/src/index.js"(exports2,module2){"use strict";var cursor={to(x,y2){return y2?`\x1B[${y2+1};${x+1}H`:`\x1B[${x+1}G`},move(x,y2){let ret="";return x<0?ret+=`\x1B[${-x}D`:x>0&&(ret+=`\x1B[${x}C`),y2<0?ret+=`\x1B[${-y2}A`:y2>0&&(ret+=`\x1B[${y2}B`),ret},up:__name((count=1)=>`\x1B[${count}A`,"up"),down:__name((count=1)=>`\x1B[${count}B`,"down"),forward:__name((count=1)=>`\x1B[${count}C`,"forward"),backward:__name((count=1)=>`\x1B[${count}D`,"backward"),nextLine:__name((count=1)=>"\x1B[E".repeat(count),"nextLine"),prevLine:__name((count=1)=>"\x1B[F".repeat(count),"prevLine"),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},scroll={up:__name((count=1)=>"\x1B[S".repeat(count),"up"),down:__name((count=1)=>"\x1B[T".repeat(count),"down")},erase={screen:"\x1B[2J",up:__name((count=1)=>"\x1B[1J".repeat(count),"up"),down:__name((count=1)=>"\x1B[J".repeat(count),"down"),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(count){let clear="";for(let i=0;i<count;i++)clear+=this.line+(i<count-1?cursor.up():"");return count&&(clear+=cursor.left),clear}};module2.exports={cursor,scroll,erase,beep:"\x07"}}});function recoverTenantApiBaseUrl(tenantApiUrl,projectId2,branch){try{let normalized=tenantApiUrl.replace(/\/$/,""),url=new URL(normalized),prefix=`${projectId2}-${envResourceKey(branch)}.`;if(!url.hostname.startsWith(prefix))return;url.hostname=url.hostname.slice(prefix.length);let base=url.toString().replace(/\/$/,"");return buildTenantApiUrl(projectId2,branch,base)===normalized?base:void 0}catch{return}}function createIdentityService(cfg=loadConfig()){let transport=createCliHttpTransport(cfg);return{getCurrentSession(){return transport.request("/api/auth/get-session")}}}function createGitService(cfg=loadConfig(),headerBranch){let transport=createCliHttpTransport(cfg,headerBranch);return{async getRemote(projectId2,branch){let body=await transport.request(`/api/management/projects/${projectId2}/branches/${encodeURIComponent(branch)}/git-remote`,{},{preserveForbidden:!0});if(!body.data.tenantApiBaseUrl){let recovered=recoverTenantApiBaseUrl(body.data.tenantApiUrl,projectId2,branch);if(recovered)return{...body.data,tenantApiBaseUrl:recovered}}return body.data},async getCredential(projectId2,branch){return(await transport.request(`/api/management/projects/${projectId2}/branches/${encodeURIComponent(branch)}/git-credential`,{},{preserveForbidden:!0})).data}}}function createPublicationControlService(cfg=loadConfig(),branch){let transport=createCliHttpTransport(cfg,branch);return{async publish(projectId2,request={}){return(await transport.request(`/api/management/projects/${projectId2}/publish`,{method:"POST",body:JSON.stringify(request)}))?.data?.publicationId??null},async unpublish(projectId2){await transport.request(`/api/management/projects/${projectId2}/unpublish`,{method:"POST"})}}}function publicationIdFromError(error){let body=error instanceof ApiRequestError?error.body:void 0;if(typeof body!="object"||body===null)return null;let candidate=body.publicationId;return typeof candidate=="string"?candidate:null}function transferBlockersFromError(error){let body=error instanceof ApiRequestError?error.body:void 0;if(typeof body!="object"||body===null)return[];let blockers=body.blockers;return Array.isArray(blockers)?blockers:[]}function createSandboxService(cfg=loadConfig(),headerBranch){let transport=createCliHttpTransport(cfg,headerBranch);return{async getHostedPreview(projectId2,branch){return(await transport.request(`/api/management/projects/${projectId2}/branches/${encodeBranchPathSegment(branch)}/hosted-preview`)).data},async pull(projectId2,onProgress,branch,options={}){let params=new URLSearchParams;options.wait!==void 0&¶ms.set("wait",String(options.wait));let search=params.toString(),response=await transport.response(`/api/management/projects/${projectId2}/branches/${encodeURIComponent(branch)}/sandbox/pull${search?`?${search}`:""}`,{method:"POST",headers:{Accept:"text/event-stream"}});if(!response.body)throw new Error("Sandbox pull failed: empty response stream");let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",failure=null,readiness=null,timings=null,completed=!1;try{for(;;){let{value,done}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});let separatorIndex=buffer.indexOf(`
|
|
47
47
|
|
|
@@ -49,11 +49,11 @@ Expecting one of '${allowedValues.join("', '")}'`);let helpEvent=`${position}Hel
|
|
|
49
49
|
|
|
50
50
|
`);let eventName="message",dataLines=[];for(let line of rawEvent.split(`
|
|
51
51
|
`))line.startsWith("event:")?eventName=line.slice(6).trim():line.startsWith("data:")&&dataLines.push(line.slice(5).trim());if(dataLines.length===0)continue;let payload=dataLines.join(`
|
|
52
|
-
`);if(eventName==="progress")try{onProgress?.(JSON.parse(payload))}catch{}else if(eventName==="complete"){completed=!0;try{let complete=JSON.parse(payload);readiness=complete.readiness??null,timings=complete.timings??null}catch{}}else if(eventName==="error"){let parsed;try{parsed=JSON.parse(payload)}catch{parsed=void 0}let result=SandboxPullFailureSchema.safeParse(parsed);failure=result.success?result.data:{message:"Sandbox pull failed"}}}}}finally{reader.releaseLock()}if(failure)throw new SandboxPullError(failure);if(!completed)throw new Error("Sandbox pull stream ended before completion");return{readiness:readiness??{status:"skipped",reason:"not_reported",durationMs:0},timings:timings??{dependencyInstallMs:0,serverStartMs:0,readinessMs:readiness?.durationMs??0,totalSandboxMs:0}}}}}function createSupportService(cfg=loadConfig()){let transport=createCliHttpTransport(cfg);return{async submit(input){return(await transport.request("/api/support/issues",{method:"POST",body:JSON.stringify(input)})).data}}}function createTelemetryService(cfg=loadConfig()){let transport=createCliHttpTransport(cfg);return{async trackProjectEvent(projectId2,event,properties={}){await transport.request(`/api/management/projects/${projectId2}/track`,{method:"POST",body:JSON.stringify({event,properties})})}}}var SandboxPullError,init_project_services=__esm({"src/cli/services/project-services.ts"(){init_esm();init_config();init_sdk_transport();__name(recoverTenantApiBaseUrl,"recoverTenantApiBaseUrl");__name(createIdentityService,"createIdentityService");__name(createGitService,"createGitService");__name(createPublicationControlService,"createPublicationControlService");__name(publicationIdFromError,"publicationIdFromError");__name(transferBlockersFromError,"transferBlockersFromError");SandboxPullError=class extends Error{static{__name(this,"SandboxPullError")}failure;constructor(failure){super(failure.message),this.name="SandboxPullError",this.failure=failure}};__name(createSandboxService,"createSandboxService");__name(createSupportService,"createSupportService");__name(createTelemetryService,"createTelemetryService")}});function colorEnabled(opts={}){if(opts.forceDisable)return!1;let env=opts.env??process.env;return env.NO_COLOR&&env.NO_COLOR.length>0?!1:env.FORCE_COLOR&&env.FORCE_COLOR!=="0"&&env.FORCE_COLOR!=="false"?!0:(opts.isTTY??process.stdout.isTTY??!1)===!0}function makeColorPalette(opts={}){let on=colorEnabled(opts),wrap=__name(style=>s=>on?`${ANSI[style]}${s}${ANSI.reset}`:s,"wrap");return{enabled:on,bold:wrap("bold"),dim:wrap("dim"),red:wrap("red"),green:wrap("green"),yellow:wrap("yellow"),blue:wrap("blue"),magenta:wrap("magenta"),cyan:wrap("cyan"),gray:wrap("gray")}}var ANSI,palette,init_color=__esm({"src/cli/utils/format/color.ts"(){ANSI={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m"};__name(colorEnabled,"colorEnabled");__name(makeColorPalette,"makeColorPalette");palette=makeColorPalette()}});function planRemoteConfig(remoteUrl){let u2=new URL(remoteUrl),cleanUrl=`${u2.protocol}//${u2.host}${u2.pathname}`,credentialKey=`credential.${u2.protocol}//${u2.host}`;return{cleanUrl,credentialKey}}function shellQuote(value){return`'${value.replace(/'/g,"'\\''")}'`}function credentialHelperCommand(argv=process.argv){let entry=argv[1];return entry?`!${shellQuote(process.execPath)} ${shellQuote(entry)} git-credential`:"!fimo git-credential"}async function ensureFimoRemote(cwd,remoteUrl){let{cleanUrl,credentialKey}=planRemoteConfig(remoteUrl);await runGit(["remote","set-url","fimo",cleanUrl],cwd).catch(async()=>{await runGit(["remote","add","fimo",cleanUrl],cwd)}),await runGit(["config","--unset-all",`${credentialKey}.helper`],cwd).catch(()=>{}),await runGit(["config","--add",`${credentialKey}.helper`,""],cwd),await runGit(["config","--add",`${credentialKey}.helper`,credentialHelperCommand()],cwd),await runGit(["config",`${credentialKey}.useHttpPath`,"true"],cwd),await runGit(["config",`${credentialKey}.username`,"t"],cwd)}var init_git_credential_setup=__esm({"src/cli/utils/git-credential-setup.ts"(){init_git();__name(planRemoteConfig,"planRemoteConfig");__name(shellQuote,"shellQuote");__name(credentialHelperCommand,"credentialHelperCommand");__name(ensureFimoRemote,"ensureFimoRemote")}});import path9 from"node:path";function remoteRef(remoteBranch){return`refs/remotes/fimo/${remoteBranch}`}async function remoteHeadOrNull(cwd,remoteBranch){try{return await runGit(["rev-parse","--verify",remoteRef(remoteBranch)],cwd)}catch{return null}}function relationFromCounts(ahead,behind){return ahead===0&&behind===0?"in-sync":ahead>0&&behind===0?"ahead":ahead===0&&behind>0?"behind":"diverged"}async function inspectBranchCheckout(args){args.fetch!==!1&&await runGit(["fetch","--quiet","--no-tags","--prune","fimo"],args.cwd);let[localBranch,localHead,remoteHead]=await Promise.all([currentBranch2(args.cwd),runGit(["rev-parse","HEAD"],args.cwd),remoteHeadOrNull(args.cwd,args.remoteBranch)]);if(!remoteHead)return{localBranch,remoteBranch:args.remoteBranch,localHead,remoteHead:null,ahead:0,behind:0,relation:"missing-remote"};let counts=await runGit(["rev-list","--left-right","--count",`HEAD...${remoteRef(args.remoteBranch)}`],args.cwd),[ahead=0,behind=0]=counts.split(/\s+/).map(Number);return{localBranch,remoteBranch:args.remoteBranch,localHead,remoteHead,ahead,behind,relation:relationFromCounts(ahead,behind)}}async function hasPathChanges(cwd,filePath){let relativePath=path9.relative(cwd,filePath);return(await runGit(["status","--porcelain","--",relativePath],cwd)).length>0}function assertLocaleMutationState(state){if(state.localBranch!==state.remoteBranch)throw new BranchCheckoutError("ENV_BRANCH_MISMATCH",`The selected environment uses branch '${state.remoteBranch}', but the checkout is on '${state.localBranch}'.`,`Switch to '${state.remoteBranch}' before changing its locales.`);if(state.relation==="missing-remote")throw new BranchCheckoutError("ENV_REMOTE_MISSING",`The environment branch 'fimo/${state.remoteBranch}' does not exist yet.`,"Deploy the project before changing its locale lifecycle.");if(state.relation==="ahead")throw new BranchCheckoutError("ENV_BRANCH_AHEAD",`The local branch is ${state.ahead} commit${state.ahead===1?"":"s"} ahead of fimo/${state.remoteBranch}.`,"Deploy those commits first, then run the locale command again.");if(state.relation==="diverged")throw new BranchCheckoutError("ENV_BRANCH_DIVERGED",`The local branch and fimo/${state.remoteBranch} have diverged.`,"Reconcile the branches before changing the environment locales.")}async function planLocaleMutationCheckout(args){let state=await inspectBranchCheckout(args);if(assertLocaleMutationState(state),await hasPathChanges(args.cwd,args.configPath))throw new BranchCheckoutError("ENV_CONFIG_DIRTY","The project config has uncommitted changes.","Commit, discard, or deploy the config change before changing locales.");if(state.relation==="behind"&&await hasUncommittedChanges(args.cwd))throw new BranchCheckoutError("ENV_BRANCH_BEHIND_DIRTY",`The checkout is behind fimo/${state.remoteBranch} and has uncommitted changes.`,"Stash the changes, then run the locale command again.");return{cwd:args.cwd,configPath:args.configPath,state}}async function applyLocaleMutationCheckoutPlan(plan){let current=await inspectBranchCheckout({cwd:plan.cwd,remoteBranch:plan.state.remoteBranch,fetch:!1});if(current.localBranch!==plan.state.localBranch||current.localHead!==plan.state.localHead||current.remoteHead!==plan.state.remoteHead)throw new BranchCheckoutError("ENV_CHECKOUT_CHANGED","The checkout changed after the locale operation was reviewed.","Review the current Git state and run the locale command again.");if(assertLocaleMutationState(current),await hasPathChanges(plan.cwd,plan.configPath))throw new BranchCheckoutError("ENV_CONFIG_DIRTY","The project config changed after the locale operation was reviewed.","Commit, discard, or deploy the config change, then run the locale command again.");if(current.relation==="behind"){if(await hasUncommittedChanges(plan.cwd))throw new BranchCheckoutError("ENV_BRANCH_BEHIND_DIRTY",`The checkout is behind fimo/${current.remoteBranch} and now has uncommitted changes.`,"Stash the changes, then run the locale command again.");await runGit(["merge","--ff-only",remoteRef(current.remoteBranch)],plan.cwd)}}function recoveryCommands(remoteBranch,localBranch,relation){let inspect=`git log --oneline --left-right HEAD...fimo/${remoteBranch}`;return[...localBranch&&localBranch!==remoteBranch?[`git switch ${remoteBranch}`]:[],"git status","git fetch fimo",...relation==="ahead"||relation==="diverged"?[inspect]:[`git merge --ff-only fimo/${remoteBranch}`]]}async function synchronizeLocaleMutationCheckout(args){let state;try{state=await inspectBranchCheckout(args)}catch(error){return{status:"required",reason:error instanceof Error?error.message:String(error),recovery:recoveryCommands(args.remoteBranch)}}if(state.localBranch!==state.remoteBranch)return{status:"required",reason:`The checkout moved to '${state.localBranch}' after the remote locale change.`,recovery:recoveryCommands(state.remoteBranch,state.localBranch,state.relation)};if(state.relation==="in-sync")return{status:"synchronized"};if(state.relation!=="behind")return{status:"required",reason:`The local branch is ${state.relation} relative to fimo/${state.remoteBranch}.`,recovery:recoveryCommands(state.remoteBranch,void 0,state.relation)};try{return await runGit(["merge","--ff-only",remoteRef(state.remoteBranch)],args.cwd),{status:"synchronized"}}catch(error){return{status:"required",reason:error instanceof Error?error.message:String(error),recovery:recoveryCommands(state.remoteBranch)}}}async function inspectPublishSource(args){try{await ensureFimoRemote(args.cwd,args.remoteUrl);let localBranch=await currentBranch2(args.cwd).catch(()=>null);if(localBranch===null)return{status:"unavailable",reason:"the checkout is on a detached HEAD, not on a branch"};if(localBranch!==args.remoteBranch)return{status:"unavailable",reason:`the checkout is on '${localBranch}', not '${args.remoteBranch}'`};let state=await inspectBranchCheckout(args);return state.remoteHead===null?{status:"unavailable",reason:`the Fimo remote has no '${args.remoteBranch}' branch yet`}:{status:"known",remoteHead:state.remoteHead,unpushed:state.ahead,dirty:await hasUncommittedChanges(args.cwd)}}catch(error){return{status:"unavailable",reason:gitErrorSummary(error)}}}async function prepareDeployCheckout(args){let localBranch=await currentBranch2(args.cwd);if(localBranch!==args.remoteBranch)throw new BranchCheckoutError("ENV_BRANCH_MISMATCH",`Deploy requires branch '${args.remoteBranch}'; checkout is on '${localBranch}'.`,`Run 'fimo checkout ${args.remoteBranch}'.`);let state=await inspectBranchCheckout(args);if(state.relation==="missing-remote")return"missing-remote";if(state.relation==="in-sync"||state.relation==="ahead")return"ready";if(state.relation==="diverged")throw new BranchCheckoutError("ENV_BRANCH_DIVERGED",`The local checkout and fimo/${state.remoteBranch} have diverged.`,"Reconcile the branches before deploying.");if(await hasUncommittedChanges(args.cwd))throw new BranchCheckoutError("ENV_BRANCH_BEHIND_DIRTY",`The local checkout is behind fimo/${state.remoteBranch} and has uncommitted changes.`,"Stash the changes before deploying.");return await runGit(["merge","--ff-only",remoteRef(state.remoteBranch)],args.cwd),"ready"}async function hasCommits(cwd){try{return await runGit(["rev-parse","--verify","--quiet","HEAD"],cwd),!0}catch{return!1}}async function fastForwardPull(cwd,remoteBranch){if((await runGit(["status","--porcelain","--untracked-files=no"],cwd)).length>0)throw new BranchCheckoutError("ENV_BRANCH_BEHIND_DIRTY",`The local checkout is behind fimo/${remoteBranch} and has uncommitted changes.`,"Commit or stash the changes before pulling.");await runGit(["merge","--ff-only",remoteRef(remoteBranch)],cwd)}async function pullCheckout(args){let localBranch=await currentBranch2(args.cwd).catch(()=>null);if(localBranch!==args.remoteBranch)throw new BranchCheckoutError("ENV_BRANCH_MISMATCH",`Pull requires branch '${args.remoteBranch}'; checkout is on ${localBranch===null?"a detached HEAD":`'${localBranch}'`}.`,`Run 'fimo checkout ${args.remoteBranch}'.`);if(!await hasCommits(args.cwd)){if(await runGit(["fetch","--quiet","--no-tags","--prune","fimo"],args.cwd),await remoteHeadOrNull(args.cwd,args.remoteBranch)===null)return{relation:"missing-remote",pulled:0};let pulled=Number(await runGit(["rev-list","--count",remoteRef(args.remoteBranch)],args.cwd));return await fastForwardPull(args.cwd,args.remoteBranch),{relation:"behind",pulled}}let state=await inspectBranchCheckout(args);if(state.relation==="missing-remote"||state.relation==="in-sync"||state.relation==="ahead")return{relation:state.relation,pulled:0};if(state.relation==="diverged")throw new BranchCheckoutError("ENV_BRANCH_DIVERGED",`The local checkout and fimo/${state.remoteBranch} have diverged.`,`Reconcile the branches with 'git pull --rebase fimo ${state.remoteBranch}' before pulling.`);return await fastForwardPull(args.cwd,state.remoteBranch),{relation:"behind",pulled:state.behind}}var BranchCheckoutError,init_branch_checkout=__esm({"src/cli/utils/branch-checkout.ts"(){init_git_credential_setup();init_git();BranchCheckoutError=class extends Error{constructor(code2,message,hint){super(message);this.code=code2;this.hint=hint;this.name="BranchCheckoutError"}static{__name(this,"BranchCheckoutError")}};__name(remoteRef,"remoteRef");__name(remoteHeadOrNull,"remoteHeadOrNull");__name(relationFromCounts,"relationFromCounts");__name(inspectBranchCheckout,"inspectBranchCheckout");__name(hasPathChanges,"hasPathChanges");__name(assertLocaleMutationState,"assertLocaleMutationState");__name(planLocaleMutationCheckout,"planLocaleMutationCheckout");__name(applyLocaleMutationCheckoutPlan,"applyLocaleMutationCheckoutPlan");__name(recoveryCommands,"recoveryCommands");__name(synchronizeLocaleMutationCheckout,"synchronizeLocaleMutationCheckout");__name(inspectPublishSource,"inspectPublishSource");__name(prepareDeployCheckout,"prepareDeployCheckout");__name(hasCommits,"hasCommits");__name(fastForwardPull,"fastForwardPull");__name(pullCheckout,"pullCheckout")}});var require_common=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/common.js"(exports2,module2){"use strict";function isNothing(subject){return typeof subject>"u"||subject===null}__name(isNothing,"isNothing");function isObject2(subject){return typeof subject=="object"&&subject!==null}__name(isObject2,"isObject");function toArray(sequence){return Array.isArray(sequence)?sequence:isNothing(sequence)?[]:[sequence]}__name(toArray,"toArray");function extend(target,source){var index,length,key,sourceKeys;if(source)for(sourceKeys=Object.keys(source),index=0,length=sourceKeys.length;index<length;index+=1)key=sourceKeys[index],target[key]=source[key];return target}__name(extend,"extend");function repeat(string,count){var result="",cycle;for(cycle=0;cycle<count;cycle+=1)result+=string;return result}__name(repeat,"repeat");function isNegativeZero(number){return number===0&&Number.NEGATIVE_INFINITY===1/number}__name(isNegativeZero,"isNegativeZero");module2.exports.isNothing=isNothing;module2.exports.isObject=isObject2;module2.exports.toArray=toArray;module2.exports.repeat=repeat;module2.exports.isNegativeZero=isNegativeZero;module2.exports.extend=extend}});var require_exception=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/exception.js"(exports2,module2){"use strict";function YAMLException(reason,mark){Error.call(this),this.name="YAMLException",this.reason=reason,this.mark=mark,this.message=(this.reason||"(unknown reason)")+(this.mark?" "+this.mark.toString():""),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}__name(YAMLException,"YAMLException");YAMLException.prototype=Object.create(Error.prototype);YAMLException.prototype.constructor=YAMLException;YAMLException.prototype.toString=__name(function(compact2){var result=this.name+": ";return result+=this.reason||"(unknown reason)",!compact2&&this.mark&&(result+=" "+this.mark.toString()),result},"toString");module2.exports=YAMLException}});var require_mark=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/mark.js"(exports2,module2){"use strict";var common=require_common();function Mark(name,buffer,position,line,column){this.name=name,this.buffer=buffer,this.position=position,this.line=line,this.column=column}__name(Mark,"Mark");Mark.prototype.getSnippet=__name(function(indent,maxLength){var head,start,tail,end,snippet;if(!this.buffer)return null;for(indent=indent||4,maxLength=maxLength||75,head="",start=this.position;start>0&&`\0\r
|
|
52
|
+
`);if(eventName==="progress")try{onProgress?.(JSON.parse(payload))}catch{}else if(eventName==="complete"){completed=!0;try{let complete=JSON.parse(payload);readiness=complete.readiness??null,timings=complete.timings??null}catch{}}else if(eventName==="error"){let parsed;try{parsed=JSON.parse(payload)}catch{parsed=void 0}let result=SandboxPullFailureSchema.safeParse(parsed);failure=result.success?result.data:{message:"Sandbox pull failed"}}}}}finally{reader.releaseLock()}if(failure)throw new SandboxPullError(failure);if(!completed)throw new Error("Sandbox pull stream ended before completion");return{readiness:readiness??{status:"skipped",reason:"not_reported",durationMs:0},timings:timings??{dependencyInstallMs:0,serverStartMs:0,readinessMs:readiness?.durationMs??0,totalSandboxMs:0}}}}}function createSupportService(cfg=loadConfig()){let transport=createCliHttpTransport(cfg);return{async submit(input){return(await transport.request("/api/support/issues",{method:"POST",body:JSON.stringify(input)})).data}}}function createTelemetryService(cfg=loadConfig()){let transport=createCliHttpTransport(cfg);return{async trackProjectEvent(projectId2,event,properties={}){await transport.request(`/api/management/projects/${projectId2}/track`,{method:"POST",body:JSON.stringify({event,properties})})}}}var SandboxPullError,init_project_services=__esm({"src/cli/services/project-services.ts"(){init_esm();init_config();init_sdk_transport();__name(recoverTenantApiBaseUrl,"recoverTenantApiBaseUrl");__name(createIdentityService,"createIdentityService");__name(createGitService,"createGitService");__name(createPublicationControlService,"createPublicationControlService");__name(publicationIdFromError,"publicationIdFromError");__name(transferBlockersFromError,"transferBlockersFromError");SandboxPullError=class extends Error{static{__name(this,"SandboxPullError")}failure;constructor(failure){super(failure.message),this.name="SandboxPullError",this.failure=failure}};__name(createSandboxService,"createSandboxService");__name(createSupportService,"createSupportService");__name(createTelemetryService,"createTelemetryService")}});function colorEnabled(opts={}){if(opts.forceDisable)return!1;let env=opts.env??process.env;return env.NO_COLOR&&env.NO_COLOR.length>0?!1:env.FORCE_COLOR&&env.FORCE_COLOR!=="0"&&env.FORCE_COLOR!=="false"?!0:(opts.isTTY??process.stdout.isTTY??!1)===!0}function makeColorPalette(opts={}){let on=colorEnabled(opts),wrap=__name(style=>s=>on?`${ANSI[style]}${s}${ANSI.reset}`:s,"wrap");return{enabled:on,bold:wrap("bold"),dim:wrap("dim"),red:wrap("red"),green:wrap("green"),yellow:wrap("yellow"),blue:wrap("blue"),magenta:wrap("magenta"),cyan:wrap("cyan"),gray:wrap("gray")}}var ANSI,palette,init_color=__esm({"src/cli/utils/format/color.ts"(){ANSI={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m"};__name(colorEnabled,"colorEnabled");__name(makeColorPalette,"makeColorPalette");palette=makeColorPalette()}});function planRemoteConfig(remoteUrl){let u2=new URL(remoteUrl),cleanUrl=`${u2.protocol}//${u2.host}${u2.pathname}`,credentialKey=`credential.${u2.protocol}//${u2.host}`;return{cleanUrl,credentialKey}}function shellQuote(value){return`'${value.replace(/'/g,"'\\''")}'`}function credentialHelperCommand(argv=process.argv){let entry=argv[1];return entry?`!${shellQuote(process.execPath)} ${shellQuote(entry)} git-credential`:"!fimo git-credential"}async function ensureFimoRemote(cwd,remoteUrl){let{cleanUrl,credentialKey}=planRemoteConfig(remoteUrl);await runGit(["remote","set-url","fimo",cleanUrl],cwd).catch(async()=>{await runGit(["remote","add","fimo",cleanUrl],cwd)}),await runGit(["config","--unset-all",`${credentialKey}.helper`],cwd).catch(()=>{}),await runGit(["config","--add",`${credentialKey}.helper`,""],cwd),await runGit(["config","--add",`${credentialKey}.helper`,credentialHelperCommand()],cwd),await runGit(["config",`${credentialKey}.useHttpPath`,"true"],cwd),await runGit(["config",`${credentialKey}.username`,"t"],cwd)}var init_git_credential_setup=__esm({"src/cli/utils/git-credential-setup.ts"(){init_git();__name(planRemoteConfig,"planRemoteConfig");__name(shellQuote,"shellQuote");__name(credentialHelperCommand,"credentialHelperCommand");__name(ensureFimoRemote,"ensureFimoRemote")}});import path9 from"node:path";function remoteRef(remoteBranch,remote=FIMO_REMOTE){return`refs/remotes/${remote}/${remoteBranch}`}async function remoteHeadOrNull(cwd,remoteBranch,remote=FIMO_REMOTE){try{return await runGit(["rev-parse","--verify",remoteRef(remoteBranch,remote)],cwd)}catch{return null}}function relationFromCounts(ahead,behind){return ahead===0&&behind===0?"in-sync":ahead>0&&behind===0?"ahead":ahead===0&&behind>0?"behind":"diverged"}async function inspectBranchCheckout(args){let remote=args.remote??FIMO_REMOTE;args.fetch!==!1&&await runGit(["fetch","--quiet","--no-tags","--prune",remote],args.cwd);let[localBranch,localHead,remoteHead]=await Promise.all([currentBranch2(args.cwd),runGit(["rev-parse","HEAD"],args.cwd),remoteHeadOrNull(args.cwd,args.remoteBranch,remote)]);if(!remoteHead)return{localBranch,remoteBranch:args.remoteBranch,localHead,remoteHead:null,ahead:0,behind:0,relation:"missing-remote"};let counts=await runGit(["rev-list","--left-right","--count",`HEAD...${remoteRef(args.remoteBranch,remote)}`],args.cwd),[ahead=0,behind=0]=counts.split(/\s+/).map(Number);return{localBranch,remoteBranch:args.remoteBranch,localHead,remoteHead,ahead,behind,relation:relationFromCounts(ahead,behind)}}async function hasPathChanges(cwd,filePath){let relativePath=path9.relative(cwd,filePath);return(await runGit(["status","--porcelain","--",relativePath],cwd)).length>0}function assertLocaleMutationState(state,remote){if(state.localBranch!==state.remoteBranch)throw new BranchCheckoutError("ENV_BRANCH_MISMATCH",`The selected environment uses branch '${state.remoteBranch}', but the checkout is on '${state.localBranch}'.`,`Switch to '${state.remoteBranch}' before changing its locales.`);if(state.relation==="missing-remote")throw new BranchCheckoutError("ENV_REMOTE_MISSING",`The environment branch '${remote}/${state.remoteBranch}' does not exist yet.`,"Deploy the project before changing its locale lifecycle.");if(state.relation==="ahead")throw new BranchCheckoutError("ENV_BRANCH_AHEAD",`The local branch is ${state.ahead} commit${state.ahead===1?"":"s"} ahead of ${remote}/${state.remoteBranch}.`,"Deploy those commits first, then run the locale command again.");if(state.relation==="diverged")throw new BranchCheckoutError("ENV_BRANCH_DIVERGED",`The local branch and ${remote}/${state.remoteBranch} have diverged.`,"Reconcile the branches before changing the environment locales.")}async function planLocaleMutationCheckout(args){let remote=args.remote??FIMO_REMOTE,state=await inspectBranchCheckout({...args,remote});if(assertLocaleMutationState(state,remote),await hasPathChanges(args.cwd,args.configPath))throw new BranchCheckoutError("ENV_CONFIG_DIRTY","The project config has uncommitted changes.","Commit, discard, or deploy the config change before changing locales.");if(state.relation==="behind"&&await hasUncommittedChanges(args.cwd))throw new BranchCheckoutError("ENV_BRANCH_BEHIND_DIRTY",`The checkout is behind ${remote}/${state.remoteBranch} and has uncommitted changes.`,"Stash the changes, then run the locale command again.");return{cwd:args.cwd,configPath:args.configPath,remote,state}}async function applyLocaleMutationCheckoutPlan(plan){let current=await inspectBranchCheckout({cwd:plan.cwd,remote:plan.remote,remoteBranch:plan.state.remoteBranch,fetch:!1});if(current.localBranch!==plan.state.localBranch||current.localHead!==plan.state.localHead||current.remoteHead!==plan.state.remoteHead)throw new BranchCheckoutError("ENV_CHECKOUT_CHANGED","The checkout changed after the locale operation was reviewed.","Review the current Git state and run the locale command again.");if(assertLocaleMutationState(current,plan.remote),await hasPathChanges(plan.cwd,plan.configPath))throw new BranchCheckoutError("ENV_CONFIG_DIRTY","The project config changed after the locale operation was reviewed.","Commit, discard, or deploy the config change, then run the locale command again.");if(current.relation==="behind"){if(await hasUncommittedChanges(plan.cwd))throw new BranchCheckoutError("ENV_BRANCH_BEHIND_DIRTY",`The checkout is behind ${plan.remote}/${current.remoteBranch} and now has uncommitted changes.`,"Stash the changes, then run the locale command again.");await runGit(["merge","--ff-only",remoteRef(current.remoteBranch,plan.remote)],plan.cwd)}}function recoveryCommands(remote,remoteBranch,localBranch,relation){let inspect=`git log --oneline --left-right HEAD...${remote}/${remoteBranch}`;return[...localBranch&&localBranch!==remoteBranch?[`git switch ${remoteBranch}`]:[],"git status",`git fetch ${remote}`,...relation==="ahead"||relation==="diverged"?[inspect]:[`git merge --ff-only ${remote}/${remoteBranch}`]]}async function synchronizeLocaleMutationCheckout(args){let remote=args.remote??FIMO_REMOTE,state;try{state=await inspectBranchCheckout({...args,remote})}catch(error){return{status:"required",reason:error instanceof Error?error.message:String(error),recovery:recoveryCommands(remote,args.remoteBranch)}}if(state.localBranch!==state.remoteBranch)return{status:"required",reason:`The checkout moved to '${state.localBranch}' after the remote locale change.`,recovery:recoveryCommands(remote,state.remoteBranch,state.localBranch,state.relation)};if(state.relation==="in-sync")return{status:"synchronized"};if(state.relation!=="behind")return{status:"required",reason:`The local branch is ${state.relation} relative to ${remote}/${state.remoteBranch}.`,recovery:recoveryCommands(remote,state.remoteBranch,void 0,state.relation)};try{return await runGit(["merge","--ff-only",remoteRef(state.remoteBranch,remote)],args.cwd),{status:"synchronized"}}catch(error){return{status:"required",reason:error instanceof Error?error.message:String(error),recovery:recoveryCommands(remote,state.remoteBranch)}}}async function inspectPublishSource(args){try{await ensureFimoRemote(args.cwd,args.remoteUrl);let localBranch=await currentBranch2(args.cwd).catch(()=>null);if(localBranch===null)return{status:"unavailable",reason:"the checkout is on a detached HEAD, not on a branch"};if(localBranch!==args.remoteBranch)return{status:"unavailable",reason:`the checkout is on '${localBranch}', not '${args.remoteBranch}'`};let state=await inspectBranchCheckout(args);return state.remoteHead===null?{status:"unavailable",reason:`the Fimo remote has no '${args.remoteBranch}' branch yet`}:{status:"known",remoteHead:state.remoteHead,unpushed:state.ahead,dirty:await hasUncommittedChanges(args.cwd)}}catch(error){return{status:"unavailable",reason:gitErrorSummary(error)}}}async function prepareDeployCheckout(args){let localBranch=await currentBranch2(args.cwd);if(localBranch!==args.remoteBranch)throw new BranchCheckoutError("ENV_BRANCH_MISMATCH",`Deploy requires branch '${args.remoteBranch}'; checkout is on '${localBranch}'.`,`Run 'fimo checkout ${args.remoteBranch}'.`);let state=await inspectBranchCheckout(args);if(state.relation==="missing-remote")return"missing-remote";if(state.relation==="in-sync"||state.relation==="ahead")return"ready";if(state.relation==="diverged")throw new BranchCheckoutError("ENV_BRANCH_DIVERGED",`The local checkout and fimo/${state.remoteBranch} have diverged.`,"Reconcile the branches before deploying.");if(await hasUncommittedChanges(args.cwd))throw new BranchCheckoutError("ENV_BRANCH_BEHIND_DIRTY",`The local checkout is behind fimo/${state.remoteBranch} and has uncommitted changes.`,"Stash the changes before deploying.");return await runGit(["merge","--ff-only",remoteRef(state.remoteBranch)],args.cwd),"ready"}async function hasCommits(cwd){try{return await runGit(["rev-parse","--verify","--quiet","HEAD"],cwd),!0}catch{return!1}}async function fastForwardPull(cwd,remoteBranch){if((await runGit(["status","--porcelain","--untracked-files=no"],cwd)).length>0)throw new BranchCheckoutError("ENV_BRANCH_BEHIND_DIRTY",`The local checkout is behind fimo/${remoteBranch} and has uncommitted changes.`,"Commit or stash the changes before pulling.");await runGit(["merge","--ff-only",remoteRef(remoteBranch)],cwd)}async function pullCheckout(args){let localBranch=await currentBranch2(args.cwd).catch(()=>null);if(localBranch!==args.remoteBranch)throw new BranchCheckoutError("ENV_BRANCH_MISMATCH",`Pull requires branch '${args.remoteBranch}'; checkout is on ${localBranch===null?"a detached HEAD":`'${localBranch}'`}.`,`Run 'fimo checkout ${args.remoteBranch}'.`);if(!await hasCommits(args.cwd)){if(await runGit(["fetch","--quiet","--no-tags","--prune","fimo"],args.cwd),await remoteHeadOrNull(args.cwd,args.remoteBranch)===null)return{relation:"missing-remote",pulled:0};let pulled=Number(await runGit(["rev-list","--count",remoteRef(args.remoteBranch)],args.cwd));return await fastForwardPull(args.cwd,args.remoteBranch),{relation:"behind",pulled}}let state=await inspectBranchCheckout(args);if(state.relation==="missing-remote"||state.relation==="in-sync"||state.relation==="ahead")return{relation:state.relation,pulled:0};if(state.relation==="diverged")throw new BranchCheckoutError("ENV_BRANCH_DIVERGED",`The local checkout and fimo/${state.remoteBranch} have diverged.`,`Reconcile the branches with 'git pull --rebase fimo ${state.remoteBranch}' before pulling.`);return await fastForwardPull(args.cwd,state.remoteBranch),{relation:"behind",pulled:state.behind}}var BranchCheckoutError,FIMO_REMOTE,init_branch_checkout=__esm({"src/cli/utils/branch-checkout.ts"(){init_git_credential_setup();init_git();BranchCheckoutError=class extends Error{constructor(code2,message,hint){super(message);this.code=code2;this.hint=hint;this.name="BranchCheckoutError"}static{__name(this,"BranchCheckoutError")}},FIMO_REMOTE="fimo";__name(remoteRef,"remoteRef");__name(remoteHeadOrNull,"remoteHeadOrNull");__name(relationFromCounts,"relationFromCounts");__name(inspectBranchCheckout,"inspectBranchCheckout");__name(hasPathChanges,"hasPathChanges");__name(assertLocaleMutationState,"assertLocaleMutationState");__name(planLocaleMutationCheckout,"planLocaleMutationCheckout");__name(applyLocaleMutationCheckoutPlan,"applyLocaleMutationCheckoutPlan");__name(recoveryCommands,"recoveryCommands");__name(synchronizeLocaleMutationCheckout,"synchronizeLocaleMutationCheckout");__name(inspectPublishSource,"inspectPublishSource");__name(prepareDeployCheckout,"prepareDeployCheckout");__name(hasCommits,"hasCommits");__name(fastForwardPull,"fastForwardPull");__name(pullCheckout,"pullCheckout")}});var require_common=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/common.js"(exports2,module2){"use strict";function isNothing(subject){return typeof subject>"u"||subject===null}__name(isNothing,"isNothing");function isObject2(subject){return typeof subject=="object"&&subject!==null}__name(isObject2,"isObject");function toArray(sequence){return Array.isArray(sequence)?sequence:isNothing(sequence)?[]:[sequence]}__name(toArray,"toArray");function extend(target,source){var index,length,key,sourceKeys;if(source)for(sourceKeys=Object.keys(source),index=0,length=sourceKeys.length;index<length;index+=1)key=sourceKeys[index],target[key]=source[key];return target}__name(extend,"extend");function repeat(string,count){var result="",cycle;for(cycle=0;cycle<count;cycle+=1)result+=string;return result}__name(repeat,"repeat");function isNegativeZero(number){return number===0&&Number.NEGATIVE_INFINITY===1/number}__name(isNegativeZero,"isNegativeZero");module2.exports.isNothing=isNothing;module2.exports.isObject=isObject2;module2.exports.toArray=toArray;module2.exports.repeat=repeat;module2.exports.isNegativeZero=isNegativeZero;module2.exports.extend=extend}});var require_exception=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/exception.js"(exports2,module2){"use strict";function YAMLException(reason,mark){Error.call(this),this.name="YAMLException",this.reason=reason,this.mark=mark,this.message=(this.reason||"(unknown reason)")+(this.mark?" "+this.mark.toString():""),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}__name(YAMLException,"YAMLException");YAMLException.prototype=Object.create(Error.prototype);YAMLException.prototype.constructor=YAMLException;YAMLException.prototype.toString=__name(function(compact2){var result=this.name+": ";return result+=this.reason||"(unknown reason)",!compact2&&this.mark&&(result+=" "+this.mark.toString()),result},"toString");module2.exports=YAMLException}});var require_mark=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/mark.js"(exports2,module2){"use strict";var common=require_common();function Mark(name,buffer,position,line,column){this.name=name,this.buffer=buffer,this.position=position,this.line=line,this.column=column}__name(Mark,"Mark");Mark.prototype.getSnippet=__name(function(indent,maxLength){var head,start,tail,end,snippet;if(!this.buffer)return null;for(indent=indent||4,maxLength=maxLength||75,head="",start=this.position;start>0&&`\0\r
|
|
53
53
|
\x85\u2028\u2029`.indexOf(this.buffer.charAt(start-1))===-1;)if(start-=1,this.position-start>maxLength/2-1){head=" ... ",start+=5;break}for(tail="",end=this.position;end<this.buffer.length&&`\0\r
|
|
54
54
|
\x85\u2028\u2029`.indexOf(this.buffer.charAt(end))===-1;)if(end+=1,end-this.position>maxLength/2-1){tail=" ... ",end-=5;break}return snippet=this.buffer.slice(start,end),common.repeat(" ",indent)+head+snippet+tail+`
|
|
55
55
|
`+common.repeat(" ",indent+this.position-start+head.length)+"^"},"getSnippet");Mark.prototype.toString=__name(function(compact2){var snippet,where="";return this.name&&(where+='in "'+this.name+'" '),where+="at line "+(this.line+1)+", column "+(this.column+1),compact2||(snippet=this.getSnippet(),snippet&&(where+=`:
|
|
56
|
-
`+snippet)),where},"toString");module2.exports=Mark}});var require_type=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type.js"(exports2,module2){"use strict";var YAMLException=require_exception(),TYPE_CONSTRUCTOR_OPTIONS=["kind","resolve","construct","instanceOf","predicate","represent","defaultStyle","styleAliases"],YAML_NODE_KINDS=["scalar","sequence","mapping"];function compileStyleAliases(map){var result={};return map!==null&&Object.keys(map).forEach(function(style){map[style].forEach(function(alias){result[String(alias)]=style})}),result}__name(compileStyleAliases,"compileStyleAliases");function Type(tag,options){if(options=options||{},Object.keys(options).forEach(function(name){if(TYPE_CONSTRUCTOR_OPTIONS.indexOf(name)===-1)throw new YAMLException('Unknown option "'+name+'" is met in definition of "'+tag+'" YAML type.')}),this.tag=tag,this.kind=options.kind||null,this.resolve=options.resolve||function(){return!0},this.construct=options.construct||function(data){return data},this.instanceOf=options.instanceOf||null,this.predicate=options.predicate||null,this.represent=options.represent||null,this.defaultStyle=options.defaultStyle||null,this.styleAliases=compileStyleAliases(options.styleAliases||null),YAML_NODE_KINDS.indexOf(this.kind)===-1)throw new YAMLException('Unknown kind "'+this.kind+'" is specified for "'+tag+'" YAML type.')}__name(Type,"Type");module2.exports=Type}});var require_schema=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/schema.js"(exports2,module2){"use strict";var common=require_common(),YAMLException=require_exception(),Type=require_type();function compileList(schema,name,result){var exclude=[];return schema.include.forEach(function(includedSchema){result=compileList(includedSchema,name,result)}),schema[name].forEach(function(currentType){result.forEach(function(previousType,previousIndex){previousType.tag===currentType.tag&&previousType.kind===currentType.kind&&exclude.push(previousIndex)}),result.push(currentType)}),result.filter(function(type,index){return exclude.indexOf(index)===-1})}__name(compileList,"compileList");function compileMap(){var result={scalar:{},sequence:{},mapping:{},fallback:{}},index,length;function collectType(type){result[type.kind][type.tag]=result.fallback[type.tag]=type}for(__name(collectType,"collectType"),index=0,length=arguments.length;index<length;index+=1)arguments[index].forEach(collectType);return result}__name(compileMap,"compileMap");function Schema(definition){this.include=definition.include||[],this.implicit=definition.implicit||[],this.explicit=definition.explicit||[],this.implicit.forEach(function(type){if(type.loadKind&&type.loadKind!=="scalar")throw new YAMLException("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.")}),this.compiledImplicit=compileList(this,"implicit",[]),this.compiledExplicit=compileList(this,"explicit",[]),this.compiledTypeMap=compileMap(this.compiledImplicit,this.compiledExplicit)}__name(Schema,"Schema");Schema.DEFAULT=null;Schema.create=__name(function(){var schemas3,types;switch(arguments.length){case 1:schemas3=Schema.DEFAULT,types=arguments[0];break;case 2:schemas3=arguments[0],types=arguments[1];break;default:throw new YAMLException("Wrong number of arguments for Schema.create function")}if(schemas3=common.toArray(schemas3),types=common.toArray(types),!schemas3.every(function(schema){return schema instanceof Schema}))throw new YAMLException("Specified list of super schemas (or a single Schema object) contains a non-Schema object.");if(!types.every(function(type){return type instanceof Type}))throw new YAMLException("Specified list of YAML types (or a single Type object) contains a non-Type object.");return new Schema({include:schemas3,explicit:types})},"createSchema");module2.exports=Schema}});var require_str=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type/str.js"(exports2,module2){"use strict";var Type=require_type();module2.exports=new Type("tag:yaml.org,2002:str",{kind:"scalar",construct:__name(function(data){return data!==null?data:""},"construct")})}});var require_seq=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type/seq.js"(exports2,module2){"use strict";var Type=require_type();module2.exports=new Type("tag:yaml.org,2002:seq",{kind:"sequence",construct:__name(function(data){return data!==null?data:[]},"construct")})}});var require_map=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type/map.js"(exports2,module2){"use strict";var Type=require_type();module2.exports=new Type("tag:yaml.org,2002:map",{kind:"mapping",construct:__name(function(data){return data!==null?data:{}},"construct")})}});var require_failsafe=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/schema/failsafe.js"(exports2,module2){"use strict";var Schema=require_schema();module2.exports=new Schema({explicit:[require_str(),require_seq(),require_map()]})}});var require_null=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type/null.js"(exports2,module2){"use strict";var Type=require_type();function resolveYamlNull(data){if(data===null)return!0;var max=data.length;return max===1&&data==="~"||max===4&&(data==="null"||data==="Null"||data==="NULL")}__name(resolveYamlNull,"resolveYamlNull");function constructYamlNull(){return null}__name(constructYamlNull,"constructYamlNull");function isNull(object){return object===null}__name(isNull,"isNull");module2.exports=new Type("tag:yaml.org,2002:null",{kind:"scalar",resolve:resolveYamlNull,construct:constructYamlNull,predicate:isNull,represent:{canonical:__name(function(){return"~"},"canonical"),lowercase:__name(function(){return"null"},"lowercase"),uppercase:__name(function(){return"NULL"},"uppercase"),camelcase:__name(function(){return"Null"},"camelcase")},defaultStyle:"lowercase"})}});var require_bool=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type/bool.js"(exports2,module2){"use strict";var Type=require_type();function resolveYamlBoolean(data){if(data===null)return!1;var max=data.length;return max===4&&(data==="true"||data==="True"||data==="TRUE")||max===5&&(data==="false"||data==="False"||data==="FALSE")}__name(resolveYamlBoolean,"resolveYamlBoolean");function constructYamlBoolean(data){return data==="true"||data==="True"||data==="TRUE"}__name(constructYamlBoolean,"constructYamlBoolean");function isBoolean(object){return Object.prototype.toString.call(object)==="[object Boolean]"}__name(isBoolean,"isBoolean");module2.exports=new Type("tag:yaml.org,2002:bool",{kind:"scalar",resolve:resolveYamlBoolean,construct:constructYamlBoolean,predicate:isBoolean,represent:{lowercase:__name(function(object){return object?"true":"false"},"lowercase"),uppercase:__name(function(object){return object?"TRUE":"FALSE"},"uppercase"),camelcase:__name(function(object){return object?"True":"False"},"camelcase")},defaultStyle:"lowercase"})}});var require_int=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type/int.js"(exports2,module2){"use strict";var common=require_common(),Type=require_type();function isHexCode(c2){return 48<=c2&&c2<=57||65<=c2&&c2<=70||97<=c2&&c2<=102}__name(isHexCode,"isHexCode");function isOctCode(c2){return 48<=c2&&c2<=55}__name(isOctCode,"isOctCode");function isDecCode(c2){return 48<=c2&&c2<=57}__name(isDecCode,"isDecCode");function resolveYamlInteger(data){if(data===null)return!1;var max=data.length,index=0,hasDigits=!1,ch;if(!max)return!1;if(ch=data[index],(ch==="-"||ch==="+")&&(ch=data[++index]),ch==="0"){if(index+1===max)return!0;if(ch=data[++index],ch==="b"){for(index++;index<max;index++)if(ch=data[index],ch!=="_"){if(ch!=="0"&&ch!=="1")return!1;hasDigits=!0}return hasDigits&&ch!=="_"}if(ch==="x"){for(index++;index<max;index++)if(ch=data[index],ch!=="_"){if(!isHexCode(data.charCodeAt(index)))return!1;hasDigits=!0}return hasDigits&&ch!=="_"}for(;index<max;index++)if(ch=data[index],ch!=="_"){if(!isOctCode(data.charCodeAt(index)))return!1;hasDigits=!0}return hasDigits&&ch!=="_"}if(ch==="_")return!1;for(;index<max;index++)if(ch=data[index],ch!=="_"){if(ch===":")break;if(!isDecCode(data.charCodeAt(index)))return!1;hasDigits=!0}return!hasDigits||ch==="_"?!1:ch!==":"?!0:/^(:[0-5]?[0-9])+$/.test(data.slice(index))}__name(resolveYamlInteger,"resolveYamlInteger");function constructYamlInteger(data){var value=data,sign=1,ch,base,digits=[];return value.indexOf("_")!==-1&&(value=value.replace(/_/g,"")),ch=value[0],(ch==="-"||ch==="+")&&(ch==="-"&&(sign=-1),value=value.slice(1),ch=value[0]),value==="0"?0:ch==="0"?value[1]==="b"?sign*parseInt(value.slice(2),2):value[1]==="x"?sign*parseInt(value,16):sign*parseInt(value,8):value.indexOf(":")!==-1?(value.split(":").forEach(function(v){digits.unshift(parseInt(v,10))}),value=0,base=1,digits.forEach(function(d3){value+=d3*base,base*=60}),sign*value):sign*parseInt(value,10)}__name(constructYamlInteger,"constructYamlInteger");function isInteger2(object){return Object.prototype.toString.call(object)==="[object Number]"&&object%1===0&&!common.isNegativeZero(object)}__name(isInteger2,"isInteger");module2.exports=new Type("tag:yaml.org,2002:int",{kind:"scalar",resolve:resolveYamlInteger,construct:constructYamlInteger,predicate:isInteger2,represent:{binary:__name(function(obj){return obj>=0?"0b"+obj.toString(2):"-0b"+obj.toString(2).slice(1)},"binary"),octal:__name(function(obj){return obj>=0?"0"+obj.toString(8):"-0"+obj.toString(8).slice(1)},"octal"),decimal:__name(function(obj){return obj.toString(10)},"decimal"),hexadecimal:__name(function(obj){return obj>=0?"0x"+obj.toString(16).toUpperCase():"-0x"+obj.toString(16).toUpperCase().slice(1)},"hexadecimal")},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}})}});var require_float=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type/float.js"(exports2,module2){"use strict";var common=require_common(),Type=require_type(),YAML_FLOAT_PATTERN=new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function resolveYamlFloat(data){return!(data===null||!YAML_FLOAT_PATTERN.test(data)||data[data.length-1]==="_")}__name(resolveYamlFloat,"resolveYamlFloat");function constructYamlFloat(data){var value,sign,base,digits;return value=data.replace(/_/g,"").toLowerCase(),sign=value[0]==="-"?-1:1,digits=[],"+-".indexOf(value[0])>=0&&(value=value.slice(1)),value===".inf"?sign===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:value===".nan"?NaN:value.indexOf(":")>=0?(value.split(":").forEach(function(v){digits.unshift(parseFloat(v,10))}),value=0,base=1,digits.forEach(function(d3){value+=d3*base,base*=60}),sign*value):sign*parseFloat(value,10)}__name(constructYamlFloat,"constructYamlFloat");var SCIENTIFIC_WITHOUT_DOT=/^[-+]?[0-9]+e/;function representYamlFloat(object,style){var res;if(isNaN(object))switch(style){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===object)switch(style){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===object)switch(style){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(common.isNegativeZero(object))return"-0.0";return res=object.toString(10),SCIENTIFIC_WITHOUT_DOT.test(res)?res.replace("e",".e"):res}__name(representYamlFloat,"representYamlFloat");function isFloat2(object){return Object.prototype.toString.call(object)==="[object Number]"&&(object%1!==0||common.isNegativeZero(object))}__name(isFloat2,"isFloat");module2.exports=new Type("tag:yaml.org,2002:float",{kind:"scalar",resolve:resolveYamlFloat,construct:constructYamlFloat,predicate:isFloat2,represent:representYamlFloat,defaultStyle:"lowercase"})}});var require_json=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/schema/json.js"(exports2,module2){"use strict";var Schema=require_schema();module2.exports=new Schema({include:[require_failsafe()],implicit:[require_null(),require_bool(),require_int(),require_float()]})}});var require_core=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/schema/core.js"(exports2,module2){"use strict";var Schema=require_schema();module2.exports=new Schema({include:[require_json()]})}});var require_timestamp=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type/timestamp.js"(exports2,module2){"use strict";var Type=require_type(),YAML_DATE_REGEXP=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),YAML_TIMESTAMP_REGEXP=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");function resolveYamlTimestamp(data){return data===null?!1:YAML_DATE_REGEXP.exec(data)!==null||YAML_TIMESTAMP_REGEXP.exec(data)!==null}__name(resolveYamlTimestamp,"resolveYamlTimestamp");function constructYamlTimestamp(data){var match,year,month,day2,hour,minute,second,fraction=0,delta=null,tz_hour,tz_minute,date;if(match=YAML_DATE_REGEXP.exec(data),match===null&&(match=YAML_TIMESTAMP_REGEXP.exec(data)),match===null)throw new Error("Date resolve error");if(year=+match[1],month=+match[2]-1,day2=+match[3],!match[4])return new Date(Date.UTC(year,month,day2));if(hour=+match[4],minute=+match[5],second=+match[6],match[7]){for(fraction=match[7].slice(0,3);fraction.length<3;)fraction+="0";fraction=+fraction}return match[9]&&(tz_hour=+match[10],tz_minute=+(match[11]||0),delta=(tz_hour*60+tz_minute)*6e4,match[9]==="-"&&(delta=-delta)),date=new Date(Date.UTC(year,month,day2,hour,minute,second,fraction)),delta&&date.setTime(date.getTime()-delta),date}__name(constructYamlTimestamp,"constructYamlTimestamp");function representYamlTimestamp(object){return object.toISOString()}__name(representYamlTimestamp,"representYamlTimestamp");module2.exports=new Type("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:resolveYamlTimestamp,construct:constructYamlTimestamp,instanceOf:Date,represent:representYamlTimestamp})}});var require_merge=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type/merge.js"(exports2,module2){"use strict";var Type=require_type();function resolveYamlMerge(data){return data==="<<"||data===null}__name(resolveYamlMerge,"resolveYamlMerge");module2.exports=new Type("tag:yaml.org,2002:merge",{kind:"scalar",resolve:resolveYamlMerge})}});var require_binary=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type/binary.js"(exports2,module2){"use strict";var NodeBuffer;try{_require=__require,NodeBuffer=_require("buffer").Buffer}catch{}var _require,Type=require_type(),BASE64_MAP=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
|
|
56
|
+
`+snippet)),where},"toString");module2.exports=Mark}});var require_type=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type.js"(exports2,module2){"use strict";var YAMLException=require_exception(),TYPE_CONSTRUCTOR_OPTIONS=["kind","resolve","construct","instanceOf","predicate","represent","defaultStyle","styleAliases"],YAML_NODE_KINDS=["scalar","sequence","mapping"];function compileStyleAliases(map){var result={};return map!==null&&Object.keys(map).forEach(function(style){map[style].forEach(function(alias){result[String(alias)]=style})}),result}__name(compileStyleAliases,"compileStyleAliases");function Type(tag,options){if(options=options||{},Object.keys(options).forEach(function(name){if(TYPE_CONSTRUCTOR_OPTIONS.indexOf(name)===-1)throw new YAMLException('Unknown option "'+name+'" is met in definition of "'+tag+'" YAML type.')}),this.tag=tag,this.kind=options.kind||null,this.resolve=options.resolve||function(){return!0},this.construct=options.construct||function(data){return data},this.instanceOf=options.instanceOf||null,this.predicate=options.predicate||null,this.represent=options.represent||null,this.defaultStyle=options.defaultStyle||null,this.styleAliases=compileStyleAliases(options.styleAliases||null),YAML_NODE_KINDS.indexOf(this.kind)===-1)throw new YAMLException('Unknown kind "'+this.kind+'" is specified for "'+tag+'" YAML type.')}__name(Type,"Type");module2.exports=Type}});var require_schema=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/schema.js"(exports2,module2){"use strict";var common=require_common(),YAMLException=require_exception(),Type=require_type();function compileList(schema,name,result){var exclude=[];return schema.include.forEach(function(includedSchema){result=compileList(includedSchema,name,result)}),schema[name].forEach(function(currentType){result.forEach(function(previousType,previousIndex){previousType.tag===currentType.tag&&previousType.kind===currentType.kind&&exclude.push(previousIndex)}),result.push(currentType)}),result.filter(function(type,index){return exclude.indexOf(index)===-1})}__name(compileList,"compileList");function compileMap(){var result={scalar:{},sequence:{},mapping:{},fallback:{}},index,length;function collectType(type){result[type.kind][type.tag]=result.fallback[type.tag]=type}for(__name(collectType,"collectType"),index=0,length=arguments.length;index<length;index+=1)arguments[index].forEach(collectType);return result}__name(compileMap,"compileMap");function Schema(definition){this.include=definition.include||[],this.implicit=definition.implicit||[],this.explicit=definition.explicit||[],this.implicit.forEach(function(type){if(type.loadKind&&type.loadKind!=="scalar")throw new YAMLException("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.")}),this.compiledImplicit=compileList(this,"implicit",[]),this.compiledExplicit=compileList(this,"explicit",[]),this.compiledTypeMap=compileMap(this.compiledImplicit,this.compiledExplicit)}__name(Schema,"Schema");Schema.DEFAULT=null;Schema.create=__name(function(){var schemas3,types;switch(arguments.length){case 1:schemas3=Schema.DEFAULT,types=arguments[0];break;case 2:schemas3=arguments[0],types=arguments[1];break;default:throw new YAMLException("Wrong number of arguments for Schema.create function")}if(schemas3=common.toArray(schemas3),types=common.toArray(types),!schemas3.every(function(schema){return schema instanceof Schema}))throw new YAMLException("Specified list of super schemas (or a single Schema object) contains a non-Schema object.");if(!types.every(function(type){return type instanceof Type}))throw new YAMLException("Specified list of YAML types (or a single Type object) contains a non-Type object.");return new Schema({include:schemas3,explicit:types})},"createSchema");module2.exports=Schema}});var require_str=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type/str.js"(exports2,module2){"use strict";var Type=require_type();module2.exports=new Type("tag:yaml.org,2002:str",{kind:"scalar",construct:__name(function(data){return data!==null?data:""},"construct")})}});var require_seq=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type/seq.js"(exports2,module2){"use strict";var Type=require_type();module2.exports=new Type("tag:yaml.org,2002:seq",{kind:"sequence",construct:__name(function(data){return data!==null?data:[]},"construct")})}});var require_map=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type/map.js"(exports2,module2){"use strict";var Type=require_type();module2.exports=new Type("tag:yaml.org,2002:map",{kind:"mapping",construct:__name(function(data){return data!==null?data:{}},"construct")})}});var require_failsafe=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/schema/failsafe.js"(exports2,module2){"use strict";var Schema=require_schema();module2.exports=new Schema({explicit:[require_str(),require_seq(),require_map()]})}});var require_null=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type/null.js"(exports2,module2){"use strict";var Type=require_type();function resolveYamlNull(data){if(data===null)return!0;var max=data.length;return max===1&&data==="~"||max===4&&(data==="null"||data==="Null"||data==="NULL")}__name(resolveYamlNull,"resolveYamlNull");function constructYamlNull(){return null}__name(constructYamlNull,"constructYamlNull");function isNull(object){return object===null}__name(isNull,"isNull");module2.exports=new Type("tag:yaml.org,2002:null",{kind:"scalar",resolve:resolveYamlNull,construct:constructYamlNull,predicate:isNull,represent:{canonical:__name(function(){return"~"},"canonical"),lowercase:__name(function(){return"null"},"lowercase"),uppercase:__name(function(){return"NULL"},"uppercase"),camelcase:__name(function(){return"Null"},"camelcase")},defaultStyle:"lowercase"})}});var require_bool=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type/bool.js"(exports2,module2){"use strict";var Type=require_type();function resolveYamlBoolean(data){if(data===null)return!1;var max=data.length;return max===4&&(data==="true"||data==="True"||data==="TRUE")||max===5&&(data==="false"||data==="False"||data==="FALSE")}__name(resolveYamlBoolean,"resolveYamlBoolean");function constructYamlBoolean(data){return data==="true"||data==="True"||data==="TRUE"}__name(constructYamlBoolean,"constructYamlBoolean");function isBoolean(object){return Object.prototype.toString.call(object)==="[object Boolean]"}__name(isBoolean,"isBoolean");module2.exports=new Type("tag:yaml.org,2002:bool",{kind:"scalar",resolve:resolveYamlBoolean,construct:constructYamlBoolean,predicate:isBoolean,represent:{lowercase:__name(function(object){return object?"true":"false"},"lowercase"),uppercase:__name(function(object){return object?"TRUE":"FALSE"},"uppercase"),camelcase:__name(function(object){return object?"True":"False"},"camelcase")},defaultStyle:"lowercase"})}});var require_int=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type/int.js"(exports2,module2){"use strict";var common=require_common(),Type=require_type();function isHexCode(c2){return 48<=c2&&c2<=57||65<=c2&&c2<=70||97<=c2&&c2<=102}__name(isHexCode,"isHexCode");function isOctCode(c2){return 48<=c2&&c2<=55}__name(isOctCode,"isOctCode");function isDecCode(c2){return 48<=c2&&c2<=57}__name(isDecCode,"isDecCode");function resolveYamlInteger(data){if(data===null)return!1;var max=data.length,index=0,hasDigits=!1,ch;if(!max)return!1;if(ch=data[index],(ch==="-"||ch==="+")&&(ch=data[++index]),ch==="0"){if(index+1===max)return!0;if(ch=data[++index],ch==="b"){for(index++;index<max;index++)if(ch=data[index],ch!=="_"){if(ch!=="0"&&ch!=="1")return!1;hasDigits=!0}return hasDigits&&ch!=="_"}if(ch==="x"){for(index++;index<max;index++)if(ch=data[index],ch!=="_"){if(!isHexCode(data.charCodeAt(index)))return!1;hasDigits=!0}return hasDigits&&ch!=="_"}for(;index<max;index++)if(ch=data[index],ch!=="_"){if(!isOctCode(data.charCodeAt(index)))return!1;hasDigits=!0}return hasDigits&&ch!=="_"}if(ch==="_")return!1;for(;index<max;index++)if(ch=data[index],ch!=="_"){if(ch===":")break;if(!isDecCode(data.charCodeAt(index)))return!1;hasDigits=!0}return!hasDigits||ch==="_"?!1:ch!==":"?!0:/^(:[0-5]?[0-9])+$/.test(data.slice(index))}__name(resolveYamlInteger,"resolveYamlInteger");function constructYamlInteger(data){var value=data,sign=1,ch,base,digits=[];return value.indexOf("_")!==-1&&(value=value.replace(/_/g,"")),ch=value[0],(ch==="-"||ch==="+")&&(ch==="-"&&(sign=-1),value=value.slice(1),ch=value[0]),value==="0"?0:ch==="0"?value[1]==="b"?sign*parseInt(value.slice(2),2):value[1]==="x"?sign*parseInt(value,16):sign*parseInt(value,8):value.indexOf(":")!==-1?(value.split(":").forEach(function(v){digits.unshift(parseInt(v,10))}),value=0,base=1,digits.forEach(function(d3){value+=d3*base,base*=60}),sign*value):sign*parseInt(value,10)}__name(constructYamlInteger,"constructYamlInteger");function isInteger2(object){return Object.prototype.toString.call(object)==="[object Number]"&&object%1===0&&!common.isNegativeZero(object)}__name(isInteger2,"isInteger");module2.exports=new Type("tag:yaml.org,2002:int",{kind:"scalar",resolve:resolveYamlInteger,construct:constructYamlInteger,predicate:isInteger2,represent:{binary:__name(function(obj){return obj>=0?"0b"+obj.toString(2):"-0b"+obj.toString(2).slice(1)},"binary"),octal:__name(function(obj){return obj>=0?"0"+obj.toString(8):"-0"+obj.toString(8).slice(1)},"octal"),decimal:__name(function(obj){return obj.toString(10)},"decimal"),hexadecimal:__name(function(obj){return obj>=0?"0x"+obj.toString(16).toUpperCase():"-0x"+obj.toString(16).toUpperCase().slice(1)},"hexadecimal")},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}})}});var require_float=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type/float.js"(exports2,module2){"use strict";var common=require_common(),Type=require_type(),YAML_FLOAT_PATTERN=new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function resolveYamlFloat(data){return!(data===null||!YAML_FLOAT_PATTERN.test(data)||data[data.length-1]==="_")}__name(resolveYamlFloat,"resolveYamlFloat");function constructYamlFloat(data){var value,sign,base,digits;return value=data.replace(/_/g,"").toLowerCase(),sign=value[0]==="-"?-1:1,digits=[],"+-".indexOf(value[0])>=0&&(value=value.slice(1)),value===".inf"?sign===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:value===".nan"?NaN:value.indexOf(":")>=0?(value.split(":").forEach(function(v){digits.unshift(parseFloat(v,10))}),value=0,base=1,digits.forEach(function(d3){value+=d3*base,base*=60}),sign*value):sign*parseFloat(value,10)}__name(constructYamlFloat,"constructYamlFloat");var SCIENTIFIC_WITHOUT_DOT=/^[-+]?[0-9]+e/;function representYamlFloat(object,style){var res;if(isNaN(object))switch(style){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===object)switch(style){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===object)switch(style){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(common.isNegativeZero(object))return"-0.0";return res=object.toString(10),SCIENTIFIC_WITHOUT_DOT.test(res)?res.replace("e",".e"):res}__name(representYamlFloat,"representYamlFloat");function isFloat2(object){return Object.prototype.toString.call(object)==="[object Number]"&&(object%1!==0||common.isNegativeZero(object))}__name(isFloat2,"isFloat");module2.exports=new Type("tag:yaml.org,2002:float",{kind:"scalar",resolve:resolveYamlFloat,construct:constructYamlFloat,predicate:isFloat2,represent:representYamlFloat,defaultStyle:"lowercase"})}});var require_json=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/schema/json.js"(exports2,module2){"use strict";var Schema=require_schema();module2.exports=new Schema({include:[require_failsafe()],implicit:[require_null(),require_bool(),require_int(),require_float()]})}});var require_core=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/schema/core.js"(exports2,module2){"use strict";var Schema=require_schema();module2.exports=new Schema({include:[require_json()]})}});var require_timestamp=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type/timestamp.js"(exports2,module2){"use strict";var Type=require_type(),YAML_DATE_REGEXP=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),YAML_TIMESTAMP_REGEXP=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");function resolveYamlTimestamp(data){return data===null?!1:YAML_DATE_REGEXP.exec(data)!==null||YAML_TIMESTAMP_REGEXP.exec(data)!==null}__name(resolveYamlTimestamp,"resolveYamlTimestamp");function constructYamlTimestamp(data){var match,year,month,day3,hour,minute,second,fraction=0,delta=null,tz_hour,tz_minute,date;if(match=YAML_DATE_REGEXP.exec(data),match===null&&(match=YAML_TIMESTAMP_REGEXP.exec(data)),match===null)throw new Error("Date resolve error");if(year=+match[1],month=+match[2]-1,day3=+match[3],!match[4])return new Date(Date.UTC(year,month,day3));if(hour=+match[4],minute=+match[5],second=+match[6],match[7]){for(fraction=match[7].slice(0,3);fraction.length<3;)fraction+="0";fraction=+fraction}return match[9]&&(tz_hour=+match[10],tz_minute=+(match[11]||0),delta=(tz_hour*60+tz_minute)*6e4,match[9]==="-"&&(delta=-delta)),date=new Date(Date.UTC(year,month,day3,hour,minute,second,fraction)),delta&&date.setTime(date.getTime()-delta),date}__name(constructYamlTimestamp,"constructYamlTimestamp");function representYamlTimestamp(object){return object.toISOString()}__name(representYamlTimestamp,"representYamlTimestamp");module2.exports=new Type("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:resolveYamlTimestamp,construct:constructYamlTimestamp,instanceOf:Date,represent:representYamlTimestamp})}});var require_merge=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type/merge.js"(exports2,module2){"use strict";var Type=require_type();function resolveYamlMerge(data){return data==="<<"||data===null}__name(resolveYamlMerge,"resolveYamlMerge");module2.exports=new Type("tag:yaml.org,2002:merge",{kind:"scalar",resolve:resolveYamlMerge})}});var require_binary=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type/binary.js"(exports2,module2){"use strict";var NodeBuffer;try{_require=__require,NodeBuffer=_require("buffer").Buffer}catch{}var _require,Type=require_type(),BASE64_MAP=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
|
|
57
57
|
\r`;function resolveYamlBinary(data){if(data===null)return!1;var code2,idx,bitlen=0,max=data.length,map=BASE64_MAP;for(idx=0;idx<max;idx++)if(code2=map.indexOf(data.charAt(idx)),!(code2>64)){if(code2<0)return!1;bitlen+=6}return bitlen%8===0}__name(resolveYamlBinary,"resolveYamlBinary");function constructYamlBinary(data){var idx,tailbits,input=data.replace(/[\r\n=]/g,""),max=input.length,map=BASE64_MAP,bits=0,result=[];for(idx=0;idx<max;idx++)idx%4===0&&idx&&(result.push(bits>>16&255),result.push(bits>>8&255),result.push(bits&255)),bits=bits<<6|map.indexOf(input.charAt(idx));return tailbits=max%4*6,tailbits===0?(result.push(bits>>16&255),result.push(bits>>8&255),result.push(bits&255)):tailbits===18?(result.push(bits>>10&255),result.push(bits>>2&255)):tailbits===12&&result.push(bits>>4&255),NodeBuffer?NodeBuffer.from?NodeBuffer.from(result):new NodeBuffer(result):result}__name(constructYamlBinary,"constructYamlBinary");function representYamlBinary(object){var result="",bits=0,idx,tail,max=object.length,map=BASE64_MAP;for(idx=0;idx<max;idx++)idx%3===0&&idx&&(result+=map[bits>>18&63],result+=map[bits>>12&63],result+=map[bits>>6&63],result+=map[bits&63]),bits=(bits<<8)+object[idx];return tail=max%3,tail===0?(result+=map[bits>>18&63],result+=map[bits>>12&63],result+=map[bits>>6&63],result+=map[bits&63]):tail===2?(result+=map[bits>>10&63],result+=map[bits>>4&63],result+=map[bits<<2&63],result+=map[64]):tail===1&&(result+=map[bits>>2&63],result+=map[bits<<4&63],result+=map[64],result+=map[64]),result}__name(representYamlBinary,"representYamlBinary");function isBinary(object){return NodeBuffer&&NodeBuffer.isBuffer(object)}__name(isBinary,"isBinary");module2.exports=new Type("tag:yaml.org,2002:binary",{kind:"scalar",resolve:resolveYamlBinary,construct:constructYamlBinary,predicate:isBinary,represent:representYamlBinary})}});var require_omap=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type/omap.js"(exports2,module2){"use strict";var Type=require_type(),_hasOwnProperty=Object.prototype.hasOwnProperty,_toString=Object.prototype.toString;function resolveYamlOmap(data){if(data===null)return!0;var objectKeys=[],index,length,pair,pairKey,pairHasKey,object=data;for(index=0,length=object.length;index<length;index+=1){if(pair=object[index],pairHasKey=!1,_toString.call(pair)!=="[object Object]")return!1;for(pairKey in pair)if(_hasOwnProperty.call(pair,pairKey))if(!pairHasKey)pairHasKey=!0;else return!1;if(!pairHasKey)return!1;if(objectKeys.indexOf(pairKey)===-1)objectKeys.push(pairKey);else return!1}return!0}__name(resolveYamlOmap,"resolveYamlOmap");function constructYamlOmap(data){return data!==null?data:[]}__name(constructYamlOmap,"constructYamlOmap");module2.exports=new Type("tag:yaml.org,2002:omap",{kind:"sequence",resolve:resolveYamlOmap,construct:constructYamlOmap})}});var require_pairs=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type/pairs.js"(exports2,module2){"use strict";var Type=require_type(),_toString=Object.prototype.toString;function resolveYamlPairs(data){if(data===null)return!0;var index,length,pair,keys,result,object=data;for(result=new Array(object.length),index=0,length=object.length;index<length;index+=1){if(pair=object[index],_toString.call(pair)!=="[object Object]"||(keys=Object.keys(pair),keys.length!==1))return!1;result[index]=[keys[0],pair[keys[0]]]}return!0}__name(resolveYamlPairs,"resolveYamlPairs");function constructYamlPairs(data){if(data===null)return[];var index,length,pair,keys,result,object=data;for(result=new Array(object.length),index=0,length=object.length;index<length;index+=1)pair=object[index],keys=Object.keys(pair),result[index]=[keys[0],pair[keys[0]]];return result}__name(constructYamlPairs,"constructYamlPairs");module2.exports=new Type("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:resolveYamlPairs,construct:constructYamlPairs})}});var require_set=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type/set.js"(exports2,module2){"use strict";var Type=require_type(),_hasOwnProperty=Object.prototype.hasOwnProperty;function resolveYamlSet(data){if(data===null)return!0;var key,object=data;for(key in object)if(_hasOwnProperty.call(object,key)&&object[key]!==null)return!1;return!0}__name(resolveYamlSet,"resolveYamlSet");function constructYamlSet(data){return data!==null?data:{}}__name(constructYamlSet,"constructYamlSet");module2.exports=new Type("tag:yaml.org,2002:set",{kind:"mapping",resolve:resolveYamlSet,construct:constructYamlSet})}});var require_default_safe=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/schema/default_safe.js"(exports2,module2){"use strict";var Schema=require_schema();module2.exports=new Schema({include:[require_core()],implicit:[require_timestamp(),require_merge()],explicit:[require_binary(),require_omap(),require_pairs(),require_set()]})}});var require_undefined=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type/js/undefined.js"(exports2,module2){"use strict";var Type=require_type();function resolveJavascriptUndefined(){return!0}__name(resolveJavascriptUndefined,"resolveJavascriptUndefined");function constructJavascriptUndefined(){}__name(constructJavascriptUndefined,"constructJavascriptUndefined");function representJavascriptUndefined(){return""}__name(representJavascriptUndefined,"representJavascriptUndefined");function isUndefined(object){return typeof object>"u"}__name(isUndefined,"isUndefined");module2.exports=new Type("tag:yaml.org,2002:js/undefined",{kind:"scalar",resolve:resolveJavascriptUndefined,construct:constructJavascriptUndefined,predicate:isUndefined,represent:representJavascriptUndefined})}});var require_regexp=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type/js/regexp.js"(exports2,module2){"use strict";var Type=require_type();function resolveJavascriptRegExp(data){if(data===null||data.length===0)return!1;var regexp=data,tail=/\/([gim]*)$/.exec(data),modifiers="";return!(regexp[0]==="/"&&(tail&&(modifiers=tail[1]),modifiers.length>3||regexp[regexp.length-modifiers.length-1]!=="/"))}__name(resolveJavascriptRegExp,"resolveJavascriptRegExp");function constructJavascriptRegExp(data){var regexp=data,tail=/\/([gim]*)$/.exec(data),modifiers="";return regexp[0]==="/"&&(tail&&(modifiers=tail[1]),regexp=regexp.slice(1,regexp.length-modifiers.length-1)),new RegExp(regexp,modifiers)}__name(constructJavascriptRegExp,"constructJavascriptRegExp");function representJavascriptRegExp(object){var result="/"+object.source+"/";return object.global&&(result+="g"),object.multiline&&(result+="m"),object.ignoreCase&&(result+="i"),result}__name(representJavascriptRegExp,"representJavascriptRegExp");function isRegExp(object){return Object.prototype.toString.call(object)==="[object RegExp]"}__name(isRegExp,"isRegExp");module2.exports=new Type("tag:yaml.org,2002:js/regexp",{kind:"scalar",resolve:resolveJavascriptRegExp,construct:constructJavascriptRegExp,predicate:isRegExp,represent:representJavascriptRegExp})}});var require_function=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/type/js/function.js"(exports2,module2){"use strict";var esprima;try{_require=__require,esprima=_require("esprima")}catch{typeof window<"u"&&(esprima=window.esprima)}var _require,Type=require_type();function resolveJavascriptFunction(data){if(data===null)return!1;try{var source="("+data+")",ast=esprima.parse(source,{range:!0});return!(ast.type!=="Program"||ast.body.length!==1||ast.body[0].type!=="ExpressionStatement"||ast.body[0].expression.type!=="ArrowFunctionExpression"&&ast.body[0].expression.type!=="FunctionExpression")}catch{return!1}}__name(resolveJavascriptFunction,"resolveJavascriptFunction");function constructJavascriptFunction(data){var source="("+data+")",ast=esprima.parse(source,{range:!0}),params=[],body;if(ast.type!=="Program"||ast.body.length!==1||ast.body[0].type!=="ExpressionStatement"||ast.body[0].expression.type!=="ArrowFunctionExpression"&&ast.body[0].expression.type!=="FunctionExpression")throw new Error("Failed to resolve function");return ast.body[0].expression.params.forEach(function(param){params.push(param.name)}),body=ast.body[0].expression.body.range,ast.body[0].expression.body.type==="BlockStatement"?new Function(params,source.slice(body[0]+1,body[1]-1)):new Function(params,"return "+source.slice(body[0],body[1]))}__name(constructJavascriptFunction,"constructJavascriptFunction");function representJavascriptFunction(object){return object.toString()}__name(representJavascriptFunction,"representJavascriptFunction");function isFunction(object){return Object.prototype.toString.call(object)==="[object Function]"}__name(isFunction,"isFunction");module2.exports=new Type("tag:yaml.org,2002:js/function",{kind:"scalar",resolve:resolveJavascriptFunction,construct:constructJavascriptFunction,predicate:isFunction,represent:representJavascriptFunction})}});var require_default_full=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/schema/default_full.js"(exports2,module2){"use strict";var Schema=require_schema();module2.exports=Schema.DEFAULT=new Schema({include:[require_default_safe()],explicit:[require_undefined(),require_regexp(),require_function()]})}});var require_loader=__commonJS({"../../node_modules/.pnpm/js-yaml@3.13.1/node_modules/js-yaml/lib/js-yaml/loader.js"(exports2,module2){"use strict";var common=require_common(),YAMLException=require_exception(),Mark=require_mark(),DEFAULT_SAFE_SCHEMA=require_default_safe(),DEFAULT_FULL_SCHEMA=require_default_full(),_hasOwnProperty=Object.prototype.hasOwnProperty,CONTEXT_FLOW_IN=1,CONTEXT_FLOW_OUT=2,CONTEXT_BLOCK_IN=3,CONTEXT_BLOCK_OUT=4,CHOMPING_CLIP=1,CHOMPING_STRIP=2,CHOMPING_KEEP=3,PATTERN_NON_PRINTABLE=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,PATTERN_NON_ASCII_LINE_BREAKS=/[\x85\u2028\u2029]/,PATTERN_FLOW_INDICATORS=/[,\[\]\{\}]/,PATTERN_TAG_HANDLE=/^(?:!|!!|![a-z\-]+!)$/i,PATTERN_TAG_URI=/^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;function _class(obj){return Object.prototype.toString.call(obj)}__name(_class,"_class");function is_EOL(c2){return c2===10||c2===13}__name(is_EOL,"is_EOL");function is_WHITE_SPACE(c2){return c2===9||c2===32}__name(is_WHITE_SPACE,"is_WHITE_SPACE");function is_WS_OR_EOL(c2){return c2===9||c2===32||c2===10||c2===13}__name(is_WS_OR_EOL,"is_WS_OR_EOL");function is_FLOW_INDICATOR(c2){return c2===44||c2===91||c2===93||c2===123||c2===125}__name(is_FLOW_INDICATOR,"is_FLOW_INDICATOR");function fromHexCode(c2){var lc;return 48<=c2&&c2<=57?c2-48:(lc=c2|32,97<=lc&&lc<=102?lc-97+10:-1)}__name(fromHexCode,"fromHexCode");function escapedHexLen(c2){return c2===120?2:c2===117?4:c2===85?8:0}__name(escapedHexLen,"escapedHexLen");function fromDecimalCode(c2){return 48<=c2&&c2<=57?c2-48:-1}__name(fromDecimalCode,"fromDecimalCode");function simpleEscapeSequence(c2){return c2===48?"\0":c2===97?"\x07":c2===98?"\b":c2===116||c2===9?" ":c2===110?`
|
|
58
58
|
`:c2===118?"\v":c2===102?"\f":c2===114?"\r":c2===101?"\x1B":c2===32?" ":c2===34?'"':c2===47?"/":c2===92?"\\":c2===78?"\x85":c2===95?"\xA0":c2===76?"\u2028":c2===80?"\u2029":""}__name(simpleEscapeSequence,"simpleEscapeSequence");function charFromCodepoint(c2){return c2<=65535?String.fromCharCode(c2):String.fromCharCode((c2-65536>>10)+55296,(c2-65536&1023)+56320)}__name(charFromCodepoint,"charFromCodepoint");var simpleEscapeCheck=new Array(256),simpleEscapeMap=new Array(256);for(i=0;i<256;i++)simpleEscapeCheck[i]=simpleEscapeSequence(i)?1:0,simpleEscapeMap[i]=simpleEscapeSequence(i);var i;function State(input,options){this.input=input,this.filename=options.filename||null,this.schema=options.schema||DEFAULT_FULL_SCHEMA,this.onWarning=options.onWarning||null,this.legacy=options.legacy||!1,this.json=options.json||!1,this.listener=options.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=input.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.documents=[]}__name(State,"State");function generateError(state,message){return new YAMLException(message,new Mark(state.filename,state.input,state.position,state.line,state.position-state.lineStart))}__name(generateError,"generateError");function throwError(state,message){throw generateError(state,message)}__name(throwError,"throwError");function throwWarning(state,message){state.onWarning&&state.onWarning.call(null,generateError(state,message))}__name(throwWarning,"throwWarning");var directiveHandlers={YAML:__name(function(state,name,args){var match,major,minor;state.version!==null&&throwError(state,"duplication of %YAML directive"),args.length!==1&&throwError(state,"YAML directive accepts exactly one argument"),match=/^([0-9]+)\.([0-9]+)$/.exec(args[0]),match===null&&throwError(state,"ill-formed argument of the YAML directive"),major=parseInt(match[1],10),minor=parseInt(match[2],10),major!==1&&throwError(state,"unacceptable YAML version of the document"),state.version=args[0],state.checkLineBreaks=minor<2,minor!==1&&minor!==2&&throwWarning(state,"unsupported YAML version of the document")},"handleYamlDirective"),TAG:__name(function(state,name,args){var handle,prefix;args.length!==2&&throwError(state,"TAG directive accepts exactly two arguments"),handle=args[0],prefix=args[1],PATTERN_TAG_HANDLE.test(handle)||throwError(state,"ill-formed tag handle (first argument) of the TAG directive"),_hasOwnProperty.call(state.tagMap,handle)&&throwError(state,'there is a previously declared suffix for "'+handle+'" tag handle'),PATTERN_TAG_URI.test(prefix)||throwError(state,"ill-formed tag prefix (second argument) of the TAG directive"),state.tagMap[handle]=prefix},"handleTagDirective")};function captureSegment(state,start,end,checkJson){var _position,_length,_character,_result;if(start<end){if(_result=state.input.slice(start,end),checkJson)for(_position=0,_length=_result.length;_position<_length;_position+=1)_character=_result.charCodeAt(_position),_character===9||32<=_character&&_character<=1114111||throwError(state,"expected valid JSON character");else PATTERN_NON_PRINTABLE.test(_result)&&throwError(state,"the stream contains non-printable characters");state.result+=_result}}__name(captureSegment,"captureSegment");function mergeMappings(state,destination,source,overridableKeys){var sourceKeys,key,index,quantity;for(common.isObject(source)||throwError(state,"cannot merge mappings; the provided source object is unacceptable"),sourceKeys=Object.keys(source),index=0,quantity=sourceKeys.length;index<quantity;index+=1)key=sourceKeys[index],_hasOwnProperty.call(destination,key)||(destination[key]=source[key],overridableKeys[key]=!0)}__name(mergeMappings,"mergeMappings");function storeMappingPair(state,_result,overridableKeys,keyTag,keyNode,valueNode,startLine,startPos){var index,quantity;if(Array.isArray(keyNode))for(keyNode=Array.prototype.slice.call(keyNode),index=0,quantity=keyNode.length;index<quantity;index+=1)Array.isArray(keyNode[index])&&throwError(state,"nested arrays are not supported inside keys"),typeof keyNode=="object"&&_class(keyNode[index])==="[object Object]"&&(keyNode[index]="[object Object]");if(typeof keyNode=="object"&&_class(keyNode)==="[object Object]"&&(keyNode="[object Object]"),keyNode=String(keyNode),_result===null&&(_result={}),keyTag==="tag:yaml.org,2002:merge")if(Array.isArray(valueNode))for(index=0,quantity=valueNode.length;index<quantity;index+=1)mergeMappings(state,_result,valueNode[index],overridableKeys);else mergeMappings(state,_result,valueNode,overridableKeys);else!state.json&&!_hasOwnProperty.call(overridableKeys,keyNode)&&_hasOwnProperty.call(_result,keyNode)&&(state.line=startLine||state.line,state.position=startPos||state.position,throwError(state,"duplicated mapping key")),_result[keyNode]=valueNode,delete overridableKeys[keyNode];return _result}__name(storeMappingPair,"storeMappingPair");function readLineBreak(state){var ch;ch=state.input.charCodeAt(state.position),ch===10?state.position++:ch===13?(state.position++,state.input.charCodeAt(state.position)===10&&state.position++):throwError(state,"a line break is expected"),state.line+=1,state.lineStart=state.position}__name(readLineBreak,"readLineBreak");function skipSeparationSpace(state,allowComments,checkIndent){for(var lineBreaks=0,ch=state.input.charCodeAt(state.position);ch!==0;){for(;is_WHITE_SPACE(ch);)ch=state.input.charCodeAt(++state.position);if(allowComments&&ch===35)do ch=state.input.charCodeAt(++state.position);while(ch!==10&&ch!==13&&ch!==0);if(is_EOL(ch))for(readLineBreak(state),ch=state.input.charCodeAt(state.position),lineBreaks++,state.lineIndent=0;ch===32;)state.lineIndent++,ch=state.input.charCodeAt(++state.position);else break}return checkIndent!==-1&&lineBreaks!==0&&state.lineIndent<checkIndent&&throwWarning(state,"deficient indentation"),lineBreaks}__name(skipSeparationSpace,"skipSeparationSpace");function testDocumentSeparator(state){var _position=state.position,ch;return ch=state.input.charCodeAt(_position),!!((ch===45||ch===46)&&ch===state.input.charCodeAt(_position+1)&&ch===state.input.charCodeAt(_position+2)&&(_position+=3,ch=state.input.charCodeAt(_position),ch===0||is_WS_OR_EOL(ch)))}__name(testDocumentSeparator,"testDocumentSeparator");function writeFoldedLines(state,count){count===1?state.result+=" ":count>1&&(state.result+=common.repeat(`
|
|
59
59
|
`,count-1))}__name(writeFoldedLines,"writeFoldedLines");function readPlainScalar(state,nodeIndent,withinFlowCollection){var preceding,following,captureStart,captureEnd,hasPendingContent,_line,_lineStart,_lineIndent,_kind=state.kind,_result=state.result,ch;if(ch=state.input.charCodeAt(state.position),is_WS_OR_EOL(ch)||is_FLOW_INDICATOR(ch)||ch===35||ch===38||ch===42||ch===33||ch===124||ch===62||ch===39||ch===34||ch===37||ch===64||ch===96||(ch===63||ch===45)&&(following=state.input.charCodeAt(state.position+1),is_WS_OR_EOL(following)||withinFlowCollection&&is_FLOW_INDICATOR(following)))return!1;for(state.kind="scalar",state.result="",captureStart=captureEnd=state.position,hasPendingContent=!1;ch!==0;){if(ch===58){if(following=state.input.charCodeAt(state.position+1),is_WS_OR_EOL(following)||withinFlowCollection&&is_FLOW_INDICATOR(following))break}else if(ch===35){if(preceding=state.input.charCodeAt(state.position-1),is_WS_OR_EOL(preceding))break}else{if(state.position===state.lineStart&&testDocumentSeparator(state)||withinFlowCollection&&is_FLOW_INDICATOR(ch))break;if(is_EOL(ch))if(_line=state.line,_lineStart=state.lineStart,_lineIndent=state.lineIndent,skipSeparationSpace(state,!1,-1),state.lineIndent>=nodeIndent){hasPendingContent=!0,ch=state.input.charCodeAt(state.position);continue}else{state.position=captureEnd,state.line=_line,state.lineStart=_lineStart,state.lineIndent=_lineIndent;break}}hasPendingContent&&(captureSegment(state,captureStart,captureEnd,!1),writeFoldedLines(state,state.line-_line),captureStart=captureEnd=state.position,hasPendingContent=!1),is_WHITE_SPACE(ch)||(captureEnd=state.position+1),ch=state.input.charCodeAt(++state.position)}return captureSegment(state,captureStart,captureEnd,!1),state.result?!0:(state.kind=_kind,state.result=_result,!1)}__name(readPlainScalar,"readPlainScalar");function readSingleQuotedScalar(state,nodeIndent){var ch,captureStart,captureEnd;if(ch=state.input.charCodeAt(state.position),ch!==39)return!1;for(state.kind="scalar",state.result="",state.position++,captureStart=captureEnd=state.position;(ch=state.input.charCodeAt(state.position))!==0;)if(ch===39)if(captureSegment(state,captureStart,state.position,!0),ch=state.input.charCodeAt(++state.position),ch===39)captureStart=state.position,state.position++,captureEnd=state.position;else return!0;else is_EOL(ch)?(captureSegment(state,captureStart,captureEnd,!0),writeFoldedLines(state,skipSeparationSpace(state,!1,nodeIndent)),captureStart=captureEnd=state.position):state.position===state.lineStart&&testDocumentSeparator(state)?throwError(state,"unexpected end of the document within a single quoted scalar"):(state.position++,captureEnd=state.position);throwError(state,"unexpected end of the stream within a single quoted scalar")}__name(readSingleQuotedScalar,"readSingleQuotedScalar");function readDoubleQuotedScalar(state,nodeIndent){var captureStart,captureEnd,hexLength,hexResult,tmp,ch;if(ch=state.input.charCodeAt(state.position),ch!==34)return!1;for(state.kind="scalar",state.result="",state.position++,captureStart=captureEnd=state.position;(ch=state.input.charCodeAt(state.position))!==0;){if(ch===34)return captureSegment(state,captureStart,state.position,!0),state.position++,!0;if(ch===92){if(captureSegment(state,captureStart,state.position,!0),ch=state.input.charCodeAt(++state.position),is_EOL(ch))skipSeparationSpace(state,!1,nodeIndent);else if(ch<256&&simpleEscapeCheck[ch])state.result+=simpleEscapeMap[ch],state.position++;else if((tmp=escapedHexLen(ch))>0){for(hexLength=tmp,hexResult=0;hexLength>0;hexLength--)ch=state.input.charCodeAt(++state.position),(tmp=fromHexCode(ch))>=0?hexResult=(hexResult<<4)+tmp:throwError(state,"expected hexadecimal character");state.result+=charFromCodepoint(hexResult),state.position++}else throwError(state,"unknown escape sequence");captureStart=captureEnd=state.position}else is_EOL(ch)?(captureSegment(state,captureStart,captureEnd,!0),writeFoldedLines(state,skipSeparationSpace(state,!1,nodeIndent)),captureStart=captureEnd=state.position):state.position===state.lineStart&&testDocumentSeparator(state)?throwError(state,"unexpected end of the document within a double quoted scalar"):(state.position++,captureEnd=state.position)}throwError(state,"unexpected end of the stream within a double quoted scalar")}__name(readDoubleQuotedScalar,"readDoubleQuotedScalar");function readFlowCollection(state,nodeIndent){var readNext=!0,_line,_tag=state.tag,_result,_anchor=state.anchor,following,terminator,isPair,isExplicitPair,isMapping,overridableKeys={},keyNode,keyTag,valueNode,ch;if(ch=state.input.charCodeAt(state.position),ch===91)terminator=93,isMapping=!1,_result=[];else if(ch===123)terminator=125,isMapping=!0,_result={};else return!1;for(state.anchor!==null&&(state.anchorMap[state.anchor]=_result),ch=state.input.charCodeAt(++state.position);ch!==0;){if(skipSeparationSpace(state,!0,nodeIndent),ch=state.input.charCodeAt(state.position),ch===terminator)return state.position++,state.tag=_tag,state.anchor=_anchor,state.kind=isMapping?"mapping":"sequence",state.result=_result,!0;readNext||throwError(state,"missed comma between flow collection entries"),keyTag=keyNode=valueNode=null,isPair=isExplicitPair=!1,ch===63&&(following=state.input.charCodeAt(state.position+1),is_WS_OR_EOL(following)&&(isPair=isExplicitPair=!0,state.position++,skipSeparationSpace(state,!0,nodeIndent))),_line=state.line,composeNode(state,nodeIndent,CONTEXT_FLOW_IN,!1,!0),keyTag=state.tag,keyNode=state.result,skipSeparationSpace(state,!0,nodeIndent),ch=state.input.charCodeAt(state.position),(isExplicitPair||state.line===_line)&&ch===58&&(isPair=!0,ch=state.input.charCodeAt(++state.position),skipSeparationSpace(state,!0,nodeIndent),composeNode(state,nodeIndent,CONTEXT_FLOW_IN,!1,!0),valueNode=state.result),isMapping?storeMappingPair(state,_result,overridableKeys,keyTag,keyNode,valueNode):isPair?_result.push(storeMappingPair(state,null,overridableKeys,keyTag,keyNode,valueNode)):_result.push(keyNode),skipSeparationSpace(state,!0,nodeIndent),ch=state.input.charCodeAt(state.position),ch===44?(readNext=!0,ch=state.input.charCodeAt(++state.position)):readNext=!1}throwError(state,"unexpected end of the stream within a flow collection")}__name(readFlowCollection,"readFlowCollection");function readBlockScalar(state,nodeIndent){var captureStart,folding,chomping=CHOMPING_CLIP,didReadContent=!1,detectedIndent=!1,textIndent=nodeIndent,emptyLines=0,atMoreIndented=!1,tmp,ch;if(ch=state.input.charCodeAt(state.position),ch===124)folding=!1;else if(ch===62)folding=!0;else return!1;for(state.kind="scalar",state.result="";ch!==0;)if(ch=state.input.charCodeAt(++state.position),ch===43||ch===45)CHOMPING_CLIP===chomping?chomping=ch===43?CHOMPING_KEEP:CHOMPING_STRIP:throwError(state,"repeat of a chomping mode identifier");else if((tmp=fromDecimalCode(ch))>=0)tmp===0?throwError(state,"bad explicit indentation width of a block scalar; it cannot be less than one"):detectedIndent?throwError(state,"repeat of an indentation width identifier"):(textIndent=nodeIndent+tmp-1,detectedIndent=!0);else break;if(is_WHITE_SPACE(ch)){do ch=state.input.charCodeAt(++state.position);while(is_WHITE_SPACE(ch));if(ch===35)do ch=state.input.charCodeAt(++state.position);while(!is_EOL(ch)&&ch!==0)}for(;ch!==0;){for(readLineBreak(state),state.lineIndent=0,ch=state.input.charCodeAt(state.position);(!detectedIndent||state.lineIndent<textIndent)&&ch===32;)state.lineIndent++,ch=state.input.charCodeAt(++state.position);if(!detectedIndent&&state.lineIndent>textIndent&&(textIndent=state.lineIndent),is_EOL(ch)){emptyLines++;continue}if(state.lineIndent<textIndent){chomping===CHOMPING_KEEP?state.result+=common.repeat(`
|
|
@@ -167,7 +167,7 @@ ${indentStep}${indent}${line}`:`
|
|
|
167
167
|
${indent}${end}`}else return`${start}${fcPadding}${lines.join(" ")}${fcPadding}${end}`}__name(stringifyFlowCollection,"stringifyFlowCollection");function addCommentBefore({indent,options:{commentString}},lines,comment,chompKeep){if(comment&&chompKeep&&(comment=comment.replace(/^\n+/,"")),comment){let ic=stringifyComment.indentComment(commentString(comment),indent);lines.push(ic.trimStart())}}__name(addCommentBefore,"addCommentBefore");exports2.stringifyCollection=stringifyCollection}});var require_YAMLMap=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/YAMLMap.js"(exports2){"use strict";var stringifyCollection=require_stringifyCollection(),addPairToJSMap=require_addPairToJSMap(),Collection=require_Collection(),identity2=require_identity(),Pair=require_Pair(),Scalar=require_Scalar();function findPair(items,key){let k=identity2.isScalar(key)?key.value:key;for(let it2 of items)if(identity2.isPair(it2)&&(it2.key===key||it2.key===k||identity2.isScalar(it2.key)&&it2.key.value===k))return it2}__name(findPair,"findPair");var YAMLMap=class extends Collection.Collection{static{__name(this,"YAMLMap")}static get tagName(){return"tag:yaml.org,2002:map"}constructor(schema){super(identity2.MAP,schema),this.items=[]}static from(schema,obj,ctx){let{keepUndefined,replacer}=ctx,map=new this(schema),add=__name((key,value)=>{if(typeof replacer=="function")value=replacer.call(obj,key,value);else if(Array.isArray(replacer)&&!replacer.includes(key))return;(value!==void 0||keepUndefined)&&map.items.push(Pair.createPair(key,value,ctx))},"add");if(obj instanceof Map)for(let[key,value]of obj)add(key,value);else if(obj&&typeof obj=="object")for(let key of Object.keys(obj))add(key,obj[key]);return typeof schema.sortMapEntries=="function"&&map.items.sort(schema.sortMapEntries),map}add(pair,overwrite){let _pair;identity2.isPair(pair)?_pair=pair:!pair||typeof pair!="object"||!("key"in pair)?_pair=new Pair.Pair(pair,pair?.value):_pair=new Pair.Pair(pair.key,pair.value);let prev=findPair(this.items,_pair.key),sortEntries=this.schema?.sortMapEntries;if(prev){if(!overwrite)throw new Error(`Key ${_pair.key} already set`);identity2.isScalar(prev.value)&&Scalar.isScalarValue(_pair.value)?prev.value.value=_pair.value:prev.value=_pair.value}else if(sortEntries){let i=this.items.findIndex(item=>sortEntries(_pair,item)<0);i===-1?this.items.push(_pair):this.items.splice(i,0,_pair)}else this.items.push(_pair)}delete(key){let it2=findPair(this.items,key);return it2?this.items.splice(this.items.indexOf(it2),1).length>0:!1}get(key,keepScalar){let node=findPair(this.items,key)?.value;return(!keepScalar&&identity2.isScalar(node)?node.value:node)??void 0}has(key){return!!findPair(this.items,key)}set(key,value){this.add(new Pair.Pair(key,value),!0)}toJSON(_,ctx,Type){let map=Type?new Type:ctx?.mapAsMap?new Map:{};ctx?.onCreate&&ctx.onCreate(map);for(let item of this.items)addPairToJSMap.addPairToJSMap(ctx,map,item);return map}toString(ctx,onComment,onChompKeep){if(!ctx)return JSON.stringify(this);for(let item of this.items)if(!identity2.isPair(item))throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);return!ctx.allNullValues&&this.hasAllNullValues(!1)&&(ctx=Object.assign({},ctx,{allNullValues:!0})),stringifyCollection.stringifyCollection(this,ctx,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:ctx.indent||"",onChompKeep,onComment})}};exports2.YAMLMap=YAMLMap;exports2.findPair=findPair}});var require_map2=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/common/map.js"(exports2){"use strict";var identity2=require_identity(),YAMLMap=require_YAMLMap(),map={collection:"map",default:!0,nodeClass:YAMLMap.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(map2,onError){return identity2.isMap(map2)||onError("Expected a mapping for this tag"),map2},createNode:__name((schema,obj,ctx)=>YAMLMap.YAMLMap.from(schema,obj,ctx),"createNode")};exports2.map=map}});var require_YAMLSeq=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/nodes/YAMLSeq.js"(exports2){"use strict";var createNode=require_createNode(),stringifyCollection=require_stringifyCollection(),Collection=require_Collection(),identity2=require_identity(),Scalar=require_Scalar(),toJS=require_toJS(),YAMLSeq=class extends Collection.Collection{static{__name(this,"YAMLSeq")}static get tagName(){return"tag:yaml.org,2002:seq"}constructor(schema){super(identity2.SEQ,schema),this.items=[]}add(value){this.items.push(value)}delete(key){let idx=asItemIndex(key);return typeof idx!="number"?!1:this.items.splice(idx,1).length>0}get(key,keepScalar){let idx=asItemIndex(key);if(typeof idx!="number")return;let it2=this.items[idx];return!keepScalar&&identity2.isScalar(it2)?it2.value:it2}has(key){let idx=asItemIndex(key);return typeof idx=="number"&&idx<this.items.length}set(key,value){let idx=asItemIndex(key);if(typeof idx!="number")throw new Error(`Expected a valid index, not ${key}.`);let prev=this.items[idx];identity2.isScalar(prev)&&Scalar.isScalarValue(value)?prev.value=value:this.items[idx]=value}toJSON(_,ctx){let seq=[];ctx?.onCreate&&ctx.onCreate(seq);let i=0;for(let item of this.items)seq.push(toJS.toJS(item,String(i++),ctx));return seq}toString(ctx,onComment,onChompKeep){return ctx?stringifyCollection.stringifyCollection(this,ctx,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(ctx.indent||"")+" ",onChompKeep,onComment}):JSON.stringify(this)}static from(schema,obj,ctx){let{replacer}=ctx,seq=new this(schema);if(obj&&Symbol.iterator in Object(obj)){let i=0;for(let it2 of obj){if(typeof replacer=="function"){let key=obj instanceof Set?it2:String(i++);it2=replacer.call(obj,key,it2)}seq.items.push(createNode.createNode(it2,void 0,ctx))}}return seq}};function asItemIndex(key){let idx=identity2.isScalar(key)?key.value:key;return idx&&typeof idx=="string"&&(idx=Number(idx)),typeof idx=="number"&&Number.isInteger(idx)&&idx>=0?idx:null}__name(asItemIndex,"asItemIndex");exports2.YAMLSeq=YAMLSeq}});var require_seq2=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/common/seq.js"(exports2){"use strict";var identity2=require_identity(),YAMLSeq=require_YAMLSeq(),seq={collection:"seq",default:!0,nodeClass:YAMLSeq.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(seq2,onError){return identity2.isSeq(seq2)||onError("Expected a sequence for this tag"),seq2},createNode:__name((schema,obj,ctx)=>YAMLSeq.YAMLSeq.from(schema,obj,ctx),"createNode")};exports2.seq=seq}});var require_string=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/common/string.js"(exports2){"use strict";var stringifyString=require_stringifyString(),string={identify:__name(value=>typeof value=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:__name(str=>str,"resolve"),stringify(item,ctx,onComment,onChompKeep){return ctx=Object.assign({actualString:!0},ctx),stringifyString.stringifyString(item,ctx,onComment,onChompKeep)}};exports2.string=string}});var require_null2=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/common/null.js"(exports2){"use strict";var Scalar=require_Scalar(),nullTag={identify:__name(value=>value==null,"identify"),createNode:__name(()=>new Scalar.Scalar(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:__name(()=>new Scalar.Scalar(null),"resolve"),stringify:__name(({source},ctx)=>typeof source=="string"&&nullTag.test.test(source)?source:ctx.options.nullStr,"stringify")};exports2.nullTag=nullTag}});var require_bool2=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/core/bool.js"(exports2){"use strict";var Scalar=require_Scalar(),boolTag={identify:__name(value=>typeof value=="boolean","identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:__name(str=>new Scalar.Scalar(str[0]==="t"||str[0]==="T"),"resolve"),stringify({source,value},ctx){if(source&&boolTag.test.test(source)){let sv=source[0]==="t"||source[0]==="T";if(value===sv)return source}return value?ctx.options.trueStr:ctx.options.falseStr}};exports2.boolTag=boolTag}});var require_stringifyNumber=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyNumber.js"(exports2){"use strict";function stringifyNumber({format:format2,minFractionDigits,tag,value}){if(typeof value=="bigint")return String(value);let num=typeof value=="number"?value:Number(value);if(!isFinite(num))return isNaN(num)?".nan":num<0?"-.inf":".inf";let n=Object.is(value,-0)?"-0":JSON.stringify(value);if(!format2&&minFractionDigits&&(!tag||tag==="tag:yaml.org,2002:float")&&/^-?\d/.test(n)&&!n.includes("e")){let i=n.indexOf(".");i<0&&(i=n.length,n+=".");let d3=minFractionDigits-(n.length-i-1);for(;d3-- >0;)n+="0"}return n}__name(stringifyNumber,"stringifyNumber");exports2.stringifyNumber=stringifyNumber}});var require_float2=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/core/float.js"(exports2){"use strict";var Scalar=require_Scalar(),stringifyNumber=require_stringifyNumber(),floatNaN={identify:__name(value=>typeof value=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:__name(str=>str.slice(-3).toLowerCase()==="nan"?NaN:str[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:stringifyNumber.stringifyNumber},floatExp={identify:__name(value=>typeof value=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:__name(str=>parseFloat(str),"resolve"),stringify(node){let num=Number(node.value);return isFinite(num)?num.toExponential():stringifyNumber.stringifyNumber(node)}},float={identify:__name(value=>typeof value=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(str){let node=new Scalar.Scalar(parseFloat(str)),dot=str.indexOf(".");return dot!==-1&&str[str.length-1]==="0"&&(node.minFractionDigits=str.length-dot-1),node},stringify:stringifyNumber.stringifyNumber};exports2.float=float;exports2.floatExp=floatExp;exports2.floatNaN=floatNaN}});var require_int2=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/core/int.js"(exports2){"use strict";var stringifyNumber=require_stringifyNumber(),intIdentify=__name(value=>typeof value=="bigint"||Number.isInteger(value),"intIdentify"),intResolve=__name((str,offset,radix,{intAsBigInt})=>intAsBigInt?BigInt(str):parseInt(str.substring(offset),radix),"intResolve");function intStringify(node,radix,prefix){let{value}=node;return intIdentify(value)&&value>=0?prefix+value.toString(radix):stringifyNumber.stringifyNumber(node)}__name(intStringify,"intStringify");var intOct={identify:__name(value=>intIdentify(value)&&value>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:__name((str,_onError,opt)=>intResolve(str,2,8,opt),"resolve"),stringify:__name(node=>intStringify(node,8,"0o"),"stringify")},int={identify:intIdentify,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:__name((str,_onError,opt)=>intResolve(str,0,10,opt),"resolve"),stringify:stringifyNumber.stringifyNumber},intHex={identify:__name(value=>intIdentify(value)&&value>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:__name((str,_onError,opt)=>intResolve(str,2,16,opt),"resolve"),stringify:__name(node=>intStringify(node,16,"0x"),"stringify")};exports2.int=int;exports2.intHex=intHex;exports2.intOct=intOct}});var require_schema2=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/core/schema.js"(exports2){"use strict";var map=require_map2(),_null=require_null2(),seq=require_seq2(),string=require_string(),bool=require_bool2(),float=require_float2(),int=require_int2(),schema=[map.map,seq.seq,string.string,_null.nullTag,bool.boolTag,int.intOct,int.int,int.intHex,float.floatNaN,float.floatExp,float.float];exports2.schema=schema}});var require_schema3=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/json/schema.js"(exports2){"use strict";var Scalar=require_Scalar(),map=require_map2(),seq=require_seq2();function intIdentify(value){return typeof value=="bigint"||Number.isInteger(value)}__name(intIdentify,"intIdentify");var stringifyJSON=__name(({value})=>JSON.stringify(value),"stringifyJSON"),jsonScalars=[{identify:__name(value=>typeof value=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:__name(str=>str,"resolve"),stringify:stringifyJSON},{identify:__name(value=>value==null,"identify"),createNode:__name(()=>new Scalar.Scalar(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:__name(()=>null,"resolve"),stringify:stringifyJSON},{identify:__name(value=>typeof value=="boolean","identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:__name(str=>str==="true","resolve"),stringify:stringifyJSON},{identify:intIdentify,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:__name((str,_onError,{intAsBigInt})=>intAsBigInt?BigInt(str):parseInt(str,10),"resolve"),stringify:__name(({value})=>intIdentify(value)?value.toString():JSON.stringify(value),"stringify")},{identify:__name(value=>typeof value=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:__name(str=>parseFloat(str),"resolve"),stringify:stringifyJSON}],jsonError={default:!0,tag:"",test:/^/,resolve(str,onError){return onError(`Unresolved plain scalar ${JSON.stringify(str)}`),str}},schema=[map.map,seq.seq].concat(jsonScalars,jsonError);exports2.schema=schema}});var require_binary2=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/binary.js"(exports2){"use strict";var node_buffer=__require("buffer"),Scalar=require_Scalar(),stringifyString=require_stringifyString(),binary={identify:__name(value=>value instanceof Uint8Array,"identify"),default:!1,tag:"tag:yaml.org,2002:binary",resolve(src,onError){if(typeof node_buffer.Buffer=="function")return node_buffer.Buffer.from(src,"base64");if(typeof atob=="function"){let str=atob(src.replace(/[\n\r]/g,"")),buffer=new Uint8Array(str.length);for(let i=0;i<str.length;++i)buffer[i]=str.charCodeAt(i);return buffer}else return onError("This environment does not support reading binary tags; either Buffer or atob is required"),src},stringify({comment,type,value},ctx,onComment,onChompKeep){if(!value)return"";let buf=value,str;if(typeof node_buffer.Buffer=="function")str=buf instanceof node_buffer.Buffer?buf.toString("base64"):node_buffer.Buffer.from(buf.buffer).toString("base64");else if(typeof btoa=="function"){let s="";for(let i=0;i<buf.length;++i)s+=String.fromCharCode(buf[i]);str=btoa(s)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(type??(type=Scalar.Scalar.BLOCK_LITERAL),type!==Scalar.Scalar.QUOTE_DOUBLE){let lineWidth=Math.max(ctx.options.lineWidth-ctx.indent.length,ctx.options.minContentWidth),n=Math.ceil(str.length/lineWidth),lines=new Array(n);for(let i=0,o=0;i<n;++i,o+=lineWidth)lines[i]=str.substr(o,lineWidth);str=lines.join(type===Scalar.Scalar.BLOCK_LITERAL?`
|
|
168
168
|
`:" ")}return stringifyString.stringifyString({comment,type,value:str},ctx,onComment,onChompKeep)}};exports2.binary=binary}});var require_pairs2=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/pairs.js"(exports2){"use strict";var identity2=require_identity(),Pair=require_Pair(),Scalar=require_Scalar(),YAMLSeq=require_YAMLSeq();function resolvePairs(seq,onError){if(identity2.isSeq(seq))for(let i=0;i<seq.items.length;++i){let item=seq.items[i];if(!identity2.isPair(item)){if(identity2.isMap(item)){item.items.length>1&&onError("Each pair must have its own sequence indicator");let pair=item.items[0]||new Pair.Pair(new Scalar.Scalar(null));if(item.commentBefore&&(pair.key.commentBefore=pair.key.commentBefore?`${item.commentBefore}
|
|
169
169
|
${pair.key.commentBefore}`:item.commentBefore),item.comment){let cn=pair.value??pair.key;cn.comment=cn.comment?`${item.comment}
|
|
170
|
-
${cn.comment}`:item.comment}item=pair}seq.items[i]=identity2.isPair(item)?item:new Pair.Pair(item)}}else onError("Expected a sequence for this tag");return seq}__name(resolvePairs,"resolvePairs");function createPairs(schema,iterable,ctx){let{replacer}=ctx,pairs2=new YAMLSeq.YAMLSeq(schema);pairs2.tag="tag:yaml.org,2002:pairs";let i=0;if(iterable&&Symbol.iterator in Object(iterable))for(let it2 of iterable){typeof replacer=="function"&&(it2=replacer.call(iterable,String(i++),it2));let key,value;if(Array.isArray(it2))if(it2.length===2)key=it2[0],value=it2[1];else throw new TypeError(`Expected [key, value] tuple: ${it2}`);else if(it2&&it2 instanceof Object){let keys=Object.keys(it2);if(keys.length===1)key=keys[0],value=it2[key];else throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`)}else key=it2;pairs2.items.push(Pair.createPair(key,value,ctx))}return pairs2}__name(createPairs,"createPairs");var pairs={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:resolvePairs,createNode:createPairs};exports2.createPairs=createPairs;exports2.pairs=pairs;exports2.resolvePairs=resolvePairs}});var require_omap2=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/omap.js"(exports2){"use strict";var identity2=require_identity(),toJS=require_toJS(),YAMLMap=require_YAMLMap(),YAMLSeq=require_YAMLSeq(),pairs=require_pairs2(),YAMLOMap=class _YAMLOMap extends YAMLSeq.YAMLSeq{static{__name(this,"YAMLOMap")}constructor(){super(),this.add=YAMLMap.YAMLMap.prototype.add.bind(this),this.delete=YAMLMap.YAMLMap.prototype.delete.bind(this),this.get=YAMLMap.YAMLMap.prototype.get.bind(this),this.has=YAMLMap.YAMLMap.prototype.has.bind(this),this.set=YAMLMap.YAMLMap.prototype.set.bind(this),this.tag=_YAMLOMap.tag}toJSON(_,ctx){if(!ctx)return super.toJSON(_);let map=new Map;ctx?.onCreate&&ctx.onCreate(map);for(let pair of this.items){let key,value;if(identity2.isPair(pair)?(key=toJS.toJS(pair.key,"",ctx),value=toJS.toJS(pair.value,key,ctx)):key=toJS.toJS(pair,"",ctx),map.has(key))throw new Error("Ordered maps must not include duplicate keys");map.set(key,value)}return map}static from(schema,iterable,ctx){let pairs$1=pairs.createPairs(schema,iterable,ctx),omap2=new this;return omap2.items=pairs$1.items,omap2}};YAMLOMap.tag="tag:yaml.org,2002:omap";var omap={collection:"seq",identify:__name(value=>value instanceof Map,"identify"),nodeClass:YAMLOMap,default:!1,tag:"tag:yaml.org,2002:omap",resolve(seq,onError){let pairs$1=pairs.resolvePairs(seq,onError),seenKeys=[];for(let{key}of pairs$1.items)identity2.isScalar(key)&&(seenKeys.includes(key.value)?onError(`Ordered maps must not include duplicate keys: ${key.value}`):seenKeys.push(key.value));return Object.assign(new YAMLOMap,pairs$1)},createNode:__name((schema,iterable,ctx)=>YAMLOMap.from(schema,iterable,ctx),"createNode")};exports2.YAMLOMap=YAMLOMap;exports2.omap=omap}});var require_bool3=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/bool.js"(exports2){"use strict";var Scalar=require_Scalar();function boolStringify({value,source},ctx){return source&&(value?trueTag:falseTag).test.test(source)?source:value?ctx.options.trueStr:ctx.options.falseStr}__name(boolStringify,"boolStringify");var trueTag={identify:__name(value=>value===!0,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:__name(()=>new Scalar.Scalar(!0),"resolve"),stringify:boolStringify},falseTag={identify:__name(value=>value===!1,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:__name(()=>new Scalar.Scalar(!1),"resolve"),stringify:boolStringify};exports2.falseTag=falseTag;exports2.trueTag=trueTag}});var require_float3=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/float.js"(exports2){"use strict";var Scalar=require_Scalar(),stringifyNumber=require_stringifyNumber(),floatNaN={identify:__name(value=>typeof value=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:__name(str=>str.slice(-3).toLowerCase()==="nan"?NaN:str[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:stringifyNumber.stringifyNumber},floatExp={identify:__name(value=>typeof value=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:__name(str=>parseFloat(str.replace(/_/g,"")),"resolve"),stringify(node){let num=Number(node.value);return isFinite(num)?num.toExponential():stringifyNumber.stringifyNumber(node)}},float={identify:__name(value=>typeof value=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(str){let node=new Scalar.Scalar(parseFloat(str.replace(/_/g,""))),dot=str.indexOf(".");if(dot!==-1){let f=str.substring(dot+1).replace(/_/g,"");f[f.length-1]==="0"&&(node.minFractionDigits=f.length)}return node},stringify:stringifyNumber.stringifyNumber};exports2.float=float;exports2.floatExp=floatExp;exports2.floatNaN=floatNaN}});var require_int3=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/int.js"(exports2){"use strict";var stringifyNumber=require_stringifyNumber(),intIdentify=__name(value=>typeof value=="bigint"||Number.isInteger(value),"intIdentify");function intResolve(str,offset,radix,{intAsBigInt}){let sign=str[0];if((sign==="-"||sign==="+")&&(offset+=1),str=str.substring(offset).replace(/_/g,""),intAsBigInt){switch(radix){case 2:str=`0b${str}`;break;case 8:str=`0o${str}`;break;case 16:str=`0x${str}`;break}let n2=BigInt(str);return sign==="-"?BigInt(-1)*n2:n2}let n=parseInt(str,radix);return sign==="-"?-1*n:n}__name(intResolve,"intResolve");function intStringify(node,radix,prefix){let{value}=node;if(intIdentify(value)){let str=value.toString(radix);return value<0?"-"+prefix+str.substr(1):prefix+str}return stringifyNumber.stringifyNumber(node)}__name(intStringify,"intStringify");var intBin={identify:intIdentify,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:__name((str,_onError,opt)=>intResolve(str,2,2,opt),"resolve"),stringify:__name(node=>intStringify(node,2,"0b"),"stringify")},intOct={identify:intIdentify,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:__name((str,_onError,opt)=>intResolve(str,1,8,opt),"resolve"),stringify:__name(node=>intStringify(node,8,"0"),"stringify")},int={identify:intIdentify,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:__name((str,_onError,opt)=>intResolve(str,0,10,opt),"resolve"),stringify:stringifyNumber.stringifyNumber},intHex={identify:intIdentify,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:__name((str,_onError,opt)=>intResolve(str,2,16,opt),"resolve"),stringify:__name(node=>intStringify(node,16,"0x"),"stringify")};exports2.int=int;exports2.intBin=intBin;exports2.intHex=intHex;exports2.intOct=intOct}});var require_set2=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/set.js"(exports2){"use strict";var identity2=require_identity(),Pair=require_Pair(),YAMLMap=require_YAMLMap(),YAMLSet=class _YAMLSet extends YAMLMap.YAMLMap{static{__name(this,"YAMLSet")}constructor(schema){super(schema),this.tag=_YAMLSet.tag}add(key){let pair;identity2.isPair(key)?pair=key:key&&typeof key=="object"&&"key"in key&&"value"in key&&key.value===null?pair=new Pair.Pair(key.key,null):pair=new Pair.Pair(key,null),YAMLMap.findPair(this.items,pair.key)||this.items.push(pair)}get(key,keepPair){let pair=YAMLMap.findPair(this.items,key);return!keepPair&&identity2.isPair(pair)?identity2.isScalar(pair.key)?pair.key.value:pair.key:pair}set(key,value){if(typeof value!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);let prev=YAMLMap.findPair(this.items,key);prev&&!value?this.items.splice(this.items.indexOf(prev),1):!prev&&value&&this.items.push(new Pair.Pair(key))}toJSON(_,ctx){return super.toJSON(_,ctx,Set)}toString(ctx,onComment,onChompKeep){if(!ctx)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},ctx,{allNullValues:!0}),onComment,onChompKeep);throw new Error("Set items must all have null values")}static from(schema,iterable,ctx){let{replacer}=ctx,set2=new this(schema);if(iterable&&Symbol.iterator in Object(iterable))for(let value of iterable)typeof replacer=="function"&&(value=replacer.call(iterable,value,value)),set2.items.push(Pair.createPair(value,null,ctx));return set2}};YAMLSet.tag="tag:yaml.org,2002:set";var set={collection:"map",identify:__name(value=>value instanceof Set,"identify"),nodeClass:YAMLSet,default:!1,tag:"tag:yaml.org,2002:set",createNode:__name((schema,iterable,ctx)=>YAMLSet.from(schema,iterable,ctx),"createNode"),resolve(map,onError){if(identity2.isMap(map)){if(map.hasAllNullValues(!0))return Object.assign(new YAMLSet,map);onError("Set items must all have null values")}else onError("Expected a mapping for this tag");return map}};exports2.YAMLSet=YAMLSet;exports2.set=set}});var require_timestamp2=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/timestamp.js"(exports2){"use strict";var stringifyNumber=require_stringifyNumber();function parseSexagesimal(str,asBigInt){let sign=str[0],parts=sign==="-"||sign==="+"?str.substring(1):str,num=__name(n=>asBigInt?BigInt(n):Number(n),"num"),res=parts.replace(/_/g,"").split(":").reduce((res2,p2)=>res2*num(60)+num(p2),num(0));return sign==="-"?num(-1)*res:res}__name(parseSexagesimal,"parseSexagesimal");function stringifySexagesimal(node){let{value}=node,num=__name(n=>n,"num");if(typeof value=="bigint")num=__name(n=>BigInt(n),"num");else if(isNaN(value)||!isFinite(value))return stringifyNumber.stringifyNumber(node);let sign="";value<0&&(sign="-",value*=num(-1));let _60=num(60),parts=[value%_60];return value<60?parts.unshift(0):(value=(value-parts[0])/_60,parts.unshift(value%_60),value>=60&&(value=(value-parts[0])/_60,parts.unshift(value))),sign+parts.map(n=>String(n).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}__name(stringifySexagesimal,"stringifySexagesimal");var intTime={identify:__name(value=>typeof value=="bigint"||Number.isInteger(value),"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:__name((str,_onError,{intAsBigInt})=>parseSexagesimal(str,intAsBigInt),"resolve"),stringify:stringifySexagesimal},floatTime={identify:__name(value=>typeof value=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:__name(str=>parseSexagesimal(str,!1),"resolve"),stringify:stringifySexagesimal},timestamp={identify:__name(value=>value instanceof Date,"identify"),default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(str){let match=str.match(timestamp.test);if(!match)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,year,month,day2,hour,minute,second]=match.map(Number),millisec=match[7]?Number((match[7]+"00").substr(1,3)):0,date=Date.UTC(year,month-1,day2,hour||0,minute||0,second||0,millisec),tz=match[8];if(tz&&tz!=="Z"){let d3=parseSexagesimal(tz,!1);Math.abs(d3)<30&&(d3*=60),date-=6e4*d3}return new Date(date)},stringify:__name(({value})=>value?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??"","stringify")};exports2.floatTime=floatTime;exports2.intTime=intTime;exports2.timestamp=timestamp}});var require_schema4=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/schema.js"(exports2){"use strict";var map=require_map2(),_null=require_null2(),seq=require_seq2(),string=require_string(),binary=require_binary2(),bool=require_bool3(),float=require_float3(),int=require_int3(),merge=require_merge2(),omap=require_omap2(),pairs=require_pairs2(),set=require_set2(),timestamp=require_timestamp2(),schema=[map.map,seq.seq,string.string,_null.nullTag,bool.trueTag,bool.falseTag,int.intBin,int.intOct,int.int,int.intHex,float.floatNaN,float.floatExp,float.float,binary.binary,merge.merge,omap.omap,pairs.pairs,set.set,timestamp.intTime,timestamp.floatTime,timestamp.timestamp];exports2.schema=schema}});var require_tags=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/tags.js"(exports2){"use strict";var map=require_map2(),_null=require_null2(),seq=require_seq2(),string=require_string(),bool=require_bool2(),float=require_float2(),int=require_int2(),schema=require_schema2(),schema$1=require_schema3(),binary=require_binary2(),merge=require_merge2(),omap=require_omap2(),pairs=require_pairs2(),schema$2=require_schema4(),set=require_set2(),timestamp=require_timestamp2(),schemas3=new Map([["core",schema.schema],["failsafe",[map.map,seq.seq,string.string]],["json",schema$1.schema],["yaml11",schema$2.schema],["yaml-1.1",schema$2.schema]]),tagsByName={binary:binary.binary,bool:bool.boolTag,float:float.float,floatExp:float.floatExp,floatNaN:float.floatNaN,floatTime:timestamp.floatTime,int:int.int,intHex:int.intHex,intOct:int.intOct,intTime:timestamp.intTime,map:map.map,merge:merge.merge,null:_null.nullTag,omap:omap.omap,pairs:pairs.pairs,seq:seq.seq,set:set.set,timestamp:timestamp.timestamp},coreKnownTags={"tag:yaml.org,2002:binary":binary.binary,"tag:yaml.org,2002:merge":merge.merge,"tag:yaml.org,2002:omap":omap.omap,"tag:yaml.org,2002:pairs":pairs.pairs,"tag:yaml.org,2002:set":set.set,"tag:yaml.org,2002:timestamp":timestamp.timestamp};function getTags(customTags,schemaName,addMergeTag){let schemaTags=schemas3.get(schemaName);if(schemaTags&&!customTags)return addMergeTag&&!schemaTags.includes(merge.merge)?schemaTags.concat(merge.merge):schemaTags.slice();let tags=schemaTags;if(!tags)if(Array.isArray(customTags))tags=[];else{let keys=Array.from(schemas3.keys()).filter(key=>key!=="yaml11").map(key=>JSON.stringify(key)).join(", ");throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`)}if(Array.isArray(customTags))for(let tag of customTags)tags=tags.concat(tag);else typeof customTags=="function"&&(tags=customTags(tags.slice()));return addMergeTag&&(tags=tags.concat(merge.merge)),tags.reduce((tags2,tag)=>{let tagObj=typeof tag=="string"?tagsByName[tag]:tag;if(!tagObj){let tagName=JSON.stringify(tag),keys=Object.keys(tagsByName).map(key=>JSON.stringify(key)).join(", ");throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`)}return tags2.includes(tagObj)||tags2.push(tagObj),tags2},[])}__name(getTags,"getTags");exports2.coreKnownTags=coreKnownTags;exports2.getTags=getTags}});var require_Schema=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/Schema.js"(exports2){"use strict";var identity2=require_identity(),map=require_map2(),seq=require_seq2(),string=require_string(),tags=require_tags(),sortMapEntriesByKey=__name((a,b)=>a.key<b.key?-1:a.key>b.key?1:0,"sortMapEntriesByKey"),Schema=class _Schema{static{__name(this,"Schema")}constructor({compat,customTags,merge,resolveKnownTags,schema,sortMapEntries,toStringDefaults}){this.compat=Array.isArray(compat)?tags.getTags(compat,"compat"):compat?tags.getTags(null,compat):null,this.name=typeof schema=="string"&&schema||"core",this.knownTags=resolveKnownTags?tags.coreKnownTags:{},this.tags=tags.getTags(customTags,this.name,merge),this.toStringOptions=toStringDefaults??null,Object.defineProperty(this,identity2.MAP,{value:map.map}),Object.defineProperty(this,identity2.SCALAR,{value:string.string}),Object.defineProperty(this,identity2.SEQ,{value:seq.seq}),this.sortMapEntries=typeof sortMapEntries=="function"?sortMapEntries:sortMapEntries===!0?sortMapEntriesByKey:null}clone(){let copy=Object.create(_Schema.prototype,Object.getOwnPropertyDescriptors(this));return copy.tags=this.tags.slice(),copy}};exports2.Schema=Schema}});var require_stringifyDocument=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyDocument.js"(exports2){"use strict";var identity2=require_identity(),stringify3=require_stringify(),stringifyComment=require_stringifyComment();function stringifyDocument(doc,options){let lines=[],hasDirectives=options.directives===!0;if(options.directives!==!1&&doc.directives){let dir=doc.directives.toString(doc);dir?(lines.push(dir),hasDirectives=!0):doc.directives.docStart&&(hasDirectives=!0)}hasDirectives&&lines.push("---");let ctx=stringify3.createStringifyContext(doc,options),{commentString}=ctx.options;if(doc.commentBefore){lines.length!==1&&lines.unshift("");let cs=commentString(doc.commentBefore);lines.unshift(stringifyComment.indentComment(cs,""))}let chompKeep=!1,contentComment=null;if(doc.contents){if(identity2.isNode(doc.contents)){if(doc.contents.spaceBefore&&hasDirectives&&lines.push(""),doc.contents.commentBefore){let cs=commentString(doc.contents.commentBefore);lines.push(stringifyComment.indentComment(cs,""))}ctx.forceBlockIndent=!!doc.comment,contentComment=doc.contents.comment}let onChompKeep=contentComment?void 0:()=>chompKeep=!0,body=stringify3.stringify(doc.contents,ctx,()=>contentComment=null,onChompKeep);contentComment&&(body+=stringifyComment.lineComment(body,"",commentString(contentComment))),(body[0]==="|"||body[0]===">")&&lines[lines.length-1]==="---"?lines[lines.length-1]=`--- ${body}`:lines.push(body)}else lines.push(stringify3.stringify(doc.contents,ctx));if(doc.directives?.docEnd)if(doc.comment){let cs=commentString(doc.comment);cs.includes(`
|
|
170
|
+
${cn.comment}`:item.comment}item=pair}seq.items[i]=identity2.isPair(item)?item:new Pair.Pair(item)}}else onError("Expected a sequence for this tag");return seq}__name(resolvePairs,"resolvePairs");function createPairs(schema,iterable,ctx){let{replacer}=ctx,pairs2=new YAMLSeq.YAMLSeq(schema);pairs2.tag="tag:yaml.org,2002:pairs";let i=0;if(iterable&&Symbol.iterator in Object(iterable))for(let it2 of iterable){typeof replacer=="function"&&(it2=replacer.call(iterable,String(i++),it2));let key,value;if(Array.isArray(it2))if(it2.length===2)key=it2[0],value=it2[1];else throw new TypeError(`Expected [key, value] tuple: ${it2}`);else if(it2&&it2 instanceof Object){let keys=Object.keys(it2);if(keys.length===1)key=keys[0],value=it2[key];else throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`)}else key=it2;pairs2.items.push(Pair.createPair(key,value,ctx))}return pairs2}__name(createPairs,"createPairs");var pairs={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:resolvePairs,createNode:createPairs};exports2.createPairs=createPairs;exports2.pairs=pairs;exports2.resolvePairs=resolvePairs}});var require_omap2=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/omap.js"(exports2){"use strict";var identity2=require_identity(),toJS=require_toJS(),YAMLMap=require_YAMLMap(),YAMLSeq=require_YAMLSeq(),pairs=require_pairs2(),YAMLOMap=class _YAMLOMap extends YAMLSeq.YAMLSeq{static{__name(this,"YAMLOMap")}constructor(){super(),this.add=YAMLMap.YAMLMap.prototype.add.bind(this),this.delete=YAMLMap.YAMLMap.prototype.delete.bind(this),this.get=YAMLMap.YAMLMap.prototype.get.bind(this),this.has=YAMLMap.YAMLMap.prototype.has.bind(this),this.set=YAMLMap.YAMLMap.prototype.set.bind(this),this.tag=_YAMLOMap.tag}toJSON(_,ctx){if(!ctx)return super.toJSON(_);let map=new Map;ctx?.onCreate&&ctx.onCreate(map);for(let pair of this.items){let key,value;if(identity2.isPair(pair)?(key=toJS.toJS(pair.key,"",ctx),value=toJS.toJS(pair.value,key,ctx)):key=toJS.toJS(pair,"",ctx),map.has(key))throw new Error("Ordered maps must not include duplicate keys");map.set(key,value)}return map}static from(schema,iterable,ctx){let pairs$1=pairs.createPairs(schema,iterable,ctx),omap2=new this;return omap2.items=pairs$1.items,omap2}};YAMLOMap.tag="tag:yaml.org,2002:omap";var omap={collection:"seq",identify:__name(value=>value instanceof Map,"identify"),nodeClass:YAMLOMap,default:!1,tag:"tag:yaml.org,2002:omap",resolve(seq,onError){let pairs$1=pairs.resolvePairs(seq,onError),seenKeys=[];for(let{key}of pairs$1.items)identity2.isScalar(key)&&(seenKeys.includes(key.value)?onError(`Ordered maps must not include duplicate keys: ${key.value}`):seenKeys.push(key.value));return Object.assign(new YAMLOMap,pairs$1)},createNode:__name((schema,iterable,ctx)=>YAMLOMap.from(schema,iterable,ctx),"createNode")};exports2.YAMLOMap=YAMLOMap;exports2.omap=omap}});var require_bool3=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/bool.js"(exports2){"use strict";var Scalar=require_Scalar();function boolStringify({value,source},ctx){return source&&(value?trueTag:falseTag).test.test(source)?source:value?ctx.options.trueStr:ctx.options.falseStr}__name(boolStringify,"boolStringify");var trueTag={identify:__name(value=>value===!0,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:__name(()=>new Scalar.Scalar(!0),"resolve"),stringify:boolStringify},falseTag={identify:__name(value=>value===!1,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:__name(()=>new Scalar.Scalar(!1),"resolve"),stringify:boolStringify};exports2.falseTag=falseTag;exports2.trueTag=trueTag}});var require_float3=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/float.js"(exports2){"use strict";var Scalar=require_Scalar(),stringifyNumber=require_stringifyNumber(),floatNaN={identify:__name(value=>typeof value=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:__name(str=>str.slice(-3).toLowerCase()==="nan"?NaN:str[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:stringifyNumber.stringifyNumber},floatExp={identify:__name(value=>typeof value=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:__name(str=>parseFloat(str.replace(/_/g,"")),"resolve"),stringify(node){let num=Number(node.value);return isFinite(num)?num.toExponential():stringifyNumber.stringifyNumber(node)}},float={identify:__name(value=>typeof value=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(str){let node=new Scalar.Scalar(parseFloat(str.replace(/_/g,""))),dot=str.indexOf(".");if(dot!==-1){let f=str.substring(dot+1).replace(/_/g,"");f[f.length-1]==="0"&&(node.minFractionDigits=f.length)}return node},stringify:stringifyNumber.stringifyNumber};exports2.float=float;exports2.floatExp=floatExp;exports2.floatNaN=floatNaN}});var require_int3=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/int.js"(exports2){"use strict";var stringifyNumber=require_stringifyNumber(),intIdentify=__name(value=>typeof value=="bigint"||Number.isInteger(value),"intIdentify");function intResolve(str,offset,radix,{intAsBigInt}){let sign=str[0];if((sign==="-"||sign==="+")&&(offset+=1),str=str.substring(offset).replace(/_/g,""),intAsBigInt){switch(radix){case 2:str=`0b${str}`;break;case 8:str=`0o${str}`;break;case 16:str=`0x${str}`;break}let n2=BigInt(str);return sign==="-"?BigInt(-1)*n2:n2}let n=parseInt(str,radix);return sign==="-"?-1*n:n}__name(intResolve,"intResolve");function intStringify(node,radix,prefix){let{value}=node;if(intIdentify(value)){let str=value.toString(radix);return value<0?"-"+prefix+str.substr(1):prefix+str}return stringifyNumber.stringifyNumber(node)}__name(intStringify,"intStringify");var intBin={identify:intIdentify,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:__name((str,_onError,opt)=>intResolve(str,2,2,opt),"resolve"),stringify:__name(node=>intStringify(node,2,"0b"),"stringify")},intOct={identify:intIdentify,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:__name((str,_onError,opt)=>intResolve(str,1,8,opt),"resolve"),stringify:__name(node=>intStringify(node,8,"0"),"stringify")},int={identify:intIdentify,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:__name((str,_onError,opt)=>intResolve(str,0,10,opt),"resolve"),stringify:stringifyNumber.stringifyNumber},intHex={identify:intIdentify,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:__name((str,_onError,opt)=>intResolve(str,2,16,opt),"resolve"),stringify:__name(node=>intStringify(node,16,"0x"),"stringify")};exports2.int=int;exports2.intBin=intBin;exports2.intHex=intHex;exports2.intOct=intOct}});var require_set2=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/set.js"(exports2){"use strict";var identity2=require_identity(),Pair=require_Pair(),YAMLMap=require_YAMLMap(),YAMLSet=class _YAMLSet extends YAMLMap.YAMLMap{static{__name(this,"YAMLSet")}constructor(schema){super(schema),this.tag=_YAMLSet.tag}add(key){let pair;identity2.isPair(key)?pair=key:key&&typeof key=="object"&&"key"in key&&"value"in key&&key.value===null?pair=new Pair.Pair(key.key,null):pair=new Pair.Pair(key,null),YAMLMap.findPair(this.items,pair.key)||this.items.push(pair)}get(key,keepPair){let pair=YAMLMap.findPair(this.items,key);return!keepPair&&identity2.isPair(pair)?identity2.isScalar(pair.key)?pair.key.value:pair.key:pair}set(key,value){if(typeof value!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);let prev=YAMLMap.findPair(this.items,key);prev&&!value?this.items.splice(this.items.indexOf(prev),1):!prev&&value&&this.items.push(new Pair.Pair(key))}toJSON(_,ctx){return super.toJSON(_,ctx,Set)}toString(ctx,onComment,onChompKeep){if(!ctx)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},ctx,{allNullValues:!0}),onComment,onChompKeep);throw new Error("Set items must all have null values")}static from(schema,iterable,ctx){let{replacer}=ctx,set2=new this(schema);if(iterable&&Symbol.iterator in Object(iterable))for(let value of iterable)typeof replacer=="function"&&(value=replacer.call(iterable,value,value)),set2.items.push(Pair.createPair(value,null,ctx));return set2}};YAMLSet.tag="tag:yaml.org,2002:set";var set={collection:"map",identify:__name(value=>value instanceof Set,"identify"),nodeClass:YAMLSet,default:!1,tag:"tag:yaml.org,2002:set",createNode:__name((schema,iterable,ctx)=>YAMLSet.from(schema,iterable,ctx),"createNode"),resolve(map,onError){if(identity2.isMap(map)){if(map.hasAllNullValues(!0))return Object.assign(new YAMLSet,map);onError("Set items must all have null values")}else onError("Expected a mapping for this tag");return map}};exports2.YAMLSet=YAMLSet;exports2.set=set}});var require_timestamp2=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/timestamp.js"(exports2){"use strict";var stringifyNumber=require_stringifyNumber();function parseSexagesimal(str,asBigInt){let sign=str[0],parts=sign==="-"||sign==="+"?str.substring(1):str,num=__name(n=>asBigInt?BigInt(n):Number(n),"num"),res=parts.replace(/_/g,"").split(":").reduce((res2,p2)=>res2*num(60)+num(p2),num(0));return sign==="-"?num(-1)*res:res}__name(parseSexagesimal,"parseSexagesimal");function stringifySexagesimal(node){let{value}=node,num=__name(n=>n,"num");if(typeof value=="bigint")num=__name(n=>BigInt(n),"num");else if(isNaN(value)||!isFinite(value))return stringifyNumber.stringifyNumber(node);let sign="";value<0&&(sign="-",value*=num(-1));let _60=num(60),parts=[value%_60];return value<60?parts.unshift(0):(value=(value-parts[0])/_60,parts.unshift(value%_60),value>=60&&(value=(value-parts[0])/_60,parts.unshift(value))),sign+parts.map(n=>String(n).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}__name(stringifySexagesimal,"stringifySexagesimal");var intTime={identify:__name(value=>typeof value=="bigint"||Number.isInteger(value),"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:__name((str,_onError,{intAsBigInt})=>parseSexagesimal(str,intAsBigInt),"resolve"),stringify:stringifySexagesimal},floatTime={identify:__name(value=>typeof value=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:__name(str=>parseSexagesimal(str,!1),"resolve"),stringify:stringifySexagesimal},timestamp={identify:__name(value=>value instanceof Date,"identify"),default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(str){let match=str.match(timestamp.test);if(!match)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,year,month,day3,hour,minute,second]=match.map(Number),millisec=match[7]?Number((match[7]+"00").substr(1,3)):0,date=Date.UTC(year,month-1,day3,hour||0,minute||0,second||0,millisec),tz=match[8];if(tz&&tz!=="Z"){let d3=parseSexagesimal(tz,!1);Math.abs(d3)<30&&(d3*=60),date-=6e4*d3}return new Date(date)},stringify:__name(({value})=>value?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??"","stringify")};exports2.floatTime=floatTime;exports2.intTime=intTime;exports2.timestamp=timestamp}});var require_schema4=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/yaml-1.1/schema.js"(exports2){"use strict";var map=require_map2(),_null=require_null2(),seq=require_seq2(),string=require_string(),binary=require_binary2(),bool=require_bool3(),float=require_float3(),int=require_int3(),merge=require_merge2(),omap=require_omap2(),pairs=require_pairs2(),set=require_set2(),timestamp=require_timestamp2(),schema=[map.map,seq.seq,string.string,_null.nullTag,bool.trueTag,bool.falseTag,int.intBin,int.intOct,int.int,int.intHex,float.floatNaN,float.floatExp,float.float,binary.binary,merge.merge,omap.omap,pairs.pairs,set.set,timestamp.intTime,timestamp.floatTime,timestamp.timestamp];exports2.schema=schema}});var require_tags=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/tags.js"(exports2){"use strict";var map=require_map2(),_null=require_null2(),seq=require_seq2(),string=require_string(),bool=require_bool2(),float=require_float2(),int=require_int2(),schema=require_schema2(),schema$1=require_schema3(),binary=require_binary2(),merge=require_merge2(),omap=require_omap2(),pairs=require_pairs2(),schema$2=require_schema4(),set=require_set2(),timestamp=require_timestamp2(),schemas3=new Map([["core",schema.schema],["failsafe",[map.map,seq.seq,string.string]],["json",schema$1.schema],["yaml11",schema$2.schema],["yaml-1.1",schema$2.schema]]),tagsByName={binary:binary.binary,bool:bool.boolTag,float:float.float,floatExp:float.floatExp,floatNaN:float.floatNaN,floatTime:timestamp.floatTime,int:int.int,intHex:int.intHex,intOct:int.intOct,intTime:timestamp.intTime,map:map.map,merge:merge.merge,null:_null.nullTag,omap:omap.omap,pairs:pairs.pairs,seq:seq.seq,set:set.set,timestamp:timestamp.timestamp},coreKnownTags={"tag:yaml.org,2002:binary":binary.binary,"tag:yaml.org,2002:merge":merge.merge,"tag:yaml.org,2002:omap":omap.omap,"tag:yaml.org,2002:pairs":pairs.pairs,"tag:yaml.org,2002:set":set.set,"tag:yaml.org,2002:timestamp":timestamp.timestamp};function getTags(customTags,schemaName,addMergeTag){let schemaTags=schemas3.get(schemaName);if(schemaTags&&!customTags)return addMergeTag&&!schemaTags.includes(merge.merge)?schemaTags.concat(merge.merge):schemaTags.slice();let tags=schemaTags;if(!tags)if(Array.isArray(customTags))tags=[];else{let keys=Array.from(schemas3.keys()).filter(key=>key!=="yaml11").map(key=>JSON.stringify(key)).join(", ");throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`)}if(Array.isArray(customTags))for(let tag of customTags)tags=tags.concat(tag);else typeof customTags=="function"&&(tags=customTags(tags.slice()));return addMergeTag&&(tags=tags.concat(merge.merge)),tags.reduce((tags2,tag)=>{let tagObj=typeof tag=="string"?tagsByName[tag]:tag;if(!tagObj){let tagName=JSON.stringify(tag),keys=Object.keys(tagsByName).map(key=>JSON.stringify(key)).join(", ");throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`)}return tags2.includes(tagObj)||tags2.push(tagObj),tags2},[])}__name(getTags,"getTags");exports2.coreKnownTags=coreKnownTags;exports2.getTags=getTags}});var require_Schema=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/schema/Schema.js"(exports2){"use strict";var identity2=require_identity(),map=require_map2(),seq=require_seq2(),string=require_string(),tags=require_tags(),sortMapEntriesByKey=__name((a,b)=>a.key<b.key?-1:a.key>b.key?1:0,"sortMapEntriesByKey"),Schema=class _Schema{static{__name(this,"Schema")}constructor({compat,customTags,merge,resolveKnownTags,schema,sortMapEntries,toStringDefaults}){this.compat=Array.isArray(compat)?tags.getTags(compat,"compat"):compat?tags.getTags(null,compat):null,this.name=typeof schema=="string"&&schema||"core",this.knownTags=resolveKnownTags?tags.coreKnownTags:{},this.tags=tags.getTags(customTags,this.name,merge),this.toStringOptions=toStringDefaults??null,Object.defineProperty(this,identity2.MAP,{value:map.map}),Object.defineProperty(this,identity2.SCALAR,{value:string.string}),Object.defineProperty(this,identity2.SEQ,{value:seq.seq}),this.sortMapEntries=typeof sortMapEntries=="function"?sortMapEntries:sortMapEntries===!0?sortMapEntriesByKey:null}clone(){let copy=Object.create(_Schema.prototype,Object.getOwnPropertyDescriptors(this));return copy.tags=this.tags.slice(),copy}};exports2.Schema=Schema}});var require_stringifyDocument=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/stringify/stringifyDocument.js"(exports2){"use strict";var identity2=require_identity(),stringify3=require_stringify(),stringifyComment=require_stringifyComment();function stringifyDocument(doc,options){let lines=[],hasDirectives=options.directives===!0;if(options.directives!==!1&&doc.directives){let dir=doc.directives.toString(doc);dir?(lines.push(dir),hasDirectives=!0):doc.directives.docStart&&(hasDirectives=!0)}hasDirectives&&lines.push("---");let ctx=stringify3.createStringifyContext(doc,options),{commentString}=ctx.options;if(doc.commentBefore){lines.length!==1&&lines.unshift("");let cs=commentString(doc.commentBefore);lines.unshift(stringifyComment.indentComment(cs,""))}let chompKeep=!1,contentComment=null;if(doc.contents){if(identity2.isNode(doc.contents)){if(doc.contents.spaceBefore&&hasDirectives&&lines.push(""),doc.contents.commentBefore){let cs=commentString(doc.contents.commentBefore);lines.push(stringifyComment.indentComment(cs,""))}ctx.forceBlockIndent=!!doc.comment,contentComment=doc.contents.comment}let onChompKeep=contentComment?void 0:()=>chompKeep=!0,body=stringify3.stringify(doc.contents,ctx,()=>contentComment=null,onChompKeep);contentComment&&(body+=stringifyComment.lineComment(body,"",commentString(contentComment))),(body[0]==="|"||body[0]===">")&&lines[lines.length-1]==="---"?lines[lines.length-1]=`--- ${body}`:lines.push(body)}else lines.push(stringify3.stringify(doc.contents,ctx));if(doc.directives?.docEnd)if(doc.comment){let cs=commentString(doc.comment);cs.includes(`
|
|
171
171
|
`)?(lines.push("..."),lines.push(stringifyComment.indentComment(cs,""))):lines.push(`... ${cs}`)}else lines.push("...");else{let dc=doc.comment;dc&&chompKeep&&(dc=dc.replace(/^\n+/,"")),dc&&((!chompKeep||contentComment)&&lines[lines.length-1]!==""&&lines.push(""),lines.push(stringifyComment.indentComment(commentString(dc),"")))}return lines.join(`
|
|
172
172
|
`)+`
|
|
173
173
|
`}__name(stringifyDocument,"stringifyDocument");exports2.stringifyDocument=stringifyDocument}});var require_Document=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/doc/Document.js"(exports2){"use strict";var Alias=require_Alias(),Collection=require_Collection(),identity2=require_identity(),Pair=require_Pair(),toJS=require_toJS(),Schema=require_Schema(),stringifyDocument=require_stringifyDocument(),anchors=require_anchors(),applyReviver=require_applyReviver(),createNode=require_createNode(),directives=require_directives(),Document=class _Document{static{__name(this,"Document")}constructor(value,replacer,options){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,identity2.NODE_TYPE,{value:identity2.DOC});let _replacer=null;typeof replacer=="function"||Array.isArray(replacer)?_replacer=replacer:options===void 0&&replacer&&(options=replacer,replacer=void 0);let opt=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},options);this.options=opt;let{version}=opt;options?._directives?(this.directives=options._directives.atDocument(),this.directives.yaml.explicit&&(version=this.directives.yaml.version)):this.directives=new directives.Directives({version}),this.setSchema(version,options),this.contents=value===void 0?null:this.createNode(value,_replacer,options)}clone(){let copy=Object.create(_Document.prototype,{[identity2.NODE_TYPE]:{value:identity2.DOC}});return copy.commentBefore=this.commentBefore,copy.comment=this.comment,copy.errors=this.errors.slice(),copy.warnings=this.warnings.slice(),copy.options=Object.assign({},this.options),this.directives&&(copy.directives=this.directives.clone()),copy.schema=this.schema.clone(),copy.contents=identity2.isNode(this.contents)?this.contents.clone(copy.schema):this.contents,this.range&&(copy.range=this.range.slice()),copy}add(value){assertCollection(this.contents)&&this.contents.add(value)}addIn(path52,value){assertCollection(this.contents)&&this.contents.addIn(path52,value)}createAlias(node,name){if(!node.anchor){let prev=anchors.anchorNames(this);node.anchor=!name||prev.has(name)?anchors.findNewAnchor(name||"a",prev):name}return new Alias.Alias(node.anchor)}createNode(value,replacer,options){let _replacer;if(typeof replacer=="function")value=replacer.call({"":value},"",value),_replacer=replacer;else if(Array.isArray(replacer)){let keyToStr=__name(v=>typeof v=="number"||v instanceof String||v instanceof Number,"keyToStr"),asStr=replacer.filter(keyToStr).map(String);asStr.length>0&&(replacer=replacer.concat(asStr)),_replacer=replacer}else options===void 0&&replacer&&(options=replacer,replacer=void 0);let{aliasDuplicateObjects,anchorPrefix,flow,keepUndefined,onTagObj,tag}=options??{},{onAnchor,setAnchors,sourceObjects}=anchors.createNodeAnchors(this,anchorPrefix||"a"),ctx={aliasDuplicateObjects:aliasDuplicateObjects??!0,keepUndefined:keepUndefined??!1,onAnchor,onTagObj,replacer:_replacer,schema:this.schema,sourceObjects},node=createNode.createNode(value,tag,ctx);return flow&&identity2.isCollection(node)&&(node.flow=!0),setAnchors(),node}createPair(key,value,options={}){let k=this.createNode(key,null,options),v=this.createNode(value,null,options);return new Pair.Pair(k,v)}delete(key){return assertCollection(this.contents)?this.contents.delete(key):!1}deleteIn(path52){return Collection.isEmptyPath(path52)?this.contents==null?!1:(this.contents=null,!0):assertCollection(this.contents)?this.contents.deleteIn(path52):!1}get(key,keepScalar){return identity2.isCollection(this.contents)?this.contents.get(key,keepScalar):void 0}getIn(path52,keepScalar){return Collection.isEmptyPath(path52)?!keepScalar&&identity2.isScalar(this.contents)?this.contents.value:this.contents:identity2.isCollection(this.contents)?this.contents.getIn(path52,keepScalar):void 0}has(key){return identity2.isCollection(this.contents)?this.contents.has(key):!1}hasIn(path52){return Collection.isEmptyPath(path52)?this.contents!==void 0:identity2.isCollection(this.contents)?this.contents.hasIn(path52):!1}set(key,value){this.contents==null?this.contents=Collection.collectionFromPath(this.schema,[key],value):assertCollection(this.contents)&&this.contents.set(key,value)}setIn(path52,value){Collection.isEmptyPath(path52)?this.contents=value:this.contents==null?this.contents=Collection.collectionFromPath(this.schema,Array.from(path52),value):assertCollection(this.contents)&&this.contents.setIn(path52,value)}setSchema(version,options={}){typeof version=="number"&&(version=String(version));let opt;switch(version){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new directives.Directives({version:"1.1"}),opt={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=version:this.directives=new directives.Directives({version}),opt={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,opt=null;break;default:{let sv=JSON.stringify(version);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`)}}if(options.schema instanceof Object)this.schema=options.schema;else if(opt)this.schema=new Schema.Schema(Object.assign(opt,options));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json,jsonArg,mapAsMap,maxAliasCount,onAnchor,reviver}={}){let ctx={anchors:new Map,doc:this,keep:!json,mapAsMap:mapAsMap===!0,mapKeyWarned:!1,maxAliasCount:typeof maxAliasCount=="number"?maxAliasCount:100},res=toJS.toJS(this.contents,jsonArg??"",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}toJSON(jsonArg,onAnchor){return this.toJS({json:!0,jsonArg,mapAsMap:!1,onAnchor})}toString(options={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in options&&(!Number.isInteger(options.indent)||Number(options.indent)<=0)){let s=JSON.stringify(options.indent);throw new Error(`"indent" option must be a positive integer, not ${s}`)}return stringifyDocument.stringifyDocument(this,options)}};function assertCollection(contents){if(identity2.isCollection(contents))return!0;throw new Error("Expected a YAML collection as document contents")}__name(assertCollection,"assertCollection");exports2.Document=Document}});var require_errors=__commonJS({"../../node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/dist/errors.js"(exports2){"use strict";var YAMLError=class extends Error{static{__name(this,"YAMLError")}constructor(name,pos,code2,message){super(),this.name=name,this.code=code2,this.message=message,this.pos=pos}},YAMLParseError=class extends YAMLError{static{__name(this,"YAMLParseError")}constructor(pos,code2,message){super("YAMLParseError",pos,code2,message)}},YAMLWarning=class extends YAMLError{static{__name(this,"YAMLWarning")}constructor(pos,code2,message){super("YAMLWarning",pos,code2,message)}},prettifyError=__name((src,lc)=>error=>{if(error.pos[0]===-1)return;error.linePos=error.pos.map(pos=>lc.linePos(pos));let{line,col}=error.linePos[0];error.message+=` at line ${line}, column ${col}`;let ci=col-1,lineStr=src.substring(lc.lineStarts[line-1],lc.lineStarts[line]).replace(/[\n\r]+$/,"");if(ci>=60&&lineStr.length>80){let trimStart=Math.min(ci-39,lineStr.length-79);lineStr="\u2026"+lineStr.substring(trimStart),ci-=trimStart-1}if(lineStr.length>80&&(lineStr=lineStr.substring(0,79)+"\u2026"),line>1&&/^ *$/.test(lineStr.substring(0,ci))){let prev=src.substring(lc.lineStarts[line-2],lc.lineStarts[line-1]);prev.length>80&&(prev=prev.substring(0,79)+`\u2026
|
|
@@ -283,7 +283,7 @@ ${end.comment}`:end.comment}this.doc.range[2]=end.offset;break}default:this.erro
|
|
|
283
283
|
${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(`
|
|
284
284
|
`).filter(Boolean).map(line=>{let code2=line.slice(0,2),path52=line.slice(3).trim();return{verb:code2.startsWith("A")||code2.startsWith("?")?"added":code2.startsWith("D")?"removed":"changed",key:path52,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)}
|
|
285
285
|
|
|
286
|
-
${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_project2();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 fs47 from"node:fs";import path51 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_config();init_sdk_transport();var ENTRIES=[{token:"agents:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project agents, chats and routines"},{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 z134}from"zod";var SurfaceGuardPolicySchema=z134.enum(["block","warn","allow"]),ClassificationSchema=z134.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z134.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z134.object({enabled:z134.boolean(),allowed_skills:z134.array(z134.string().min(1)).default([]),allowed_classifications:z134.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z134.enum(["off","daily","weekly"]),NotificationFormatSchema=z134.object({markdown:z134.boolean().default(!0),html:z134.boolean().default(!1)}),NotificationsPolicySchema=z134.object({email_recipients:z134.array(z134.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z134.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z134.object({agents:FimoAgentsConfigSchema.optional()}).passthrough();var SITE_SCRIPT=String.raw`// fimo-site: crawl the site as a browser renders it, then check it (SEO, GEO, content, quality). Node 20+, agent-browser, no dependencies.
|
|
286
|
+
${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_project2();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 fs47 from"node:fs";import path51 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_config();init_sdk_transport();var ENTRIES=[{token:"agents:read",risk:"low",declarable:!0,enforcedBy:"api",description:"Read project agents, chats and routines"},{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:"i18n:locales:add",risk:"medium",declarable:!0,enforcedBy:"api",description:"Add a supported locale to the project; never remove one or change the default"},{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 z134}from"zod";var SurfaceGuardPolicySchema=z134.enum(["block","warn","allow"]),ClassificationSchema=z134.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z134.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z134.object({enabled:z134.boolean(),allowed_skills:z134.array(z134.string().min(1)).default([]),allowed_classifications:z134.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z134.enum(["off","daily","weekly"]),NotificationFormatSchema=z134.object({markdown:z134.boolean().default(!0),html:z134.boolean().default(!1)}),NotificationsPolicySchema=z134.object({email_recipients:z134.array(z134.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z134.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z134.object({agents:FimoAgentsConfigSchema.optional()}).passthrough();var SITE_SCRIPT=String.raw`// fimo-site: crawl the site as a browser renders it, then check it (SEO, GEO, content, quality). Node 20+, agent-browser, no dependencies.
|
|
287
287
|
// Every fact is fine, broken, or unknown (could not tell); only broken leads to a finding.
|
|
288
288
|
import { spawn, spawnSync } from 'node:child_process';
|
|
289
289
|
import crypto from 'node:crypto';
|
|
@@ -2275,7 +2275,7 @@ else if (cmd === 'diff') diff();
|
|
|
2275
2275
|
else if (cmd === 'text') pageText();
|
|
2276
2276
|
else if (cmd === 'links') links();
|
|
2277
2277
|
else console.log('node site.mjs crawl [origin] [--max 300] [--max-links 300] [--deadline 900] [--parallel 1] [--seed previous.txt] [--preview-host host] [--hosted url] [--quality] [--phone-max 20] [--compliance] [--consent-max 6] [--fresh] [--pages file] [--http [--browser-max 100]] [--session name] | wait | check [--topic t1,t2] [--retired "Old=New;..."] [--today YYYY-MM-DD] | text [/path ...] | links (after crawl --pages) | diff previous.txt (writes snapshot.txt)');
|
|
2278
|
-
`;import{z as z135}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=z135.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z135.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={"agents.list":"agents:read","agents.routines":"agents:read","agents.routine_runs":"agents:read","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.site.check":"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");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_project2();function registerAgentsCommands(program2){let agents=program2.command("agents").description("Read project agents and their routines"),scoped=__name(command=>command.option("--project <id>","Site id (defaults to the linked site)").option("-C, --cwd <dir>","Site directory"),"scoped");scoped(agents).action((_options,command)=>agentsCommand(command.optsWithGlobals(),void 0,command)),scoped(agents.command("list").description("List agents and routine schedules")).action((_options,command)=>agentsCommand(command.optsWithGlobals(),void 0,command)),scoped(agents.command("show <name-or-id>").description("Read an agent and its routine instructions")).action((ref,_options,command)=>agentsCommand(command.optsWithGlobals(),ref,command)),scoped(agents.command("runs <agent> [routine]").description("List the newest runs of an agent's routines, or of one routine by name or ID").option("--limit <n>","Runs per routine, newest first (1-50)","10")).action((agent2,routine,_options,command)=>agentRunsCommand(command.optsWithGlobals(),agent2,routine,command))}__name(registerAgentsCommands,"registerAgentsCommands");async function projectScope(options,command,operation){let cwd=resolveProjectCwd(options.cwd),projectId2=options.project??resolveProjectSettings(cwd)?.projectId;if(!projectId2)throw new NotInProjectError;let branch=branchOverrideFromCommand(command)??(process.env.FIMO_ENV?.trim()||DEFAULT_BRANCH);await requireOperation(operation,{projectId:projectId2});let fimo=createCliFimoClient(loadConfig()),{chats:chats2}=await fimo.execute("agents.list",{projectId:projectId2,branch});return{projectId:projectId2,branch,fimo,agents:chats2.filter(chat=>chat.kind==="agent")}}__name(projectScope,"projectScope");function pick(items,ref,nameOf,kind){let byId=items.find(item=>item.id===ref),found=byId?[byId]:items.filter(item=>nameOf(item)===ref);if(!found.length)throw new Error(`${kind} not found: ${ref}`);if(found.length>1)throw new Error(`Multiple ${kind.toLowerCase()}s named "${ref}". Use an ID from fimo agents.`);return found[0]}__name(pick,"pick");async function agentsCommand(options,ref,command){let scope2=await projectScope(options,command,"agents.list"),{projectId:projectId2,branch,fimo}=scope2,agents=ref===void 0?scope2.agents:[pick(scope2.agents,ref,agent2=>agent2.title,"Agent")],result=await Promise.all(agents.map(async agent2=>{let{routines:routines2}=await fimo.execute("agents.routines",{projectId:projectId2,branch,threadId:agent2.id});return{id:agent2.id,name:agent2.title??"Agent",description:ref===void 0?(agent2.description??"").replace(/\s+/g," ").slice(0,60):agent2.description,routines:routines2.map(routine=>({id:routine.id,name:routine.name,schedule:routine.triggers.schedule,event:routine.triggers.event?.text??null,paused:routine.paused,nextRunAt:routine.nextRunAt,lastRunAt:routine.lastRunAt,lastOutcome:routine.lastOutcome,outOfAgentHoursUntil:routine.outOfAgentHoursUntil,...ref!==void 0?{instructions:routine.instructions}:{}}))}}));ui.result({command:ref===void 0?"agents list":"agents show",data:ref===void 0?{agents:result}:result[0],render:__name(()=>result.length?result.map(agent2=>[`${agent2.name} (${agent2.id})`,...agent2.description?[agent2.description]:[],...agent2.routines.map(routine=>{let when=[routine.schedule?`${routine.schedule.cron} (${routine.schedule.timezone})`:"manual",...routine.event?[routine.event]:[],...routine.nextRunAt?[`next ${routine.nextRunAt}`]:[],...routine.lastRunAt?[`last ${routine.lastRunAt}${routine.lastOutcome?` (${routine.lastOutcome})`:""}`]:[],...routine.outOfAgentHoursUntil?[`out of agent-hours until ${routine.outOfAgentHoursUntil}`]:[]].join("; ");return` - ${routine.name}: ${when}${routine.paused?" [paused]":""}${routine.instructions?`
|
|
2278
|
+
`;import{z as z135}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=z135.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z135.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={"agents.list":"agents:read","agents.routines":"agents:read","agents.routine_runs":"agents:read","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","i18n.locales.add":"i18n:locales:add","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.site.check":"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");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_project2();function registerAgentsCommands(program2){let agents=program2.command("agents").description("Read project agents and their routines"),scoped=__name(command=>command.option("--project <id>","Site id (defaults to the linked site)").option("-C, --cwd <dir>","Site directory"),"scoped");scoped(agents).action((_options,command)=>agentsCommand(command.optsWithGlobals(),void 0,command)),scoped(agents.command("list").description("List agents and routine schedules")).action((_options,command)=>agentsCommand(command.optsWithGlobals(),void 0,command)),scoped(agents.command("show <name-or-id>").description("Read an agent and its routine instructions")).action((ref,_options,command)=>agentsCommand(command.optsWithGlobals(),ref,command)),scoped(agents.command("runs <agent> [routine]").description("List the newest runs of an agent's routines, or of one routine by name or ID").option("--limit <n>","Runs per routine, newest first (1-50)","10")).action((agent2,routine,_options,command)=>agentRunsCommand(command.optsWithGlobals(),agent2,routine,command))}__name(registerAgentsCommands,"registerAgentsCommands");async function projectScope(options,command,operation){let cwd=resolveProjectCwd(options.cwd),projectId2=options.project??resolveProjectSettings(cwd)?.projectId;if(!projectId2)throw new NotInProjectError;let branch=branchOverrideFromCommand(command)??(process.env.FIMO_ENV?.trim()||DEFAULT_BRANCH);await requireOperation(operation,{projectId:projectId2});let fimo=createCliFimoClient(loadConfig()),{chats:chats2}=await fimo.execute("agents.list",{projectId:projectId2,branch});return{projectId:projectId2,branch,fimo,agents:chats2.filter(chat=>chat.kind==="agent")}}__name(projectScope,"projectScope");function pick(items,ref,nameOf,kind){let byId=items.find(item=>item.id===ref),found=byId?[byId]:items.filter(item=>nameOf(item)===ref);if(!found.length)throw new Error(`${kind} not found: ${ref}`);if(found.length>1)throw new Error(`Multiple ${kind.toLowerCase()}s named "${ref}". Use an ID from fimo agents.`);return found[0]}__name(pick,"pick");async function agentsCommand(options,ref,command){let scope2=await projectScope(options,command,"agents.list"),{projectId:projectId2,branch,fimo}=scope2,agents=ref===void 0?scope2.agents:[pick(scope2.agents,ref,agent2=>agent2.title,"Agent")],result=await Promise.all(agents.map(async agent2=>{let{routines:routines2}=await fimo.execute("agents.routines",{projectId:projectId2,branch,threadId:agent2.id});return{id:agent2.id,name:agent2.title??"Agent",description:ref===void 0?(agent2.description??"").replace(/\s+/g," ").slice(0,60):agent2.description,routines:routines2.map(routine=>({id:routine.id,name:routine.name,schedule:routine.triggers.schedule,event:routine.triggers.event?.text??null,paused:routine.paused,nextRunAt:routine.nextRunAt,lastRunAt:routine.lastRunAt,lastOutcome:routine.lastOutcome,outOfAgentHoursUntil:routine.outOfAgentHoursUntil,...ref!==void 0?{instructions:routine.instructions}:{}}))}}));ui.result({command:ref===void 0?"agents list":"agents show",data:ref===void 0?{agents:result}:result[0],render:__name(()=>result.length?result.map(agent2=>[`${agent2.name} (${agent2.id})`,...agent2.description?[agent2.description]:[],...agent2.routines.map(routine=>{let when=[routine.schedule?`${routine.schedule.cron} (${routine.schedule.timezone})`:"manual",...routine.event?[routine.event]:[],...routine.nextRunAt?[`next ${routine.nextRunAt}`]:[],...routine.lastRunAt?[`last ${routine.lastRunAt}${routine.lastOutcome?` (${routine.lastOutcome})`:""}`]:[],...routine.outOfAgentHoursUntil?[`out of agent-hours until ${routine.outOfAgentHoursUntil}`]:[]].join("; ");return` - ${routine.name}: ${when}${routine.paused?" [paused]":""}${routine.instructions?`
|
|
2279
2279
|
${routine.instructions}`:""}`})].join(`
|
|
2280
2280
|
`)).join(`
|
|
2281
2281
|
|
|
@@ -2501,7 +2501,7 @@ ${failure.stderr}`});break}}__name(emitPushFailure,"emitPushFailure");function e
|
|
|
2501
2501
|
Purchase: ${formatPrice(pricing.price)} \xD7 ${effectiveYears} year${effectiveYears===1?"":"s"} = ${formatPrice(totalCents)}
|
|
2502
2502
|
Renewal: ${formatPrice(pricing.renewalPrice)}/year${autoRenew===!1?" (auto-renew off)":" (auto-renews)"}`);let confirmed=await ot2({message:`Create a checkout invoice for ${domain}?`,initialValue:!1});if(q(confirmed)||!confirmed){ui.info({command:"domains buy",message:"Cancelled."});return}}let purchased;try{purchased=await fimo.execute("registeredDomains.purchase",{organizationId,domain,years:effectiveYears,autoRenew})}catch(err){rethrowCliAuthError(err);let featureMsg=featureDisabledMessage(err);if(featureMsg){ui.error({command:"domains buy",code:"DOMAIN_PURCHASE_DISABLED",message:featureMsg});return}if(err instanceof ApiRequestError){if(err.status===403){ui.error({command:"domains buy",code:"PURCHASE_FORBIDDEN",message:"You don't have permission to buy domains for this organization.",hint:"Org admins only."});return}ui.error({command:"domains buy",code:"PURCHASE_FAILED",message:`Purchase failed: ${err.detail}`});return}throw err}ui.result({command:"domains buy",data:purchased,render:__name(()=>{let lines=[];return lines.push(""),lines.push(`Invoice created for ${purchased.domain} (${formatPrice(purchased.price)}).`),lines.push("Pay to complete registration:"),lines.push(""),lines.push(` ${purchased.checkoutUrl??"(checkout URL pending \u2014 refresh in a moment)"}`),lines.push(""),lines.push("No money moves until you complete payment in the browser."),lines.push(`Once paid, ${purchased.domain} registers automatically and shows up in \`fimo domains owned\`.`),lines.join(`
|
|
2503
2503
|
`)},"render")}),options.open&&purchased.checkoutUrl&&await open_default(purchased.checkoutUrl).catch(()=>{});let{enabled:waitEnabled,timeoutMs}=parseWait(options,!1);waitEnabled&&await pollPurchasePayment(fimo,organizationId,purchased,timeoutMs)}__name(domainsBuyCommand,"domainsBuyCommand");async function pollPurchasePayment(fimo,organizationId,initial,timeoutMs){let start=Date.now(),sp=spinner(`Waiting for payment (status: ${initial.status})`),current=initial;for(;Date.now()-start<timeoutMs;){if(current.status==="owned")return sp.succeed(`Registered \u2014 ${current.domain} is now yours.`),current;if(current.status==="registration_failed"||current.status==="payment_failed")return sp.fail(`${current.status==="payment_failed"?"Payment":"Registration"} failed for ${current.domain}.`),current;await new Promise(resolve10=>setTimeout(resolve10,5e3));try{current=await fimo.execute("registeredDomains.refreshPayment",{organizationId,domainId:current.id}),sp.update(`Waiting (status: ${current.status})`)}catch(err){return rethrowCliAuthError(err,()=>sp.fail("Authentication required")),sp.fail(`Refresh failed: ${err instanceof Error?err.message:String(err)}`),current}}return sp.fail("Timed out. Run `fimo domains owned` later to check status."),current}__name(pollPurchasePayment,"pollPurchasePayment");async function domainsOwnedCommand(options){let cfg=loadConfig(),fimo=createCliFimoClient(cfg),organizationId=resolveOrgId(options),domains2;try{domains2=await fimo.execute("registeredDomains.list",{organizationId})}catch(err){rethrowCliAuthError(err);let featureMsg=featureDisabledMessage(err);if(featureMsg){ui.error({command:"domains owned",code:"DOMAIN_PURCHASE_DISABLED",message:featureMsg});return}if(err instanceof ApiRequestError&&err.status===403){ui.error({command:"domains owned",code:"OWNED_DOMAINS_FORBIDDEN",message:"You don't have access to this organization's domains.",hint:"Org admins only."});return}throw err}let statusFilter=options.status?.split(",").map(s=>s.trim().toLowerCase()).filter(s=>s.length>0),limit=options.limit?parseInt(options.limit,10):null,filtered=domains2;if(statusFilter&&statusFilter.length>0&&(filtered=filtered.filter(d3=>statusFilter.includes(d3.status.toLowerCase()))),limit!==null&&Number.isFinite(limit)&&limit>0&&(filtered=filtered.slice(0,limit)),filtered.length===0){ui.info({command:"domains owned",message:"No domains registered through Fimo yet.",hint:"Try `fimo domains search <keyword>`."});return}ui.result({command:"domains owned",data:{domains:filtered,total:filtered.length},render:__name(()=>{let nameW=Math.max(8,...filtered.map(d3=>d3.domain.length)),statusW=Math.max(8,...filtered.map(d3=>d3.status.length)),lines=[];lines.push(` ${pad("DOMAIN",nameW)} ${pad("STATUS",statusW)} EXPIRES`);for(let d3 of filtered){let expires=d3.expirationDate?new Date(d3.expirationDate).toISOString().slice(0,10):"\u2014";lines.push(` ${pad(d3.domain,nameW)} ${pad(d3.status,statusW)} ${expires}`)}return lines.join(`
|
|
2504
|
-
`)},"render")})}__name(domainsOwnedCommand,"domainsOwnedCommand");init_dist();init_config();init_sdk_transport();init_project_context();init_project2();import fs28 from"node:fs";import path27 from"node:path";function selectedInputSources(options,inlineFlag){return[options.body!==void 0?inlineFlag:void 0,options.file?"--file":void 0,options.stdin?"--stdin":void 0].filter(source=>!!source)}__name(selectedInputSources,"selectedInputSources");async function readContentInputSource(options,createError,inlineFlag="--body"){if(selectedInputSources(options,inlineFlag).length!==1)throw createError(`Pass exactly one of ${inlineFlag}, --file, or --stdin.`);if(options.body!==void 0)return options.body;if(options.file){let filePath=path27.resolve(resolveProjectCwd(options.cwd),options.file);try{return fs28.readFileSync(filePath,"utf8")}catch(error){throw createError(error instanceof Error?error.message:`Could not read ${filePath}.`)}}if(process.stdin.isTTY)throw createError("Pipe input to the command when using --stdin.");let chunks=[];for await(let chunk of process.stdin)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));return Buffer.concat(chunks).toString("utf8")}__name(readContentInputSource,"readContentInputSource");function renderPrettyJson5(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson5,"renderPrettyJson");var EntriesInputError=class extends Error{static{__name(this,"EntriesInputError")}constructor(message){super(message),this.name="EntriesInputError"}};function reportSingleContentTypeError(command,error){return!(error instanceof ApiRequestError)||error.code!=="single_content_type"?!1:(ui.error({command,code:"SINGLE_CONTENT_TYPE",message:"This content type is a Single. Use `fimo singles update` to create or update it."}),!0)}__name(reportSingleContentTypeError,"reportSingleContentTypeError");var DEFAULT_BULK_CHUNK_SIZE=100,MAX_BULK_CHUNK_SIZE=1e3;function parseJsonObject(value){let parsed=JSON.parse(value);if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new Error("Expected a JSON object");return parsed}__name(parseJsonObject,"parseJsonObject");function parseJsonArray(value){let parsed;try{parsed=JSON.parse(value)}catch(error){throw new EntriesInputError(error instanceof Error?`Invalid JSON: ${error.message}`:"Invalid JSON.")}if(!Array.isArray(parsed))throw new EntriesInputError("Expected a JSON array.");return parsed}__name(parseJsonArray,"parseJsonArray");function parseChunkSize(value){if(value===void 0)return DEFAULT_BULK_CHUNK_SIZE;let size=Number(value);if(!Number.isInteger(size)||size<1||size>MAX_BULK_CHUNK_SIZE)throw new EntriesInputError(`--chunk-size must be an integer from 1 to ${MAX_BULK_CHUNK_SIZE}.`);return size}__name(parseChunkSize,"parseChunkSize");function chunksOf(items,size){let chunks=[];for(let offset=0;offset<items.length;offset+=size)chunks.push(items.slice(offset,offset+size));return chunks}__name(chunksOf,"chunksOf");function parseEntryInput(value,index){if(!value||typeof value!="object"||Array.isArray(value))throw new EntriesInputError(`Entry ${index+1} must be a JSON object.`);let input=value;if(!input.data||typeof input.data!="object"||Array.isArray(input.data))throw new EntriesInputError(`Entry ${index+1} must include a data object.`);return input}__name(parseEntryInput,"parseEntryInput");function identityValue(input,field,index){let value=field==="slug"?input.data.slug??input.data[field]:input.data[field];if(typeof value!="string"||value.length===0)throw new EntriesInputError(`Entry ${index+1} needs a non-empty data.${field} for --upsert-by ${field}.`);return value}__name(identityValue,"identityValue");function identityKey(value,locale){return`${locale??""}\0${value}`}__name(identityKey,"identityKey");async function listEntriesByIdentity(content2,projectId2,typeName,field,inputs){let byLocale=new Map;for(let[index,input]of inputs.entries()){let values=byLocale.get(input.locale)??new Set;values.add(identityValue(input,field,index)),byLocale.set(input.locale,values)}let found=new Map;for(let[locale,values]of byLocale){let result=await content2.listEntries(projectId2,typeName,{limit:"100",where:JSON.stringify({[field]:{$in:[...values]}}),fields:`id,documentId,${field},locale`,...locale?{locale}:{}});if(result.meta.hasMore)throw new EntriesInputError(`More than 100 ${typeName} entries matched this ${field} batch; reduce --chunk-size.`);for(let entry of result.data){let value=entry[field];if(typeof value!="string")continue;let key=identityKey(value,locale);found.set(key,[...found.get(key)??[],entry])}}return found}__name(listEntriesByIdentity,"listEntriesByIdentity");async function createWithReconciliation(fimo,content2,projectId2,branch,typeName,field,inputs){let pending=inputs,created=0,reconciled=0;for(let attempt=0;attempt<2&&pending.length>0;attempt+=1)try{let result=await fimo.execute("entries.bulkCreate",{projectId:projectId2,branch,typeName,entries:pending});created+=result.meta.created,pending=[]}catch(error){if(!(error instanceof ApiRequestError)||error.status!==504)throw error;let existing=await listEntriesByIdentity(content2,projectId2,typeName,field,pending),absent=pending.filter((input,index)=>{let key=identityKey(identityValue(input,field,index),input.locale);return(existing.get(key)?.length??0)===0});reconciled+=pending.length-absent.length,pending=absent}if(pending.length>0)throw new EntriesInputError(`${pending.length} entries remain absent after reconciling an ambiguous 504; rerun the same upsert input safely.`);return{created,reconciled}}__name(createWithReconciliation,"createWithReconciliation");async function upsertChunk(fimo,content2,projectId2,branch,typeName,field,inputs,chunk,identityCounts){let existing=await listEntriesByIdentity(content2,projectId2,typeName,field,inputs),creates=[],updates=[],conflicts=0;for(let[index,input]of inputs.entries()){let key=identityKey(identityValue(input,field,index),input.locale),matches=existing.get(key)??[];if((identityCounts.get(key)??0)>1||matches.length>1){conflicts+=1;continue}matches.length===1?updates.push({id:matches[0].documentId,body:input}):creates.push(input)}let updated=0;if(updates.length>0)try{let result=await fimo.execute("entries.bulkUpdate",{projectId:projectId2,branch,typeName,selection:{updates}});updated=result.meta.updated,conflicts+=result.meta.missing.length}catch(error){throw!(error instanceof ApiRequestError)||error.status!==504?error:(await listEntriesByIdentity(content2,projectId2,typeName,field,inputs),new EntriesInputError(`${updates.length} updates had an ambiguous 504; identities were reread without replay. Rerun the same upsert input safely.`))}let createResult=await createWithReconciliation(fimo,content2,projectId2,branch,typeName,field,creates);return{chunk,input:inputs.length,created:createResult.created,updated,conflicts,reconciled:createResult.reconciled}}__name(upsertChunk,"upsertChunk");function parseBulkJsonObject(value){try{return parseJsonObject(value)}catch(error){throw new EntriesInputError(error instanceof Error?error.message:"Expected a JSON object.")}}__name(parseBulkJsonObject,"parseBulkJsonObject");function parseIds(value){let ids=[...new Set(value.split(",").map(id=>id.trim()).filter(Boolean))];if(ids.length===0)throw new EntriesInputError("--ids must include at least one ID.");return ids}__name(parseIds,"parseIds");function missingIdWarnings(result,action){let{missing}=result.meta;if(missing.length===0)return[];let changed=action==="updated"?result.meta.updated:result.meta.deleted,ids=missing.join(", ");if(changed===0)return missing.length===1?[`No entries were ${action}; the requested ID was not found: ${ids}.`]:[`No entries were ${action}; all ${missing.length} requested IDs were not found: ${ids}.`];let subject=missing.length===1?"ID was":"IDs were";return[`${missing.length} requested ${subject} not found: ${ids}.`]}__name(missingIdWarnings,"missingIdWarnings");function addDefinedMetadata(body,metadata){for(let[key,value]of Object.entries(metadata))value!==void 0&&(body[key]=value);return body}__name(addDefinedMetadata,"addDefinedMetadata");async function entriesListCommand(typeName,options,cmd){let pagination=parsePaginationOptions(options,{defaultLimit:20,maxLimit:100,legacyCursor:"offset"}),{ctx}=await bootstrapProjectCommand(options,cmd),content2=createContentTransferService(loadConfig(),ctx.branch);await requireOperation("cms.list",{projectId:ctx.projectId,branch:ctx.branch});let params={};params.limit=String(pagination.limit),options.search&&(params.search=options.search),options.sort&&(params.sort=options.sort),!options.sort&&options.sortBy&&(params.sortBy=options.sortBy),!options.sort&&options.sortDirection&&(params.sortDirection=options.sortDirection),options.where&&(JSON.parse(options.where),params.where=options.where),options.fields&&(params.fields=options.fields),options.populate&&(params.populate=options.populate),options.locale&&(params.locale=options.locale);let 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});return toOffsetPaginationPage(await content2.listEntries(ctx.projectId,typeName,{...params,offset:String(offset)}))},"fetchPage")}),result={data:page.items,items:page.items,nextCursor:page.nextCursor,total:page.total,meta:{...page.meta,offset:initialOffset,hasMore:page.nextCursor!==null}},trailingArgs=paginationTrailingArgs(options,ctx.branch);ui.result({command:"entries list",data:result,render:__name(()=>renderPrettyJson5(result),"render"),...page.nextCursor?{hint:buildPaginationHint(["fimo","entries","list",typeName],{cursor:page.nextCursor,limit:pagination.limit,trailingArgs})}:{}})}__name(entriesListCommand,"entriesListCommand");function paginationTrailingArgs(options,branch){return[["--branch",branch],["--search",options.search],["--sort",options.sort],["--sort-by",options.sortBy],["--sort-direction",options.sortDirection],["--where",options.where],["--fields",options.fields],["--populate",options.populate],["--locale",options.locale],["--cwd",options.cwd]].flatMap(([flag2,value])=>value===void 0?[]:[flag2,value])}__name(paginationTrailingArgs,"paginationTrailingArgs");async function entriesGetCommand(typeName,id,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.get",{projectId:ctx.projectId,branch:ctx.branch});let{data:result}=await fimo.execute("entries.get",{projectId:ctx.projectId,branch:ctx.branch,typeName,id,locale:options.locale,populate:options.populate?[options.populate]:void 0});ui.result({command:"entries get",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesGetCommand,"entriesGetCommand");async function entriesCreateCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.create",{projectId:ctx.projectId,branch:ctx.branch});let input=addDefinedMetadata(parseJsonObject(options.body),{locale:options.locale,documentId:options.documentId}),{data:result}=await fimo.execute("entries.create",{projectId:ctx.projectId,branch:ctx.branch,typeName,...input});ui.result({command:"entries create",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesCreateCommand,"entriesCreateCommand");async function entriesUpdateCommand(typeName,id,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.update",{projectId:ctx.projectId,branch:ctx.branch});let data=parseJsonObject(options.body),result=await fimo.execute("entries.updateFields",{projectId:ctx.projectId,branch:ctx.branch,typeName,id,locale:options.locale,fields:data});ui.result({command:"entries update",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesUpdateCommand,"entriesUpdateCommand");async function entriesDeleteCommand(typeName,id,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.delete",{projectId:ctx.projectId,branch:ctx.branch});let{data:result}=await fimo.execute("entries.delete",{projectId:ctx.projectId,branch:ctx.branch,typeName,id,locale:options.locale});ui.result({command:"entries delete",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesDeleteCommand,"entriesDeleteCommand");async function entriesQueryCommand(options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.query",{projectId:ctx.projectId,branch:ctx.branch});let sql=await readContentInputSource({...options,body:options.sql},message=>new EntriesInputError(message),"--sql"),result=await fimo.execute("entries.querySql",{projectId:ctx.projectId,branch:ctx.branch,sql});ui.result({command:"entries query",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesQueryCommand,"entriesQueryCommand");async function entriesBulkCreateCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0}),content2=createContentTransferService(loadConfig(),ctx.branch);await requireOperation("cms.bulk_create",{projectId:ctx.projectId,branch:ctx.branch}),options.upsertBy&&(await requireOperation("cms.list",{projectId:ctx.projectId,branch:ctx.branch}),await requireOperation("cms.bulk_update",{projectId:ctx.projectId,branch:ctx.branch}));let entries2=parseJsonArray(await readContentInputSource(options,message=>new EntriesInputError(message))),chunkSize=parseChunkSize(options.chunkSize);if(entries2.length===0){if(options.upsertBy)throw new EntriesInputError("Upsert input must be a non-empty JSON array.");let result2=await fimo.execute("entries.bulkCreate",{projectId:ctx.projectId,branch:ctx.branch,typeName,entries:entries2});ui.result({command:"entries bulk-create",data:result2,render:__name(()=>renderPrettyJson5(result2),"render")});return}let upsertInputs=options.upsertBy?entries2.map((entry,index)=>parseEntryInput(entry,index)):[],identityCounts=new Map;if(options.upsertBy)for(let[index,input]of upsertInputs.entries()){let key=identityKey(identityValue(input,options.upsertBy,index),input.locale);identityCounts.set(key,(identityCounts.get(key)??0)+1)}let chunks=chunksOf(options.upsertBy?upsertInputs:entries2,chunkSize),receipts=[],data=[];for(let[index,chunk]of chunks.entries()){if(options.upsertBy){receipts.push(await upsertChunk(fimo,content2,ctx.projectId,ctx.branch,typeName,options.upsertBy,chunk,index+1,identityCounts));continue}let result2=await fimo.execute("entries.bulkCreate",{projectId:ctx.projectId,branch:ctx.branch,typeName,entries:chunk});data.push(...result2.data),receipts.push({chunk:index+1,input:chunk.length,created:result2.meta.created,updated:0,conflicts:0,reconciled:0})}let result={data,meta:{created:receipts.reduce((sum,receipt)=>sum+receipt.created,0),updated:receipts.reduce((sum,receipt)=>sum+receipt.updated,0),conflicts:receipts.reduce((sum,receipt)=>sum+receipt.conflicts,0),chunks:receipts}};ui.result({command:"entries bulk-create",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesBulkCreateCommand,"entriesBulkCreateCommand");async function entriesBulkUpdateCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.bulk_update",{projectId:ctx.projectId,branch:ctx.branch});let usesBatchInput=!!(options.file||options.stdin),selection,body;if(usesBatchInput){if(options.body!==void 0||options.ids||options.where)throw new EntriesInputError("Use --file or --stdin alone for per-entry updates.");selection={updates:parseJsonArray(await readContentInputSource(options,message=>new EntriesInputError(message)))}}else{if((options.ids?1:0)+(options.where?1:0)!=1||options.body===void 0)throw new EntriesInputError("Pass --body with exactly one of --ids or --where.");selection=options.ids?{ids:parseIds(options.ids)}:{where:parseBulkJsonObject(options.where)},body=parseBulkJsonObject(options.body)}let result=await fimo.execute("entries.bulkUpdate",{projectId:ctx.projectId,branch:ctx.branch,typeName,selection,body});ui.result({command:"entries bulk-update",data:result,warnings:missingIdWarnings(result,"updated"),render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesBulkUpdateCommand,"entriesBulkUpdateCommand");async function entriesBulkDeleteCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});if(await requireOperation("cms.bulk_delete",{projectId:ctx.projectId,branch:ctx.branch}),(options.ids?1:0)+(options.where?1:0)!=1)throw new EntriesInputError("Pass exactly one of --ids or --where.");let selection=options.ids?{ids:parseIds(options.ids)}:{where:parseBulkJsonObject(options.where)},result=await fimo.execute("entries.bulkDelete",{projectId:ctx.projectId,branch:ctx.branch,typeName,selection,locale:options.locale});ui.result({command:"entries bulk-delete",data:result,warnings:missingIdWarnings(result,"deleted"),render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesBulkDeleteCommand,"entriesBulkDeleteCommand");init_dist();init_config();init_sdk_transport();init_project2();function collect(value,previous){return[...previous??[],value]}__name(collect,"collect");function addScopeOptions(command){return command.option("--project <id>","Site id (defaults to the locally linked site)").option("-C, --cwd <dir>","Site directory")}__name(addScopeOptions,"addScopeOptions");function registerEnvironmentsCommands(program2){let environments=program2.command("environments").description("Group site Branches into deployment Environments").addHelpText("after",`
|
|
2504
|
+
`)},"render")})}__name(domainsOwnedCommand,"domainsOwnedCommand");init_dist();init_config();init_sdk_transport();init_project_context();init_project2();import fs28 from"node:fs";import path27 from"node:path";function selectedInputSources(options,inlineFlag){return[options.body!==void 0?inlineFlag:void 0,options.file?"--file":void 0,options.stdin?"--stdin":void 0].filter(source=>!!source)}__name(selectedInputSources,"selectedInputSources");async function readContentInputSource(options,createError,inlineFlag="--body"){if(selectedInputSources(options,inlineFlag).length!==1)throw createError(`Pass exactly one of ${inlineFlag}, --file, or --stdin.`);if(options.body!==void 0)return options.body;if(options.file){let filePath=path27.resolve(resolveProjectCwd(options.cwd),options.file);try{return fs28.readFileSync(filePath,"utf8")}catch(error){throw createError(error instanceof Error?error.message:`Could not read ${filePath}.`)}}if(process.stdin.isTTY)throw createError("Pipe input to the command when using --stdin.");let chunks=[];for await(let chunk of process.stdin)chunks.push(Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk));return Buffer.concat(chunks).toString("utf8")}__name(readContentInputSource,"readContentInputSource");function renderPrettyJson5(data){return JSON.stringify(data,null,2)}__name(renderPrettyJson5,"renderPrettyJson");var EntriesInputError=class extends Error{static{__name(this,"EntriesInputError")}constructor(message){super(message),this.name="EntriesInputError"}};function reportSingleContentTypeError(command,error){return!(error instanceof ApiRequestError)||error.code!=="single_content_type"?!1:(ui.error({command,code:"SINGLE_CONTENT_TYPE",message:"This content type is a Single. Use `fimo singles update` to create or update it."}),!0)}__name(reportSingleContentTypeError,"reportSingleContentTypeError");var DEFAULT_BULK_CHUNK_SIZE=100,MAX_BULK_CHUNK_SIZE=1e3;function parseJsonObject(value){let parsed=JSON.parse(value);if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw new Error("Expected a JSON object");return parsed}__name(parseJsonObject,"parseJsonObject");function parseJsonArray(value){let parsed;try{parsed=JSON.parse(value)}catch(error){throw new EntriesInputError(error instanceof Error?`Invalid JSON: ${error.message}`:"Invalid JSON.")}if(!Array.isArray(parsed))throw new EntriesInputError("Expected a JSON array.");return parsed}__name(parseJsonArray,"parseJsonArray");function parseChunkSize(value){if(value===void 0)return DEFAULT_BULK_CHUNK_SIZE;let size=Number(value);if(!Number.isInteger(size)||size<1||size>MAX_BULK_CHUNK_SIZE)throw new EntriesInputError(`--chunk-size must be an integer from 1 to ${MAX_BULK_CHUNK_SIZE}.`);return size}__name(parseChunkSize,"parseChunkSize");function chunksOf(items,size){let chunks=[];for(let offset=0;offset<items.length;offset+=size)chunks.push(items.slice(offset,offset+size));return chunks}__name(chunksOf,"chunksOf");function parseEntryInput(value,index){if(!value||typeof value!="object"||Array.isArray(value))throw new EntriesInputError(`Entry ${index+1} must be a JSON object.`);let input=value;if(!input.data||typeof input.data!="object"||Array.isArray(input.data))throw new EntriesInputError(`Entry ${index+1} must include a data object.`);return input}__name(parseEntryInput,"parseEntryInput");function identityValue(input,field,index){let value=field==="slug"?input.data.slug??input.data[field]:input.data[field];if(typeof value!="string"||value.length===0)throw new EntriesInputError(`Entry ${index+1} needs a non-empty data.${field} for --upsert-by ${field}.`);return value}__name(identityValue,"identityValue");function identityKey(value,locale){return`${locale??""}\0${value}`}__name(identityKey,"identityKey");async function listEntriesByIdentity(content2,projectId2,typeName,field,inputs){let byLocale=new Map;for(let[index,input]of inputs.entries()){let values=byLocale.get(input.locale)??new Set;values.add(identityValue(input,field,index)),byLocale.set(input.locale,values)}let found=new Map;for(let[locale,values]of byLocale){let result=await content2.listEntries(projectId2,typeName,{limit:"100",where:JSON.stringify({[field]:{$in:[...values]}}),fields:`id,documentId,${field},locale`,...locale?{locale}:{}});if(result.meta.hasMore)throw new EntriesInputError(`More than 100 ${typeName} entries matched this ${field} batch; reduce --chunk-size.`);for(let entry of result.data){let value=entry[field];if(typeof value!="string")continue;let key=identityKey(value,locale);found.set(key,[...found.get(key)??[],entry])}}return found}__name(listEntriesByIdentity,"listEntriesByIdentity");async function createWithReconciliation(fimo,content2,projectId2,branch,typeName,field,inputs){let pending=inputs,created=0,reconciled=0;for(let attempt=0;attempt<2&&pending.length>0;attempt+=1)try{let result=await fimo.execute("entries.bulkCreate",{projectId:projectId2,branch,typeName,entries:pending});created+=result.meta.created,pending=[]}catch(error){if(!(error instanceof ApiRequestError)||error.status!==504)throw error;let existing=await listEntriesByIdentity(content2,projectId2,typeName,field,pending),absent=pending.filter((input,index)=>{let key=identityKey(identityValue(input,field,index),input.locale);return(existing.get(key)?.length??0)===0});reconciled+=pending.length-absent.length,pending=absent}if(pending.length>0)throw new EntriesInputError(`${pending.length} entries remain absent after reconciling an ambiguous 504; rerun the same upsert input safely.`);return{created,reconciled}}__name(createWithReconciliation,"createWithReconciliation");async function upsertChunk(fimo,content2,projectId2,branch,typeName,field,inputs,chunk,identityCounts){let existing=await listEntriesByIdentity(content2,projectId2,typeName,field,inputs),creates=[],updates=[],conflicts=0;for(let[index,input]of inputs.entries()){let key=identityKey(identityValue(input,field,index),input.locale),matches=existing.get(key)??[];if((identityCounts.get(key)??0)>1||matches.length>1){conflicts+=1;continue}matches.length===1?updates.push({id:matches[0].documentId,body:input}):creates.push(input)}let updated=0;if(updates.length>0)try{let result=await fimo.execute("entries.bulkUpdate",{projectId:projectId2,branch,typeName,selection:{updates}});updated=result.meta.updated,conflicts+=result.meta.missing.length}catch(error){throw!(error instanceof ApiRequestError)||error.status!==504?error:(await listEntriesByIdentity(content2,projectId2,typeName,field,inputs),new EntriesInputError(`${updates.length} updates had an ambiguous 504; identities were reread without replay. Rerun the same upsert input safely.`))}let createResult=await createWithReconciliation(fimo,content2,projectId2,branch,typeName,field,creates);return{chunk,input:inputs.length,created:createResult.created,updated,conflicts,reconciled:createResult.reconciled}}__name(upsertChunk,"upsertChunk");function parseBulkJsonObject(value){try{return parseJsonObject(value)}catch(error){throw new EntriesInputError(error instanceof Error?error.message:"Expected a JSON object.")}}__name(parseBulkJsonObject,"parseBulkJsonObject");function parseIds(value){let ids=[...new Set(value.split(",").map(id=>id.trim()).filter(Boolean))];if(ids.length===0)throw new EntriesInputError("--ids must include at least one ID.");return ids}__name(parseIds,"parseIds");function missingIdWarnings(result,action){let{missing}=result.meta;if(missing.length===0)return[];let changed=action==="updated"?result.meta.updated:result.meta.deleted,ids=missing.join(", ");if(changed===0)return missing.length===1?[`No entries were ${action}; the requested ID was not found: ${ids}.`]:[`No entries were ${action}; all ${missing.length} requested IDs were not found: ${ids}.`];let subject=missing.length===1?"ID was":"IDs were";return[`${missing.length} requested ${subject} not found: ${ids}.`]}__name(missingIdWarnings,"missingIdWarnings");function addDefinedMetadata(body,metadata){for(let[key,value]of Object.entries(metadata))value!==void 0&&(body[key]=value);return body}__name(addDefinedMetadata,"addDefinedMetadata");async function entriesListCommand(typeName,options,cmd){let pagination=parsePaginationOptions(options,{defaultLimit:20,maxLimit:100,legacyCursor:"offset"}),{ctx}=await bootstrapProjectCommand(options,cmd),content2=createContentTransferService(loadConfig(),ctx.branch);await requireOperation("cms.list",{projectId:ctx.projectId,branch:ctx.branch});let params={};params.limit=String(pagination.limit),options.search&&(params.search=options.search),options.sort&&(params.sort=options.sort),!options.sort&&options.sortBy&&(params.sortBy=options.sortBy),!options.sort&&options.sortDirection&&(params.sortDirection=options.sortDirection),options.where&&(JSON.parse(options.where),params.where=options.where),options.fields&&(params.fields=options.fields),options.populate&&(params.populate=options.populate),options.locale&&(params.locale=options.locale);let 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});return toOffsetPaginationPage(await content2.listEntries(ctx.projectId,typeName,{...params,offset:String(offset)}))},"fetchPage")}),result={data:page.items,items:page.items,nextCursor:page.nextCursor,total:page.total,meta:{...page.meta,offset:initialOffset,hasMore:page.nextCursor!==null}},trailingArgs=paginationTrailingArgs(options,ctx.branch);ui.result({command:"entries list",data:result,render:__name(()=>renderPrettyJson5(result),"render"),...page.nextCursor?{hint:buildPaginationHint(["fimo","entries","list",typeName],{cursor:page.nextCursor,limit:pagination.limit,trailingArgs})}:{}})}__name(entriesListCommand,"entriesListCommand");function paginationTrailingArgs(options,branch){return[["--branch",branch],["--search",options.search],["--sort",options.sort],["--sort-by",options.sortBy],["--sort-direction",options.sortDirection],["--where",options.where],["--fields",options.fields],["--populate",options.populate],["--locale",options.locale],["--cwd",options.cwd]].flatMap(([flag2,value])=>value===void 0?[]:[flag2,value])}__name(paginationTrailingArgs,"paginationTrailingArgs");async function entriesGetCommand(typeName,id,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.get",{projectId:ctx.projectId,branch:ctx.branch});let{data:result}=await fimo.execute("entries.get",{projectId:ctx.projectId,branch:ctx.branch,typeName,id,locale:options.locale,populate:options.populate?[options.populate]:void 0});ui.result({command:"entries get",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesGetCommand,"entriesGetCommand");async function entriesCreateCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.create",{projectId:ctx.projectId,branch:ctx.branch});let input=addDefinedMetadata(parseJsonObject(options.body),{locale:options.locale,documentId:options.documentId}),{data:result}=await fimo.execute("entries.create",{projectId:ctx.projectId,branch:ctx.branch,typeName,...input});ui.result({command:"entries create",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesCreateCommand,"entriesCreateCommand");async function entriesUpdateCommand(typeName,id,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.update",{projectId:ctx.projectId,branch:ctx.branch});let data=parseJsonObject(options.body),result=await fimo.execute("entries.updateFields",{projectId:ctx.projectId,branch:ctx.branch,typeName,id,locale:options.locale,fields:data});ui.result({command:"entries update",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesUpdateCommand,"entriesUpdateCommand");async function entriesDeleteCommand(typeName,id,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.delete",{projectId:ctx.projectId,branch:ctx.branch});let{data:result}=await fimo.execute("entries.delete",{projectId:ctx.projectId,branch:ctx.branch,typeName,id,locale:options.locale});ui.result({command:"entries delete",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesDeleteCommand,"entriesDeleteCommand");async function entriesQueryCommand(options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("cms.query",{projectId:ctx.projectId,branch:ctx.branch});let sql=await readContentInputSource({...options,body:options.sql},message=>new EntriesInputError(message),"--sql"),result=await fimo.execute("entries.querySql",{projectId:ctx.projectId,branch:ctx.branch,sql});ui.result({command:"entries query",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesQueryCommand,"entriesQueryCommand");async function entriesBulkCreateCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0}),content2=createContentTransferService(loadConfig(),ctx.branch);await requireOperation("cms.bulk_create",{projectId:ctx.projectId,branch:ctx.branch}),options.upsertBy&&(await requireOperation("cms.list",{projectId:ctx.projectId,branch:ctx.branch}),await requireOperation("cms.bulk_update",{projectId:ctx.projectId,branch:ctx.branch}));let entries2=parseJsonArray(await readContentInputSource(options,message=>new EntriesInputError(message))),chunkSize=parseChunkSize(options.chunkSize);if(entries2.length===0){if(options.upsertBy)throw new EntriesInputError("Upsert input must be a non-empty JSON array.");let result2=await fimo.execute("entries.bulkCreate",{projectId:ctx.projectId,branch:ctx.branch,typeName,entries:entries2});ui.result({command:"entries bulk-create",data:result2,render:__name(()=>renderPrettyJson5(result2),"render")});return}let upsertInputs=options.upsertBy?entries2.map((entry,index)=>parseEntryInput(entry,index)):[],identityCounts=new Map;if(options.upsertBy)for(let[index,input]of upsertInputs.entries()){let key=identityKey(identityValue(input,options.upsertBy,index),input.locale);identityCounts.set(key,(identityCounts.get(key)??0)+1)}let chunks=chunksOf(options.upsertBy?upsertInputs:entries2,chunkSize),receipts=[],data=[];for(let[index,chunk]of chunks.entries()){if(options.upsertBy){receipts.push(await upsertChunk(fimo,content2,ctx.projectId,ctx.branch,typeName,options.upsertBy,chunk,index+1,identityCounts));continue}let result2=await fimo.execute("entries.bulkCreate",{projectId:ctx.projectId,branch:ctx.branch,typeName,entries:chunk});data.push(...result2.data),receipts.push({chunk:index+1,input:chunk.length,created:result2.meta.created,updated:0,conflicts:0,reconciled:0})}let result={data,meta:{created:receipts.reduce((sum,receipt)=>sum+receipt.created,0),updated:receipts.reduce((sum,receipt)=>sum+receipt.updated,0),conflicts:receipts.reduce((sum,receipt)=>sum+receipt.conflicts,0),chunks:receipts}};ui.result({command:"entries bulk-create",data:result,render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesBulkCreateCommand,"entriesBulkCreateCommand");function withBulkLocale(body,locale,source){if(locale===void 0||!body||typeof body!="object"||Array.isArray(body))return body;let bodyLocale=body.locale;if(bodyLocale!==void 0&&bodyLocale!==locale)throw new EntriesInputError(`--locale ${locale} disagrees with "locale": ${JSON.stringify(bodyLocale)} in ${source}. Pass the locale once.`);return{...body,locale}}__name(withBulkLocale,"withBulkLocale");async function entriesBulkUpdateCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("cms.bulk_update",{projectId:ctx.projectId,branch:ctx.branch});let usesBatchInput=!!(options.file||options.stdin),selection,body;if(usesBatchInput){if(options.body!==void 0||options.ids||options.where)throw new EntriesInputError("Use --file or --stdin alone for per-entry updates.");selection={updates:parseJsonArray(await readContentInputSource(options,message=>new EntriesInputError(message))).map((update,index)=>update&&typeof update=="object"&&!Array.isArray(update)?{...update,body:withBulkLocale(update.body,options.locale,`update ${index+1}`)}:update)}}else{if((options.ids?1:0)+(options.where?1:0)!=1||options.body===void 0)throw new EntriesInputError("Pass --body with exactly one of --ids or --where.");selection=options.ids?{ids:parseIds(options.ids)}:{where:parseBulkJsonObject(options.where)},body=withBulkLocale(parseBulkJsonObject(options.body),options.locale,"--body")}let result=await fimo.execute("entries.bulkUpdate",{projectId:ctx.projectId,branch:ctx.branch,typeName,selection,body});ui.result({command:"entries bulk-update",data:result,warnings:missingIdWarnings(result,"updated"),render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesBulkUpdateCommand,"entriesBulkUpdateCommand");async function entriesBulkDeleteCommand(typeName,options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});if(await requireOperation("cms.bulk_delete",{projectId:ctx.projectId,branch:ctx.branch}),(options.ids?1:0)+(options.where?1:0)!=1)throw new EntriesInputError("Pass exactly one of --ids or --where.");let selection=options.ids?{ids:parseIds(options.ids)}:{where:parseBulkJsonObject(options.where)},result=await fimo.execute("entries.bulkDelete",{projectId:ctx.projectId,branch:ctx.branch,typeName,selection,locale:options.locale});ui.result({command:"entries bulk-delete",data:result,warnings:missingIdWarnings(result,"deleted"),render:__name(()=>renderPrettyJson5(result),"render")})}__name(entriesBulkDeleteCommand,"entriesBulkDeleteCommand");init_dist();init_config();init_sdk_transport();init_project2();function collect(value,previous){return[...previous??[],value]}__name(collect,"collect");function addScopeOptions(command){return command.option("--project <id>","Site id (defaults to the locally linked site)").option("-C, --cwd <dir>","Site directory")}__name(addScopeOptions,"addScopeOptions");function registerEnvironmentsCommands(program2){let environments=program2.command("environments").description("Group site Branches into deployment Environments").addHelpText("after",`
|
|
2505
2505
|
Environments group Branches. Production is the deployed snapshot published from the configured Production source.
|
|
2506
2506
|
Automatic previews receives every unclaimed Branch.
|
|
2507
2507
|
|
|
@@ -2670,11 +2670,11 @@ Aborted. Deleting site ${projectName}\u2026
|
|
|
2670
2670
|
`)}__name(renderSkillsInstall,"renderSkillsInstall");async function skillsInstallCommand(options={}){let outcome=await runSkillsInstall(options);switch(outcome.status){case"error":ui.error({command:"skills install",code:outcome.code,message:outcome.message,hint:outcome.hint});return;case"cancelled":ui.info({command:"skills install",message:"Cancelled."});return;case"ok":ui.result({command:"skills install",data:outcome.data,render:__name(()=>renderSkillsInstall(outcome.data),"render")});return}}__name(skillsInstallCommand,"skillsInstallCommand");async function skillsSyncCommand(options={}){if(!fs33.existsSync(BOOTSTRAP_SKILL_SOURCE)){ui.error({command:"skills sync",code:"BUNDLED_SKILL_MISSING",message:`Bundled skill "${BOOTSTRAP_SKILL_NAME}" not found in this fimo install.`,hint:"Try reinstalling fimo, or report this as a bug."});return}let explicit;try{explicit=parseAgentsFlag(options)}catch(err){ui.error({command:"skills sync",code:"AGENT_FLAG_PARSE_FAILED",message:err instanceof Error?err.message:String(err)});return}if(explicit==="none"){ui.error({command:"skills sync",code:"INVALID_AGENTS_NONE",message:"`--agents=none` is not valid for sync."});return}let agents=explicit??await detectAgentsWithFimoSkills();if(agents.length===0){ui.result({command:"skills sync",data:{ok:!0,agents:[],failures:[],removedStale:[]},render:__name(()=>"No agents have Fimo skills installed. Run `fimo skills install` first.","render")});return}let failures=(await installSkillsFromSource({source:BOOTSTRAP_SKILL_SOURCE,agents,global:!0,mode:"symlink"})).failed.map(f=>({agent:f.agent,error:f.error})),removedStale=cleanupStaleGlobalSkills(agents);ui.result({command:"skills sync",data:{ok:failures.length===0,agents,failures,removedStale},render:__name(()=>{let lines=[`Re-ensured the ${BOOTSTRAP_SKILL_NAME} skill for: ${agents.join(", ")}`];if(removedStale.length>0){let names=[...new Set(removedStale.map(r=>r.skill))].join(", ");lines.push(`Cleaned up stale global skills: ${names}`)}for(let f of failures)lines.push(` ! failed for ${f.agent}: ${f.error}`);return lines.join(`
|
|
2671
2671
|
`)},"render")})}__name(skillsSyncCommand,"skillsSyncCommand");async function detectAgentsWithFimoSkills(){let allAgents=getSkillAgentTypes().filter(id=>id!=="universal"),result=[];for(let agent2 of allAgents){let baseDir;try{baseDir=getSkillAgentDir(agent2,{global:!0})}catch{continue}for(let skill of DETECTABLE_FIMO_SKILL_NAMES)if(fs33.existsSync(path33.join(baseDir,skill))){result.push(agent2);break}}return result}__name(detectAgentsWithFimoSkills,"detectAgentsWithFimoSkills");function removeDirIfExists(targetPath){return!fs33.existsSync(targetPath)&&!fs33.lstatSync(targetPath,{throwIfNoEntry:!1})?!1:(fs33.rmSync(targetPath,{recursive:!0,force:!0}),!0)}__name(removeDirIfExists,"removeDirIfExists");function removeGlobalSkillDirs(skillNames,agents){let removed=[];for(let agent2 of agents){let baseDir;try{baseDir=getSkillAgentDir(agent2,{global:!0})}catch{continue}for(let skill of skillNames){let skillDir=path33.join(baseDir,skill);removeDirIfExists(skillDir)&&removed.push({skill,agent:agent2,path:skillDir})}}return removed}__name(removeGlobalSkillDirs,"removeGlobalSkillDirs");function hasGlobalSkillInstalled(skillNames){for(let agent2 of getSkillAgentTypes().filter(id=>id!=="universal")){let baseDir;try{baseDir=getSkillAgentDir(agent2,{global:!0})}catch{continue}for(let skill of skillNames)if(fs33.existsSync(path33.join(baseDir,skill)))return!0}return!1}__name(hasGlobalSkillInstalled,"hasGlobalSkillInstalled");function removeCanonicalSkillDirs(skillNames){let removed=[],canonicalDir=getCanonicalSkillsDir(!0);for(let skill of skillNames){let canonicalSkill=path33.join(canonicalDir,skill);removeDirIfExists(canonicalSkill)&&removed.push({skill,agent:"canonical",path:canonicalSkill})}return removed}__name(removeCanonicalSkillDirs,"removeCanonicalSkillDirs");function cleanupStaleGlobalSkills(agents){let removed=removeGlobalSkillDirs(STALE_GLOBAL_SKILL_NAMES,agents);return hasGlobalSkillInstalled(STALE_GLOBAL_SKILL_NAMES)||removed.push(...removeCanonicalSkillDirs(STALE_GLOBAL_SKILL_NAMES)),removed}__name(cleanupStaleGlobalSkills,"cleanupStaleGlobalSkills");async function skillsUninstallCommand(options={}){let targetAgents,explicit;try{explicit=parseAgentsFlag(options)}catch(err){ui.error({command:"skills uninstall",code:"AGENT_FLAG_PARSE_FAILED",message:err instanceof Error?err.message:String(err)});return}if(explicit==="none"){ui.error({command:"skills uninstall",code:"INVALID_AGENTS_NONE",message:"`--agents=none` is not valid for uninstall."});return}if(targetAgents=explicit??await detectAgentsWithFimoSkills(),targetAgents.length===0){ui.result({command:"skills uninstall",data:{ok:!0,uninstalled:[]},render:__name(()=>"No Fimo skills are installed for any agent.","render")});return}if(isPrettyMode()&&!!process.stdout.isTTY){mt("Uninstall Fimo skills (global)");let confirmed=await ot2({message:`Remove the Fimo skill from ${targetAgents.join(", ")}?`,initialValue:!0});if(q(confirmed)||!confirmed){ui.info({command:"skills uninstall",message:"Cancelled."});return}}let removed=removeGlobalSkillDirs(DETECTABLE_FIMO_SKILL_NAMES,targetAgents);(await detectAgentsWithFimoSkills()).length===0&&removed.push(...removeCanonicalSkillDirs(DETECTABLE_FIMO_SKILL_NAMES)),ui.result({command:"skills uninstall",data:{ok:!0,uninstalled:removed},render:__name(()=>removed.length===0?"No Fimo skills were installed for the selected agents.":`Uninstalled:
|
|
2672
2672
|
${removed.map(r=>` ${r.skill} \u2192 ${r.agent}`).join(`
|
|
2673
|
-
`)}`,"render")})}__name(skillsUninstallCommand,"skillsUninstallCommand");function listReferenceDocs(skillDir){let refsDir=path33.join(skillDir,"references");if(!fs33.existsSync(refsDir))return[];let out=[],walk=__name((cur,prefix)=>{for(let entry of fs33.readdirSync(cur,{withFileTypes:!0})){let rel=prefix?`${prefix}/${entry.name}`:entry.name;entry.isDirectory()?walk(path33.join(cur,entry.name),rel):entry.isFile()&&entry.name.endsWith(".md")&&out.push(rel.slice(0,-3))}},"walk");return walk(refsDir,""),out.sort()}__name(listReferenceDocs,"listReferenceDocs");function discoverBundledSkills(skillsRoot=SKILLS_ROOT){if(!fs33.existsSync(skillsRoot))return[];let skills2=[];for(let entry of fs33.readdirSync(skillsRoot,{withFileTypes:!0})){if(!entry.isDirectory()||entry.name===BOOTSTRAP_SKILL_NAME)continue;let dir=path33.join(skillsRoot,entry.name),skillMd=path33.join(dir,"SKILL.md");if(!fs33.existsSync(skillMd))continue;let{data}=parseFrontmatter(fs33.readFileSync(
|
|
2673
|
+
`)}`,"render")})}__name(skillsUninstallCommand,"skillsUninstallCommand");function listReferenceDocs(skillDir){let refsDir=path33.join(skillDir,"references");if(!fs33.existsSync(refsDir))return[];let out=[],walk=__name((cur,prefix)=>{for(let entry of fs33.readdirSync(cur,{withFileTypes:!0})){let rel=prefix?`${prefix}/${entry.name}`:entry.name;entry.isDirectory()?walk(path33.join(cur,entry.name),rel):entry.isFile()&&entry.name.endsWith(".md")&&out.push(rel.slice(0,-3))}},"walk");return walk(refsDir,""),out.sort()}__name(listReferenceDocs,"listReferenceDocs");function mainDocument(skillDir){let surface=process.env.FIMO_SKILLS_SURFACE;if(surface&&/^[a-z]+$/.test(surface)){let variant=path33.join(skillDir,`SKILL.${surface}.md`);if(fs33.existsSync(variant))return variant}return path33.join(skillDir,"SKILL.md")}__name(mainDocument,"mainDocument");function discoverBundledSkills(skillsRoot=SKILLS_ROOT){if(!fs33.existsSync(skillsRoot))return[];let skills2=[];for(let entry of fs33.readdirSync(skillsRoot,{withFileTypes:!0})){if(!entry.isDirectory()||entry.name===BOOTSTRAP_SKILL_NAME)continue;let dir=path33.join(skillsRoot,entry.name),skillMd=path33.join(dir,"SKILL.md");if(!fs33.existsSync(skillMd))continue;let{data}=parseFrontmatter(fs33.readFileSync(mainDocument(dir),"utf8")),description=typeof data.description=="string"?data.description.trim():"";skills2.push({name:entry.name,description,refs:listReferenceDocs(dir),dir})}return skills2.sort((a,b)=>a.name.localeCompare(b.name))}__name(discoverBundledSkills,"discoverBundledSkills");function firstLine(text){let line=text.split(`
|
|
2674
2674
|
`,1)[0]?.trim()??"";return line.length>80?`${line.slice(0,79)}\u2026`:line}__name(firstLine,"firstLine");function skillsListCommand(){let skills2=discoverBundledSkills();if(skills2.length===0){ui.error({command:"skills list",code:"BUNDLED_SKILL_MISSING",message:`No bundled skills found at ${SKILLS_ROOT}.`,hint:"Try reinstalling fimo, or report this as a bug."});return}ui.result({command:"skills list",data:{skills:skills2.map(s=>({name:s.name,description:s.description,refs:s.refs}))},render:__name(()=>{let nameWidth=Math.max(4,...skills2.map(s=>s.name.length)),header=`${"NAME".padEnd(nameWidth)} REFS DESCRIPTION`,lines=skills2.map(s=>{let refs=String(s.refs.length).padStart(4);return`${s.name.padEnd(nameWidth)} ${refs} ${firstLine(s.description)}`});return[header,...lines].join(`
|
|
2675
2675
|
`)},"render"),hint:"Run `fimo skills get <name>` for a skill, or add `--ref <doc>` for a reference."})}__name(skillsListCommand,"skillsListCommand");function runningCliSource(){let version=getCliVersion();return{status:"ok",data:{root:SKILLS_ROOT,source:"running-cli",version,cliVersion:version}}}__name(runningCliSource,"runningCliSource");function resolveSkillsGetSource(name,cwd){if(name!=="fimo-code")return runningCliSource();let projectRoot=findProjectRoot2(cwd);if(!projectRoot)return runningCliSource();let packageJsonPath=resolveProjectFimoPackageJson(projectRoot);if(!packageJsonPath)return{status:"error",code:"PROJECT_RUNTIME_NOT_INSTALLED",message:"The project-local fimo package is not installed, so version-matched code guidance is unavailable.",hint:"Install the project dependencies, then run `fimo skills get fimo-code` again."};let version="unknown";try{let pkg=JSON.parse(fs33.readFileSync(packageJsonPath,"utf8"));typeof pkg.version=="string"&&(version=pkg.version)}catch{}let root=path33.join(path33.dirname(packageJsonPath),"assets","skills");return fs33.existsSync(path33.join(root,"fimo-code","SKILL.md"))?{status:"ok",data:{root,source:"project-runtime",version,cliVersion:getCliVersion()}}:{status:"error",code:"PROJECT_SKILL_UNAVAILABLE",message:`Project runtime fimo@${version} does not include version-matched fimo-code guidance.`,hint:"Upgrade the project runtime, then run `fimo skills get fimo-code` again."}}__name(resolveSkillsGetSource,"resolveSkillsGetSource");function formatSkillStamp(skillName,refId,source,ctx){let separator=ctx.ascii?" | ":" \xB7 ",subject=refId?`${skillName} (references/${refId})`:skillName,origin=source.source==="project-runtime"?[`project runtime fimo@${source.version}`,`CLI fimo@${source.cliVersion}`]:[`running CLI fimo@${source.version}`];return[subject,...origin].join(separator)}__name(formatSkillStamp,"formatSkillStamp");function stampedSkillBody(stamp,content2,ctx){let rule=(ctx.ascii?"-":"\u2500").repeat(stamp.length);return`${stamp}
|
|
2676
2676
|
${rule}
|
|
2677
|
-
${content2}`}__name(stampedSkillBody,"stampedSkillBody");function resolveProjectFimoPackageJson(projectRoot){let requireFromProject=createRequire4(path33.join(projectRoot,"package.json")),ancestorNodeModules=new Set,directory=projectRoot;for(;;){ancestorNodeModules.add(path33.join(directory,"node_modules"));let parent=path33.dirname(directory);if(parent===directory)break;directory=parent}for(let searchRoot of requireFromProject.resolve.paths("fimo")??[]){if(!ancestorNodeModules.has(path33.normalize(searchRoot)))continue;let packageJsonPath=path33.join(searchRoot,"fimo","package.json");if(fs33.existsSync(packageJsonPath))return packageJsonPath}}__name(resolveProjectFimoPackageJson,"resolveProjectFimoPackageJson");function normalizeRef(ref){return ref.trim().replace(/\\/g,"/").replace(/^references\//,"").replace(/\.md$/,"")}__name(normalizeRef,"normalizeRef");function skillsGetCommand(name,options={}){let source=resolveSkillsGetSource(name,path33.resolve(options.cwd??process.cwd()));if(source.status==="error"){ui.error({command:"skills get",code:source.code,message:source.message,hint:source.hint});return}let skills2=discoverBundledSkills(source.data.root),skill=skills2.find(s=>s.name===name);if(!skill){ui.error({command:"skills get",code:"SKILL_NOT_FOUND",message:`Unknown skill "${name}".`,hint:skills2.length?`Available: ${skills2.map(s=>s.name).join(", ")}. Run \`fimo skills list\`.`:"No bundled skills found \u2014 try reinstalling fimo."});return}let targetPath,refId=null;if(options.ref){refId=normalizeRef(options.ref);let refsRoot=path33.resolve(skill.dir,"references"),candidate=path33.resolve(refsRoot,`${refId}.md`);if(!(candidate===refsRoot||candidate.startsWith(refsRoot+path33.sep))||!fs33.existsSync(candidate)){ui.error({command:"skills get",code:"SKILL_REF_NOT_FOUND",message:`Reference "${options.ref}" not found in skill "${skill.name}".`,hint:skill.refs.length?`Available refs: ${skill.refs.join(", ")}.`:"This skill has no reference docs."});return}targetPath=candidate}else targetPath=
|
|
2677
|
+
${content2}`}__name(stampedSkillBody,"stampedSkillBody");function resolveProjectFimoPackageJson(projectRoot){let requireFromProject=createRequire4(path33.join(projectRoot,"package.json")),ancestorNodeModules=new Set,directory=projectRoot;for(;;){ancestorNodeModules.add(path33.join(directory,"node_modules"));let parent=path33.dirname(directory);if(parent===directory)break;directory=parent}for(let searchRoot of requireFromProject.resolve.paths("fimo")??[]){if(!ancestorNodeModules.has(path33.normalize(searchRoot)))continue;let packageJsonPath=path33.join(searchRoot,"fimo","package.json");if(fs33.existsSync(packageJsonPath))return packageJsonPath}}__name(resolveProjectFimoPackageJson,"resolveProjectFimoPackageJson");function normalizeRef(ref){return ref.trim().replace(/\\/g,"/").replace(/^references\//,"").replace(/\.md$/,"")}__name(normalizeRef,"normalizeRef");function skillsGetCommand(name,options={}){let source=resolveSkillsGetSource(name,path33.resolve(options.cwd??process.cwd()));if(source.status==="error"){ui.error({command:"skills get",code:source.code,message:source.message,hint:source.hint});return}let skills2=discoverBundledSkills(source.data.root),skill=skills2.find(s=>s.name===name);if(!skill){ui.error({command:"skills get",code:"SKILL_NOT_FOUND",message:`Unknown skill "${name}".`,hint:skills2.length?`Available: ${skills2.map(s=>s.name).join(", ")}. Run \`fimo skills list\`.`:"No bundled skills found \u2014 try reinstalling fimo."});return}let targetPath,refId=null;if(options.ref){refId=normalizeRef(options.ref);let refsRoot=path33.resolve(skill.dir,"references"),candidate=path33.resolve(refsRoot,`${refId}.md`);if(!(candidate===refsRoot||candidate.startsWith(refsRoot+path33.sep))||!fs33.existsSync(candidate)){ui.error({command:"skills get",code:"SKILL_REF_NOT_FOUND",message:`Reference "${options.ref}" not found in skill "${skill.name}".`,hint:skill.refs.length?`Available refs: ${skill.refs.join(", ")}.`:"This skill has no reference docs."});return}targetPath=candidate}else targetPath=mainDocument(skill.dir);let content2=fs33.readFileSync(targetPath,"utf8");ui.result({command:"skills get",data:{skill:skill.name,ref:refId,path:targetPath,content:content2,source:source.data.source,version:source.data.version,cliVersion:source.data.cliVersion},render:__name(ctx=>stampedSkillBody(formatSkillStamp(skill.name,refId,source.data,ctx),content2,ctx),"render"),hint:STREAMED_REFERENCE_HINT})}__name(skillsGetCommand,"skillsGetCommand");var 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 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&&!isPackageManager(initOptions.packageManager.toLowerCase()))return{status:"error",code:"PACKAGE_MANAGER_INVALID",message:`Unknown package manager "${initOptions.packageManager}".`,hint:`Use one of: ${PACKAGE_MANAGERS.join(", ")}.`};let authAbort=await ensureSignedIn(cfg,initOptions);if(authAbort)return authAbort;let fimo=createCliFimoClient(cfg),creds=readCredentials(cfg),mode2=await resolveUseExisting(initOptions);if(mode2==="cancelled")return{status:"cancelled"};let useExisting=mode2==="existing",planned=await planInit({fimo,creds,useExisting,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}):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,initialCommit={pushedInitial:!0};ran.run.scaffolded&&await configureGeneratedPackageManager(plan.options.templatePackageManager??"pnpm",checkout.targetDir);let depResult=await maybeInstallDependencies(checkout.targetDir,plan.packageManager);try{initialCommit=await ran.run.finalize(checkout.targetDir)}finally{ran.run.releaseAbort()}let{pushedInitial}=initialCommit,skills2=await maybeInstallSkills(plan.options),warnings=[];return pushedInitial||warnings.push(`Initial commit was not pushed (${initialCommit.error}) \u2014 the site's remote is empty. Sign in (\`fimo login\`), then run \`${FINISH_FIRST_PUSH_COMMAND}\` from the site directory to push it.`),depResult.error&&warnings.push(`Dependency install failed: ${depResult.error}`),plan.skillsWarning&&warnings.push(plan.skillsWarning),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},renderArgs:{projectName:checkout.projectName,relativeDir:checkout.relativeTarget,isNew:!useExisting,installedDeps:depResult.installed,packageManager:depResult.packageManager,pushedInitial},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"],["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.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(`
|
|
2678
2678
|
`)}__name(renderInitSuccess,"renderInitSuccess");function renderInitPushFailed(p2,ascii,args){let warn=ascii?"[!]":"\u26A0\uFE0F",steps=[["npx fimo login","to sign in (if you are not already)"],[`npx ${FINISH_FIRST_PUSH_COMMAND}`,"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 lines.join(`
|
|
2679
2679
|
`)}__name(renderInitPushFailed,"renderInitPushFailed");async function ensureSignedIn(cfg,options){if(readCredentials(cfg)?.access_token)return null;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`. Without an account, or in a shell that cannot open a browser, run `fimo new <dir>` instead: it creates a site a person claims later (`fimo new --instructions` prints the guide)."};isPretty()&&O2.step("You are not signed in yet \u2014 opening your browser to sign in.");try{return await performBrowserLogin(cfg),null}catch(error){if(error instanceof LoginError)return{status:"error",code:error.code,message:error.message,...error.hint?{hint:error.hint}:{}};throw error}}__name(ensureSignedIn,"ensureSignedIn");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,dirArg,options}=args,projectId2,targetDir,displayName,skillsWarning,derived={...options},applySkillAgents=__name(resolved=>{if("skipped"in resolved){derived.skills=!1,derived.agents="none",skillsWarning=resolved.skipped;return}derived.skills=!0,derived.agents=resolved.agents},"applySkillAgents");if(useExisting)if(options.projectId)projectId2=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;projectId2=picked.projectId}else{let resolved=await resolveTargetDir(dirArg,nonInteractive(options));if("status"in resolved)return resolved;if(targetDir=resolved.targetDir,displayName=resolved.displayName,isNonEmptyDirectory(targetDir)){let name=path34.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.`}}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===!0&&applySkillAgents(await resolveSkillAgents(options));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}wantSkills?applySkillAgents(await resolveSkillAgents(options)):(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:projectId2,targetDir,displayName,packageManager,options:derived,skillsWarning}}}__name(planInit,"planInit");async function resolveSkillAgents(options){try{let agents=await selectAgents(options,{promptMessage:"Which agents do you want to set up?",detectFn:detectAgentsWithFimoSkills});return{agents:agents.length>0?agents.join(","):"none"}}catch(err){return{skipped:`Fimo skills were not set up: ${err instanceof Error?err.message:String(err)} Run \`fimo skills install --agents=<id>\` to set them up later.`}}}__name(resolveSkillAgents,"resolveSkillAgents");async function runExisting(args){let{fimo,cfg,projectId:projectId2,dirArg,options}=args;try{let result=await cloneProject({fimo,cfg,projectId:projectId2,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,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,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,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 resolveTargetDir(dirArg,noPrompt2){if(dirArg)return{targetDir:path34.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:path34.resolve(folder),displayName}}__name(resolveTargetDir,"resolveTargetDir");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){if(options.skills===!1)return{setUp:!1,error:null};if(options.skills!==!0&&nonInteractive(options))return{setUp:!1,error:null};let outcome=await runSkillsInstall({agents:options.agents,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 fs34 from"node:fs";import path35 from"node:path";init_dist();init_auth();init_config();init_sdk_transport();init_project2();init_dist();init_config();init_sdk_transport();init_project_context();init_project2();init_dist();init_config();init_dist();function markDeprecated(group,replacements,exempt=()=>!1){group.description(`${group.description()} (deprecated: use \`fimo integrations\`)`),group.hook("preAction",(_group,action)=>{if(exempt(action.args))return;let name=action.parent&&action.parent!==group?`${action.parent.name()} ${action.name()}`:action.name(),replacement=replacements[name]??"fimo integrations";ui.warn({command:`${group.name()} ${name}`,message:`\`fimo ${group.name()} ${name}\` is deprecated and will be removed. Use \`${replacement}\` instead.`})})}__name(markDeprecated,"markDeprecated");init_project2();var MCP_HEADER_NAME=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;function registerMcpCommands(program2){let mcp=program2.command("mcp").description("Manage remote MCP servers for this site").addHelpText("after",`
|
|
2680
2680
|
Examples:
|
|
@@ -2736,15 +2736,15 @@ Run \`fimo integrations <command> --help\` for command-specific help.
|
|
|
2736
2736
|
`),{written:relative3,warning:null})}__name(recordRuntimeFramework,"recordRuntimeFramework");function missingBuildHooks(targetDir,framework){let warnings=[];for(let hook of BUILD_HOOKS[framework]){let file=hook.files.find(candidate=>fs37.existsSync(path38.join(targetDir,candidate)));if(!file){warnings.push(`This application has no ${hook.files[0]} \u2014 ${hook.instruction} when you add one.`);continue}let source=fs37.readFileSync(path38.join(targetDir,file),"utf-8");hook.specifiers.some(specifier=>source.includes(specifier))||warnings.push(`${file} does not use \`${hook.specifiers[0]}\` \u2014 ${hook.instruction}.`)}return warnings.length>0&&warnings.push(`For the full setup, run \`fimo skills get fimo-code --ref ${SETUP_REFERENCES[framework]}\`.`),warnings}__name(missingBuildHooks,"missingBuildHooks");init_branch_identity();init_local_runtime_env();import fs38 from"node:fs";import path39 from"node:path";import{parseEnv as parseEnv2}from"node:util";function removeSeededBranchResidue(targetDir,link){let removed=[],urlKeys=new Set(LOCAL_CONTENT_API_ENV_KEYS),selectorKeys=new Set(LOCAL_ENV_SELECTOR_KEYS);for(let file of[".env",".env.local"]){let filePath=path39.join(targetDir,file);if(!fs38.existsSync(filePath))continue;let original=fs38.readFileSync(filePath,"utf-8"),eol=original.includes(`\r
|
|
2737
2737
|
`)?`\r
|
|
2738
2738
|
`:`
|
|
2739
|
-
`,kept=[],removedUrlHere=!1,lines=original.split(/\r?\n/),isSeededUrl=__name((key,value)=>urlKeys.has(key)&&isFimoMintedTenantUrl(value,link),"isSeededUrl");removedUrlHere=lines.some(line=>{let parsed=parseLine(line);return parsed!==null&&isSeededUrl(parsed.key,parsed.value)});for(let line of lines){let parsed=parseLine(line);if(parsed&&(isSeededUrl(parsed.key,parsed.value)||removedUrlHere&&selectorKeys.has(parsed.key))){removed.push({file,key:parsed.key,value:parsed.value});continue}kept.push(line)}if(kept.length!==lines.length){let content2=kept.join(eol);fs38.writeFileSync(filePath,content2)}}return removed}__name(removeSeededBranchResidue,"removeSeededBranchResidue");function parseLine(line){let[entry]=Object.entries(parseEnv2(line));return entry?{key:entry[0],value:entry[1]??""}:null}__name(parseLine,"parseLine");init_git_credential_setup();init_git();init_project_context();init_project2();function registerLinkCommand(program2){program2.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((projectId2,options,command)=>linkCommand(projectId2,{...options,branch:branchOverrideFromCommand(command)}))}__name(registerLinkCommand,"registerLinkCommand");async function linkCommand(projectIdArg,options={}){let targetDir=path40.resolve(options.cwd??process.cwd()),existingProjectId=findProjectRoot2(targetDir)===targetDir?readLinkedProjectId(targetDir):null;if(projectIdArg&&existingProjectId&&projectIdArg!==existingProjectId&&!options.relink){ui.error({command:"link",code:"PROJECT_ID_MISMATCH",message:`This application is already linked to site ${existingProjectId}, not ${projectIdArg}.`,hint:`Run \`fimo link ${projectIdArg} --relink\` to replace the existing link.`});return}if(options.branch&&!isValidBranch(options.branch)){ui.error({command:"link",code:"INVALID_ENV",message:`'${options.branch}' is not a valid Branch name.`});return}let cfg=loadConfig();requireAuth(cfg);let creds=readCredentials(cfg),fimo=createCliFimoClient(cfg),linkedProjectId2=projectIdArg??existingProjectId,resolved=linkedProjectId2?{projectId:linkedProjectId2,created:!1}:await resolveProjectId6(fimo,creds,targetDir);if(!resolved)return;let{projectId:projectId2,created}=resolved,fail2=__name((code2,message,retryBranch,hint)=>{let retry=retryCommand2(projectId2,targetDir,retryBranch);ui.error({command:"link",code:code2,message:created?`Created site ${projectId2}, but did not link it. ${message}`:message,hint:created?`Run \`${retry}\` to finish. Without the site id, \`fimo link\` creates another site.`:hint,details:created?{project_id:projectId2,project_created:!0,retry_command:retry}:void 0})},"fail"),project;try{project=(await fimo.execute("projects.get",{projectId:projectId2})).data}catch(error){fail2(error instanceof ApiRequestError&&error.status===404?"PROJECT_NOT_FOUND":"LINK_FAILED",`Could not read site ${projectId2}: ${errorMessage2(error)}`,options.branch,"Check the site id with `fimo projects list`.");return}let defaultBranch=project.defaultBranch??DEFAULT_BRANCH,branch=await resolveLinkBranch(targetDir,options.branch,defaultBranch),remote;try{remote=await createGitService(cfg,branch).getRemote(projectId2,branch)}catch(error){error instanceof ApiRequestError&&error.status===404?fail2("ENV_NOT_FOUND",`Site ${projectId2} has no Branch '${branch}'.`,defaultBranch,`Link an existing Branch: \`${retryCommand2(projectId2,targetDir,defaultBranch)}\`.`):fail2("LINK_FAILED",`Could not read site ${projectId2} (Branch '${branch}'): ${errorMessage2(error)}`,branch,"Check that the Branch exists with `fimo branch`.");return}let checkout=await setUpCheckout(targetDir,project,remote,cfg.apiUrl,defaultBranch).catch(error=>{if(!created)throw error;return fail2("LINK_FAILED",`Could not set up ${targetDir}: ${errorMessage2(error)}`,branch),null});if(!checkout)return;let{gitInitialized,adoption,removed}=checkout,runtime=resolveLocalRuntimeEnv({cwd:targetDir}),warnings=[...adoption.warnings];remote.tenantApiBaseUrl||warnings.push("The server did not return a tenant API base URL, so this checkout cannot derive Branch URLs on its own. Upgrade the Fimo backend, or set VITE_API_URL / NEXT_PUBLIC_FIMO_API_URL yourself.");let localBranch=await currentBranch2(targetDir).catch(()=>null);localBranch&&localBranch!==branch&&warnings.push(`Linked Branch '${branch}', but this checkout is on git branch '${localBranch}', and the local site follows the git branch. To work on '${branch}' locally, rename this branch (\`git branch -m ${shellArg(localBranch)} ${branch}\`) or switch to it (\`git switch ${branch}\`).`);let relinked=!!existingProjectId;ui.ok({command:"link",headline:relinked?`Repaired the link to '${project.displayName??project.name}' on Branch '${branch}'`:`Linked ${path40.basename(targetDir)} to '${project.displayName??project.name}' on Branch '${branch}'`,details:{project_id:projectId2,branch,env:branch,relinked,git_remote:"fimo",git_initialized:gitInitialized,framework:adoption.framework,fimo_setup:adoption.written,tenant_api_url:runtime?.tenantApiUrl??null,removed_env_lines:removed.map(entry=>`${entry.file}: ${entry.key}`)},hint:relinked?void 0:'Text typed in this app\'s code shows "Nothing to edit" in Fimo Studio. To make it editable, run `fimo skills get fimo-migration` and follow its source-backed path.',warnings:warnings.length>0?warnings:void 0})}__name(linkCommand,"linkCommand");async function setUpCheckout(targetDir,project,remote,apiUrl,defaultBranch){let gitInitialized=await ensureGitRepo(targetDir,defaultBranch);await ensureFimoRemote(targetDir,remote.url),writeLocalProjectFiles({targetDir,project,apiUrl,tenantApiBaseUrl:remote.tenantApiBaseUrl});let adoption=await adoptApplication(targetDir),removed=remote.tenantApiBaseUrl?removeSeededBranchResidue(targetDir,{projectId:project.id,tenantApiBaseUrl:remote.tenantApiBaseUrl}):[];return{gitInitialized,adoption,removed}}__name(setUpCheckout,"setUpCheckout");function retryCommand2(projectId2,targetDir,branch){return`fimo link ${shellArg(projectId2)} -C ${shellArg(targetDir)}${branch?` --branch ${shellArg(branch)}`:""}`}__name(retryCommand2,"retryCommand");function shellArg(value){return/^[\w./@:+-]+$/.test(value)?value:`'${value.replace(/'/g,"'\\''")}'`}__name(shellArg,"shellArg");function errorMessage2(error){return error instanceof Error?error.message:String(error)}__name(errorMessage2,"errorMessage");function readLinkedProjectId(targetDir){try{return loadProjectSettings(targetDir).projectId}catch{return null}}__name(readLinkedProjectId,"readLinkedProjectId");function noPrompt(){return currentMode().format==="json"||!isInteractive()}__name(noPrompt,"noPrompt");async function resolveProjectId6(fimo,creds,targetDir){if(!noPrompt()){let choice=await _t({message:"Which Fimo site should this application link to?",options:[{value:"new",label:"Create a new site"},{value:"existing",label:"Link an existing site"}]});if(q(choice))return ui.info({command:"link",message:"Cancelled."}),null;if(choice==="existing"){let picked=await selectProjectId({fimo,activeOrganizationId:creds?.activeOrganization?.id,message:"Which Fimo site should this application link to?"});switch(picked.status){case"selected":return{projectId:picked.projectId,created:!1};case"cancelled":return ui.info({command:"link",message:"Cancelled."}),null;case"empty":O2.step(`${picked.message} Creating one for this application.`);break;default:return ui.error({command:"link",code:picked.code,message:picked.message,hint:picked.hint}),null}}}return createProjectForApplication(fimo,targetDir)}__name(resolveProjectId6,"resolveProjectId");async function createProjectForApplication(fimo,targetDir){let organizationId;try{organizationId=await resolveOrganization(fimo,void 0,{nonInteractive:noPrompt()})}catch(error){if(!(error instanceof ScaffoldError))throw error;return error.code==="ORGANIZATION_SELECTION_CANCELLED"?(ui.info({command:"link",message:"Cancelled."}),null):(ui.error({command:"link",code:error.code,message:error.message,hint:error.code==="ORGANIZATION_REQUIRED"?"Run `fimo orgs switch --org <id-or-slug>` first, or pass a project id: `fimo link <projectId>`.":error.hint}),null)}let createSpinner=spinner("Creating Fimo site");try{let{data:project}=await fimo.execute("projects.create",{organizationId,displayName:path40.basename(targetDir)});return createSpinner.succeed(`Project ${project.displayName??project.name} created (${project.id})`),{projectId:project.id,created:!0}}catch(error){return createSpinner.fail("Project creation failed"),ui.error({command:"link",code:"PROJECT_CREATE_FAILED",message:explainCreateProjectError(error)}),null}}__name(createProjectForApplication,"createProjectForApplication");async function ensureGitRepo(targetDir,defaultBranch){if(await isGitRepo(targetDir))return!1;let gitSpinner=spinner("Initializing git repository");return await runGit(["init","-b",defaultBranch],targetDir),gitSpinner.succeed("Git initialized"),!0}__name(ensureGitRepo,"ensureGitRepo");async function resolveLinkBranch(targetDir,override,defaultBranch){if(override)return override;let branch=await currentBranch2(targetDir).catch(()=>null);return branch&&branch!=="HEAD"&&isValidBranch(branch)?branch:defaultBranch}__name(resolveLinkBranch,"resolveLinkBranch");init_dist();init_config();init_sdk_transport();init_project_services();init_branch_checkout();init_git_credential_setup();init_project_context();init_project2();function coverage(value){return`${value.translated}/${value.total}`}__name(coverage,"coverage");function localeLines(stats){return stats.map(item=>`${item.isDefault?"* ":" "}${item.locale.padEnd(12)} entries ${coverage(item.entries).padEnd(9)} labels ${coverage(item.labels)}`)}__name(localeLines,"localeLines");function renderLocaleStats(branch,stats){return[`Locales for ${branch}`,"",...localeLines(stats.locales)].join(`
|
|
2739
|
+
`,kept=[],removedUrlHere=!1,lines=original.split(/\r?\n/),isSeededUrl=__name((key,value)=>urlKeys.has(key)&&isFimoMintedTenantUrl(value,link),"isSeededUrl");removedUrlHere=lines.some(line=>{let parsed=parseLine(line);return parsed!==null&&isSeededUrl(parsed.key,parsed.value)});for(let line of lines){let parsed=parseLine(line);if(parsed&&(isSeededUrl(parsed.key,parsed.value)||removedUrlHere&&selectorKeys.has(parsed.key))){removed.push({file,key:parsed.key,value:parsed.value});continue}kept.push(line)}if(kept.length!==lines.length){let content2=kept.join(eol);fs38.writeFileSync(filePath,content2)}}return removed}__name(removeSeededBranchResidue,"removeSeededBranchResidue");function parseLine(line){let[entry]=Object.entries(parseEnv2(line));return entry?{key:entry[0],value:entry[1]??""}:null}__name(parseLine,"parseLine");init_git_credential_setup();init_git();init_project_context();init_project2();function registerLinkCommand(program2){program2.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((projectId2,options,command)=>linkCommand(projectId2,{...options,branch:branchOverrideFromCommand(command)}))}__name(registerLinkCommand,"registerLinkCommand");async function linkCommand(projectIdArg,options={}){let targetDir=path40.resolve(options.cwd??process.cwd()),existingProjectId=findProjectRoot2(targetDir)===targetDir?readLinkedProjectId(targetDir):null;if(projectIdArg&&existingProjectId&&projectIdArg!==existingProjectId&&!options.relink){ui.error({command:"link",code:"PROJECT_ID_MISMATCH",message:`This application is already linked to site ${existingProjectId}, not ${projectIdArg}.`,hint:`Run \`fimo link ${projectIdArg} --relink\` to replace the existing link.`});return}if(options.branch&&!isValidBranch(options.branch)){ui.error({command:"link",code:"INVALID_ENV",message:`'${options.branch}' is not a valid Branch name.`});return}let cfg=loadConfig();requireAuth(cfg);let creds=readCredentials(cfg),fimo=createCliFimoClient(cfg),linkedProjectId2=projectIdArg??existingProjectId,resolved=linkedProjectId2?{projectId:linkedProjectId2,created:!1}:await resolveProjectId6(fimo,creds,targetDir);if(!resolved)return;let{projectId:projectId2,created}=resolved,fail2=__name((code2,message,retryBranch,hint)=>{let retry=retryCommand2(projectId2,targetDir,retryBranch);ui.error({command:"link",code:code2,message:created?`Created site ${projectId2}, but did not link it. ${message}`:message,hint:created?`Run \`${retry}\` to finish. Without the site id, \`fimo link\` creates another site.`:hint,details:created?{project_id:projectId2,project_created:!0,retry_command:retry}:void 0})},"fail"),project;try{project=(await fimo.execute("projects.get",{projectId:projectId2})).data}catch(error){fail2(error instanceof ApiRequestError&&error.status===404?"PROJECT_NOT_FOUND":"LINK_FAILED",`Could not read site ${projectId2}: ${errorMessage2(error)}`,options.branch,"Check the site id with `fimo projects list`.");return}let defaultBranch=project.defaultBranch??DEFAULT_BRANCH,branch=await resolveLinkBranch(targetDir,options.branch,defaultBranch),remote;try{remote=await createGitService(cfg,branch).getRemote(projectId2,branch)}catch(error){error instanceof ApiRequestError&&error.status===404?fail2("ENV_NOT_FOUND",`Site ${projectId2} has no Branch '${branch}'.`,defaultBranch,`Link an existing Branch: \`${retryCommand2(projectId2,targetDir,defaultBranch)}\`.`):fail2("LINK_FAILED",`Could not read site ${projectId2} (Branch '${branch}'): ${errorMessage2(error)}`,branch,"Check that the Branch exists with `fimo branch`.");return}let checkout=await setUpCheckout(targetDir,project,remote,cfg.apiUrl,defaultBranch).catch(error=>{if(!created)throw error;return fail2("LINK_FAILED",`Could not set up ${targetDir}: ${errorMessage2(error)}`,branch),null});if(!checkout)return;let{gitInitialized,adoption,removed}=checkout,runtime=resolveLocalRuntimeEnv({cwd:targetDir}),warnings=[...adoption.warnings];remote.tenantApiBaseUrl||warnings.push("The server did not return a tenant API base URL, so this checkout cannot derive Branch URLs on its own. Upgrade the Fimo backend, or set VITE_API_URL / NEXT_PUBLIC_FIMO_API_URL yourself.");let localBranch=await currentBranch2(targetDir).catch(()=>null);localBranch&&localBranch!==branch&&warnings.push(`Linked Branch '${branch}', but this checkout is on git branch '${localBranch}', and the local site follows the git branch. To work on '${branch}' locally, rename this branch (\`git branch -m ${shellArg(localBranch)} ${branch}\`) or switch to it (\`git switch ${branch}\`).`);let relinked=!!existingProjectId;ui.ok({command:"link",headline:relinked?`Repaired the link to '${project.displayName??project.name}' on Branch '${branch}'`:`Linked ${path40.basename(targetDir)} to '${project.displayName??project.name}' on Branch '${branch}'`,details:{project_id:projectId2,branch,env:branch,relinked,git_remote:"fimo",git_initialized:gitInitialized,framework:adoption.framework,fimo_setup:adoption.written,tenant_api_url:runtime?.tenantApiUrl??null,removed_env_lines:removed.map(entry=>`${entry.file}: ${entry.key}`)},hint:relinked?void 0:'Text typed in this app\'s code shows "Nothing to edit" in Fimo Studio. To make it editable, run `fimo skills get fimo-migration` and follow its source-backed path.',warnings:warnings.length>0?warnings:void 0})}__name(linkCommand,"linkCommand");async function setUpCheckout(targetDir,project,remote,apiUrl,defaultBranch){let gitInitialized=await ensureGitRepo(targetDir,defaultBranch);await ensureFimoRemote(targetDir,remote.url),writeLocalProjectFiles({targetDir,project,apiUrl,tenantApiBaseUrl:remote.tenantApiBaseUrl});let adoption=await adoptApplication(targetDir),removed=remote.tenantApiBaseUrl?removeSeededBranchResidue(targetDir,{projectId:project.id,tenantApiBaseUrl:remote.tenantApiBaseUrl}):[];return{gitInitialized,adoption,removed}}__name(setUpCheckout,"setUpCheckout");function retryCommand2(projectId2,targetDir,branch){return`fimo link ${shellArg(projectId2)} -C ${shellArg(targetDir)}${branch?` --branch ${shellArg(branch)}`:""}`}__name(retryCommand2,"retryCommand");function shellArg(value){return/^[\w./@:+-]+$/.test(value)?value:`'${value.replace(/'/g,"'\\''")}'`}__name(shellArg,"shellArg");function errorMessage2(error){return error instanceof Error?error.message:String(error)}__name(errorMessage2,"errorMessage");function readLinkedProjectId(targetDir){try{return loadProjectSettings(targetDir).projectId}catch{return null}}__name(readLinkedProjectId,"readLinkedProjectId");function noPrompt(){return currentMode().format==="json"||!isInteractive()}__name(noPrompt,"noPrompt");async function resolveProjectId6(fimo,creds,targetDir){if(!noPrompt()){let choice=await _t({message:"Which Fimo site should this application link to?",options:[{value:"new",label:"Create a new site"},{value:"existing",label:"Link an existing site"}]});if(q(choice))return ui.info({command:"link",message:"Cancelled."}),null;if(choice==="existing"){let picked=await selectProjectId({fimo,activeOrganizationId:creds?.activeOrganization?.id,message:"Which Fimo site should this application link to?"});switch(picked.status){case"selected":return{projectId:picked.projectId,created:!1};case"cancelled":return ui.info({command:"link",message:"Cancelled."}),null;case"empty":O2.step(`${picked.message} Creating one for this application.`);break;default:return ui.error({command:"link",code:picked.code,message:picked.message,hint:picked.hint}),null}}}return createProjectForApplication(fimo,targetDir)}__name(resolveProjectId6,"resolveProjectId");async function createProjectForApplication(fimo,targetDir){let organizationId;try{organizationId=await resolveOrganization(fimo,void 0,{nonInteractive:noPrompt()})}catch(error){if(!(error instanceof ScaffoldError))throw error;return error.code==="ORGANIZATION_SELECTION_CANCELLED"?(ui.info({command:"link",message:"Cancelled."}),null):(ui.error({command:"link",code:error.code,message:error.message,hint:error.code==="ORGANIZATION_REQUIRED"?"Run `fimo orgs switch --org <id-or-slug>` first, or pass a project id: `fimo link <projectId>`.":error.hint}),null)}let createSpinner=spinner("Creating Fimo site");try{let{data:project}=await fimo.execute("projects.create",{organizationId,displayName:path40.basename(targetDir)});return createSpinner.succeed(`Project ${project.displayName??project.name} created (${project.id})`),{projectId:project.id,created:!0}}catch(error){return createSpinner.fail("Project creation failed"),ui.error({command:"link",code:"PROJECT_CREATE_FAILED",message:explainCreateProjectError(error)}),null}}__name(createProjectForApplication,"createProjectForApplication");async function ensureGitRepo(targetDir,defaultBranch){if(await isGitRepo(targetDir))return!1;let gitSpinner=spinner("Initializing git repository");return await runGit(["init","-b",defaultBranch],targetDir),gitSpinner.succeed("Git initialized"),!0}__name(ensureGitRepo,"ensureGitRepo");async function resolveLinkBranch(targetDir,override,defaultBranch){if(override)return override;let branch=await currentBranch2(targetDir).catch(()=>null);return branch&&branch!=="HEAD"&&isValidBranch(branch)?branch:defaultBranch}__name(resolveLinkBranch,"resolveLinkBranch");init_esm();init_dist();init_config();init_sdk_transport();init_project_services();init_branch_checkout();init_git_credential_setup();init_project_context();init_project2();function coverage(value){return`${value.translated}/${value.total}`}__name(coverage,"coverage");function localeLines(stats){return stats.map(item=>`${item.isDefault?"* ":" "}${item.locale.padEnd(12)} entries ${coverage(item.entries).padEnd(9)} labels ${coverage(item.labels)}`)}__name(localeLines,"localeLines");function renderLocaleStats(branch,stats){return[`Locales for ${branch}`,"",...localeLines(stats.locales)].join(`
|
|
2740
2740
|
`)}__name(renderLocaleStats,"renderLocaleStats");async function localesListCommand(options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("i18n.list",{projectId:ctx.projectId,branch:ctx.branch});let{data:stats}=await fimo.execute("locales.list",{projectId:ctx.projectId,branch:ctx.branch});ui.result({command:"locales list",data:{branch:ctx.branch,...stats},render:__name(()=>renderLocaleStats(ctx.branch,stats),"render")})}__name(localesListCommand,"localesListCommand");function confirmationDetails(spec,locale,branch,plan){let movement=plan.state.relation==="behind"?`Fimo will first fast-forward '${plan.state.localBranch}' by ${plan.state.behind} commit${plan.state.behind===1?"":"s"}, then commit this change to fimo/${plan.state.remoteBranch} and synchronize it back.`:`Fimo will commit this change to fimo/${plan.state.remoteBranch}, then fast-forward '${plan.state.localBranch}' to that commit.`;return[`${spec.verb} locale '${locale}' in Branch '${branch}'.`,movement,...spec.destructive?[`This permanently deletes stored entries and labels for '${locale}' from this Branch.`]:[]].join(`
|
|
2741
2741
|
`)}__name(confirmationDetails,"confirmationDetails");function rejectMissingConfirmation(spec,options){return options.yes||currentMode().format!=="json"&&isInteractive()?!1:(ui.error({command:`locales ${spec.operation}`,code:"CONFIRMATION_REQUIRED",message:"Locale lifecycle changes require confirmation.",hint:"Review the operation, then pass --yes to apply it non-interactively."}),!0)}__name(rejectMissingConfirmation,"rejectMissingConfirmation");async function confirmMutation(spec,locale,branch,plan,options){if(options.yes)return!0;wt(confirmationDetails(spec,locale,branch,plan),"What will happen");let confirmed=await ot2({message:"Continue?",initialValue:!1});return q(confirmed)||!confirmed?(ui.info({command:`locales ${spec.operation}`,message:"Cancelled."}),!1):!0}__name(confirmMutation,"confirmMutation");function emitPreflightError(command,error){return error instanceof BranchCheckoutError?(ui.error({command,code:error.code,message:error.message,hint:error.hint}),!0):!1}__name(emitPreflightError,"emitPreflightError");function emitApiError(command,error){return rethrowCliAuthError(error),error instanceof ApiRequestError?(ui.error({command,code:error.code?.toUpperCase()??"LOCALE_MUTATION_FAILED",message:error.detail}),!0):!1}__name(emitApiError,"emitApiError");function renderMutationResult(spec,response,branch,sync){if(sync.status==="required")return[`Locale '${response.locale}' was changed in '${branch}', but this checkout could not be synchronized.`,"The remote change succeeded. Do not retry the locale command.","",sync.reason,"","Recover the checkout:",...sync.recovery.map(command=>` ${command}`)].join(`
|
|
2742
2742
|
`);let removal="entriesDeleted"in response?` Deleted ${response.entriesDeleted} entr${response.entriesDeleted===1?"y":"ies"} and ${response.labelsDeleted} label${response.labelsDeleted===1?"":"s"}.`:"";return`${spec.verb} locale '${response.locale}' in '${branch}'.${removal}
|
|
2743
|
-
Remote config and local checkout are synchronized.`}__name(renderMutationResult,"renderMutationResult");async function runLocaleMutation(locale,options,cmd,spec){let command=`locales ${spec.operation}`;if(rejectMissingConfirmation(spec,options))return;let cwd=resolveProjectCwd(options.cwd),{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation(spec.capability,{projectId:ctx.projectId,branch:ctx.branch});let plan;try{
|
|
2743
|
+
Remote config and local checkout are synchronized.`}__name(renderMutationResult,"renderMutationResult");async function localeMutationRemote(cwd,projectId2,branch){if(currentAgentSession())return{remote:"origin",remoteBranch:branch};let remote=await createGitService(loadConfig(),branch).getRemote(projectId2,branch);return await ensureFimoRemote(cwd,remote.url),{remote:"fimo",remoteBranch:remote.branch}}__name(localeMutationRemote,"localeMutationRemote");async function runLocaleMutation(locale,options,cmd,spec){let command=`locales ${spec.operation}`;if(rejectMissingConfirmation(spec,options))return;let cwd=resolveProjectCwd(options.cwd),{ctx,fimo}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation(spec.capability,{projectId:ctx.projectId,branch:ctx.branch});let plan;try{plan=await planLocaleMutationCheckout({cwd,...await localeMutationRemote(cwd,ctx.projectId,ctx.branch),configPath:resolveProjectConfigPath(cwd)})}catch(error){if(emitPreflightError(command,error)||emitApiError(command,error))return;throw error}if(!await confirmMutation(spec,locale,ctx.branch,plan,options))return;try{await applyLocaleMutationCheckoutPlan(plan)}catch(error){if(emitPreflightError(command,error))return;throw error}let response;try{response=await spec.mutate(fimo,ctx.projectId,ctx.branch,locale)}catch(error){if(emitApiError(command,error))return;throw error}let sync=await synchronizeLocaleMutationCheckout({cwd,remote:plan.remote,remoteBranch:plan.state.remoteBranch}),data={operation:spec.operation,branch:ctx.branch,applied:!0,...response,...sync.status==="required"?{code:"LOCALE_APPLIED_SYNC_REQUIRED"}:{},sync};ui.result({command,data,render:__name(()=>renderMutationResult(spec,response,ctx.branch,sync),"render")}),sync.status==="required"&&(process.exitCode=2)}__name(runLocaleMutation,"runLocaleMutation");async function localesAddCommand(locale,options,cmd){return runLocaleMutation(locale,options,cmd,{operation:"add",capability:"i18n.locales.add",verb:"Add",destructive:!1,mutate:__name(async(fimo,projectId2,branch,locale2)=>{let{data}=await fimo.execute("locales.add",{projectId:projectId2,branch,locale:locale2});return data},"mutate")})}__name(localesAddCommand,"localesAddCommand");async function localesSetDefaultCommand(locale,options,cmd){return runLocaleMutation(locale,options,cmd,{operation:"set-default",capability:"i18n.update",verb:"Set the default to",destructive:!1,mutate:__name(async(fimo,projectId2,branch,locale2)=>{let{data}=await fimo.execute("locales.setDefault",{projectId:projectId2,branch,locale:locale2});return data},"mutate")})}__name(localesSetDefaultCommand,"localesSetDefaultCommand");async function localesRemoveCommand(locale,options,cmd){return runLocaleMutation(locale,options,cmd,{operation:"remove",capability:"i18n.delete",verb:"Remove",destructive:!0,mutate:__name(async(fimo,projectId2,branch,locale2)=>{let{data}=await fimo.execute("locales.delete",{projectId:projectId2,branch,locale:locale2});return data},"mutate")})}__name(localesRemoveCommand,"localesRemoveCommand");function registerLocalesCommands(program2){let locales=program2.command("locales").description("Manage site locale lifecycle");locales.command("list").description("List configured locales and stored content coverage").option("-C, --cwd <dir>","Site directory").action(localesListCommand),locales.command("add <locale>").description("Add a locale to the selected Branch").option("-C, --cwd <dir>","Site directory").option("-y, --yes","Apply without an interactive confirmation").action(localesAddCommand),locales.command("set-default <locale>").description("Set the default locale for the selected Branch").option("-C, --cwd <dir>","Site directory").option("-y, --yes","Apply without an interactive confirmation").action(localesSetDefaultCommand),locales.command("remove <locale>").description("Remove a locale and permanently delete its stored content").option("-C, --cwd <dir>","Site directory").option("-y, --yes","Apply without an interactive confirmation").action(localesRemoveCommand)}__name(registerLocalesCommands,"registerLocalesCommands");init_dist();init_auth();init_config();async function logoutCommand(){let cfg=loadConfig(),creds=readCredentials(cfg);if(!creds?.access_token){ui.info({command:"logout",message:"Already signed out."});return}clearCredentials(cfg),ui.ok({command:"logout",headline:`Signed out${creds.user?.email?` (${creds.user.email})`:""}.`,details:creds.user?.email?{email:creds.user.email}:void 0})}__name(logoutCommand,"logoutCommand");init_dist();init_project_context();var MAX_LIMIT=1e3;async function logsCommand(options,cmd){let{ctx,fimo}=await bootstrapProjectCommand(options,cmd);await requireOperation("fimo.logs.read",{projectId:ctx.projectId,branch:ctx.branch});let pagination;try{pagination=parsePaginationOptions(options,{defaultLimit:200,maxLimit:MAX_LIMIT,legacyCursor:"before"})}catch(error){ui.error({command:"logs",code:error instanceof PaginationValidationError&&error.kind!=="invalid_limit"?"LOGS_INVALID_CURSOR":"LOGS_INVALID_LIMIT",message:errorMessage3(error)});return}let result;try{let first=await fimo.execute("sandbox.logs",{projectId:ctx.projectId,branch:ctx.branch,limit:pagination.limit,cursor:pagination.cursor});if(first.status==="unavailable")result=projectSandboxLogs2(first);else{let pendingFirst=first,page2=await collectPaginatedItems({cursor:pagination.cursor,allPages:pagination.allPages,fetchPage:__name(async cursor=>{let response=pendingFirst??await fimo.execute("sandbox.logs",{projectId:ctx.projectId,branch:ctx.branch,limit:pagination.limit,cursor});if(pendingFirst=void 0,response.status==="unavailable")throw new Error(response.message);return response},"fetchPage")});result=projectSandboxLogs2({...page2,items:page2.items})}}catch(error){ui.error({command:"logs",code:"LOGS_REQUEST_FAILED",message:`Could not read sandbox logs: ${errorMessage3(error)}`});return}let data=result.status==="unavailable"?{project_id:ctx.projectId,branch:ctx.branch,env:ctx.branch,...result,items:[],nextCursor:null}:{project_id:ctx.projectId,branch:ctx.branch,env:ctx.branch,...result,items:result.events,nextCursor:result.previousCursor};if(result.status==="unavailable"){let{message}=result;ui.result({command:"logs",data,render:__name(()=>message,"render")});return}let page=result,hint=page.previousCursor?buildOlderHint(page.previousCursor,ctx.branch,pagination.limit,options):void 0;ui.result({command:"logs",data,render:__name(()=>renderLogs(page,ctx.branch),"render"),...hint?{hint}:{}})}__name(logsCommand,"logsCommand");function projectSandboxLogs2(result){return result.status==="unavailable"?{status:result.status,reason:result.reason,message:result.message}:{status:result.status,events:result.items,previousCursor:result.nextCursor,truncated:result.nextCursor!==null,retention:result.retention}}__name(projectSandboxLogs2,"projectSandboxLogs");function renderLogs(page,branch){let lines=[],count=page.events.length;lines.push(`${branch}: ${count} ${count===1?"event":"events"}${page.truncated?" (older ones remain)":""}`);for(let phase of page.retention.phases)lines.push(` ${renderPhase(phase)}`);if(page.retention.droppedOldest&&lines.push(" Note: the sandbox buffer dropped its oldest lines; they cannot be paged back to."),count===0)return lines.push(""),lines.push("No output recorded for these phases yet."),lines.join(`
|
|
2744
2744
|
`);lines.push("");let width=Math.max(...page.events.map(event=>event.source.length));for(let event of[...page.events].reverse())lines.push(`${event.source.padEnd(width)} ${event.message}`);return lines.join(`
|
|
2745
2745
|
`)}__name(renderLogs,"renderLogs");function renderPhase(phase){let parts=[phase.status];return phase.exitCode!==null&&parts.push(`exit ${phase.exitCode}`),phase.startedAt&&parts.push(`started ${phase.startedAt}`),parts.push(`${phase.events} ${phase.events===1?"line":"lines"}`),`${phase.phase}: ${parts.join(", ")}`}__name(renderPhase,"renderPhase");function buildOlderHint(cursor,branch,limit,options){let trailingArgs=["--branch",branch];return options.cwd&&trailingArgs.push("--cwd",options.cwd),buildPaginationHint(["fimo","logs"],{cursor,limit,trailingArgs},"Older")}__name(buildOlderHint,"buildOlderHint");function errorMessage3(error){return error instanceof Error?error.message:String(error)}__name(errorMessage3,"errorMessage");init_esm();init_dist();init_project_context();function taskTokens(task){let argv=process.argv.slice(2),namespaceIndex=argv.indexOf(task.modality);if(namespaceIndex===-1)return[];let verbIndex=argv.indexOf(task.operation,namespaceIndex+1);return verbIndex===-1?[]:argv.slice(verbIndex+1)}__name(taskTokens,"taskTokens");function renderTaskHelp(task){return renderGenerationHelp({usage:`fimo ${task.modality} ${task.operation} [flags]`,description:task.description,flags:task.flags})}__name(renderTaskHelp,"renderTaskHelp");async function runTask(task,command){let tokens=taskTokens(task),wantsHelp=tokens.includes("--help")||tokens.includes("-h"),commandName2=`${task.modality} ${task.operation}`;if(wantsHelp){ui.result({command:commandName2,data:{task},render:__name(()=>renderTaskHelp(task),"render")});return}let{values,bools,options}=parseGenerationFlags({commandName:commandName2,subject:task.id,helpCommand:`fimo ${commandName2} --help`,flags:task.flags,tokens}),body={task:task.id,options,name:values.get("name")?.[0],parentId:values.get("parent")?.[0]??null},isJson=currentMode().format==="json",{ctx,fimo}=await bootstrapProjectCommand({cwd:values.get("cwd")?.[0]},command,{refuseReadOnly:!0,quiet:isJson});if(bools.get("dry-run")===!0){let estimate=await fimo.execute("generation.estimateTask",{projectId:ctx.projectId,branch:ctx.branch,task:task.id,options}),data={...body,estimate};ui.result({command:commandName2,data,render:__name(()=>JSON.stringify(data,null,2),"render")});return}await submitGeneration({commandName:commandName2,ctx,fimo,body})}__name(runTask,"runTask");function registerTaskCommand(parent,task){parent.command(task.operation).description(task.description).allowUnknownOption(!0).allowExcessArguments(!0).helpOption(!1).action(async(_options,command)=>{await runTask(task,command)})}__name(registerTaskCommand,"registerTaskCommand");function registerMediaTaskCommands(program2){let image=program2.command("image").description("Generate and transform images"),video=program2.command("video").description("Generate and transform videos");for(let task of GENERATION_TASK_MANIFESTS)registerTaskCommand(task.modality==="image"?image:video,task)}__name(registerMediaTaskCommands,"registerMediaTaskCommands");import{execSync,spawnSync as spawnSync3}from"node:child_process";import{mkdtempSync,readFileSync as readFileSync11,writeFileSync as writeFileSync5}from"node:fs";import{tmpdir as tmpdir3}from"node:os";import path41 from"node:path";init_dist();init_config();init_sdk_transport();init_color();function renderMergeSuccess(result,p2){let lines=[];if(lines.push(p2.green(`\u2713 Merged ${result.fromBranch??result.fromEnv} \u2192 ${result.toBranch??result.toEnv}`)),result.summary&&lines.push(p2.dim(` ${result.summary}`)),result.applied&&result.applied.length>0){lines.push(""),lines.push(p2.bold("Applied:"));for(let a of result.applied)lines.push(p2.dim(` ${a.surface.padEnd(14)} ${a.count} item${a.count===1?"":"s"}`))}return lines.join(`
|
|
2746
2746
|
`)}__name(renderMergeSuccess,"renderMergeSuccess");function renderConflict(conflict,p2){let lines=[];return lines.push(`${p2.yellow("!")} ${p2.bold(`${conflict.surface}: ${conflict.key}`)}`),lines.push(p2.dim(` ${conflict.description}`)),conflict.parentValue!==void 0&&lines.push(p2.dim(" parent: ")+summariseValue(conflict.parentValue)),conflict.childValue!==void 0&&lines.push(p2.dim(" child: ")+summariseValue(conflict.childValue)),lines.join(`
|
|
2747
|
-
`)}__name(renderConflict,"renderConflict");function renderResolverHeader(conflicts,p2){let surfaceCounts=conflicts.reduce((acc,c2)=>(acc[c2.surface]=(acc[c2.surface]??0)+1,acc),{}),parts=Object.entries(surfaceCounts).map(([s,n])=>`${n} ${s}`);return p2.yellow(`! ${conflicts.length} conflict${conflicts.length===1?"":"s"} (${parts.join(", ")}) \u2014 resolve below.`)}__name(renderResolverHeader,"renderResolverHeader");function summariseValue(v){if(v===null)return"null";if(typeof v=="string")return v.length>60?v.slice(0,57)+"...":v;if(typeof v=="number"||typeof v=="boolean")return String(v);try{let s=JSON.stringify(v);return s.length>60?s.slice(0,57)+"...":s}catch{return"[unserialisable]"}}__name(summariseValue,"summariseValue");init_project_context();init_esm();var ProtectedFlowError=class extends Error{static{__name(this,"ProtectedFlowError")}env;constructor(env){super(`Refusing to run this mutating command against the protected Branch '${env}'. Use the PR/review flow or pass --allow-direct-merge to override.`),this.name="ProtectedFlowError",this.env=env}};function assertNotOnMain(env,opts={}){let protectedEnvs=opts.protectedEnvs??[DEFAULT_BRANCH];if(!opts.allowDirectMerge&&protectedEnvs.includes(env))throw new ProtectedFlowError(env)}__name(assertNotOnMain,"assertNotOnMain");async function fetchDrillContext(args){let{fimo,ctx,fromBranch,conflict,p:p2}=args,surface=conflict.surface;try{switch(surface){case"code":{let payload=await fimo.execute("branches.diffCodeFile",{projectId:ctx.projectId,branch:fromBranch,path:conflict.key,against:ctx.branch});return renderCodeFileDiff(payload,p2,{bare:!1})}case"content":{let[collection,rowId]=splitOnce2(conflict.key,":");if(!collection||!rowId)return null;let payload=await fimo.execute("branches.diffContentEntry",{projectId:ctx.projectId,branch:fromBranch,collection,rowId,against:ctx.branch});return renderContentRowDiff(payload,p2,{bare:!1})}case"translations":{let[locale,key]=splitOnce2(conflict.key,":");if(!locale||!key)return null;let payload=await fimo.execute("branches.diffLabel",{projectId:ctx.projectId,branch:fromBranch,locale,key,against:ctx.branch});return renderTranslationRowDiff(payload,p2,{bare:!1})}case"schemas":{let payload=await fimo.execute("branches.diffSchema",{projectId:ctx.projectId,branch:fromBranch,typeName:conflict.key,against:ctx.branch});return renderSchemaTypeDiff(payload,p2,{bare:!1})}case"forms":{let payload=await fimo.execute("branches.diffForm",{projectId:ctx.projectId,branch:fromBranch,formName:conflict.key,against:ctx.branch});return renderFormSchemaDiff(payload,p2,{bare:!1})}case"assets":{let payload=await fimo.execute("branches.diffAsset",{projectId:ctx.projectId,branch:fromBranch,assetId:conflict.key,against:ctx.branch});return renderAssetDiff(payload,p2,{bare:!1})}}}catch{return null}return null}__name(fetchDrillContext,"fetchDrillContext");function splitOnce2(s,sep2){let idx=s.indexOf(sep2);return idx<0?[s,""]:[s.slice(0,idx),s.slice(idx+1)]}__name(splitOnce2,"splitOnce");function portableResolution(resolution){return{...resolution,surface:resolution.surface==="translations"?"labels":resolution.surface}}__name(portableResolution,"portableResolution");function legacyConflict(conflict){return{...conflict,surface:conflict.surface==="labels"?"translations":conflict.surface}}__name(legacyConflict,"legacyConflict");function legacyMergeResult(result){return{...result,fromEnv:result.fromBranch,toEnv:result.toBranch,applied:result.applied.map(item=>({...item,surface:item.surface==="labels"?"translations":item.surface})),conflicts:result.conflicts?.map(legacyConflict)}}__name(legacyMergeResult,"legacyMergeResult");var DRAFT_DEBOUNCE_MS=1500,MERGE_POLL_MS=1e3,MERGE_WAIT_MS=10*6e4;function keepTarget(conflict){return{surface:conflict.surface,key:conflict.key,choice:"parent"}}__name(keepTarget,"keepTarget");function resumeHint(from){return`Resolve in a terminal with \`fimo merge ${from} --resume\`, keep the target value for every conflict with \`fimo merge ${from} --resume --yes\`, or resolve in Studio.`}__name(resumeHint,"resumeHint");function reportConflicts(from,ctx,mergeId,conflicts){ui.error({command:"merge",code:"MERGE_CONFLICTS",message:conflicts?`Merge ${from} \u2192 ${ctx.branch} stopped on ${conflicts.length} conflict${conflicts.length===1?"":"s"}; nothing was applied.`:`Merge ${from} \u2192 ${ctx.branch} stopped on conflicts; nothing was applied.`,details:{merge_id:mergeId,from,to:ctx.branch,...conflicts?{conflicts}:{}},hint:resumeHint(from)})}__name(reportConflicts,"reportConflicts");async function mergeCommand(from,options,cmd){let program2=cmd?.parent??cmd,branchOverride2=branchOverrideFromCommand(program2),ctx=await getProjectContext({cwd:options.cwd,branchOverride:branchOverride2}),fimo=createCliFimoClient(loadConfig(),ctx.branch);try{assertNotOnMain(ctx.branch,{allowDirectMerge:options.allowDirectMerge})}catch(err){if(err instanceof ProtectedFlowError){ui.error({command:"merge",code:"PROTECTED_FLOW",message:err.message,hint:"See: https://fimo.ai/docs/environments/overview#a-pr-style-flow"});return}throw err}let isJson=currentMode().format==="json",p2=options.noColor?makeColorPalette({forceDisable:!0}):palette;if(options.resume)return resumeMerge({fimo,ctx,from,options,p:p2,isJson});isJson||mt(p2.bold(`Merging ${from} \u2192 ${ctx.branch}`));let result;try{result=legacyMergeResult(await fimo.execute("branches.merge",{projectId:ctx.projectId,branch:ctx.branch,from,allowDirectMerge:options.allowDirectMerge}))}catch(err){rethrowCliAuthError(err),ui.error({command:"merge",code:"MERGE_REQUEST_FAILED",message:`Merge failed: ${err.message}`});return}if(result.ok){ui.result({command:"merge",data:result,render:__name(rctx=>renderMergeSuccess(result,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")});return}let conflicts=result.conflicts??[];if(conflicts.length===0){ui.error({command:"merge",code:"MERGE_EMPTY_CONFLICTS",message:"Merge returned ok=false but produced no conflicts. Aborting."});return}if(isJson&&options.yes!==!0){reportConflicts(from,ctx,result.mergeId,conflicts);return}let resolutions;if(isJson?resolutions=conflicts.map(keepTarget):(O2.warn(renderResolverHeader(conflicts,p2)),resolutions=await resolveConflictsInteractive({fimo,ctx,from,mergeId:result.mergeId,conflicts,drafted:[],p:p2,acceptDefaults:options.yes===!0})),resolutions===null){await fimo.execute("branches.cancelMerge",{projectId:ctx.projectId,branch:ctx.branch,mergeId:result.mergeId}).catch(()=>{}),ui.error({command:"merge",code:"MERGE_CANCELLED",message:"Merge cancelled; compensating actions triggered server-side."});return}await commitResolutions({fimo,ctx,from,mergeId:result.mergeId,resolutions})}__name(mergeCommand,"mergeCommand");async function resolveConflictsInteractive(args){let draftedMap=new Map;for(let d3 of args.drafted)draftedMap.set(`${d3.surface}:${d3.key}`,d3);let resolutions=[...args.drafted],pendingSave=null,flush=__name(async()=>{pendingSave&&(clearTimeout(pendingSave),pendingSave=null);try{await args.fimo.execute("branches.saveMergeDraft",{projectId:args.ctx.projectId,branch:args.ctx.branch,from:args.from,mergeId:args.mergeId,resolutions:resolutions.map(portableResolution)})}catch{}},"flush"),scheduleSave=__name(()=>{pendingSave&&clearTimeout(pendingSave),pendingSave=setTimeout(()=>{flush().catch(()=>{})},DRAFT_DEBOUNCE_MS)},"scheduleSave");for(let conflict of args.conflicts){let key=`${conflict.surface}:${conflict.key}`;if(draftedMap.has(key))continue;if(await printConflictWithContext(args.fimo,args.ctx,args.from,conflict,args.p),args.acceptDefaults){resolutions.push(keepTarget(conflict)),scheduleSave();continue}let isCode=conflict.surface==="code",choice=await _t({message:"How should this conflict be resolved?",options:[{value:"parent",label:isCode?`parent \u2014 keep ${args.ctx.branch}'s file`:"parent \u2014 keep target value"},{value:"child",label:isCode?`child \u2014 take ${args.from}'s file`:"child \u2014 take source value"},{value:"pick",label:isCode?"pick \u2014 resolve conflict markers in $EDITOR":"pick \u2014 edit a custom value in $EDITOR"},{value:"abort",label:"abort \u2014 cancel the merge"}]});if(q(choice)||choice==="abort")return await flush(),null;if(choice==="pick"){let picked=isCode?await openEditorForCodePick(args.fimo,args.ctx,args.from,conflict):openEditorForPick(conflict);if(picked===null)return O2.warn("Empty buffer \u2014 treating as abort. Re-run with --resume to continue."),await flush(),null;resolutions.push({surface:conflict.surface,key:conflict.key,choice:"pick",pickedValue:picked})}else resolutions.push({surface:conflict.surface,key:conflict.key,choice});scheduleSave()}return await flush(),resolutions}__name(resolveConflictsInteractive,"resolveConflictsInteractive");async function printConflictWithContext(fimo,ctx,fromBranch,conflict,p2){console.log(renderConflict(conflict,p2));try{let drill=await fetchDrillContext({fimo,ctx,fromBranch,conflict,p:p2});drill&&console.log(drill)}catch{}}__name(printConflictWithContext,"printConflictWithContext");async function commitResolutions(args){let accepted;try{accepted=await args.fimo.execute("branches.resolveMerge",{projectId:args.ctx.projectId,branch:args.ctx.branch,from:args.from,mergeId:args.mergeId,resolutions:args.resolutions.map(portableResolution)})}catch(err){rethrowCliAuthError(err),ui.error({command:"merge",code:"MERGE_RESOLVE_FAILED",message:`Resolve failed: ${err.message}`});return}await awaitMerge({fimo:args.fimo,ctx:args.ctx,from:args.from,mergeId:accepted.mergeId})}__name(commitResolutions,"commitResolutions");async function settledMerge(args){let deadline=Date.now()+MERGE_WAIT_MS;for(;;){let merge=await args.fimo.execute("branches.mergeStatus",{projectId:args.ctx.projectId,mergeId:args.mergeId});if(merge.status!=="in_progress"||Date.now()>=deadline)return merge;await new Promise(resolve10=>setTimeout(resolve10,MERGE_POLL_MS))}}__name(settledMerge,"settledMerge");async function awaitMerge(args){let sp=spinner(`Applying merge ${args.from} \u2192 ${args.ctx.branch}`),merge;try{merge=await settledMerge(args)}catch(err){rethrowCliAuthError(err),ui.error({command:"merge",code:"MERGE_STATUS_FAILED",message:`Merge ${args.mergeId} was accepted, but reading its status failed: ${err.message}`,details:{merge_id:args.mergeId},hint:`Run \`fimo merge ${args.from} --resume\` to follow it; it does not resubmit.`});return}finally{sp.stop()}let details={merge_id:merge.mergeId,from:merge.fromBranch,to:merge.toBranch};switch(merge.status){case"complete":{let result={ok:!0,mergeId:merge.mergeId,fromBranch:merge.fromBranch,toBranch:merge.toBranch,fromEnv:merge.fromBranch,toEnv:merge.toBranch,...merge.summary?{summary:merge.summary}:{}};ui.result({command:"merge",data:result,render:__name(rctx=>renderMergeSuccess(result,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")});return}case"conflicts":reportConflicts(args.from,args.ctx,merge.mergeId);return;case"in_progress":ui.error({command:"merge",code:"MERGE_IN_PROGRESS",message:`Merge ${merge.mergeId} is still applying after ${MERGE_WAIT_MS/6e4} minutes.`,details,hint:`Run \`fimo merge ${args.from} --resume\` to keep following it; it does not resubmit.`});return;case"rolled_back":ui.error({command:"merge",code:"MERGE_CANCELLED",message:`Merge ${merge.mergeId} was rolled back${merge.error?`: ${merge.error}`:""}.`,details});return;case"failed":ui.error({command:"merge",code:"MERGE_FAILED",message:`Merge ${merge.mergeId} failed${merge.error?`: ${merge.error}`:""}.`,details,hint:`Run \`fimo merge ${args.from}\` to start a new merge.`});return}}__name(awaitMerge,"awaitMerge");async function resumeMerge(args){let hydration;try{let portableHydration=await args.fimo.execute("branches.mergeConflicts",{projectId:args.ctx.projectId,branch:args.ctx.branch,from:args.from});hydration={...portableHydration,conflicts:portableHydration.conflicts.map(legacyConflict),draftResolutions:portableHydration.draftResolutions.map(resolution=>({...resolution,surface:resolution.surface==="labels"?"translations":resolution.surface}))}}catch(err){rethrowCliAuthError(err),ui.error({command:"merge",code:"MERGE_RESUME_FAILED",message:`Failed to load in-progress merge: ${err.message}`});return}if(hydration.status==="in_progress"){await awaitMerge({fimo:args.fimo,ctx:args.ctx,from:args.from,mergeId:hydration.mergeId});return}if(hydration.status!=="conflicts"){ui.error({command:"merge",code:"MERGE_NOT_RESUMABLE",message:`Merge ${hydration.mergeId} is ${hydration.status}; nothing to resume.`});return}if(hydration.conflicts.length===0){args.isJson||O2.info("No conflicts to resolve \u2014 submitting empty batch."),await commitResolutions({fimo:args.fimo,ctx:args.ctx,from:args.from,mergeId:hydration.mergeId,resolutions:[]});return}if(args.isJson){let drafted=new Set(hydration.draftResolutions.map(d3=>`${d3.surface}:${d3.key}`)),unanswered=hydration.conflicts.filter(c2=>!drafted.has(`${c2.surface}:${c2.key}`));if(unanswered.length>0&&args.options.yes!==!0){reportConflicts(args.from,args.ctx,hydration.mergeId,unanswered);return}await commitResolutions({fimo:args.fimo,ctx:args.ctx,from:args.from,mergeId:hydration.mergeId,resolutions:[...hydration.draftResolutions,...unanswered.map(keepTarget)]});return}mt(args.p.bold(`Resuming merge ${args.from} \u2192 ${args.ctx.branch}`)),O2.info(`${hydration.draftResolutions.length} of ${hydration.conflicts.length} conflict${hydration.conflicts.length===1?"":"s"} already drafted`);let resolutions=await resolveConflictsInteractive({fimo:args.fimo,ctx:args.ctx,from:args.from,mergeId:hydration.mergeId,conflicts:hydration.conflicts,drafted:hydration.draftResolutions,p:args.p,acceptDefaults:args.options.yes===!0});if(resolutions===null){ui.info({command:"merge",message:"Cancelled \u2014 draft kept. Run --resume again to continue."});return}await commitResolutions({fimo:args.fimo,ctx:args.ctx,from:args.from,mergeId:hydration.mergeId,resolutions})}__name(resumeMerge,"resumeMerge");function openEditorForPick(conflict){let editor=process.env.EDITOR??process.env.VISUAL??"nano",tmp=mkdtempSync(path41.join(tmpdir3(),"fimo-merge-")),file=path41.join(tmp,`${conflict.surface}-${sanitiseKey(conflict.key)}.json`),seed=conflict.childValue!==void 0?JSON.stringify(conflict.childValue,null,2):`// Replace this comment with the resolved value as JSON
|
|
2747
|
+
`)}__name(renderConflict,"renderConflict");function renderResolverHeader(conflicts,p2){let surfaceCounts=conflicts.reduce((acc,c2)=>(acc[c2.surface]=(acc[c2.surface]??0)+1,acc),{}),parts=Object.entries(surfaceCounts).map(([s,n])=>`${n} ${s}`);return p2.yellow(`! ${conflicts.length} conflict${conflicts.length===1?"":"s"} (${parts.join(", ")}) \u2014 resolve below.`)}__name(renderResolverHeader,"renderResolverHeader");function summariseValue(v){if(v===null)return"null";if(typeof v=="string")return v.length>60?v.slice(0,57)+"...":v;if(typeof v=="number"||typeof v=="boolean")return String(v);try{let s=JSON.stringify(v);return s.length>60?s.slice(0,57)+"...":s}catch{return"[unserialisable]"}}__name(summariseValue,"summariseValue");init_project_context();init_esm();var ProtectedFlowError=class extends Error{static{__name(this,"ProtectedFlowError")}env;constructor(env){super(`Refusing to run this mutating command against the protected Branch '${env}'. Use the PR/review flow or pass --allow-direct-merge to override.`),this.name="ProtectedFlowError",this.env=env}};function assertNotOnMain(env,opts={}){let protectedEnvs=opts.protectedEnvs??[DEFAULT_BRANCH];if(!opts.allowDirectMerge&&protectedEnvs.includes(env))throw new ProtectedFlowError(env)}__name(assertNotOnMain,"assertNotOnMain");async function fetchDrillContext(args){let{fimo,ctx,fromBranch,conflict,p:p2}=args,surface=conflict.surface;try{switch(surface){case"code":{let payload=await fimo.execute("branches.diffCodeFile",{projectId:ctx.projectId,branch:fromBranch,path:conflict.key,against:ctx.branch});return renderCodeFileDiff(payload,p2,{bare:!1})}case"content":{let[collection,rowId]=splitOnce2(conflict.key,":");if(!collection||!rowId)return null;let payload=await fimo.execute("branches.diffContentEntry",{projectId:ctx.projectId,branch:fromBranch,collection,rowId,against:ctx.branch});return renderContentRowDiff(payload,p2,{bare:!1})}case"translations":{let[locale,key]=splitOnce2(conflict.key,":");if(!locale||!key)return null;let payload=await fimo.execute("branches.diffLabel",{projectId:ctx.projectId,branch:fromBranch,locale,key,against:ctx.branch});return renderTranslationRowDiff(payload,p2,{bare:!1})}case"schemas":{let payload=await fimo.execute("branches.diffSchema",{projectId:ctx.projectId,branch:fromBranch,typeName:conflict.key,against:ctx.branch});return renderSchemaTypeDiff(payload,p2,{bare:!1})}case"forms":{let payload=await fimo.execute("branches.diffForm",{projectId:ctx.projectId,branch:fromBranch,formName:conflict.key,against:ctx.branch});return renderFormSchemaDiff(payload,p2,{bare:!1})}case"assets":{let payload=await fimo.execute("branches.diffAsset",{projectId:ctx.projectId,branch:fromBranch,assetId:conflict.key,against:ctx.branch});return renderAssetDiff(payload,p2,{bare:!1})}}}catch{return null}return null}__name(fetchDrillContext,"fetchDrillContext");function splitOnce2(s,sep2){let idx=s.indexOf(sep2);return idx<0?[s,""]:[s.slice(0,idx),s.slice(idx+1)]}__name(splitOnce2,"splitOnce");function portableResolution(resolution){return{...resolution,surface:resolution.surface==="translations"?"labels":resolution.surface}}__name(portableResolution,"portableResolution");function legacyConflict(conflict){return{...conflict,surface:conflict.surface==="labels"?"translations":conflict.surface}}__name(legacyConflict,"legacyConflict");function legacyMergeResult(result){return{...result,fromEnv:result.fromBranch,toEnv:result.toBranch,applied:result.applied.map(item=>({...item,surface:item.surface==="labels"?"translations":item.surface})),conflicts:result.conflicts?.map(legacyConflict)}}__name(legacyMergeResult,"legacyMergeResult");var DRAFT_DEBOUNCE_MS=1500,MERGE_POLL_MS=1e3,MERGE_WAIT_MS=10*6e4;function keepTarget(conflict){return{surface:conflict.surface,key:conflict.key,choice:"parent"}}__name(keepTarget,"keepTarget");function resumeHint(from){return`Resolve in a terminal with \`fimo merge ${from} --resume\`, keep the target value for every conflict with \`fimo merge ${from} --resume --yes\`, or resolve in Studio.`}__name(resumeHint,"resumeHint");function reportConflicts(from,ctx,mergeId,conflicts){ui.error({command:"merge",code:"MERGE_CONFLICTS",message:conflicts?`Merge ${from} \u2192 ${ctx.branch} stopped on ${conflicts.length} conflict${conflicts.length===1?"":"s"}; nothing was applied.`:`Merge ${from} \u2192 ${ctx.branch} stopped on conflicts; nothing was applied.`,details:{merge_id:mergeId,from,to:ctx.branch,...conflicts?{conflicts}:{}},hint:resumeHint(from)})}__name(reportConflicts,"reportConflicts");async function mergeCommand(from,options,cmd){let program2=cmd?.parent??cmd,branchOverride2=branchOverrideFromCommand(program2),ctx=await getProjectContext({cwd:options.cwd,branchOverride:branchOverride2}),fimo=createCliFimoClient(loadConfig(),ctx.branch);try{assertNotOnMain(ctx.branch,{allowDirectMerge:options.allowDirectMerge})}catch(err){if(err instanceof ProtectedFlowError){ui.error({command:"merge",code:"PROTECTED_FLOW",message:err.message,hint:"Pass --allow-direct-merge to merge into main. See: https://fimo.ai/docs/environments/overview#work-with-branches"});return}throw err}let isJson=currentMode().format==="json",p2=options.noColor?makeColorPalette({forceDisable:!0}):palette;if(options.resume)return resumeMerge({fimo,ctx,from,options,p:p2,isJson});isJson||mt(p2.bold(`Merging ${from} \u2192 ${ctx.branch}`));let result;try{result=legacyMergeResult(await fimo.execute("branches.merge",{projectId:ctx.projectId,branch:ctx.branch,from,allowDirectMerge:options.allowDirectMerge}))}catch(err){rethrowCliAuthError(err),ui.error({command:"merge",code:"MERGE_REQUEST_FAILED",message:`Merge failed: ${err.message}`});return}if(result.ok){ui.result({command:"merge",data:result,render:__name(rctx=>renderMergeSuccess(result,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")});return}let conflicts=result.conflicts??[];if(conflicts.length===0){ui.error({command:"merge",code:"MERGE_EMPTY_CONFLICTS",message:"Merge returned ok=false but produced no conflicts. Aborting."});return}if(isJson&&options.yes!==!0){reportConflicts(from,ctx,result.mergeId,conflicts);return}let resolutions;if(isJson?resolutions=conflicts.map(keepTarget):(O2.warn(renderResolverHeader(conflicts,p2)),resolutions=await resolveConflictsInteractive({fimo,ctx,from,mergeId:result.mergeId,conflicts,drafted:[],p:p2,acceptDefaults:options.yes===!0})),resolutions===null){await fimo.execute("branches.cancelMerge",{projectId:ctx.projectId,branch:ctx.branch,mergeId:result.mergeId}).catch(()=>{}),ui.error({command:"merge",code:"MERGE_CANCELLED",message:"Merge cancelled; compensating actions triggered server-side."});return}await commitResolutions({fimo,ctx,from,mergeId:result.mergeId,resolutions})}__name(mergeCommand,"mergeCommand");async function resolveConflictsInteractive(args){let draftedMap=new Map;for(let d3 of args.drafted)draftedMap.set(`${d3.surface}:${d3.key}`,d3);let resolutions=[...args.drafted],pendingSave=null,flush=__name(async()=>{pendingSave&&(clearTimeout(pendingSave),pendingSave=null);try{await args.fimo.execute("branches.saveMergeDraft",{projectId:args.ctx.projectId,branch:args.ctx.branch,from:args.from,mergeId:args.mergeId,resolutions:resolutions.map(portableResolution)})}catch{}},"flush"),scheduleSave=__name(()=>{pendingSave&&clearTimeout(pendingSave),pendingSave=setTimeout(()=>{flush().catch(()=>{})},DRAFT_DEBOUNCE_MS)},"scheduleSave");for(let conflict of args.conflicts){let key=`${conflict.surface}:${conflict.key}`;if(draftedMap.has(key))continue;if(await printConflictWithContext(args.fimo,args.ctx,args.from,conflict,args.p),args.acceptDefaults){resolutions.push(keepTarget(conflict)),scheduleSave();continue}let isCode=conflict.surface==="code",choice=await _t({message:"How should this conflict be resolved?",options:[{value:"parent",label:isCode?`parent \u2014 keep ${args.ctx.branch}'s file`:"parent \u2014 keep target value"},{value:"child",label:isCode?`child \u2014 take ${args.from}'s file`:"child \u2014 take source value"},{value:"pick",label:isCode?"pick \u2014 resolve conflict markers in $EDITOR":"pick \u2014 edit a custom value in $EDITOR"},{value:"abort",label:"abort \u2014 cancel the merge"}]});if(q(choice)||choice==="abort")return await flush(),null;if(choice==="pick"){let picked=isCode?await openEditorForCodePick(args.fimo,args.ctx,args.from,conflict):openEditorForPick(conflict);if(picked===null)return O2.warn("Empty buffer \u2014 treating as abort. Re-run with --resume to continue."),await flush(),null;resolutions.push({surface:conflict.surface,key:conflict.key,choice:"pick",pickedValue:picked})}else resolutions.push({surface:conflict.surface,key:conflict.key,choice});scheduleSave()}return await flush(),resolutions}__name(resolveConflictsInteractive,"resolveConflictsInteractive");async function printConflictWithContext(fimo,ctx,fromBranch,conflict,p2){console.log(renderConflict(conflict,p2));try{let drill=await fetchDrillContext({fimo,ctx,fromBranch,conflict,p:p2});drill&&console.log(drill)}catch{}}__name(printConflictWithContext,"printConflictWithContext");async function commitResolutions(args){let accepted;try{accepted=await args.fimo.execute("branches.resolveMerge",{projectId:args.ctx.projectId,branch:args.ctx.branch,from:args.from,mergeId:args.mergeId,resolutions:args.resolutions.map(portableResolution)})}catch(err){rethrowCliAuthError(err),ui.error({command:"merge",code:"MERGE_RESOLVE_FAILED",message:`Resolve failed: ${err.message}`});return}await awaitMerge({fimo:args.fimo,ctx:args.ctx,from:args.from,mergeId:accepted.mergeId})}__name(commitResolutions,"commitResolutions");async function settledMerge(args){let deadline=Date.now()+MERGE_WAIT_MS;for(;;){let merge=await args.fimo.execute("branches.mergeStatus",{projectId:args.ctx.projectId,mergeId:args.mergeId});if(merge.status!=="in_progress"||Date.now()>=deadline)return merge;await new Promise(resolve10=>setTimeout(resolve10,MERGE_POLL_MS))}}__name(settledMerge,"settledMerge");async function awaitMerge(args){let sp=spinner(`Applying merge ${args.from} \u2192 ${args.ctx.branch}`),merge;try{merge=await settledMerge(args)}catch(err){rethrowCliAuthError(err),ui.error({command:"merge",code:"MERGE_STATUS_FAILED",message:`Merge ${args.mergeId} was accepted, but reading its status failed: ${err.message}`,details:{merge_id:args.mergeId},hint:`Run \`fimo merge ${args.from} --resume\` to follow it; it does not resubmit.`});return}finally{sp.stop()}let details={merge_id:merge.mergeId,from:merge.fromBranch,to:merge.toBranch};switch(merge.status){case"complete":{let result={ok:!0,mergeId:merge.mergeId,fromBranch:merge.fromBranch,toBranch:merge.toBranch,fromEnv:merge.fromBranch,toEnv:merge.toBranch,...merge.summary?{summary:merge.summary}:{}};ui.result({command:"merge",data:result,render:__name(rctx=>renderMergeSuccess(result,rctx.color?palette:makeColorPalette({forceDisable:!0})),"render")});return}case"conflicts":reportConflicts(args.from,args.ctx,merge.mergeId);return;case"in_progress":ui.error({command:"merge",code:"MERGE_IN_PROGRESS",message:`Merge ${merge.mergeId} is still applying after ${MERGE_WAIT_MS/6e4} minutes.`,details,hint:`Run \`fimo merge ${args.from} --resume\` to keep following it; it does not resubmit.`});return;case"rolled_back":ui.error({command:"merge",code:"MERGE_CANCELLED",message:`Merge ${merge.mergeId} was rolled back${merge.error?`: ${merge.error}`:""}.`,details});return;case"failed":ui.error({command:"merge",code:"MERGE_FAILED",message:`Merge ${merge.mergeId} failed${merge.error?`: ${merge.error}`:""}.`,details,hint:`Run \`fimo merge ${args.from}\` to start a new merge.`});return}}__name(awaitMerge,"awaitMerge");async function resumeMerge(args){let hydration;try{let portableHydration=await args.fimo.execute("branches.mergeConflicts",{projectId:args.ctx.projectId,branch:args.ctx.branch,from:args.from});hydration={...portableHydration,conflicts:portableHydration.conflicts.map(legacyConflict),draftResolutions:portableHydration.draftResolutions.map(resolution=>({...resolution,surface:resolution.surface==="labels"?"translations":resolution.surface}))}}catch(err){rethrowCliAuthError(err),ui.error({command:"merge",code:"MERGE_RESUME_FAILED",message:`Failed to load in-progress merge: ${err.message}`});return}if(hydration.status==="in_progress"){await awaitMerge({fimo:args.fimo,ctx:args.ctx,from:args.from,mergeId:hydration.mergeId});return}if(hydration.status!=="conflicts"){ui.error({command:"merge",code:"MERGE_NOT_RESUMABLE",message:`Merge ${hydration.mergeId} is ${hydration.status}; nothing to resume.`});return}if(hydration.conflicts.length===0){args.isJson||O2.info("No conflicts to resolve \u2014 submitting empty batch."),await commitResolutions({fimo:args.fimo,ctx:args.ctx,from:args.from,mergeId:hydration.mergeId,resolutions:[]});return}if(args.isJson){let drafted=new Set(hydration.draftResolutions.map(d3=>`${d3.surface}:${d3.key}`)),unanswered=hydration.conflicts.filter(c2=>!drafted.has(`${c2.surface}:${c2.key}`));if(unanswered.length>0&&args.options.yes!==!0){reportConflicts(args.from,args.ctx,hydration.mergeId,unanswered);return}await commitResolutions({fimo:args.fimo,ctx:args.ctx,from:args.from,mergeId:hydration.mergeId,resolutions:[...hydration.draftResolutions,...unanswered.map(keepTarget)]});return}mt(args.p.bold(`Resuming merge ${args.from} \u2192 ${args.ctx.branch}`)),O2.info(`${hydration.draftResolutions.length} of ${hydration.conflicts.length} conflict${hydration.conflicts.length===1?"":"s"} already drafted`);let resolutions=await resolveConflictsInteractive({fimo:args.fimo,ctx:args.ctx,from:args.from,mergeId:hydration.mergeId,conflicts:hydration.conflicts,drafted:hydration.draftResolutions,p:args.p,acceptDefaults:args.options.yes===!0});if(resolutions===null){ui.info({command:"merge",message:"Cancelled \u2014 draft kept. Run --resume again to continue."});return}await commitResolutions({fimo:args.fimo,ctx:args.ctx,from:args.from,mergeId:hydration.mergeId,resolutions})}__name(resumeMerge,"resumeMerge");function openEditorForPick(conflict){let editor=process.env.EDITOR??process.env.VISUAL??"nano",tmp=mkdtempSync(path41.join(tmpdir3(),"fimo-merge-")),file=path41.join(tmp,`${conflict.surface}-${sanitiseKey(conflict.key)}.json`),seed=conflict.childValue!==void 0?JSON.stringify(conflict.childValue,null,2):`// Replace this comment with the resolved value as JSON
|
|
2748
2748
|
""`;writeFileSync5(file,seed,"utf8"),spawnSync3(editor,[file],{stdio:"inherit"});let raw=readFileSync11(file,"utf8").trim();if(raw===""||raw===seed.trim())return null;try{return JSON.parse(raw)}catch{return raw}}__name(openEditorForPick,"openEditorForPick");async function openEditorForCodePick(fimo,ctx,fromBranch,conflict){let filePath=conflict.code?.path??conflict.key,seed="",seedLoaded=!1;try{seed=(await fimo.execute("branches.codeConflict",{projectId:ctx.projectId,branch:ctx.branch,from:fromBranch,path:filePath})).result.content??"",seedLoaded=!0}catch{O2.warn(`Could not load the 3-way merge for ${filePath}; leaving it unresolved. Re-run with --resume.`)}let editor=process.env.EDITOR??process.env.VISUAL??"nano",tmp=mkdtempSync(path41.join(tmpdir3(),"fimo-merge-")),ext=path41.extname(filePath)||".txt",file=path41.join(tmp,`${sanitiseKey(filePath)}${ext}`);writeFileSync5(file,seed,"utf8"),spawnSync3(editor,[file],{stdio:"inherit"});let raw=readFileSync11(file,"utf8");return raw.trim()===""&&(seed.trim()!==""||!seedLoaded)?null:((raw.includes("<<<<<<<")||raw.includes(">>>>>>>"))&&O2.warn("Conflict markers remain \u2014 they will be committed as-is. Re-run with --resume to fix."),raw)}__name(openEditorForCodePick,"openEditorForCodePick");function sanitiseKey(key){return key.replace(/[^A-Za-z0-9._-]/g,"_").slice(0,60)}__name(sanitiseKey,"sanitiseKey");init_esm();init_dist();init_auth();init_config();init_project_services();import fs39 from"node:fs";import path42 from"node:path";init_project2();var MIGRATION_DIR=path42.join(".fimo","migration"),MigrateCommandError=class extends Error{static{__name(this,"MigrateCommandError")}code;hint;constructor(code2,message,opts={}){super(message),this.code=code2,opts.hint!==void 0&&(this.hint=opts.hint)}},MigrateCancelled=class extends Error{static{__name(this,"MigrateCancelled")}constructor(message="Cancelled."){super(message)}};function emitMigrateError(command,error,fallbackCode){if(error instanceof MigrateCancelled){ui.info({command,message:error.message});return}if(error instanceof MigrateCommandError){ui.error({command,code:error.code,message:error.message,...error.hint?{hint:error.hint}:{}});return}ui.error({command,code:fallbackCode,message:error instanceof Error?error.message:String(error)})}__name(emitMigrateError,"emitMigrateError");function isMigrationSourceUrl(value){let target=value.trim();return/^https?:\/\//i.test(target)?!0:/^[a-z0-9-]+(\.[a-z0-9-]+)+(:\d+)?(\/|$)/i.test(target)}__name(isMigrationSourceUrl,"isMigrationSourceUrl");async function migrateInitCommand(targetArg,options){let command="migrate init";try{let{receipt,scaffoldWarnings}=await runMigrateInit(targetArg??options.cwd,options);await reportMigration(receipt.project_id,"didStartMigration",{sourcePlatform:receipt.source_platform}),await reportMigration(receipt.project_id,"didEndMigration",{sourcePlatform:receipt.source_platform,success:!0}),ui.result({command,data:receipt,render:__name(()=>renderInitReceipt(receipt),"render"),warnings:scaffoldWarnings.length>0?scaffoldWarnings:void 0,hint:`Load the fimo-migration skill (\`fimo skills get fimo-migration\`), read the source site yourself, and plan the migration in ${path42.join(receipt.migration_dir,"migration-plan.md")}`})}catch(error){emitMigrateError(command,error,"COMMAND_FAILED")}}__name(migrateInitCommand,"migrateInitCommand");async function runMigrateInit(dirArg,options){if(!dirArg)throw new MigrateCommandError("DIRECTORY_REQUIRED","A target project directory is required.",{hint:"Run `fimo migrate init <dir> --project-id <projectId>`, or `--org <organizationId>` to create a new site."});if(isMigrationSourceUrl(dirArg))throw new MigrateCommandError("DIRECTORY_REQUIRED","`fimo migrate init` takes a target directory, not a URL.",{hint:"Set the target up with `fimo migrate init <dir> --project-id <projectId>` (or `--org <organizationId>`), then read the source site yourself with a browser \u2014 the CLI no longer crawls it."});let sourcePlatform=parseSourcePlatform(options.sourcePlatform),explicitDir=path42.resolve(dirArg);if(fs39.existsSync(resolveProjectSettingsPath(explicitDir))){let settings=loadProjectSettings(explicitDir);if(options.projectId&&options.projectId!==settings.projectId)throw new MigrateCommandError("PROJECT_ID_MISMATCH",`${explicitDir} is already linked to project ${settings.projectId}, not ${options.projectId}.`,{hint:"Drop --project-id to reuse the existing link, or pass a different target directory."});let framework=assertRequestedFramework(explicitDir,options.framework);return{receipt:buildInitReceipt(explicitDir,settings.projectId,settings.name,requireMigrateAuth(),framework,sourcePlatform),scaffoldWarnings:[]}}if(fs39.existsSync(explicitDir)&&fs39.readdirSync(explicitDir).length>0)throw new MigrateCommandError("DIRECTORY_NOT_EMPTY",`Refusing to set up a migration target in non-empty directory ${explicitDir}.`,{hint:"Pass a linked Fimo site directory or an empty/new directory."});let outcome=await runInit(dirArg,{...options,framework:options.framework??"react-router",skills:!1,origin:"migration"});switch(outcome.status){case"ok":{let creds=readCredentials(loadConfig());return{receipt:buildInitReceipt(outcome.data.target_dir,outcome.data.project_id,outcome.data.project_name,creds?.user?.email??null,assertRequestedFramework(outcome.data.target_dir,options.framework),sourcePlatform),scaffoldWarnings:outcome.warnings}}case"cancelled":throw new MigrateCancelled;case"info":throw new MigrateCancelled(outcome.message);case"error":throw new MigrateCommandError(outcome.code,outcome.message,{hint:outcome.code==="NOT_AUTHENTICATED"?"Run `fimo login` first, then re-run `fimo migrate init`.":outcome.hint})}}__name(runMigrateInit,"runMigrateInit");function parseSourcePlatform(value){let normalized=value?.trim().toLowerCase();if(!normalized)return"unknown";let platform4=MIGRATION_SOURCE_PLATFORMS.find(candidate=>candidate===normalized);if(!platform4)throw new MigrateCommandError("SOURCE_PLATFORM_INVALID",`Unknown source platform "${value}".`,{hint:`Use one of: ${MIGRATION_SOURCE_PLATFORMS.join(", ")}.`});return platform4}__name(parseSourcePlatform,"parseSourcePlatform");async function reportMigration(projectId2,event,properties){try{await createTelemetryService(loadConfig()).trackProjectEvent(projectId2,event,properties)}catch{}}__name(reportMigration,"reportMigration");function requireMigrateAuth(){try{return requireAccountCredentials(loadConfig()).user?.email??null}catch(error){throw error instanceof AccountRequiredError?new MigrateCommandError("REQUIRES_ACCOUNT","Migrating into Fimo needs a Fimo account.",{hint:REQUIRES_ACCOUNT_HINT}):new MigrateCommandError("NOT_AUTHENTICATED","You are not signed in to Fimo.",{hint:"Run `fimo login` first, then re-run `fimo migrate init`."})}}__name(requireMigrateAuth,"requireMigrateAuth");function buildInitReceipt(projectRoot,projectId2,projectName,user,framework,sourcePlatform){let migrationDir=path42.join(projectRoot,MIGRATION_DIR);return fs39.mkdirSync(migrationDir,{recursive:!0}),{mode:"source-backed",authenticated:!0,user,project_id:projectId2,project_name:projectName,target_dir:projectRoot,migration_dir:migrationDir,framework,source_platform:sourcePlatform,ready:!0}}__name(buildInitReceipt,"buildInitReceipt");function readTargetFramework(projectRoot){let configPath=resolveProjectConfigPath(projectRoot);if(!fs39.existsSync(configPath))return null;try{let config=JSON.parse(fs39.readFileSync(configPath,"utf8"));return typeof config.runtime?.framework=="string"?config.runtime.framework:null}catch{return null}}__name(readTargetFramework,"readTargetFramework");function assertRequestedFramework(projectRoot,requestedFramework){let actualFramework=readTargetFramework(projectRoot);if(!requestedFramework)return actualFramework;let requested=requestedFramework.trim().toLowerCase();if(!actualFramework||actualFramework.trim().toLowerCase()!==requested)throw new MigrateCommandError("FRAMEWORK_MISMATCH",actualFramework?`Migration target uses ${actualFramework}, but ${requestedFramework} was requested.`:`Migration target does not declare runtime.framework, but ${requestedFramework} was requested.`,{hint:"Recreate or relink the target with the requested framework before importing migration data."});return actualFramework}__name(assertRequestedFramework,"assertRequestedFramework");function renderInitReceipt(receipt){return["Mode: source-backed",`Auth: signed in${receipt.user?` as ${receipt.user}`:""}`,`Project: ${receipt.project_name} (${receipt.project_id})`,`Target: ${receipt.target_dir} (linked)`,`Framework: ${receipt.framework??"unknown"}`,`Source: ${receipt.source_platform}`,`Migration dir: ${receipt.migration_dir}`,"Ready: yes \u2014 no schemas, entries, assets, or forms were written"].join(`
|
|
2749
2749
|
`)}__name(renderInitReceipt,"renderInitReceipt");init_dist();init_project_context();function padRight(s,width){return s.length>=width?s:s+" ".repeat(width-s.length)}__name(padRight,"padRight");function fmtUsd(n){let trimmed=n.toFixed(4).replace(/0+$/,"").replace(/\.$/,"");return trimmed.includes(".")?trimmed:`${trimmed}.00`}__name(fmtUsd,"fmtUsd");function priceRate(price){let unit=price.unit.replace(/s$/,"");return`${price.confidence==="metered"?"~":""}$${fmtUsd(price.unitPrice)} / ${unit}`}__name(priceRate,"priceRate");function bestFor(description){let start=description.indexOf("Best for:");if(start===-1)return`${description.split(". ")[0]}.`;let rest=description.slice(start),notFor=rest.indexOf("Not for:");return(notFor===-1?rest:rest.slice(0,notFor)).replace(/^Best for:\s*/,"").trim()}__name(bestFor,"bestFor");function flagSignature(flag2){if(flag2.type==="boolean")return`--${flag2.name}`;let type=flag2.enumValues?.length?flag2.enumValues.join("|"):flag2.type;return`--${flag2.name} <${type}>`}__name(flagSignature,"flagSignature");function flagMeta(flag2){let parts=[flag2.required?"required":"optional"];return flag2.isArray&&parts.push("repeatable"),flag2.defaultValue!==void 0&&parts.push(`default ${JSON.stringify(flag2.defaultValue)}`),parts.join(", ")}__name(flagMeta,"flagMeta");function flagExample(flag2){let name=`--${flag2.name}`;if(flag2.type==="boolean")return flag2.defaultValue===!0?`--no-${flag2.name}`:name;let value;return flag2.enumValues?.length?value=String(flag2.enumValues[0]):/url|image/i.test(flag2.name)?value="<url>":flag2.type==="integer"||flag2.type==="number"?value=flag2.defaultValue!==void 0?String(flag2.defaultValue):"<n>":value='"\u2026"',flag2.isArray?`${name} ${value} ${name} ${value}`:`${name} ${value}`}__name(flagExample,"flagExample");async function modelsListCommand(opts){let context=await getProjectContext({cwd:opts.cwd}),models=await createModelCatalogService().list(context.projectId,{modality:opts.modality,tag:opts.tag,q:opts.search,category:opts.category});if(models.length===0){ui.info({command:"models list",message:"No models match the filter."});return}ui.result({command:"models list",data:{models},render:__name(()=>renderModelsListHuman(models,opts.extended===!0),"render")})}__name(modelsListCommand,"modelsListCommand");function renderModelsListHuman(models,extended){let groups=new Map;for(let m of models){let arr=groups.get(m.modality)??[];arr.push(m),groups.set(m.modality,arr)}let modalityOrder=["image","video","audio"],sortedModalities=Array.from(groups.keys()).sort((a,b)=>modalityOrder.indexOf(a)-modalityOrder.indexOf(b)),out=[],first=!0;for(let modality of sortedModalities){first||out.push(""),first=!1;let group=groups.get(modality)??[];if(out.push(modality.toUpperCase()),extended){for(let m of group)out.push(renderExtendedEntry(m));continue}let nameWidth=Math.max(...group.map(m=>m.id.length));for(let m of group){let headline=m.description.split(". ")[0],tags=m.tags.length>0?`[${m.tags.join(", ")}]`:"",price=m.price?` ${priceRate(m.price)}`:"";out.push(` ${padRight(m.id,nameWidth)} ${tags}${price}`),out.push(` ${padRight("",nameWidth)} ${headline}.`)}}return out.join(`
|
|
2750
2750
|
`)}__name(renderModelsListHuman,"renderModelsListHuman");function renderExtendedEntry(m){let required=m.flags.filter(f=>f.required).map(f=>`--${f.name}`),optionalCount=m.flags.length-required.length,lines=[],row2=__name((label,value)=>{lines.push(` ${`${label}:`.padEnd(10)}${value}`)},"row"),flagsValue=m.flags.length===0?"none":`${required.length?`${required.join(", ")} (required)`:"none required"}${optionalCount?`, ${optionalCount} more`:""} \u2014 fimo models show ${m.id}`;return lines.push(` ${m.id} (${m.provider})`),row2("tags",m.tags.join(", ")||"\u2014"),m.price&&row2("price",priceRate(m.price)),row2("best for",bestFor(m.description)),row2("flags",flagsValue),lines.join(`
|
|
@@ -2860,10 +2860,10 @@ Header values use Name=secret:KEY, Name=bearer:KEY, Name=token:KEY, or Name=lite
|
|
|
2860
2860
|
`)}__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(`
|
|
2861
2861
|
`).map(line=>` ${line}`).join(`
|
|
2862
2862
|
`)}__name(indentBlock,"indentBlock");init_sdk_transport();init_color();init_project_context();function computeVersionString(){let pkgVersion="0.0.0";try{let pkg=JSON.parse(fs47.readFileSync(path51.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(fs47.readFileSync(path51.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(path52){if(!(currentMode().format!=="pretty"||NO_UNCLAIMED_REMINDER.has(path52)))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}
|
|
2863
|
-
`)}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
|
|
2863
|
+
`)}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 the site default Branch)").action(cloneCommand);registerLinkCommand(program);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 the site default Branch)").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("-y, --yes","Accepted for compatibility: `fimo new` never 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("--description <text>","Why the change was made: the commit body for any uncommitted changes, read later by teammates and agents").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.").option("--force","Deploy even if validation fails (escape hatch; may still fail later in the sandbox)").addOption(new Option("--no-restart","Deprecated: has no effect").hideHelp()).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",`
|
|
2864
2864
|
Logs come from the sandbox's own process buffers, so they end when the sandbox does.
|
|
2865
2865
|
There is no --follow; re-run the command instead.
|
|
2866
|
-
`).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("Fast-forward the local checkout to the current Branch's code on Fimo").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","Keep the target Branch's value for every unresolved conflict (non-interactive)").option("--resume","Resume a parked merge from its saved draft, or follow one that is still applying").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);registerSiteCommands(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").addHelpText("after",`
|
|
2866
|
+
`).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 the site default Branch)").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("Fast-forward the local checkout to the current Branch's code on Fimo").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 the Branch it was created from, else 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","Keep the target Branch's value for every unresolved conflict (non-interactive)").option("--resume","Resume a parked merge from its saved draft, or follow one that is still applying").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);registerSiteCommands(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").addHelpText("after",`
|
|
2867
2867
|
Examples (BlogPost must have a title field):
|
|
2868
2868
|
fimo entries create BlogPost --body '{"data":{"slug":"hello","title":"Hello"}}'
|
|
2869
2869
|
fimo entries list BlogPost --where '{"slug":"hello"}'
|
|
@@ -2871,7 +2871,28 @@ Examples (BlogPost must have a title field):
|
|
|
2871
2871
|
fimo entries update BlogPost <id> --body '{"data":{"title":"Updated"}}'
|
|
2872
2872
|
|
|
2873
2873
|
Use the UUID returned as id by create/list for get, update, and delete.
|
|
2874
|
-
The content type is positional. Create/update require --body; JSON files use bulk-create/bulk-update.`);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 UUID returned as id by create/list").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 body, e.g. '{"data":{"slug":"hello","title":"Hello"}}'`).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 UUID returned as id by create/list").option("-C, --cwd <dir>","Site directory").requiredOption("--body <json>",`Entry body, e.g. '{"data":{"title":"Updated"}}'`).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 UUID returned as id by create/list").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").
|
|
2874
|
+
The content type is positional. Create/update require --body; JSON files use bulk-create/bulk-update.`);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 UUID returned as id by create/list").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 body, e.g. '{"data":{"slug":"hello","title":"Hello"}}'`).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 UUID returned as id by create/list").option("-C, --cwd <dir>","Site directory").requiredOption("--body <json>",`Entry body, e.g. '{"data":{"title":"Updated"}}'`).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 UUID returned as id by create/list").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").addHelpText("after",`
|
|
2875
|
+
One SELECT that reads only the entries table. Writes are rejected. Limits: 5 seconds, 1,000 rows.
|
|
2876
|
+
|
|
2877
|
+
Columns (one row per locale variant):
|
|
2878
|
+
document_id Stable entry id. Other fimo commands, references and the API use it.
|
|
2879
|
+
id Internal id of one locale variant. Do not pass it to other commands.
|
|
2880
|
+
content_type Type name, e.g. 'BlogPost'
|
|
2881
|
+
locale Locale code; null when the type is not localized
|
|
2882
|
+
slug, created_at, updated_at
|
|
2883
|
+
data JSONB schema fields, e.g. data->>'title'
|
|
2884
|
+
Select only the columns you need. When rows feed another fimo command, select document_id AS id and use locale to pick the variant.
|
|
2885
|
+
|
|
2886
|
+
Example:
|
|
2887
|
+
fimo entries query --sql "SELECT locale, data->>'format' AS format, count(*) FROM entries WHERE content_type = 'Story' GROUP BY 1, 2"`).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").option("--locale <locale>","Entry locale to update (defaults to the site locale)").addHelpText("after",`
|
|
2888
|
+
Same change for many entries (--body with --ids or --where):
|
|
2889
|
+
fimo entries bulk-update BlogPost --where '{"status":"draft"}' --body '{"data":{"status":"published"}}'
|
|
2890
|
+
fimo entries bulk-update BlogPost --ids <id1>,<id2> --locale es --body '{"data":{"featured":true}}'
|
|
2891
|
+
|
|
2892
|
+
A different change for each entry (--file or --stdin, no --body): a JSON array of {id, body}
|
|
2893
|
+
[{"id":"<id1>","body":{"data":{"title":"New title"}}},{"id":"<id2>","body":{"data":{"featured":true}}}]
|
|
2894
|
+
|
|
2895
|
+
One request writes at most 1,000 entries. An invalid entry saves none of them; IDs that are not found are listed in meta.missing.`).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").addHelpText("after",`
|
|
2875
2896
|
Example: fimo assets upload ./hero.jpg --name "Hero Image"
|
|
2876
2897
|
Set alt text in the content media field or rendering component.`).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=`
|
|
2877
2898
|
Supported agents:
|