fimo 0.11.0-staging.2 → 0.11.0-staging.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -39,7 +39,7 @@ Expecting one of '${allowedValues.join("', '")}'`);return this._lifeCycleHooks[e
39
39
  `),this.outputHelp({error:!0}));let config=errorOptions||{},exitCode=config.exitCode||1,code2=config.code||"commander.error";this._exit(exitCode,code2,message)}_parseOptionsEnv(){this.options.forEach(option=>{if(option.envVar&&option.envVar in process8.env){let optionKey=option.attributeName();(this.getOptionValue(optionKey)===void 0||["default","config","env"].includes(this.getOptionValueSource(optionKey)))&&(option.required||option.optional?this.emit(`optionEnv:${option.name()}`,process8.env[option.envVar]):this.emit(`optionEnv:${option.name()}`))}})}_parseOptionsImplied(){let dualHelper=new DualOptions(this.options),hasCustomOptionValue=__name(optionKey=>this.getOptionValue(optionKey)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(optionKey)),"hasCustomOptionValue");this.options.filter(option=>option.implied!==void 0&&hasCustomOptionValue(option.attributeName())&&dualHelper.valueFromOption(this.getOptionValue(option.attributeName()),option)).forEach(option=>{Object.keys(option.implied).filter(impliedKey=>!hasCustomOptionValue(impliedKey)).forEach(impliedKey=>{this.setOptionValueWithSource(impliedKey,option.implied[impliedKey],"implied")})})}missingArgument(name){let message=`error: missing required argument '${name}'`;this.error(message,{code:"commander.missingArgument"})}optionMissingArgument(option){let message=`error: option '${option.flags}' argument missing`;this.error(message,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(option){let message=`error: required option '${option.flags}' not specified`;this.error(message,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(option,conflictingOption){let findBestOptionFromValue=__name(option2=>{let optionKey=option2.attributeName(),optionValue=this.getOptionValue(optionKey),negativeOption=this.options.find(target=>target.negate&&optionKey===target.attributeName()),positiveOption=this.options.find(target=>!target.negate&&optionKey===target.attributeName());return negativeOption&&(negativeOption.presetArg===void 0&&optionValue===!1||negativeOption.presetArg!==void 0&&optionValue===negativeOption.presetArg)?negativeOption:positiveOption||option2},"findBestOptionFromValue"),getErrorMessage=__name(option2=>{let bestOption=findBestOptionFromValue(option2),optionKey=bestOption.attributeName();return this.getOptionValueSource(optionKey)==="env"?`environment variable '${bestOption.envVar}'`:`option '${bestOption.flags}'`},"getErrorMessage"),message=`error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;this.error(message,{code:"commander.conflictingOption"})}unknownOption(flag2){if(this._allowUnknownOption)return;let suggestion="";if(flag2.startsWith("--")&&this._showSuggestionAfterError){let candidateFlags=[],command=this;do{let moreFlags=command.createHelp().visibleOptions(command).filter(option=>option.long).map(option=>option.long);candidateFlags=candidateFlags.concat(moreFlags),command=command.parent}while(command&&!command._enablePositionalOptions);suggestion=suggestSimilar(flag2,candidateFlags)}let message=`error: unknown option '${flag2}'${suggestion}`;this.error(message,{code:"commander.unknownOption"})}_excessArguments(receivedArgs){if(this._allowExcessArguments)return;let expected=this.registeredArguments.length,s=expected===1?"":"s",message=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;this.error(message,{code:"commander.excessArguments"})}unknownCommand(){let unknownName=this.args[0],suggestion="";if(this._showSuggestionAfterError){let candidateNames=[];this.createHelp().visibleCommands(this).forEach(command=>{candidateNames.push(command.name()),command.alias()&&candidateNames.push(command.alias())}),suggestion=suggestSimilar(unknownName,candidateNames)}let message=`error: unknown command '${unknownName}'${suggestion}`;this.error(message,{code:"commander.unknownCommand"})}version(str,flags,description){if(str===void 0)return this._version;this._version=str,flags=flags||"-V, --version",description=description||"output the version number";let versionOption=this.createOption(flags,description);return this._versionOptionName=versionOption.attributeName(),this._registerOption(versionOption),this.on("option:"+versionOption.name(),()=>{this._outputConfiguration.writeOut(`${str}
40
40
  `),this._exit(0,"commander.version",str)}),this}description(str,argsDescription){return str===void 0&&argsDescription===void 0?this._description:(this._description=str,argsDescription&&(this._argsDescription=argsDescription),this)}summary(str){return str===void 0?this._summary:(this._summary=str,this)}alias(alias){if(alias===void 0)return this._aliases[0];let command=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(command=this.commands[this.commands.length-1]),alias===command._name)throw new Error("Command alias can't be the same as its name");let matchingCommand=this.parent?._findCommand(alias);if(matchingCommand){let existingCmd=[matchingCommand.name()].concat(matchingCommand.aliases()).join("|");throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`)}return command._aliases.push(alias),this}aliases(aliases2){return aliases2===void 0?this._aliases:(aliases2.forEach(alias=>this.alias(alias)),this)}usage(str){if(str===void 0){if(this._usage)return this._usage;let args=this.registeredArguments.map(arg=>humanReadableArgName(arg));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?args:[]).join(" ")}return this._usage=str,this}name(str){return str===void 0?this._name:(this._name=str,this)}nameFromFilename(filename){return this._name=path47.basename(filename,path47.extname(filename)),this}executableDir(path48){return path48===void 0?this._executableDir:(this._executableDir=path48,this)}helpInformation(contextOptions){let helper=this.createHelp(),context=this._getOutputContext(contextOptions);helper.prepareContext({error:context.error,helpWidth:context.helpWidth,outputHasColors:context.hasColors});let text3=helper.formatHelp(this,helper);return context.hasColors?text3:this._outputConfiguration.stripColor(text3)}_getOutputContext(contextOptions){contextOptions=contextOptions||{};let error=!!contextOptions.error,baseWrite,hasColors,helpWidth;return error?(baseWrite=__name(str=>this._outputConfiguration.writeErr(str),"baseWrite"),hasColors=this._outputConfiguration.getErrHasColors(),helpWidth=this._outputConfiguration.getErrHelpWidth()):(baseWrite=__name(str=>this._outputConfiguration.writeOut(str),"baseWrite"),hasColors=this._outputConfiguration.getOutHasColors(),helpWidth=this._outputConfiguration.getOutHelpWidth()),{error,write:__name(str=>(hasColors||(str=this._outputConfiguration.stripColor(str)),baseWrite(str)),"write"),hasColors,helpWidth}}outputHelp(contextOptions){let deprecatedCallback;typeof contextOptions=="function"&&(deprecatedCallback=contextOptions,contextOptions=void 0);let outputContext=this._getOutputContext(contextOptions),eventContext={error:outputContext.error,write:outputContext.write,command:this};this._getCommandAndAncestors().reverse().forEach(command=>command.emit("beforeAllHelp",eventContext)),this.emit("beforeHelp",eventContext);let helpInformation=this.helpInformation({error:outputContext.error});if(deprecatedCallback&&(helpInformation=deprecatedCallback(helpInformation),typeof helpInformation!="string"&&!Buffer.isBuffer(helpInformation)))throw new Error("outputHelp callback must return a string or a Buffer");outputContext.write(helpInformation),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",eventContext),this._getCommandAndAncestors().forEach(command=>command.emit("afterAllHelp",eventContext))}helpOption(flags,description){return typeof flags=="boolean"?(flags?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(flags=flags??"-h, --help",description=description??"display help for command",this._helpOption=this.createOption(flags,description),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(option){return this._helpOption=option,this}help(contextOptions){this.outputHelp(contextOptions);let exitCode=Number(process8.exitCode??0);exitCode===0&&contextOptions&&typeof contextOptions!="function"&&contextOptions.error&&(exitCode=1),this._exit(exitCode,"commander.help","(outputHelp)")}addHelpText(position,text3){let allowedValues=["beforeAll","before","after","afterAll"];if(!allowedValues.includes(position))throw new Error(`Unexpected value for position to addHelpText.
41
41
  Expecting one of '${allowedValues.join("', '")}'`);let helpEvent=`${position}Help`;return this.on(helpEvent,context=>{let helpStr;typeof text3=="function"?helpStr=text3({error:context.error,command:context.command}):helpStr=text3,helpStr&&context.write(`${helpStr}
42
- `)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();helpOption&&args.find(arg=>helpOption.is(arg))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;return(match=arg.match(/^(--inspect(-brk)?)$/))!==null?debugOption=match[1]:(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(debugOption=match[1],/^\d+$/.test(match[3])?debugPort=match[3]:debugHost=match[3]):(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match[1],debugHost=match[3],debugPort=match[4]),debugOption&&debugPort!=="0"?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}__name(incrementNodeInspectorPort,"incrementNodeInspectorPort");function useColor(){if(process8.env.NO_COLOR||process8.env.FORCE_COLOR==="0"||process8.env.FORCE_COLOR==="false")return!1;if(process8.env.FORCE_COLOR||process8.env.CLICOLOR_FORCE!==void 0)return!0}__name(useColor,"useColor");exports2.Command=Command2;exports2.useColor=useColor}});var require_commander=__commonJS({"../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js"(exports2){var{Argument:Argument2}=require_argument(),{Command:Command2}=require_command(),{CommanderError:CommanderError2,InvalidArgumentError:InvalidArgumentError2}=require_error(),{Help:Help2}=require_help(),{Option:Option2}=require_option();exports2.program=new Command2;exports2.createCommand=name=>new Command2(name);exports2.createOption=(flags,description)=>new Option2(flags,description);exports2.createArgument=(name,description)=>new Argument2(name,description);exports2.Command=Command2;exports2.Option=Option2;exports2.Argument=Argument2;exports2.Help=Help2;exports2.CommanderError=CommanderError2;exports2.InvalidArgumentError=InvalidArgumentError2;exports2.InvalidOptionArgumentError=InvalidArgumentError2}});import{z}from"zod";function filterUnknownProperties(data2,schema){if(data2==null)return data2;if(schema instanceof z.ZodOptional||schema instanceof z.ZodNullable||schema instanceof z.ZodDefault)return filterUnknownProperties(data2,schema.unwrap());if(schema instanceof z.ZodArray){if(!Array.isArray(data2))return data2;let itemSchema=schema.unwrap();return data2.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z.ZodDiscriminatedUnion){if(typeof data2!="object"||data2===null)return data2;let unionSchema=schema,discriminator=unionSchema.def.discriminator,discriminatorValue=data2[discriminator],matchingSchema=unionSchema.options.find(option=>{let discriminatorField=option.shape[discriminator];return discriminatorField instanceof z.ZodLiteral?discriminatorField.def.values.includes(discriminatorValue):!1});return matchingSchema?filterUnknownProperties(data2,matchingSchema):data2}if(schema instanceof z.ZodObject){if(typeof data2!="object")return data2;let shape=schema.shape,result={};for(let key in shape)if(Object.prototype.hasOwnProperty.call(data2,key)){let fieldSchema=shape[key],fieldValue=data2[key];result[key]=filterUnknownProperties(fieldValue,fieldSchema)}if(schema.def.catchall instanceof z.ZodUnknown)for(let[key,value]of Object.entries(data2))key in shape||(result[key]=value);return result}return data2}function createObjectDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)},partial(){let partialSchema=schema.partial();return createObjectDTO(partialSchema)},pick(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),picked=schema.pick(mask);return createObjectDTO(picked)},omit(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),omitted=schema.omit(mask);return createObjectDTO(omitted)}}}function createDiscriminatedUnionDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)}}}function createDTO(schema){if(schema instanceof z.ZodObject)return createObjectDTO(schema);if(schema instanceof z.ZodDiscriminatedUnion)return createDiscriminatedUnionDTO(schema);throw new Error(`Unsupported schema type: ${schema.constructor.name}. createDTO supports ZodObject and ZodDiscriminatedUnion.`)}var init_create_dto=__esm({"../../packages/api-contracts/dist/esm/utils/create-dto.js"(){"use strict";__name(filterUnknownProperties,"filterUnknownProperties");__name(createObjectDTO,"createObjectDTO");__name(createDiscriminatedUnionDTO,"createDiscriminatedUnionDTO");__name(createDTO,"createDTO")}});import{z as z2}from"zod";function createCursorPageDataSchema(dataSchema){return z2.object({items:z2.array(dataSchema),nextCursor:z2.string().nullable()})}function createCursorPaginatedResponseSchema(dataSchema){return z2.object({data:createCursorPageDataSchema(dataSchema)})}var createResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema=__name(dataSchema=>z2.object({data:dataSchema}),"createResponseSchema");__name(createCursorPageDataSchema,"createCursorPageDataSchema");__name(createCursorPaginatedResponseSchema,"createCursorPaginatedResponseSchema")}});import{z as z3}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z3.object({page:z3.coerce.number().int().positive().default(1),limit:z3.coerce.number().int().positive().max(100).default(20)})}});import{z as z4}from"zod";var CommonSchemas,BaseEntitySchema,ProjectRoleKeySchema,ProjectRoleKeyWithSystemSchema,ProjectPrincipalTypeSchema,ProjectVisibilitySchema,ProjectStatusSchema,ProjectInviteStatusSchema,PublicationStatusSchema,OrganizationRoleSchema,AssetTypeSchema,TemplateCodeSchema,FieldTypeSchema,RESERVED_CONTENT_FIELD_NAMES,CONTENT_TYPE_NAME_PATTERN,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION,CONTENT_FIELD_NAME_PATTERN,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION,init_common=__esm({"../../packages/api-contracts/dist/esm/types/common.js"(){"use strict";CommonSchemas={timestamp:z4.coerce.date(),positiveInt:z4.number().int().positive(),nonNegativeInt:z4.number().int().nonnegative()},BaseEntitySchema=z4.object({id:z4.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z4.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z4.enum(["full","edit","comment","view","agent","schedule"]),ProjectPrincipalTypeSchema=z4.enum(["user","org","orgRole","public","email"]),ProjectVisibilitySchema=z4.enum(["public","private"]),ProjectStatusSchema=z4.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z4.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z4.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z4.enum(["owner","admin","member"]),AssetTypeSchema=z4.enum(["file","folder"]),TemplateCodeSchema=z4.enum(["Free","Premium"]),FieldTypeSchema=z4.enum(["string","text","richtext","media","number","boolean","date","json","reference","blocks"]),RESERVED_CONTENT_FIELD_NAMES=["id","entryId","documentId","slug","locale","createdAt","updatedAt","__fimo"],CONTENT_TYPE_NAME_PATTERN=/^[A-Za-z]\w*$/,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter",CONTENT_FIELD_NAME_PATTERN=/^[A-Za-z_]\w*$/,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter or underscore"}});var ATTACHMENT_TYPES,ATTACHMENT_MIME_TYPES,ATTACHMENT_IMAGE_MIME_TYPES,ATTACHMENT_DOCUMENT_MIME_TYPES,ATTACHMENT_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image"},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image"},{mime:"image/webp",extensions:[".webp"],category:"image"},{mime:"image/avif",extensions:[".avif"],category:"image"},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:5242880},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:5242880},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:5242880}],ATTACHMENT_MIME_TYPES=ATTACHMENT_TYPES.map(t2=>t2.mime),ATTACHMENT_IMAGE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="image").map(t2=>t2.mime),ATTACHMENT_DOCUMENT_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="document").map(t2=>t2.mime),ATTACHMENT_ACCEPT_EXTENSIONS=ATTACHMENT_TYPES.flatMap(t2=>t2.extensions),ATTACHMENT_ACCEPT_STRING=[...ATTACHMENT_ACCEPT_EXTENSIONS,...ATTACHMENT_MIME_TYPES].join(","),ATTACHMENT_DROPZONE_ACCEPT=Object.fromEntries(ATTACHMENT_TYPES.map(t2=>[t2.mime,t2.extensions]))}});import{z as z5}from"zod";function isValidEnv(env){return typeof env!="string"||env.length===0||env.length>MAX_ENV_LENGTH||env.startsWith("-")||env.startsWith(".")||env.includes("//")||env.includes("--")||env.split("/").some(segment=>segment==="..")?!1:ENV_ID_REGEX.test(env)}function encodeEnvPathSegment(env){return env.replace(/\//g,"--")}function isProductionEnv(env){return env===PRODUCTION_ENV}var ENV_ID_REGEX,MAX_ENV_LENGTH,EnvSchema,DEFAULT_ENV,PRODUCTION_ENV,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";ENV_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_ENV_LENGTH=255;__name(isValidEnv,"isValidEnv");__name(encodeEnvPathSegment,"encodeEnvPathSegment");EnvSchema=z5.string().min(1,"env must not be empty").max(MAX_ENV_LENGTH,`env must be at most ${MAX_ENV_LENGTH} characters`).refine(isValidEnv,{error:"env must match /^[a-zA-Z0-9._/-]+$/ and must not start with `-`"}),DEFAULT_ENV="main",PRODUCTION_ENV="prod";__name(isProductionEnv,"isProductionEnv")}});var init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict"}});import{z as z6}from"zod";function referenceDocumentId(value){if(typeof value=="string")return value;if(value&&typeof value=="object"){let reference=value,hasId=Object.prototype.hasOwnProperty.call(reference,"id"),hasDocumentId=Object.prototype.hasOwnProperty.call(reference,"documentId"),id=reference.id,documentId=reference.documentId;if(hasId&&typeof id!="string"||hasDocumentId&&typeof documentId!="string"||typeof id=="string"&&typeof documentId=="string"&&id!==documentId)return null;if(typeof id=="string")return id;if(typeof documentId=="string")return documentId}return null}function toReferenceValue(value){let documentId=referenceDocumentId(value);return documentId?{documentId}:null}function referenceContentType(value){if(value&&typeof value=="object"&&"contentType"in value){let contentType=value.contentType;return typeof contentType=="string"&&contentType.length>0?contentType:null}return null}function toPolymorphicReferenceValue(value){let documentId=referenceDocumentId(value),contentType=referenceContentType(value);return documentId&&contentType?{contentType,documentId}:null}var referenceValuePreprocess,ReferenceValueSchema,ReferenceInputValueSchema,polymorphicReferenceValuePreprocess,PolymorphicReferenceValueSchema,PolymorphicReferenceInputValueSchema,init_references=__esm({"../../packages/api-contracts/dist/esm/types/references.js"(){"use strict";__name(referenceDocumentId,"referenceDocumentId");__name(toReferenceValue,"toReferenceValue");referenceValuePreprocess=__name(value=>{let reference=toReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"referenceValuePreprocess"),ReferenceValueSchema=z6.preprocess(referenceValuePreprocess,z6.object({documentId:z6.uuid()})),ReferenceInputValueSchema=z6.preprocess(referenceValuePreprocess,z6.union([z6.object({documentId:z6.uuid()}),z6.object({slug:z6.string().min(1)})]));__name(referenceContentType,"referenceContentType");__name(toPolymorphicReferenceValue,"toPolymorphicReferenceValue");polymorphicReferenceValuePreprocess=__name(value=>{let reference=toPolymorphicReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"polymorphicReferenceValuePreprocess"),PolymorphicReferenceValueSchema=z6.preprocess(polymorphicReferenceValuePreprocess,z6.object({contentType:z6.string().min(1),documentId:z6.uuid()})),PolymorphicReferenceInputValueSchema=z6.preprocess(polymorphicReferenceValuePreprocess,z6.union([z6.object({contentType:z6.string().min(1),documentId:z6.uuid()}),z6.object({contentType:z6.string().min(1),slug:z6.string().min(1)})]))}});import{z as z7}from"zod";function rejectLegacyLocaleSettings(field,ctx){"localized"in field&&ctx.addIssue({code:"custom",path:["localized"],message:'Field-level locale settings use "i18n".'})}function rejectFieldI18n(field,ctx){"i18n"in field&&ctx.addIssue({code:"custom",path:["i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}function refineConditions(field,ctx){if(field.showIf!==void 0&&field.showIfAny!==void 0&&ctx.addIssue({code:"custom",path:["showIfAny"],message:'A field declares "showIf" or "showIfAny", never both.'}),Array.isArray(field.showIf)){let fields=field.showIf.map(clause=>clause.field);new Set(fields).size!==fields.length&&ctx.addIssue({code:"custom",path:["showIf"],message:'"showIf" clauses must each name a different field. Use "in" for several values of one field.'})}}function rejectUnsupportedUnique(field,ctx,type){"unique"in field&&!uniqueFieldTypes.has(type)&&ctx.addIssue({code:"custom",path:["unique"],message:UNSUPPORTED_UNIQUE_MESSAGE})}function getConditionDefinition(field){if(field.showIfAny!==void 0)return{key:"showIfAny",clauses:field.showIfAny};if(field.showIf!==void 0)return{key:"showIf",clauses:Array.isArray(field.showIf)?field.showIf:[field.showIf]}}function getConditionValues(clause){return"equals"in clause?[clause.equals]:clause.in}function collectClauseProblems(fieldName,condition,clause,fields,path47){let conditionPath=[...path47,fieldName,condition.key],trigger=fields[clause.field];if(trigger===void 0)return[{path:conditionPath,message:`"${condition.key}" references unknown field "${clause.field}".`}];if(trigger.showIf!==void 0||trigger.showIfAny!==void 0)return[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is conditional too. Conditions are one level deep.`}];if(trigger.type!=="boolean"&&trigger.type!=="number"&&trigger.type!=="string")return[{path:conditionPath,message:`"${condition.key}" can only reference boolean, number, and string fields. "${clause.field}" is a ${trigger.type} field.`}];let triggerOptions=trigger.type==="string"?trigger.options:void 0;if(trigger.type==="string"&&triggerOptions===void 0)return[{path:conditionPath,message:`"${condition.key}" can only reference a string field that declares "options". Add options to "${clause.field}".`}];let values=getConditionValues(clause);if(values.some(value=>typeof value!==trigger.type))return[{path:conditionPath,message:`"${condition.key}" on "${clause.field}" expects a ${trigger.type} value.`}];if(triggerOptions!==void 0){let invalidValues=values.filter(value=>!triggerOptions.includes(value));if(invalidValues.length>0)return invalidValues.map(value=>({path:conditionPath,message:`"${value}" is not one of the options declared by "${clause.field}".`}))}return trigger.editable===!1?[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is not editable.`}]:[]}function collectConditionProblems(fields){let problems=[],walk=__name((currentFields,path47)=>{for(let[fieldName,field]of Object.entries(currentFields)){let condition=getConditionDefinition(field);if(condition!==void 0)for(let clause of condition.clauses)problems.push(...collectClauseProblems(fieldName,condition,clause,currentFields,path47));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path47,fieldName,variant.uid]);else walk(field.schema.fields,[...path47,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path47,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path47,fieldName];visit2({field,path:fieldPath,structuredDepth,insideStructuredContent});let nextDepth=structuredDepth+1;if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...fieldPath,variant.uid],nextDepth,!0);else walk(field.schema.fields,fieldPath,nextDepth,!0)}},"walk");walk(fields,[],0,!1)}var UNIQUE_FIELD_TYPES,utf8,MAX_STRUCTURED_CONTENT_DEPTH,MAX_BLOCK_VARIANTS,MAX_BLOCK_ITEMS,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES,showIfClauseSchema,commonFieldShape,FIELD_I18N_UNSUPPORTED_MESSAGE,uniqueFieldTypes,UNSUPPORTED_UNIQUE_MESSAGE,scalarFieldSchema,referenceFieldSchema,reservedStructuredContentNames,ContentFieldDefinitionSchema,blockFieldsSchema,blockVariantSchema,fixedBlocksSchema,blocksSchema,blocksFieldSchema,contentFieldDefinitionSchema,init_content_fields=__esm({"../../packages/api-contracts/dist/esm/types/content-fields.js"(){"use strict";init_common();UNIQUE_FIELD_TYPES=["string","text","number","boolean","date"],utf8=new TextEncoder,MAX_STRUCTURED_CONTENT_DEPTH=3,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],showIfClauseSchema=z7.union([z7.object({field:z7.string().min(1),equals:z7.union([z7.string(),z7.number(),z7.boolean()])}).strict(),z7.object({field:z7.string().min(1),in:z7.array(z7.union([z7.string(),z7.number(),z7.boolean()])).min(1)}).strict()]),commonFieldShape={label:z7.string().min(1).optional(),description:z7.string().optional(),editable:z7.boolean().optional(),required:z7.boolean().optional(),default:z7.unknown().optional(),showIf:z7.union([showIfClauseSchema,z7.array(showIfClauseSchema).min(1)]).optional(),showIfAny:z7.array(showIfClauseSchema).min(1).optional()},FIELD_I18N_UNSUPPORTED_MESSAGE='"i18n" is only supported on top-level scalar and reference fields.';__name(rejectLegacyLocaleSettings,"rejectLegacyLocaleSettings");__name(rejectFieldI18n,"rejectFieldI18n");__name(refineConditions,"refineConditions");uniqueFieldTypes=new Set(UNIQUE_FIELD_TYPES),UNSUPPORTED_UNIQUE_MESSAGE=`"unique" is only supported on ${UNIQUE_FIELD_TYPES.join(", ")} fields.`;__name(rejectUnsupportedUnique,"rejectUnsupportedUnique");scalarFieldSchema=z7.object({...commonFieldShape,type:z7.enum(["string","text","richtext","media","number","boolean","date","json"]),min:z7.number().optional(),max:z7.number().optional(),minLength:z7.number().int().nonnegative().optional(),maxLength:z7.number().int().nonnegative().optional(),regex:z7.string().optional(),multiple:z7.boolean().optional(),allowedMimeTypes:z7.array(z7.string()).optional(),options:z7.array(z7.string().min(1)).min(1).optional(),unique:z7.boolean().optional(),i18n:z7.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),rejectUnsupportedUnique(field,ctx,field.type);for(let key of["target","targets","many","repeatable","schema"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on ${field.type} fields.`});if(field.type!=="number")for(let key of["min","max"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on number fields.`});if(field.type!=="string"&&field.type!=="text")for(let key of["minLength","maxLength","regex"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on string and text fields.`});field.min!==void 0&&field.max!==void 0&&field.min>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to "min".'});let effectiveMinimumLength=Math.max(field.minLength??0,field.required?1:0);if(field.maxLength!==void 0&&effectiveMinimumLength>field.maxLength&&ctx.addIssue({code:"custom",path:["maxLength"],message:'"maxLength" must be greater than or equal to the minimum required length.'}),field.regex!==void 0)try{new RegExp(field.regex)}catch{ctx.addIssue({code:"custom",path:["regex"],message:'"regex" must be a valid regular expression.'})}if(field.type!=="media")for(let key of["multiple","allowedMimeTypes"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on media fields.`});if(field.type!=="string"&&"options"in field&&ctx.addIssue({code:"custom",path:["options"],message:'"options" is only supported on string fields.'}),field.options!==void 0){new Set(field.options).size!==field.options.length&&ctx.addIssue({code:"custom",path:["options"],message:"Options must be unique."});for(let key of["regex","minLength","maxLength"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported alongside "options".`});field.default!==void 0&&!field.options.includes(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:'"default" must be one of the declared options.'})}}),referenceFieldSchema=z7.object({...commonFieldShape,type:z7.literal("reference"),target:z7.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z7.array(z7.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z7.boolean().optional(),i18n:z7.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),!field.target&&!field.targets&&ctx.addIssue({code:"custom",path:["target"],message:'Reference fields must declare "target" or "targets".'}),field.target&&field.targets&&ctx.addIssue({code:"custom",path:["targets"],message:'A reference field declares "target" or "targets", never both.'}),field.targets&&new Set(field.targets).size!==field.targets.length&&ctx.addIssue({code:"custom",path:["targets"],message:"Reference targets must be unique."});for(let key of["repeatable","schema","min","max","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on reference fields.`})}),reservedStructuredContentNames=new Set(RESERVED_STRUCTURED_CONTENT_FIELD_NAMES),ContentFieldDefinitionSchema=z7.lazy(()=>contentFieldDefinitionSchema);__name(getConditionDefinition,"getConditionDefinition");__name(getConditionValues,"getConditionValues");__name(collectClauseProblems,"collectClauseProblems");__name(collectConditionProblems,"collectConditionProblems");blockFieldsSchema=z7.record(z7.string(),ContentFieldDefinitionSchema).superRefine((fields,ctx)=>{for(let fieldName of Object.keys(fields))CONTENT_FIELD_NAME_PATTERN.test(fieldName)||ctx.addIssue({code:"custom",path:[fieldName],message:`Field names must use ${CONTENT_FIELD_NAME_PATTERN_DESCRIPTION}.`}),reservedStructuredContentNames.has(fieldName)&&ctx.addIssue({code:"custom",path:[fieldName],message:`"${fieldName}" is reserved structured-content metadata.`}),"unique"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"unique"],message:'"unique" is only supported on top-level fields.'}),"i18n"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}),blockVariantSchema=z7.object({uid:z7.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z7.string().min(1),description:z7.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z7.object({fields:blockFieldsSchema}).strict(),blocksSchema=z7.object({oneOf:z7.array(blockVariantSchema).min(1).max(MAX_BLOCK_VARIANTS)}).strict().superRefine((schema,ctx)=>{let seen=new Set;for(let[index2,variant]of schema.oneOf.entries())seen.has(variant.uid)&&ctx.addIssue({code:"custom",path:["oneOf",index2,"uid"],message:"Variant UIDs must be unique."}),seen.add(variant.uid)}),blocksFieldSchema=z7.object({...commonFieldShape,type:z7.literal("blocks"),min:z7.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z7.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z7.union([fixedBlocksSchema,blocksSchema])}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),rejectFieldI18n(field,ctx),refineConditions(field,ctx);let effectiveMinimum=Math.max(field.min??0,field.required?1:0);field.max!==void 0&&effectiveMinimum>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to the minimum number of blocks.'});for(let key of["target","targets","many","repeatable","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on blocks fields.`})}),contentFieldDefinitionSchema=z7.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z8}from"zod";var AUDIT_ACTIONS,AuditActionSchema,AUDIT_OUTCOMES,AuditOutcomeSchema,AUDIT_ACTOR_KINDS,AuditActorKindSchema,init_audit_log=__esm({"../../packages/api-contracts/dist/esm/types/audit-log.js"(){"use strict";AUDIT_ACTIONS=["env_create","env_delete","env_sync","capability_check","shell_exec","git_push","git_tag","git_merge","fimo_deploy","merge_decision","session_start","session_end","cost_breach","trigger_fire","cutover_step","agent_delegate","ops_access_change","ops_service_token_change","ops_project_search","ops_project_inspect","ops_project_chat_read","ops_recent_chat_read","ops_project_snapshot","ops_support_thread_read","ops_support_report_read","ops_support_report_change","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send"],AuditActionSchema=z8.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z8.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z8.enum(AUDIT_ACTOR_KINDS)}});import{z as z9}from"zod";var OPS_BACKEND_PROFILES,OpsBackendProfileSchema,OPS_PERMISSIONS,OpsPermissionSchema,OPS_PERMISSION_PRESETS,OPS_SERVICE_PERMISSION_PRESETS,OpsAccessGrantInputSchema,OpsServiceTokenInputSchema,OpsCustomerProjectInputSchema,OPS_INVESTIGATION_STATUSES,OpsInvestigationStatusSchema,OpsInvestigationCreateInputSchema,OpsInvestigationUpdateInputSchema,OPS_KNOWN_ISSUE_STATUSES,OpsKnownIssueStatusSchema,OpsKnownIssueCreateInputSchema,OpsKnownIssueUpdateInputSchema,OPS_VALIDATION_OUTCOMES,OpsValidationOutcomeSchema,OpsValidationRunInputSchema,OpsNotificationPreviewInputSchema,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z9.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:sentry:read","ops:logs:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview","ops:notification:approve","ops:notification:send"],OpsPermissionSchema=z9.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:validations:read","ops:notification:preview"],engineer:["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:sentry:read","ops:logs:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview"],full:[...OPS_PERMISSIONS]},OPS_SERVICE_PERMISSION_PRESETS={support:OPS_PERMISSION_PRESETS.support,engineer:OPS_PERMISSION_PRESETS.engineer,full:OPS_PERMISSION_PRESETS.full.filter(permission=>permission!=="ops:notification:approve")},OpsAccessGrantInputSchema=z9.object({permissions:z9.array(OpsPermissionSchema).min(1),backendProfiles:z9.array(OpsBackendProfileSchema).min(1),enabled:z9.boolean().default(!0)}),OpsServiceTokenInputSchema=z9.object({name:z9.string().trim().min(1).max(120),permissions:z9.array(OpsPermissionSchema).min(1),backendProfiles:z9.array(OpsBackendProfileSchema).min(1),expiresAt:z9.coerce.date()}).refine(input=>!input.permissions.includes("ops:notification:approve"),{path:["permissions"],message:"Service credentials cannot approve customer notifications"}).refine(input=>input.expiresAt.getTime()>Date.now(),{path:["expiresAt"],message:"Service credential expiry must be in the future"}),OpsCustomerProjectInputSchema=z9.object({importanceReason:z9.string().trim().min(1).max(1e3),ownerUserId:z9.string().trim().min(1).nullable().optional(),framework:z9.string().trim().max(120).nullable().optional(),packageManager:z9.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z9.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z9.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z9.object({projectId:z9.uuid(),title:z9.string().trim().min(1).max(240),userReport:z9.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z9.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z9.string().trim().max(1e4).nullable().optional(),outcome:z9.string().trim().max(1e4).nullable().optional(),evidence:z9.array(z9.record(z9.string(),z9.unknown())).max(100).optional()}).refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_KNOWN_ISSUE_STATUSES=["open","monitoring","resolved"],OpsKnownIssueStatusSchema=z9.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z9.object({fingerprint:z9.string().trim().min(1).max(240),title:z9.string().trim().min(1).max(240),description:z9.string().trim().min(1).max(1e4),affectedVersions:z9.array(z9.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z9.array(z9.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z9.string().trim().min(1).max(64).nullable().optional(),workaround:z9.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z9.array(z9.string().trim().min(1).max(120)).max(100),detectionQueries:z9.array(z9.string().trim().min(1).max(2e3)).max(50),status:OpsKnownIssueStatusSchema}).partial().refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_VALIDATION_OUTCOMES=["passed","failed","inconclusive"],OpsValidationOutcomeSchema=z9.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z9.object({changeReference:z9.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z9.string().trim().min(1).max(1e4),evidence:z9.array(z9.record(z9.string(),z9.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z9.object({recipientEmail:z9.email().optional(),subject:z9.string().trim().min(1).max(200).default("An update from Fimo"),message:z9.string().trim().min(1).max(5e3),locale:z9.string().trim().min(2).max(20),reason:z9.string().trim().min(1).max(1e3),acknowledgePolicy:z9.literal(!0)})}});import{z as z10}from"zod";var ProjectDTOSchema,ProjectDTO,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,QuestionAnswerMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectHistoryUsageDTOSchema,ProjectVersionPageDTOSchema,ProjectVersionPageDTO,ProjectHistorySummaryDTOSchema,ProjectHistorySummaryDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionResponseSchema,ProjectVersionPageResponseSchema,ProjectHistorySummaryResponseSchema,VersionMutationResponseSchema,ProjectPublicationStateDTOSchema,ProjectPublicationStateDTO,PublicationMutationDTOSchema,PublicationMutationDTO,ProjectPublicationStateResponseSchema,PublicationMutationResponseSchema,ProjectResponseSchema,ProjectWithPlanResponseSchema,init_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project.dto.js"(){"use strict";init_common();init_create_dto();init_response();ProjectDTOSchema=BaseEntitySchema.extend({name:z10.string(),displayName:z10.string().nullable(),subdomain:z10.string().nullable().optional(),subdomainUpdatedAt:z10.date().nullable().optional(),organizationId:z10.string().nullable(),createdBy:z10.string().nullable(),visibility:ProjectVisibilitySchema,previewEnabled:z10.boolean().default(!0),status:ProjectStatusSchema,creationStatus:z10.string(),thumbnailUrl:z10.string().nullable(),publishedThumbnailUrl:z10.string().nullable(),category:z10.string().nullable(),appUrl:z10.string().nullable(),lastPublishedAt:z10.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z10.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z10.object({id:z10.uuid(),name:z10.string(),displayName:z10.string().nullable(),thumbnailUrl:z10.string().nullable(),visibility:ProjectVisibilitySchema,category:z10.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z10.object({id:z10.string(),name:z10.string(),avatar:z10.string().nullable(),color:z10.object({bg:z10.string(),text:z10.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z10.object({path:z10.string(),content:z10.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z10.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z10.object({id:z10.string(),messageId:z10.string(),versionId:z10.string().nullable(),role:ProjectChatMessageRole,parts:z10.array(z10.any()),createdAt:z10.coerce.date()}),MessageUserMetadataSchema=z10.object({id:z10.string(),name:z10.string().nullable().optional(),image:z10.string().nullable().optional()}).nullable().optional(),QuestionAnswerMetadataSchema=z10.object({shortTitle:z10.string().optional(),questions:z10.array(z10.object({header:z10.string(),question:z10.string(),answer:z10.string(),selectedLabels:z10.array(z10.string()),freeText:z10.string(),skipped:z10.boolean()}))}).optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z10.number(),metadata:z10.object({user:MessageUserMetadataSchema,changeManifest:z10.array(z10.any()).optional(),questionAnswer:QuestionAnswerMetadataSchema}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z10.object({versionId:z10.uuid(),commitHash:z10.string(),name:z10.string(),description:z10.string().nullable(),kind:z10.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z10.object({versionCount:z10.number().int().nonnegative(),snapshotBytes:z10.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z10.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z10.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z10.object({content:z10.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z10.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z10.object({success:z10.boolean(),message:z10.string().optional(),warning:z10.string().optional(),durationMs:z10.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z10.object({isPublished:z10.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z10.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublicationMutationDTOSchema=z10.object({success:z10.boolean(),message:z10.string().optional(),publishedAt:CommonSchemas.timestamp.optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z11}from"zod";var ProjectEnvStatusSchema,ProjectEnvDTOSchema,ProjectEnvDTO,CreateProjectEnvRequestSchema,SyncProjectEnvRequestSchema,ProjectEnvResponseSchema,ProjectEnvsListResponseSchema,EnvSurfaceDiffSchema,EnvDiffResultSchema,EnvDiffResultDTO,init_project_env_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-env.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();ProjectEnvStatusSchema=z11.enum(["provisioning","active","deleted"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z11.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,previewUrl:z11.string().nullable(),parentEnv:EnvSchema.nullable(),createdBy:z11.string().nullable(),deletedAt:z11.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),CreateProjectEnvRequestSchema=z11.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z11.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z11.array(ProjectEnvDTOSchema)),EnvSurfaceDiffSchema=z11.object({surface:z11.enum(["code","schemas","content","translations","assets","forms","activations"]),status:z11.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z11.number().int().nonnegative(),conflictCount:z11.number().int().nonnegative()}),EnvDiffResultSchema=z11.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z11.coerce.date(),surfaces:z11.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z12}from"zod";var ExportProjectResponseDTOSchema,ExportProjectResponseDTO,ImportProjectResultDTOSchema,ImportProjectResultDTO,ImportPreviewCountsDTOSchema,ImportPreviewSurfaceDTOSchema,ImportPreviewDTOSchema,ImportPreviewDTO,ImportPreviewResponseDTOSchema,ImportPreviewResponseDTO,init_project_import_export_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-import-export.dto.js"(){"use strict";init_create_dto();ExportProjectResponseDTOSchema=z12.object({success:z12.literal(!0),downloadUrl:z12.string(),expiresAt:z12.string(),fileSize:z12.number(),duration:z12.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z12.object({success:z12.literal(!0),projectId:z12.string(),projectName:z12.string(),displayName:z12.string(),projectUrl:z12.string(),duration:z12.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z12.object({contentTypes:z12.number(),entries:z12.number(),assets:z12.number(),translations:z12.number(),forms:z12.number(),codeFiles:z12.number(),assetFiles:z12.number()}),ImportPreviewSurfaceDTOSchema=z12.object({name:z12.string(),included:z12.boolean(),count:z12.number().optional(),note:z12.string().optional()}),ImportPreviewDTOSchema=z12.object({projectName:z12.string(),displayName:z12.string().nullable(),visibility:z12.string().nullable(),category:z12.string().nullable(),exportedAt:z12.string(),version:z12.string(),envScope:z12.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z12.array(ImportPreviewSurfaceDTOSchema),fileSize:z12.number(),fileName:z12.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z12.object({success:z12.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z13}from"zod";var TriggerKindSchema,ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema,TriggerSchema,init_agent_trigger_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-trigger.dto.js"(){"use strict";TriggerKindSchema=z13.enum(["manual","schedule","webhook"]),ManualTriggerSchema=z13.object({type:z13.literal("manual")}),ScheduleTriggerSchema=z13.object({type:z13.literal("schedule"),cron:z13.string().min(1,"cron expression required").regex(/^\s*\S+\s+\S+\s+\S+\s+\S+\s+\S+\s*$/,"cron must be a 5-field expression"),tz:z13.string().optional()}),WebhookTriggerSchema=z13.object({type:z13.literal("webhook"),path:z13.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z13.discriminatedUnion("type",[ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema])}});import{z as z14}from"zod";var ActivateRequestSchema,DeactivateRequestSchema,AgentActivationDTOSchema,AgentActivationDTO,AgentActivationsListResponseSchema,AgentActivationResponseSchema,WebhookPathTakenErrorSchema,ManualRunRequestSchema,DispatchSkippedSchema,DispatchAcceptedSchema,ManualRunResponseSchema,init_agent_activation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-activation.dto.js"(){"use strict";init_env();init_create_dto();init_response();init_agent_trigger_dto();ActivateRequestSchema=z14.object({triggerIndices:z14.array(z14.number().int().nonnegative()).optional()}),DeactivateRequestSchema=z14.object({triggerIndices:z14.array(z14.number().int().nonnegative()).optional()}),AgentActivationDTOSchema=z14.object({projectId:z14.uuid(),env:EnvSchema,agentName:z14.string().min(1),triggerIndex:z14.number().int().nonnegative(),triggerKind:TriggerKindSchema,trigger:TriggerSchema,enabled:z14.boolean(),lastFiredAt:z14.coerce.date().nullable(),webhookPath:z14.string().nullable(),createdAt:z14.coerce.date(),updatedAt:z14.coerce.date()}),AgentActivationDTO=createDTO(AgentActivationDTOSchema),AgentActivationsListResponseSchema=createResponseSchema(z14.array(AgentActivationDTOSchema)),AgentActivationResponseSchema=createResponseSchema(AgentActivationDTOSchema),WebhookPathTakenErrorSchema=z14.object({error:z14.literal("webhook_path_taken"),conflictAgent:z14.string(),path:z14.string()}),ManualRunRequestSchema=z14.object({args:z14.unknown().optional(),requestId:z14.string().min(1).max(128).optional()}),DispatchSkippedSchema=z14.object({skipped:z14.enum(["duplicate","no-activation","agent-not-cloud","bundle-missing","trigger-stale"])}),DispatchAcceptedSchema=z14.object({sessionId:z14.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z14.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z15}from"zod";var CapabilityRiskTierSchema,CapabilitySummaryEntrySchema,AgentSubAgentSummarySchema,AgentInstallSummaryDTOSchema,AgentInstallSummaryDTO,AgentInstallSummaryResponseSchema,init_agent_install_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-install-summary.dto.js"(){"use strict";init_create_dto();init_response();CapabilityRiskTierSchema=z15.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z15.object({token:z15.string().min(1),risk:CapabilityRiskTierSchema,description:z15.string()}),AgentSubAgentSummarySchema=z15.object({name:z15.string().min(1),grant:z15.enum(["inherit","explicit"]),effectiveCaps:z15.array(z15.string().min(1))}),AgentInstallSummaryDTOSchema=z15.object({agentName:z15.string().min(1),env:z15.string().min(1),declaredCapabilities:z15.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z15.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z15.array(CapabilitySummaryEntrySchema),criticalCapabilities:z15.array(CapabilitySummaryEntrySchema),subAgents:z15.array(AgentSubAgentSummarySchema),declaresDelegate:z15.boolean(),cycle:z15.array(z15.string()).nullable(),missingSubAgents:z15.array(z15.string()),warnings:z15.array(z15.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z16}from"zod";var AgentListItemTriggerSchema,AgentListItemActivationSchema,AgentListItemDTOSchema,AgentListItemDTO,AgentListResponseSchema,init_agent_list_item_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-list-item.dto.js"(){"use strict";init_create_dto();init_response();init_agent_install_summary_dto();init_agent_trigger_dto();AgentListItemTriggerSchema=z16.object({kind:TriggerKindSchema,summary:z16.string()}),AgentListItemActivationSchema=z16.object({triggerIndex:z16.number().int().nonnegative(),triggerKind:TriggerKindSchema,env:z16.string().min(1),active:z16.boolean()}),AgentListItemDTOSchema=z16.object({name:z16.string().min(1),description:z16.string().nullable(),goalFirstLine:z16.string().nullable(),declaredCapabilities:z16.array(CapabilitySummaryEntrySchema),triggers:z16.array(AgentListItemTriggerSchema),activations:z16.array(AgentListItemActivationSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z16.array(AgentListItemDTOSchema))}});import{z as z17}from"zod";var AgentSessionStatusSchema,SessionMetricsSchema,AgentSessionDTOSchema,AgentSessionDTO,AgentSessionCheckpointDTOSchema,AgentSessionCheckpointDTO,AgentSessionResponseSchema,AgentSessionsListResponseSchema,AgentSessionCheckpointsListResponseSchema,AgentSessionWithCheckpointsResponseSchema,SessionErrorCodeSchema,CancelSessionRequestSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_env();init_create_dto();init_response();init_agent_trigger_dto();AgentSessionStatusSchema=z17.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z17.object({cpuMs:z17.number().nonnegative().default(0),netBytes:z17.number().nonnegative().default(0),walltimeMs:z17.number().nonnegative().default(0),llmTokensIn:z17.number().nonnegative().optional(),llmTokensOut:z17.number().nonnegative().optional()}),AgentSessionDTOSchema=z17.object({id:z17.uuid(),projectId:z17.uuid(),env:EnvSchema,agentName:z17.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z17.unknown().optional(),capabilities:z17.array(z17.string()).optional(),dataSources:z17.array(z17.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z17.string().nullable(),startedAt:z17.coerce.date().nullable(),finishedAt:z17.coerce.date().nullable(),cancelledAt:z17.coerce.date().nullable(),costUsd:z17.number().nonnegative(),costCeilingUsd:z17.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z17.boolean(),lastCheckpointId:z17.uuid().nullable(),branchEnvId:z17.uuid().nullable(),parentSessionId:z17.uuid().nullable(),terminalReason:z17.string().nullable(),errorMessage:z17.string().nullable(),report:z17.string().nullable(),createdAt:z17.coerce.date(),updatedAt:z17.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z17.object({id:z17.uuid(),sessionId:z17.uuid(),checkpointIdx:z17.number().int().nonnegative(),payloadRef:z17.string(),payloadSizeBytes:z17.number().int().nonnegative(),checksum:z17.string().length(64),createdAt:z17.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z17.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z17.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z17.object({session:AgentSessionDTOSchema,checkpoints:z17.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z17.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","too_many_agent_envs","env_provisioning_failed"]),CancelSessionRequestSchema=z17.object({reason:z17.string().min(1).max(120).optional()})}});import{z as z18}from"zod";var AgentBranchClassificationSchema,AgentBranchDecidedPathSchema,AgentBranchProposalDTOSchema,AgentBranchProposalDTO,DecideProposalRequestSchema,AgentBranchProposalResponseSchema,AgentBranchProposalsListResponseSchema,DecideProposalConflictResponseSchema,init_agent_proposal_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-proposal.dto.js"(){"use strict";init_create_dto();init_response();AgentBranchClassificationSchema=z18.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z18.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z18.object({id:z18.uuid(),envId:z18.uuid(),sessionId:z18.uuid().nullable(),skillName:z18.string().min(1),classification:AgentBranchClassificationSchema,rationale:z18.string().nullable(),summary:z18.string().nullable(),surfaceDeltas:z18.record(z18.string(),z18.unknown()),createdAt:z18.coerce.date(),decidedAt:z18.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z18.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z18.object({path:z18.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z18.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z18.object({code:z18.literal("merge_conflict"),message:z18.string(),conflicts:z18.record(z18.string(),z18.number().int().nonnegative())})}});import{z as z19}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,SetProjectIntegrationCredentialRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,ConnectOrganizationIntegrationRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,BindProjectChannelRequestSchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolOptionsSchema,RunProjectIntegrationToolRequestSchema,ProjectIntegrationToolRunUsageSchema,ProjectIntegrationToolRunBillingSchema,FirecrawlScrapeToolOutputSchema,FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlMonitorScheduleOutputSchema,FirecrawlMonitorTargetOutputSchema,FirecrawlMonitorOutputSchema,FirecrawlMonitorCheckOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema,FirecrawlToolKeySchema,FirecrawlToolOutputSchema,ProjectIntegrationToolRunBaseSchema,ProjectIntegrationToolRunDTOSchema,ProjectIntegrationToolRunDTO,IntegrationsListResponseSchema,IntegrationInfoResponseSchema,ProjectIntegrationStatusResponseSchema,ProjectIntegrationInstallationResponseSchema,ProjectIntegrationToolRunResponseSchema,StartProjectIntegrationConnectResponseResponseSchema,OrganizationIntegrationConnectionResponseSchema,ProjectChannelBindingResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z19.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z19.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z19.enum(["secret_text"]),IntegrationCredentialUsageSchema=z19.enum(["http_bearer","api_key"]),ProjectIntegrationCredentialStatusSchema=z19.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z19.object({mode:IntegrationAuthModeSchema,label:z19.string().min(1),description:z19.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z19.object({id:z19.string().min(1),label:z19.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z19.boolean()}),IntegrationToolDefinitionDTOSchema=z19.object({key:z19.string().min(1),name:z19.string().min(1),description:z19.string().min(1)}),IntegrationRecipeDTOSchema=z19.object({title:z19.string().min(1),description:z19.string().min(1),command:z19.string().min(1).optional()}),IntegrationInfoDTOSchema=z19.object({key:z19.string().min(1),name:z19.string().min(1),summary:z19.string().min(1),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z19.array(IntegrationAuthModeDTOSchema),credentials:z19.array(IntegrationCredentialDefinitionDTOSchema),tools:z19.array(IntegrationToolDefinitionDTOSchema),recipes:z19.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z19.object({projectId:z19.uuid(),integrationKey:z19.string().min(1),installed:z19.boolean(),enabled:z19.boolean(),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z19.string().nullable(),connectionId:z19.uuid().nullable().optional(),connectionAlias:z19.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z19.array(z19.string()),installedAt:z19.coerce.date().nullable(),updatedAt:z19.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z19.object({id:z19.uuid(),projectId:z19.uuid(),integrationKey:z19.string().min(1),enabled:z19.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z19.string(),connectionId:z19.uuid().nullable().optional(),connectionAlias:z19.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z19.array(z19.string()),createdAt:z19.coerce.date(),updatedAt:z19.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z19.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z19.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z19.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z19.object({value:z19.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z19.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z19.object({id:z19.uuid(),organizationId:z19.string().min(1),integrationKey:z19.string().min(1),alias:z19.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z19.string().min(1),externalAccountName:z19.string().nullable(),externalBotUserId:z19.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z19.array(z19.string()),connectedAt:z19.coerce.date(),updatedAt:z19.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ConnectOrganizationIntegrationRequestSchema=z19.object({alias:z19.string().min(1).max(120).optional(),token:z19.string().min(1).optional()}),StartProjectIntegrationConnectResponseSchema=z19.object({integrationKey:z19.string().min(1),connectUrl:z19.string().url(),expiresAt:z19.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),BindProjectChannelRequestSchema=z19.object({ref:z19.string().min(1),connectionAlias:z19.string().min(1).optional(),agentName:z19.string().min(1).max(160).nullable().optional(),force:z19.boolean().optional()}),ProjectChannelBindingDTOSchema=z19.object({id:z19.uuid(),projectId:z19.uuid(),integrationKey:z19.string().min(1),connectionId:z19.uuid(),externalWorkspaceId:z19.string().min(1),externalChannelId:z19.string().min(1),externalChannelName:z19.string().nullable(),agentName:z19.string().nullable(),enabled:z19.boolean(),createdAt:z19.coerce.date(),updatedAt:z19.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),FirecrawlScrapeFormatsSchema=z19.object({markdown:z19.boolean().optional(),summary:z19.boolean().optional(),links:z19.boolean().optional(),images:z19.boolean().optional(),html:z19.union([z19.literal("cleaned"),z19.literal("raw"),z19.boolean()]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z19.object({url:z19.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z19.boolean().optional(),timeoutMs:z19.number().int().positive().max(12e4).optional(),waitForMs:z19.number().int().min(0).max(3e4).optional()}),FirecrawlSearchToolInputSchema=z19.object({query:z19.string().min(1),maxResults:z19.number().int().positive().max(20).optional(),sources:z19.array(z19.enum(["web","news","images"])).min(1).max(3).optional(),categories:z19.array(z19.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z19.array(z19.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z19.array(z19.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z19.enum(["hour","day","week","month","year"]).optional(),location:z19.string().min(1).max(160).optional(),country:z19.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z19.boolean().optional(),timeoutMs:z19.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlMapToolInputSchema=z19.object({url:z19.string().url(),search:z19.string().min(1).optional(),limit:z19.number().int().positive().max(200).optional(),includeSubdomains:z19.boolean().optional(),timeoutMs:z19.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z19.object({url:z19.string().url(),limit:z19.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z19.boolean().optional(),timeoutMs:z19.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z19.object({text:z19.string().min(1).max(200).optional(),cron:z19.string().min(1).max(120).optional(),timezone:z19.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorTargetInputSchema=z19.object({type:z19.enum(["scrape","crawl"]).default("scrape"),urls:z19.array(z19.string().url()).min(1).max(50),scrapeOptions:z19.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z19.boolean().optional(),timeoutMs:z19.number().int().positive().max(12e4).optional(),waitForMs:z19.number().int().min(0).max(3e4).optional()}).optional()}),FirecrawlMonitorCreateToolInputSchema=z19.object({name:z19.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z19.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z19.string().min(1).max(2e3).optional(),judgeEnabled:z19.boolean().optional(),retentionDays:z19.number().int().min(1).max(365).optional(),notification:z19.object({email:z19.object({enabled:z19.boolean().default(!0),recipients:z19.array(z19.string().email()).min(1).max(20),includeDiffs:z19.boolean().optional()}).optional()}).optional()}),FirecrawlMonitorIdToolInputSchema=z19.object({monitorId:z19.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z19.string().uuid()}),RunProjectIntegrationToolOptionsSchema=z19.object({connectionAlias:z19.string().min(1).optional()}),RunProjectIntegrationToolRequestSchema=z19.discriminatedUnion("tool",[RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("search"),input:FirecrawlSearchToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("scrape"),input:FirecrawlScrapeToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("map"),input:FirecrawlMapToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("crawl"),input:FirecrawlCrawlToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.create"),input:FirecrawlMonitorCreateToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.list"),input:z19.object({}).default({})}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.get"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.pause"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.resume"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.delete"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.run"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.checks"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z19.literal("monitor.check"),input:FirecrawlMonitorCheckToolInputSchema})]),ProjectIntegrationToolRunUsageSchema=z19.object({provider:z19.string().min(1),providerCredits:z19.number().nonnegative().optional(),providerCostUsd:z19.number().nonnegative().optional(),requests:z19.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z19.object({credits:z19.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z19.object({url:z19.string(),provider:z19.literal("firecrawl"),title:z19.string().optional(),statusCode:z19.number().optional(),markdown:z19.string().optional(),summary:z19.string().optional(),links:z19.array(z19.string()).optional(),images:z19.array(z19.string()).optional(),html:z19.string().optional(),warning:z19.string().optional()}),FirecrawlSearchToolOutputSchema=z19.object({query:z19.string(),provider:z19.literal("firecrawl"),warning:z19.string().optional(),results:z19.array(z19.object({title:z19.string(),url:z19.string(),snippet:z19.string().optional(),content:z19.string().optional(),score:z19.number().optional(),publishedAt:z19.string().optional()}))}),FirecrawlMapToolOutputSchema=z19.object({url:z19.string(),provider:z19.literal("firecrawl"),count:z19.number(),links:z19.array(z19.object({url:z19.string(),title:z19.string().optional(),description:z19.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z19.object({url:z19.string(),provider:z19.literal("firecrawl"),total:z19.number(),pages:z19.array(z19.object({url:z19.string(),title:z19.string().optional(),statusCode:z19.number().optional(),markdown:z19.string().optional(),summary:z19.string().optional(),links:z19.array(z19.string()).optional(),images:z19.array(z19.string()).optional(),html:z19.string().optional(),warning:z19.string().optional()})),warning:z19.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z19.object({cron:z19.string().optional(),text:z19.string().optional(),timezone:z19.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z19.object({id:z19.string().optional(),urls:z19.array(z19.string()).optional(),scrapeOptions:z19.record(z19.string(),z19.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z19.object({id:z19.string(),name:z19.string(),status:z19.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z19.string().nullable().optional(),lastRunAt:z19.string().nullable().optional(),currentCheckId:z19.string().nullable().optional(),targets:z19.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z19.string().nullable().optional(),judgeEnabled:z19.boolean().optional(),estimatedCreditsPerMonth:z19.number().optional(),createdAt:z19.string().optional(),updatedAt:z19.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z19.object({id:z19.string(),monitorId:z19.string(),scheduledFor:z19.string().nullable().optional(),startedAt:z19.string().nullable().optional(),finishedAt:z19.string().nullable().optional(),estimatedCredits:z19.number().optional(),reservedCredits:z19.number().optional(),actualCredits:z19.number().optional(),billingStatus:z19.string().nullable().optional(),summary:z19.object({totalPages:z19.number().optional(),same:z19.number().optional(),changed:z19.number().optional(),new:z19.number().optional(),removed:z19.number().optional(),error:z19.number().optional()}).passthrough().optional(),error:z19.string().nullable().optional(),createdAt:z19.string().optional(),updatedAt:z19.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z19.object({provider:z19.literal("firecrawl"),monitors:z19.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z19.object({provider:z19.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z19.object({provider:z19.literal("firecrawl"),monitorId:z19.string(),deleted:z19.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z19.object({provider:z19.literal("firecrawl"),monitorId:z19.string(),checks:z19.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z19.object({provider:z19.literal("firecrawl"),monitorId:z19.string(),check:FirecrawlMonitorCheckOutputSchema,next:z19.string().optional()}),FirecrawlToolKeySchema=z19.enum(["search","scrape","map","crawl","monitor.create","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z19.union([FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z19.object({projectId:z19.uuid(),integrationKey:z19.string().min(1),tool:FirecrawlToolKeySchema,connectionAlias:z19.string().min(1).nullable().optional(),output:FirecrawlToolOutputSchema,executedAt:z19.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z19.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z19.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z19.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z19.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z19.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z19.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z19.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z19.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema)}});import{z as z20}from"zod";var PROJECT_SECRET_KEY_PATTERN,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN,RESERVED_PROJECT_SECRET_KEYS,ProjectSecretKeySchema,ProjectScheduleStatusSchema,ProjectScheduleDTOSchema,ProjectScheduleDTO,CreateProjectScheduleRequestSchema,UpdateProjectScheduleRequestSchema,ProjectScheduleRunStatusSchema,ProjectScheduleRunTriggerSchema,ProjectScheduleRunSecretSnapshotStateSchema,ProjectScheduleRunSecretResolutionSchema,ProjectSchedulePolicySchema,ProjectScheduleUsageSchema,ProjectScheduleRunDTOSchema,ProjectScheduleRunDTO,ProjectScheduleRunSecretSnapshotSchema,ProjectScheduleRunDetailDTOSchema,ProjectScheduleRunDetailDTO,RunProjectScheduleRequestSchema,ProjectScheduleRunsQuerySchema,ProjectScheduleResponseSchema,ProjectSchedulesListDataSchema,ProjectSchedulesListResponseSchema,ProjectSchedulesOverviewResponseSchema,ProjectScheduleDetailDataSchema,ProjectScheduleDetailResponseSchema,ProjectScheduleRunsPageSchema,ProjectScheduleRunsResponseSchema,ProjectScheduleRunResponseSchema,ProjectScheduleRunDetailResponseSchema,init_schedule_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule.dto.js"(){"use strict";init_common();init_create_dto();init_response();PROJECT_SECRET_KEY_PATTERN=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN=/^(PUBLIC_|VITE_|NEXT_PUBLIC_)/,RESERVED_PROJECT_SECRET_KEYS=new Set(["FIMO_API_URL","FIMO_API_TOKEN","FIMO_PROJECT_ID","FIMO_ENV","FIMO_AGENT_SESSION","FIMO_DATA_SOURCES","FIMO_SCHEDULE_ID","FIMO_SCHEDULE_RUN_ID","FIMO_SCHEDULE_NAME","VITE_API_URL","VITE_ENABLE_ANALYTICS","VITE_FIMO_BRANCH","VITE_FIMO_IMAGE_HOSTS"]),ProjectSecretKeySchema=z20.string().min(1).max(255).superRefine((key,context)=>{PROJECT_SECRET_KEY_PATTERN.test(key)?RESERVED_PROJECT_SECRET_KEYS.has(key)?context.addIssue({code:"custom",message:`Secret key '${key}' is managed by Fimo and cannot be stored in project secrets.`}):PUBLIC_PROJECT_SECRET_PREFIX_PATTERN.test(key)&&context.addIssue({code:"custom",message:`Secret key '${key}' uses a public variable prefix. Store public values with fimo vars instead.`}):context.addIssue({code:"custom",message:`Secret key '${key}' must be UPPER_SNAKE_CASE.`})}),ProjectScheduleStatusSchema=z20.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z20.uuid(),env:z20.string().min(1),name:z20.string().min(1),cron:z20.string().min(1),command:z20.string().min(1),secretKeys:z20.array(z20.string().min(1)),enabled:z20.boolean(),lastRunAt:z20.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z20.string().nullable()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z20.object({name:z20.string().min(1).max(120),cron:z20.string().min(1).max(120),command:z20.string().min(1).max(500),secretKeys:z20.array(ProjectSecretKeySchema).default([])}),UpdateProjectScheduleRequestSchema=z20.object({name:z20.string().min(1).max(120).optional(),cron:z20.string().min(1).max(120).optional(),command:z20.string().min(1).max(500).optional(),secretKeys:z20.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z20.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z20.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z20.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z20.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z20.object({maxRuns:z20.number().int().positive(),retentionDays:z20.number().int().positive().nullable(),outputRetentionDays:z20.number().int().positive(),maxOutputBytes:z20.number().int().positive()}),ProjectScheduleUsageSchema=z20.object({runCount:z20.number().int().nonnegative(),runsWithOutput:z20.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z20.object({id:z20.uuid(),scheduleId:z20.uuid(),projectId:z20.uuid(),env:z20.string().min(1),scheduleName:z20.string().min(1),command:z20.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z20.object({id:z20.string().min(1),name:z20.string().min(1)}).nullable(),queuedAt:z20.coerce.date(),startedAt:z20.coerce.date().nullable(),finishedAt:z20.coerce.date().nullable(),exitCode:z20.number().int().nullable(),errorCode:z20.string().nullable(),error:z20.string().nullable(),outputBytes:z20.number().int().nonnegative(),outputTruncated:z20.boolean(),outputExpiresAt:z20.coerce.date().nullable(),metadataExpiresAt:z20.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z20.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z20.coerce.date().nullable(),items:z20.array(z20.object({key:z20.string().min(1),updatedAt:z20.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z20.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z20.object({trigger:z20.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z20.object({limit:z20.coerce.number().int().min(1).max(100).default(25),cursor:z20.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z20.object({items:z20.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z20.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z20.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z20.object({items:z20.array(ProjectScheduleRunDTOSchema),nextCursor:z20.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z21}from"zod";var AuditLogRowDTOSchema,AuditLogRowDTO,AuditLogListResponseSchema,AuditLogQuerySchema,init_audit_log_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/audit-log.dto.js"(){"use strict";init_audit_log();init_create_dto();init_response();AuditLogRowDTOSchema=z21.object({id:z21.uuid(),occurredAt:z21.coerce.date(),projectId:z21.uuid().nullable(),env:z21.string().nullable(),actor:z21.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z21.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z21.unknown().optional(),ipAddress:z21.string().nullable().optional(),userAgent:z21.string().nullable().optional(),error:z21.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z21.object({rows:z21.array(AuditLogRowDTOSchema),nextCursor:z21.string().nullable()})),AuditLogQuerySchema=z21.object({env:z21.string().optional(),action:AuditActionSchema.optional(),actor:z21.string().optional(),from:z21.coerce.date().optional(),to:z21.coerce.date().optional(),limit:z21.coerce.number().int().min(1).max(200).optional(),cursor:z21.string().optional()})}});import{z as z22}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,ActivationSnapshotSchema,ActivationDiffSchema,ActivationDiffDTO,ActivationDiffResponseSchema,CONFLICT_KINDS,ConflictKindSchema,ConflictSchema,FieldPickSchema,ConflictResolutionSchema,MergeResultSchema,MergeResultDTO,MergeResultResponseSchema,EngineStrategySchema,VendorStrategySchema,MergeStrategySchema,ResolvedStrategySchema,MergeRequestSchema,MergeInitiateResultSchema,MergeInitiateResultDTO,MergeInitiateResponseSchema,MergeConflictsHydrationSchema,MergeConflictsHydrationDTO,MergeConflictsHydrationResponseSchema,MergeResolveDraftRequestSchema,MergeResolveDraftResultSchema,MergeResolveDraftResultDTO,MergeResolveRequestSchema,MergeCancelRequestSchema,PublishReleaseRequestSchema,PublishReleaseResultSchema,PublishReleaseResultDTO,PublishReleaseResponseSchema,init_env_status_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-status.dto.js"(){"use strict";init_env();init_create_dto();init_response();SurfaceNameSchema=z22.enum(["code","schemas","content","translations","assets","forms","activations"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms","activations"],SurfaceDeltaVerbSchema=z22.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z22.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z22.object({verb:SurfaceDeltaVerbSchema,key:z22.string(),detail:z22.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z22.record(z22.string(),z22.unknown()).optional()}),PerSurfaceDeltaSchema=z22.object({surface:SurfaceNameSchema,status:z22.enum(["ok","timed_out","failed","unchanged"]),durationMs:z22.number().int().nonnegative().optional(),changedCount:z22.number().int().nonnegative(),conflictCount:z22.number().int().nonnegative(),items:z22.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z22.boolean().optional(),error:z22.string().optional()}),CrossSurfaceFindingSchema=z22.object({id:z22.string(),kind:z22.string(),description:z22.string(),severity:z22.enum(["warning","error"]),source:z22.object({surface:SurfaceNameSchema,key:z22.string()}),target:z22.object({surface:SurfaceNameSchema,key:z22.string()}),actions:z22.array(z22.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z22.object({env:EnvSchema,vs:EnvSchema,syncState:z22.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z22.coerce.date(),surfaces:z22.array(PerSurfaceDeltaSchema),agents:z22.array(z22.object({id:z22.string(),name:z22.string(),status:z22.enum(["active","paused","failed"]),lastRunAt:z22.coerce.date().nullable()})).optional(),crossSurface:z22.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z22.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z22.coerce.date(),surfaces:z22.array(PerSurfaceDeltaSchema),crossSurface:z22.array(CrossSurfaceFindingSchema).optional(),fingerprint:z22.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z22.object({path:z22.string(),state:z22.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z22.string(),additions:z22.number().int().nonnegative(),deletions:z22.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z22.object({oid:z22.string().optional(),content:z22.string().optional(),truncated:z22.boolean(),binary:z22.boolean()}),CodeConflictDetailSchema=z22.object({path:z22.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z22.string(),targetTipSha:z22.string(),mergeBaseSha:z22.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z22.object({id:z22.string(),slug:z22.string(),contentType:z22.string(),data:z22.record(z22.string(),z22.unknown()),updatedAt:z22.coerce.date()}),ContentRowDiffSchema=z22.object({collection:z22.string(),rowId:z22.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z22.object({name:z22.string(),label:z22.string(),isSingleton:z22.boolean(),fields:z22.record(z22.string(),z22.unknown())}),SchemaTypeDiffSchema=z22.object({typeName:z22.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z22.object({id:z22.string(),name:z22.string(),type:z22.enum(["file","folder"]),mimeType:z22.string().nullable(),storageKey:z22.string().nullable(),url:z22.string().nullable(),fileSize:z22.number().nullable(),width:z22.number().nullable(),height:z22.number().nullable(),altText:z22.string().nullable(),caption:z22.string().nullable(),createdAt:z22.coerce.date(),updatedAt:z22.coerce.date()}),AssetDiffSchema=z22.object({assetId:z22.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z22.object({locale:z22.string(),key:z22.string(),parent:z22.string().nullable(),child:z22.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z22.object({formName:z22.string(),label:z22.string().nullable(),schemaFingerprint:z22.string(),fields:z22.record(z22.string(),z22.unknown()),settings:z22.record(z22.string(),z22.unknown()).optional()}),FormSchemaDiffSchema=z22.object({formName:z22.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),ActivationSnapshotSchema=z22.object({agentName:z22.string(),triggerIndex:z22.number().int().nonnegative(),triggerKind:z22.string(),triggerSpec:z22.record(z22.string(),z22.unknown()),enabled:z22.boolean(),emailRecipients:z22.array(z22.string()).nullable(),qstashScheduleId:z22.string().nullable()}),ActivationDiffSchema=z22.object({agentName:z22.string(),triggerIndex:z22.number().int().nonnegative(),parent:ActivationSnapshotSchema.nullable(),child:ActivationSnapshotSchema.nullable()}),ActivationDiffDTO=createDTO(ActivationDiffSchema),ActivationDiffResponseSchema=createResponseSchema(ActivationDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z22.enum(CONFLICT_KINDS),ConflictSchema=z22.object({surface:SurfaceNameSchema,key:z22.string(),kind:ConflictKindSchema.optional(),description:z22.string(),parentValue:z22.unknown().optional(),childValue:z22.unknown().optional(),conflictingFields:z22.array(z22.string()).optional(),code:z22.object({path:z22.string(),unresolvable:z22.boolean().optional(),reason:z22.string().optional()}).optional()}),FieldPickSchema=z22.object({field:z22.string(),choice:z22.enum(["parent","child","pick","ai-pick"]),pickedValue:z22.unknown().optional(),aiSessionId:z22.string().optional()}),ConflictResolutionSchema=z22.object({surface:SurfaceNameSchema,key:z22.string(),choice:z22.enum(["parent","child","pick"]),pickedValue:z22.unknown().optional(),fieldPicks:z22.array(FieldPickSchema).optional()}),MergeResultSchema=z22.object({ok:z22.boolean(),mergeId:z22.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z22.array(z22.object({surface:SurfaceNameSchema,count:z22.number().int().nonnegative()})),conflicts:z22.array(ConflictSchema).optional(),summary:z22.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z22.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z22.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z22.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z22.boolean().optional()}),ResolvedStrategySchema=z22.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z22.boolean()}),MergeRequestSchema=z22.object({from:EnvSchema,allowDirectMerge:z22.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z22.object({mergeId:z22.string().uuid(),streamUrl:z22.string(),strategy:ResolvedStrategySchema,acceptedAt:z22.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z22.object({mergeId:z22.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z22.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z22.array(ConflictSchema),draftResolutions:z22.array(ConflictResolutionSchema),lastEditedBy:z22.string().nullable(),lastEditedAt:z22.coerce.date().nullable(),initiator:z22.object({userId:z22.string().nullable(),role:z22.string().nullable(),agentName:z22.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z22.object({resolutions:z22.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z22.object({mergeId:z22.string().uuid(),draftResolutions:z22.array(ConflictResolutionSchema),lastEditedAt:z22.coerce.date(),lastEditedBy:z22.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z22.object({mergeId:z22.string().uuid(),resolutions:z22.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z22.object({mergeId:z22.string().uuid()}),PublishReleaseRequestSchema=z22.object({version:z22.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z22.string().max(2e4).optional()}),PublishReleaseResultSchema=z22.object({releaseTag:z22.string(),sha:z22.string(),publishedAt:z22.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z23}from"zod";var DiffRefSchema,InlineSchema,SummaryBlockSchema,EnvDiffSummarySchema,EnvDiffSummaryResultSchema,EnvDiffSummaryResultDTO,EnvDiffSummaryResponseSchema,init_env_diff_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-diff-summary.dto.js"(){"use strict";init_create_dto();init_response();init_env_status_dto();DiffRefSchema=z23.object({surface:SurfaceNameSchema,key:z23.string(),label:z23.string()}),InlineSchema=z23.object({text:z23.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z23.discriminatedUnion("type",[z23.object({type:z23.literal("paragraph"),content:z23.array(InlineSchema).max(24)}),z23.object({type:z23.literal("preview"),ref:DiffRefSchema,caption:z23.string().optional()}),z23.object({type:z23.literal("code"),code:z23.string(),lang:z23.string().optional(),caption:z23.string().optional()}),z23.object({type:z23.literal("risk"),level:z23.enum(["warning","error"]),content:z23.array(InlineSchema).max(24)}),z23.object({type:z23.literal("list"),items:z23.array(z23.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z23.object({headline:z23.string(),blocks:z23.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z23.object({summary:EnvDiffSummarySchema,fingerprint:z23.string(),generatedAt:z23.coerce.date(),cached:z23.boolean().optional(),credits:z23.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z24}from"zod";var PROJECT_ANALYTICS_PRESETS,PROJECT_ANALYTICS_GROUP_BY_OPTIONS,ProjectDailyVisitorsDTOSchema,ProjectAnalyticsBreakdownItemDTOSchema,ProjectAnalyticsPageBreakdownItemDTOSchema,ProjectAnalyticsRangeDTOSchema,ProjectAnalyticsAnnotationDTOSchema,ProjectPageviewAnalyticsDTOSchema,ProjectPageviewAnalyticsDTO,ProjectAnalyticsAnnotationDTO,init_project_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-analytics.dto.js"(){"use strict";init_create_dto();PROJECT_ANALYTICS_PRESETS=["today","yesterday","this_week","this_month","last_7_days","last_30_days","last_90_days","last_week","last_month","last_quarter","last_year","custom"],PROJECT_ANALYTICS_GROUP_BY_OPTIONS=["day","week","month","quarter"],ProjectDailyVisitorsDTOSchema=z24.object({date:z24.string(),visitors:z24.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z24.object({key:z24.string(),visitors:z24.number().int().nonnegative(),pageviews:z24.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z24.object({path:z24.string(),pageName:z24.string().nullable().optional(),visitors:z24.number().int().nonnegative(),pageviews:z24.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z24.object({preset:z24.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z24.string(),requestedTo:z24.string(),effectiveFrom:z24.string(),effectiveTo:z24.string(),isRetentionLimited:z24.boolean(),groupBy:z24.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z24.object({date:z24.string(),content:z24.string(),updatedAt:z24.string(),updatedByUserId:z24.string()}),ProjectPageviewAnalyticsDTOSchema=z24.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z24.number().int().nonnegative(),pageviews:z24.number().int().nonnegative(),bounceRate:z24.number().min(0).max(100),viewsPerVisit:z24.number().nonnegative(),averageVisitDurationSeconds:z24.number().nonnegative(),visitorsSeries:z24.array(ProjectDailyVisitorsDTOSchema),topPages:z24.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z24.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z24.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z24.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z24.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z24.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z25}from"zod";var ProjectInviteDTOSchema,ProjectInviteDTO,CreatedProjectInviteDTOSchema,CreatedProjectInviteDTO,AcceptedProjectInviteDTOSchema,AcceptedProjectInviteDTO,init_project_invite_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-invite.dto.js"(){"use strict";init_common();init_create_dto();ProjectInviteDTOSchema=z25.object({id:z25.string(),email:z25.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z25.coerce.date(),createdAt:z25.coerce.date(),inviterUserId:z25.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z25.object({id:z25.string(),token:z25.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z25.object({success:z25.boolean(),projectId:z25.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z26}from"zod";var PublicUserDTOSchema,PublicUserDTO,ReferralCountCTOSchema,ReferralCountCTO,ReferralSummaryCTOSchema,ReferralSummaryCTO,AuthenticatedUserDTOSchema,AuthenticatedUserDTO,AuthenticatedUserResponseSchema,ReferralCountResponseSchema,ReferralSummaryResponseSchema,init_user_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/user.dto.js"(){"use strict";init_create_dto();init_response();PublicUserDTOSchema=z26.object({id:z26.string(),name:z26.string(),image:z26.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z26.object({count:z26.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z26.object({counts:z26.object({signed_up:z26.int(),activated:z26.int()}),credits:z26.object({total:z26.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z26.email(),emailVerified:z26.boolean(),createdAt:z26.coerce.date(),updatedAt:z26.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z27}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,ProjectPermissionsDTOSchema,ProjectPermissionsDTO,ProjectAccessDTOSchema,ProjectAccessDTO,AccessMutationResponseSchema,InviteAcceptResponseSchema,init_project_access_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-access.dto.js"(){"use strict";init_common();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z27.object({id:z27.string(),principalType:ProjectPrincipalTypeSchema,principalId:z27.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z27.coerce.date(),expiresAt:z27.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),ProjectPermissionsDTOSchema=z27.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z27.record(z27.string(),z27.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z27.object({access:z27.array(ProjectAccessItemDTOSchema),invites:z27.array(ProjectInviteDTOSchema),organization:z27.object({name:z27.string().nullable(),logo:z27.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z27.object({success:z27.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z27.object({success:z27.boolean(),projectId:z27.uuid()}))}});import{z as z28}from"zod";var PublicationStateDTOSchema,PublicationStateDTO,init_publication_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/publication.dto.js"(){"use strict";init_common();init_create_dto();PublicationStateDTOSchema=z28.object({publicationStatus:PublicationStatusSchema,appUrl:z28.string().nullable(),lastPublishedAt:z28.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z29}from"zod";var SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();SandboxSessionDTOSchema=z29.object({url:z29.url(),expiresAt:z29.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema)}});import{z as z30}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z30.string(),slug:z30.string().nullable(),logo:z30.string().nullable(),metadata:z30.record(z30.string(),z30.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z30.object({id:z30.string(),name:z30.string(),email:z30.email(),image:z30.string().nullable()}),OrganizationMemberDTOSchema=z30.object({id:z30.string(),userId:z30.string(),organizationId:z30.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z30.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z31}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common();init_create_dto();init_response();CancellationReasonCodeSchema=z31.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z31.object({reason:CancellationReasonCodeSchema,details:z31.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z31.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),AiCreditsEntitlementSchema=z31.object({included:z31.number().optional(),unitPrice:z31.number().optional(),dailyCap:z31.number().nullable().optional()}),EntitlementsDTOSchema=z31.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z31.object({retentionDays:z31.number().int().positive(),canUseExtendedDateRanges:z31.boolean()}).optional(),history:z31.object({retentionDays:z31.number().int().positive()}).optional(),members:z31.object({canInvite:z31.boolean(),maxMembers:z31.number().int().positive().nullable()}).optional(),projects:z31.object({canCreatePrivateProjects:z31.boolean(),maxPrivateProjects:z31.number().int().positive().nullable()}).optional(),domains:z31.object({canUseCustomDomains:z31.boolean(),maxDomains:z31.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z31.object({id:z31.string(),external_id:z31.string(),customerId:z31.string(),planId:z31.string(),planCode:TemplateCodeSchema,currentPeriod:z31.object({start:z31.string(),end:z31.string().nullable()}),cancelAt:z31.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z31.string(),nextPaymentAt:z31.string().nullable(),baseAmount:z31.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z31.object({totalCap:z31.number(),dailyCap:z31.number(),usedTotal:z31.number()}),CreditBalanceDTOSchema=z31.object({total:z31.number(),base:z31.number(),dailyBase:z31.number(),purchases:z31.number(),awards:z31.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z31.object({total:z31.number(),nearLimit:z31.boolean(),canChat:z31.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z31.object({dailyFreeAvailable:z31.number(),monthlyAvailable:z31.number(),purchasedAvailable:z31.number(),awardedAvailable:z31.number()}),ProjectDailyCreditAllowanceDTOSchema=z31.object({periodCap:z31.number(),dailyGrant:z31.number(),usedThisPeriod:z31.number(),remainingThisPeriod:z31.number()}),ProjectCreditBalanceDTOSchema=z31.object({projectId:z31.uuid(),organizationId:z31.string(),balance:z31.object({totalAvailable:z31.number(),nearLimit:z31.boolean(),canUseAi:z31.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z31.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),SuccessfulPurchaseDTOSchema=z31.object({invoiceId:z31.string(),newBalance:z31.int(),creditCount:z31.int(),amountUsd:z31.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z31.object({url:z31.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema)}});import{z as z32}from"zod";var PaymentMethodDTOSchema,PaymentMethodDTO,init_payment_method_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/payment-method.dto.js"(){"use strict";init_create_dto();PaymentMethodDTOSchema=z32.object({brand:z32.string(),last4:z32.string(),exp:z32.string(),isDefault:z32.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z33}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema,EntryDTO,PaginatedEntriesDTOSchema,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,EntryTranslationGapDTOSchema,EntryTranslationGapDTO,EntryTranslationGapResponseSchema,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema,EntryListResponseSchema,MAX_BULK_ENTRIES,entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema,EntryWhereSchema,EntryMutationBodySchema,entryIdsSchema,EntrySqlQueryRequestSchema,BulkCreateEntriesRequestSchema,BulkUpdateEntriesRequestSchema,BulkDeleteEntriesRequestSchema,EntrySqlQueryResponseSchema,EntrySqlQueryResponseDTO,BulkCreateEntriesResponseSchema,BulkCreateEntriesResponseDTO,BulkUpdateEntriesResponseSchema,BulkUpdateEntriesResponseDTO,BulkDeleteEntriesResponseSchema,BulkDeleteEntriesResponseDTO,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common();init_content_fields();init_create_dto();init_response();FieldDefinitionSchema=ContentFieldDefinitionSchema,SchemaFieldPathSchema=z33.string().superRefine((path47,ctx)=>{let segments=path47.split(".");(segments.length===0||segments.some(segment=>!CONTENT_FIELD_NAME_PATTERN.test(segment)))&&ctx.addIssue({code:"custom",message:"Field paths must use dot-separated field or block variant names."})}),SchemaMigrationOperationSchema=z33.object({type:z33.literal("renameField"),contentType:z33.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z33.object({enabled:z33.boolean()}).strict(),ContentTypeDTOSchema=z33.object({id:z33.string(),name:z33.string(),label:z33.string(),isSingleton:z33.boolean(),i18n:ContentTypeI18nSchema,fields:z33.record(z33.string(),FieldDefinitionSchema),createdAt:z33.string(),updatedAt:z33.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z33.object({contentTypes:z33.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z33.object({id:z33.string(),entryId:z33.string(),documentId:z33.string(),slug:z33.string(),locale:z33.string().optional(),createdAt:z33.string(),updatedAt:z33.string(),__fimo:z33.object({contentType:z33.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z33.object({data:z33.array(EntryDTOSchema),meta:z33.object({limit:z33.number(),offset:z33.number(),total:z33.number(),hasMore:z33.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z33.object({contentType:z33.string(),count:z33.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z33.object({counts:z33.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z33.object({count:z33.number().int().nonnegative(),sourceLocale:z33.string(),targetLocale:z33.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z33.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z33.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z33.union([z33.string(),z33.number(),z33.boolean(),z33.null()]),entryWhereOperatorSchema=z33.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z33.array(entryWhereScalarSchema).optional(),$nin:z33.array(entryWhereScalarSchema).optional(),$contains:z33.string().optional(),$startsWith:z33.string().optional(),$null:z33.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z33.record(z33.string(),z33.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z33.record(z33.string(),z33.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z33.object({data:z33.record(z33.string(),z33.unknown()),locale:z33.string().min(1).optional(),documentId:z33.uuid().optional()}),entryIdsSchema=z33.array(z33.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z33.object({sql:z33.string().min(1)}),BulkCreateEntriesRequestSchema=z33.object({entries:z33.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z33.union([z33.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z33.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z33.object({updates:z33.array(z33.object({id:z33.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z33.union([z33.object({ids:entryIdsSchema,locale:z33.string().min(1).optional()}),z33.object({where:EntryWhereSchema,locale:z33.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z33.object({data:z33.array(z33.record(z33.string(),z33.unknown())),meta:z33.object({rowCount:z33.number().int().nonnegative(),truncated:z33.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z33.object({data:z33.array(EntryDTOSchema),meta:z33.object({created:z33.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z33.object({data:z33.array(EntryDTOSchema),meta:z33.object({updated:z33.number().int().nonnegative(),missing:z33.array(z33.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z33.object({data:z33.array(EntryDTOSchema),meta:z33.object({deleted:z33.number().int().nonnegative(),missing:z33.array(z33.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z34}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z34.object({index:z34.number().int().nonnegative(),contentType:z34.string(),field:z34.string(),value:z34.string(),against:z34.enum(["stored","batch"]),ownerDocumentId:z34.uuid().optional(),ownerIndex:z34.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z34.object({code:z34.literal("unique_conflict"),message:z34.string(),conflicts:z34.array(UniqueConflictSchema),truncated:z34.boolean().optional()})}});import{z as z35}from"zod";var UniqueConflictIssueSchema,SchemaTransitionIssueSchema,SchemaTransitionRejectedErrorSchema,init_schema_transition_rejected_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schema-transition-rejected.dto.js"(){"use strict";UniqueConflictIssueSchema=z35.object({kind:z35.literal("unique_conflict"),contentType:z35.string(),field:z35.string(),value:z35.string(),documentCount:z35.number().int().positive(),documentIds:z35.array(z35.uuid()),documentIdsTruncated:z35.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z35.object({code:z35.literal("schema_transition_rejected"),message:z35.string(),issues:z35.array(SchemaTransitionIssueSchema),truncated:z35.boolean().optional()})}});import{z as z36}from"zod";var CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH,CmsContentTypeNameSchema,CmsFieldNameSchema,CmsCollectionOrderSchema,CmsFieldOrderSchema,CmsListSortSchema,CmsDisplayDefaultsDTOSchema,CmsDisplayDefaultsDTO,CmsCollectionOrderRequestSchema,CmsFieldOrderRequestSchema,CmsDisplayDefaultsResponseSchema,init_cms_display_defaults_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/cms-display-defaults.dto.js"(){"use strict";init_common();init_create_dto();init_response();CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS=200,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH=255,CmsContentTypeNameSchema=z36.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z36.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z36.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z36.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z36.object({field:CmsFieldNameSchema,direction:z36.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z36.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z36.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z36.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z36.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z36.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z37}from"zod";var AssetPathItemSchema,AssetDTOSchema,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema,AssetListResponseSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common();init_create_dto();init_response();AssetPathItemSchema=z37.object({id:z37.string(),name:z37.string()}),AssetDTOSchema=z37.object({id:z37.string(),name:z37.string(),type:AssetTypeSchema,originalFileName:z37.string().nullable(),parentId:z37.string().nullable(),mimeType:z37.string().nullable(),fileSize:z37.number().nullable(),url:z37.string().nullable(),storageKey:z37.string().nullable(),createdAt:z37.string(),updatedAt:z37.string(),altText:z37.string().nullable().optional(),caption:z37.string().nullable().optional(),aiCaption:z37.string().nullable().optional(),aiAltText:z37.string().nullable().optional(),aiTags:z37.array(z37.string()).nullable().optional(),aiPrimaryColor:z37.string().nullable().optional(),aiProcessingStatus:z37.string().nullable().optional(),width:z37.number().nullable().optional(),height:z37.number().nullable().optional(),path:z37.array(AssetPathItemSchema).optional(),hasChildren:z37.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z37.lazy(()=>z37.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z37.array(AssetDTOSchema))}});import{z as z38}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z38.object({key:z38.string(),value:z38.string().optional(),defaultValue:z38.string(),locale:z38.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z39}from"zod";var DocumentNodeDTOSchema,DocumentTreeDTOSchema,DocumentPathDTOSchema,DocumentPathDTO,DocumentTreeResponseSchema,DocumentPathResponseSchema,init_document_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/document.dto.js"(){"use strict";init_create_dto();init_response();DocumentNodeDTOSchema=z39.object({id:z39.string(),name:z39.string(),type:z39.enum(["file","folder"]),path:z39.string(),children:z39.lazy(()=>z39.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z39.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z39.object({path:z39.string(),exists:z39.boolean(),type:z39.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z40}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatThreadMessageDTOSchema,ChatThreadMessagesPageDTOSchema,ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema,ChatNonStreamingOutcomeDTOSchema,ChatDeletionDTOSchema,ChatDeletionDTO,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,ChatDeletionResponseSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_create_dto();init_response();init_project_dto();ChatMessageListDTOSchema=z40.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z40.object({items:z40.array(ProjectMessagePublicDTOSchema),nextCursor:z40.string().nullable()}),ChatLiveTurnDTOSchema=z40.object({invocationId:z40.string(),step:z40.enum(["preparing","working","merging"]),startedAt:z40.string()}),ChatThreadMessageDTOSchema=z40.object({id:z40.string(),role:z40.enum(["user","assistant"]),parts:z40.array(z40.unknown()),metadata:z40.record(z40.string(),z40.unknown()).nullable(),createdAt:z40.date().transform(value=>value.toISOString()),providerMessageId:z40.string().nullable().optional(),invocationId:z40.string().nullable().optional(),invocationStatus:z40.string().nullable().optional(),invocationTerminalReason:z40.string().nullable().optional()}),ChatThreadMessagesPageDTOSchema=z40.object({threadId:z40.string().nullable(),title:z40.string().nullable(),messages:z40.array(ChatThreadMessageDTOSchema),nextCursor:z40.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z40.object({kind:z40.literal("replay"),threadId:z40.string(),userMessageId:z40.string()}),ChatQueuedOutcomeDTOSchema=z40.object({kind:z40.literal("queued"),threadId:z40.string(),userMessageId:z40.string(),blockingRootId:z40.string()}),ChatBusyOutcomeDTOSchema=z40.object({kind:z40.literal("busy"),threadId:z40.string(),userMessageId:z40.string(),blockingRootId:z40.string().optional()}),ChatRefusedOutcomeDTOSchema=z40.object({kind:z40.literal("refused"),threadId:z40.string(),userMessageId:z40.string(),refusedInvocationId:z40.string(),terminalReason:z40.string()}),ChatNonStreamingOutcomeDTOSchema=z40.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z40.object({success:z40.boolean(),deletedCount:z40.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema)}});import{z as z41}from"zod";var UploadResultDTOSchema,UploadResultDTO,UploadResultResponseSchema,init_upload_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/upload.dto.js"(){"use strict";init_common();init_create_dto();init_response();UploadResultDTOSchema=z41.object({url:z41.string().url(),key:z41.string(),size:z41.number(),contentType:z41.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z42}from"zod";var ServicePermissionsDTOSchema,ServicePermissionsDTO,ServicePermissionsResponseSchema,init_service_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/service.dto.js"(){"use strict";init_create_dto();init_response();ServicePermissionsDTOSchema=z42.object({canAccess:z42.boolean(),permissions:z42.record(z42.string(),z42.boolean()),role:z42.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z43}from"zod";var OrganizationProjectsSearchQuerySchema,init_search_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/search.dto.js"(){"use strict";init_pagination();OrganizationProjectsSearchQuerySchema=PaginationQuerySchema.extend({q:z43.string().trim().default(""),sort:z43.enum(["recent","name","relevance"]).default("recent"),category:z43.string().optional(),visibility:z43.enum(["public","private"]).optional()})}});import{z as z44}from"zod";var DomainStatusSchema,DomainSourceSchema,PaymentStatusSchema,DomainDTOSchema,DomainDTO,DomainSearchResultDTOSchema,DomainSearchResultDTO,DomainPricingDTOSchema,DomainPricingDTO,DomainContactSchema,DomainContactDTO,UpdateDomainContactsRequestSchema,SearchDomainsRequestSchema,CheckAvailabilityRequestSchema,DOMAIN_NAME_REGEX,DomainNameSchema,PurchaseDomainRequestSchema,UpdateDomainSettingsRequestSchema,RenewDomainRequestSchema,DomainResponseSchema,DomainListResponseSchema,DomainSearchResultListResponseSchema,DomainPricingResponseSchema,DomainContactResponseSchema,ContactVerificationStatusSchema,ContactVerificationStatusResponseSchema,init_registered_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/registered-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();DomainStatusSchema=z44.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z44.enum(["fimo","external"]),PaymentStatusSchema=z44.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z44.object({id:z44.string().uuid(),domain:z44.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z44.boolean(),price:z44.number().int().nullable(),renewalPrice:z44.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z44.string().nullable(),failureReason:z44.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z44.object({domain:z44.string(),available:z44.boolean(),premium:z44.boolean(),price:z44.number().nullable(),renewalPrice:z44.number().nullable(),purchaseType:z44.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z44.object({domain:z44.string(),price:z44.number().nullable(),renewalPrice:z44.number().nullable(),premium:z44.boolean(),allowedYears:z44.array(z44.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z44.object({firstName:z44.string().max(100),lastName:z44.string().max(100),companyName:z44.string().max(100).optional(),address1:z44.string().max(255),address2:z44.string().max(255).optional(),city:z44.string().max(100),state:z44.string().max(100),zip:z44.string().max(20),country:z44.string().max(2),phone:z44.string().max(30),email:z44.union([z44.string().email().max(255),z44.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z44.object({firstName:z44.string().min(1).max(100),lastName:z44.string().min(1).max(100),companyName:z44.string().max(100).optional(),address1:z44.string().min(1).max(255),address2:z44.string().max(255).optional(),city:z44.string().min(1).max(100),state:z44.string().min(1).max(100),zip:z44.string().min(1).max(20),country:z44.string().min(1).max(2),phone:z44.string().min(1).max(30),email:z44.string().email().max(255)}),SearchDomainsRequestSchema=z44.object({keyword:z44.string().min(1).max(100),tldFilter:z44.array(z44.string()).optional()}),CheckAvailabilityRequestSchema=z44.object({domains:z44.array(z44.string()).min(1).max(50)}),DOMAIN_NAME_REGEX=/^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,DomainNameSchema=z44.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z44.object({domain:DomainNameSchema,years:z44.number().int().min(1).max(10).optional().default(3),autoRenew:z44.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z44.object({autoRenew:z44.boolean().optional()}),RenewDomainRequestSchema=z44.object({years:z44.number().int().min(1).max(10).optional().default(1),autoRenew:z44.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z44.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z44.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z44.object({verified:z44.boolean(),email:z44.string().nullable(),verifyBy:z44.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z45}from"zod";var ProjectDomainStatusSchema,SSLStatusSchema,SSLValidationRecordSchema,SSLValidationErrorSchema,OwnershipVerificationSchema,ProjectDomainSSLDTOSchema,DomainProviderSchema,DomainTypeSchema,RedirectConfigSchema,ProjectDomainDTOSchema,ProjectDomainDTO,ProjectDomainListResponseSchema,ProjectDomainResponseSchema,AddProjectDomainRequestSchema,CheckProjectDomainHostnameReasonSchema,CheckProjectDomainHostnameResponseSchema,DeleteProjectDomainResponseSchema,init_project_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();ProjectDomainStatusSchema=z45.enum(["pending","active","pending_validation","active_redeploying","moved","deleted","pending_deletion","pending_migration","pending_provisioned","test_pending","test_active","test_active_apex","test_blocked","test_failed","provisioned","blocked"]),SSLStatusSchema=z45.enum(["initializing","pending_validation","pending_issuance","pending_deployment","pending_expiration","expired","active","deleted","pending_cleanup","staging_deployment","staging_active","deactivating","inactive","backup_issued","holding_deployment"]),SSLValidationRecordSchema=z45.object({txtName:z45.string().nullable().optional(),txtValue:z45.string().nullable().optional(),httpUrl:z45.string().nullable().optional(),httpBody:z45.string().nullable().optional(),cname:z45.string().nullable().optional(),cnameTarget:z45.string().nullable().optional()}),SSLValidationErrorSchema=z45.object({message:z45.string()}),OwnershipVerificationSchema=z45.object({type:z45.string(),name:z45.string(),value:z45.string()}),ProjectDomainSSLDTOSchema=z45.object({status:z45.string(),method:z45.string().nullable(),type:z45.string().nullable(),validationRecords:z45.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z45.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z45.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z45.enum(["subdomain","apex"]),RedirectConfigSchema=z45.object({type:z45.literal("apex_to_www"),linkedDomainId:z45.string()}).nullable().optional(),ProjectDomainDTOSchema=z45.object({id:z45.string(),hostname:z45.string(),status:z45.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z45.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z45.string(),scdCnameTarget:z45.string().optional(),apexTargets:z45.array(z45.string()),dnsAutoConfigured:z45.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z45.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z45.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z45.object({hostname:z45.hostname().regex(/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,{error:"Invalid hostname"}).refine(value=>!/\.fimo\.site$/i.test(value),{error:"This is a Fimo-owned domain. Edit your built-in URL instead."}),redirectToWww:z45.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z45.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z45.object({available:z45.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z45.object({success:z45.boolean(),hostname:z45.string()}))}});import{z as z46}from"zod";var SUBDOMAIN_REGEX,SubdomainCheckReasonSchema,CheckProjectSubdomainResponseSchema,UpdateProjectSubdomainRequestSchema,UpdateProjectSubdomainErrorReasonSchema,UpdateProjectSubdomainResponseSchema,SubdomainSuggestionsQuerySchema,SubdomainSuggestionsResponseSchema,init_project_subdomain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-subdomain.dto.js"(){"use strict";init_response();SUBDOMAIN_REGEX=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,SubdomainCheckReasonSchema=z46.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z46.object({available:z46.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z46.object({slug:z46.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z46.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z46.object({subdomain:z46.string(),subdomainUpdatedAt:z46.coerce.date()})),SubdomainSuggestionsQuerySchema=z46.object({base:z46.string().max(100).optional(),max:z46.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z46.object({suggestions:z46.array(z46.string())}))}});import{z as z47}from"zod";var ProjectLocaleCoverageSchema,ProjectLocaleStatsItemSchema,ProjectLocaleStatsSchema,ProjectLocaleStatsDTO,ProjectLocaleStatsResponseSchema,AddProjectLocaleRequestSchema,RemoveProjectLocaleParamsSchema,ProjectLocaleMutationSchema,ProjectLocaleMutationDTO,ProjectLocaleMutationResponseSchema,RemoveProjectLocaleSchema,RemoveProjectLocaleDTO,RemoveProjectLocaleResponseSchema,init_project_locale_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-locale.dto.js"(){"use strict";init_create_dto();init_response();ProjectLocaleCoverageSchema=z47.object({translated:z47.number().int().nonnegative(),total:z47.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z47.object({locale:z47.string(),isDefault:z47.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z47.object({defaultLocale:z47.string(),routing:z47.object({strategy:z47.literal("path-prefix"),prefixDefaultLocale:z47.boolean()}),locales:z47.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z47.object({locale:z47.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z47.object({locale:z47.string().min(1).max(40)}),ProjectLocaleMutationSchema=z47.object({locale:z47.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z47.object({locale:z47.string(),entriesDeleted:z47.number().int().nonnegative(),labelsDeleted:z47.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z48}from"zod";function flag(key,description,options={}){return{name:key.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),key,description,type:options.type??"string",required:options.required??!1,...options.defaultValue!==void 0?{defaultValue:options.defaultValue}:{},...options.enumValues?{enumValues:[...options.enumValues]}:{},isArray:options.isArray??!1}}var GENERATION_QUALITIES,GENERATION_ASPECT_RATIOS,GENERATION_TASK_IDS,GenerationQualitySchema,GenerationTaskIdSchema,GENERATION_TASK_MANIFESTS,GenerationTaskEstimateDTOSchema,GenerationTaskEstimateDTO,init_generation_task_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation-task.dto.js"(){"use strict";init_create_dto();GENERATION_QUALITIES=["draft","standard","premium"],GENERATION_ASPECT_RATIOS=["1:1","16:9","9:16","4:3","3:4"],GENERATION_TASK_IDS=["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"],GenerationQualitySchema=z48.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z48.enum(GENERATION_TASK_IDS);__name(flag,"flag");GENERATION_TASK_MANIFESTS=[{id:"image.generate",modality:"image",operation:"generate",displayName:"Generate image",description:"Create an image from a prompt. Quality selects the appropriate generation route.",flags:[flag("prompt","Generation prompt",{required:!0}),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.edit",modality:"image",operation:"edit",displayName:"Edit image",description:"Transform up to five source images using a natural-language instruction.",flags:[flag("prompt","Editing instruction",{required:!0}),flag("images","Source asset id or absolute URL; repeatable up to five times",{required:!0,isArray:!0}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.remove-background",modality:"image",operation:"remove-background",displayName:"Remove image background",description:"Remove the background from one image and return a transparent cutout.",flags:[flag("image","Source asset id or absolute URL",{required:!0})]},{id:"image.upscale",modality:"image",operation:"upscale",displayName:"Upscale image",description:"Increase image resolution while preserving and optionally enhancing detail.",flags:[flag("image","Source asset id or absolute URL",{required:!0}),flag("targetMegapixels","Target resolution in megapixels",{type:"integer",defaultValue:4}),flag("outputFormat","Output image format",{type:"enum",defaultValue:"png",enumValues:["webp","jpg","png"]}),flag("enhanceDetails","Improve fine detail during upscaling",{type:"boolean",defaultValue:!0}),flag("enhanceRealism","Favor photorealistic detail reconstruction",{type:"boolean",defaultValue:!1})]},{id:"video.generate",modality:"video",operation:"generate",displayName:"Generate video",description:"Create a video from text or animate one source image. Loop closes the final frame back to the first.",flags:[flag("prompt","Generation and motion prompt",{required:!0}),flag("image","Optional source asset id or absolute URL"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"16:9",enumValues:GENERATION_ASPECT_RATIOS}),flag("duration","Duration in seconds; loops support 3 to 20 seconds",{type:"integer",defaultValue:5}),flag("includeAudio","Generate audio with the video",{type:"boolean",defaultValue:!1}),flag("loop","Make the final frame return to the source image",{type:"boolean",defaultValue:!1})]},{id:"video.animate",modality:"video",operation:"animate",displayName:"Animate image from video",description:"Apply the motion and camera movement from a source video to a reference image.",flags:[flag("video","Motion source asset id or absolute URL",{required:!0}),flag("image","Subject reference asset id or absolute URL",{required:!0}),flag("prompt","Optional instruction for the animation"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]},{id:"video.replace",modality:"video",operation:"replace",displayName:"Replace subjects in video",description:"Replace people in a source video with one to three reference identities while preserving motion.",flags:[flag("video","Source video asset id or absolute URL",{required:!0}),flag("images","Identity reference asset id or URL; repeatable up to three times",{required:!0,isArray:!0}),flag("prompt","Optional placement instruction"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]}],GenerationTaskEstimateDTOSchema=z48.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z48.number(),credits:z48.number().optional(),billingMode:z48.enum(["fimo-credits","provider-account"]).optional(),confidence:z48.enum(["exact","estimated","metered"]),basis:z48.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z49}from"zod";var GenerateRequestBaseSchema,GenerateRequestDTOSchema,GenerateRequestDTO,GenerateResponseDataSchema,GenerateResponseDTO,GenerateResponseSchema,GenerateErrorSchema,init_generation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation.dto.js"(){"use strict";init_create_dto();init_response();init_asset_dto();init_generation_task_dto();GenerateRequestBaseSchema=z49.object({options:z49.record(z49.string(),z49.unknown()),name:z49.string().optional(),parentId:z49.string().nullable().optional(),altText:z49.string().optional(),caption:z49.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z49.string().min(1).optional(),model:z49.string().min(1).optional()}).superRefine((value,context)=>{!!value.task==!!value.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model",path:["task"]})}),GenerateRequestDTO=createDTO(GenerateRequestDTOSchema),GenerateResponseDataSchema=z49.object({jobId:z49.string(),status:z49.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z49.string().nullable().optional(),credits:z49.number().optional(),costUsd:z49.number().optional(),billingMode:z49.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z49.object({error:z49.string(),code:z49.enum(["unknown-task","unknown-model","options-invalid","source-invalid","task-routing-failed","generation-failed","provider-error","cost-limit-exceeded","cost-estimate-unavailable","unsupported-modality"]),availableTasks:z49.array(GenerationTaskIdSchema).optional(),availableModels:z49.array(z49.string()).optional(),issues:z49.array(z49.unknown()).optional()})}});import{z as z50}from"zod";var FlagTypeSchema,FlagSpecSchema,AssetModelPriceSchema,AssetModelDTOSchema,AssetModelDTO,AssetModelEstimateDTOSchema,AssetModelEstimateDTO,init_asset_model_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset-model.dto.js"(){"use strict";init_create_dto();FlagTypeSchema=z50.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z50.object({name:z50.string(),key:z50.string(),description:z50.string(),type:FlagTypeSchema,required:z50.boolean(),defaultValue:z50.unknown().optional(),enumValues:z50.array(z50.string()).optional(),isArray:z50.boolean()}),AssetModelPriceSchema=z50.object({unitPrice:z50.number(),unit:z50.string(),confidence:z50.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z50.object({id:z50.string(),shortName:z50.string(),provider:z50.string(),source:z50.string(),modality:z50.enum(["image","video","audio"]),tags:z50.array(z50.string()),displayName:z50.string(),description:z50.string(),flags:z50.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z50.object({model:z50.string(),costUsd:z50.number(),credits:z50.number(),billingMode:z50.enum(["fimo-credits","provider-account"]),confidence:z50.enum(["exact","estimated","metered"]),basis:z50.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z51}from"zod";var UserTourDTOSchema,UserTourDTO,UserTourResponseSchema,UserTourListResponseSchema,init_tour_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/tour.dto.js"(){"use strict";init_create_dto();init_response();UserTourDTOSchema=z51.object({tourId:z51.string(),version:z51.string(),status:z51.string(),completedAt:z51.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z51.array(UserTourDTOSchema))}});import{z as z52}from"zod";var SUPPORT_REPORT_CATEGORIES,SupportReportCategorySchema,SUPPORT_REPORT_STATUSES,SupportReportStatusSchema,SupportReportSourceSchema,SupportReportDeliveryStatusSchema,SUPPORT_REPORT_LINK_KINDS,SupportReportLinkKindSchema,SupportReportEventKindSchema,SupportReportActorKindSchema,SupportReportTagSchema,SupportReportHttpUrlSchema,SupportReportContextInputSchema,CreateSupportReportInputSchema,SupportReportListQuerySchema,UpdateSupportReportInputSchema,CreateSupportReportMessageInputSchema,CreateSupportReportLinkInputSchema,SupportReportActorDTOSchema,SupportReportLinkDTOSchema,SupportReportLinkDTO,SupportReportEventDTOSchema,SupportReportEventDTO,SupportReportSummaryDTOSchema,SupportReportSummaryDTO,SupportReportDetailDTOSchema,SupportReportDetailDTO,SupportReportListDTOSchema,SupportReportListDTO,CreateSupportReportResultDTOSchema,CreateSupportReportResultDTO,init_support_report_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/support-report.dto.js"(){"use strict";init_create_dto();SUPPORT_REPORT_CATEGORIES=[{value:"account_billing",label:"Account & billing"},{value:"project_issues",label:"Project issues"},{value:"ai_prompt_output_quality",label:"AI prompt & output quality"},{value:"roles_access_collaboration",label:"Roles, access & collaboration"},{value:"code_technical_questions",label:"Code & technical questions"},{value:"others",label:"Other"}],SupportReportCategorySchema=z52.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z52.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z52.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z52.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z52.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z52.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z52.enum(["user","agent","system"]),SupportReportTagSchema=z52.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z52.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z52.object({organization:z52.object({id:z52.string().trim().min(1).max(255),name:z52.string().trim().max(240).optional()}),project:z52.object({id:z52.uuid(),name:z52.string().trim().max(240).optional(),createdAt:z52.coerce.date().optional()}).optional(),environment:z52.string().trim().max(255).optional(),clientVersion:z52.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z52.object({message:z52.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z52.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z52.string().trim().max(200).optional(),limit:z52.coerce.number().int().min(1).max(100).default(50),offset:z52.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z52.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z52.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z52.uuid().nullable().optional(),note:z52.string().trim().min(1).max(2e4).optional()}).refine(input=>Object.values(input).some(value=>value!==void 0),{message:"At least one report change is required"}),CreateSupportReportMessageInputSchema=z52.object({message:z52.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z52.object({kind:SupportReportLinkKindSchema,label:z52.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z52.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z52.object({kind:SupportReportActorKindSchema,id:z52.string().nullable(),name:z52.string().nullable()}),SupportReportLinkDTOSchema=z52.object({id:z52.uuid(),kind:SupportReportLinkKindSchema,label:z52.string(),url:SupportReportHttpUrlSchema,externalId:z52.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z52.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z52.object({id:z52.uuid(),kind:SupportReportEventKindSchema,body:z52.string().nullable(),metadata:z52.record(z52.string(),z52.unknown()),actor:SupportReportActorDTOSchema,createdAt:z52.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z52.object({id:z52.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z52.array(z52.string()),source:SupportReportSourceSchema,message:z52.string(),reporter:z52.object({id:z52.string().nullable(),name:z52.string().nullable(),email:z52.string().nullable()}),organization:z52.object({id:z52.string().nullable(),name:z52.string()}),project:z52.object({id:z52.uuid().nullable(),name:z52.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z52.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z52.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z52.string().nullable(),deliveredAt:z52.coerce.date().nullable()}).nullable(),duplicateOfReportId:z52.uuid().nullable(),resolvedAt:z52.coerce.date().nullable(),createdAt:z52.coerce.date(),updatedAt:z52.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z52.string().nullable(),clientVersion:z52.string().nullable(),links:z52.array(SupportReportLinkDTOSchema),events:z52.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z52.object({reports:z52.array(SupportReportSummaryDTOSchema),total:z52.number().int().nonnegative(),statusCounts:z52.object({new:z52.number().int().nonnegative(),in_progress:z52.number().int().nonnegative(),waiting:z52.number().int().nonnegative(),resolved:z52.number().int().nonnegative(),duplicate:z52.number().int().nonnegative(),irrelevant:z52.number().int().nonnegative(),ignored:z52.number().int().nonnegative()}),limit:z52.number().int().positive(),offset:z52.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z52.object({id:z52.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z52.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z53}from"zod";var OPS_RECENT_CHAT_MAX_WINDOW_MS,OpsChatTimestampInputSchema,OpsRecentChatInputSchema,OpsRecentChatMessageSchema,OpsRecentChatResponseSchema,OpsRecentChatResponseDTO,init_ops_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-chat.dto.js"(){"use strict";init_ops();init_create_dto();OPS_RECENT_CHAT_MAX_WINDOW_MS=10080*60*1e3,OpsChatTimestampInputSchema=z53.iso.datetime({offset:!0}).pipe(z53.coerce.date()),OpsRecentChatInputSchema=z53.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z53.string().trim().min(1).max(255).optional(),limit:z53.coerce.number().int().min(1).max(200).default(100),cursor:z53.string().trim().min(1).max(2e3).optional(),slim:z53.boolean().default(!0),reason:z53.string().trim().min(1).max(1e3)}).refine(input=>input.from<=(input.to??new Date),{message:"from must be before or equal to to",path:["from"]}).refine(input=>(input.to??new Date).getTime()-input.from.getTime()<=OPS_RECENT_CHAT_MAX_WINDOW_MS,{message:"recent chat window cannot exceed 7 days",path:["from"]}).refine(input=>!input.cursor||!!input.to,{message:"to is required when continuing with a cursor",path:["to"]}),OpsRecentChatMessageSchema=z53.object({id:z53.string(),messageId:z53.string(),env:z53.string(),versionId:z53.string().nullable(),userId:z53.string().nullable(),role:z53.string(),parts:z53.array(z53.record(z53.string(),z53.unknown())),metadata:z53.object({status:z53.string().optional(),traceUrl:z53.string().optional(),externalFileChanges:z53.array(z53.unknown()).optional()}),stats:z53.object({toolCount:z53.number().int().nonnegative(),failedToolCount:z53.number().int().nonnegative()}),createdAt:z53.iso.datetime({offset:!0}),project:z53.object({id:z53.string(),name:z53.string(),displayName:z53.string().nullable(),organizationId:z53.string().nullable()})}),OpsRecentChatResponseSchema=z53.object({target:z53.object({backendProfile:OpsBackendProfileSchema,projectEnv:z53.string().nullable()}),window:z53.object({from:z53.iso.datetime({offset:!0}),to:z53.iso.datetime({offset:!0})}),messages:z53.object({items:z53.array(OpsRecentChatMessageSchema),nextCursor:z53.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z54}from"zod";function createAgentRunWebhookEventDataSchema(status){return z54.object({run:z54.object({id:z54.string(),agentName:z54.string(),trigger:z54.string(),status:z54.literal(status),startedAt:z54.string().nullable(),finishedAt:z54.string().nullable(),reason:z54.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEntryBatchWindowSecondsSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AgentReviewRequestedWebhookEventDataSchema,AgentReviewResolvedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,MediaGeneratedWebhookEventDataSchema,MediaProcessingFailedWebhookEventDataSchema,DomainCreatedWebhookEventDataSchema,DomainDeletedWebhookEventDataSchema,LabelChangedWebhookEventDataSchema,LocaleCreatedWebhookEventDataSchema,LocaleDefaultChangedWebhookEventDataSchema,LocaleDeletedWebhookEventDataSchema,EnvironmentCreatedWebhookEventDataSchema,EnvironmentDeletedWebhookEventDataSchema,EnvironmentMergedWebhookEventDataSchema,EnvironmentRestoredWebhookEventDataSchema,WEBHOOK_EVENT_DATA_SCHEMAS,WebhookEventFamilySchema,WebhookDestinationKindSchema,WebhookHeaderValueInputSchema,WebhookHeaderInputSchema,WebhookHeaderDTOSchema,WebhookFilterSchema,JsonValueSchema,CreateProjectWebhookRequestSchema,UpdateProjectWebhookRequestSchema,TestProjectWebhookRequestSchema,WebhookDeliveryStatusSchema,ProjectWebhookDTOSchema,ProjectWebhookDTO,WebhookDeliveryDTOSchema,WebhookDeliveryDTO,WebhookDeliveriesPageSchema,WebhookDeliveryAttemptDTOSchema,WebhookDeliveryAttemptDTO,ProjectWebhookResponseSchema,ProjectWebhooksListResponseSchema,WebhookDeliveriesListResponseSchema,WebhookDeliveryAttemptsListResponseSchema,init_webhook_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/webhook.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();init_env_status_dto();init_project_domain_dto();WEBHOOK_EVENT_TYPES=["entry.changed","form.submitted","publish.started","publish.succeeded","publish.failed","publish.unpublished","agent.run.started","agent.run.completed","agent.run.failed","agent.run.cancelled","agent.review.requested","agent.review.resolved","analytics.report_ready","media.uploaded","media.updated","media.deleted","media.generated","media.processing_failed","domain.created","domain.deleted","label.changed","locale.created","locale.default_changed","locale.deleted","environment.created","environment.deleted","environment.merged","environment.restored"],WebhookEventTypeSchema=z54.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z54.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z54.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z54.enum(["main","all"]),WebhookEntryBatchWindowSecondsSchema=z54.union([z54.literal(0),z54.literal(5),z54.literal(30),z54.literal(60)]),EntryChangedWebhookEventDataSchema=z54.object({reason:WebhookEntryChangeReasonSchema,operationId:z54.string().optional(),batch:z54.object({index:z54.number().int().positive(),total:z54.number().int().positive()}).optional(),changes:z54.array(z54.object({action:WebhookEntryChangeActionSchema,contentType:z54.string(),id:z54.string(),documentId:z54.string(),locale:z54.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z54.object({form:z54.object({id:z54.string(),label:z54.string()}),submission:z54.object({id:z54.string(),data:z54.record(z54.string(),z54.unknown()),submittedAt:z54.string()})}),PublishStartedWebhookEventDataSchema=z54.object({publication:z54.object({status:z54.literal("publishing"),startedAt:z54.string()})}),PublishSucceededWebhookEventDataSchema=z54.object({publication:z54.object({status:z54.literal("published"),url:z54.string(),publishedAt:z54.string(),firstPublish:z54.boolean()})}),PublishFailedWebhookEventDataSchema=z54.object({publication:z54.object({status:z54.literal("failed"),reason:z54.string()})}),PublishUnpublishedWebhookEventDataSchema=z54.object({publication:z54.object({previousUrl:z54.string(),unpublishedAt:z54.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z54.object({review:z54.object({id:z54.string(),runId:z54.string(),agentName:z54.string(),classification:z54.string(),summary:z54.string(),reasons:z54.array(z54.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z54.object({review:z54.object({id:z54.string(),runId:z54.string(),agentName:z54.string(),resolution:z54.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z54.object({report:z54.object({weekStart:z54.string(),weekEnd:z54.string(),pageviews:z54.number(),visitors:z54.number(),previousPageviews:z54.number(),previousVisitors:z54.number()})}),MediaAssetWebhookEventDataSchema=z54.object({id:z54.string().nullable(),name:z54.string().nullable(),type:z54.string(),mimeType:z54.string().nullable(),fileSize:z54.number().nullable()}),MediaUploadedWebhookEventDataSchema=z54.object({asset:MediaAssetWebhookEventDataSchema,operation:z54.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z54.object({asset:MediaAssetWebhookEventDataSchema,operation:z54.enum(["updated","moved","analysis"]),analysis:z54.object({category:z54.string(),status:z54.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z54.object({asset:MediaAssetWebhookEventDataSchema,operation:z54.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z54.object({asset:MediaAssetWebhookEventDataSchema,operation:z54.literal("generated"),generation:z54.object({model:z54.string(),mode:z54.string()})}),MediaProcessingFailedWebhookEventDataSchema=z54.object({asset:MediaAssetWebhookEventDataSchema,operation:z54.enum(["analysis","generation"]),failure:z54.object({code:z54.string()})}),DomainCreatedWebhookEventDataSchema=z54.object({domain:z54.object({id:z54.string(),hostname:z54.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z54.object({domain:z54.object({id:z54.string(),hostname:z54.string()})}),LabelChangedWebhookEventDataSchema=z54.object({changes:z54.array(z54.object({action:z54.enum(["created","updated","deleted"]),key:z54.string(),locale:z54.string(),value:z54.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z54.object({locale:z54.object({code:z54.string(),isDefault:z54.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z54.object({locale:z54.object({code:z54.string(),previousCode:z54.string()})}),LocaleDeletedWebhookEventDataSchema=z54.object({locale:z54.object({code:z54.string(),entriesDeleted:z54.number().int().nonnegative(),labelsDeleted:z54.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z54.object({environment:z54.object({name:EnvSchema,parent:EnvSchema})}),EnvironmentDeletedWebhookEventDataSchema=z54.object({environment:z54.object({name:EnvSchema})}),EnvironmentMergedWebhookEventDataSchema=z54.object({merge:z54.object({id:z54.string(),from:EnvSchema,to:EnvSchema,applied:z54.array(z54.object({surface:SurfaceNameSchema,count:z54.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z54.object({environment:z54.object({name:EnvSchema}),version:z54.object({versionId:z54.uuid(),name:z54.string()})}),WEBHOOK_EVENT_DATA_SCHEMAS={"entry.changed":EntryChangedWebhookEventDataSchema,"form.submitted":FormSubmittedWebhookEventDataSchema,"publish.started":PublishStartedWebhookEventDataSchema,"publish.succeeded":PublishSucceededWebhookEventDataSchema,"publish.failed":PublishFailedWebhookEventDataSchema,"publish.unpublished":PublishUnpublishedWebhookEventDataSchema,"agent.run.started":createAgentRunWebhookEventDataSchema("running"),"agent.run.completed":createAgentRunWebhookEventDataSchema("completed"),"agent.run.failed":createAgentRunWebhookEventDataSchema("failed"),"agent.run.cancelled":createAgentRunWebhookEventDataSchema("cancelled"),"agent.review.requested":AgentReviewRequestedWebhookEventDataSchema,"agent.review.resolved":AgentReviewResolvedWebhookEventDataSchema,"analytics.report_ready":AnalyticsReportReadyWebhookEventDataSchema,"media.uploaded":MediaUploadedWebhookEventDataSchema,"media.updated":MediaUpdatedWebhookEventDataSchema,"media.deleted":MediaDeletedWebhookEventDataSchema,"media.generated":MediaGeneratedWebhookEventDataSchema,"media.processing_failed":MediaProcessingFailedWebhookEventDataSchema,"domain.created":DomainCreatedWebhookEventDataSchema,"domain.deleted":DomainDeletedWebhookEventDataSchema,"label.changed":LabelChangedWebhookEventDataSchema,"locale.created":LocaleCreatedWebhookEventDataSchema,"locale.default_changed":LocaleDefaultChangedWebhookEventDataSchema,"locale.deleted":LocaleDeletedWebhookEventDataSchema,"environment.created":EnvironmentCreatedWebhookEventDataSchema,"environment.deleted":EnvironmentDeletedWebhookEventDataSchema,"environment.merged":EnvironmentMergedWebhookEventDataSchema,"environment.restored":EnvironmentRestoredWebhookEventDataSchema},WebhookEventFamilySchema=z54.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z54.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z54.discriminatedUnion("source",[z54.object({source:z54.literal("literal"),value:z54.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z54.object({source:z54.literal("secret"),key:z54.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z54.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z54.object({name:z54.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z54.object({name:z54.string(),source:z54.enum(["literal","secret"]),secretKey:z54.string().nullable(),secretPrefix:z54.string().nullable(),configured:z54.literal(!0)}),WebhookFilterSchema=z54.object({environment:WebhookEnvironmentScopeSchema.optional(),formId:z54.string().min(1).max(255).optional(),agentName:z54.string().min(1).max(120).optional(),mediaType:z54.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z54.string().min(1).max(255).optional(),locale:z54.string().min(1).max(120).optional()}),JsonValueSchema=z54.lazy(()=>z54.union([z54.string(),z54.number(),z54.boolean(),z54.null(),z54.array(JsonValueSchema),z54.record(z54.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z54.object({name:z54.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z54.url(),enabled:z54.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z54.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z54.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z54.object({name:z54.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z54.url().optional(),enabled:z54.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z54.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z54.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z54.object({eventType:WebhookEventTypeSchema.optional(),data:z54.record(z54.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z54.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z54.uuid(),name:z54.string(),eventType:WebhookEventTypeSchema,enabled:z54.boolean(),destination:z54.object({host:z54.string(),maskedUrl:z54.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z54.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z54.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z54.coerce.date().nullable(),deliveryStats24h:z54.object({succeeded:z54.number().int().nonnegative(),failed:z54.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z54.uuid(),projectId:z54.uuid(),env:EnvSchema,eventId:z54.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z54.number().int().positive(),test:z54.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z54.number().int().nonnegative(),responseStatus:z54.number().int().nullable(),lastErrorCode:z54.string().nullable(),lastErrorMessage:z54.string().nullable(),payloadAvailable:z54.boolean(),destination:z54.object({host:z54.string(),maskedUrl:z54.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z54.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z54.string().nullable(),qstashMessageId:z54.string().nullable(),deliveredAt:z54.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z54.object({items:z54.array(WebhookDeliveryDTOSchema),pagination:z54.object({page:z54.number().int().positive(),limit:z54.number().int().positive(),total:z54.number().int().nonnegative(),totalPages:z54.number().int().positive(),hasMore:z54.boolean()}),stats:z54.object({total:z54.number().int().nonnegative(),succeeded:z54.number().int().nonnegative(),failed:z54.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z54.object({id:z54.uuid(),deliveryId:z54.uuid(),attempt:z54.number().int().positive(),status:z54.enum(["delivering","succeeded","failed"]),responseStatus:z54.number().int().nullable(),durationMs:z54.number().int().nonnegative(),responseExcerpt:z54.string().nullable(),errorCode:z54.string().nullable(),errorMessage:z54.string().nullable(),createdAt:z54.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z54.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z54.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z55}from"zod";var PREVIEW_FEATURE_REGISTRY,previewFeatureKeys,PreviewFeatureDTOSchema,PreviewFeatureDTO,PreviewFeatureResponseSchema,PreviewFeatureListResponseSchema,init_preview_feature_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/preview-feature.dto.js"(){"use strict";init_create_dto();init_response();PREVIEW_FEATURE_REGISTRY={"fimo-2":{key:"fimo-2",defaultEnabled:!1}},previewFeatureKeys=Object.keys(PREVIEW_FEATURE_REGISTRY),PreviewFeatureDTOSchema=z55.object({key:z55.enum(previewFeatureKeys),enabled:z55.boolean(),dismissed:z55.boolean().default(!1),interacted:z55.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema),PreviewFeatureResponseSchema=createResponseSchema(PreviewFeatureDTOSchema),PreviewFeatureListResponseSchema=createResponseSchema(z55.array(PreviewFeatureDTOSchema))}});import{z as z56}from"zod";var SubscriptionStatusSchema,CreditBalanceBreakdownDTOSchema,CreditBalanceBreakdownDTO,SubscriptionPlanDTOSchema,SubscriptionPlanDTO,SubscriptionPaymentMethodDTOSchema,SubscriptionPaymentMethodDTO,SubscriptionPricingDTOSchema,SubscriptionPricingDTO,SubscriptionDetailsDTOSchema,SubscriptionDetailsDTO,CreditAlertDTOSchema,CreditAlertDTO,PlanAllocationDTOSchema,PlanAllocationDTO,LatestCancellationDTOSchema,LatestCancellationDTO,OrganizationSubscriptionDTOSchema,OrganizationSubscriptionDTO,BaseCreditTopupRequestSchema,FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema,CreditTopupRequestDTOSchema,CreditTopupRequestDTO,CreditTopupResponseDTOSchema,CreditTopupResponseDTO,init_subscription_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/subscription.dto.js"(){"use strict";init_common();init_create_dto();init_billing_dto();SubscriptionStatusSchema=z56.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z56.object({total:z56.number(),base:z56.number(),purchases:z56.number(),awards:z56.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z56.object({id:z56.string(),name:z56.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z56.object({type:z56.string(),brand:z56.string().nullable(),last4:z56.string().nullable(),expirationDate:z56.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z56.object({currency:z56.string(),nextPaymentAmount:z56.number().nullable(),nextPaymentAt:z56.string().nullable(),billingInterval:z56.string().nullable(),totalAmount:z56.number().nullable(),discountAmount:z56.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z56.object({id:z56.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z56.string().nullable(),currentPeriodEndsAt:z56.string().nullable(),renewsAt:z56.string().nullable(),cancelAt:z56.string().nullable(),renewAutomatically:z56.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z56.object({type:z56.enum(["low_balance","critical_balance","approaching_limit"]),message:z56.string(),estimatedPromptsRemaining:z56.number().nullable(),avgCostPerPrompt:z56.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z56.object({monthlyCredits:z56.number().nullable(),usedThisPeriod:z56.number(),remainingThisPeriod:z56.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z56.object({organizationId:z56.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z56.string().nullable(),tenureDays:z56.number().int().nonnegative(),capturedAt:z56.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z56.object({hasSubscription:z56.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z56.number().nullable(),alerts:z56.array(CreditAlertDTOSchema),portalUrl:z56.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z56.object({creditCount:z56.number().int().positive(),expiresAt:z56.string().datetime().nullable().optional(),message:z56.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z56.literal("free"),amountCents:z56.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z56.literal("purchase"),amountCents:z56.number().int().positive()}),CreditTopupRequestDTOSchema=z56.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z56.object({success:z56.boolean(),transactionId:z56.string().nullable(),newBalance:z56.number(),creditCount:z56.number(),type:z56.enum(["free","purchase"]),invoiceId:z56.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z57}from"zod";var UsageSummaryDTOSchema,UsageSummaryDTO,UsageByProjectDTOSchema,UsageByProjectDTO,UsageByUserDTOSchema,UsageByUserDTO,UsageTimelineItemDTOSchema,UsageTimelineItemDTO,UsageByUserForProjectDTOSchema,UsageByUserForProjectDTO,ProjectUsageDetailDTOSchema,ProjectUsageDetailDTO,OrganizationUsageDTOSchema,OrganizationUsageDTO,init_usage_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage.dto.js"(){"use strict";init_create_dto();UsageSummaryDTOSchema=z57.object({totalCredits:z57.number(),totalCostUsd:z57.number(),totalMessages:z57.number(),avgCostPerMessage:z57.number(),periodStart:z57.string().nullable(),periodEnd:z57.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z57.object({projectId:z57.string(),projectName:z57.string(),projectDisplayName:z57.string().nullable(),credits:z57.number(),costUsd:z57.number(),messages:z57.number(),percentage:z57.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z57.object({userId:z57.string(),userName:z57.string().nullable(),userEmail:z57.string().email().nullable(),credits:z57.number(),costUsd:z57.number(),messages:z57.number(),percentage:z57.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z57.object({date:z57.string(),credits:z57.number(),costUsd:z57.number(),messages:z57.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z57.object({userId:z57.string(),userName:z57.string().nullable(),userEmail:z57.string().email().nullable(),credits:z57.number(),costUsd:z57.number(),messages:z57.number(),percentage:z57.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z57.object({projectId:z57.string(),projectName:z57.string(),projectDisplayName:z57.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z57.array(UsageByUserForProjectDTOSchema),timeline:z57.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z57.object({summary:UsageSummaryDTOSchema,byProject:z57.array(UsageByProjectDTOSchema),byUser:z57.array(UsageByUserDTOSchema),timeline:z57.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z58}from"zod";var TimeRangePresetSchema,SortOrderSchema,UsageAnalyticsQuerySchema,UsageOverviewSummaryDTOSchema,UsageOverviewSummaryDTO,UsageTimelinePointDTOSchema,UsageTimelinePointDTO,OrganizationUsageRowDTOSchema,OrganizationUsageRowDTO,UserUsageRowDTOSchema,UserUsageRowDTO,ProjectUsageRowDTOSchema,ProjectUsageRowDTO,UsageDistributionItemDTOSchema,UsageDistributionItemDTO,UsageHeatmapPointDTOSchema,UsageHeatmapPointDTO,UsageOverviewResponseDTOSchema,UsageOverviewResponseDTO,UsagePaginationDTOSchema,UsagePaginationDTO,UsageByOrganizationResponseDTOSchema,UsageByOrganizationResponseDTO,ExtendedUserUsageRowDTOSchema,ExtendedUserUsageRowDTO,UsageByUserResponseDTOSchema,UsageByUserResponseDTO,ExtendedProjectUsageRowDTOSchema,ExtendedProjectUsageRowDTO,UsageByProjectResponseDTOSchema,UsageByProjectResponseDTO,ExportFormatSchema,UsageExportQuerySchema,PeekUsageMetricsDTOSchema,PeekUsageMetricsDTO,OrganizationPeekDTOSchema,OrganizationPeekDTO,UserPeekDTOSchema,UserPeekDTO,ProjectPeekDTOSchema,ProjectPeekDTO,init_usage_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage-analytics.dto.js"(){"use strict";init_create_dto();TimeRangePresetSchema=z58.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z58.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z58.object({startDate:z58.string().optional(),endDate:z58.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z58.coerce.number().int().positive().default(1),limit:z58.coerce.number().int().positive().max(100).default(20),sortBy:z58.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z58.string().optional()}),UsageOverviewSummaryDTOSchema=z58.object({totalCredits:z58.number(),totalCostUsd:z58.number(),totalMessages:z58.number(),avgCostPerMessage:z58.number(),avgCreditsPerMessage:z58.number(),periodStart:z58.string(),periodEnd:z58.string(),creditsChange:z58.number().nullable(),costChange:z58.number().nullable(),messagesChange:z58.number().nullable()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z58.object({date:z58.string(),credits:z58.number(),costUsd:z58.number(),messages:z58.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z58.object({organizationId:z58.string(),organizationName:z58.string(),credits:z58.number(),costUsd:z58.number(),messages:z58.number(),percentage:z58.number(),userCount:z58.number(),projectCount:z58.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z58.object({userId:z58.string(),userName:z58.string().nullable(),userEmail:z58.string().nullable(),userImage:z58.string().nullable(),organizationId:z58.string().nullable(),organizationName:z58.string().nullable(),credits:z58.number(),costUsd:z58.number(),messages:z58.number(),percentage:z58.number(),projectCount:z58.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z58.object({projectId:z58.string(),projectName:z58.string(),projectDisplayName:z58.string().nullable(),organizationId:z58.string(),organizationName:z58.string(),credits:z58.number(),costUsd:z58.number(),messages:z58.number(),percentage:z58.number(),userCount:z58.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z58.object({id:z58.string(),name:z58.string(),value:z58.number(),percentage:z58.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z58.object({day:z58.number(),hour:z58.number(),value:z58.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z58.object({summary:UsageOverviewSummaryDTOSchema,timeline:z58.array(UsageTimelinePointDTOSchema),topOrganizations:z58.array(OrganizationUsageRowDTOSchema),topUsers:z58.array(UserUsageRowDTOSchema),topProjects:z58.array(ProjectUsageRowDTOSchema),creditDistribution:z58.array(UsageDistributionItemDTOSchema),heatmap:z58.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z58.object({page:z58.number(),limit:z58.number(),totalItems:z58.number(),totalPages:z58.number(),hasMore:z58.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z58.object({organizations:z58.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z58.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z58.object({users:z58.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z58.string(),ownerName:z58.string().nullable(),ownerEmail:z58.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z58.object({projects:z58.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z58.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z58.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z58.object({credits:z58.number(),costUsd:z58.number(),messages:z58.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z58.object({id:z58.string(),name:z58.string(),createdAt:z58.string(),memberCount:z58.number(),projectCount:z58.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z58.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z58.object({id:z58.string(),name:z58.string().nullable(),email:z58.string(),image:z58.string().nullable(),createdAt:z58.string(),organizationCount:z58.number(),projectCount:z58.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z58.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z58.object({id:z58.string(),name:z58.string(),displayName:z58.string().nullable(),createdAt:z58.string(),organizationId:z58.string(),organizationName:z58.string(),ownerId:z58.string(),ownerName:z58.string().nullable(),ownerEmail:z58.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z58.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z59}from"zod";var SandboxProcessStatusSchema,PresetSandboxCommandSchema,ExecuteSandboxCommandRequestDTOSchema,ExecuteSandboxCommandRequestDTO,SandboxProcessInfoDTOSchema,SandboxProcessInfoDTO,SandboxProcessInfoResponseSchema,SandboxProcessListDTOSchema,SandboxProcessListDTO,SandboxProcessListResponseSchema,ExecuteSandboxCommandResponseDTOSchema,ExecuteSandboxCommandResponseDTO,PresetCommandResponseDTOSchema,PresetCommandResponseDTO,PresetCommandResponseSchema,init_sandbox_command_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/sandbox-command.dto.js"(){"use strict";init_env();init_create_dto();init_response();SandboxProcessStatusSchema=z59.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z59.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z59.object({command:z59.string().min(1).max(1e4),cwd:z59.string().optional(),projectEnv:EnvSchema.optional(),env:z59.record(z59.string(),z59.string()).optional(),name:z59.string().optional(),waitForCompletion:z59.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z59.object({identifier:z59.string(),status:SandboxProcessStatusSchema,command:z59.string().optional(),startedAt:z59.string().optional(),exitCode:z59.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z59.object({processes:z59.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z59.object({processId:z59.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z59.object({success:z59.boolean(),message:z59.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z60}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common();init_attachments();init_env();init_realtime();init_references();init_content_fields();init_audit_log();init_ops();init_project_dto();init_project_env_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_activation_dto();init_agent_list_item_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_audit_log_dto();init_env_status_dto();init_env_diff_summary_dto();init_project_analytics_dto();init_project_access_dto();init_project_invite_dto();init_publication_dto();init_sandbox_dto();init_organization_dto();init_billing_dto();init_payment_method_dto();init_user_dto();init_content_dto();init_unique_conflict_dto();init_schema_transition_rejected_dto();init_cms_display_defaults_dto();init_asset_dto();init_translation_dto();init_document_dto();init_chat_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_webhook_dto();init_preview_feature_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto()}});import{createHash}from"node:crypto";function normalizeApiUrl(input){let trimmed=input.trim();try{let url=new URL(trimmed),pathname=url.pathname.replace(/\/+$/,"");return`${url.protocol}//${url.host}${pathname}`}catch{return trimmed.replace(/\/+$/,"")}}function hashApiUrl(input){return createHash("sha256").update(normalizeApiUrl(input)).digest("hex").slice(0,6)}function safeHostLabel(host){return host.replace(/:/g,"-").replace(/[^a-zA-Z0-9.-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").toLowerCase()}function credentialsFilename(apiUrl){let normalized=normalizeApiUrl(apiUrl),hostLabel="unknown";try{hostLabel=safeHostLabel(new URL(normalized).host)}catch{}return hostLabel.length===0&&(hostLabel="unknown"),`${hostLabel}-${hashApiUrl(apiUrl)}.json`}var init_credentials_path=__esm({"src/cli/utils/credentials-path.ts"(){__name(normalizeApiUrl,"normalizeApiUrl");__name(hashApiUrl,"hashApiUrl");__name(safeHostLabel,"safeHostLabel");__name(credentialsFilename,"credentialsFilename")}});import fs from"node:fs";import{homedir}from"node:os";import path,{join}from"node:path";import{fileURLToPath}from"node:url";function readReleaseManifest(){try{let raw=fs.readFileSync(RELEASE_FILE,"utf8"),parsed=JSON.parse(raw),manifest={};return typeof parsed.apiUrl=="string"&&parsed.apiUrl.length>0&&(manifest.apiUrl=parsed.apiUrl),typeof parsed.webUrl=="string"&&parsed.webUrl.length>0&&(manifest.webUrl=parsed.webUrl),manifest}catch{return{}}}function loadConfig(){let baked=readReleaseManifest(),apiUrl=process.env.FIMO_API_URL?.trim()||baked.apiUrl||DEFAULT_API_URL,webUrl=process.env.FIMO_WEB_URL?.trim()||baked.webUrl||DEFAULT_WEB_URL,configDir=join(process.env.XDG_CONFIG_HOME||join(homedir(),".config"),"fimo"),credentialsDir=join(configDir,"credentials");return{apiUrl,webUrl,configDir,credentialsDir,credentialsFile:join(credentialsDir,credentialsFilename(apiUrl))}}var DEFAULT_API_URL,DEFAULT_WEB_URL,THIS_FILE,CLI_ROOT,RELEASE_FILE,init_config=__esm({"src/cli/config.ts"(){init_credentials_path();DEFAULT_API_URL="http://localhost:3000",DEFAULT_WEB_URL="http://localhost:5173",THIS_FILE=fileURLToPath(import.meta.url),CLI_ROOT=path.resolve(path.dirname(THIS_FILE),"..",".."),RELEASE_FILE=path.resolve(CLI_ROOT,"release.json");__name(readReleaseManifest,"readReleaseManifest");__name(loadConfig,"loadConfig")}});import fs2 from"node:fs";function ensureCredentialsDir(cfg){fs2.existsSync(cfg.credentialsDir)||fs2.mkdirSync(cfg.credentialsDir,{recursive:!0})}function readCredentials(cfg=loadConfig()){if(!fs2.existsSync(cfg.credentialsFile))return null;let raw=fs2.readFileSync(cfg.credentialsFile,"utf-8");return JSON.parse(raw)}function writeCredentials(credentials,cfg=loadConfig()){ensureCredentialsDir(cfg);let tmpFile=`${cfg.credentialsFile}.tmp-${process.pid}`;fs2.writeFileSync(tmpFile,JSON.stringify(credentials,null,2)),fs2.renameSync(tmpFile,cfg.credentialsFile)}function clearCredentials(cfg=loadConfig()){fs2.existsSync(cfg.credentialsFile)&&fs2.unlinkSync(cfg.credentialsFile)}function setActiveOrganization(organization,cfg=loadConfig()){let creds=requireCredentials(cfg);writeCredentials({...creds,activeOrganization:organization},cfg)}function recordAuthFailure(cfg=loadConfig()){let creds=readCredentials(cfg);creds&&writeCredentials({...creds,lastFailedAuthAt:new Date().toISOString()},cfg)}function requireToken(cfg=loadConfig()){return requireCredentials(cfg).access_token}function requireCredentials(cfg=loadConfig()){let creds=readCredentials(cfg);if(!creds?.access_token)throw new NotAuthenticatedError(cfg.apiUrl);return creds}var NotAuthenticatedError,init_auth=__esm({"src/cli/auth.ts"(){init_config();NotAuthenticatedError=class extends Error{static{__name(this,"NotAuthenticatedError")}apiUrl;constructor(apiUrl,message="You are not signed in to Fimo."){super(message),this.name="NotAuthenticatedError",this.apiUrl=apiUrl}};__name(ensureCredentialsDir,"ensureCredentialsDir");__name(readCredentials,"readCredentials");__name(writeCredentials,"writeCredentials");__name(clearCredentials,"clearCredentials");__name(setActiveOrganization,"setActiveOrganization");__name(recordAuthFailure,"recordAuthFailure");__name(requireToken,"requireToken");__name(requireCredentials,"requireCredentials")}});import{spawnSync}from"node:child_process";import fs3 from"node:fs";import path2 from"node:path";import{setTimeout as sleep}from"node:timers/promises";function isPublishedInstall(cliRoot=CLI_ROOT){return fs3.existsSync(path2.join(cliRoot,"release.json"))}function buildSkipsVersionCheck(cliRoot=CLI_ROOT,readFile5=defaultReadFile){try{return JSON.parse(readFile5(path2.join(cliRoot,"release.json"))).skipVersionCheck===!0}catch{return!1}}function defaultReadFile(file){return fs3.readFileSync(file,"utf8")}function resolveGlobalFimoRoot(){let result=spawnSync("npm",["root","-g"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:GLOBAL_ROOT_TIMEOUT_MS});return result.error||result.status!==0||typeof result.stdout!="string"||result.stdout.trim().length===0?null:path2.resolve(result.stdout.trim(),"fimo")}function normalizedPath(input){try{return fs3.realpathSync(input)}catch{return path2.resolve(input)}}function autoUpgradeEnabled(options={}){let usesDefaults=Object.keys(options).length===0;if(usesDefaults&&defaultEligibility!==void 0)return defaultEligibility;let env=options.env??process.env,cliRoot=options.cliRoot??CLI_ROOT,published=options.published??isPublishedInstall(cliRoot);if(env.FIMO_AUTO_UPGRADE!=="1"||!published||buildSkipsVersionCheck(cliRoot))return usesDefaults&&(defaultEligibility=!1),!1;let globalFimoRoot=options.globalFimoRoot===void 0?resolveGlobalFimoRoot():options.globalFimoRoot;if(!globalFimoRoot)return usesDefaults&&(defaultEligibility=!1),!1;let eligible=normalizedPath(cliRoot)===normalizedPath(globalFimoRoot);return usesDefaults&&(defaultEligibility=eligible),eligible}async function acquireLock(lockDir){let deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{fs3.mkdirSync(lockDir);return}catch(error){if(error.code!=="EEXIST")throw error}let stale=!1;try{stale=Date.now()-fs3.statSync(lockDir).mtimeMs>LOCK_STALE_MS}catch{continue}if(stale){try{fs3.rmdirSync(lockDir)}catch{}continue}if(Date.now()>=deadline)throw new Error("auto-upgrade lock timeout");await sleep(LOCK_POLL_MS)}}function readGlobalFimoVersion(){let root2=resolveGlobalFimoRoot();if(!root2)return null;try{let pkg=JSON.parse(fs3.readFileSync(path2.join(root2,"package.json"),"utf8"));return typeof pkg.version=="string"?pkg.version:null}catch{return null}}async function autoUpgradeGlobal(latest){if(!VERSION_PATTERN.test(latest))return!1;let lockDir=path2.join(loadConfig().configDir,"auto-upgrade.lock");try{fs3.mkdirSync(path2.dirname(lockDir),{recursive:!0}),await acquireLock(lockDir)}catch{return!1}try{if(readGlobalFimoVersion()===latest)return!0;let install=spawnSync("npm",["install","-g",`fimo@${latest}`],{stdio:["ignore","ignore","inherit"],timeout:INSTALL_TIMEOUT_MS});return install.error||install.status!==0?!1:readGlobalFimoVersion()===latest}finally{try{fs3.rmdirSync(lockDir)}catch{}}}var INSTALL_TIMEOUT_MS,GLOBAL_ROOT_TIMEOUT_MS,LOCK_WAIT_MS,LOCK_STALE_MS,LOCK_POLL_MS,VERSION_PATTERN,defaultEligibility,init_auto_upgrade=__esm({"src/cli/auto-upgrade.ts"(){init_config();INSTALL_TIMEOUT_MS=12e4,GLOBAL_ROOT_TIMEOUT_MS=5e3,LOCK_WAIT_MS=18e4,LOCK_STALE_MS=3e5,LOCK_POLL_MS=500,VERSION_PATTERN=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;__name(isPublishedInstall,"isPublishedInstall");__name(buildSkipsVersionCheck,"buildSkipsVersionCheck");__name(defaultReadFile,"defaultReadFile");__name(resolveGlobalFimoRoot,"resolveGlobalFimoRoot");__name(normalizedPath,"normalizedPath");__name(autoUpgradeEnabled,"autoUpgradeEnabled");__name(acquireLock,"acquireLock");__name(readGlobalFimoVersion,"readGlobalFimoVersion");__name(autoUpgradeGlobal,"autoUpgradeGlobal")}});import fs4 from"node:fs";import path3 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";function getCliVersion(){try{let raw=fs4.readFileSync(PACKAGE_JSON_PATH,"utf8");return JSON.parse(raw).version??"0.0.0"}catch{return"0.0.0"}}var THIS_FILE2,CLI_ROOT2,PACKAGE_JSON_PATH,init_version=__esm({"src/cli/version.ts"(){THIS_FILE2=fileURLToPath2(import.meta.url),CLI_ROOT2=path3.resolve(path3.dirname(THIS_FILE2),"..",".."),PACKAGE_JSON_PATH=path3.join(CLI_ROOT2,"package.json");__name(getCliVersion,"getCliVersion")}});function lazyFetchQs(against,extras={}){let params=new URLSearchParams;against&&params.set("against",against);for(let[k,v]of Object.entries(extras))params.set(k,v);return params.toString()}function throwUnauthorized(cfg,status){try{recordAuthFailure(cfg)}catch{}throw new UnauthorizedError(cfg.apiUrl,status)}async function throwPermissionDenied(cfg,response){let required=[];try{let body=await response.json();required=Array.isArray(body.required)?body.required:body.required?[body.required]:[]}catch{}throw new PermissionDeniedError(cfg.apiUrl,required)}async function fimoFetch(url,init){let headers=new Headers(init.headers);headers.delete(CLI_VERSION_HEADER),headers.delete(CLI_AUTO_UPGRADE_HEADER);let canAutoUpgrade=process.argv[2]!=="git-credential"&&autoUpgradeEnabled();canAutoUpgrade&&(headers.set(CLI_VERSION_HEADER,getCliVersion()),headers.set(CLI_AUTO_UPGRADE_HEADER,"1"));let response=await fetch(url,{...init,headers});if(canAutoUpgrade&&response.status===426){let latest=response.headers.get(CLI_LATEST_HEADER);if(latest){await autoUpgradeGlobal(latest)||ui.warn({command:process.argv[2]??"fimo",message:`Could not upgrade to ${latest}; continuing with the current command.`});let retryHeaders=new Headers(init.headers);return retryHeaders.delete(CLI_VERSION_HEADER),retryHeaders.delete(CLI_AUTO_UPGRADE_HEADER),fetch(url,{...init,headers:retryHeaders})}}return response}function formatZodIssues(parsed){if(!parsed||typeof parsed!="object")return null;let error=parsed.error,issues=error&&typeof error=="object"&&"issues"in error?error.issues:void 0;return!Array.isArray(issues)||issues.length===0?null:issues.map(issue=>{let{path:path47,message}=issue;return`${Array.isArray(path47)&&path47.length>0?`${path47.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}var ApiRequestError,UnauthorizedError,PermissionDeniedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_ENV_HEADER,FimoApiClient,init_api=__esm({"src/cli/api.ts"(){init_esm();init_dist();init_auth();init_auto_upgrade();init_config();init_version();__name(lazyFetchQs,"lazyFetchQs");ApiRequestError=class extends Error{static{__name(this,"ApiRequestError")}status;method;path;detail;code;body;constructor(method,path47,status,detail,code2,body){super(`API ${method} ${path47} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path47,this.status=status,this.detail=detail,this.code=code2,this.body=body}},UnauthorizedError=class extends Error{static{__name(this,"UnauthorizedError")}apiUrl;status;constructor(apiUrl,status,message){super(message??`Session for ${apiUrl} expired or invalid (HTTP ${status}).`),this.name="UnauthorizedError",this.apiUrl=apiUrl,this.status=status}},PermissionDeniedError=class extends Error{static{__name(this,"PermissionDeniedError")}apiUrl;required;constructor(apiUrl,required=[],message){let detail=required.length?` Missing permission: ${required.join(", ")}.`:"";super(message??`You don't have permission to do this on ${apiUrl}.${detail}`),this.name="PermissionDeniedError",this.apiUrl=apiUrl,this.required=required}};__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");CLI_VERSION_HEADER="X-Fimo-CLI-Version",CLI_LATEST_HEADER="X-Fimo-CLI-Latest",CLI_AUTO_UPGRADE_HEADER="X-Fimo-CLI-Auto-Upgrade",FIMO_ENV_HEADER="X-Fimo-Env";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");FimoApiClient=class _FimoApiClient{constructor(cfg=loadConfig()){this.cfg=cfg}static{__name(this,"FimoApiClient")}env;withEnv(env){let next2=new _FimoApiClient(this.cfg);return next2.env=env,next2}formatError(status,text3,body){if(!text3)return String(status);if(body&&typeof body=="object"&&!Array.isArray(body)){let parsed=body;if(typeof parsed.message=="string"&&parsed.message.length>0){let partial=formatPartialResult(parsed);return partial?`${parsed.message} ${partial}`:parsed.message}if(typeof parsed.error=="string"&&parsed.error.length>0)return parsed.error;if(parsed.error&&typeof parsed.error=="object"&&"message"in parsed.error&&typeof parsed.error.message=="string")return parsed.error.message;let zodIssues=formatZodIssues(parsed);if(zodIssues)return zodIssues}return text3}async parseError(response){let text3=await response.text(),body;try{body=text3?JSON.parse(text3):void 0}catch{return{detail:this.formatError(response.status,text3)}}let code2=body&&typeof body=="object"&&!Array.isArray(body)&&typeof body.code=="string"?body.code:void 0;return{detail:this.formatError(response.status,text3,body),code:code2,body}}resolveAuthToken(){return process.env.FIMO_API_TOKEN?.trim()||requireToken(this.cfg)}async request(path47,init={},opts={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path47}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&!opts.allow403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new ApiRequestError(init.method??"GET",path47,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async rawRequest(path47,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path47}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new Error(`API ${init.method??"GET"} ${path47} failed: ${response.status} ${error.detail}`)}return response}tenantPath(projectId,route){if(!this.env)throw new Error("FimoApiClient: tenant-scoped call requires an env. Use `client.withEnv(env)` before calling tenant CRUD methods.");return`/api/tenant/${projectId}/envs/${encodeEnvPathSegment(this.env)}${route}`}projectEnvManagementPath(projectId,route){if(!this.env)throw new Error("FimoApiClient: env-scoped management call requires an env. Use `client.withEnv(env)` before calling env CRUD methods.");return`/api/management/projects/${projectId}/envs/${encodeEnvPathSegment(this.env)}${route}`}async listModels(projectId,query={}){let params=new URLSearchParams;query.modality&&params.set("modality",query.modality);for(let t2 of query.tag??[])params.append("tag",t2);query.q&&params.set("q",query.q),query.category&&params.set("category",query.category);let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models${qs?`?${qs}`:""}`)).data}async getModel(projectId,key){try{return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/${key}`)).data}catch(err){if(err instanceof ApiRequestError&&err.status===404)return null;throw err}}async estimateModel(projectId,key,options){return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/estimate`,{method:"POST",body:JSON.stringify({model:key,options})})).data}async estimateGenerationTask(projectId,key,options){return(await this.request(this.tenantPath(projectId,"/assets/generate/estimate"),{method:"POST",body:JSON.stringify({task:key,options})})).data}async listOrganizations(){return(await this.request("/api/management/organizations")).data}async listOrganizationMembers(organizationId){return(await this.request(`/api/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`))?.members??[]}async inviteOrganizationMember(input){return this.request("/api/auth/organization/invite-member",{method:"POST",body:JSON.stringify(input)})}async getCurrentSession(){return this.request("/api/auth/get-session")}async submitSupportIssue(input){return(await this.request("/api/support/issues",{method:"POST",body:JSON.stringify(input)})).data}async getReferralSummary(userId){return(await this.request(`/api/users/${encodeURIComponent(userId)}/referrals/summary`)).data}async listProjects(organizationId){return(await this.request(`/api/management/organizations/${encodeURIComponent(organizationId)}/projects`)).data}async publishProject(projectId){await this.request(`/api/management/projects/${projectId}/publish`,{method:"POST"})}async unpublishProject(projectId){await this.request(`/api/management/projects/${projectId}/unpublish`,{method:"POST"})}async createProject(input){return(await this.request("/api/management/projects",{method:"POST",body:JSON.stringify({...input,source:"cli"})})).data}async getProject(projectId){return(await this.request(`/api/management/projects/${projectId}`)).data}async getProjectCredits(projectId){return(await this.request(`/api/management/projects/${projectId}/billing/credits`)).data}async listProjectVersions(projectId,options){let params=new URLSearchParams({limit:String(options.limit)});return options.cursor&&params.set("cursor",options.cursor),(await this.request(`${this.projectEnvManagementPath(projectId,"/versions")}?${params.toString()}`)).data}async getProjectHistorySummary(projectId){return(await this.request(this.projectEnvManagementPath(projectId,"/versions/summary"))).data}async getProjectVersion(projectId,versionId){return(await this.request(this.projectEnvManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}`))).data}async createProjectVersion(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/versions"),{method:"POST",body:JSON.stringify(input)})).data}async restoreProjectVersion(projectId,versionId){return(await this.request(this.projectEnvManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}/restore`),{method:"POST"})).data}async listProjectSecretEntries(projectId,opts={}){let qs=opts.kind?`?kind=${encodeURIComponent(opts.kind)}`:"";return(await this.request(`/api/management/projects/${projectId}/secrets${qs}`)).data}async createProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets`,{method:"POST",body:JSON.stringify({key:input.key,kind:input.kind,value:input.value})})).data}async updateProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets/${encodeURIComponent(input.key)}`,{method:"PATCH",body:JSON.stringify({kind:input.kind,value:input.value})})).data}async deleteProjectSecretEntry(projectId,key,kind){let qs=`?kind=${encodeURIComponent(kind)}`;await this.request(`/api/management/projects/${projectId}/secrets/${encodeURIComponent(key)}${qs}`,{method:"DELETE"})}async listProjectIntegrations(projectId){return(await this.request(`/api/management/projects/${projectId}/integrations`)).data}async getProjectIntegrationInfo(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/info`)).data}async getProjectIntegrationStatus(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/status`)).data}async enableProjectIntegration(input){let payload={...input.authMode?{authMode:input.authMode}:{},...input.connectionAlias?{connectionAlias:input.connectionAlias}:{}};return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}`,{method:"PUT",body:JSON.stringify(payload)})).data}async connectOrganizationIntegrationWithToken(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({...input.alias?{alias:input.alias}:{},token:input.token})})).data}async startOrganizationIntegrationConnect(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({})})).data}async switchProjectIntegrationAuth(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/auth`,{method:"PATCH",body:JSON.stringify({authMode:input.authMode})})).data}async disableProjectIntegration(projectId,integrationKey){await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}`,{method:"DELETE"})}async setProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"PUT",body:JSON.stringify({value:input.value})})).data}async clearProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"DELETE"})).data}async runProjectIntegrationTool(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/run`,{method:"POST",body:JSON.stringify(input.request)})).data}async startProjectIntegrationConnect(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST"})).data}async bindProjectChannel(projectId,request){return(await this.request(`/api/management/projects/${projectId}/channels/bind`,{method:"POST",body:JSON.stringify(request)})).data}async createSchedule(projectId,request){return(await this.request(`/api/management/projects/${projectId}/schedules`,{method:"POST",body:JSON.stringify(request)})).data}async listSchedules(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules`)).data}async getSchedulesOverview(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules/overview`)).data}async getSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`)).data}async updateSchedule(projectId,scheduleId,request){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"PATCH",body:JSON.stringify(request)})).data}async setScheduleEnabled(projectId,scheduleId,enabled){let action=enabled?"resume":"pause";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/${action}`,{method:"POST"})).data}async runSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/run`,{method:"POST",body:JSON.stringify({trigger:"cli"})})).data}async listScheduleRuns(projectId,scheduleId,query={}){let params=new URLSearchParams;query.limit!==void 0&&params.set("limit",String(query.limit)),query.cursor&&params.set("cursor",query.cursor),query.status&&params.set("status",query.status);let suffix=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/runs${suffix}`)).data}async getScheduleRun(projectId,runId){return(await this.request(`/api/management/projects/${projectId}/schedules/runs/${encodeURIComponent(runId)}`)).data}async listWebhookEvents(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks/events`)).data}async listProjectWebhooks(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks`)).data}async getProjectWebhook(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`)).data}async createProjectWebhook(projectId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks`,{method:"POST",body:JSON.stringify(request)})).data}async updateProjectWebhook(projectId,webhookId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"PATCH",body:JSON.stringify(request)})).data}async deleteProjectWebhook(projectId,webhookId){await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"DELETE"})}async rotateProjectWebhookSecret(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/rotate-signing-secret`,{method:"POST"})).data.signingSecret}async testProjectWebhook(projectId,webhookId,input){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/test`,{method:"POST",body:JSON.stringify(input)})).data}async listProjectWebhookDeliveries(projectId,webhookId,limit){let query=`?page=1&limit=${limit??50}`;return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries${query}`)).data.items}async getProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}`)).data}async retryProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}/retry`,{method:"POST"})).data}async deleteSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"DELETE"})).data}async listEnvs(projectId,opts={}){let qs=opts.includeDeleted?"?includeDeleted=true":"";return(await this.request(`/api/management/projects/${projectId}/envs${qs}`)).data}async getEnv(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`)).data}async createEnv(projectId,input){return(await this.request(`/api/management/projects/${projectId}/envs`,{method:"POST",body:JSON.stringify(input)})).data}async syncEnv(projectId,env,input={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sync`,{method:"POST",body:JSON.stringify(input)})).data}async deleteEnv(projectId,env){await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`,{method:"DELETE"})}async getEnvDiff(projectId,env,opts={}){let params=new URLSearchParams;opts.against&&params.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&&params.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff${qs?`?${qs}`:""}`)).data}async getEnvStatus(projectId,env,opts={}){let params=new URLSearchParams;opts.against&&params.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&&params.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/status${qs?`?${qs}`:""}`)).data}async getCodeFileDiff(projectId,env,path47,opts={}){let qs=lazyFetchQs(opts.against,{path:path47});return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/code/file?${qs}`)).data}async getCodeConflictDetail(projectId,env,fromEnv,filePath){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflict/code?path=${encodeURIComponent(filePath)}`)).data}async getContentRowDiff(projectId,env,collection,rowId,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getSchemaTypeDiff(projectId,env,typeName,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getAssetDiff(projectId,env,assetId,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getTranslationRowDiff(projectId,env,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getFormSchemaDiff(projectId,env,formName,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getActivationDiff(projectId,env,agentName,triggerIndex,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/activations/${encodeURIComponent(agentName)}/${triggerIndex}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async mergeEnv(projectId,env,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge`,{method:"POST",body:JSON.stringify(body)})).data}async resolveMerge(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve`,{method:"POST",body:JSON.stringify(body)})).data}async cancelMerge(projectId,env,mergeId){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/cancel`,{method:"POST",body:JSON.stringify({mergeId})})).data}async getMergeConflicts(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflicts`)).data}async putResolveDraft(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"PUT",body:JSON.stringify(body)})).data}async deleteResolveDraft(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"DELETE"})).data}async publishRelease(projectId,body){return(await this.request(`/api/management/projects/${projectId}/releases`,{method:"POST",body:JSON.stringify(body)})).data}async activateAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/activations`,{method:"POST",body:JSON.stringify(body)})).data}async deactivateAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/activations`,{method:"DELETE",body:JSON.stringify(body)})).data}async runAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/run`,{method:"POST",body:JSON.stringify(body)})).data}async listAgentSessions(projectId,opts={}){let params=new URLSearchParams;opts.agentName&&params.set("agent_name",opts.agentName),opts.env&&params.set("env",opts.env),opts.status&&params.set("status",opts.status),opts.limit!==void 0&&params.set("limit",String(opts.limit));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/agents/sessions${qs?`?${qs}`:""}`)).data}async getAgentSession(projectId,sessionId){return(await this.request(`/api/management/projects/${projectId}/agents/sessions/${encodeURIComponent(sessionId)}`)).data.session}async getFeatures(){return this.request("/api/features")}async inviteProjectUser(input){return{id:(await this.request(`/api/management/projects/${input.projectId}/invites`,{method:"POST",body:JSON.stringify({email:input.email,roleKey:input.roleKey})})).data.id}}async updateProjectSettings(projectId,settings){return(await this.request(`/api/management/projects/${projectId}/settings`,{method:"PUT",body:JSON.stringify(settings)})).data}async deleteProject(projectId){await this.request(`/api/management/projects/${projectId}`,{method:"DELETE",body:JSON.stringify({})})}async getGitRemote(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-remote`,{},{allow403:!0})).data}async getGitCredential(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-credential`,{},{allow403:!0})).data}async getPreviewUrl(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sandbox`)).data}async sandboxPull(projectId,onProgress,env,options={}){let query=options.noRestart?"?noRestart=true":"",response=await this.rawRequest(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sandbox/pull${query}`,{method:"POST",headers:{Accept:"text/event-stream"}});if(!response.body)throw new Error("Sandbox pull failed: empty response stream");let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",errorMessage3=null,completed=!1;try{for(;;){let{value,done}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});let separatorIndex=buffer.indexOf(`
42
+ `)}),this}_outputHelpIfRequested(args){let helpOption=this._getHelpOption();helpOption&&args.find(arg=>helpOption.is(arg))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function incrementNodeInspectorPort(args){return args.map(arg=>{if(!arg.startsWith("--inspect"))return arg;let debugOption,debugHost="127.0.0.1",debugPort="9229",match;return(match=arg.match(/^(--inspect(-brk)?)$/))!==null?debugOption=match[1]:(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(debugOption=match[1],/^\d+$/.test(match[3])?debugPort=match[3]:debugHost=match[3]):(match=arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(debugOption=match[1],debugHost=match[3],debugPort=match[4]),debugOption&&debugPort!=="0"?`${debugOption}=${debugHost}:${parseInt(debugPort)+1}`:arg})}__name(incrementNodeInspectorPort,"incrementNodeInspectorPort");function useColor(){if(process8.env.NO_COLOR||process8.env.FORCE_COLOR==="0"||process8.env.FORCE_COLOR==="false")return!1;if(process8.env.FORCE_COLOR||process8.env.CLICOLOR_FORCE!==void 0)return!0}__name(useColor,"useColor");exports2.Command=Command2;exports2.useColor=useColor}});var require_commander=__commonJS({"../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js"(exports2){var{Argument:Argument2}=require_argument(),{Command:Command2}=require_command(),{CommanderError:CommanderError2,InvalidArgumentError:InvalidArgumentError2}=require_error(),{Help:Help2}=require_help(),{Option:Option2}=require_option();exports2.program=new Command2;exports2.createCommand=name=>new Command2(name);exports2.createOption=(flags,description)=>new Option2(flags,description);exports2.createArgument=(name,description)=>new Argument2(name,description);exports2.Command=Command2;exports2.Option=Option2;exports2.Argument=Argument2;exports2.Help=Help2;exports2.CommanderError=CommanderError2;exports2.InvalidArgumentError=InvalidArgumentError2;exports2.InvalidOptionArgumentError=InvalidArgumentError2}});import{z}from"zod";function filterUnknownProperties(data2,schema){if(data2==null)return data2;if(schema instanceof z.ZodOptional||schema instanceof z.ZodNullable||schema instanceof z.ZodDefault)return filterUnknownProperties(data2,schema.unwrap());if(schema instanceof z.ZodArray){if(!Array.isArray(data2))return data2;let itemSchema=schema.unwrap();return data2.map(item=>filterUnknownProperties(item,itemSchema))}if(schema instanceof z.ZodDiscriminatedUnion){if(typeof data2!="object"||data2===null)return data2;let unionSchema=schema,discriminator=unionSchema.def.discriminator,discriminatorValue=data2[discriminator],matchingSchema=unionSchema.options.find(option=>{let discriminatorField=option.shape[discriminator];return discriminatorField instanceof z.ZodLiteral?discriminatorField.def.values.includes(discriminatorValue):!1});return matchingSchema?filterUnknownProperties(data2,matchingSchema):data2}if(schema instanceof z.ZodObject){if(typeof data2!="object")return data2;let shape=schema.shape,result={};for(let key in shape)if(Object.prototype.hasOwnProperty.call(data2,key)){let fieldSchema=shape[key],fieldValue=data2[key];result[key]=filterUnknownProperties(fieldValue,fieldSchema)}if(schema.def.catchall instanceof z.ZodUnknown)for(let[key,value]of Object.entries(data2))key in shape||(result[key]=value);return result}return data2}function createObjectDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)},partial(){let partialSchema=schema.partial();return createObjectDTO(partialSchema)},pick(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),picked=schema.pick(mask);return createObjectDTO(picked)},omit(keys){let mask=keys.reduce((acc,key)=>({...acc,[key]:!0}),{}),omitted=schema.omit(mask);return createObjectDTO(omitted)}}}function createDiscriminatedUnionDTO(schema){return{schema,from(data2){let filtered=filterUnknownProperties(data2,schema);return schema.parse(filtered)},fromList(data2){return data2.map(item=>this.from(item))},safeParse(data2){let filtered=filterUnknownProperties(data2,schema);return schema.safeParse(filtered)}}}function createDTO(schema){if(schema instanceof z.ZodObject)return createObjectDTO(schema);if(schema instanceof z.ZodDiscriminatedUnion)return createDiscriminatedUnionDTO(schema);throw new Error(`Unsupported schema type: ${schema.constructor.name}. createDTO supports ZodObject and ZodDiscriminatedUnion.`)}var init_create_dto=__esm({"../../packages/api-contracts/dist/esm/utils/create-dto.js"(){"use strict";__name(filterUnknownProperties,"filterUnknownProperties");__name(createObjectDTO,"createObjectDTO");__name(createDiscriminatedUnionDTO,"createDiscriminatedUnionDTO");__name(createDTO,"createDTO")}});import{z as z2}from"zod";function createCursorPageDataSchema(dataSchema){return z2.object({items:z2.array(dataSchema),nextCursor:z2.string().nullable()})}function createCursorPaginatedResponseSchema(dataSchema){return z2.object({data:createCursorPageDataSchema(dataSchema)})}var createResponseSchema,init_response=__esm({"../../packages/api-contracts/dist/esm/utils/response.js"(){"use strict";createResponseSchema=__name(dataSchema=>z2.object({data:dataSchema}),"createResponseSchema");__name(createCursorPageDataSchema,"createCursorPageDataSchema");__name(createCursorPaginatedResponseSchema,"createCursorPaginatedResponseSchema")}});import{z as z3}from"zod";var PaginationQuerySchema,init_pagination=__esm({"../../packages/api-contracts/dist/esm/utils/pagination.js"(){"use strict";PaginationQuerySchema=z3.object({page:z3.coerce.number().int().positive().default(1),limit:z3.coerce.number().int().positive().max(100).default(20)})}});import{z as z4}from"zod";var CommonSchemas,BaseEntitySchema,ProjectRoleKeySchema,ProjectRoleKeyWithSystemSchema,ProjectPrincipalTypeSchema,ProjectVisibilitySchema,ProjectStatusSchema,ProjectInviteStatusSchema,PublicationStatusSchema,OrganizationRoleSchema,AssetTypeSchema,TemplateCodeSchema,FieldTypeSchema,RESERVED_CONTENT_FIELD_NAMES,CONTENT_TYPE_NAME_PATTERN,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION,CONTENT_FIELD_NAME_PATTERN,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION,init_common=__esm({"../../packages/api-contracts/dist/esm/types/common.js"(){"use strict";CommonSchemas={timestamp:z4.coerce.date(),positiveInt:z4.number().int().positive(),nonNegativeInt:z4.number().int().nonnegative()},BaseEntitySchema=z4.object({id:z4.uuid(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),ProjectRoleKeySchema=z4.enum(["full","edit","comment","view"]),ProjectRoleKeyWithSystemSchema=z4.enum(["full","edit","comment","view","agent","schedule"]),ProjectPrincipalTypeSchema=z4.enum(["user","org","orgRole","public","email"]),ProjectVisibilitySchema=z4.enum(["public","private"]),ProjectStatusSchema=z4.enum(["creating","forking","start_server","created","failed"]),ProjectInviteStatusSchema=z4.enum(["pending","accepted","revoked","expired"]),PublicationStatusSchema=z4.enum(["idle","publishing","published","failed","unpublished"]),OrganizationRoleSchema=z4.enum(["owner","admin","member"]),AssetTypeSchema=z4.enum(["file","folder"]),TemplateCodeSchema=z4.enum(["Free","Premium"]),FieldTypeSchema=z4.enum(["string","text","richtext","media","number","boolean","date","json","reference","blocks"]),RESERVED_CONTENT_FIELD_NAMES=["id","entryId","documentId","slug","locale","createdAt","updatedAt","__fimo"],CONTENT_TYPE_NAME_PATTERN=/^[A-Za-z]\w*$/,CONTENT_TYPE_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter",CONTENT_FIELD_NAME_PATTERN=/^[A-Za-z_]\w*$/,CONTENT_FIELD_NAME_PATTERN_DESCRIPTION="letters, numbers, and underscores, starting with a letter or underscore"}});var ATTACHMENT_TYPES,ATTACHMENT_MIME_TYPES,ATTACHMENT_IMAGE_MIME_TYPES,ATTACHMENT_DOCUMENT_MIME_TYPES,ATTACHMENT_ACCEPT_EXTENSIONS,ATTACHMENT_ACCEPT_STRING,ATTACHMENT_DROPZONE_ACCEPT,init_attachments=__esm({"../../packages/api-contracts/dist/esm/types/attachments.js"(){"use strict";ATTACHMENT_TYPES=[{mime:"image/png",extensions:[".png"],category:"image"},{mime:"image/jpeg",extensions:[".jpg",".jpeg"],category:"image"},{mime:"image/webp",extensions:[".webp"],category:"image"},{mime:"image/avif",extensions:[".avif"],category:"image"},{mime:"application/pdf",extensions:[".pdf"],category:"document",maxSizeBytes:5242880},{mime:"text/csv",extensions:[".csv"],category:"document",maxSizeBytes:5242880},{mime:"text/plain",extensions:[".txt"],category:"document",maxSizeBytes:5242880}],ATTACHMENT_MIME_TYPES=ATTACHMENT_TYPES.map(t2=>t2.mime),ATTACHMENT_IMAGE_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="image").map(t2=>t2.mime),ATTACHMENT_DOCUMENT_MIME_TYPES=ATTACHMENT_TYPES.filter(t2=>t2.category==="document").map(t2=>t2.mime),ATTACHMENT_ACCEPT_EXTENSIONS=ATTACHMENT_TYPES.flatMap(t2=>t2.extensions),ATTACHMENT_ACCEPT_STRING=[...ATTACHMENT_ACCEPT_EXTENSIONS,...ATTACHMENT_MIME_TYPES].join(","),ATTACHMENT_DROPZONE_ACCEPT=Object.fromEntries(ATTACHMENT_TYPES.map(t2=>[t2.mime,t2.extensions]))}});import{z as z5}from"zod";function isValidEnv(env){return typeof env!="string"||env.length===0||env.length>MAX_ENV_LENGTH||env.startsWith("-")||env.startsWith(".")||env.includes("//")||env.includes("--")||env.split("/").some(segment=>segment==="..")?!1:ENV_ID_REGEX.test(env)}function encodeEnvPathSegment(env){return env.replace(/\//g,"--")}function isProductionEnv(env){return env===PRODUCTION_ENV}var ENV_ID_REGEX,MAX_ENV_LENGTH,EnvSchema,DEFAULT_ENV,PRODUCTION_ENV,init_env=__esm({"../../packages/api-contracts/dist/esm/types/env.js"(){"use strict";ENV_ID_REGEX=/^[a-zA-Z0-9._/-]+$/,MAX_ENV_LENGTH=255;__name(isValidEnv,"isValidEnv");__name(encodeEnvPathSegment,"encodeEnvPathSegment");EnvSchema=z5.string().min(1,"env must not be empty").max(MAX_ENV_LENGTH,`env must be at most ${MAX_ENV_LENGTH} characters`).refine(isValidEnv,{error:"env must match /^[a-zA-Z0-9._/-]+$/ and must not start with `-`"}),DEFAULT_ENV="main",PRODUCTION_ENV="prod";__name(isProductionEnv,"isProductionEnv")}});var init_realtime=__esm({"../../packages/api-contracts/dist/esm/types/realtime.js"(){"use strict"}});import{z as z6}from"zod";function referenceDocumentId(value){if(typeof value=="string")return value;if(value&&typeof value=="object"){let reference=value,hasId=Object.prototype.hasOwnProperty.call(reference,"id"),hasDocumentId=Object.prototype.hasOwnProperty.call(reference,"documentId"),id=reference.id,documentId=reference.documentId;if(hasId&&typeof id!="string"||hasDocumentId&&typeof documentId!="string"||typeof id=="string"&&typeof documentId=="string"&&id!==documentId)return null;if(typeof id=="string")return id;if(typeof documentId=="string")return documentId}return null}function toReferenceValue(value){let documentId=referenceDocumentId(value);return documentId?{documentId}:null}function referenceContentType(value){if(value&&typeof value=="object"&&"contentType"in value){let contentType=value.contentType;return typeof contentType=="string"&&contentType.length>0?contentType:null}return null}function toPolymorphicReferenceValue(value){let documentId=referenceDocumentId(value),contentType=referenceContentType(value);return documentId&&contentType?{contentType,documentId}:null}var referenceValuePreprocess,ReferenceValueSchema,ReferenceInputValueSchema,polymorphicReferenceValuePreprocess,PolymorphicReferenceValueSchema,PolymorphicReferenceInputValueSchema,init_references=__esm({"../../packages/api-contracts/dist/esm/types/references.js"(){"use strict";__name(referenceDocumentId,"referenceDocumentId");__name(toReferenceValue,"toReferenceValue");referenceValuePreprocess=__name(value=>{let reference=toReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"referenceValuePreprocess"),ReferenceValueSchema=z6.preprocess(referenceValuePreprocess,z6.object({documentId:z6.uuid()})),ReferenceInputValueSchema=z6.preprocess(referenceValuePreprocess,z6.union([z6.object({documentId:z6.uuid()}),z6.object({slug:z6.string().min(1)})]));__name(referenceContentType,"referenceContentType");__name(toPolymorphicReferenceValue,"toPolymorphicReferenceValue");polymorphicReferenceValuePreprocess=__name(value=>{let reference=toPolymorphicReferenceValue(value);return reference||(value&&typeof value=="object"&&("id"in value||"documentId"in value)?null:value)},"polymorphicReferenceValuePreprocess"),PolymorphicReferenceValueSchema=z6.preprocess(polymorphicReferenceValuePreprocess,z6.object({contentType:z6.string().min(1),documentId:z6.uuid()})),PolymorphicReferenceInputValueSchema=z6.preprocess(polymorphicReferenceValuePreprocess,z6.union([z6.object({contentType:z6.string().min(1),documentId:z6.uuid()}),z6.object({contentType:z6.string().min(1),slug:z6.string().min(1)})]))}});import{z as z7}from"zod";function rejectLegacyLocaleSettings(field,ctx){"localized"in field&&ctx.addIssue({code:"custom",path:["localized"],message:'Field-level locale settings use "i18n".'})}function rejectFieldI18n(field,ctx){"i18n"in field&&ctx.addIssue({code:"custom",path:["i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}function refineConditions(field,ctx){if(field.showIf!==void 0&&field.showIfAny!==void 0&&ctx.addIssue({code:"custom",path:["showIfAny"],message:'A field declares "showIf" or "showIfAny", never both.'}),Array.isArray(field.showIf)){let fields=field.showIf.map(clause=>clause.field);new Set(fields).size!==fields.length&&ctx.addIssue({code:"custom",path:["showIf"],message:'"showIf" clauses must each name a different field. Use "in" for several values of one field.'})}}function rejectUnsupportedUnique(field,ctx,type){"unique"in field&&!uniqueFieldTypes.has(type)&&ctx.addIssue({code:"custom",path:["unique"],message:UNSUPPORTED_UNIQUE_MESSAGE})}function getConditionDefinition(field){if(field.showIfAny!==void 0)return{key:"showIfAny",clauses:field.showIfAny};if(field.showIf!==void 0)return{key:"showIf",clauses:Array.isArray(field.showIf)?field.showIf:[field.showIf]}}function getConditionValues(clause){return"equals"in clause?[clause.equals]:clause.in}function collectClauseProblems(fieldName,condition,clause,fields,path47){let conditionPath=[...path47,fieldName,condition.key],trigger=fields[clause.field];if(trigger===void 0)return[{path:conditionPath,message:`"${condition.key}" references unknown field "${clause.field}".`}];if(trigger.showIf!==void 0||trigger.showIfAny!==void 0)return[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is conditional too. Conditions are one level deep.`}];if(trigger.type!=="boolean"&&trigger.type!=="number"&&trigger.type!=="string")return[{path:conditionPath,message:`"${condition.key}" can only reference boolean, number, and string fields. "${clause.field}" is a ${trigger.type} field.`}];let triggerOptions=trigger.type==="string"?trigger.options:void 0;if(trigger.type==="string"&&triggerOptions===void 0)return[{path:conditionPath,message:`"${condition.key}" can only reference a string field that declares "options". Add options to "${clause.field}".`}];let values=getConditionValues(clause);if(values.some(value=>typeof value!==trigger.type))return[{path:conditionPath,message:`"${condition.key}" on "${clause.field}" expects a ${trigger.type} value.`}];if(triggerOptions!==void 0){let invalidValues=values.filter(value=>!triggerOptions.includes(value));if(invalidValues.length>0)return invalidValues.map(value=>({path:conditionPath,message:`"${value}" is not one of the options declared by "${clause.field}".`}))}return trigger.editable===!1?[{path:conditionPath,message:`"${condition.key}" cannot reference "${clause.field}" because it is not editable.`}]:[]}function collectConditionProblems(fields){let problems=[],walk=__name((currentFields,path47)=>{for(let[fieldName,field]of Object.entries(currentFields)){let condition=getConditionDefinition(field);if(condition!==void 0)for(let clause of condition.clauses)problems.push(...collectClauseProblems(fieldName,condition,clause,currentFields,path47));if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...path47,fieldName,variant.uid]);else walk(field.schema.fields,[...path47,fieldName])}},"walk");return walk(fields,[]),problems}function isBlocksUnion(schema){return"oneOf"in schema}function walkContentFields(fields,visit2){let walk=__name((currentFields,path47,structuredDepth,insideStructuredContent)=>{for(let[fieldName,field]of Object.entries(currentFields)){let fieldPath=[...path47,fieldName];visit2({field,path:fieldPath,structuredDepth,insideStructuredContent});let nextDepth=structuredDepth+1;if(field.type==="blocks")if(isBlocksUnion(field.schema))for(let variant of field.schema.oneOf)walk(variant.fields,[...fieldPath,variant.uid],nextDepth,!0);else walk(field.schema.fields,fieldPath,nextDepth,!0)}},"walk");walk(fields,[],0,!1)}var UNIQUE_FIELD_TYPES,utf8,MAX_STRUCTURED_CONTENT_DEPTH,MAX_BLOCK_VARIANTS,MAX_BLOCK_ITEMS,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES,showIfClauseSchema,commonFieldShape,FIELD_I18N_UNSUPPORTED_MESSAGE,uniqueFieldTypes,UNSUPPORTED_UNIQUE_MESSAGE,scalarFieldSchema,referenceFieldSchema,reservedStructuredContentNames,ContentFieldDefinitionSchema,blockFieldsSchema,blockVariantSchema,fixedBlocksSchema,blocksSchema,blocksFieldSchema,contentFieldDefinitionSchema,init_content_fields=__esm({"../../packages/api-contracts/dist/esm/types/content-fields.js"(){"use strict";init_common();UNIQUE_FIELD_TYPES=["string","text","number","boolean","date"],utf8=new TextEncoder,MAX_STRUCTURED_CONTENT_DEPTH=7,MAX_BLOCK_VARIANTS=40,MAX_BLOCK_ITEMS=200,RESERVED_STRUCTURED_CONTENT_FIELD_NAMES=["_key","_type"],showIfClauseSchema=z7.union([z7.object({field:z7.string().min(1),equals:z7.union([z7.string(),z7.number(),z7.boolean()])}).strict(),z7.object({field:z7.string().min(1),in:z7.array(z7.union([z7.string(),z7.number(),z7.boolean()])).min(1)}).strict()]),commonFieldShape={label:z7.string().min(1).optional(),description:z7.string().optional(),editable:z7.boolean().optional(),required:z7.boolean().optional(),default:z7.unknown().optional(),showIf:z7.union([showIfClauseSchema,z7.array(showIfClauseSchema).min(1)]).optional(),showIfAny:z7.array(showIfClauseSchema).min(1).optional()},FIELD_I18N_UNSUPPORTED_MESSAGE='"i18n" is only supported on top-level scalar and reference fields.';__name(rejectLegacyLocaleSettings,"rejectLegacyLocaleSettings");__name(rejectFieldI18n,"rejectFieldI18n");__name(refineConditions,"refineConditions");uniqueFieldTypes=new Set(UNIQUE_FIELD_TYPES),UNSUPPORTED_UNIQUE_MESSAGE=`"unique" is only supported on ${UNIQUE_FIELD_TYPES.join(", ")} fields.`;__name(rejectUnsupportedUnique,"rejectUnsupportedUnique");scalarFieldSchema=z7.object({...commonFieldShape,type:z7.enum(["string","text","richtext","media","number","boolean","date","json"]),min:z7.number().optional(),max:z7.number().optional(),minLength:z7.number().int().nonnegative().optional(),maxLength:z7.number().int().nonnegative().optional(),regex:z7.string().optional(),multiple:z7.boolean().optional(),allowedMimeTypes:z7.array(z7.string()).optional(),options:z7.array(z7.string().min(1)).min(1).optional(),unique:z7.boolean().optional(),i18n:z7.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),rejectUnsupportedUnique(field,ctx,field.type);for(let key of["target","targets","many","repeatable","schema"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on ${field.type} fields.`});if(field.type!=="number")for(let key of["min","max"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on number fields.`});if(field.type!=="string"&&field.type!=="text")for(let key of["minLength","maxLength","regex"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on string and text fields.`});field.min!==void 0&&field.max!==void 0&&field.min>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to "min".'});let effectiveMinimumLength=Math.max(field.minLength??0,field.required?1:0);if(field.maxLength!==void 0&&effectiveMinimumLength>field.maxLength&&ctx.addIssue({code:"custom",path:["maxLength"],message:'"maxLength" must be greater than or equal to the minimum required length.'}),field.regex!==void 0)try{new RegExp(field.regex)}catch{ctx.addIssue({code:"custom",path:["regex"],message:'"regex" must be a valid regular expression.'})}if(field.type!=="media")for(let key of["multiple","allowedMimeTypes"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is only supported on media fields.`});if(field.type!=="string"&&"options"in field&&ctx.addIssue({code:"custom",path:["options"],message:'"options" is only supported on string fields.'}),field.options!==void 0){new Set(field.options).size!==field.options.length&&ctx.addIssue({code:"custom",path:["options"],message:"Options must be unique."});for(let key of["regex","minLength","maxLength"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported alongside "options".`});field.default!==void 0&&!field.options.includes(field.default)&&ctx.addIssue({code:"custom",path:["default"],message:'"default" must be one of the declared options.'})}}),referenceFieldSchema=z7.object({...commonFieldShape,type:z7.literal("reference"),target:z7.string().regex(CONTENT_TYPE_NAME_PATTERN).optional(),targets:z7.array(z7.string().regex(CONTENT_TYPE_NAME_PATTERN)).min(1).optional(),many:z7.boolean().optional(),i18n:z7.boolean().optional()}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),refineConditions(field,ctx),!field.target&&!field.targets&&ctx.addIssue({code:"custom",path:["target"],message:'Reference fields must declare "target" or "targets".'}),field.target&&field.targets&&ctx.addIssue({code:"custom",path:["targets"],message:'A reference field declares "target" or "targets", never both.'}),field.targets&&new Set(field.targets).size!==field.targets.length&&ctx.addIssue({code:"custom",path:["targets"],message:"Reference targets must be unique."});for(let key of["repeatable","schema","min","max","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on reference fields.`})}),reservedStructuredContentNames=new Set(RESERVED_STRUCTURED_CONTENT_FIELD_NAMES),ContentFieldDefinitionSchema=z7.lazy(()=>contentFieldDefinitionSchema);__name(getConditionDefinition,"getConditionDefinition");__name(getConditionValues,"getConditionValues");__name(collectClauseProblems,"collectClauseProblems");__name(collectConditionProblems,"collectConditionProblems");blockFieldsSchema=z7.record(z7.string(),ContentFieldDefinitionSchema).superRefine((fields,ctx)=>{for(let fieldName of Object.keys(fields))CONTENT_FIELD_NAME_PATTERN.test(fieldName)||ctx.addIssue({code:"custom",path:[fieldName],message:`Field names must use ${CONTENT_FIELD_NAME_PATTERN_DESCRIPTION}.`}),reservedStructuredContentNames.has(fieldName)&&ctx.addIssue({code:"custom",path:[fieldName],message:`"${fieldName}" is reserved structured-content metadata.`}),"unique"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"unique"],message:'"unique" is only supported on top-level fields.'}),"i18n"in fields[fieldName]&&ctx.addIssue({code:"custom",path:[fieldName,"i18n"],message:FIELD_I18N_UNSUPPORTED_MESSAGE})}),blockVariantSchema=z7.object({uid:z7.string().regex(CONTENT_TYPE_NAME_PATTERN),label:z7.string().min(1),description:z7.string().optional(),fields:blockFieldsSchema}).strict(),fixedBlocksSchema=z7.object({fields:blockFieldsSchema}).strict(),blocksSchema=z7.object({oneOf:z7.array(blockVariantSchema).min(1).max(MAX_BLOCK_VARIANTS)}).strict().superRefine((schema,ctx)=>{let seen=new Set;for(let[index2,variant]of schema.oneOf.entries())seen.has(variant.uid)&&ctx.addIssue({code:"custom",path:["oneOf",index2,"uid"],message:"Variant UIDs must be unique."}),seen.add(variant.uid)}),blocksFieldSchema=z7.object({...commonFieldShape,type:z7.literal("blocks"),min:z7.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),max:z7.number().int().nonnegative().max(MAX_BLOCK_ITEMS).optional(),schema:z7.union([fixedBlocksSchema,blocksSchema])}).loose().superRefine((field,ctx)=>{rejectLegacyLocaleSettings(field,ctx),rejectFieldI18n(field,ctx),refineConditions(field,ctx);let effectiveMinimum=Math.max(field.min??0,field.required?1:0);field.max!==void 0&&effectiveMinimum>field.max&&ctx.addIssue({code:"custom",path:["max"],message:'"max" must be greater than or equal to the minimum number of blocks.'});for(let key of["target","targets","many","repeatable","minLength","maxLength","regex","options","unique"])key in field&&ctx.addIssue({code:"custom",path:[key],message:`"${key}" is not supported on blocks fields.`})}),contentFieldDefinitionSchema=z7.discriminatedUnion("type",[scalarFieldSchema,referenceFieldSchema,blocksFieldSchema]);__name(isBlocksUnion,"isBlocksUnion");__name(walkContentFields,"walkContentFields")}});import{z as z8}from"zod";var AUDIT_ACTIONS,AuditActionSchema,AUDIT_OUTCOMES,AuditOutcomeSchema,AUDIT_ACTOR_KINDS,AuditActorKindSchema,init_audit_log=__esm({"../../packages/api-contracts/dist/esm/types/audit-log.js"(){"use strict";AUDIT_ACTIONS=["env_create","env_delete","env_sync","capability_check","shell_exec","git_push","git_tag","git_merge","fimo_deploy","merge_decision","session_start","session_end","cost_breach","trigger_fire","cutover_step","agent_delegate","ops_access_change","ops_service_token_change","ops_project_search","ops_project_inspect","ops_project_chat_read","ops_recent_chat_read","ops_project_snapshot","ops_support_thread_read","ops_support_report_read","ops_support_report_change","ops_customer_registry_change","ops_investigation_change","ops_known_issue_change","ops_validation_record","ops_notification_preview","ops_notification_approve","ops_notification_send"],AuditActionSchema=z8.enum(AUDIT_ACTIONS),AUDIT_OUTCOMES=["success","denied","error"],AuditOutcomeSchema=z8.enum(AUDIT_OUTCOMES),AUDIT_ACTOR_KINDS=["user","agent","system"],AuditActorKindSchema=z8.enum(AUDIT_ACTOR_KINDS)}});import{z as z9}from"zod";var OPS_BACKEND_PROFILES,OpsBackendProfileSchema,OPS_PERMISSIONS,OpsPermissionSchema,OPS_PERMISSION_PRESETS,OPS_SERVICE_PERMISSION_PRESETS,OpsAccessGrantInputSchema,OpsServiceTokenInputSchema,OpsCustomerProjectInputSchema,OPS_INVESTIGATION_STATUSES,OpsInvestigationStatusSchema,OpsInvestigationCreateInputSchema,OpsInvestigationUpdateInputSchema,OPS_KNOWN_ISSUE_STATUSES,OpsKnownIssueStatusSchema,OpsKnownIssueCreateInputSchema,OpsKnownIssueUpdateInputSchema,OPS_VALIDATION_OUTCOMES,OpsValidationOutcomeSchema,OpsValidationRunInputSchema,OpsNotificationPreviewInputSchema,init_ops=__esm({"../../packages/api-contracts/dist/esm/types/ops.js"(){"use strict";OPS_BACKEND_PROFILES=["local","staging","prod"],OpsBackendProfileSchema=z9.enum(OPS_BACKEND_PROFILES),OPS_PERMISSIONS=["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:sentry:read","ops:logs:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview","ops:notification:approve","ops:notification:send"],OpsPermissionSchema=z9.enum(OPS_PERMISSIONS),OPS_PERMISSION_PRESETS={support:["ops:project:read","ops:project:chat:read","ops:support:read","ops:support:write","ops:customers:read","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:validations:read","ops:notification:preview"],engineer:["ops:project:read","ops:project:chat:read","ops:project:snapshot","ops:sentry:read","ops:logs:read","ops:support:read","ops:support:write","ops:customers:read","ops:customers:write","ops:investigations:read","ops:investigations:write","ops:known-issues:read","ops:known-issues:write","ops:validations:read","ops:validations:write","ops:audit:read","ops:notification:preview"],full:[...OPS_PERMISSIONS]},OPS_SERVICE_PERMISSION_PRESETS={support:OPS_PERMISSION_PRESETS.support,engineer:OPS_PERMISSION_PRESETS.engineer,full:OPS_PERMISSION_PRESETS.full.filter(permission=>permission!=="ops:notification:approve")},OpsAccessGrantInputSchema=z9.object({permissions:z9.array(OpsPermissionSchema).min(1),backendProfiles:z9.array(OpsBackendProfileSchema).min(1),enabled:z9.boolean().default(!0)}),OpsServiceTokenInputSchema=z9.object({name:z9.string().trim().min(1).max(120),permissions:z9.array(OpsPermissionSchema).min(1),backendProfiles:z9.array(OpsBackendProfileSchema).min(1),expiresAt:z9.coerce.date()}).refine(input=>!input.permissions.includes("ops:notification:approve"),{path:["permissions"],message:"Service credentials cannot approve customer notifications"}).refine(input=>input.expiresAt.getTime()>Date.now(),{path:["expiresAt"],message:"Service credential expiry must be in the future"}),OpsCustomerProjectInputSchema=z9.object({importanceReason:z9.string().trim().min(1).max(1e3),ownerUserId:z9.string().trim().min(1).nullable().optional(),framework:z9.string().trim().max(120).nullable().optional(),packageManager:z9.enum(["npm","pnpm","yarn","bun"]).nullable().optional(),notes:z9.string().trim().max(5e3).nullable().optional()}),OPS_INVESTIGATION_STATUSES=["open","investigating","awaiting_approval","resolved","monitoring","closed"],OpsInvestigationStatusSchema=z9.enum(OPS_INVESTIGATION_STATUSES),OpsInvestigationCreateInputSchema=z9.object({projectId:z9.uuid(),title:z9.string().trim().min(1).max(240),userReport:z9.string().trim().max(1e4).nullable().optional()}),OpsInvestigationUpdateInputSchema=z9.object({status:OpsInvestigationStatusSchema.optional(),hypothesis:z9.string().trim().max(1e4).nullable().optional(),outcome:z9.string().trim().max(1e4).nullable().optional(),evidence:z9.array(z9.record(z9.string(),z9.unknown())).max(100).optional()}).refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_KNOWN_ISSUE_STATUSES=["open","monitoring","resolved"],OpsKnownIssueStatusSchema=z9.enum(OPS_KNOWN_ISSUE_STATUSES),OpsKnownIssueCreateInputSchema=z9.object({fingerprint:z9.string().trim().min(1).max(240),title:z9.string().trim().min(1).max(240),description:z9.string().trim().min(1).max(1e4),affectedVersions:z9.array(z9.string().trim().min(1).max(120)).max(100).default([]),detectionQueries:z9.array(z9.string().trim().min(1).max(2e3)).max(50).default([]),fixedVersion:z9.string().trim().min(1).max(64).nullable().optional(),workaround:z9.string().trim().min(1).max(1e4).nullable().optional(),status:OpsKnownIssueStatusSchema.default("open")}),OpsKnownIssueUpdateInputSchema=OpsKnownIssueCreateInputSchema.omit({fingerprint:!0}).extend({affectedVersions:z9.array(z9.string().trim().min(1).max(120)).max(100),detectionQueries:z9.array(z9.string().trim().min(1).max(2e3)).max(50),status:OpsKnownIssueStatusSchema}).partial().refine(input=>Object.keys(input).length>0,"At least one field is required"),OPS_VALIDATION_OUTCOMES=["passed","failed","inconclusive"],OpsValidationOutcomeSchema=z9.enum(OPS_VALIDATION_OUTCOMES),OpsValidationRunInputSchema=z9.object({changeReference:z9.string().trim().min(1).max(500),outcome:OpsValidationOutcomeSchema,summary:z9.string().trim().min(1).max(1e4),evidence:z9.array(z9.record(z9.string(),z9.unknown())).max(100).default([])}),OpsNotificationPreviewInputSchema=z9.object({recipientEmail:z9.email().optional(),subject:z9.string().trim().min(1).max(200).default("An update from Fimo"),message:z9.string().trim().min(1).max(5e3),locale:z9.string().trim().min(2).max(20),reason:z9.string().trim().min(1).max(1e3),acknowledgePolicy:z9.literal(!0)})}});import{z as z10}from"zod";function getChatFormOptionLabels(body){switch(body.type){case"choices":return body.actions.map(action=>action.label);case"cards":return body.items.map(item=>item.title);case"table":return body.rows.map(row2=>row2.cells[0]??"");case"assets":return body.items.map(item=>item.label??item.alt)}}var BlockSayActionSchema,BlockActionSchema,BlockAppActionSchema,BlockBaseSchema,ChoicesBlockSchema,TableRowTargetSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,ChatDisplayBlockSchema,ChatFormBodySchema,ChatFormStepSchema,FormBlockSchema,ChatBlockSchema,ChatBlockToolInputSchema,ChatFormAnswerItemSchema,ChatFormAnswerMetadataSchema,ChatFormResponseSchema,init_chat_block=__esm({"../../packages/api-contracts/dist/esm/types/chat-block.js"(){"use strict";BlockSayActionSchema=z10.object({kind:z10.literal("say"),label:z10.string().trim().min(1).max(40,"Button labels must be 40 characters or fewer."),description:z10.string().min(1).max(240).optional(),message:z10.string().trim().min(1,"Every say button needs the sentence the user is saying by clicking.").max(2e3),style:z10.enum(["primary","default","ghost"]).optional()}),BlockActionSchema=BlockSayActionSchema,BlockAppActionSchema=z10.object({kind:z10.literal("app"),command:z10.literal("publish")}).strict(),BlockBaseSchema=z10.object({fallback:z10.string().trim().min(1,"Every block needs a fallback line for clients that cannot render it.").max(500),title:z10.string().min(1).max(80).optional()}),ChoicesBlockSchema=BlockBaseSchema.extend({type:z10.literal("choices"),text:z10.string().max(500).optional(),actions:z10.array(BlockActionSchema).min(2,"A choices block needs 2 to 4 buttons.").max(4,"A choices block needs 2 to 4 buttons.")}),TableRowTargetSchema=z10.discriminatedUnion("kind",[z10.object({kind:z10.literal("entry"),collection:z10.string().min(1).max(80),entryId:z10.string().min(1).max(120)}),z10.object({kind:z10.literal("url"),url:z10.url({protocol:/^https$/}).max(2e3)})]),TableBlockSchema=BlockBaseSchema.extend({type:z10.literal("table"),columns:z10.array(z10.object({label:z10.string().min(1).max(24)})).min(2).max(4),rows:z10.array(z10.object({cells:z10.array(z10.string().max(80)).min(2).max(4),target:TableRowTargetSchema.optional()})).min(1).max(8)}).superRefine((table,ctx)=>{table.rows.forEach((row2,index2)=>{row2.cells.length!==table.columns.length&&ctx.addIssue({code:"custom",path:["rows",index2,"cells"],message:`Every table row needs exactly ${table.columns.length} cells, one for each column.`})})}),CardsBlockSchema=BlockBaseSchema.extend({type:z10.literal("cards"),layout:z10.enum(["rail","stack"]).optional(),items:z10.array(z10.object({title:z10.string().min(1).max(60),subtitle:z10.string().min(1).max(120).optional(),imageUrl:z10.url({protocol:/^https$/}).max(2e3).optional(),action:BlockSayActionSchema.optional()})).min(2).max(6)}),EntryBlockSchema=BlockBaseSchema.extend({type:z10.literal("entry"),label:z10.string().min(1).max(80),collection:z10.string().min(1).max(80),entryId:z10.string().min(1).max(120),path:z10.string().min(1).max(120).optional()}),AssetsBlockSchema=BlockBaseSchema.extend({type:z10.literal("assets"),items:z10.array(z10.object({url:z10.url({protocol:/^https$/}).max(2e3),alt:z10.string().min(1).max(120),label:z10.string().min(1).max(60).optional()})).min(1).max(6)}),CalloutBlockSchema=BlockBaseSchema.extend({type:z10.literal("callout"),title:z10.string().min(1).max(80),text:z10.string().min(1).max(240),action:BlockAppActionSchema}).strict(),StatBlockSchema=BlockBaseSchema.extend({type:z10.literal("stat"),items:z10.array(z10.object({label:z10.string().min(1).max(24),value:z10.string().min(1).max(16),delta:z10.string().min(1).max(12).optional(),tone:z10.enum(["up","down","flat"]).optional()})).min(1).max(4)}),ChartBlockSchema=BlockBaseSchema.extend({type:z10.literal("chart"),unit:z10.string().min(1).max(12).optional(),points:z10.array(z10.object({label:z10.string().min(1).max(12),value:z10.number().finite().min(0).max(1e9)})).min(2).max(12)}),ChatDisplayBlockSchema=z10.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema]),ChatFormBodySchema=z10.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,AssetsBlockSchema]);__name(getChatFormOptionLabels,"getChatFormOptionLabels");ChatFormStepSchema=z10.object({question:z10.string().min(1).max(500),header:z10.string().min(1).max(25),body:ChatFormBodySchema,multiSelect:z10.boolean(),recommended:z10.string().min(1).max(80).optional()}).superRefine((step,ctx)=>{let labels2=getChatFormOptionLabels(step.body);labels2.some(label=>!label.trim())&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a visible label."}),new Set(labels2).size!==labels2.length&&ctx.addIssue({code:"custom",path:["body"],message:"Every form option needs a unique label."}),step.recommended&&!labels2.includes(step.recommended)&&ctx.addIssue({code:"custom",path:["recommended"],message:"The recommended option must match a visible option label."})}),FormBlockSchema=BlockBaseSchema.extend({type:z10.literal("form"),steps:z10.array(ChatFormStepSchema).min(1).max(4)}),ChatBlockSchema=z10.discriminatedUnion("type",[ChoicesBlockSchema,TableBlockSchema,CardsBlockSchema,EntryBlockSchema,AssetsBlockSchema,CalloutBlockSchema,StatBlockSchema,ChartBlockSchema,FormBlockSchema]),ChatBlockToolInputSchema=z10.object({block:ChatBlockSchema}),ChatFormAnswerItemSchema=z10.object({header:z10.string().min(1).max(25),question:z10.string().min(1).max(500),answer:z10.string().min(1).max(3e3),selectedLabels:z10.array(z10.string().min(1).max(120)).max(8),freeText:z10.string().max(2e3),skipped:z10.boolean()}),ChatFormAnswerMetadataSchema=z10.object({toolCallId:z10.string().max(255).optional(),shortTitle:z10.string().max(80).optional(),questions:z10.array(ChatFormAnswerItemSchema).max(4)}),ChatFormResponseSchema=ChatFormAnswerMetadataSchema.extend({toolCallId:z10.string().min(1).max(255)})}});import{z as z11}from"zod";var ProjectDTOSchema,ProjectDTO,ProjectWithPlanDTOSchema,ProjectWithPlanDTO,ProjectSummaryDTOSchema,ProjectSummaryDTO,ProjectUserDTOSchema,ProjectUserDTO,ProjectFileDTOSchema,ProjectFileDTO,ProjectChatMessageRole,ProjectMessageBaseSchema,MessageUserMetadataSchema,ProjectMessagePublicDTOSchema,ProjectMessagePublicDTO,ProjectMessageDTOSchema,ProjectVersionDTOSchema,ProjectVersionDTO,ProjectHistoryUsageDTOSchema,ProjectVersionPageDTOSchema,ProjectVersionPageDTO,ProjectHistorySummaryDTOSchema,ProjectHistorySummaryDTO,ProjectDocumentContentDTOSchema,ProjectDocumentContentDTO,ProjectListResponseSchema,ProjectVersionResponseSchema,ProjectVersionPageResponseSchema,ProjectHistorySummaryResponseSchema,VersionMutationResponseSchema,ProjectPublicationStateDTOSchema,ProjectPublicationStateDTO,PublicationMutationDTOSchema,PublicationMutationDTO,ProjectPublicationStateResponseSchema,PublicationMutationResponseSchema,ProjectResponseSchema,ProjectWithPlanResponseSchema,init_project_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project.dto.js"(){"use strict";init_chat_block();init_common();init_create_dto();init_response();ProjectDTOSchema=BaseEntitySchema.extend({name:z11.string(),displayName:z11.string().nullable(),subdomain:z11.string().nullable().optional(),subdomainUpdatedAt:z11.date().nullable().optional(),organizationId:z11.string().nullable(),createdBy:z11.string().nullable(),visibility:ProjectVisibilitySchema,previewEnabled:z11.boolean().default(!0),status:ProjectStatusSchema,creationStatus:z11.string(),thumbnailUrl:z11.string().nullable(),publishedThumbnailUrl:z11.string().nullable(),category:z11.string().nullable(),appUrl:z11.string().nullable(),lastPublishedAt:z11.coerce.date()}),ProjectDTO=createDTO(ProjectDTOSchema),ProjectWithPlanDTOSchema=ProjectDTOSchema.extend({planTier:z11.string().nullable()}),ProjectWithPlanDTO=createDTO(ProjectWithPlanDTOSchema),ProjectSummaryDTOSchema=z11.object({id:z11.uuid(),name:z11.string(),displayName:z11.string().nullable(),thumbnailUrl:z11.string().nullable(),visibility:ProjectVisibilitySchema,category:z11.string().nullable()}),ProjectSummaryDTO=createDTO(ProjectSummaryDTOSchema),ProjectUserDTOSchema=z11.object({id:z11.string(),name:z11.string(),avatar:z11.string().nullable(),color:z11.object({bg:z11.string(),text:z11.string()})}),ProjectUserDTO=createDTO(ProjectUserDTOSchema),ProjectFileDTOSchema=z11.object({path:z11.string(),content:z11.string()}),ProjectFileDTO=createDTO(ProjectFileDTOSchema),ProjectChatMessageRole=z11.enum(["user","assistant","system"]),ProjectMessageBaseSchema=z11.object({id:z11.string(),messageId:z11.string(),versionId:z11.string().nullable(),role:ProjectChatMessageRole,parts:z11.array(z11.any()),createdAt:z11.coerce.date()}),MessageUserMetadataSchema=z11.object({id:z11.string(),name:z11.string().nullable().optional(),image:z11.string().nullable().optional()}).nullable().optional(),ProjectMessagePublicDTOSchema=ProjectMessageBaseSchema.extend({credits:z11.number(),metadata:z11.object({user:MessageUserMetadataSchema,changeManifest:z11.array(z11.any()).optional(),questionAnswer:ChatFormAnswerMetadataSchema.optional()}).nullable().optional()}),ProjectMessagePublicDTO=createDTO(ProjectMessagePublicDTOSchema),ProjectMessageDTOSchema=ProjectMessagePublicDTOSchema,ProjectVersionDTOSchema=z11.object({versionId:z11.uuid(),commitHash:z11.string(),name:z11.string(),description:z11.string().nullable(),kind:z11.enum(["manual","agent","restore-safety","deploy","merge","content","legacy"]),createdAt:CommonSchemas.timestamp,expiresAt:CommonSchemas.timestamp}),ProjectVersionDTO=createDTO(ProjectVersionDTOSchema),ProjectHistoryUsageDTOSchema=z11.object({versionCount:z11.number().int().nonnegative(),snapshotBytes:z11.number().int().nonnegative()}),ProjectVersionPageDTOSchema=createCursorPageDataSchema(ProjectVersionDTOSchema),ProjectVersionPageDTO=createDTO(ProjectVersionPageDTOSchema),ProjectHistorySummaryDTOSchema=z11.object({usage:ProjectHistoryUsageDTOSchema,retentionDays:z11.number().int().positive()}),ProjectHistorySummaryDTO=createDTO(ProjectHistorySummaryDTOSchema),ProjectDocumentContentDTOSchema=z11.object({content:z11.string()}),ProjectDocumentContentDTO=createDTO(ProjectDocumentContentDTOSchema),ProjectListResponseSchema=createResponseSchema(z11.array(ProjectDTOSchema)),ProjectVersionResponseSchema=createResponseSchema(ProjectVersionDTOSchema),ProjectVersionPageResponseSchema=createCursorPaginatedResponseSchema(ProjectVersionDTOSchema),ProjectHistorySummaryResponseSchema=createResponseSchema(ProjectHistorySummaryDTOSchema),VersionMutationResponseSchema=createResponseSchema(z11.object({success:z11.boolean(),message:z11.string().optional(),warning:z11.string().optional(),durationMs:z11.number().int().nonnegative().optional()})),ProjectPublicationStateDTOSchema=z11.object({isPublished:z11.boolean(),publishedAt:CommonSchemas.timestamp.nullable(),publishedVersion:z11.string().nullable()}),ProjectPublicationStateDTO=createDTO(ProjectPublicationStateDTOSchema),PublicationMutationDTOSchema=z11.object({success:z11.boolean(),message:z11.string().optional(),publishedAt:CommonSchemas.timestamp.optional()}),PublicationMutationDTO=createDTO(PublicationMutationDTOSchema),ProjectPublicationStateResponseSchema=createResponseSchema(ProjectPublicationStateDTOSchema),PublicationMutationResponseSchema=createResponseSchema(PublicationMutationDTOSchema),ProjectResponseSchema=createResponseSchema(ProjectDTOSchema),ProjectWithPlanResponseSchema=createResponseSchema(ProjectWithPlanDTOSchema)}});import{z as z12}from"zod";var ProjectEnvStatusSchema,ProjectEnvDTOSchema,ProjectEnvDTO,CreateProjectEnvRequestSchema,SyncProjectEnvRequestSchema,ProjectEnvResponseSchema,ProjectEnvsListResponseSchema,EnvSurfaceDiffSchema,EnvDiffResultSchema,EnvDiffResultDTO,init_project_env_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-env.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();ProjectEnvStatusSchema=z12.enum(["provisioning","active","deleted"]),ProjectEnvDTOSchema=BaseEntitySchema.extend({projectId:z12.uuid(),env:EnvSchema,status:ProjectEnvStatusSchema,previewUrl:z12.string().nullable(),parentEnv:EnvSchema.nullable(),createdBy:z12.string().nullable(),deletedAt:z12.coerce.date().nullable()}),ProjectEnvDTO=createDTO(ProjectEnvDTOSchema),CreateProjectEnvRequestSchema=z12.object({env:EnvSchema,parentEnv:EnvSchema.optional()}),SyncProjectEnvRequestSchema=z12.object({from:EnvSchema.optional()}),ProjectEnvResponseSchema=createResponseSchema(ProjectEnvDTOSchema),ProjectEnvsListResponseSchema=createResponseSchema(z12.array(ProjectEnvDTOSchema)),EnvSurfaceDiffSchema=z12.object({surface:z12.enum(["code","schemas","content","translations","assets","forms","activations"]),status:z12.enum(["unchanged","changed","conflicting","missing-on-target"]),changedCount:z12.number().int().nonnegative(),conflictCount:z12.number().int().nonnegative()}),EnvDiffResultSchema=z12.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z12.coerce.date(),surfaces:z12.array(EnvSurfaceDiffSchema)}),EnvDiffResultDTO=createDTO(EnvDiffResultSchema)}});import{z as z13}from"zod";var ExportProjectResponseDTOSchema,ExportProjectResponseDTO,ImportProjectResultDTOSchema,ImportProjectResultDTO,ImportPreviewCountsDTOSchema,ImportPreviewSurfaceDTOSchema,ImportPreviewDTOSchema,ImportPreviewDTO,ImportPreviewResponseDTOSchema,ImportPreviewResponseDTO,init_project_import_export_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-import-export.dto.js"(){"use strict";init_create_dto();ExportProjectResponseDTOSchema=z13.object({success:z13.literal(!0),downloadUrl:z13.string(),expiresAt:z13.string(),fileSize:z13.number(),duration:z13.number()}),ExportProjectResponseDTO=createDTO(ExportProjectResponseDTOSchema),ImportProjectResultDTOSchema=z13.object({success:z13.literal(!0),projectId:z13.string(),projectName:z13.string(),displayName:z13.string(),projectUrl:z13.string(),duration:z13.number()}),ImportProjectResultDTO=createDTO(ImportProjectResultDTOSchema),ImportPreviewCountsDTOSchema=z13.object({contentTypes:z13.number(),entries:z13.number(),assets:z13.number(),translations:z13.number(),forms:z13.number(),codeFiles:z13.number(),assetFiles:z13.number()}),ImportPreviewSurfaceDTOSchema=z13.object({name:z13.string(),included:z13.boolean(),count:z13.number().optional(),note:z13.string().optional()}),ImportPreviewDTOSchema=z13.object({projectName:z13.string(),displayName:z13.string().nullable(),visibility:z13.string().nullable(),category:z13.string().nullable(),exportedAt:z13.string(),version:z13.string(),envScope:z13.enum(["main","tree"]),counts:ImportPreviewCountsDTOSchema,surfaces:z13.array(ImportPreviewSurfaceDTOSchema),fileSize:z13.number(),fileName:z13.string()}),ImportPreviewDTO=createDTO(ImportPreviewDTOSchema),ImportPreviewResponseDTOSchema=z13.object({success:z13.literal(!0),preview:ImportPreviewDTOSchema}),ImportPreviewResponseDTO=createDTO(ImportPreviewResponseDTOSchema)}});import{z as z14}from"zod";var TriggerKindSchema,ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema,TriggerSchema,init_agent_trigger_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-trigger.dto.js"(){"use strict";TriggerKindSchema=z14.enum(["manual","schedule","webhook"]),ManualTriggerSchema=z14.object({type:z14.literal("manual")}),ScheduleTriggerSchema=z14.object({type:z14.literal("schedule"),cron:z14.string().min(1,"cron expression required").regex(/^\s*\S+\s+\S+\s+\S+\s+\S+\s+\S+\s*$/,"cron must be a 5-field expression"),tz:z14.string().optional()}),WebhookTriggerSchema=z14.object({type:z14.literal("webhook"),path:z14.string().min(1).max(120).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema=z14.discriminatedUnion("type",[ManualTriggerSchema,ScheduleTriggerSchema,WebhookTriggerSchema])}});import{z as z15}from"zod";var ActivateRequestSchema,DeactivateRequestSchema,AgentActivationDTOSchema,AgentActivationDTO,AgentActivationsListResponseSchema,AgentActivationResponseSchema,WebhookPathTakenErrorSchema,ManualRunRequestSchema,DispatchSkippedSchema,DispatchAcceptedSchema,ManualRunResponseSchema,init_agent_activation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-activation.dto.js"(){"use strict";init_env();init_create_dto();init_response();init_agent_trigger_dto();ActivateRequestSchema=z15.object({triggerIndices:z15.array(z15.number().int().nonnegative()).optional()}),DeactivateRequestSchema=z15.object({triggerIndices:z15.array(z15.number().int().nonnegative()).optional()}),AgentActivationDTOSchema=z15.object({projectId:z15.uuid(),env:EnvSchema,agentName:z15.string().min(1),triggerIndex:z15.number().int().nonnegative(),triggerKind:TriggerKindSchema,trigger:TriggerSchema,enabled:z15.boolean(),lastFiredAt:z15.coerce.date().nullable(),webhookPath:z15.string().nullable(),createdAt:z15.coerce.date(),updatedAt:z15.coerce.date()}),AgentActivationDTO=createDTO(AgentActivationDTOSchema),AgentActivationsListResponseSchema=createResponseSchema(z15.array(AgentActivationDTOSchema)),AgentActivationResponseSchema=createResponseSchema(AgentActivationDTOSchema),WebhookPathTakenErrorSchema=z15.object({error:z15.literal("webhook_path_taken"),conflictAgent:z15.string(),path:z15.string()}),ManualRunRequestSchema=z15.object({args:z15.unknown().optional(),requestId:z15.string().min(1).max(128).optional()}),DispatchSkippedSchema=z15.object({skipped:z15.enum(["duplicate","no-activation","agent-not-cloud","bundle-missing","trigger-stale"])}),DispatchAcceptedSchema=z15.object({sessionId:z15.string().min(1)}),ManualRunResponseSchema=createResponseSchema(z15.union([DispatchAcceptedSchema,DispatchSkippedSchema]))}});import{z as z16}from"zod";var CapabilityRiskTierSchema,CapabilitySummaryEntrySchema,AgentSubAgentSummarySchema,AgentInstallSummaryDTOSchema,AgentInstallSummaryDTO,AgentInstallSummaryResponseSchema,init_agent_install_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-install-summary.dto.js"(){"use strict";init_create_dto();init_response();CapabilityRiskTierSchema=z16.enum(["low","medium","high","critical"]),CapabilitySummaryEntrySchema=z16.object({token:z16.string().min(1),risk:CapabilityRiskTierSchema,description:z16.string()}),AgentSubAgentSummarySchema=z16.object({name:z16.string().min(1),grant:z16.enum(["inherit","explicit"]),effectiveCaps:z16.array(z16.string().min(1))}),AgentInstallSummaryDTOSchema=z16.object({agentName:z16.string().min(1),env:z16.string().min(1),declaredCapabilities:z16.array(CapabilitySummaryEntrySchema),transitiveCapabilities:z16.array(CapabilitySummaryEntrySchema),highRiskCapabilities:z16.array(CapabilitySummaryEntrySchema),criticalCapabilities:z16.array(CapabilitySummaryEntrySchema),subAgents:z16.array(AgentSubAgentSummarySchema),declaresDelegate:z16.boolean(),cycle:z16.array(z16.string()).nullable(),missingSubAgents:z16.array(z16.string()),warnings:z16.array(z16.string())}),AgentInstallSummaryDTO=createDTO(AgentInstallSummaryDTOSchema),AgentInstallSummaryResponseSchema=createResponseSchema(AgentInstallSummaryDTOSchema)}});import{z as z17}from"zod";var AgentListItemTriggerSchema,AgentListItemActivationSchema,AgentListItemDTOSchema,AgentListItemDTO,AgentListResponseSchema,init_agent_list_item_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-list-item.dto.js"(){"use strict";init_create_dto();init_response();init_agent_install_summary_dto();init_agent_trigger_dto();AgentListItemTriggerSchema=z17.object({kind:TriggerKindSchema,summary:z17.string()}),AgentListItemActivationSchema=z17.object({triggerIndex:z17.number().int().nonnegative(),triggerKind:TriggerKindSchema,env:z17.string().min(1),active:z17.boolean()}),AgentListItemDTOSchema=z17.object({name:z17.string().min(1),description:z17.string().nullable(),goalFirstLine:z17.string().nullable(),declaredCapabilities:z17.array(CapabilitySummaryEntrySchema),triggers:z17.array(AgentListItemTriggerSchema),activations:z17.array(AgentListItemActivationSchema)}),AgentListItemDTO=createDTO(AgentListItemDTOSchema),AgentListResponseSchema=createResponseSchema(z17.array(AgentListItemDTOSchema))}});import{z as z18}from"zod";var AgentSessionStatusSchema,SessionMetricsSchema,AgentSessionDTOSchema,AgentSessionDTO,AgentSessionCheckpointDTOSchema,AgentSessionCheckpointDTO,AgentSessionResponseSchema,AgentSessionsListResponseSchema,AgentSessionCheckpointsListResponseSchema,AgentSessionWithCheckpointsResponseSchema,SessionErrorCodeSchema,CancelSessionRequestSchema,init_agent_session_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-session.dto.js"(){"use strict";init_env();init_create_dto();init_response();init_agent_trigger_dto();AgentSessionStatusSchema=z18.enum(["planned","running","finished","cancelled","errored"]),SessionMetricsSchema=z18.object({cpuMs:z18.number().nonnegative().default(0),netBytes:z18.number().nonnegative().default(0),walltimeMs:z18.number().nonnegative().default(0),llmTokensIn:z18.number().nonnegative().optional(),llmTokensOut:z18.number().nonnegative().optional()}),AgentSessionDTOSchema=z18.object({id:z18.uuid(),projectId:z18.uuid(),env:EnvSchema,agentName:z18.string().min(1),triggerKind:TriggerKindSchema,triggerPayload:z18.unknown().optional(),capabilities:z18.array(z18.string()).optional(),dataSources:z18.array(z18.string()).optional(),status:AgentSessionStatusSchema,sandboxId:z18.string().nullable(),startedAt:z18.coerce.date().nullable(),finishedAt:z18.coerce.date().nullable(),cancelledAt:z18.coerce.date().nullable(),costUsd:z18.number().nonnegative(),costCeilingUsd:z18.number().positive(),metrics:SessionMetricsSchema.nullable(),longRunning:z18.boolean(),lastCheckpointId:z18.uuid().nullable(),branchEnvId:z18.uuid().nullable(),parentSessionId:z18.uuid().nullable(),terminalReason:z18.string().nullable(),errorMessage:z18.string().nullable(),report:z18.string().nullable(),createdAt:z18.coerce.date(),updatedAt:z18.coerce.date()}),AgentSessionDTO=createDTO(AgentSessionDTOSchema),AgentSessionCheckpointDTOSchema=z18.object({id:z18.uuid(),sessionId:z18.uuid(),checkpointIdx:z18.number().int().nonnegative(),payloadRef:z18.string(),payloadSizeBytes:z18.number().int().nonnegative(),checksum:z18.string().length(64),createdAt:z18.coerce.date()}),AgentSessionCheckpointDTO=createDTO(AgentSessionCheckpointDTOSchema),AgentSessionResponseSchema=createResponseSchema(AgentSessionDTOSchema),AgentSessionsListResponseSchema=createResponseSchema(z18.array(AgentSessionDTOSchema)),AgentSessionCheckpointsListResponseSchema=createResponseSchema(z18.array(AgentSessionCheckpointDTOSchema)),AgentSessionWithCheckpointsResponseSchema=createResponseSchema(z18.object({session:AgentSessionDTOSchema,checkpoints:z18.array(AgentSessionCheckpointDTOSchema)})),SessionErrorCodeSchema=z18.enum(["invalid_session_transition","session_not_found","capability_snapshot_invalid","checkpoint_restore_failed","cost_ceiling_invalid","too_many_agent_envs","env_provisioning_failed"]),CancelSessionRequestSchema=z18.object({reason:z18.string().min(1).max(120).optional()})}});import{z as z19}from"zod";var AgentBranchClassificationSchema,AgentBranchDecidedPathSchema,AgentBranchProposalDTOSchema,AgentBranchProposalDTO,DecideProposalRequestSchema,AgentBranchProposalResponseSchema,AgentBranchProposalsListResponseSchema,DecideProposalConflictResponseSchema,init_agent_proposal_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/agent-proposal.dto.js"(){"use strict";init_create_dto();init_response();AgentBranchClassificationSchema=z19.enum(["trivial","structural"]),AgentBranchDecidedPathSchema=z19.enum(["auto-merge","review-merged","review-discarded"]),AgentBranchProposalDTOSchema=z19.object({id:z19.uuid(),envId:z19.uuid(),sessionId:z19.uuid().nullable(),skillName:z19.string().min(1),classification:AgentBranchClassificationSchema,rationale:z19.string().nullable(),summary:z19.string().nullable(),surfaceDeltas:z19.record(z19.string(),z19.unknown()),createdAt:z19.coerce.date(),decidedAt:z19.coerce.date().nullable(),decidedPath:AgentBranchDecidedPathSchema.nullable(),decidedBy:z19.string().nullable()}),AgentBranchProposalDTO=createDTO(AgentBranchProposalDTOSchema),DecideProposalRequestSchema=z19.object({path:z19.enum(["review-merged","review-discarded"])}),AgentBranchProposalResponseSchema=createResponseSchema(AgentBranchProposalDTOSchema),AgentBranchProposalsListResponseSchema=createResponseSchema(z19.array(AgentBranchProposalDTOSchema)),DecideProposalConflictResponseSchema=z19.object({code:z19.literal("merge_conflict"),message:z19.string(),conflicts:z19.record(z19.string(),z19.number().int().nonnegative())})}});import{z as z20}from"zod";var IntegrationAuthModeSchema,IntegrationAuthKindSchema,IntegrationCredentialInputSchema,IntegrationCredentialUsageSchema,ProjectIntegrationCredentialStatusSchema,IntegrationAuthModeDTOSchema,IntegrationCredentialDefinitionDTOSchema,IntegrationToolDefinitionDTOSchema,IntegrationRecipeDTOSchema,IntegrationInfoDTOSchema,IntegrationInfoDTO,ProjectIntegrationStatusDTOSchema,ProjectIntegrationStatusDTO,ProjectIntegrationInstallationDTOSchema,ProjectIntegrationInstallationDTO,EnableProjectIntegrationRequestSchema,SwitchProjectIntegrationAuthRequestSchema,SetProjectIntegrationCredentialRequestSchema,OrganizationIntegrationConnectionStatusSchema,OrganizationIntegrationConnectionDTOSchema,OrganizationIntegrationConnectionDTO,ConnectOrganizationIntegrationRequestSchema,StartProjectIntegrationConnectResponseSchema,StartProjectIntegrationConnectResponseDTO,BindProjectChannelRequestSchema,ProjectChannelBindingDTOSchema,ProjectChannelBindingDTO,FirecrawlScrapeFormatsSchema,FirecrawlScrapeToolInputSchema,FirecrawlSearchToolInputSchema,FirecrawlMapToolInputSchema,FirecrawlCrawlToolInputSchema,FirecrawlMonitorScheduleInputSchema,FirecrawlMonitorTargetInputSchema,FirecrawlMonitorCreateToolInputSchema,FirecrawlMonitorIdToolInputSchema,FirecrawlMonitorCheckToolInputSchema,RunProjectIntegrationToolOptionsSchema,RunProjectIntegrationToolRequestSchema,ProjectIntegrationToolRunUsageSchema,ProjectIntegrationToolRunBillingSchema,FirecrawlScrapeToolOutputSchema,FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlMonitorScheduleOutputSchema,FirecrawlMonitorTargetOutputSchema,FirecrawlMonitorOutputSchema,FirecrawlMonitorCheckOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema,FirecrawlToolKeySchema,FirecrawlToolOutputSchema,ProjectIntegrationToolRunBaseSchema,ProjectIntegrationToolRunDTOSchema,ProjectIntegrationToolRunDTO,IntegrationsListResponseSchema,IntegrationInfoResponseSchema,ProjectIntegrationStatusResponseSchema,ProjectIntegrationInstallationResponseSchema,ProjectIntegrationToolRunResponseSchema,StartProjectIntegrationConnectResponseResponseSchema,OrganizationIntegrationConnectionResponseSchema,ProjectChannelBindingResponseSchema,init_integration_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/integration.dto.js"(){"use strict";init_create_dto();init_response();IntegrationAuthModeSchema=z20.enum(["fimo","personal","oauth"]),IntegrationAuthKindSchema=z20.enum(["oauth","api_key","bot_token","basic"]),IntegrationCredentialInputSchema=z20.enum(["secret_text"]),IntegrationCredentialUsageSchema=z20.enum(["http_bearer","api_key"]),ProjectIntegrationCredentialStatusSchema=z20.enum(["not_required","missing","configured"]),IntegrationAuthModeDTOSchema=z20.object({mode:IntegrationAuthModeSchema,label:z20.string().min(1),description:z20.string().min(1)}),IntegrationCredentialDefinitionDTOSchema=z20.object({id:z20.string().min(1),label:z20.string().min(1),input:IntegrationCredentialInputSchema,usage:IntegrationCredentialUsageSchema,required:z20.boolean()}),IntegrationToolDefinitionDTOSchema=z20.object({key:z20.string().min(1),name:z20.string().min(1),description:z20.string().min(1)}),IntegrationRecipeDTOSchema=z20.object({title:z20.string().min(1),description:z20.string().min(1),command:z20.string().min(1).optional()}),IntegrationInfoDTOSchema=z20.object({key:z20.string().min(1),name:z20.string().min(1),summary:z20.string().min(1),defaultAuthMode:IntegrationAuthModeSchema.nullable().optional(),authModes:z20.array(IntegrationAuthModeDTOSchema),credentials:z20.array(IntegrationCredentialDefinitionDTOSchema),tools:z20.array(IntegrationToolDefinitionDTOSchema),recipes:z20.array(IntegrationRecipeDTOSchema)}),IntegrationInfoDTO=createDTO(IntegrationInfoDTOSchema),ProjectIntegrationStatusDTOSchema=z20.object({projectId:z20.uuid(),integrationKey:z20.string().min(1),installed:z20.boolean(),enabled:z20.boolean(),authMode:IntegrationAuthModeSchema.nullable(),authModeLabel:z20.string().nullable(),connectionId:z20.uuid().nullable().optional(),connectionAlias:z20.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z20.array(z20.string()),installedAt:z20.coerce.date().nullable(),updatedAt:z20.coerce.date().nullable()}),ProjectIntegrationStatusDTO=createDTO(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationDTOSchema=z20.object({id:z20.uuid(),projectId:z20.uuid(),integrationKey:z20.string().min(1),enabled:z20.boolean(),authMode:IntegrationAuthModeSchema,authModeLabel:z20.string(),connectionId:z20.uuid().nullable().optional(),connectionAlias:z20.string().min(1).nullable().optional(),credentialStatus:ProjectIntegrationCredentialStatusSchema,configuredCredentials:z20.array(z20.string()),createdAt:z20.coerce.date(),updatedAt:z20.coerce.date()}),ProjectIntegrationInstallationDTO=createDTO(ProjectIntegrationInstallationDTOSchema),EnableProjectIntegrationRequestSchema=z20.object({authMode:IntegrationAuthModeSchema.optional(),connectionAlias:z20.string().min(1).optional()}),SwitchProjectIntegrationAuthRequestSchema=z20.object({authMode:IntegrationAuthModeSchema}),SetProjectIntegrationCredentialRequestSchema=z20.object({value:z20.string().min(1)}),OrganizationIntegrationConnectionStatusSchema=z20.enum(["active","revoked"]),OrganizationIntegrationConnectionDTOSchema=z20.object({id:z20.uuid(),organizationId:z20.string().min(1),integrationKey:z20.string().min(1),alias:z20.string().min(1),authKind:IntegrationAuthKindSchema,externalAccountId:z20.string().min(1),externalAccountName:z20.string().nullable(),externalBotUserId:z20.string().nullable(),status:OrganizationIntegrationConnectionStatusSchema,scopes:z20.array(z20.string()),connectedAt:z20.coerce.date(),updatedAt:z20.coerce.date()}),OrganizationIntegrationConnectionDTO=createDTO(OrganizationIntegrationConnectionDTOSchema),ConnectOrganizationIntegrationRequestSchema=z20.object({alias:z20.string().min(1).max(120).optional(),token:z20.string().min(1).optional()}),StartProjectIntegrationConnectResponseSchema=z20.object({integrationKey:z20.string().min(1),connectUrl:z20.string().url(),expiresAt:z20.coerce.date()}),StartProjectIntegrationConnectResponseDTO=createDTO(StartProjectIntegrationConnectResponseSchema),BindProjectChannelRequestSchema=z20.object({ref:z20.string().min(1),connectionAlias:z20.string().min(1).optional(),agentName:z20.string().min(1).max(160).nullable().optional(),force:z20.boolean().optional()}),ProjectChannelBindingDTOSchema=z20.object({id:z20.uuid(),projectId:z20.uuid(),integrationKey:z20.string().min(1),connectionId:z20.uuid(),externalWorkspaceId:z20.string().min(1),externalChannelId:z20.string().min(1),externalChannelName:z20.string().nullable(),agentName:z20.string().nullable(),enabled:z20.boolean(),createdAt:z20.coerce.date(),updatedAt:z20.coerce.date()}),ProjectChannelBindingDTO=createDTO(ProjectChannelBindingDTOSchema),FirecrawlScrapeFormatsSchema=z20.object({markdown:z20.boolean().optional(),summary:z20.boolean().optional(),links:z20.boolean().optional(),images:z20.boolean().optional(),html:z20.union([z20.literal("cleaned"),z20.literal("raw"),z20.boolean()]).optional()}).default({markdown:!0}),FirecrawlScrapeToolInputSchema=z20.object({url:z20.string().url(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z20.boolean().optional(),timeoutMs:z20.number().int().positive().max(12e4).optional(),waitForMs:z20.number().int().min(0).max(3e4).optional()}),FirecrawlSearchToolInputSchema=z20.object({query:z20.string().min(1),maxResults:z20.number().int().positive().max(20).optional(),sources:z20.array(z20.enum(["web","news","images"])).min(1).max(3).optional(),categories:z20.array(z20.enum(["github","research","pdf"])).min(1).max(3).optional(),includeDomains:z20.array(z20.string().min(1).max(253)).min(1).max(100).optional(),excludeDomains:z20.array(z20.string().min(1).max(253)).min(1).max(100).optional(),timeRange:z20.enum(["hour","day","week","month","year"]).optional(),location:z20.string().min(1).max(160).optional(),country:z20.string().regex(/^[A-Za-z]{2}$/,"Country must be a two-letter code.").optional(),highlights:z20.boolean().optional(),timeoutMs:z20.number().int().positive().max(12e4).optional()}).refine(value=>!(value.includeDomains&&value.excludeDomains),{message:"Choose includeDomains or excludeDomains, not both."}),FirecrawlMapToolInputSchema=z20.object({url:z20.string().url(),search:z20.string().min(1).optional(),limit:z20.number().int().positive().max(200).optional(),includeSubdomains:z20.boolean().optional(),timeoutMs:z20.number().int().positive().max(12e4).optional()}),FirecrawlCrawlToolInputSchema=z20.object({url:z20.string().url(),limit:z20.number().int().positive().max(20).optional(),formats:FirecrawlScrapeFormatsSchema,onlyMainContent:z20.boolean().optional(),timeoutMs:z20.number().int().positive().max(12e4).optional()}),FirecrawlMonitorScheduleInputSchema=z20.object({text:z20.string().min(1).max(200).optional(),cron:z20.string().min(1).max(120).optional(),timezone:z20.string().min(1).max(80).optional()}).refine(value=>!!(value.text||value.cron),"Firecrawl monitor schedule needs text or cron."),FirecrawlMonitorTargetInputSchema=z20.object({type:z20.enum(["scrape","crawl"]).default("scrape"),urls:z20.array(z20.string().url()).min(1).max(50),scrapeOptions:z20.object({formats:FirecrawlScrapeFormatsSchema.optional(),onlyMainContent:z20.boolean().optional(),timeoutMs:z20.number().int().positive().max(12e4).optional(),waitForMs:z20.number().int().min(0).max(3e4).optional()}).optional()}),FirecrawlMonitorCreateToolInputSchema=z20.object({name:z20.string().min(1).max(256),schedule:FirecrawlMonitorScheduleInputSchema,targets:z20.array(FirecrawlMonitorTargetInputSchema).min(1).max(50),goal:z20.string().min(1).max(2e3).optional(),judgeEnabled:z20.boolean().optional(),retentionDays:z20.number().int().min(1).max(365).optional(),notification:z20.object({email:z20.object({enabled:z20.boolean().default(!0),recipients:z20.array(z20.string().email()).min(1).max(20),includeDiffs:z20.boolean().optional()}).optional()}).optional()}),FirecrawlMonitorIdToolInputSchema=z20.object({monitorId:z20.string().uuid()}),FirecrawlMonitorCheckToolInputSchema=FirecrawlMonitorIdToolInputSchema.extend({checkId:z20.string().uuid()}),RunProjectIntegrationToolOptionsSchema=z20.object({connectionAlias:z20.string().min(1).optional()}),RunProjectIntegrationToolRequestSchema=z20.discriminatedUnion("tool",[RunProjectIntegrationToolOptionsSchema.extend({tool:z20.literal("search"),input:FirecrawlSearchToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z20.literal("scrape"),input:FirecrawlScrapeToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z20.literal("map"),input:FirecrawlMapToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z20.literal("crawl"),input:FirecrawlCrawlToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z20.literal("monitor.create"),input:FirecrawlMonitorCreateToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z20.literal("monitor.list"),input:z20.object({}).default({})}),RunProjectIntegrationToolOptionsSchema.extend({tool:z20.literal("monitor.get"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z20.literal("monitor.pause"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z20.literal("monitor.resume"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z20.literal("monitor.delete"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z20.literal("monitor.run"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z20.literal("monitor.checks"),input:FirecrawlMonitorIdToolInputSchema}),RunProjectIntegrationToolOptionsSchema.extend({tool:z20.literal("monitor.check"),input:FirecrawlMonitorCheckToolInputSchema})]),ProjectIntegrationToolRunUsageSchema=z20.object({provider:z20.string().min(1),providerCredits:z20.number().nonnegative().optional(),providerCostUsd:z20.number().nonnegative().optional(),requests:z20.number().int().nonnegative().optional()}),ProjectIntegrationToolRunBillingSchema=z20.object({credits:z20.number().int().nonnegative()}),FirecrawlScrapeToolOutputSchema=z20.object({url:z20.string(),provider:z20.literal("firecrawl"),title:z20.string().optional(),statusCode:z20.number().optional(),markdown:z20.string().optional(),summary:z20.string().optional(),links:z20.array(z20.string()).optional(),images:z20.array(z20.string()).optional(),html:z20.string().optional(),warning:z20.string().optional()}),FirecrawlSearchToolOutputSchema=z20.object({query:z20.string(),provider:z20.literal("firecrawl"),warning:z20.string().optional(),results:z20.array(z20.object({title:z20.string(),url:z20.string(),snippet:z20.string().optional(),content:z20.string().optional(),score:z20.number().optional(),publishedAt:z20.string().optional()}))}),FirecrawlMapToolOutputSchema=z20.object({url:z20.string(),provider:z20.literal("firecrawl"),count:z20.number(),links:z20.array(z20.object({url:z20.string(),title:z20.string().optional(),description:z20.string().optional()}))}),FirecrawlCrawlToolOutputSchema=z20.object({url:z20.string(),provider:z20.literal("firecrawl"),total:z20.number(),pages:z20.array(z20.object({url:z20.string(),title:z20.string().optional(),statusCode:z20.number().optional(),markdown:z20.string().optional(),summary:z20.string().optional(),links:z20.array(z20.string()).optional(),images:z20.array(z20.string()).optional(),html:z20.string().optional(),warning:z20.string().optional()})),warning:z20.string().optional()}),FirecrawlMonitorScheduleOutputSchema=z20.object({cron:z20.string().optional(),text:z20.string().optional(),timezone:z20.string().optional()}).passthrough(),FirecrawlMonitorTargetOutputSchema=z20.object({id:z20.string().optional(),urls:z20.array(z20.string()).optional(),scrapeOptions:z20.record(z20.string(),z20.unknown()).optional()}).passthrough(),FirecrawlMonitorOutputSchema=z20.object({id:z20.string(),name:z20.string(),status:z20.string().optional(),schedule:FirecrawlMonitorScheduleOutputSchema.optional(),nextRunAt:z20.string().nullable().optional(),lastRunAt:z20.string().nullable().optional(),currentCheckId:z20.string().nullable().optional(),targets:z20.array(FirecrawlMonitorTargetOutputSchema).optional(),goal:z20.string().nullable().optional(),judgeEnabled:z20.boolean().optional(),estimatedCreditsPerMonth:z20.number().optional(),createdAt:z20.string().optional(),updatedAt:z20.string().optional()}).passthrough(),FirecrawlMonitorCheckOutputSchema=z20.object({id:z20.string(),monitorId:z20.string(),scheduledFor:z20.string().nullable().optional(),startedAt:z20.string().nullable().optional(),finishedAt:z20.string().nullable().optional(),estimatedCredits:z20.number().optional(),reservedCredits:z20.number().optional(),actualCredits:z20.number().optional(),billingStatus:z20.string().nullable().optional(),summary:z20.object({totalPages:z20.number().optional(),same:z20.number().optional(),changed:z20.number().optional(),new:z20.number().optional(),removed:z20.number().optional(),error:z20.number().optional()}).passthrough().optional(),error:z20.string().nullable().optional(),createdAt:z20.string().optional(),updatedAt:z20.string().optional()}).passthrough(),FirecrawlMonitorListToolOutputSchema=z20.object({provider:z20.literal("firecrawl"),monitors:z20.array(FirecrawlMonitorOutputSchema)}),FirecrawlMonitorDetailToolOutputSchema=z20.object({provider:z20.literal("firecrawl"),monitor:FirecrawlMonitorOutputSchema}),FirecrawlMonitorDeleteToolOutputSchema=z20.object({provider:z20.literal("firecrawl"),monitorId:z20.string(),deleted:z20.boolean()}),FirecrawlMonitorChecksToolOutputSchema=z20.object({provider:z20.literal("firecrawl"),monitorId:z20.string(),checks:z20.array(FirecrawlMonitorCheckOutputSchema)}),FirecrawlMonitorCheckDetailToolOutputSchema=z20.object({provider:z20.literal("firecrawl"),monitorId:z20.string(),check:FirecrawlMonitorCheckOutputSchema,next:z20.string().optional()}),FirecrawlToolKeySchema=z20.enum(["search","scrape","map","crawl","monitor.create","monitor.list","monitor.get","monitor.pause","monitor.resume","monitor.delete","monitor.run","monitor.checks","monitor.check"]),FirecrawlToolOutputSchema=z20.union([FirecrawlSearchToolOutputSchema,FirecrawlMapToolOutputSchema,FirecrawlCrawlToolOutputSchema,FirecrawlScrapeToolOutputSchema,FirecrawlMonitorListToolOutputSchema,FirecrawlMonitorDetailToolOutputSchema,FirecrawlMonitorDeleteToolOutputSchema,FirecrawlMonitorChecksToolOutputSchema,FirecrawlMonitorCheckDetailToolOutputSchema]),ProjectIntegrationToolRunBaseSchema=z20.object({projectId:z20.uuid(),integrationKey:z20.string().min(1),tool:FirecrawlToolKeySchema,connectionAlias:z20.string().min(1).nullable().optional(),output:FirecrawlToolOutputSchema,executedAt:z20.coerce.date()}),ProjectIntegrationToolRunDTOSchema=z20.discriminatedUnion("authMode",[ProjectIntegrationToolRunBaseSchema.extend({authMode:z20.literal("fimo"),billing:ProjectIntegrationToolRunBillingSchema,usage:z20.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z20.literal("personal"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z20.undefined().optional()}),ProjectIntegrationToolRunBaseSchema.extend({authMode:z20.literal("oauth"),usage:ProjectIntegrationToolRunUsageSchema.optional(),billing:z20.undefined().optional()})]),ProjectIntegrationToolRunDTO=createDTO(ProjectIntegrationToolRunDTOSchema),IntegrationsListResponseSchema=createResponseSchema(z20.array(ProjectIntegrationStatusDTOSchema)),IntegrationInfoResponseSchema=createResponseSchema(IntegrationInfoDTOSchema),ProjectIntegrationStatusResponseSchema=createResponseSchema(ProjectIntegrationStatusDTOSchema),ProjectIntegrationInstallationResponseSchema=createResponseSchema(ProjectIntegrationInstallationDTOSchema),ProjectIntegrationToolRunResponseSchema=createResponseSchema(ProjectIntegrationToolRunDTOSchema),StartProjectIntegrationConnectResponseResponseSchema=createResponseSchema(StartProjectIntegrationConnectResponseSchema),OrganizationIntegrationConnectionResponseSchema=createResponseSchema(OrganizationIntegrationConnectionDTOSchema),ProjectChannelBindingResponseSchema=createResponseSchema(ProjectChannelBindingDTOSchema)}});import{z as z21}from"zod";var PROJECT_SECRET_KEY_PATTERN,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN,RESERVED_PROJECT_SECRET_KEYS,ProjectSecretKeySchema,ProjectScheduleStatusSchema,ProjectScheduleDTOSchema,ProjectScheduleDTO,CreateProjectScheduleRequestSchema,UpdateProjectScheduleRequestSchema,ProjectScheduleRunStatusSchema,ProjectScheduleRunTriggerSchema,ProjectScheduleRunSecretSnapshotStateSchema,ProjectScheduleRunSecretResolutionSchema,ProjectSchedulePolicySchema,ProjectScheduleUsageSchema,ProjectScheduleRunDTOSchema,ProjectScheduleRunDTO,ProjectScheduleRunSecretSnapshotSchema,ProjectScheduleRunDetailDTOSchema,ProjectScheduleRunDetailDTO,RunProjectScheduleRequestSchema,ProjectScheduleRunsQuerySchema,ProjectScheduleResponseSchema,ProjectSchedulesListDataSchema,ProjectSchedulesListResponseSchema,ProjectSchedulesOverviewResponseSchema,ProjectScheduleDetailDataSchema,ProjectScheduleDetailResponseSchema,ProjectScheduleRunsPageSchema,ProjectScheduleRunsResponseSchema,ProjectScheduleRunResponseSchema,ProjectScheduleRunDetailResponseSchema,init_schedule_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schedule.dto.js"(){"use strict";init_common();init_create_dto();init_response();PROJECT_SECRET_KEY_PATTERN=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_PROJECT_SECRET_PREFIX_PATTERN=/^(PUBLIC_|VITE_|NEXT_PUBLIC_)/,RESERVED_PROJECT_SECRET_KEYS=new Set(["FIMO_API_URL","FIMO_API_TOKEN","FIMO_PROJECT_ID","FIMO_ENV","FIMO_AGENT_SESSION","FIMO_DATA_SOURCES","FIMO_SCHEDULE_ID","FIMO_SCHEDULE_RUN_ID","FIMO_SCHEDULE_NAME","VITE_API_URL","VITE_ENABLE_ANALYTICS","VITE_FIMO_BRANCH","VITE_FIMO_IMAGE_HOSTS"]),ProjectSecretKeySchema=z21.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=z21.enum(["ok","failed"]),ProjectScheduleDTOSchema=BaseEntitySchema.extend({projectId:z21.uuid(),env:z21.string().min(1),name:z21.string().min(1),cron:z21.string().min(1),command:z21.string().min(1),secretKeys:z21.array(z21.string().min(1)),enabled:z21.boolean(),lastRunAt:z21.coerce.date().nullable(),lastStatus:ProjectScheduleStatusSchema.nullable(),lastError:z21.string().nullable()}),ProjectScheduleDTO=createDTO(ProjectScheduleDTOSchema),CreateProjectScheduleRequestSchema=z21.object({name:z21.string().min(1).max(120),cron:z21.string().min(1).max(120),command:z21.string().min(1).max(500),secretKeys:z21.array(ProjectSecretKeySchema).default([])}),UpdateProjectScheduleRequestSchema=z21.object({name:z21.string().min(1).max(120).optional(),cron:z21.string().min(1).max(120).optional(),command:z21.string().min(1).max(500).optional(),secretKeys:z21.array(ProjectSecretKeySchema).optional()}).refine(request=>Object.keys(request).length>0,"Pass at least one schedule field to update."),ProjectScheduleRunStatusSchema=z21.enum(["queued","running","succeeded","failed","skipped"]),ProjectScheduleRunTriggerSchema=z21.enum(["cron","ui","cli"]),ProjectScheduleRunSecretSnapshotStateSchema=z21.enum(["pending","resolved","failed"]),ProjectScheduleRunSecretResolutionSchema=z21.enum(["resolved","missing","deleted","recreated","rotated"]),ProjectSchedulePolicySchema=z21.object({maxRuns:z21.number().int().positive(),retentionDays:z21.number().int().positive().nullable(),outputRetentionDays:z21.number().int().positive(),maxOutputBytes:z21.number().int().positive()}),ProjectScheduleUsageSchema=z21.object({runCount:z21.number().int().nonnegative(),runsWithOutput:z21.number().int().nonnegative()}),ProjectScheduleRunDTOSchema=z21.object({id:z21.uuid(),scheduleId:z21.uuid(),projectId:z21.uuid(),env:z21.string().min(1),scheduleName:z21.string().min(1),command:z21.string().min(1),status:ProjectScheduleRunStatusSchema,trigger:ProjectScheduleRunTriggerSchema,triggeredBy:z21.object({id:z21.string().min(1),name:z21.string().min(1)}).nullable(),queuedAt:z21.coerce.date(),startedAt:z21.coerce.date().nullable(),finishedAt:z21.coerce.date().nullable(),exitCode:z21.number().int().nullable(),errorCode:z21.string().nullable(),error:z21.string().nullable(),outputBytes:z21.number().int().nonnegative(),outputTruncated:z21.boolean(),outputExpiresAt:z21.coerce.date().nullable(),metadataExpiresAt:z21.coerce.date().nullable()}),ProjectScheduleRunDTO=createDTO(ProjectScheduleRunDTOSchema),ProjectScheduleRunSecretSnapshotSchema=z21.object({state:ProjectScheduleRunSecretSnapshotStateSchema,capturedAt:z21.coerce.date().nullable(),items:z21.array(z21.object({key:z21.string().min(1),updatedAt:z21.coerce.date().nullable(),resolution:ProjectScheduleRunSecretResolutionSchema}))}),ProjectScheduleRunDetailDTOSchema=ProjectScheduleRunDTOSchema.extend({output:z21.string().nullable(),secretSnapshot:ProjectScheduleRunSecretSnapshotSchema}),ProjectScheduleRunDetailDTO=createDTO(ProjectScheduleRunDetailDTOSchema),RunProjectScheduleRequestSchema=z21.object({trigger:z21.enum(["ui","cli"])}),ProjectScheduleRunsQuerySchema=z21.object({limit:z21.coerce.number().int().min(1).max(100).default(25),cursor:z21.string().trim().min(1).optional(),status:ProjectScheduleRunStatusSchema.optional()}),ProjectScheduleResponseSchema=createResponseSchema(ProjectScheduleDTOSchema),ProjectSchedulesListDataSchema=z21.object({items:z21.array(ProjectScheduleDTOSchema),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema}),ProjectSchedulesListResponseSchema=createResponseSchema(z21.array(ProjectScheduleDTOSchema)),ProjectSchedulesOverviewResponseSchema=createResponseSchema(ProjectSchedulesListDataSchema),ProjectScheduleDetailDataSchema=z21.object({schedule:ProjectScheduleDTOSchema,usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema}),ProjectScheduleDetailResponseSchema=createResponseSchema(ProjectScheduleDetailDataSchema),ProjectScheduleRunsPageSchema=z21.object({items:z21.array(ProjectScheduleRunDTOSchema),nextCursor:z21.string().nullable(),usage:ProjectScheduleUsageSchema,policy:ProjectSchedulePolicySchema}),ProjectScheduleRunsResponseSchema=createResponseSchema(ProjectScheduleRunsPageSchema),ProjectScheduleRunResponseSchema=createResponseSchema(ProjectScheduleRunDTOSchema),ProjectScheduleRunDetailResponseSchema=createResponseSchema(ProjectScheduleRunDetailDTOSchema)}});import{z as z22}from"zod";var AuditLogRowDTOSchema,AuditLogRowDTO,AuditLogListResponseSchema,AuditLogQuerySchema,init_audit_log_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/audit-log.dto.js"(){"use strict";init_audit_log();init_create_dto();init_response();AuditLogRowDTOSchema=z22.object({id:z22.uuid(),occurredAt:z22.coerce.date(),projectId:z22.uuid().nullable(),env:z22.string().nullable(),actor:z22.string().nullable(),actorKind:AuditActorKindSchema.nullable().optional(),action:AuditActionSchema,resource:z22.string().nullable().optional(),outcome:AuditOutcomeSchema,metadata:z22.unknown().optional(),ipAddress:z22.string().nullable().optional(),userAgent:z22.string().nullable().optional(),error:z22.string().nullable().optional()}),AuditLogRowDTO=createDTO(AuditLogRowDTOSchema),AuditLogListResponseSchema=createResponseSchema(z22.object({rows:z22.array(AuditLogRowDTOSchema),nextCursor:z22.string().nullable()})),AuditLogQuerySchema=z22.object({env:z22.string().optional(),action:AuditActionSchema.optional(),actor:z22.string().optional(),from:z22.coerce.date().optional(),to:z22.coerce.date().optional(),limit:z22.coerce.number().int().min(1).max(200).optional(),cursor:z22.string().optional()})}});import{z as z23}from"zod";var SurfaceNameSchema,SURFACE_NAMES,SurfaceDeltaVerbSchema,SurfaceItemOriginSchema,SurfaceDeltaItemSchema,PerSurfaceDeltaSchema,CrossSurfaceFindingSchema,StatusReportSchema,StatusReportDTO,StatusReportResponseSchema,DiffReportSchema,DiffReportDTO,DiffReportResponseSchema,CodeFileDiffSchema,CodeFileDiffDTO,CodeFileDiffResponseSchema,CodeConflictBlobSchema,CodeConflictDetailSchema,CodeConflictDetailDTO,CodeConflictDetailResponseSchema,ContentEntrySnapshotSchema,ContentRowDiffSchema,ContentRowDiffDTO,ContentRowDiffResponseSchema,SchemaTypeSnapshotSchema,SchemaTypeDiffSchema,SchemaTypeDiffDTO,SchemaTypeDiffResponseSchema,AssetSnapshotSchema,AssetDiffSchema,AssetDiffDTO,AssetDiffResponseSchema,TranslationRowDiffSchema,TranslationRowDiffDTO,TranslationRowDiffResponseSchema,FormSchemaSnapshotSchema,FormSchemaDiffSchema,FormSchemaDiffDTO,FormSchemaDiffResponseSchema,ActivationSnapshotSchema,ActivationDiffSchema,ActivationDiffDTO,ActivationDiffResponseSchema,CONFLICT_KINDS,ConflictKindSchema,ConflictSchema,FieldPickSchema,ConflictResolutionSchema,MergeResultSchema,MergeResultDTO,MergeResultResponseSchema,EngineStrategySchema,VendorStrategySchema,MergeStrategySchema,ResolvedStrategySchema,MergeRequestSchema,MergeInitiateResultSchema,MergeInitiateResultDTO,MergeInitiateResponseSchema,MergeConflictsHydrationSchema,MergeConflictsHydrationDTO,MergeConflictsHydrationResponseSchema,MergeResolveDraftRequestSchema,MergeResolveDraftResultSchema,MergeResolveDraftResultDTO,MergeResolveRequestSchema,MergeCancelRequestSchema,PublishReleaseRequestSchema,PublishReleaseResultSchema,PublishReleaseResultDTO,PublishReleaseResponseSchema,init_env_status_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-status.dto.js"(){"use strict";init_env();init_create_dto();init_response();SurfaceNameSchema=z23.enum(["code","schemas","content","translations","assets","forms","activations"]),SURFACE_NAMES=["code","schemas","content","translations","assets","forms","activations"],SurfaceDeltaVerbSchema=z23.enum(["added","removed","changed","conflict"]),SurfaceItemOriginSchema=z23.enum(["committed-ahead","local-uncommitted"]),SurfaceDeltaItemSchema=z23.object({verb:SurfaceDeltaVerbSchema,key:z23.string(),detail:z23.string().optional(),origin:SurfaceItemOriginSchema.optional(),meta:z23.record(z23.string(),z23.unknown()).optional()}),PerSurfaceDeltaSchema=z23.object({surface:SurfaceNameSchema,status:z23.enum(["ok","timed_out","failed","unchanged"]),durationMs:z23.number().int().nonnegative().optional(),changedCount:z23.number().int().nonnegative(),conflictCount:z23.number().int().nonnegative(),items:z23.array(SurfaceDeltaItemSchema).max(1e3).optional(),truncated:z23.boolean().optional(),error:z23.string().optional()}),CrossSurfaceFindingSchema=z23.object({id:z23.string(),kind:z23.string(),description:z23.string(),severity:z23.enum(["warning","error"]),source:z23.object({surface:SurfaceNameSchema,key:z23.string()}),target:z23.object({surface:SurfaceNameSchema,key:z23.string()}),actions:z23.array(z23.enum(["restore-target","fix-source","ignore"])).min(1)}),StatusReportSchema=z23.object({env:EnvSchema,vs:EnvSchema,syncState:z23.enum(["in-sync","ahead","behind","diverged","unknown"]),generatedAt:z23.coerce.date(),surfaces:z23.array(PerSurfaceDeltaSchema),agents:z23.array(z23.object({id:z23.string(),name:z23.string(),status:z23.enum(["active","paused","failed"]),lastRunAt:z23.coerce.date().nullable()})).optional(),crossSurface:z23.array(CrossSurfaceFindingSchema).optional()}),StatusReportDTO=createDTO(StatusReportSchema),StatusReportResponseSchema=createResponseSchema(StatusReportSchema),DiffReportSchema=z23.object({fromEnv:EnvSchema,toEnv:EnvSchema,generatedAt:z23.coerce.date(),surfaces:z23.array(PerSurfaceDeltaSchema),crossSurface:z23.array(CrossSurfaceFindingSchema).optional(),fingerprint:z23.string()}),DiffReportDTO=createDTO(DiffReportSchema),DiffReportResponseSchema=createResponseSchema(DiffReportSchema),CodeFileDiffSchema=z23.object({path:z23.string(),state:z23.enum(["added","modified","deleted","renamed","copied","type_changed","unmerged","unknown"]),raw:z23.string(),additions:z23.number().int().nonnegative(),deletions:z23.number().int().nonnegative()}),CodeFileDiffDTO=createDTO(CodeFileDiffSchema),CodeFileDiffResponseSchema=createResponseSchema(CodeFileDiffSchema),CodeConflictBlobSchema=z23.object({oid:z23.string().optional(),content:z23.string().optional(),truncated:z23.boolean(),binary:z23.boolean()}),CodeConflictDetailSchema=z23.object({path:z23.string(),base:CodeConflictBlobSchema,ours:CodeConflictBlobSchema,theirs:CodeConflictBlobSchema,result:CodeConflictBlobSchema,sourceTipSha:z23.string(),targetTipSha:z23.string(),mergeBaseSha:z23.string().optional()}),CodeConflictDetailDTO=createDTO(CodeConflictDetailSchema),CodeConflictDetailResponseSchema=createResponseSchema(CodeConflictDetailSchema),ContentEntrySnapshotSchema=z23.object({id:z23.string(),slug:z23.string(),contentType:z23.string(),data:z23.record(z23.string(),z23.unknown()),updatedAt:z23.coerce.date()}),ContentRowDiffSchema=z23.object({collection:z23.string(),rowId:z23.string(),parent:ContentEntrySnapshotSchema.nullable(),child:ContentEntrySnapshotSchema.nullable()}),ContentRowDiffDTO=createDTO(ContentRowDiffSchema),ContentRowDiffResponseSchema=createResponseSchema(ContentRowDiffSchema),SchemaTypeSnapshotSchema=z23.object({name:z23.string(),label:z23.string(),isSingleton:z23.boolean(),fields:z23.record(z23.string(),z23.unknown())}),SchemaTypeDiffSchema=z23.object({typeName:z23.string(),parent:SchemaTypeSnapshotSchema.nullable(),child:SchemaTypeSnapshotSchema.nullable()}),SchemaTypeDiffDTO=createDTO(SchemaTypeDiffSchema),SchemaTypeDiffResponseSchema=createResponseSchema(SchemaTypeDiffSchema),AssetSnapshotSchema=z23.object({id:z23.string(),name:z23.string(),type:z23.enum(["file","folder"]),mimeType:z23.string().nullable(),storageKey:z23.string().nullable(),url:z23.string().nullable(),fileSize:z23.number().nullable(),width:z23.number().nullable(),height:z23.number().nullable(),altText:z23.string().nullable(),caption:z23.string().nullable(),createdAt:z23.coerce.date(),updatedAt:z23.coerce.date()}),AssetDiffSchema=z23.object({assetId:z23.string(),parent:AssetSnapshotSchema.nullable(),child:AssetSnapshotSchema.nullable()}),AssetDiffDTO=createDTO(AssetDiffSchema),AssetDiffResponseSchema=createResponseSchema(AssetDiffSchema),TranslationRowDiffSchema=z23.object({locale:z23.string(),key:z23.string(),parent:z23.string().nullable(),child:z23.string().nullable()}),TranslationRowDiffDTO=createDTO(TranslationRowDiffSchema),TranslationRowDiffResponseSchema=createResponseSchema(TranslationRowDiffSchema),FormSchemaSnapshotSchema=z23.object({formName:z23.string(),label:z23.string().nullable(),schemaFingerprint:z23.string(),fields:z23.record(z23.string(),z23.unknown()),settings:z23.record(z23.string(),z23.unknown()).optional()}),FormSchemaDiffSchema=z23.object({formName:z23.string(),parent:FormSchemaSnapshotSchema.nullable(),child:FormSchemaSnapshotSchema.nullable()}),FormSchemaDiffDTO=createDTO(FormSchemaDiffSchema),FormSchemaDiffResponseSchema=createResponseSchema(FormSchemaDiffSchema),ActivationSnapshotSchema=z23.object({agentName:z23.string(),triggerIndex:z23.number().int().nonnegative(),triggerKind:z23.string(),triggerSpec:z23.record(z23.string(),z23.unknown()),enabled:z23.boolean(),emailRecipients:z23.array(z23.string()).nullable(),qstashScheduleId:z23.string().nullable()}),ActivationDiffSchema=z23.object({agentName:z23.string(),triggerIndex:z23.number().int().nonnegative(),parent:ActivationSnapshotSchema.nullable(),child:ActivationSnapshotSchema.nullable()}),ActivationDiffDTO=createDTO(ActivationDiffSchema),ActivationDiffResponseSchema=createResponseSchema(ActivationDiffSchema),CONFLICT_KINDS=["merge-conflict","requires-manual-strategy","cross-surface-integrity","unique-conflict"],ConflictKindSchema=z23.enum(CONFLICT_KINDS),ConflictSchema=z23.object({surface:SurfaceNameSchema,key:z23.string(),kind:ConflictKindSchema.optional(),description:z23.string(),parentValue:z23.unknown().optional(),childValue:z23.unknown().optional(),conflictingFields:z23.array(z23.string()).optional(),code:z23.object({path:z23.string(),unresolvable:z23.boolean().optional(),reason:z23.string().optional()}).optional()}),FieldPickSchema=z23.object({field:z23.string(),choice:z23.enum(["parent","child","pick","ai-pick"]),pickedValue:z23.unknown().optional(),aiSessionId:z23.string().optional()}),ConflictResolutionSchema=z23.object({surface:SurfaceNameSchema,key:z23.string(),choice:z23.enum(["parent","child","pick"]),pickedValue:z23.unknown().optional(),fieldPicks:z23.array(FieldPickSchema).optional()}),MergeResultSchema=z23.object({ok:z23.boolean(),mergeId:z23.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,applied:z23.array(z23.object({surface:SurfaceNameSchema,count:z23.number().int().nonnegative()})),conflicts:z23.array(ConflictSchema).optional(),summary:z23.string().optional()}),MergeResultDTO=createDTO(MergeResultSchema),MergeResultResponseSchema=createResponseSchema(MergeResultSchema),EngineStrategySchema=z23.enum(["ff-only","auto","theirs","ours","manual"]),VendorStrategySchema=z23.enum(["ff_only","ff_prefer","merge"]),MergeStrategySchema=z23.object({engine:EngineStrategySchema.optional(),vendor:VendorStrategySchema.optional(),squash:z23.boolean().optional()}),ResolvedStrategySchema=z23.object({engine:EngineStrategySchema,vendor:VendorStrategySchema,squash:z23.boolean()}),MergeRequestSchema=z23.object({from:EnvSchema,allowDirectMerge:z23.boolean().optional(),strategy:MergeStrategySchema.optional()}),MergeInitiateResultSchema=z23.object({mergeId:z23.string().uuid(),streamUrl:z23.string(),strategy:ResolvedStrategySchema,acceptedAt:z23.coerce.date()}),MergeInitiateResultDTO=createDTO(MergeInitiateResultSchema),MergeInitiateResponseSchema=createResponseSchema(MergeInitiateResultSchema),MergeConflictsHydrationSchema=z23.object({mergeId:z23.string().uuid(),fromEnv:EnvSchema,toEnv:EnvSchema,status:z23.enum(["in_progress","complete","failed","rolled_back","conflicts"]),strategy:ResolvedStrategySchema,conflicts:z23.array(ConflictSchema),draftResolutions:z23.array(ConflictResolutionSchema),lastEditedBy:z23.string().nullable(),lastEditedAt:z23.coerce.date().nullable(),initiator:z23.object({userId:z23.string().nullable(),role:z23.string().nullable(),agentName:z23.string().nullable()})}),MergeConflictsHydrationDTO=createDTO(MergeConflictsHydrationSchema),MergeConflictsHydrationResponseSchema=createResponseSchema(MergeConflictsHydrationSchema),MergeResolveDraftRequestSchema=z23.object({resolutions:z23.array(ConflictResolutionSchema)}),MergeResolveDraftResultSchema=z23.object({mergeId:z23.string().uuid(),draftResolutions:z23.array(ConflictResolutionSchema),lastEditedAt:z23.coerce.date(),lastEditedBy:z23.string()}),MergeResolveDraftResultDTO=createDTO(MergeResolveDraftResultSchema),MergeResolveRequestSchema=z23.object({mergeId:z23.string().uuid(),resolutions:z23.array(ConflictResolutionSchema)}),MergeCancelRequestSchema=z23.object({mergeId:z23.string().uuid()}),PublishReleaseRequestSchema=z23.object({version:z23.string().regex(/^v?\d+\.\d+\.\d+(-[\w.]+)?$/,"Use semver (v1.4.2 / 1.4.2 / 1.4.2-rc.1)"),notes:z23.string().max(2e4).optional()}),PublishReleaseResultSchema=z23.object({releaseTag:z23.string(),sha:z23.string(),publishedAt:z23.coerce.date()}),PublishReleaseResultDTO=createDTO(PublishReleaseResultSchema),PublishReleaseResponseSchema=createResponseSchema(PublishReleaseResultSchema)}});import{z as z24}from"zod";var DiffRefSchema,InlineSchema,SummaryBlockSchema,EnvDiffSummarySchema,EnvDiffSummaryResultSchema,EnvDiffSummaryResultDTO,EnvDiffSummaryResponseSchema,init_env_diff_summary_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/env-diff-summary.dto.js"(){"use strict";init_create_dto();init_response();init_env_status_dto();DiffRefSchema=z24.object({surface:SurfaceNameSchema,key:z24.string(),label:z24.string()}),InlineSchema=z24.object({text:z24.string(),ref:DiffRefSchema.optional()}),SummaryBlockSchema=z24.discriminatedUnion("type",[z24.object({type:z24.literal("paragraph"),content:z24.array(InlineSchema).max(24)}),z24.object({type:z24.literal("preview"),ref:DiffRefSchema,caption:z24.string().optional()}),z24.object({type:z24.literal("code"),code:z24.string(),lang:z24.string().optional(),caption:z24.string().optional()}),z24.object({type:z24.literal("risk"),level:z24.enum(["warning","error"]),content:z24.array(InlineSchema).max(24)}),z24.object({type:z24.literal("list"),items:z24.array(z24.array(InlineSchema).max(24)).max(8)})]),EnvDiffSummarySchema=z24.object({headline:z24.string(),blocks:z24.array(SummaryBlockSchema).max(15)}),EnvDiffSummaryResultSchema=z24.object({summary:EnvDiffSummarySchema,fingerprint:z24.string(),generatedAt:z24.coerce.date(),cached:z24.boolean().optional(),credits:z24.number().int().nonnegative().optional()}),EnvDiffSummaryResultDTO=createDTO(EnvDiffSummaryResultSchema),EnvDiffSummaryResponseSchema=createResponseSchema(EnvDiffSummaryResultSchema)}});import{z as z25}from"zod";var PROJECT_ANALYTICS_PRESETS,PROJECT_ANALYTICS_GROUP_BY_OPTIONS,ProjectDailyVisitorsDTOSchema,ProjectAnalyticsBreakdownItemDTOSchema,ProjectAnalyticsPageBreakdownItemDTOSchema,ProjectAnalyticsRangeDTOSchema,ProjectAnalyticsAnnotationDTOSchema,ProjectPageviewAnalyticsDTOSchema,ProjectPageviewAnalyticsDTO,ProjectAnalyticsAnnotationDTO,init_project_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-analytics.dto.js"(){"use strict";init_create_dto();PROJECT_ANALYTICS_PRESETS=["today","yesterday","this_week","this_month","last_7_days","last_30_days","last_90_days","last_week","last_month","last_quarter","last_year","custom"],PROJECT_ANALYTICS_GROUP_BY_OPTIONS=["day","week","month","quarter"],ProjectDailyVisitorsDTOSchema=z25.object({date:z25.string(),visitors:z25.number().int().nonnegative()}),ProjectAnalyticsBreakdownItemDTOSchema=z25.object({key:z25.string(),visitors:z25.number().int().nonnegative(),pageviews:z25.number().int().nonnegative()}),ProjectAnalyticsPageBreakdownItemDTOSchema=z25.object({path:z25.string(),pageName:z25.string().nullable().optional(),visitors:z25.number().int().nonnegative(),pageviews:z25.number().int().nonnegative()}),ProjectAnalyticsRangeDTOSchema=z25.object({preset:z25.enum(PROJECT_ANALYTICS_PRESETS),requestedFrom:z25.string(),requestedTo:z25.string(),effectiveFrom:z25.string(),effectiveTo:z25.string(),isRetentionLimited:z25.boolean(),groupBy:z25.enum(PROJECT_ANALYTICS_GROUP_BY_OPTIONS)}),ProjectAnalyticsAnnotationDTOSchema=z25.object({date:z25.string(),content:z25.string(),updatedAt:z25.string(),updatedByUserId:z25.string()}),ProjectPageviewAnalyticsDTOSchema=z25.object({range:ProjectAnalyticsRangeDTOSchema,visitors:z25.number().int().nonnegative(),pageviews:z25.number().int().nonnegative(),bounceRate:z25.number().min(0).max(100),viewsPerVisit:z25.number().nonnegative(),averageVisitDurationSeconds:z25.number().nonnegative(),visitorsSeries:z25.array(ProjectDailyVisitorsDTOSchema),topPages:z25.array(ProjectAnalyticsPageBreakdownItemDTOSchema),topBrowsers:z25.array(ProjectAnalyticsBreakdownItemDTOSchema),topDevices:z25.array(ProjectAnalyticsBreakdownItemDTOSchema),topCountries:z25.array(ProjectAnalyticsBreakdownItemDTOSchema),topSources:z25.array(ProjectAnalyticsBreakdownItemDTOSchema),annotations:z25.array(ProjectAnalyticsAnnotationDTOSchema)}),ProjectPageviewAnalyticsDTO=createDTO(ProjectPageviewAnalyticsDTOSchema),ProjectAnalyticsAnnotationDTO=createDTO(ProjectAnalyticsAnnotationDTOSchema)}});import{z as z26}from"zod";var ProjectInviteDTOSchema,ProjectInviteDTO,CreatedProjectInviteDTOSchema,CreatedProjectInviteDTO,AcceptedProjectInviteDTOSchema,AcceptedProjectInviteDTO,init_project_invite_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-invite.dto.js"(){"use strict";init_common();init_create_dto();ProjectInviteDTOSchema=z26.object({id:z26.string(),email:z26.email(),roleKey:ProjectRoleKeySchema,status:ProjectInviteStatusSchema,expiresAt:z26.coerce.date(),createdAt:z26.coerce.date(),inviterUserId:z26.string()}),ProjectInviteDTO=createDTO(ProjectInviteDTOSchema),CreatedProjectInviteDTOSchema=z26.object({id:z26.string(),token:z26.string()}),CreatedProjectInviteDTO=createDTO(CreatedProjectInviteDTOSchema),AcceptedProjectInviteDTOSchema=z26.object({success:z26.boolean(),projectId:z26.string().optional()}),AcceptedProjectInviteDTO=createDTO(AcceptedProjectInviteDTOSchema)}});import{z as z27}from"zod";var PublicUserDTOSchema,PublicUserDTO,ReferralCountCTOSchema,ReferralCountCTO,ReferralSummaryCTOSchema,ReferralSummaryCTO,AuthenticatedUserDTOSchema,AuthenticatedUserDTO,AuthenticatedUserResponseSchema,ReferralCountResponseSchema,ReferralSummaryResponseSchema,init_user_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/user.dto.js"(){"use strict";init_create_dto();init_response();PublicUserDTOSchema=z27.object({id:z27.string(),name:z27.string(),image:z27.string().nullable()}),PublicUserDTO=createDTO(PublicUserDTOSchema),ReferralCountCTOSchema=z27.object({count:z27.int()}),ReferralCountCTO=createDTO(ReferralCountCTOSchema),ReferralSummaryCTOSchema=z27.object({counts:z27.object({signed_up:z27.int(),activated:z27.int()}),credits:z27.object({total:z27.int()})}),ReferralSummaryCTO=createDTO(ReferralSummaryCTOSchema),AuthenticatedUserDTOSchema=PublicUserDTOSchema.extend({email:z27.email(),emailVerified:z27.boolean(),createdAt:z27.coerce.date(),updatedAt:z27.coerce.date()}),AuthenticatedUserDTO=createDTO(AuthenticatedUserDTOSchema),AuthenticatedUserResponseSchema=createResponseSchema(AuthenticatedUserDTOSchema),ReferralCountResponseSchema=createResponseSchema(ReferralCountCTOSchema),ReferralSummaryResponseSchema=createResponseSchema(ReferralSummaryCTOSchema)}});import{z as z28}from"zod";var ProjectAccessItemDTOSchema,ProjectAccessItemDTO,ProjectPermissionsDTOSchema,ProjectPermissionsDTO,ProjectAccessDTOSchema,ProjectAccessDTO,AccessMutationResponseSchema,InviteAcceptResponseSchema,init_project_access_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-access.dto.js"(){"use strict";init_common();init_create_dto();init_response();init_project_invite_dto();init_user_dto();ProjectAccessItemDTOSchema=z28.object({id:z28.string(),principalType:ProjectPrincipalTypeSchema,principalId:z28.string().nullable(),roleKey:ProjectRoleKeySchema,createdAt:z28.coerce.date(),expiresAt:z28.coerce.date().nullable(),user:PublicUserDTOSchema.nullable()}),ProjectAccessItemDTO=createDTO(ProjectAccessItemDTOSchema),ProjectPermissionsDTOSchema=z28.object({role:ProjectRoleKeyWithSystemSchema.nullable(),permissions:z28.record(z28.string(),z28.boolean())}),ProjectPermissionsDTO=createDTO(ProjectPermissionsDTOSchema),ProjectAccessDTOSchema=z28.object({access:z28.array(ProjectAccessItemDTOSchema),invites:z28.array(ProjectInviteDTOSchema),organization:z28.object({name:z28.string().nullable(),logo:z28.string().nullable()}).nullable()}),ProjectAccessDTO=createDTO(ProjectAccessDTOSchema),AccessMutationResponseSchema=createResponseSchema(z28.object({success:z28.boolean()})),InviteAcceptResponseSchema=createResponseSchema(z28.object({success:z28.boolean(),projectId:z28.uuid()}))}});import{z as z29}from"zod";var PublicationStateDTOSchema,PublicationStateDTO,init_publication_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/publication.dto.js"(){"use strict";init_common();init_create_dto();PublicationStateDTOSchema=z29.object({publicationStatus:PublicationStatusSchema,appUrl:z29.string().nullable(),lastPublishedAt:z29.string().nullable()}),PublicationStateDTO=createDTO(PublicationStateDTOSchema)}});import{z as z30}from"zod";var SandboxSessionDTOSchema,SandboxSessionDTO,SandboxSessionResponseSchema,init_sandbox_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/sandbox.dto.js"(){"use strict";init_create_dto();init_response();SandboxSessionDTOSchema=z30.object({url:z30.url(),expiresAt:z30.iso.datetime()}),SandboxSessionDTO=createDTO(SandboxSessionDTOSchema),SandboxSessionResponseSchema=createResponseSchema(SandboxSessionDTOSchema)}});import{z as z31}from"zod";var OrganizationDTOSchema,OrganizationDTO,MemberUserDTOSchema,OrganizationMemberDTOSchema,OrganizationMemberDTO,init_organization_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/organization.dto.js"(){"use strict";init_common();init_create_dto();OrganizationDTOSchema=BaseEntitySchema.extend({name:z31.string(),slug:z31.string().nullable(),logo:z31.string().nullable(),metadata:z31.record(z31.string(),z31.unknown()).nullable()}),OrganizationDTO=createDTO(OrganizationDTOSchema),MemberUserDTOSchema=z31.object({id:z31.string(),name:z31.string(),email:z31.email(),image:z31.string().nullable()}),OrganizationMemberDTOSchema=z31.object({id:z31.string(),userId:z31.string(),organizationId:z31.string(),role:OrganizationRoleSchema,user:MemberUserDTOSchema,createdAt:z31.coerce.date()}),OrganizationMemberDTO=createDTO(OrganizationMemberDTOSchema)}});import{z as z32}from"zod";var CancellationReasonCodeSchema,CancellationFeedbackDTOSchema,CancellationFeedbackDTO,AiCreditsEntitlementSchema,EntitlementsDTOSchema,SubscriptionDTOSchema,SubscriptionDTO,DailyCreditsStatusSchema,CreditBalanceDTOSchema,CreditBalanceDTO,MinimalCreditBalanceDTOSchema,MinimalCreditBalanceDTO,ProjectCreditBucketsDTOSchema,ProjectDailyCreditAllowanceDTOSchema,ProjectCreditBalanceDTOSchema,ProjectCreditBalanceDTO,SuccessfulPurchaseDTOSchema,SuccessfulPurchaseDTO,PortalDTOSchema,PortalDTO,CreditBalanceResponseSchema,MinimalCreditBalanceResponseSchema,ProjectCreditBalanceResponseSchema,SuccessfulPurchaseResponseSchema,SubscriptionResponseSchema,EntitlementsResponseSchema,PortalResponseSchema,init_billing_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/billing.dto.js"(){"use strict";init_common();init_create_dto();init_response();CancellationReasonCodeSchema=z32.enum(["just_testing","too_expensive","not_using_enough","missing_features","bug_or_technical_issue","switching_to_another_tool","closing_or_pausing_business","other"]),CancellationFeedbackDTOSchema=z32.object({reason:CancellationReasonCodeSchema,details:z32.string().trim().max(1e3).nullable().optional().transform(value=>value||null)}).superRefine((value,ctx)=>{value.reason==="other"&&!value.details&&ctx.addIssue({code:z32.ZodIssueCode.custom,message:"Details are required when selecting other.",path:["details"]})}),CancellationFeedbackDTO=createDTO(CancellationFeedbackDTOSchema),AiCreditsEntitlementSchema=z32.object({included:z32.number().optional(),unitPrice:z32.number().optional(),dailyCap:z32.number().nullable().optional()}),EntitlementsDTOSchema=z32.object({ai_credits:AiCreditsEntitlementSchema.optional(),analytics:z32.object({retentionDays:z32.number().int().positive(),canUseExtendedDateRanges:z32.boolean()}).optional(),history:z32.object({retentionDays:z32.number().int().positive()}).optional(),members:z32.object({canInvite:z32.boolean(),maxMembers:z32.number().int().positive().nullable()}).optional(),projects:z32.object({canCreatePrivateProjects:z32.boolean(),maxPrivateProjects:z32.number().int().positive().nullable()}).optional(),domains:z32.object({canUseCustomDomains:z32.boolean(),maxDomains:z32.number().int().nonnegative().nullable()}).optional()}),SubscriptionDTOSchema=z32.object({id:z32.string(),external_id:z32.string(),customerId:z32.string(),planId:z32.string(),planCode:TemplateCodeSchema,currentPeriod:z32.object({start:z32.string(),end:z32.string().nullable()}),cancelAt:z32.string().nullable(),entitlements:EntitlementsDTOSchema,currency:z32.string(),nextPaymentAt:z32.string().nullable(),baseAmount:z32.number()}),SubscriptionDTO=createDTO(SubscriptionDTOSchema),DailyCreditsStatusSchema=z32.object({totalCap:z32.number(),dailyCap:z32.number(),usedTotal:z32.number()}),CreditBalanceDTOSchema=z32.object({total:z32.number(),base:z32.number(),dailyBase:z32.number(),purchases:z32.number(),awards:z32.number(),daily:DailyCreditsStatusSchema.optional()}),CreditBalanceDTO=createDTO(CreditBalanceDTOSchema),MinimalCreditBalanceDTOSchema=z32.object({total:z32.number(),nearLimit:z32.boolean(),canChat:z32.boolean(),daily:DailyCreditsStatusSchema.optional()}),MinimalCreditBalanceDTO=createDTO(MinimalCreditBalanceDTOSchema),ProjectCreditBucketsDTOSchema=z32.object({dailyFreeAvailable:z32.number(),monthlyAvailable:z32.number(),purchasedAvailable:z32.number(),awardedAvailable:z32.number()}),ProjectDailyCreditAllowanceDTOSchema=z32.object({periodCap:z32.number(),dailyGrant:z32.number(),usedThisPeriod:z32.number(),remainingThisPeriod:z32.number()}),ProjectCreditBalanceDTOSchema=z32.object({projectId:z32.uuid(),organizationId:z32.string(),balance:z32.object({totalAvailable:z32.number(),nearLimit:z32.boolean(),canUseAi:z32.boolean(),buckets:ProjectCreditBucketsDTOSchema}),allowances:z32.object({dailyCredits:ProjectDailyCreditAllowanceDTOSchema.nullable()})}),ProjectCreditBalanceDTO=createDTO(ProjectCreditBalanceDTOSchema),SuccessfulPurchaseDTOSchema=z32.object({invoiceId:z32.string(),newBalance:z32.int(),creditCount:z32.int(),amountUsd:z32.number()}),SuccessfulPurchaseDTO=createDTO(SuccessfulPurchaseDTOSchema),PortalDTOSchema=z32.object({url:z32.string()}),PortalDTO=createDTO(PortalDTOSchema),CreditBalanceResponseSchema=createResponseSchema(CreditBalanceDTOSchema),MinimalCreditBalanceResponseSchema=createResponseSchema(MinimalCreditBalanceDTOSchema),ProjectCreditBalanceResponseSchema=createResponseSchema(ProjectCreditBalanceDTOSchema),SuccessfulPurchaseResponseSchema=createResponseSchema(SuccessfulPurchaseDTOSchema),SubscriptionResponseSchema=createResponseSchema(SubscriptionDTOSchema),EntitlementsResponseSchema=createResponseSchema(EntitlementsDTOSchema),PortalResponseSchema=createResponseSchema(PortalDTOSchema)}});import{z as z33}from"zod";var PaymentMethodDTOSchema,PaymentMethodDTO,init_payment_method_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/payment-method.dto.js"(){"use strict";init_create_dto();PaymentMethodDTOSchema=z33.object({brand:z33.string(),last4:z33.string(),exp:z33.string(),isDefault:z33.boolean()}),PaymentMethodDTO=createDTO(PaymentMethodDTOSchema)}});import{z as z34}from"zod";var FieldDefinitionSchema,SchemaFieldPathSchema,SchemaMigrationOperationSchema,ContentTypeI18nSchema,ContentTypeDTOSchema,ContentTypeDTO,SchemaDTOSchema,SchemaDTO,EntryDTOSchema,EntryDTO,PaginatedEntriesDTOSchema,PaginatedEntriesDTO,EntryCountDTOSchema,EntryCountDTO,EntryCountsDTOSchema,EntryCountsDTO,EntryTranslationGapDTOSchema,EntryTranslationGapDTO,EntryTranslationGapResponseSchema,ContentTypeResponseSchema,ContentTypeListResponseSchema,SchemaResponseSchema,EntryResponseSchema,EntryListResponseSchema,MAX_BULK_ENTRIES,entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema,EntryWhereSchema,EntryMutationBodySchema,entryIdsSchema,EntrySqlQueryRequestSchema,BulkCreateEntriesRequestSchema,BulkUpdateEntriesRequestSchema,BulkDeleteEntriesRequestSchema,EntrySqlQueryResponseSchema,EntrySqlQueryResponseDTO,BulkCreateEntriesResponseSchema,BulkCreateEntriesResponseDTO,BulkUpdateEntriesResponseSchema,BulkUpdateEntriesResponseDTO,BulkDeleteEntriesResponseSchema,BulkDeleteEntriesResponseDTO,init_content_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/content.dto.js"(){"use strict";init_common();init_content_fields();init_create_dto();init_response();FieldDefinitionSchema=ContentFieldDefinitionSchema,SchemaFieldPathSchema=z34.string().superRefine((path47,ctx)=>{let segments=path47.split(".");(segments.length===0||segments.some(segment=>!CONTENT_FIELD_NAME_PATTERN.test(segment)))&&ctx.addIssue({code:"custom",message:"Field paths must use dot-separated field or block variant names."})}),SchemaMigrationOperationSchema=z34.object({type:z34.literal("renameField"),contentType:z34.string().regex(CONTENT_TYPE_NAME_PATTERN),from:SchemaFieldPathSchema,to:SchemaFieldPathSchema}).strict(),ContentTypeI18nSchema=z34.object({enabled:z34.boolean()}).strict(),ContentTypeDTOSchema=z34.object({id:z34.string(),name:z34.string(),label:z34.string(),isSingleton:z34.boolean(),i18n:ContentTypeI18nSchema,fields:z34.record(z34.string(),FieldDefinitionSchema),createdAt:z34.string(),updatedAt:z34.string()}),ContentTypeDTO=createDTO(ContentTypeDTOSchema),SchemaDTOSchema=z34.object({contentTypes:z34.array(ContentTypeDTOSchema)}),SchemaDTO=createDTO(SchemaDTOSchema),EntryDTOSchema=z34.object({id:z34.string(),entryId:z34.string(),documentId:z34.string(),slug:z34.string(),locale:z34.string().optional(),createdAt:z34.string(),updatedAt:z34.string(),__fimo:z34.object({contentType:z34.string()})}).passthrough(),EntryDTO=createDTO(EntryDTOSchema),PaginatedEntriesDTOSchema=z34.object({data:z34.array(EntryDTOSchema),meta:z34.object({limit:z34.number(),offset:z34.number(),total:z34.number(),hasMore:z34.boolean()})}),PaginatedEntriesDTO=createDTO(PaginatedEntriesDTOSchema),EntryCountDTOSchema=z34.object({contentType:z34.string(),count:z34.number()}),EntryCountDTO=createDTO(EntryCountDTOSchema),EntryCountsDTOSchema=z34.object({counts:z34.array(EntryCountDTOSchema)}),EntryCountsDTO=createDTO(EntryCountsDTOSchema),EntryTranslationGapDTOSchema=z34.object({count:z34.number().int().nonnegative(),sourceLocale:z34.string(),targetLocale:z34.string()}),EntryTranslationGapDTO=createDTO(EntryTranslationGapDTOSchema),EntryTranslationGapResponseSchema=createResponseSchema(EntryTranslationGapDTOSchema),ContentTypeResponseSchema=createResponseSchema(ContentTypeDTOSchema),ContentTypeListResponseSchema=createResponseSchema(z34.array(ContentTypeDTOSchema)),SchemaResponseSchema=createResponseSchema(SchemaDTOSchema),EntryResponseSchema=createResponseSchema(EntryDTOSchema),EntryListResponseSchema=createResponseSchema(z34.array(EntryDTOSchema)),MAX_BULK_ENTRIES=1e3,entryWhereScalarSchema=z34.union([z34.string(),z34.number(),z34.boolean(),z34.null()]),entryWhereOperatorSchema=z34.object({$eq:entryWhereScalarSchema.optional(),$ne:entryWhereScalarSchema.optional(),$gt:entryWhereScalarSchema.optional(),$gte:entryWhereScalarSchema.optional(),$lt:entryWhereScalarSchema.optional(),$lte:entryWhereScalarSchema.optional(),$in:z34.array(entryWhereScalarSchema).optional(),$nin:z34.array(entryWhereScalarSchema).optional(),$contains:z34.string().optional(),$startsWith:z34.string().optional(),$null:z34.boolean().optional()}).strict().refine(value=>Object.keys(value).length>0,{message:"Operator object cannot be empty"}),nestedEntryWhereSchema=z34.record(z34.string(),z34.union([entryWhereScalarSchema,entryWhereOperatorSchema])),EntryWhereSchema=z34.record(z34.string(),z34.union([entryWhereScalarSchema,entryWhereOperatorSchema,nestedEntryWhereSchema])),EntryMutationBodySchema=z34.object({data:z34.record(z34.string(),z34.unknown()),locale:z34.string().min(1).optional(),documentId:z34.uuid().optional()}),entryIdsSchema=z34.array(z34.uuid()).min(1).max(MAX_BULK_ENTRIES),EntrySqlQueryRequestSchema=z34.object({sql:z34.string().min(1)}),BulkCreateEntriesRequestSchema=z34.object({entries:z34.array(EntryMutationBodySchema).min(1).max(MAX_BULK_ENTRIES)}),BulkUpdateEntriesRequestSchema=z34.union([z34.object({ids:entryIdsSchema,body:EntryMutationBodySchema}),z34.object({where:EntryWhereSchema,body:EntryMutationBodySchema}),z34.object({updates:z34.array(z34.object({id:z34.uuid(),body:EntryMutationBodySchema})).min(1).max(MAX_BULK_ENTRIES)})]),BulkDeleteEntriesRequestSchema=z34.union([z34.object({ids:entryIdsSchema,locale:z34.string().min(1).optional()}),z34.object({where:EntryWhereSchema,locale:z34.string().min(1).optional()})]),EntrySqlQueryResponseSchema=z34.object({data:z34.array(z34.record(z34.string(),z34.unknown())),meta:z34.object({rowCount:z34.number().int().nonnegative(),truncated:z34.boolean()})}),EntrySqlQueryResponseDTO=createDTO(EntrySqlQueryResponseSchema),BulkCreateEntriesResponseSchema=z34.object({data:z34.array(EntryDTOSchema),meta:z34.object({created:z34.number().int().nonnegative()})}),BulkCreateEntriesResponseDTO=createDTO(BulkCreateEntriesResponseSchema),BulkUpdateEntriesResponseSchema=z34.object({data:z34.array(EntryDTOSchema),meta:z34.object({updated:z34.number().int().nonnegative(),missing:z34.array(z34.string())})}),BulkUpdateEntriesResponseDTO=createDTO(BulkUpdateEntriesResponseSchema),BulkDeleteEntriesResponseSchema=z34.object({data:z34.array(EntryDTOSchema),meta:z34.object({deleted:z34.number().int().nonnegative(),missing:z34.array(z34.string())})}),BulkDeleteEntriesResponseDTO=createDTO(BulkDeleteEntriesResponseSchema)}});import{z as z35}from"zod";var UniqueConflictSchema,UniqueConflictErrorSchema,init_unique_conflict_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/unique-conflict.dto.js"(){"use strict";UniqueConflictSchema=z35.object({index:z35.number().int().nonnegative(),contentType:z35.string(),field:z35.string(),value:z35.string(),against:z35.enum(["stored","batch"]),ownerDocumentId:z35.uuid().optional(),ownerIndex:z35.number().int().nonnegative().optional()}),UniqueConflictErrorSchema=z35.object({code:z35.literal("unique_conflict"),message:z35.string(),conflicts:z35.array(UniqueConflictSchema),truncated:z35.boolean().optional()})}});import{z as z36}from"zod";var UniqueConflictIssueSchema,SchemaTransitionIssueSchema,SchemaTransitionRejectedErrorSchema,init_schema_transition_rejected_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/schema-transition-rejected.dto.js"(){"use strict";UniqueConflictIssueSchema=z36.object({kind:z36.literal("unique_conflict"),contentType:z36.string(),field:z36.string(),value:z36.string(),documentCount:z36.number().int().positive(),documentIds:z36.array(z36.uuid()),documentIdsTruncated:z36.boolean().optional()}),SchemaTransitionIssueSchema=UniqueConflictIssueSchema,SchemaTransitionRejectedErrorSchema=z36.object({code:z36.literal("schema_transition_rejected"),message:z36.string(),issues:z36.array(SchemaTransitionIssueSchema),truncated:z36.boolean().optional()})}});import{z as z37}from"zod";var CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH,CmsContentTypeNameSchema,CmsFieldNameSchema,CmsCollectionOrderSchema,CmsFieldOrderSchema,CmsListSortSchema,CmsDisplayDefaultsDTOSchema,CmsDisplayDefaultsDTO,CmsCollectionOrderRequestSchema,CmsFieldOrderRequestSchema,CmsDisplayDefaultsResponseSchema,init_cms_display_defaults_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/cms-display-defaults.dto.js"(){"use strict";init_common();init_create_dto();init_response();CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS=200,CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH=255,CmsContentTypeNameSchema=z37.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_TYPE_NAME_PATTERN),CmsFieldNameSchema=z37.string().max(CMS_DISPLAY_DEFAULTS_MAX_IDENTIFIER_LENGTH).regex(CONTENT_FIELD_NAME_PATTERN),CmsCollectionOrderSchema=z37.array(CmsContentTypeNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsFieldOrderSchema=z37.array(CmsFieldNameSchema).max(CMS_DISPLAY_DEFAULTS_MAX_ORDER_ITEMS),CmsListSortSchema=z37.object({field:CmsFieldNameSchema,direction:z37.enum(["asc","desc"])}),CmsDisplayDefaultsDTOSchema=z37.object({collectionOrder:CmsCollectionOrderSchema.nullable(),fieldOrders:z37.record(CmsContentTypeNameSchema,CmsFieldOrderSchema),listSorts:z37.record(CmsContentTypeNameSchema,CmsListSortSchema)}),CmsDisplayDefaultsDTO=createDTO(CmsDisplayDefaultsDTOSchema),CmsCollectionOrderRequestSchema=z37.object({order:CmsCollectionOrderSchema}),CmsFieldOrderRequestSchema=z37.object({order:CmsFieldOrderSchema}),CmsDisplayDefaultsResponseSchema=createResponseSchema(CmsDisplayDefaultsDTOSchema)}});import{z as z38}from"zod";var AssetPathItemSchema,AssetDTOSchema,AssetDTO,AssetTreeNodeDTOSchema,AssetTreeNodeDTO,AssetResponseSchema,AssetListResponseSchema,init_asset_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset.dto.js"(){"use strict";init_common();init_create_dto();init_response();AssetPathItemSchema=z38.object({id:z38.string(),name:z38.string()}),AssetDTOSchema=z38.object({id:z38.string(),name:z38.string(),type:AssetTypeSchema,originalFileName:z38.string().nullable(),parentId:z38.string().nullable(),mimeType:z38.string().nullable(),fileSize:z38.number().nullable(),url:z38.string().nullable(),storageKey:z38.string().nullable(),createdAt:z38.string(),updatedAt:z38.string(),altText:z38.string().nullable().optional(),caption:z38.string().nullable().optional(),aiCaption:z38.string().nullable().optional(),aiAltText:z38.string().nullable().optional(),aiTags:z38.array(z38.string()).nullable().optional(),aiPrimaryColor:z38.string().nullable().optional(),aiProcessingStatus:z38.string().nullable().optional(),width:z38.number().nullable().optional(),height:z38.number().nullable().optional(),path:z38.array(AssetPathItemSchema).optional(),hasChildren:z38.boolean().optional()}),AssetDTO=createDTO(AssetDTOSchema),AssetTreeNodeDTOSchema=AssetDTOSchema.extend({children:z38.lazy(()=>z38.array(AssetTreeNodeDTOSchema)).optional()}),AssetTreeNodeDTO=createDTO(AssetTreeNodeDTOSchema),AssetResponseSchema=createResponseSchema(AssetDTOSchema),AssetListResponseSchema=createResponseSchema(z38.array(AssetDTOSchema))}});import{z as z39}from"zod";var TranslationDTOSchema,TranslationDTO,init_translation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/translation.dto.js"(){"use strict";init_create_dto();TranslationDTOSchema=z39.object({key:z39.string(),value:z39.string().optional(),defaultValue:z39.string(),locale:z39.string()}),TranslationDTO=createDTO(TranslationDTOSchema)}});import{z as z40}from"zod";var DocumentNodeDTOSchema,DocumentTreeDTOSchema,DocumentPathDTOSchema,DocumentPathDTO,DocumentTreeResponseSchema,DocumentPathResponseSchema,init_document_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/document.dto.js"(){"use strict";init_create_dto();init_response();DocumentNodeDTOSchema=z40.object({id:z40.string(),name:z40.string(),type:z40.enum(["file","folder"]),path:z40.string(),children:z40.lazy(()=>z40.array(DocumentNodeDTOSchema)).optional()}),DocumentTreeDTOSchema=z40.array(DocumentNodeDTOSchema),DocumentPathDTOSchema=z40.object({path:z40.string(),exists:z40.boolean(),type:z40.enum(["file","folder"]).optional()}),DocumentPathDTO=createDTO(DocumentPathDTOSchema),DocumentTreeResponseSchema=createResponseSchema(DocumentTreeDTOSchema),DocumentPathResponseSchema=createResponseSchema(DocumentPathDTOSchema)}});import{z as z41}from"zod";var ChatMessageListDTOSchema,ChatMessagesPageDTOSchema,ChatLiveTurnDTOSchema,ChatThreadMessageDTOSchema,ChatAttentionDTOSchema,ChatThreadMessagesPageDTOSchema,ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema,ChatNonStreamingOutcomeDTOSchema,ChatDeletionDTOSchema,ChatDeletionDTO,ChatMessageListResponseSchema,ChatMessagesPageResponseSchema,ChatDeletionResponseSchema,ChatClearErrorDTOSchema,init_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/chat.dto.js"(){"use strict";init_create_dto();init_response();init_project_dto();ChatMessageListDTOSchema=z41.array(ProjectMessageDTOSchema),ChatMessagesPageDTOSchema=z41.object({items:z41.array(ProjectMessagePublicDTOSchema),nextCursor:z41.string().nullable()}),ChatLiveTurnDTOSchema=z41.object({invocationId:z41.string(),step:z41.enum(["preparing","working","merging"]),startedAt:z41.string()}),ChatThreadMessageDTOSchema=z41.object({id:z41.string(),role:z41.enum(["user","assistant"]),parts:z41.array(z41.unknown()),metadata:z41.record(z41.string(),z41.unknown()).nullable(),createdAt:z41.date().transform(value=>value.toISOString()),providerMessageId:z41.string().nullable().optional(),invocationId:z41.string().nullable().optional(),invocationStatus:z41.string().nullable().optional(),invocationTerminalReason:z41.string().nullable().optional()}),ChatAttentionDTOSchema=z41.object({type:z41.literal("merge_conflict"),merge:z41.object({mergeId:z41.string().uuid(),projectId:z41.string(),fromEnv:z41.string(),toEnv:z41.string()}),publishAfterMerge:z41.boolean()}),ChatThreadMessagesPageDTOSchema=z41.object({threadId:z41.string().nullable(),title:z41.string().nullable(),messages:z41.array(ChatThreadMessageDTOSchema),nextCursor:z41.string().nullable(),liveTurn:ChatLiveTurnDTOSchema.nullable().optional(),attention:ChatAttentionDTOSchema.nullable().optional()}),ChatReplayOutcomeDTOSchema=z41.object({kind:z41.literal("replay"),threadId:z41.string(),userMessageId:z41.string()}),ChatQueuedOutcomeDTOSchema=z41.object({kind:z41.literal("queued"),threadId:z41.string(),userMessageId:z41.string(),blockingRootId:z41.string()}),ChatBusyOutcomeDTOSchema=z41.object({kind:z41.literal("busy"),threadId:z41.string(),userMessageId:z41.string(),blockingRootId:z41.string().optional()}),ChatRefusedOutcomeDTOSchema=z41.object({kind:z41.literal("refused"),threadId:z41.string(),userMessageId:z41.string(),refusedInvocationId:z41.string(),terminalReason:z41.string()}),ChatNonStreamingOutcomeDTOSchema=z41.discriminatedUnion("kind",[ChatReplayOutcomeDTOSchema,ChatQueuedOutcomeDTOSchema,ChatBusyOutcomeDTOSchema,ChatRefusedOutcomeDTOSchema]),ChatDeletionDTOSchema=z41.object({success:z41.boolean(),deletedCount:z41.number()}),ChatDeletionDTO=createDTO(ChatDeletionDTOSchema),ChatMessageListResponseSchema=createResponseSchema(ChatMessageListDTOSchema),ChatMessagesPageResponseSchema=createResponseSchema(ChatMessagesPageDTOSchema),ChatDeletionResponseSchema=createResponseSchema(ChatDeletionDTOSchema),ChatClearErrorDTOSchema=z41.object({code:z41.enum(["retained_conflict_busy","retained_conflict_cleanup_failed"]),message:z41.string()})}});import{z as z42}from"zod";var UploadResultDTOSchema,UploadResultDTO,UploadResultResponseSchema,init_upload_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/upload.dto.js"(){"use strict";init_common();init_create_dto();init_response();UploadResultDTOSchema=z42.object({url:z42.string().url(),key:z42.string(),size:z42.number(),contentType:z42.string(),uploadedAt:CommonSchemas.timestamp}),UploadResultDTO=createDTO(UploadResultDTOSchema),UploadResultResponseSchema=createResponseSchema(UploadResultDTOSchema)}});import{z as z43}from"zod";var ServicePermissionsDTOSchema,ServicePermissionsDTO,ServicePermissionsResponseSchema,init_service_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/service.dto.js"(){"use strict";init_create_dto();init_response();ServicePermissionsDTOSchema=z43.object({canAccess:z43.boolean(),permissions:z43.record(z43.string(),z43.boolean()),role:z43.string().nullable()}),ServicePermissionsDTO=createDTO(ServicePermissionsDTOSchema),ServicePermissionsResponseSchema=createResponseSchema(ServicePermissionsDTOSchema)}});import{z as z44}from"zod";var OrganizationProjectsSearchQuerySchema,init_search_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/search.dto.js"(){"use strict";init_pagination();OrganizationProjectsSearchQuerySchema=PaginationQuerySchema.extend({q:z44.string().trim().default(""),sort:z44.enum(["recent","name","relevance"]).default("recent"),category:z44.string().optional(),visibility:z44.enum(["public","private"]).optional()})}});import{z as z45}from"zod";var DomainStatusSchema,DomainSourceSchema,PaymentStatusSchema,DomainDTOSchema,DomainDTO,DomainSearchResultDTOSchema,DomainSearchResultDTO,DomainPricingDTOSchema,DomainPricingDTO,DomainContactSchema,DomainContactDTO,UpdateDomainContactsRequestSchema,SearchDomainsRequestSchema,CheckAvailabilityRequestSchema,DOMAIN_NAME_REGEX,DomainNameSchema,PurchaseDomainRequestSchema,UpdateDomainSettingsRequestSchema,RenewDomainRequestSchema,DomainResponseSchema,DomainListResponseSchema,DomainSearchResultListResponseSchema,DomainPricingResponseSchema,DomainContactResponseSchema,ContactVerificationStatusSchema,ContactVerificationStatusResponseSchema,init_registered_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/registered-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();DomainStatusSchema=z45.enum(["pending_payment","registering","owned","registration_failed","payment_failed","expiring","expired"]),DomainSourceSchema=z45.enum(["fimo","external"]),PaymentStatusSchema=z45.enum(["pending","paid","failed","refunded"]),DomainDTOSchema=z45.object({id:z45.string().uuid(),domain:z45.string(),status:DomainStatusSchema,source:DomainSourceSchema,registrationDate:CommonSchemas.timestamp.nullable(),expirationDate:CommonSchemas.timestamp.nullable(),autoRenew:z45.boolean(),price:z45.number().int().nullable(),renewalPrice:z45.number().int().nullable(),paymentStatus:PaymentStatusSchema.nullable(),checkoutUrl:z45.string().nullable(),failureReason:z45.string().nullable(),createdAt:CommonSchemas.timestamp,updatedAt:CommonSchemas.timestamp}),DomainDTO=createDTO(DomainDTOSchema),DomainSearchResultDTOSchema=z45.object({domain:z45.string(),available:z45.boolean(),premium:z45.boolean(),price:z45.number().nullable(),renewalPrice:z45.number().nullable(),purchaseType:z45.string().nullable()}),DomainSearchResultDTO=createDTO(DomainSearchResultDTOSchema),DomainPricingDTOSchema=z45.object({domain:z45.string(),price:z45.number().nullable(),renewalPrice:z45.number().nullable(),premium:z45.boolean(),allowedYears:z45.array(z45.number().int().positive())}),DomainPricingDTO=createDTO(DomainPricingDTOSchema),DomainContactSchema=z45.object({firstName:z45.string().max(100),lastName:z45.string().max(100),companyName:z45.string().max(100).optional(),address1:z45.string().max(255),address2:z45.string().max(255).optional(),city:z45.string().max(100),state:z45.string().max(100),zip:z45.string().max(20),country:z45.string().max(2),phone:z45.string().max(30),email:z45.union([z45.string().email().max(255),z45.literal("")])}),DomainContactDTO=createDTO(DomainContactSchema),UpdateDomainContactsRequestSchema=z45.object({firstName:z45.string().min(1).max(100),lastName:z45.string().min(1).max(100),companyName:z45.string().max(100).optional(),address1:z45.string().min(1).max(255),address2:z45.string().max(255).optional(),city:z45.string().min(1).max(100),state:z45.string().min(1).max(100),zip:z45.string().min(1).max(20),country:z45.string().min(1).max(2),phone:z45.string().min(1).max(30),email:z45.string().email().max(255)}),SearchDomainsRequestSchema=z45.object({keyword:z45.string().min(1).max(100),tldFilter:z45.array(z45.string()).optional()}),CheckAvailabilityRequestSchema=z45.object({domains:z45.array(z45.string()).min(1).max(50)}),DOMAIN_NAME_REGEX=/^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,DomainNameSchema=z45.string().min(1).max(255).regex(DOMAIN_NAME_REGEX,{message:"Invalid domain name"}),PurchaseDomainRequestSchema=z45.object({domain:DomainNameSchema,years:z45.number().int().min(1).max(10).optional().default(3),autoRenew:z45.boolean().optional().default(!0)}),UpdateDomainSettingsRequestSchema=z45.object({autoRenew:z45.boolean().optional()}),RenewDomainRequestSchema=z45.object({years:z45.number().int().min(1).max(10).optional().default(1),autoRenew:z45.boolean().optional().default(!0)}),DomainResponseSchema=createResponseSchema(DomainDTOSchema),DomainListResponseSchema=createResponseSchema(z45.array(DomainDTOSchema)),DomainSearchResultListResponseSchema=createResponseSchema(z45.array(DomainSearchResultDTOSchema)),DomainPricingResponseSchema=createResponseSchema(DomainPricingDTOSchema),DomainContactResponseSchema=createResponseSchema(DomainContactSchema.nullable()),ContactVerificationStatusSchema=z45.object({verified:z45.boolean(),email:z45.string().nullable(),verifyBy:z45.string().nullable()}),ContactVerificationStatusResponseSchema=createResponseSchema(ContactVerificationStatusSchema)}});import{z as z46}from"zod";var ProjectDomainStatusSchema,SSLStatusSchema,SSLValidationRecordSchema,SSLValidationErrorSchema,OwnershipVerificationSchema,ProjectDomainSSLDTOSchema,DomainProviderSchema,DomainTypeSchema,RedirectConfigSchema,ProjectDomainDTOSchema,ProjectDomainDTO,ProjectDomainListResponseSchema,ProjectDomainResponseSchema,AddProjectDomainRequestSchema,CheckProjectDomainHostnameReasonSchema,CheckProjectDomainHostnameResponseSchema,DeleteProjectDomainResponseSchema,init_project_domain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-domain.dto.js"(){"use strict";init_common();init_create_dto();init_response();ProjectDomainStatusSchema=z46.enum(["pending","active","pending_validation","active_redeploying","moved","deleted","pending_deletion","pending_migration","pending_provisioned","test_pending","test_active","test_active_apex","test_blocked","test_failed","provisioned","blocked"]),SSLStatusSchema=z46.enum(["initializing","pending_validation","pending_issuance","pending_deployment","pending_expiration","expired","active","deleted","pending_cleanup","staging_deployment","staging_active","deactivating","inactive","backup_issued","holding_deployment"]),SSLValidationRecordSchema=z46.object({txtName:z46.string().nullable().optional(),txtValue:z46.string().nullable().optional(),httpUrl:z46.string().nullable().optional(),httpBody:z46.string().nullable().optional(),cname:z46.string().nullable().optional(),cnameTarget:z46.string().nullable().optional()}),SSLValidationErrorSchema=z46.object({message:z46.string()}),OwnershipVerificationSchema=z46.object({type:z46.string(),name:z46.string(),value:z46.string()}),ProjectDomainSSLDTOSchema=z46.object({status:z46.string(),method:z46.string().nullable(),type:z46.string().nullable(),validationRecords:z46.array(SSLValidationRecordSchema).nullable().optional(),validationErrors:z46.array(SSLValidationErrorSchema).nullable().optional()}),DomainProviderSchema=z46.enum(["cloudflare","saas_custom_domains"]),DomainTypeSchema=z46.enum(["subdomain","apex"]),RedirectConfigSchema=z46.object({type:z46.literal("apex_to_www"),linkedDomainId:z46.string()}).nullable().optional(),ProjectDomainDTOSchema=z46.object({id:z46.string(),hostname:z46.string(),status:z46.string(),ssl:ProjectDomainSSLDTOSchema,ownershipVerification:z46.array(OwnershipVerificationSchema).nullable().optional(),cnameTarget:z46.string(),scdCnameTarget:z46.string().optional(),apexTargets:z46.array(z46.string()),dnsAutoConfigured:z46.boolean(),createdAt:CommonSchemas.timestamp,provider:DomainProviderSchema,domainType:DomainTypeSchema,redirectConfig:RedirectConfigSchema,migrationStatus:z46.string().nullable().optional()}),ProjectDomainDTO=createDTO(ProjectDomainDTOSchema),ProjectDomainListResponseSchema=createResponseSchema(z46.array(ProjectDomainDTOSchema)),ProjectDomainResponseSchema=createResponseSchema(ProjectDomainDTOSchema),AddProjectDomainRequestSchema=z46.object({hostname:z46.hostname().regex(/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,{error:"Invalid hostname"}).refine(value=>!/\.fimo\.site$/i.test(value),{error:"This is a Fimo-owned domain. Edit your built-in URL instead."}),redirectToWww:z46.boolean().optional()}),CheckProjectDomainHostnameReasonSchema=z46.enum(["invalid_hostname","fimo_owned_hostname","reserved","taken_by_another_project","taken_by_this_project"]),CheckProjectDomainHostnameResponseSchema=createResponseSchema(z46.object({available:z46.boolean(),reason:CheckProjectDomainHostnameReasonSchema.optional()})),DeleteProjectDomainResponseSchema=createResponseSchema(z46.object({success:z46.boolean(),hostname:z46.string()}))}});import{z as z47}from"zod";var SUBDOMAIN_REGEX,SubdomainCheckReasonSchema,CheckProjectSubdomainResponseSchema,UpdateProjectSubdomainRequestSchema,UpdateProjectSubdomainErrorReasonSchema,UpdateProjectSubdomainResponseSchema,SubdomainSuggestionsQuerySchema,SubdomainSuggestionsResponseSchema,init_project_subdomain_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-subdomain.dto.js"(){"use strict";init_response();SUBDOMAIN_REGEX=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/,SubdomainCheckReasonSchema=z47.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain"]),CheckProjectSubdomainResponseSchema=createResponseSchema(z47.object({available:z47.boolean(),reason:SubdomainCheckReasonSchema.optional()})),UpdateProjectSubdomainRequestSchema=z47.object({slug:z47.string().min(1).max(63).regex(SUBDOMAIN_REGEX,{error:"Invalid subdomain shape"})}),UpdateProjectSubdomainErrorReasonSchema=z47.enum(["invalid_shape","reserved","taken_by_project","taken_by_legacy_custom_domain","kv_sync_failed","hosting_sync_failed"]),UpdateProjectSubdomainResponseSchema=createResponseSchema(z47.object({subdomain:z47.string(),subdomainUpdatedAt:z47.coerce.date()})),SubdomainSuggestionsQuerySchema=z47.object({base:z47.string().max(100).optional(),max:z47.coerce.number().int().min(1).max(10).optional()}),SubdomainSuggestionsResponseSchema=createResponseSchema(z47.object({suggestions:z47.array(z47.string())}))}});import{z as z48}from"zod";var ProjectLocaleCoverageSchema,ProjectLocaleStatsItemSchema,ProjectLocaleStatsSchema,ProjectLocaleStatsDTO,ProjectLocaleStatsResponseSchema,AddProjectLocaleRequestSchema,RemoveProjectLocaleParamsSchema,ProjectLocaleMutationSchema,ProjectLocaleMutationDTO,ProjectLocaleMutationResponseSchema,RemoveProjectLocaleSchema,RemoveProjectLocaleDTO,RemoveProjectLocaleResponseSchema,init_project_locale_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/project-locale.dto.js"(){"use strict";init_create_dto();init_response();ProjectLocaleCoverageSchema=z48.object({translated:z48.number().int().nonnegative(),total:z48.number().int().nonnegative()}),ProjectLocaleStatsItemSchema=z48.object({locale:z48.string(),isDefault:z48.boolean(),entries:ProjectLocaleCoverageSchema,labels:ProjectLocaleCoverageSchema}),ProjectLocaleStatsSchema=z48.object({defaultLocale:z48.string(),routing:z48.object({strategy:z48.literal("path-prefix"),prefixDefaultLocale:z48.boolean()}),locales:z48.array(ProjectLocaleStatsItemSchema)}),ProjectLocaleStatsDTO=createDTO(ProjectLocaleStatsSchema),ProjectLocaleStatsResponseSchema=createResponseSchema(ProjectLocaleStatsSchema),AddProjectLocaleRequestSchema=z48.object({locale:z48.string().min(1).max(40)}),RemoveProjectLocaleParamsSchema=z48.object({locale:z48.string().min(1).max(40)}),ProjectLocaleMutationSchema=z48.object({locale:z48.string()}),ProjectLocaleMutationDTO=createDTO(ProjectLocaleMutationSchema),ProjectLocaleMutationResponseSchema=createResponseSchema(ProjectLocaleMutationSchema),RemoveProjectLocaleSchema=z48.object({locale:z48.string(),entriesDeleted:z48.number().int().nonnegative(),labelsDeleted:z48.number().int().nonnegative()}),RemoveProjectLocaleDTO=createDTO(RemoveProjectLocaleSchema),RemoveProjectLocaleResponseSchema=createResponseSchema(RemoveProjectLocaleSchema)}});import{z as z49}from"zod";function flag(key,description,options={}){return{name:key.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),key,description,type:options.type??"string",required:options.required??!1,...options.defaultValue!==void 0?{defaultValue:options.defaultValue}:{},...options.enumValues?{enumValues:[...options.enumValues]}:{},isArray:options.isArray??!1}}var GENERATION_QUALITIES,GENERATION_ASPECT_RATIOS,GENERATION_TASK_IDS,GenerationQualitySchema,GenerationTaskIdSchema,GENERATION_TASK_MANIFESTS,GenerationTaskEstimateDTOSchema,GenerationTaskEstimateDTO,init_generation_task_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation-task.dto.js"(){"use strict";init_create_dto();GENERATION_QUALITIES=["draft","standard","premium"],GENERATION_ASPECT_RATIOS=["1:1","16:9","9:16","4:3","3:4"],GENERATION_TASK_IDS=["image.generate","image.edit","image.remove-background","image.upscale","video.generate","video.animate","video.replace"],GenerationQualitySchema=z49.enum(GENERATION_QUALITIES),GenerationTaskIdSchema=z49.enum(GENERATION_TASK_IDS);__name(flag,"flag");GENERATION_TASK_MANIFESTS=[{id:"image.generate",modality:"image",operation:"generate",displayName:"Generate image",description:"Create an image from a prompt. Quality selects the appropriate generation route.",flags:[flag("prompt","Generation prompt",{required:!0}),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.edit",modality:"image",operation:"edit",displayName:"Edit image",description:"Transform up to five source images using a natural-language instruction.",flags:[flag("prompt","Editing instruction",{required:!0}),flag("images","Source asset id or absolute URL; repeatable up to five times",{required:!0,isArray:!0}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"1:1",enumValues:GENERATION_ASPECT_RATIOS})]},{id:"image.remove-background",modality:"image",operation:"remove-background",displayName:"Remove image background",description:"Remove the background from one image and return a transparent cutout.",flags:[flag("image","Source asset id or absolute URL",{required:!0})]},{id:"image.upscale",modality:"image",operation:"upscale",displayName:"Upscale image",description:"Increase image resolution while preserving and optionally enhancing detail.",flags:[flag("image","Source asset id or absolute URL",{required:!0}),flag("targetMegapixels","Target resolution in megapixels",{type:"integer",defaultValue:4}),flag("outputFormat","Output image format",{type:"enum",defaultValue:"png",enumValues:["webp","jpg","png"]}),flag("enhanceDetails","Improve fine detail during upscaling",{type:"boolean",defaultValue:!0}),flag("enhanceRealism","Favor photorealistic detail reconstruction",{type:"boolean",defaultValue:!1})]},{id:"video.generate",modality:"video",operation:"generate",displayName:"Generate video",description:"Create a video from text or animate one source image. Loop closes the final frame back to the first.",flags:[flag("prompt","Generation and motion prompt",{required:!0}),flag("image","Optional source asset id or absolute URL"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("aspectRatio","Output aspect ratio",{type:"enum",defaultValue:"16:9",enumValues:GENERATION_ASPECT_RATIOS}),flag("duration","Duration in seconds; loops support 3 to 20 seconds",{type:"integer",defaultValue:5}),flag("includeAudio","Generate audio with the video",{type:"boolean",defaultValue:!1}),flag("loop","Make the final frame return to the source image",{type:"boolean",defaultValue:!1})]},{id:"video.animate",modality:"video",operation:"animate",displayName:"Animate image from video",description:"Apply the motion and camera movement from a source video to a reference image.",flags:[flag("video","Motion source asset id or absolute URL",{required:!0}),flag("image","Subject reference asset id or absolute URL",{required:!0}),flag("prompt","Optional instruction for the animation"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]},{id:"video.replace",modality:"video",operation:"replace",displayName:"Replace subjects in video",description:"Replace people in a source video with one to three reference identities while preserving motion.",flags:[flag("video","Source video asset id or absolute URL",{required:!0}),flag("images","Identity reference asset id or URL; repeatable up to three times",{required:!0,isArray:!0}),flag("prompt","Optional placement instruction"),flag("quality","Quality and cost tier",{type:"enum",defaultValue:"standard",enumValues:GENERATION_QUALITIES}),flag("duration","Source duration in seconds for cost calculation",{type:"integer",defaultValue:5}),flag("includeAudio","Keep audio in the generated video",{type:"boolean",defaultValue:!0})]}],GenerationTaskEstimateDTOSchema=z49.object({task:GenerationTaskIdSchema,quality:GenerationQualitySchema.optional(),costUsd:z49.number(),credits:z49.number().optional(),billingMode:z49.enum(["fimo-credits","provider-account"]).optional(),confidence:z49.enum(["exact","estimated","metered"]),basis:z49.string()}),GenerationTaskEstimateDTO=createDTO(GenerationTaskEstimateDTOSchema)}});import{z as z50}from"zod";var GenerateRequestBaseSchema,GenerateRequestDTOSchema,GenerateRequestDTO,GenerateResponseDataSchema,GenerateResponseDTO,GenerateResponseSchema,GenerateErrorSchema,init_generation_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/generation.dto.js"(){"use strict";init_create_dto();init_response();init_asset_dto();init_generation_task_dto();GenerateRequestBaseSchema=z50.object({options:z50.record(z50.string(),z50.unknown()),name:z50.string().optional(),parentId:z50.string().nullable().optional(),altText:z50.string().optional(),caption:z50.string().optional()}),GenerateRequestDTOSchema=GenerateRequestBaseSchema.extend({task:z50.string().min(1).optional(),model:z50.string().min(1).optional()}).superRefine((value,context)=>{!!value.task==!!value.model&&context.addIssue({code:"custom",message:"Provide exactly one of task or model",path:["task"]})}),GenerateRequestDTO=createDTO(GenerateRequestDTOSchema),GenerateResponseDataSchema=z50.object({jobId:z50.string(),status:z50.enum(["queued","running","completed","failed"]),asset:AssetDTOSchema.optional(),error:z50.string().nullable().optional(),credits:z50.number().optional(),costUsd:z50.number().optional(),billingMode:z50.enum(["fimo-credits","provider-account"]).optional(),task:GenerationTaskIdSchema.optional(),quality:GenerationQualitySchema.optional()}),GenerateResponseDTO=createDTO(GenerateResponseDataSchema),GenerateResponseSchema=createResponseSchema(GenerateResponseDataSchema),GenerateErrorSchema=z50.object({error:z50.string(),code:z50.enum(["unknown-task","unknown-model","options-invalid","source-invalid","task-routing-failed","generation-failed","provider-error","cost-limit-exceeded","cost-estimate-unavailable","unsupported-modality"]),availableTasks:z50.array(GenerationTaskIdSchema).optional(),availableModels:z50.array(z50.string()).optional(),issues:z50.array(z50.unknown()).optional()})}});import{z as z51}from"zod";var FlagTypeSchema,FlagSpecSchema,AssetModelPriceSchema,AssetModelDTOSchema,AssetModelDTO,AssetModelEstimateDTOSchema,AssetModelEstimateDTO,init_asset_model_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/asset-model.dto.js"(){"use strict";init_create_dto();FlagTypeSchema=z51.enum(["string","number","integer","boolean","enum","array","unknown"]),FlagSpecSchema=z51.object({name:z51.string(),key:z51.string(),description:z51.string(),type:FlagTypeSchema,required:z51.boolean(),defaultValue:z51.unknown().optional(),enumValues:z51.array(z51.string()).optional(),isArray:z51.boolean()}),AssetModelPriceSchema=z51.object({unitPrice:z51.number(),unit:z51.string(),confidence:z51.enum(["exact","estimated","metered"])}),AssetModelDTOSchema=z51.object({id:z51.string(),shortName:z51.string(),provider:z51.string(),source:z51.string(),modality:z51.enum(["image","video","audio"]),tags:z51.array(z51.string()),displayName:z51.string(),description:z51.string(),flags:z51.array(FlagSpecSchema),price:AssetModelPriceSchema.nullable()}),AssetModelDTO=createDTO(AssetModelDTOSchema),AssetModelEstimateDTOSchema=z51.object({model:z51.string(),costUsd:z51.number(),credits:z51.number(),billingMode:z51.enum(["fimo-credits","provider-account"]),confidence:z51.enum(["exact","estimated","metered"]),basis:z51.string()}),AssetModelEstimateDTO=createDTO(AssetModelEstimateDTOSchema)}});import{z as z52}from"zod";var UserTourDTOSchema,UserTourDTO,UserTourResponseSchema,UserTourListResponseSchema,init_tour_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/tour.dto.js"(){"use strict";init_create_dto();init_response();UserTourDTOSchema=z52.object({tourId:z52.string(),version:z52.string(),status:z52.string(),completedAt:z52.coerce.date()}),UserTourDTO=createDTO(UserTourDTOSchema),UserTourResponseSchema=createResponseSchema(UserTourDTOSchema),UserTourListResponseSchema=createResponseSchema(z52.array(UserTourDTOSchema))}});import{z as z53}from"zod";var SUPPORT_REPORT_CATEGORIES,SupportReportCategorySchema,SUPPORT_REPORT_STATUSES,SupportReportStatusSchema,SupportReportSourceSchema,SupportReportDeliveryStatusSchema,SUPPORT_REPORT_LINK_KINDS,SupportReportLinkKindSchema,SupportReportEventKindSchema,SupportReportActorKindSchema,SupportReportTagSchema,SupportReportHttpUrlSchema,SupportReportContextInputSchema,CreateSupportReportInputSchema,SupportReportListQuerySchema,UpdateSupportReportInputSchema,CreateSupportReportMessageInputSchema,CreateSupportReportLinkInputSchema,SupportReportActorDTOSchema,SupportReportLinkDTOSchema,SupportReportLinkDTO,SupportReportEventDTOSchema,SupportReportEventDTO,SupportReportSummaryDTOSchema,SupportReportSummaryDTO,SupportReportDetailDTOSchema,SupportReportDetailDTO,SupportReportListDTOSchema,SupportReportListDTO,CreateSupportReportResultDTOSchema,CreateSupportReportResultDTO,init_support_report_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/support-report.dto.js"(){"use strict";init_create_dto();SUPPORT_REPORT_CATEGORIES=[{value:"account_billing",label:"Account & billing"},{value:"project_issues",label:"Project issues"},{value:"ai_prompt_output_quality",label:"AI prompt & output quality"},{value:"roles_access_collaboration",label:"Roles, access & collaboration"},{value:"code_technical_questions",label:"Code & technical questions"},{value:"others",label:"Other"}],SupportReportCategorySchema=z53.enum(SUPPORT_REPORT_CATEGORIES.map(category=>category.value)),SUPPORT_REPORT_STATUSES=["new","in_progress","waiting","resolved","duplicate","irrelevant","ignored"],SupportReportStatusSchema=z53.enum(SUPPORT_REPORT_STATUSES),SupportReportSourceSchema=z53.enum(["app","cli","agent"]),SupportReportDeliveryStatusSchema=z53.enum(["pending","delivered","failed"]),SUPPORT_REPORT_LINK_KINDS=["linear","pylon","project","sentry","grafana","other"],SupportReportLinkKindSchema=z53.enum(SUPPORT_REPORT_LINK_KINDS),SupportReportEventKindSchema=z53.enum(["report_created","report_updated","message","link_added","link_removed","delivery"]),SupportReportActorKindSchema=z53.enum(["user","agent","system"]),SupportReportTagSchema=z53.string().trim().min(1).max(50),SupportReportHttpUrlSchema=z53.url({protocol:/^https?$/}).max(2e3),SupportReportContextInputSchema=z53.object({organization:z53.object({id:z53.string().trim().min(1).max(255),name:z53.string().trim().max(240).optional()}),project:z53.object({id:z53.uuid(),name:z53.string().trim().max(240).optional(),createdAt:z53.coerce.date().optional()}).optional(),environment:z53.string().trim().max(255).optional(),clientVersion:z53.string().trim().max(64).optional()}),CreateSupportReportInputSchema=z53.object({message:z53.string().trim().min(1).max(2e4),category:SupportReportCategorySchema,source:SupportReportSourceSchema.default("app"),context:SupportReportContextInputSchema}),SupportReportListQuerySchema=z53.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),source:SupportReportSourceSchema.optional(),tag:SupportReportTagSchema.optional(),query:z53.string().trim().max(200).optional(),limit:z53.coerce.number().int().min(1).max(100).default(50),offset:z53.coerce.number().int().min(0).default(0)}),UpdateSupportReportInputSchema=z53.object({status:SupportReportStatusSchema.optional(),category:SupportReportCategorySchema.optional(),tags:z53.array(SupportReportTagSchema).max(20).optional(),duplicateOfReportId:z53.uuid().nullable().optional(),note:z53.string().trim().min(1).max(2e4).optional()}).refine(input=>Object.values(input).some(value=>value!==void 0),{message:"At least one report change is required"}),CreateSupportReportMessageInputSchema=z53.object({message:z53.string().trim().min(1).max(2e4)}),CreateSupportReportLinkInputSchema=z53.object({kind:SupportReportLinkKindSchema,label:z53.string().trim().min(1).max(240),url:SupportReportHttpUrlSchema,externalId:z53.string().trim().max(240).optional()}),SupportReportActorDTOSchema=z53.object({kind:SupportReportActorKindSchema,id:z53.string().nullable(),name:z53.string().nullable()}),SupportReportLinkDTOSchema=z53.object({id:z53.uuid(),kind:SupportReportLinkKindSchema,label:z53.string(),url:SupportReportHttpUrlSchema,externalId:z53.string().nullable(),addedBy:SupportReportActorDTOSchema,createdAt:z53.coerce.date()}),SupportReportLinkDTO=createDTO(SupportReportLinkDTOSchema),SupportReportEventDTOSchema=z53.object({id:z53.uuid(),kind:SupportReportEventKindSchema,body:z53.string().nullable(),metadata:z53.record(z53.string(),z53.unknown()),actor:SupportReportActorDTOSchema,createdAt:z53.coerce.date()}),SupportReportEventDTO=createDTO(SupportReportEventDTOSchema),SupportReportSummaryDTOSchema=z53.object({id:z53.uuid(),status:SupportReportStatusSchema,category:SupportReportCategorySchema,tags:z53.array(z53.string()),source:SupportReportSourceSchema,message:z53.string(),reporter:z53.object({id:z53.string().nullable(),name:z53.string().nullable(),email:z53.string().nullable()}),organization:z53.object({id:z53.string().nullable(),name:z53.string()}),project:z53.object({id:z53.uuid().nullable(),name:z53.string()}).nullable(),assignee:SupportReportActorDTOSchema.nullable(),delivery:z53.object({status:SupportReportDeliveryStatusSchema,pylonIssueId:z53.string().nullable(),pylonIssueUrl:SupportReportHttpUrlSchema.nullable(),error:z53.string().nullable(),deliveredAt:z53.coerce.date().nullable()}).nullable(),duplicateOfReportId:z53.uuid().nullable(),resolvedAt:z53.coerce.date().nullable(),createdAt:z53.coerce.date(),updatedAt:z53.coerce.date()}),SupportReportSummaryDTO=createDTO(SupportReportSummaryDTOSchema),SupportReportDetailDTOSchema=SupportReportSummaryDTOSchema.extend({environment:z53.string().nullable(),clientVersion:z53.string().nullable(),links:z53.array(SupportReportLinkDTOSchema),events:z53.array(SupportReportEventDTOSchema)}),SupportReportDetailDTO=createDTO(SupportReportDetailDTOSchema),SupportReportListDTOSchema=z53.object({reports:z53.array(SupportReportSummaryDTOSchema),total:z53.number().int().nonnegative(),statusCounts:z53.object({new:z53.number().int().nonnegative(),in_progress:z53.number().int().nonnegative(),waiting:z53.number().int().nonnegative(),resolved:z53.number().int().nonnegative(),duplicate:z53.number().int().nonnegative(),irrelevant:z53.number().int().nonnegative(),ignored:z53.number().int().nonnegative()}),limit:z53.number().int().positive(),offset:z53.number().int().nonnegative()}),SupportReportListDTO=createDTO(SupportReportListDTOSchema),CreateSupportReportResultDTOSchema=z53.object({id:z53.uuid(),deliveryStatus:SupportReportDeliveryStatusSchema,message:z53.string()}),CreateSupportReportResultDTO=createDTO(CreateSupportReportResultDTOSchema)}});import{z as z54}from"zod";var OPS_RECENT_CHAT_MAX_WINDOW_MS,OpsChatTimestampInputSchema,OpsRecentChatInputSchema,OpsRecentChatMessageSchema,OpsRecentChatResponseSchema,OpsRecentChatResponseDTO,init_ops_chat_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/ops-chat.dto.js"(){"use strict";init_ops();init_create_dto();OPS_RECENT_CHAT_MAX_WINDOW_MS=10080*60*1e3,OpsChatTimestampInputSchema=z54.iso.datetime({offset:!0}).pipe(z54.coerce.date()),OpsRecentChatInputSchema=z54.object({from:OpsChatTimestampInputSchema,to:OpsChatTimestampInputSchema.optional(),projectEnv:z54.string().trim().min(1).max(255).optional(),limit:z54.coerce.number().int().min(1).max(200).default(100),cursor:z54.string().trim().min(1).max(2e3).optional(),slim:z54.boolean().default(!0),reason:z54.string().trim().min(1).max(1e3)}).refine(input=>input.from<=(input.to??new Date),{message:"from must be before or equal to to",path:["from"]}).refine(input=>(input.to??new Date).getTime()-input.from.getTime()<=OPS_RECENT_CHAT_MAX_WINDOW_MS,{message:"recent chat window cannot exceed 7 days",path:["from"]}).refine(input=>!input.cursor||!!input.to,{message:"to is required when continuing with a cursor",path:["to"]}),OpsRecentChatMessageSchema=z54.object({id:z54.string(),messageId:z54.string(),env:z54.string(),versionId:z54.string().nullable(),userId:z54.string().nullable(),role:z54.string(),parts:z54.array(z54.record(z54.string(),z54.unknown())),metadata:z54.object({status:z54.string().optional(),traceUrl:z54.string().optional(),externalFileChanges:z54.array(z54.unknown()).optional()}),stats:z54.object({toolCount:z54.number().int().nonnegative(),failedToolCount:z54.number().int().nonnegative()}),createdAt:z54.iso.datetime({offset:!0}),project:z54.object({id:z54.string(),name:z54.string(),displayName:z54.string().nullable(),organizationId:z54.string().nullable()})}),OpsRecentChatResponseSchema=z54.object({target:z54.object({backendProfile:OpsBackendProfileSchema,projectEnv:z54.string().nullable()}),window:z54.object({from:z54.iso.datetime({offset:!0}),to:z54.iso.datetime({offset:!0})}),messages:z54.object({items:z54.array(OpsRecentChatMessageSchema),nextCursor:z54.string().nullable()})}),OpsRecentChatResponseDTO=createDTO(OpsRecentChatResponseSchema)}});import{z as z55}from"zod";function createAgentRunWebhookEventDataSchema(status){return z55.object({run:z55.object({id:z55.string(),agentName:z55.string(),trigger:z55.string(),status:z55.literal(status),startedAt:z55.string().nullable(),finishedAt:z55.string().nullable(),reason:z55.string().nullable()})})}var WEBHOOK_EVENT_TYPES,WebhookEventTypeSchema,WebhookEntryChangeActionSchema,WebhookEntryChangeReasonSchema,WebhookEnvironmentScopeSchema,WebhookEntryBatchWindowSecondsSchema,EntryChangedWebhookEventDataSchema,FormSubmittedWebhookEventDataSchema,PublishStartedWebhookEventDataSchema,PublishSucceededWebhookEventDataSchema,PublishFailedWebhookEventDataSchema,PublishUnpublishedWebhookEventDataSchema,AgentReviewRequestedWebhookEventDataSchema,AgentReviewResolvedWebhookEventDataSchema,AnalyticsReportReadyWebhookEventDataSchema,MediaAssetWebhookEventDataSchema,MediaUploadedWebhookEventDataSchema,MediaUpdatedWebhookEventDataSchema,MediaDeletedWebhookEventDataSchema,MediaGeneratedWebhookEventDataSchema,MediaProcessingFailedWebhookEventDataSchema,DomainCreatedWebhookEventDataSchema,DomainDeletedWebhookEventDataSchema,LabelChangedWebhookEventDataSchema,LocaleCreatedWebhookEventDataSchema,LocaleDefaultChangedWebhookEventDataSchema,LocaleDeletedWebhookEventDataSchema,EnvironmentCreatedWebhookEventDataSchema,EnvironmentDeletedWebhookEventDataSchema,EnvironmentMergedWebhookEventDataSchema,EnvironmentRestoredWebhookEventDataSchema,WEBHOOK_EVENT_DATA_SCHEMAS,WebhookEventFamilySchema,WebhookDestinationKindSchema,WebhookHeaderValueInputSchema,WebhookHeaderInputSchema,WebhookHeaderDTOSchema,WebhookFilterSchema,JsonValueSchema,CreateProjectWebhookRequestSchema,UpdateProjectWebhookRequestSchema,TestProjectWebhookRequestSchema,WebhookDeliveryStatusSchema,ProjectWebhookDTOSchema,ProjectWebhookDTO,WebhookDeliveryDTOSchema,WebhookDeliveryDTO,WebhookDeliveriesPageSchema,WebhookDeliveryAttemptDTOSchema,WebhookDeliveryAttemptDTO,ProjectWebhookResponseSchema,ProjectWebhooksListResponseSchema,WebhookDeliveriesListResponseSchema,WebhookDeliveryAttemptsListResponseSchema,init_webhook_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/webhook.dto.js"(){"use strict";init_common();init_env();init_create_dto();init_response();init_env_status_dto();init_project_domain_dto();WEBHOOK_EVENT_TYPES=["entry.changed","form.submitted","publish.started","publish.succeeded","publish.failed","publish.unpublished","agent.run.started","agent.run.completed","agent.run.failed","agent.run.cancelled","agent.review.requested","agent.review.resolved","analytics.report_ready","media.uploaded","media.updated","media.deleted","media.generated","media.processing_failed","domain.created","domain.deleted","label.changed","locale.created","locale.default_changed","locale.deleted","environment.created","environment.deleted","environment.merged","environment.restored"],WebhookEventTypeSchema=z55.enum(WEBHOOK_EVENT_TYPES),WebhookEntryChangeActionSchema=z55.enum(["created","updated","deleted"]),WebhookEntryChangeReasonSchema=z55.enum(["entry_write","bulk_edit","environment_merge"]),WebhookEnvironmentScopeSchema=z55.enum(["main","all"]),WebhookEntryBatchWindowSecondsSchema=z55.union([z55.literal(0),z55.literal(5),z55.literal(30),z55.literal(60)]),EntryChangedWebhookEventDataSchema=z55.object({reason:WebhookEntryChangeReasonSchema,operationId:z55.string().optional(),batch:z55.object({index:z55.number().int().positive(),total:z55.number().int().positive()}).optional(),changes:z55.array(z55.object({action:WebhookEntryChangeActionSchema,contentType:z55.string(),id:z55.string(),documentId:z55.string(),locale:z55.string().nullable()}))}),FormSubmittedWebhookEventDataSchema=z55.object({form:z55.object({id:z55.string(),label:z55.string()}),submission:z55.object({id:z55.string(),data:z55.record(z55.string(),z55.unknown()),submittedAt:z55.string()})}),PublishStartedWebhookEventDataSchema=z55.object({publication:z55.object({status:z55.literal("publishing"),startedAt:z55.string()})}),PublishSucceededWebhookEventDataSchema=z55.object({publication:z55.object({status:z55.literal("published"),url:z55.string(),publishedAt:z55.string(),firstPublish:z55.boolean()})}),PublishFailedWebhookEventDataSchema=z55.object({publication:z55.object({status:z55.literal("failed"),reason:z55.string()})}),PublishUnpublishedWebhookEventDataSchema=z55.object({publication:z55.object({previousUrl:z55.string(),unpublishedAt:z55.string()})});__name(createAgentRunWebhookEventDataSchema,"createAgentRunWebhookEventDataSchema");AgentReviewRequestedWebhookEventDataSchema=z55.object({review:z55.object({id:z55.string(),runId:z55.string(),agentName:z55.string(),classification:z55.string(),summary:z55.string(),reasons:z55.array(z55.string()).readonly()})}),AgentReviewResolvedWebhookEventDataSchema=z55.object({review:z55.object({id:z55.string(),runId:z55.string(),agentName:z55.string(),resolution:z55.string()})}),AnalyticsReportReadyWebhookEventDataSchema=z55.object({report:z55.object({weekStart:z55.string(),weekEnd:z55.string(),pageviews:z55.number(),visitors:z55.number(),previousPageviews:z55.number(),previousVisitors:z55.number()})}),MediaAssetWebhookEventDataSchema=z55.object({id:z55.string().nullable(),name:z55.string().nullable(),type:z55.string(),mimeType:z55.string().nullable(),fileSize:z55.number().nullable()}),MediaUploadedWebhookEventDataSchema=z55.object({asset:MediaAssetWebhookEventDataSchema,operation:z55.literal("uploaded")}),MediaUpdatedWebhookEventDataSchema=z55.object({asset:MediaAssetWebhookEventDataSchema,operation:z55.enum(["updated","moved","analysis"]),analysis:z55.object({category:z55.string(),status:z55.literal("completed")}).optional()}),MediaDeletedWebhookEventDataSchema=z55.object({asset:MediaAssetWebhookEventDataSchema,operation:z55.literal("deleted")}),MediaGeneratedWebhookEventDataSchema=z55.object({asset:MediaAssetWebhookEventDataSchema,operation:z55.literal("generated"),generation:z55.object({model:z55.string(),mode:z55.string()})}),MediaProcessingFailedWebhookEventDataSchema=z55.object({asset:MediaAssetWebhookEventDataSchema,operation:z55.enum(["analysis","generation"]),failure:z55.object({code:z55.string()})}),DomainCreatedWebhookEventDataSchema=z55.object({domain:z55.object({id:z55.string(),hostname:z55.string(),status:ProjectDomainStatusSchema,sslStatus:SSLStatusSchema})}),DomainDeletedWebhookEventDataSchema=z55.object({domain:z55.object({id:z55.string(),hostname:z55.string()})}),LabelChangedWebhookEventDataSchema=z55.object({changes:z55.array(z55.object({action:z55.enum(["created","updated","deleted"]),key:z55.string(),locale:z55.string(),value:z55.string().nullable()}))}),LocaleCreatedWebhookEventDataSchema=z55.object({locale:z55.object({code:z55.string(),isDefault:z55.boolean()})}),LocaleDefaultChangedWebhookEventDataSchema=z55.object({locale:z55.object({code:z55.string(),previousCode:z55.string()})}),LocaleDeletedWebhookEventDataSchema=z55.object({locale:z55.object({code:z55.string(),entriesDeleted:z55.number().int().nonnegative(),labelsDeleted:z55.number().int().nonnegative()})}),EnvironmentCreatedWebhookEventDataSchema=z55.object({environment:z55.object({name:EnvSchema,parent:EnvSchema})}),EnvironmentDeletedWebhookEventDataSchema=z55.object({environment:z55.object({name:EnvSchema})}),EnvironmentMergedWebhookEventDataSchema=z55.object({merge:z55.object({id:z55.string(),from:EnvSchema,to:EnvSchema,applied:z55.array(z55.object({surface:SurfaceNameSchema,count:z55.number().int().nonnegative()}))})}),EnvironmentRestoredWebhookEventDataSchema=z55.object({environment:z55.object({name:EnvSchema}),version:z55.object({versionId:z55.uuid(),name:z55.string()})}),WEBHOOK_EVENT_DATA_SCHEMAS={"entry.changed":EntryChangedWebhookEventDataSchema,"form.submitted":FormSubmittedWebhookEventDataSchema,"publish.started":PublishStartedWebhookEventDataSchema,"publish.succeeded":PublishSucceededWebhookEventDataSchema,"publish.failed":PublishFailedWebhookEventDataSchema,"publish.unpublished":PublishUnpublishedWebhookEventDataSchema,"agent.run.started":createAgentRunWebhookEventDataSchema("running"),"agent.run.completed":createAgentRunWebhookEventDataSchema("completed"),"agent.run.failed":createAgentRunWebhookEventDataSchema("failed"),"agent.run.cancelled":createAgentRunWebhookEventDataSchema("cancelled"),"agent.review.requested":AgentReviewRequestedWebhookEventDataSchema,"agent.review.resolved":AgentReviewResolvedWebhookEventDataSchema,"analytics.report_ready":AnalyticsReportReadyWebhookEventDataSchema,"media.uploaded":MediaUploadedWebhookEventDataSchema,"media.updated":MediaUpdatedWebhookEventDataSchema,"media.deleted":MediaDeletedWebhookEventDataSchema,"media.generated":MediaGeneratedWebhookEventDataSchema,"media.processing_failed":MediaProcessingFailedWebhookEventDataSchema,"domain.created":DomainCreatedWebhookEventDataSchema,"domain.deleted":DomainDeletedWebhookEventDataSchema,"label.changed":LabelChangedWebhookEventDataSchema,"locale.created":LocaleCreatedWebhookEventDataSchema,"locale.default_changed":LocaleDefaultChangedWebhookEventDataSchema,"locale.deleted":LocaleDeletedWebhookEventDataSchema,"environment.created":EnvironmentCreatedWebhookEventDataSchema,"environment.deleted":EnvironmentDeletedWebhookEventDataSchema,"environment.merged":EnvironmentMergedWebhookEventDataSchema,"environment.restored":EnvironmentRestoredWebhookEventDataSchema},WebhookEventFamilySchema=z55.enum(["entries","forms","publish","agents","analytics","media","domains","labels","locales","environments"]),WebhookDestinationKindSchema=z55.enum(["custom","resend","github","slack"]),WebhookHeaderValueInputSchema=z55.discriminatedUnion("source",[z55.object({source:z55.literal("literal"),value:z55.string().min(1).max(4096).regex(/^[^\r\n]*$/)}),z55.object({source:z55.literal("secret"),key:z55.string().regex(/^[A-Z_][A-Z0-9_]*$/),prefix:z55.string().max(128).regex(/^[^\r\n]*$/).optional()})]),WebhookHeaderInputSchema=z55.object({name:z55.string().min(1).max(128),value:WebhookHeaderValueInputSchema}),WebhookHeaderDTOSchema=z55.object({name:z55.string(),source:z55.enum(["literal","secret"]),secretKey:z55.string().nullable(),secretPrefix:z55.string().nullable(),configured:z55.literal(!0)}),WebhookFilterSchema=z55.object({environment:WebhookEnvironmentScopeSchema.optional(),formId:z55.string().min(1).max(255).optional(),agentName:z55.string().min(1).max(120).optional(),mediaType:z55.enum(["image","video","audio","document","other"]).optional(),action:WebhookEntryChangeActionSchema.optional(),contentType:z55.string().min(1).max(255).optional(),locale:z55.string().min(1).max(120).optional()}),JsonValueSchema=z55.lazy(()=>z55.union([z55.string(),z55.number(),z55.boolean(),z55.null(),z55.array(JsonValueSchema),z55.record(z55.string(),JsonValueSchema)])),CreateProjectWebhookRequestSchema=z55.object({name:z55.string().trim().min(1).max(120),eventType:WebhookEventTypeSchema,url:z55.url(),enabled:z55.boolean().optional().default(!0),filter:WebhookFilterSchema.optional().default({}),headers:z55.array(WebhookHeaderInputSchema).max(20).optional().default([]),bodyTemplate:JsonValueSchema.nullable().optional().default(null),signingEnabled:z55.boolean().optional().default(!0),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional().default(0)}),UpdateProjectWebhookRequestSchema=z55.object({name:z55.string().trim().min(1).max(120).optional(),eventType:WebhookEventTypeSchema.optional(),url:z55.url().optional(),enabled:z55.boolean().optional(),filter:WebhookFilterSchema.optional(),headers:z55.array(WebhookHeaderInputSchema).max(20).optional(),bodyTemplate:JsonValueSchema.nullable().optional(),signingEnabled:z55.boolean().optional(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema.optional()}),TestProjectWebhookRequestSchema=z55.object({eventType:WebhookEventTypeSchema.optional(),data:z55.record(z55.string(),JsonValueSchema).optional()}),WebhookDeliveryStatusSchema=z55.enum(["pending","delivering","retrying","succeeded","failed"]),ProjectWebhookDTOSchema=BaseEntitySchema.extend({projectId:z55.uuid(),name:z55.string(),eventType:WebhookEventTypeSchema,enabled:z55.boolean(),destination:z55.object({host:z55.string(),maskedUrl:z55.string(),kind:WebhookDestinationKindSchema}),filter:WebhookFilterSchema,headers:z55.array(WebhookHeaderDTOSchema),bodyTemplate:JsonValueSchema.nullable(),signingEnabled:z55.boolean(),entryBatchWindowSeconds:WebhookEntryBatchWindowSecondsSchema,lastDeliveryStatus:WebhookDeliveryStatusSchema.nullable(),lastDeliveryAt:z55.coerce.date().nullable(),deliveryStats24h:z55.object({succeeded:z55.number().int().nonnegative(),failed:z55.number().int().nonnegative()})}),ProjectWebhookDTO=createDTO(ProjectWebhookDTOSchema),WebhookDeliveryDTOSchema=BaseEntitySchema.extend({webhookId:z55.uuid(),projectId:z55.uuid(),env:EnvSchema,eventId:z55.uuid(),eventType:WebhookEventTypeSchema,eventVersion:z55.number().int().positive(),test:z55.boolean(),status:WebhookDeliveryStatusSchema,attemptCount:z55.number().int().nonnegative(),responseStatus:z55.number().int().nullable(),lastErrorCode:z55.string().nullable(),lastErrorMessage:z55.string().nullable(),payloadAvailable:z55.boolean(),destination:z55.object({host:z55.string(),maskedUrl:z55.string(),kind:WebhookDestinationKindSchema}),requestHeaders:z55.array(WebhookHeaderDTOSchema),requestBodyExcerpt:z55.string().nullable(),qstashMessageId:z55.string().nullable(),deliveredAt:z55.coerce.date().nullable()}),WebhookDeliveryDTO=createDTO(WebhookDeliveryDTOSchema),WebhookDeliveriesPageSchema=z55.object({items:z55.array(WebhookDeliveryDTOSchema),pagination:z55.object({page:z55.number().int().positive(),limit:z55.number().int().positive(),total:z55.number().int().nonnegative(),totalPages:z55.number().int().positive(),hasMore:z55.boolean()}),stats:z55.object({total:z55.number().int().nonnegative(),succeeded:z55.number().int().nonnegative(),failed:z55.number().int().nonnegative()})}),WebhookDeliveryAttemptDTOSchema=z55.object({id:z55.uuid(),deliveryId:z55.uuid(),attempt:z55.number().int().positive(),status:z55.enum(["delivering","succeeded","failed"]),responseStatus:z55.number().int().nullable(),durationMs:z55.number().int().nonnegative(),responseExcerpt:z55.string().nullable(),errorCode:z55.string().nullable(),errorMessage:z55.string().nullable(),createdAt:z55.coerce.date()}),WebhookDeliveryAttemptDTO=createDTO(WebhookDeliveryAttemptDTOSchema),ProjectWebhookResponseSchema=createResponseSchema(ProjectWebhookDTOSchema),ProjectWebhooksListResponseSchema=createResponseSchema(z55.array(ProjectWebhookDTOSchema)),WebhookDeliveriesListResponseSchema=createResponseSchema(WebhookDeliveriesPageSchema),WebhookDeliveryAttemptsListResponseSchema=createResponseSchema(z55.array(WebhookDeliveryAttemptDTOSchema))}});import{z as z56}from"zod";var PREVIEW_FEATURE_REGISTRY,previewFeatureKeys,PreviewFeatureDTOSchema,PreviewFeatureDTO,PreviewFeatureResponseSchema,PreviewFeatureListResponseSchema,init_preview_feature_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/preview-feature.dto.js"(){"use strict";init_create_dto();init_response();PREVIEW_FEATURE_REGISTRY={"fimo-2":{key:"fimo-2",defaultEnabled:!1}},previewFeatureKeys=Object.keys(PREVIEW_FEATURE_REGISTRY),PreviewFeatureDTOSchema=z56.object({key:z56.enum(previewFeatureKeys),enabled:z56.boolean(),dismissed:z56.boolean().default(!1),interacted:z56.boolean().default(!1)}),PreviewFeatureDTO=createDTO(PreviewFeatureDTOSchema),PreviewFeatureResponseSchema=createResponseSchema(PreviewFeatureDTOSchema),PreviewFeatureListResponseSchema=createResponseSchema(z56.array(PreviewFeatureDTOSchema))}});import{z as z57}from"zod";var SubscriptionStatusSchema,CreditBalanceBreakdownDTOSchema,CreditBalanceBreakdownDTO,SubscriptionPlanDTOSchema,SubscriptionPlanDTO,SubscriptionPaymentMethodDTOSchema,SubscriptionPaymentMethodDTO,SubscriptionPricingDTOSchema,SubscriptionPricingDTO,SubscriptionDetailsDTOSchema,SubscriptionDetailsDTO,CreditAlertDTOSchema,CreditAlertDTO,PlanAllocationDTOSchema,PlanAllocationDTO,LatestCancellationDTOSchema,LatestCancellationDTO,OrganizationSubscriptionDTOSchema,OrganizationSubscriptionDTO,BaseCreditTopupRequestSchema,FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema,CreditTopupRequestDTOSchema,CreditTopupRequestDTO,CreditTopupResponseDTOSchema,CreditTopupResponseDTO,init_subscription_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/subscription.dto.js"(){"use strict";init_common();init_create_dto();init_billing_dto();SubscriptionStatusSchema=z57.enum(["active","cancelled","draft","errored","paused","pending","voided"]),CreditBalanceBreakdownDTOSchema=z57.object({total:z57.number(),base:z57.number(),purchases:z57.number(),awards:z57.number()}),CreditBalanceBreakdownDTO=createDTO(CreditBalanceBreakdownDTOSchema),SubscriptionPlanDTOSchema=z57.object({id:z57.string(),name:z57.string()}),SubscriptionPlanDTO=createDTO(SubscriptionPlanDTOSchema),SubscriptionPaymentMethodDTOSchema=z57.object({type:z57.string(),brand:z57.string().nullable(),last4:z57.string().nullable(),expirationDate:z57.string().nullable()}),SubscriptionPaymentMethodDTO=createDTO(SubscriptionPaymentMethodDTOSchema),SubscriptionPricingDTOSchema=z57.object({currency:z57.string(),nextPaymentAmount:z57.number().nullable(),nextPaymentAt:z57.string().nullable(),billingInterval:z57.string().nullable(),totalAmount:z57.number().nullable(),discountAmount:z57.number().nullable()}),SubscriptionPricingDTO=createDTO(SubscriptionPricingDTOSchema),SubscriptionDetailsDTOSchema=z57.object({id:z57.string(),status:SubscriptionStatusSchema,plan:SubscriptionPlanDTOSchema.nullable(),currentPeriodStartedAt:z57.string().nullable(),currentPeriodEndsAt:z57.string().nullable(),renewsAt:z57.string().nullable(),cancelAt:z57.string().nullable(),renewAutomatically:z57.boolean(),pricing:SubscriptionPricingDTOSchema.nullable(),paymentMethod:SubscriptionPaymentMethodDTOSchema.nullable()}),SubscriptionDetailsDTO=createDTO(SubscriptionDetailsDTOSchema),CreditAlertDTOSchema=z57.object({type:z57.enum(["low_balance","critical_balance","approaching_limit"]),message:z57.string(),estimatedPromptsRemaining:z57.number().nullable(),avgCostPerPrompt:z57.number().nullable()}),CreditAlertDTO=createDTO(CreditAlertDTOSchema),PlanAllocationDTOSchema=z57.object({monthlyCredits:z57.number().nullable(),usedThisPeriod:z57.number(),remainingThisPeriod:z57.number()}),PlanAllocationDTO=createDTO(PlanAllocationDTOSchema),LatestCancellationDTOSchema=z57.object({organizationId:z57.string(),planCode:TemplateCodeSchema,reason:CancellationReasonCodeSchema,details:z57.string().nullable(),tenureDays:z57.number().int().nonnegative(),capturedAt:z57.string()}),LatestCancellationDTO=createDTO(LatestCancellationDTOSchema),OrganizationSubscriptionDTOSchema=z57.object({hasSubscription:z57.boolean(),subscription:SubscriptionDetailsDTOSchema.nullable(),credits:CreditBalanceBreakdownDTOSchema,planAllocation:PlanAllocationDTOSchema.nullable(),lowBalanceThreshold:z57.number().nullable(),alerts:z57.array(CreditAlertDTOSchema),portalUrl:z57.string().nullable(),latestCancellation:LatestCancellationDTOSchema.nullable()}),OrganizationSubscriptionDTO=createDTO(OrganizationSubscriptionDTOSchema),BaseCreditTopupRequestSchema=z57.object({creditCount:z57.number().int().positive(),expiresAt:z57.string().datetime().nullable().optional(),message:z57.string().nullable().optional()}),FreeCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z57.literal("free"),amountCents:z57.number().int().positive().nullable().optional()}),PurchaseCreditTopupRequestSchema=BaseCreditTopupRequestSchema.extend({type:z57.literal("purchase"),amountCents:z57.number().int().positive()}),CreditTopupRequestDTOSchema=z57.discriminatedUnion("type",[FreeCreditTopupRequestSchema,PurchaseCreditTopupRequestSchema]),CreditTopupRequestDTO=createDTO(CreditTopupRequestDTOSchema),CreditTopupResponseDTOSchema=z57.object({success:z57.boolean(),transactionId:z57.string().nullable(),newBalance:z57.number(),creditCount:z57.number(),type:z57.enum(["free","purchase"]),invoiceId:z57.string().nullable()}),CreditTopupResponseDTO=createDTO(CreditTopupResponseDTOSchema)}});import{z as z58}from"zod";var UsageSummaryDTOSchema,UsageSummaryDTO,UsageByProjectDTOSchema,UsageByProjectDTO,UsageByUserDTOSchema,UsageByUserDTO,UsageTimelineItemDTOSchema,UsageTimelineItemDTO,UsageByUserForProjectDTOSchema,UsageByUserForProjectDTO,ProjectUsageDetailDTOSchema,ProjectUsageDetailDTO,OrganizationUsageDTOSchema,OrganizationUsageDTO,init_usage_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage.dto.js"(){"use strict";init_create_dto();UsageSummaryDTOSchema=z58.object({totalCredits:z58.number(),totalCostUsd:z58.number(),totalMessages:z58.number(),avgCostPerMessage:z58.number(),periodStart:z58.string().nullable(),periodEnd:z58.string().nullable()}),UsageSummaryDTO=createDTO(UsageSummaryDTOSchema),UsageByProjectDTOSchema=z58.object({projectId:z58.string(),projectName:z58.string(),projectDisplayName:z58.string().nullable(),credits:z58.number(),costUsd:z58.number(),messages:z58.number(),percentage:z58.number()}),UsageByProjectDTO=createDTO(UsageByProjectDTOSchema),UsageByUserDTOSchema=z58.object({userId:z58.string(),userName:z58.string().nullable(),userEmail:z58.string().email().nullable(),credits:z58.number(),costUsd:z58.number(),messages:z58.number(),percentage:z58.number()}),UsageByUserDTO=createDTO(UsageByUserDTOSchema),UsageTimelineItemDTOSchema=z58.object({date:z58.string(),credits:z58.number(),costUsd:z58.number(),messages:z58.number()}),UsageTimelineItemDTO=createDTO(UsageTimelineItemDTOSchema),UsageByUserForProjectDTOSchema=z58.object({userId:z58.string(),userName:z58.string().nullable(),userEmail:z58.string().email().nullable(),credits:z58.number(),costUsd:z58.number(),messages:z58.number(),percentage:z58.number()}),UsageByUserForProjectDTO=createDTO(UsageByUserForProjectDTOSchema),ProjectUsageDetailDTOSchema=z58.object({projectId:z58.string(),projectName:z58.string(),projectDisplayName:z58.string().nullable(),summary:UsageSummaryDTOSchema,byUser:z58.array(UsageByUserForProjectDTOSchema),timeline:z58.array(UsageTimelineItemDTOSchema)}),ProjectUsageDetailDTO=createDTO(ProjectUsageDetailDTOSchema),OrganizationUsageDTOSchema=z58.object({summary:UsageSummaryDTOSchema,byProject:z58.array(UsageByProjectDTOSchema),byUser:z58.array(UsageByUserDTOSchema),timeline:z58.array(UsageTimelineItemDTOSchema)}),OrganizationUsageDTO=createDTO(OrganizationUsageDTOSchema)}});import{z as z59}from"zod";var TimeRangePresetSchema,SortOrderSchema,UsageAnalyticsQuerySchema,UsageOverviewSummaryDTOSchema,UsageOverviewSummaryDTO,UsageTimelinePointDTOSchema,UsageTimelinePointDTO,OrganizationUsageRowDTOSchema,OrganizationUsageRowDTO,UserUsageRowDTOSchema,UserUsageRowDTO,ProjectUsageRowDTOSchema,ProjectUsageRowDTO,UsageDistributionItemDTOSchema,UsageDistributionItemDTO,UsageHeatmapPointDTOSchema,UsageHeatmapPointDTO,UsageOverviewResponseDTOSchema,UsageOverviewResponseDTO,UsagePaginationDTOSchema,UsagePaginationDTO,UsageByOrganizationResponseDTOSchema,UsageByOrganizationResponseDTO,ExtendedUserUsageRowDTOSchema,ExtendedUserUsageRowDTO,UsageByUserResponseDTOSchema,UsageByUserResponseDTO,ExtendedProjectUsageRowDTOSchema,ExtendedProjectUsageRowDTO,UsageByProjectResponseDTOSchema,UsageByProjectResponseDTO,ExportFormatSchema,UsageExportQuerySchema,PeekUsageMetricsDTOSchema,PeekUsageMetricsDTO,OrganizationPeekDTOSchema,OrganizationPeekDTO,UserPeekDTOSchema,UserPeekDTO,ProjectPeekDTOSchema,ProjectPeekDTO,init_usage_analytics_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/usage-analytics.dto.js"(){"use strict";init_create_dto();TimeRangePresetSchema=z59.enum(["today","1d","7d","14d","30d","60d","90d"]),SortOrderSchema=z59.enum(["asc","desc"]),UsageAnalyticsQuerySchema=z59.object({startDate:z59.string().optional(),endDate:z59.string().optional(),preset:TimeRangePresetSchema.optional().default("30d"),page:z59.coerce.number().int().positive().default(1),limit:z59.coerce.number().int().positive().max(100).default(20),sortBy:z59.string().optional(),sortOrder:SortOrderSchema.optional().default("desc"),search:z59.string().optional()}),UsageOverviewSummaryDTOSchema=z59.object({totalCredits:z59.number(),totalCostUsd:z59.number(),totalMessages:z59.number(),avgCostPerMessage:z59.number(),avgCreditsPerMessage:z59.number(),periodStart:z59.string(),periodEnd:z59.string(),creditsChange:z59.number().nullable(),costChange:z59.number().nullable(),messagesChange:z59.number().nullable()}),UsageOverviewSummaryDTO=createDTO(UsageOverviewSummaryDTOSchema),UsageTimelinePointDTOSchema=z59.object({date:z59.string(),credits:z59.number(),costUsd:z59.number(),messages:z59.number()}),UsageTimelinePointDTO=createDTO(UsageTimelinePointDTOSchema),OrganizationUsageRowDTOSchema=z59.object({organizationId:z59.string(),organizationName:z59.string(),credits:z59.number(),costUsd:z59.number(),messages:z59.number(),percentage:z59.number(),userCount:z59.number(),projectCount:z59.number()}),OrganizationUsageRowDTO=createDTO(OrganizationUsageRowDTOSchema),UserUsageRowDTOSchema=z59.object({userId:z59.string(),userName:z59.string().nullable(),userEmail:z59.string().nullable(),userImage:z59.string().nullable(),organizationId:z59.string().nullable(),organizationName:z59.string().nullable(),credits:z59.number(),costUsd:z59.number(),messages:z59.number(),percentage:z59.number(),projectCount:z59.number()}),UserUsageRowDTO=createDTO(UserUsageRowDTOSchema),ProjectUsageRowDTOSchema=z59.object({projectId:z59.string(),projectName:z59.string(),projectDisplayName:z59.string().nullable(),organizationId:z59.string(),organizationName:z59.string(),credits:z59.number(),costUsd:z59.number(),messages:z59.number(),percentage:z59.number(),userCount:z59.number()}),ProjectUsageRowDTO=createDTO(ProjectUsageRowDTOSchema),UsageDistributionItemDTOSchema=z59.object({id:z59.string(),name:z59.string(),value:z59.number(),percentage:z59.number()}),UsageDistributionItemDTO=createDTO(UsageDistributionItemDTOSchema),UsageHeatmapPointDTOSchema=z59.object({day:z59.number(),hour:z59.number(),value:z59.number()}),UsageHeatmapPointDTO=createDTO(UsageHeatmapPointDTOSchema),UsageOverviewResponseDTOSchema=z59.object({summary:UsageOverviewSummaryDTOSchema,timeline:z59.array(UsageTimelinePointDTOSchema),topOrganizations:z59.array(OrganizationUsageRowDTOSchema),topUsers:z59.array(UserUsageRowDTOSchema),topProjects:z59.array(ProjectUsageRowDTOSchema),creditDistribution:z59.array(UsageDistributionItemDTOSchema),heatmap:z59.array(UsageHeatmapPointDTOSchema)}),UsageOverviewResponseDTO=createDTO(UsageOverviewResponseDTOSchema),UsagePaginationDTOSchema=z59.object({page:z59.number(),limit:z59.number(),totalItems:z59.number(),totalPages:z59.number(),hasMore:z59.boolean()}),UsagePaginationDTO=createDTO(UsagePaginationDTOSchema),UsageByOrganizationResponseDTOSchema=z59.object({organizations:z59.array(OrganizationUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByOrganizationResponseDTO=createDTO(UsageByOrganizationResponseDTOSchema),ExtendedUserUsageRowDTOSchema=UserUsageRowDTOSchema.extend({organizationCount:z59.number()}),ExtendedUserUsageRowDTO=createDTO(ExtendedUserUsageRowDTOSchema),UsageByUserResponseDTOSchema=z59.object({users:z59.array(ExtendedUserUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByUserResponseDTO=createDTO(UsageByUserResponseDTOSchema),ExtendedProjectUsageRowDTOSchema=ProjectUsageRowDTOSchema.extend({ownerId:z59.string(),ownerName:z59.string().nullable(),ownerEmail:z59.string().nullable()}),ExtendedProjectUsageRowDTO=createDTO(ExtendedProjectUsageRowDTOSchema),UsageByProjectResponseDTOSchema=z59.object({projects:z59.array(ExtendedProjectUsageRowDTOSchema),summary:UsageOverviewSummaryDTOSchema,pagination:UsagePaginationDTOSchema}),UsageByProjectResponseDTO=createDTO(UsageByProjectResponseDTOSchema),ExportFormatSchema=z59.enum(["csv","json"]),UsageExportQuerySchema=UsageAnalyticsQuerySchema.extend({format:ExportFormatSchema.default("csv"),type:z59.enum(["overview","organizations","users","projects"]).default("overview")}),PeekUsageMetricsDTOSchema=z59.object({credits:z59.number(),costUsd:z59.number(),messages:z59.number()}),PeekUsageMetricsDTO=createDTO(PeekUsageMetricsDTOSchema),OrganizationPeekDTOSchema=z59.object({id:z59.string(),name:z59.string(),createdAt:z59.string(),memberCount:z59.number(),projectCount:z59.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z59.array(UsageTimelinePointDTOSchema)}),OrganizationPeekDTO=createDTO(OrganizationPeekDTOSchema),UserPeekDTOSchema=z59.object({id:z59.string(),name:z59.string().nullable(),email:z59.string(),image:z59.string().nullable(),createdAt:z59.string(),organizationCount:z59.number(),projectCount:z59.number(),usage:PeekUsageMetricsDTOSchema,recentActivity:z59.array(UsageTimelinePointDTOSchema)}),UserPeekDTO=createDTO(UserPeekDTOSchema),ProjectPeekDTOSchema=z59.object({id:z59.string(),name:z59.string(),displayName:z59.string().nullable(),createdAt:z59.string(),organizationId:z59.string(),organizationName:z59.string(),ownerId:z59.string(),ownerName:z59.string().nullable(),ownerEmail:z59.string().nullable(),usage:PeekUsageMetricsDTOSchema,recentActivity:z59.array(UsageTimelinePointDTOSchema)}),ProjectPeekDTO=createDTO(ProjectPeekDTOSchema)}});import{z as z60}from"zod";var SandboxProcessStatusSchema,PresetSandboxCommandSchema,ExecuteSandboxCommandRequestDTOSchema,ExecuteSandboxCommandRequestDTO,SandboxProcessInfoDTOSchema,SandboxProcessInfoDTO,SandboxProcessInfoResponseSchema,SandboxProcessListDTOSchema,SandboxProcessListDTO,SandboxProcessListResponseSchema,ExecuteSandboxCommandResponseDTOSchema,ExecuteSandboxCommandResponseDTO,PresetCommandResponseDTOSchema,PresetCommandResponseDTO,PresetCommandResponseSchema,init_sandbox_command_dto=__esm({"../../packages/api-contracts/dist/esm/dtos/admin/sandbox-command.dto.js"(){"use strict";init_env();init_create_dto();init_response();SandboxProcessStatusSchema=z60.enum(["running","completed","failed","stopped"]),PresetSandboxCommandSchema=z60.enum(["restart-dev-server","stop-dev-server","install-dependencies","reinstall-dependencies","build","typecheck"]),ExecuteSandboxCommandRequestDTOSchema=z60.object({command:z60.string().min(1).max(1e4),cwd:z60.string().optional(),projectEnv:EnvSchema.optional(),env:z60.record(z60.string(),z60.string()).optional(),name:z60.string().optional(),waitForCompletion:z60.boolean().optional().default(!1)}),ExecuteSandboxCommandRequestDTO=createDTO(ExecuteSandboxCommandRequestDTOSchema),SandboxProcessInfoDTOSchema=z60.object({identifier:z60.string(),status:SandboxProcessStatusSchema,command:z60.string().optional(),startedAt:z60.string().optional(),exitCode:z60.number().optional()}),SandboxProcessInfoDTO=createDTO(SandboxProcessInfoDTOSchema),SandboxProcessInfoResponseSchema=createResponseSchema(SandboxProcessInfoDTOSchema),SandboxProcessListDTOSchema=z60.object({processes:z60.array(SandboxProcessInfoDTOSchema)}),SandboxProcessListDTO=createDTO(SandboxProcessListDTOSchema),SandboxProcessListResponseSchema=createResponseSchema(SandboxProcessListDTOSchema),ExecuteSandboxCommandResponseDTOSchema=z60.object({processId:z60.string(),status:SandboxProcessStatusSchema}),ExecuteSandboxCommandResponseDTO=createDTO(ExecuteSandboxCommandResponseDTOSchema),PresetCommandResponseDTOSchema=z60.object({success:z60.boolean(),message:z60.string().optional()}),PresetCommandResponseDTO=createDTO(PresetCommandResponseDTOSchema),PresetCommandResponseSchema=createResponseSchema(PresetCommandResponseDTOSchema)}});import{z as z61}from"zod";var init_esm=__esm({"../../packages/api-contracts/dist/esm/index.js"(){"use strict";init_create_dto();init_response();init_pagination();init_common();init_attachments();init_env();init_realtime();init_references();init_content_fields();init_audit_log();init_ops();init_chat_block();init_project_dto();init_project_env_dto();init_project_import_export_dto();init_agent_trigger_dto();init_agent_activation_dto();init_agent_list_item_dto();init_agent_session_dto();init_agent_proposal_dto();init_agent_install_summary_dto();init_integration_dto();init_schedule_dto();init_audit_log_dto();init_env_status_dto();init_env_diff_summary_dto();init_project_analytics_dto();init_project_access_dto();init_project_invite_dto();init_publication_dto();init_sandbox_dto();init_organization_dto();init_billing_dto();init_payment_method_dto();init_user_dto();init_content_dto();init_unique_conflict_dto();init_schema_transition_rejected_dto();init_cms_display_defaults_dto();init_asset_dto();init_translation_dto();init_document_dto();init_chat_dto();init_upload_dto();init_service_dto();init_search_dto();init_registered_domain_dto();init_project_domain_dto();init_project_subdomain_dto();init_project_locale_dto();init_generation_dto();init_generation_task_dto();init_asset_model_dto();init_tour_dto();init_support_report_dto();init_ops_chat_dto();init_webhook_dto();init_preview_feature_dto();init_subscription_dto();init_usage_dto();init_usage_analytics_dto();init_sandbox_command_dto()}});import{createHash}from"node:crypto";function normalizeApiUrl(input){let trimmed=input.trim();try{let url=new URL(trimmed),pathname=url.pathname.replace(/\/+$/,"");return`${url.protocol}//${url.host}${pathname}`}catch{return trimmed.replace(/\/+$/,"")}}function hashApiUrl(input){return createHash("sha256").update(normalizeApiUrl(input)).digest("hex").slice(0,6)}function safeHostLabel(host){return host.replace(/:/g,"-").replace(/[^a-zA-Z0-9.-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"").toLowerCase()}function credentialsFilename(apiUrl){let normalized=normalizeApiUrl(apiUrl),hostLabel="unknown";try{hostLabel=safeHostLabel(new URL(normalized).host)}catch{}return hostLabel.length===0&&(hostLabel="unknown"),`${hostLabel}-${hashApiUrl(apiUrl)}.json`}var init_credentials_path=__esm({"src/cli/utils/credentials-path.ts"(){__name(normalizeApiUrl,"normalizeApiUrl");__name(hashApiUrl,"hashApiUrl");__name(safeHostLabel,"safeHostLabel");__name(credentialsFilename,"credentialsFilename")}});import fs from"node:fs";import{homedir}from"node:os";import path,{join}from"node:path";import{fileURLToPath}from"node:url";function readReleaseManifest(){try{let raw=fs.readFileSync(RELEASE_FILE,"utf8"),parsed=JSON.parse(raw),manifest={};return typeof parsed.apiUrl=="string"&&parsed.apiUrl.length>0&&(manifest.apiUrl=parsed.apiUrl),typeof parsed.webUrl=="string"&&parsed.webUrl.length>0&&(manifest.webUrl=parsed.webUrl),manifest}catch{return{}}}function loadConfig(){let baked=readReleaseManifest(),apiUrl=process.env.FIMO_API_URL?.trim()||baked.apiUrl||DEFAULT_API_URL,webUrl=process.env.FIMO_WEB_URL?.trim()||baked.webUrl||DEFAULT_WEB_URL,configDir=join(process.env.XDG_CONFIG_HOME||join(homedir(),".config"),"fimo"),credentialsDir=join(configDir,"credentials");return{apiUrl,webUrl,configDir,credentialsDir,credentialsFile:join(credentialsDir,credentialsFilename(apiUrl))}}var DEFAULT_API_URL,DEFAULT_WEB_URL,THIS_FILE,CLI_ROOT,RELEASE_FILE,init_config=__esm({"src/cli/config.ts"(){init_credentials_path();DEFAULT_API_URL="http://localhost:3000",DEFAULT_WEB_URL="http://localhost:5173",THIS_FILE=fileURLToPath(import.meta.url),CLI_ROOT=path.resolve(path.dirname(THIS_FILE),"..",".."),RELEASE_FILE=path.resolve(CLI_ROOT,"release.json");__name(readReleaseManifest,"readReleaseManifest");__name(loadConfig,"loadConfig")}});import fs2 from"node:fs";function ensureCredentialsDir(cfg){fs2.existsSync(cfg.credentialsDir)||fs2.mkdirSync(cfg.credentialsDir,{recursive:!0})}function readCredentials(cfg=loadConfig()){if(!fs2.existsSync(cfg.credentialsFile))return null;let raw=fs2.readFileSync(cfg.credentialsFile,"utf-8");return JSON.parse(raw)}function writeCredentials(credentials,cfg=loadConfig()){ensureCredentialsDir(cfg);let tmpFile=`${cfg.credentialsFile}.tmp-${process.pid}`;fs2.writeFileSync(tmpFile,JSON.stringify(credentials,null,2)),fs2.renameSync(tmpFile,cfg.credentialsFile)}function clearCredentials(cfg=loadConfig()){fs2.existsSync(cfg.credentialsFile)&&fs2.unlinkSync(cfg.credentialsFile)}function setActiveOrganization(organization,cfg=loadConfig()){let creds=requireCredentials(cfg);writeCredentials({...creds,activeOrganization:organization},cfg)}function recordAuthFailure(cfg=loadConfig()){let creds=readCredentials(cfg);creds&&writeCredentials({...creds,lastFailedAuthAt:new Date().toISOString()},cfg)}function requireToken(cfg=loadConfig()){return requireCredentials(cfg).access_token}function requireCredentials(cfg=loadConfig()){let creds=readCredentials(cfg);if(!creds?.access_token)throw new NotAuthenticatedError(cfg.apiUrl);return creds}var NotAuthenticatedError,init_auth=__esm({"src/cli/auth.ts"(){init_config();NotAuthenticatedError=class extends Error{static{__name(this,"NotAuthenticatedError")}apiUrl;constructor(apiUrl,message="You are not signed in to Fimo."){super(message),this.name="NotAuthenticatedError",this.apiUrl=apiUrl}};__name(ensureCredentialsDir,"ensureCredentialsDir");__name(readCredentials,"readCredentials");__name(writeCredentials,"writeCredentials");__name(clearCredentials,"clearCredentials");__name(setActiveOrganization,"setActiveOrganization");__name(recordAuthFailure,"recordAuthFailure");__name(requireToken,"requireToken");__name(requireCredentials,"requireCredentials")}});import{spawnSync}from"node:child_process";import fs3 from"node:fs";import path2 from"node:path";import{setTimeout as sleep}from"node:timers/promises";function isPublishedInstall(cliRoot=CLI_ROOT){return fs3.existsSync(path2.join(cliRoot,"release.json"))}function buildSkipsVersionCheck(cliRoot=CLI_ROOT,readFile5=defaultReadFile){try{return JSON.parse(readFile5(path2.join(cliRoot,"release.json"))).skipVersionCheck===!0}catch{return!1}}function defaultReadFile(file){return fs3.readFileSync(file,"utf8")}function resolveGlobalFimoRoot(){let result=spawnSync("npm",["root","-g"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:GLOBAL_ROOT_TIMEOUT_MS});return result.error||result.status!==0||typeof result.stdout!="string"||result.stdout.trim().length===0?null:path2.resolve(result.stdout.trim(),"fimo")}function normalizedPath(input){try{return fs3.realpathSync(input)}catch{return path2.resolve(input)}}function autoUpgradeEnabled(options={}){let usesDefaults=Object.keys(options).length===0;if(usesDefaults&&defaultEligibility!==void 0)return defaultEligibility;let env=options.env??process.env,cliRoot=options.cliRoot??CLI_ROOT,published=options.published??isPublishedInstall(cliRoot);if(env.FIMO_AUTO_UPGRADE!=="1"||!published||buildSkipsVersionCheck(cliRoot))return usesDefaults&&(defaultEligibility=!1),!1;let globalFimoRoot=options.globalFimoRoot===void 0?resolveGlobalFimoRoot():options.globalFimoRoot;if(!globalFimoRoot)return usesDefaults&&(defaultEligibility=!1),!1;let eligible=normalizedPath(cliRoot)===normalizedPath(globalFimoRoot);return usesDefaults&&(defaultEligibility=eligible),eligible}async function acquireLock(lockDir){let deadline=Date.now()+LOCK_WAIT_MS;for(;;){try{fs3.mkdirSync(lockDir);return}catch(error){if(error.code!=="EEXIST")throw error}let stale=!1;try{stale=Date.now()-fs3.statSync(lockDir).mtimeMs>LOCK_STALE_MS}catch{continue}if(stale){try{fs3.rmdirSync(lockDir)}catch{}continue}if(Date.now()>=deadline)throw new Error("auto-upgrade lock timeout");await sleep(LOCK_POLL_MS)}}function readGlobalFimoVersion(){let root2=resolveGlobalFimoRoot();if(!root2)return null;try{let pkg=JSON.parse(fs3.readFileSync(path2.join(root2,"package.json"),"utf8"));return typeof pkg.version=="string"?pkg.version:null}catch{return null}}async function autoUpgradeGlobal(latest){if(!VERSION_PATTERN.test(latest))return!1;let lockDir=path2.join(loadConfig().configDir,"auto-upgrade.lock");try{fs3.mkdirSync(path2.dirname(lockDir),{recursive:!0}),await acquireLock(lockDir)}catch{return!1}try{if(readGlobalFimoVersion()===latest)return!0;let install=spawnSync("npm",["install","-g",`fimo@${latest}`],{stdio:["ignore","ignore","inherit"],timeout:INSTALL_TIMEOUT_MS});return install.error||install.status!==0?!1:readGlobalFimoVersion()===latest}finally{try{fs3.rmdirSync(lockDir)}catch{}}}var INSTALL_TIMEOUT_MS,GLOBAL_ROOT_TIMEOUT_MS,LOCK_WAIT_MS,LOCK_STALE_MS,LOCK_POLL_MS,VERSION_PATTERN,defaultEligibility,init_auto_upgrade=__esm({"src/cli/auto-upgrade.ts"(){init_config();INSTALL_TIMEOUT_MS=12e4,GLOBAL_ROOT_TIMEOUT_MS=5e3,LOCK_WAIT_MS=18e4,LOCK_STALE_MS=3e5,LOCK_POLL_MS=500,VERSION_PATTERN=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;__name(isPublishedInstall,"isPublishedInstall");__name(buildSkipsVersionCheck,"buildSkipsVersionCheck");__name(defaultReadFile,"defaultReadFile");__name(resolveGlobalFimoRoot,"resolveGlobalFimoRoot");__name(normalizedPath,"normalizedPath");__name(autoUpgradeEnabled,"autoUpgradeEnabled");__name(acquireLock,"acquireLock");__name(readGlobalFimoVersion,"readGlobalFimoVersion");__name(autoUpgradeGlobal,"autoUpgradeGlobal")}});import fs4 from"node:fs";import path3 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";function getCliVersion(){try{let raw=fs4.readFileSync(PACKAGE_JSON_PATH,"utf8");return JSON.parse(raw).version??"0.0.0"}catch{return"0.0.0"}}var THIS_FILE2,CLI_ROOT2,PACKAGE_JSON_PATH,init_version=__esm({"src/cli/version.ts"(){THIS_FILE2=fileURLToPath2(import.meta.url),CLI_ROOT2=path3.resolve(path3.dirname(THIS_FILE2),"..",".."),PACKAGE_JSON_PATH=path3.join(CLI_ROOT2,"package.json");__name(getCliVersion,"getCliVersion")}});function lazyFetchQs(against,extras={}){let params=new URLSearchParams;against&&params.set("against",against);for(let[k,v]of Object.entries(extras))params.set(k,v);return params.toString()}function throwUnauthorized(cfg,status){try{recordAuthFailure(cfg)}catch{}throw new UnauthorizedError(cfg.apiUrl,status)}async function throwPermissionDenied(cfg,response){let required=[];try{let body=await response.json();required=Array.isArray(body.required)?body.required:body.required?[body.required]:[]}catch{}throw new PermissionDeniedError(cfg.apiUrl,required)}async function fimoFetch(url,init){let headers=new Headers(init.headers);headers.delete(CLI_VERSION_HEADER),headers.delete(CLI_AUTO_UPGRADE_HEADER);let canAutoUpgrade=process.argv[2]!=="git-credential"&&autoUpgradeEnabled();canAutoUpgrade&&(headers.set(CLI_VERSION_HEADER,getCliVersion()),headers.set(CLI_AUTO_UPGRADE_HEADER,"1"));let response=await fetch(url,{...init,headers});if(canAutoUpgrade&&response.status===426){let latest=response.headers.get(CLI_LATEST_HEADER);if(latest){await autoUpgradeGlobal(latest)||ui.warn({command:process.argv[2]??"fimo",message:`Could not upgrade to ${latest}; continuing with the current command.`});let retryHeaders=new Headers(init.headers);return retryHeaders.delete(CLI_VERSION_HEADER),retryHeaders.delete(CLI_AUTO_UPGRADE_HEADER),fetch(url,{...init,headers:retryHeaders})}}return response}function formatZodIssues(parsed){if(!parsed||typeof parsed!="object")return null;let error=parsed.error,issues=error&&typeof error=="object"&&"issues"in error?error.issues:void 0;return!Array.isArray(issues)||issues.length===0?null:issues.map(issue=>{let{path:path47,message}=issue;return`${Array.isArray(path47)&&path47.length>0?`${path47.join(".")}: `:""}${typeof message=="string"?message:"Invalid value"}`}).join("; ")}function formatPartialResult(parsed){if(!parsed.partial||typeof parsed.partial!="object"||Array.isArray(parsed.partial))return null;let partial=parsed.partial,counts=["created","updated","deleted"].flatMap(action=>typeof partial[action]=="number"&&partial[action]>0?[`${partial[action]} ${action}`]:[]);return counts.length>0?`Partial result: ${counts.join(", ")}.`:null}var ApiRequestError,UnauthorizedError,PermissionDeniedError,CLI_VERSION_HEADER,CLI_LATEST_HEADER,CLI_AUTO_UPGRADE_HEADER,FIMO_ENV_HEADER,FimoApiClient,init_api=__esm({"src/cli/api.ts"(){init_esm();init_dist();init_auth();init_auto_upgrade();init_config();init_version();__name(lazyFetchQs,"lazyFetchQs");ApiRequestError=class extends Error{static{__name(this,"ApiRequestError")}status;method;path;detail;code;body;constructor(method,path47,status,detail,code2,body){super(`API ${method} ${path47} failed: ${status} ${detail}`),this.name="ApiRequestError",this.method=method,this.path=path47,this.status=status,this.detail=detail,this.code=code2,this.body=body}},UnauthorizedError=class extends Error{static{__name(this,"UnauthorizedError")}apiUrl;status;constructor(apiUrl,status,message){super(message??`Session for ${apiUrl} expired or invalid (HTTP ${status}).`),this.name="UnauthorizedError",this.apiUrl=apiUrl,this.status=status}},PermissionDeniedError=class extends Error{static{__name(this,"PermissionDeniedError")}apiUrl;required;constructor(apiUrl,required=[],message){let detail=required.length?` Missing permission: ${required.join(", ")}.`:"";super(message??`You don't have permission to do this on ${apiUrl}.${detail}`),this.name="PermissionDeniedError",this.apiUrl=apiUrl,this.required=required}};__name(throwUnauthorized,"throwUnauthorized");__name(throwPermissionDenied,"throwPermissionDenied");CLI_VERSION_HEADER="X-Fimo-CLI-Version",CLI_LATEST_HEADER="X-Fimo-CLI-Latest",CLI_AUTO_UPGRADE_HEADER="X-Fimo-CLI-Auto-Upgrade",FIMO_ENV_HEADER="X-Fimo-Env";__name(fimoFetch,"fimoFetch");__name(formatZodIssues,"formatZodIssues");__name(formatPartialResult,"formatPartialResult");FimoApiClient=class _FimoApiClient{constructor(cfg=loadConfig()){this.cfg=cfg}static{__name(this,"FimoApiClient")}env;withEnv(env){let next2=new _FimoApiClient(this.cfg);return next2.env=env,next2}formatError(status,text3,body){if(!text3)return String(status);if(body&&typeof body=="object"&&!Array.isArray(body)){let parsed=body;if(typeof parsed.message=="string"&&parsed.message.length>0){let partial=formatPartialResult(parsed);return partial?`${parsed.message} ${partial}`:parsed.message}if(typeof parsed.error=="string"&&parsed.error.length>0)return parsed.error;if(parsed.error&&typeof parsed.error=="object"&&"message"in parsed.error&&typeof parsed.error.message=="string")return parsed.error.message;let zodIssues=formatZodIssues(parsed);if(zodIssues)return zodIssues}return text3}async parseError(response){let text3=await response.text(),body;try{body=text3?JSON.parse(text3):void 0}catch{return{detail:this.formatError(response.status,text3)}}let code2=body&&typeof body=="object"&&!Array.isArray(body)&&typeof body.code=="string"?body.code:void 0;return{detail:this.formatError(response.status,text3,body),code:code2,body}}resolveAuthToken(){return process.env.FIMO_API_TOKEN?.trim()||requireToken(this.cfg)}async request(path47,init={},opts={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),init.body&&!headers.has("Content-Type")&&headers.set("Content-Type","application/json"),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path47}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&!opts.allow403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new ApiRequestError(init.method??"GET",path47,response.status,error.detail,error.code,error.body)}if(response.status!==204)return await response.json()}async rawRequest(path47,init={}){let token=this.resolveAuthToken(),headers=new Headers(init.headers);headers.set("Authorization",`Bearer ${token}`),this.env&&!headers.has(FIMO_ENV_HEADER)&&headers.set(FIMO_ENV_HEADER,this.env);let response=await fimoFetch(`${this.cfg.apiUrl}${path47}`,{...init,headers});if(response.status===401&&throwUnauthorized(this.cfg,response.status),response.status===403&&await throwPermissionDenied(this.cfg,response),!response.ok){let error=await this.parseError(response);throw new Error(`API ${init.method??"GET"} ${path47} failed: ${response.status} ${error.detail}`)}return response}tenantPath(projectId,route){if(!this.env)throw new Error("FimoApiClient: tenant-scoped call requires an env. Use `client.withEnv(env)` before calling tenant CRUD methods.");return`/api/tenant/${projectId}/envs/${encodeEnvPathSegment(this.env)}${route}`}projectEnvManagementPath(projectId,route){if(!this.env)throw new Error("FimoApiClient: env-scoped management call requires an env. Use `client.withEnv(env)` before calling env CRUD methods.");return`/api/management/projects/${projectId}/envs/${encodeEnvPathSegment(this.env)}${route}`}async listModels(projectId,query={}){let params=new URLSearchParams;query.modality&&params.set("modality",query.modality);for(let t2 of query.tag??[])params.append("tag",t2);query.q&&params.set("q",query.q),query.category&&params.set("category",query.category);let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models${qs?`?${qs}`:""}`)).data}async getModel(projectId,key){try{return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/${key}`)).data}catch(err){if(err instanceof ApiRequestError&&err.status===404)return null;throw err}}async estimateModel(projectId,key,options){return(await this.request(`/api/management/projects/${projectId}/integrations/fal/models/estimate`,{method:"POST",body:JSON.stringify({model:key,options})})).data}async estimateGenerationTask(projectId,key,options){return(await this.request(this.tenantPath(projectId,"/assets/generate/estimate"),{method:"POST",body:JSON.stringify({task:key,options})})).data}async listOrganizations(){return(await this.request("/api/management/organizations")).data}async listOrganizationMembers(organizationId){return(await this.request(`/api/auth/organization/get-full-organization?organizationId=${encodeURIComponent(organizationId)}`))?.members??[]}async inviteOrganizationMember(input){return this.request("/api/auth/organization/invite-member",{method:"POST",body:JSON.stringify(input)})}async getCurrentSession(){return this.request("/api/auth/get-session")}async submitSupportIssue(input){return(await this.request("/api/support/issues",{method:"POST",body:JSON.stringify(input)})).data}async getReferralSummary(userId){return(await this.request(`/api/users/${encodeURIComponent(userId)}/referrals/summary`)).data}async listProjects(organizationId){return(await this.request(`/api/management/organizations/${encodeURIComponent(organizationId)}/projects`)).data}async publishProject(projectId){await this.request(`/api/management/projects/${projectId}/publish`,{method:"POST"})}async unpublishProject(projectId){await this.request(`/api/management/projects/${projectId}/unpublish`,{method:"POST"})}async createProject(input){return(await this.request("/api/management/projects",{method:"POST",body:JSON.stringify({...input,source:"cli"})})).data}async getProject(projectId){return(await this.request(`/api/management/projects/${projectId}`)).data}async getProjectCredits(projectId){return(await this.request(`/api/management/projects/${projectId}/billing/credits`)).data}async listProjectVersions(projectId,options){let params=new URLSearchParams({limit:String(options.limit)});return options.cursor&&params.set("cursor",options.cursor),(await this.request(`${this.projectEnvManagementPath(projectId,"/versions")}?${params.toString()}`)).data}async getProjectHistorySummary(projectId){return(await this.request(this.projectEnvManagementPath(projectId,"/versions/summary"))).data}async getProjectVersion(projectId,versionId){return(await this.request(this.projectEnvManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}`))).data}async createProjectVersion(projectId,input){return(await this.request(this.projectEnvManagementPath(projectId,"/versions"),{method:"POST",body:JSON.stringify(input)})).data}async restoreProjectVersion(projectId,versionId){return(await this.request(this.projectEnvManagementPath(projectId,`/versions/${encodeURIComponent(versionId)}/restore`),{method:"POST"})).data}async listProjectSecretEntries(projectId,opts={}){let qs=opts.kind?`?kind=${encodeURIComponent(opts.kind)}`:"";return(await this.request(`/api/management/projects/${projectId}/secrets${qs}`)).data}async createProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets`,{method:"POST",body:JSON.stringify({key:input.key,kind:input.kind,value:input.value})})).data}async updateProjectSecretEntry(input){return(await this.request(`/api/management/projects/${input.projectId}/secrets/${encodeURIComponent(input.key)}`,{method:"PATCH",body:JSON.stringify({kind:input.kind,value:input.value})})).data}async deleteProjectSecretEntry(projectId,key,kind){let qs=`?kind=${encodeURIComponent(kind)}`;await this.request(`/api/management/projects/${projectId}/secrets/${encodeURIComponent(key)}${qs}`,{method:"DELETE"})}async listProjectIntegrations(projectId){return(await this.request(`/api/management/projects/${projectId}/integrations`)).data}async getProjectIntegrationInfo(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/info`)).data}async getProjectIntegrationStatus(projectId,integrationKey){return(await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}/status`)).data}async enableProjectIntegration(input){let payload={...input.authMode?{authMode:input.authMode}:{},...input.connectionAlias?{connectionAlias:input.connectionAlias}:{}};return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}`,{method:"PUT",body:JSON.stringify(payload)})).data}async connectOrganizationIntegrationWithToken(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({...input.alias?{alias:input.alias}:{},token:input.token})})).data}async startOrganizationIntegrationConnect(input){return(await this.request(`/api/management/organizations/${encodeURIComponent(input.organizationId)}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST",body:JSON.stringify({})})).data}async switchProjectIntegrationAuth(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/auth`,{method:"PATCH",body:JSON.stringify({authMode:input.authMode})})).data}async disableProjectIntegration(projectId,integrationKey){await this.request(`/api/management/projects/${projectId}/integrations/${encodeURIComponent(integrationKey)}`,{method:"DELETE"})}async setProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"PUT",body:JSON.stringify({value:input.value})})).data}async clearProjectIntegrationCredential(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/credentials/${encodeURIComponent(input.credentialId)}`,{method:"DELETE"})).data}async runProjectIntegrationTool(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/run`,{method:"POST",body:JSON.stringify(input.request)})).data}async startProjectIntegrationConnect(input){return(await this.request(`/api/management/projects/${input.projectId}/integrations/${encodeURIComponent(input.integrationKey)}/connect`,{method:"POST"})).data}async bindProjectChannel(projectId,request){return(await this.request(`/api/management/projects/${projectId}/channels/bind`,{method:"POST",body:JSON.stringify(request)})).data}async createSchedule(projectId,request){return(await this.request(`/api/management/projects/${projectId}/schedules`,{method:"POST",body:JSON.stringify(request)})).data}async listSchedules(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules`)).data}async getSchedulesOverview(projectId){return(await this.request(`/api/management/projects/${projectId}/schedules/overview`)).data}async getSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`)).data}async updateSchedule(projectId,scheduleId,request){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"PATCH",body:JSON.stringify(request)})).data}async setScheduleEnabled(projectId,scheduleId,enabled){let action=enabled?"resume":"pause";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/${action}`,{method:"POST"})).data}async runSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/run`,{method:"POST",body:JSON.stringify({trigger:"cli"})})).data}async listScheduleRuns(projectId,scheduleId,query={}){let params=new URLSearchParams;query.limit!==void 0&&params.set("limit",String(query.limit)),query.cursor&&params.set("cursor",query.cursor),query.status&&params.set("status",query.status);let suffix=params.size>0?`?${params.toString()}`:"";return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}/runs${suffix}`)).data}async getScheduleRun(projectId,runId){return(await this.request(`/api/management/projects/${projectId}/schedules/runs/${encodeURIComponent(runId)}`)).data}async listWebhookEvents(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks/events`)).data}async listProjectWebhooks(projectId){return(await this.request(`/api/management/projects/${projectId}/webhooks`)).data}async getProjectWebhook(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`)).data}async createProjectWebhook(projectId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks`,{method:"POST",body:JSON.stringify(request)})).data}async updateProjectWebhook(projectId,webhookId,request){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"PATCH",body:JSON.stringify(request)})).data}async deleteProjectWebhook(projectId,webhookId){await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}`,{method:"DELETE"})}async rotateProjectWebhookSecret(projectId,webhookId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/rotate-signing-secret`,{method:"POST"})).data.signingSecret}async testProjectWebhook(projectId,webhookId,input){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/test`,{method:"POST",body:JSON.stringify(input)})).data}async listProjectWebhookDeliveries(projectId,webhookId,limit){let query=`?page=1&limit=${limit??50}`;return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries${query}`)).data.items}async getProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}`)).data}async retryProjectWebhookDelivery(projectId,webhookId,deliveryId){return(await this.request(`/api/management/projects/${projectId}/webhooks/${webhookId}/deliveries/${deliveryId}/retry`,{method:"POST"})).data}async deleteSchedule(projectId,scheduleId){return(await this.request(`/api/management/projects/${projectId}/schedules/${encodeURIComponent(scheduleId)}`,{method:"DELETE"})).data}async listEnvs(projectId,opts={}){let qs=opts.includeDeleted?"?includeDeleted=true":"";return(await this.request(`/api/management/projects/${projectId}/envs${qs}`)).data}async getEnv(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`)).data}async createEnv(projectId,input){return(await this.request(`/api/management/projects/${projectId}/envs`,{method:"POST",body:JSON.stringify(input)})).data}async syncEnv(projectId,env,input={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sync`,{method:"POST",body:JSON.stringify(input)})).data}async deleteEnv(projectId,env){await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}`,{method:"DELETE"})}async getEnvDiff(projectId,env,opts={}){let params=new URLSearchParams;opts.against&&params.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&&params.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff${qs?`?${qs}`:""}`)).data}async getEnvStatus(projectId,env,opts={}){let params=new URLSearchParams;opts.against&&params.set("against",opts.against),opts.surfaces&&opts.surfaces.length>0&&params.set("surfaces",opts.surfaces.join(","));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/status${qs?`?${qs}`:""}`)).data}async getCodeFileDiff(projectId,env,path47,opts={}){let qs=lazyFetchQs(opts.against,{path:path47});return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/code/file?${qs}`)).data}async getCodeConflictDetail(projectId,env,fromEnv,filePath){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflict/code?path=${encodeURIComponent(filePath)}`)).data}async getContentRowDiff(projectId,env,collection,rowId,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/content/${encodeURIComponent(collection)}/${encodeURIComponent(rowId)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getSchemaTypeDiff(projectId,env,typeName,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/schemas/${encodeURIComponent(typeName)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getAssetDiff(projectId,env,assetId,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/assets/${encodeURIComponent(assetId)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getTranslationRowDiff(projectId,env,locale,key,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/translations/${encodeURIComponent(locale)}/${encodeURIComponent(key)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getFormSchemaDiff(projectId,env,formName,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/forms/${encodeURIComponent(formName)}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async getActivationDiff(projectId,env,agentName,triggerIndex,opts={}){let qs=lazyFetchQs(opts.against),path47=`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/diff/activations/${encodeURIComponent(agentName)}/${triggerIndex}`;return(await this.request(qs?`${path47}?${qs}`:path47)).data}async mergeEnv(projectId,env,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge`,{method:"POST",body:JSON.stringify(body)})).data}async resolveMerge(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve`,{method:"POST",body:JSON.stringify(body)})).data}async cancelMerge(projectId,env,mergeId){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/cancel`,{method:"POST",body:JSON.stringify({mergeId})})).data}async getMergeConflicts(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/conflicts`)).data}async putResolveDraft(projectId,env,fromEnv,body){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"PUT",body:JSON.stringify(body)})).data}async deleteResolveDraft(projectId,env,fromEnv){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/merge/${encodeURIComponent(fromEnv)}/resolve/draft`,{method:"DELETE"})).data}async publishRelease(projectId,body){return(await this.request(`/api/management/projects/${projectId}/releases`,{method:"POST",body:JSON.stringify(body)})).data}async activateAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/activations`,{method:"POST",body:JSON.stringify(body)})).data}async deactivateAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/activations`,{method:"DELETE",body:JSON.stringify(body)})).data}async runAgent(projectId,env,agentName,body={}){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/agents/${encodeURIComponent(agentName)}/run`,{method:"POST",body:JSON.stringify(body)})).data}async listAgentSessions(projectId,opts={}){let params=new URLSearchParams;opts.agentName&&params.set("agent_name",opts.agentName),opts.env&&params.set("env",opts.env),opts.status&&params.set("status",opts.status),opts.limit!==void 0&&params.set("limit",String(opts.limit));let qs=params.toString();return(await this.request(`/api/management/projects/${projectId}/agents/sessions${qs?`?${qs}`:""}`)).data}async getAgentSession(projectId,sessionId){return(await this.request(`/api/management/projects/${projectId}/agents/sessions/${encodeURIComponent(sessionId)}`)).data.session}async getFeatures(){return this.request("/api/features")}async inviteProjectUser(input){return{id:(await this.request(`/api/management/projects/${input.projectId}/invites`,{method:"POST",body:JSON.stringify({email:input.email,roleKey:input.roleKey})})).data.id}}async updateProjectSettings(projectId,settings){return(await this.request(`/api/management/projects/${projectId}/settings`,{method:"PUT",body:JSON.stringify(settings)})).data}async deleteProject(projectId){await this.request(`/api/management/projects/${projectId}`,{method:"DELETE",body:JSON.stringify({})})}async getGitRemote(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-remote`,{},{allow403:!0})).data}async getGitCredential(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/git-credential`,{},{allow403:!0})).data}async getPreviewUrl(projectId,env){return(await this.request(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sandbox`)).data}async sandboxPull(projectId,onProgress,env,options={}){let query=options.noRestart?"?noRestart=true":"",response=await this.rawRequest(`/api/management/projects/${projectId}/envs/${encodeURIComponent(env)}/sandbox/pull${query}`,{method:"POST",headers:{Accept:"text/event-stream"}});if(!response.body)throw new Error("Sandbox pull failed: empty response stream");let reader=response.body.getReader(),decoder=new TextDecoder,buffer="",errorMessage3=null,completed=!1;try{for(;;){let{value,done}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:!0});let separatorIndex=buffer.indexOf(`
43
43
 
44
44
  `);for(;separatorIndex!==-1;){let rawEvent=buffer.slice(0,separatorIndex);buffer=buffer.slice(separatorIndex+2),separatorIndex=buffer.indexOf(`
45
45
 
@@ -206,13 +206,13 @@ ${agentsMdContent}`;writeIfMissing(".cursor/rules/fimo.mdc",cursorContent)}retur
206
206
  `).length-1;this.output.write(import_sisteransi.cursor.move(-999,t2*-1))}render(){let t2=wrapAnsi(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t2!==this._prevFrame){if(this.state==="initial")this.output.write(import_sisteransi.cursor.hide);else{let e=j(this._prevFrame,t2),s=A(this.output);if(this.restoreCursor(),e){let i=Math.max(0,e.numLinesAfter-s),n=Math.max(0,e.numLinesBefore-s),o=e.lines.find(a=>a>=i);if(o===void 0){this._prevFrame=t2;return}if(e.lines.length===1){this.output.write(import_sisteransi.cursor.move(0,o-n)),this.output.write(import_sisteransi.erase.lines(1));let a=t2.split(`
207
207
  `);this.output.write(a[o]),this._prevFrame=t2,this.output.write(import_sisteransi.cursor.move(0,a.length-o-1));return}else if(e.lines.length>1){if(i<n)o=i;else{let h=o-n;h>0&&this.output.write(import_sisteransi.cursor.move(0,h))}this.output.write(import_sisteransi.erase.down());let a=t2.split(`
208
208
  `).slice(o);this.output.write(a.join(`
209
- `)),this._prevFrame=t2;return}}this.output.write(import_sisteransi.erase.down())}this.output.write(t2),this.state==="initial"&&(this.state="active"),this._prevFrame=t2}}},Q=class extends p{static{__name(this,"Q")}get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t2){super(t2,!1),this.value=!!t2.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",e=>{this.output.write(import_sisteransi.cursor.move(0,-1)),this.value=e,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}},it=class extends p{static{__name(this,"it")}options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter(t2=>t2.disabled!==!0)}toggleAll(){let t2=this._enabledOptions,e=this.value!==void 0&&this.value.length===t2.length;this.value=e?[]:t2.map(s=>s.value)}toggleInvert(){let t2=this.value;if(!t2)return;let e=this._enabledOptions.filter(s=>!t2.includes(s.value));this.value=e.map(s=>s.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t2=this.value.includes(this._value);this.value=t2?this.value.filter(e=>e!==this._value):[...this.value,this._value]}constructor(t2){super(t2,!1),this.options=t2.options,this.value=[...t2.initialValues??[]];let e=Math.max(this.options.findIndex(({value:s})=>s===t2.cursorAt),0);this.cursor=this.options[e].disabled?d(e,1,this.options):e,this.on("key",s=>{s==="a"&&this.toggleAll(),s==="i"&&this.toggleInvert()}),this.on("cursor",s=>{switch(s){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},rt=class extends p{static{__name(this,"rt")}_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.masked}${y(["inverse","hidden"],"_")}`;let e=this.masked,s=e.slice(0,this.cursor),i=e.slice(this.cursor);return`${s}${y("inverse",i[0])}${i.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:t2,...e}){super(e),this._mask=t2??"\u2022",this.on("userInput",s=>{this._setValue(s)})}},nt=class extends p{static{__name(this,"nt")}options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(t2){super(t2,!1),this.options=t2.options;let e=this.options.findIndex(({value:i})=>i===t2.initialValue),s=e===-1?0:e;this.cursor=this.options[s].disabled?d(s,1,this.options):s,this.changeValue(),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break}this.changeValue()})}},at=class extends p{static{__name(this,"at")}get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.userInput}\u2588`;let e=t2.slice(0,this.cursor),[s,...i]=t2.slice(this.cursor);return`${e}${y("inverse",s)}${i.join("")}`}get cursor(){return this._cursor}constructor(t2){super({...t2,initialUserInput:t2.initialUserInput??t2.initialValue}),this.on("userInput",e=>{this._setValue(e)}),this.on("finalize",()=>{this.value||(this.value=t2.defaultValue),this.value===void 0&&(this.value="")})}}}});import{styleText as t,stripVTControlCharacters as ne}from"node:util";import P2 from"node:process";function Ze(){return P2.platform!=="win32"?P2.env.TERM!=="linux":!!P2.env.CI||!!P2.env.WT_SESSION||!!P2.env.TERMINUS_SUBLIME||P2.env.ConEmuTask==="{cmd::Cmder}"||P2.env.TERM_PROGRAM==="Terminus-Sublime"||P2.env.TERM_PROGRAM==="vscode"||P2.env.TERM==="xterm-256color"||P2.env.TERM==="alacritty"||P2.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var import_sisteransi2,ee,w2,_e,oe,ue,F,le,d2,E2,Ie,Ee,z66,H2,te,U,J,xe,se,ce,Ge,$e,de,Oe,he,pe,me,ge,V2,ye,et2,Y2,ot2,O2,pt,mt,ft,vt,wt,bt,Ve,re,_t,je,Ot,init_dist5=__esm({"../../node_modules/.pnpm/@clack+prompts@1.2.0/node_modules/@clack/prompts/dist/index.mjs"(){init_dist4();init_dist4();init_main();init_dist3();import_sisteransi2=__toESM(require_src(),1);__name(Ze,"Ze");ee=Ze(),w2=__name((e,i)=>ee?e:i,"w"),_e=w2("\u25C6","*"),oe=w2("\u25A0","x"),ue=w2("\u25B2","x"),F=w2("\u25C7","o"),le=w2("\u250C","T"),d2=w2("\u2502","|"),E2=w2("\u2514","\u2014"),Ie=w2("\u2510","T"),Ee=w2("\u2518","\u2014"),z66=w2("\u25CF",">"),H2=w2("\u25CB"," "),te=w2("\u25FB","[\u2022]"),U=w2("\u25FC","[+]"),J=w2("\u25FB","[ ]"),xe=w2("\u25AA","\u2022"),se=w2("\u2500","-"),ce=w2("\u256E","+"),Ge=w2("\u251C","+"),$e=w2("\u256F","+"),de=w2("\u2570","+"),Oe=w2("\u256D","+"),he=w2("\u25CF","\u2022"),pe=w2("\u25C6","*"),me=w2("\u25B2","!"),ge=w2("\u25A0","x"),V2=__name(e=>{switch(e){case"initial":case"active":return t("cyan",_e);case"cancel":return t("red",oe);case"error":return t("yellow",ue);case"submit":return t("green",F)}},"V"),ye=__name(e=>{switch(e){case"initial":case"active":return t("cyan",d2);case"cancel":return t("red",d2);case"error":return t("yellow",d2);case"submit":return t("green",d2)}},"ye"),et2=__name((e,i,s,r,u2)=>{let n=i,o=0;for(let c2=s;c2<r;c2++){let a=e[c2];if(n=n-a.length,o++,n<=u2)break}return{lineCount:n,removals:o}},"et"),Y2=__name(({cursor:e,options:i,style:s,output:r=process.stdout,maxItems:u2=Number.POSITIVE_INFINITY,columnPadding:n=0,rowPadding:o=4})=>{let c2=O(r)-n,a=A(r),l=t("dim","..."),$2=Math.max(a-o,0),y2=Math.max(Math.min(u2,$2),5),p2=0;e>=y2-3&&(p2=Math.max(Math.min(e-y2+3,i.length-y2),0));let m=y2<i.length&&p2>0,g=y2<i.length&&p2+y2<i.length,S2=Math.min(p2+y2,i.length),h=[],f=0;m&&f++,g&&f++;let v=p2+(m?1:0),T=S2-(g?1:0);for(let b=v;b<T;b++){let x=wrapAnsi(s(i[b],b===e),c2,{hard:!0,trim:!1}).split(`
209
+ `)),this._prevFrame=t2;return}}this.output.write(import_sisteransi.erase.down())}this.output.write(t2),this.state==="initial"&&(this.state="active"),this._prevFrame=t2}}},Q=class extends p{static{__name(this,"Q")}get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t2){super(t2,!1),this.value=!!t2.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",e=>{this.output.write(import_sisteransi.cursor.move(0,-1)),this.value=e,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}},it=class extends p{static{__name(this,"it")}options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter(t2=>t2.disabled!==!0)}toggleAll(){let t2=this._enabledOptions,e=this.value!==void 0&&this.value.length===t2.length;this.value=e?[]:t2.map(s=>s.value)}toggleInvert(){let t2=this.value;if(!t2)return;let e=this._enabledOptions.filter(s=>!t2.includes(s.value));this.value=e.map(s=>s.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t2=this.value.includes(this._value);this.value=t2?this.value.filter(e=>e!==this._value):[...this.value,this._value]}constructor(t2){super(t2,!1),this.options=t2.options,this.value=[...t2.initialValues??[]];let e=Math.max(this.options.findIndex(({value:s})=>s===t2.cursorAt),0);this.cursor=this.options[e].disabled?d(e,1,this.options):e,this.on("key",s=>{s==="a"&&this.toggleAll(),s==="i"&&this.toggleInvert()}),this.on("cursor",s=>{switch(s){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},rt=class extends p{static{__name(this,"rt")}_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.masked}${y(["inverse","hidden"],"_")}`;let e=this.masked,s=e.slice(0,this.cursor),i=e.slice(this.cursor);return`${s}${y("inverse",i[0])}${i.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:t2,...e}){super(e),this._mask=t2??"\u2022",this.on("userInput",s=>{this._setValue(s)})}},nt=class extends p{static{__name(this,"nt")}options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(t2){super(t2,!1),this.options=t2.options;let e=this.options.findIndex(({value:i})=>i===t2.initialValue),s=e===-1?0:e;this.cursor=this.options[s].disabled?d(s,1,this.options):s,this.changeValue(),this.on("cursor",i=>{switch(i){case"left":case"up":this.cursor=d(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=d(this.cursor,1,this.options);break}this.changeValue()})}},at=class extends p{static{__name(this,"at")}get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t2=this.userInput;if(this.cursor>=t2.length)return`${this.userInput}\u2588`;let e=t2.slice(0,this.cursor),[s,...i]=t2.slice(this.cursor);return`${e}${y("inverse",s)}${i.join("")}`}get cursor(){return this._cursor}constructor(t2){super({...t2,initialUserInput:t2.initialUserInput??t2.initialValue}),this.on("userInput",e=>{this._setValue(e)}),this.on("finalize",()=>{this.value||(this.value=t2.defaultValue),this.value===void 0&&(this.value="")})}}}});import{styleText as t,stripVTControlCharacters as ne}from"node:util";import P2 from"node:process";function Ze(){return P2.platform!=="win32"?P2.env.TERM!=="linux":!!P2.env.CI||!!P2.env.WT_SESSION||!!P2.env.TERMINUS_SUBLIME||P2.env.ConEmuTask==="{cmd::Cmder}"||P2.env.TERM_PROGRAM==="Terminus-Sublime"||P2.env.TERM_PROGRAM==="vscode"||P2.env.TERM==="xterm-256color"||P2.env.TERM==="alacritty"||P2.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var import_sisteransi2,ee,w2,_e,oe,ue,F,le,d2,E2,Ie,Ee,z67,H2,te,U,J,xe,se,ce,Ge,$e,de,Oe,he,pe,me,ge,V2,ye,et2,Y2,ot2,O2,pt,mt,ft,vt,wt,bt,Ve,re,_t,je,Ot,init_dist5=__esm({"../../node_modules/.pnpm/@clack+prompts@1.2.0/node_modules/@clack/prompts/dist/index.mjs"(){init_dist4();init_dist4();init_main();init_dist3();import_sisteransi2=__toESM(require_src(),1);__name(Ze,"Ze");ee=Ze(),w2=__name((e,i)=>ee?e:i,"w"),_e=w2("\u25C6","*"),oe=w2("\u25A0","x"),ue=w2("\u25B2","x"),F=w2("\u25C7","o"),le=w2("\u250C","T"),d2=w2("\u2502","|"),E2=w2("\u2514","\u2014"),Ie=w2("\u2510","T"),Ee=w2("\u2518","\u2014"),z67=w2("\u25CF",">"),H2=w2("\u25CB"," "),te=w2("\u25FB","[\u2022]"),U=w2("\u25FC","[+]"),J=w2("\u25FB","[ ]"),xe=w2("\u25AA","\u2022"),se=w2("\u2500","-"),ce=w2("\u256E","+"),Ge=w2("\u251C","+"),$e=w2("\u256F","+"),de=w2("\u2570","+"),Oe=w2("\u256D","+"),he=w2("\u25CF","\u2022"),pe=w2("\u25C6","*"),me=w2("\u25B2","!"),ge=w2("\u25A0","x"),V2=__name(e=>{switch(e){case"initial":case"active":return t("cyan",_e);case"cancel":return t("red",oe);case"error":return t("yellow",ue);case"submit":return t("green",F)}},"V"),ye=__name(e=>{switch(e){case"initial":case"active":return t("cyan",d2);case"cancel":return t("red",d2);case"error":return t("yellow",d2);case"submit":return t("green",d2)}},"ye"),et2=__name((e,i,s,r,u2)=>{let n=i,o=0;for(let c2=s;c2<r;c2++){let a=e[c2];if(n=n-a.length,o++,n<=u2)break}return{lineCount:n,removals:o}},"et"),Y2=__name(({cursor:e,options:i,style:s,output:r=process.stdout,maxItems:u2=Number.POSITIVE_INFINITY,columnPadding:n=0,rowPadding:o=4})=>{let c2=O(r)-n,a=A(r),l=t("dim","..."),$2=Math.max(a-o,0),y2=Math.max(Math.min(u2,$2),5),p2=0;e>=y2-3&&(p2=Math.max(Math.min(e-y2+3,i.length-y2),0));let m=y2<i.length&&p2>0,g=y2<i.length&&p2+y2<i.length,S2=Math.min(p2+y2,i.length),h=[],f=0;m&&f++,g&&f++;let v=p2+(m?1:0),T=S2-(g?1:0);for(let b=v;b<T;b++){let x=wrapAnsi(s(i[b],b===e),c2,{hard:!0,trim:!1}).split(`
210
210
  `);h.push(x),f+=x.length}if(f>$2){let b=0,x=0,G2=f,M2=e-v,R2=__name((j2,D)=>et2(h,G2,j2,D,$2),"R");m?({lineCount:G2,removals:b}=R2(0,M2),G2>$2&&({lineCount:G2,removals:x}=R2(M2+1,h.length))):({lineCount:G2,removals:x}=R2(M2+1,h.length),G2>$2&&({lineCount:G2,removals:b}=R2(0,M2))),b>0&&(m=!0,h.splice(0,b)),x>0&&(g=!0,h.splice(h.length-x,x))}let C2=[];m&&C2.push(l);for(let b of h)for(let x of b)C2.push(x);return g&&C2.push(l),C2},"Y"),ot2=__name(e=>{let i=e.active??"Yes",s=e.inactive??"No";return new Q({active:i,inactive:s,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??u.withGuide,u2=`${V2(this.state)} `,n=r?`${t("gray",d2)} `:"",o=R(e.output,e.message,n,u2),c2=`${r?`${t("gray",d2)}
211
211
  `:""}${o}
212
212
  `,a=this.value?i:s;switch(this.state){case"submit":{let l=r?`${t("gray",d2)} `:"";return`${c2}${l}${t("dim",a)}`}case"cancel":{let l=r?`${t("gray",d2)} `:"";return`${c2}${l}${t(["strikethrough","dim"],a)}${r?`
213
- ${t("gray",d2)}`:""}`}default:{let l=r?`${t("cyan",d2)} `:"",$2=r?t("cyan",E2):"";return`${c2}${l}${this.value?`${t("green",z66)} ${i}`:`${t("dim",H2)} ${t("dim",i)}`}${e.vertical?r?`
213
+ ${t("gray",d2)}`:""}`}default:{let l=r?`${t("cyan",d2)} `:"",$2=r?t("cyan",E2):"";return`${c2}${l}${this.value?`${t("green",z67)} ${i}`:`${t("dim",H2)} ${t("dim",i)}`}${e.vertical?r?`
214
214
  ${t("cyan",d2)} `:`
215
- `:` ${t("dim","/")} `}${this.value?`${t("dim",H2)} ${t("dim",s)}`:`${t("green",z66)} ${s}`}
215
+ `:` ${t("dim","/")} `}${this.value?`${t("dim",H2)} ${t("dim",s)}`:`${t("green",z67)} ${s}`}
216
216
  ${$2}
217
217
  `}}}}).prompt()},"ot"),O2={message:__name((e=[],{symbol:i=t("gray",d2),secondarySymbol:s=t("gray",d2),output:r=process.stdout,spacing:u2=1,withGuide:n}={})=>{let o=[],c2=n??u.withGuide,a=c2?s:"",l=c2?`${i} `:"",$2=c2?`${s} `:"";for(let p2=0;p2<u2;p2++)o.push(a);let y2=Array.isArray(e)?e:e.split(`
218
218
  `);if(y2.length>0){let[p2,...m]=y2;p2.length>0?o.push(`${l}${p2}`):o.push(c2?i:"");for(let g of m)g.length>0?o.push(`${$2}${g}`):o.push(c2?s:"")}r.write(`${o.join(`
@@ -238,7 +238,7 @@ ${o}
238
238
  `}}}}).prompt(),"bt"),Ve={light:w2("\u2500","-"),heavy:w2("\u2501","="),block:w2("\u2588","#")},re=__name((e,i)=>e.includes(`
239
239
  `)?e.split(`
240
240
  `).map(s=>i(s)).join(`
241
- `):i(e),"re"),_t=__name(e=>{let i=__name((s,r)=>{let u2=s.label??String(s.value);switch(r){case"disabled":return`${t("gray",H2)} ${re(u2,n=>t("gray",n))}${s.hint?` ${t("dim",`(${s.hint??"disabled"})`)}`:""}`;case"selected":return`${re(u2,n=>t("dim",n))}`;case"active":return`${t("green",z66)} ${u2}${s.hint?` ${t("dim",`(${s.hint})`)}`:""}`;case"cancelled":return`${re(u2,n=>t(["strikethrough","dim"],n))}`;default:return`${t("dim",H2)} ${re(u2,n=>t("dim",n))}`}},"i");return new nt({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let s=e.withGuide??u.withGuide,r=`${V2(this.state)} `,u2=`${ye(this.state)} `,n=R(e.output,e.message,u2,r),o=`${s?`${t("gray",d2)}
241
+ `):i(e),"re"),_t=__name(e=>{let i=__name((s,r)=>{let u2=s.label??String(s.value);switch(r){case"disabled":return`${t("gray",H2)} ${re(u2,n=>t("gray",n))}${s.hint?` ${t("dim",`(${s.hint??"disabled"})`)}`:""}`;case"selected":return`${re(u2,n=>t("dim",n))}`;case"active":return`${t("green",z67)} ${u2}${s.hint?` ${t("dim",`(${s.hint})`)}`:""}`;case"cancelled":return`${re(u2,n=>t(["strikethrough","dim"],n))}`;default:return`${t("dim",H2)} ${re(u2,n=>t("dim",n))}`}},"i");return new nt({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let s=e.withGuide??u.withGuide,r=`${V2(this.state)} `,u2=`${ye(this.state)} `,n=R(e.output,e.message,u2,r),o=`${s?`${t("gray",d2)}
242
242
  `:""}${n}
243
243
  `;switch(this.state){case"submit":{let c2=s?`${t("gray",d2)} `:"",a=R(e.output,i(this.options[this.cursor],"selected"),c2);return`${o}${a}`}case"cancel":{let c2=s?`${t("gray",d2)} `:"",a=R(e.output,i(this.options[this.cursor],"cancelled"),c2);return`${o}${a}${s?`
244
244
  ${t("gray",d2)}`:""}`}default:{let c2=s?`${t("cyan",d2)} `:"",a=s?t("cyan",E2):"",l=o.split(`
@@ -298,10 +298,10 @@ return __eta.res;
298
298
  `)}}return returnStr}function trimWS(str,config,wsLeft,wsRight){let leftTrim,rightTrim;return Array.isArray(config.autoTrim)?(leftTrim=config.autoTrim[1],rightTrim=config.autoTrim[0]):leftTrim=rightTrim=config.autoTrim,(wsLeft||wsLeft===!1)&&(leftTrim=wsLeft),(wsRight||wsRight===!1)&&(rightTrim=wsRight),!rightTrim&&!leftTrim?str:leftTrim==="slurp"&&rightTrim==="slurp"?str.trim():(leftTrim==="_"||leftTrim==="slurp"?str=str.trimStart():(leftTrim==="-"||leftTrim==="nl")&&(str=str.replace(/^(?:\r\n|\n|\r)/,"")),rightTrim==="_"||rightTrim==="slurp"?str=str.trimEnd():(rightTrim==="-"||rightTrim==="nl")&&(str=str.replace(/(?:\r\n|\n|\r)$/,"")),str)}function replaceChar(s){return escMap[s]}function XMLEscape(str){let newStr=String(str);return/[&<>"']/.test(newStr)?newStr.replace(/[&<>"']/g,replaceChar):newStr}function escapeRegExp(string){return string.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&")}function getLineNo(str,index2){return str.slice(0,index2).split(`
299
299
  `).length}function parse4(str){let config=this.config,buffer=[],trimLeftOfNextStr=!1,lastIndex=0,parseOptions=config.parse;if(config.plugins)for(let i=0;i<config.plugins.length;i++){let plugin=config.plugins[i];plugin.processTemplate&&(str=plugin.processTemplate(str,config))}config.rmWhitespace&&(str=str.replace(/[\r\n]+/g,`
300
300
  `).replace(/^\s+|\s+$/gm,"")),templateLitReg.lastIndex=0,singleQuoteReg.lastIndex=0,doubleQuoteReg.lastIndex=0;function pushString(strng,shouldTrimRightOfString){strng&&(strng=trimWS(strng,config,trimLeftOfNextStr,shouldTrimRightOfString),strng&&(strng=strng.replace(/\\|'/g,"\\$&").replace(/\r\n|\n|\r/g,"\\n"),buffer.push(strng)))}__name(pushString,"pushString");let prefixes=[parseOptions.exec,parseOptions.interpolate,parseOptions.raw].reduce(function(accumulator,prefix){return accumulator&&prefix?accumulator+"|"+escapeRegExp(prefix):prefix?escapeRegExp(prefix):accumulator},""),parseOpenReg=new RegExp(escapeRegExp(config.tags[0])+"(-|_)?\\s*("+prefixes+")?\\s*","g"),parseCloseReg=new RegExp("'|\"|`|\\/\\*|(\\s*(-|_)?"+escapeRegExp(config.tags[1])+")","g"),m;for(;m=parseOpenReg.exec(str);){let precedingString=str.slice(lastIndex,m.index);lastIndex=m[0].length+m.index;let wsLeft=m[1],prefix=m[2]||"";pushString(precedingString,wsLeft),parseCloseReg.lastIndex=lastIndex;let closeTag,currentObj=!1;for(;closeTag=parseCloseReg.exec(str);)if(closeTag[1]){let content2=str.slice(lastIndex,closeTag.index);parseOpenReg.lastIndex=lastIndex=parseCloseReg.lastIndex,trimLeftOfNextStr=closeTag[2],currentObj={t:prefix===parseOptions.exec?"e":prefix===parseOptions.raw?"r":prefix===parseOptions.interpolate?"i":"",val:content2};break}else{let char=closeTag[0];if(char==="/*"){let commentCloseInd=str.indexOf("*/",parseCloseReg.lastIndex);commentCloseInd===-1&&ParseErr("unclosed comment",str,closeTag.index),parseCloseReg.lastIndex=commentCloseInd}else char==="'"?(singleQuoteReg.lastIndex=closeTag.index,singleQuoteReg.exec(str)?parseCloseReg.lastIndex=singleQuoteReg.lastIndex:ParseErr("unclosed string",str,closeTag.index)):char==='"'?(doubleQuoteReg.lastIndex=closeTag.index,doubleQuoteReg.exec(str)?parseCloseReg.lastIndex=doubleQuoteReg.lastIndex:ParseErr("unclosed string",str,closeTag.index)):char==="`"&&(templateLitReg.lastIndex=closeTag.index,templateLitReg.exec(str)?parseCloseReg.lastIndex=templateLitReg.lastIndex:ParseErr("unclosed string",str,closeTag.index))}currentObj?(config.debug&&(currentObj.lineNo=getLineNo(str,m.index)),buffer.push(currentObj)):ParseErr("unclosed tag",str,m.index)}if(pushString(str.slice(lastIndex,str.length),!1),config.plugins)for(let i=0;i<config.plugins.length;i++){let plugin=config.plugins[i];plugin.processAST&&(buffer=plugin.processAST(buffer,config))}return buffer}function handleCache(template,options){let templateStore=options&&options.async?this.templatesAsync:this.templatesSync;if(this.resolvePath&&this.readFile&&!template.startsWith("@")){let templatePath2=options.filepath,cachedTemplate=templateStore.get(templatePath2);if(this.config.cache&&cachedTemplate)return cachedTemplate;{let templateString=this.readFile(templatePath2),templateFn=this.compile(templateString,options);return this.config.cache&&templateStore.define(templatePath2,templateFn),templateFn}}else{let cachedTemplate=templateStore.get(template);if(cachedTemplate)return cachedTemplate;throw new EtaNameResolutionError("Failed to get template '"+template+"'")}}function render(template,data2,meta){let templateFn,options={...meta,async:!1};return typeof template=="string"?(this.resolvePath&&this.readFile&&!template.startsWith("@")&&(options.filepath=this.resolvePath(template,options)),templateFn=handleCache.call(this,template,options)):templateFn=template,templateFn.call(this,data2,options)}function renderAsync(template,data2,meta){let templateFn,options={...meta,async:!0};typeof template=="string"?(this.resolvePath&&this.readFile&&!template.startsWith("@")&&(options.filepath=this.resolvePath(template,options)),templateFn=handleCache.call(this,template,options)):templateFn=template;let res=templateFn.call(this,data2,options);return Promise.resolve(res)}function renderString(template,data2){let templateFn=this.compile(template,{async:!1});return render.call(this,templateFn,data2)}function renderStringAsync(template,data2){let templateFn=this.compile(template,{async:!0});return renderAsync.call(this,templateFn,data2)}function readFile(path47){let res="";try{res=fs17.readFileSync(path47,"utf8")}catch(err){throw err?.code==="ENOENT"?new EtaFileResolutionError(`Could not find template: ${path47}`):err}return res}function resolvePath2(templatePath2,options){let resolvedFilePath="",views=this.config.views;if(!views)throw new EtaFileResolutionError("Views directory is not defined");let baseFilePath=options&&options.filepath,defaultExtension=this.config.defaultExtension===void 0?".eta":this.config.defaultExtension,cacheIndex=JSON.stringify({filename:baseFilePath,path:templatePath2,views:this.config.views});if(templatePath2+=path20.extname(templatePath2)?"":defaultExtension,baseFilePath){if(this.config.cacheFilepaths&&this.filepathCache[cacheIndex])return this.filepathCache[cacheIndex];let absolutePathTest=absolutePathRegExp.exec(templatePath2);if(absolutePathTest&&absolutePathTest.length){let formattedPath=templatePath2.replace(/^\/*|^\\*/,"");resolvedFilePath=path20.join(views,formattedPath)}else resolvedFilePath=path20.join(path20.dirname(baseFilePath),templatePath2)}else resolvedFilePath=path20.join(views,templatePath2);if(dirIsChild(views,resolvedFilePath))return baseFilePath&&this.config.cacheFilepaths&&(this.filepathCache[cacheIndex]=resolvedFilePath),resolvedFilePath;throw new EtaFileResolutionError(`Template '${templatePath2}' is not in the views directory`)}function dirIsChild(parent2,dir){let relative3=path20.relative(parent2,dir);return relative3&&!relative3.startsWith("..")&&!path20.isAbsolute(relative3)}var Cacher,EtaError,EtaParseError,EtaRuntimeError,EtaFileResolutionError,EtaNameResolutionError,AsyncFunction,escMap,defaultConfig2,templateLitReg,singleQuoteReg,doubleQuoteReg,Eta$1,absolutePathRegExp,Eta,init_eta_module=__esm({"../../node_modules/.pnpm/eta@3.5.0/node_modules/eta/dist/eta.module.mjs"(){Cacher=class{static{__name(this,"Cacher")}constructor(cache){this.cache=void 0,this.cache=cache}define(key,val2){this.cache[key]=val2}get(key){return this.cache[key]}remove(key){delete this.cache[key]}reset(){this.cache={}}load(cacheObj){this.cache={...this.cache,...cacheObj}}},EtaError=class extends Error{static{__name(this,"EtaError")}constructor(message){super(message),this.name="Eta Error"}},EtaParseError=class extends EtaError{static{__name(this,"EtaParseError")}constructor(message){super(message),this.name="EtaParser Error"}},EtaRuntimeError=class extends EtaError{static{__name(this,"EtaRuntimeError")}constructor(message){super(message),this.name="EtaRuntime Error"}},EtaFileResolutionError=class extends EtaError{static{__name(this,"EtaFileResolutionError")}constructor(message){super(message),this.name="EtaFileResolution Error"}},EtaNameResolutionError=class extends EtaError{static{__name(this,"EtaNameResolutionError")}constructor(message){super(message),this.name="EtaNameResolution Error"}};__name(ParseErr,"ParseErr");__name(RuntimeErr,"RuntimeErr");AsyncFunction=async function(){}.constructor;__name(compile,"compile");__name(compileToString,"compileToString");__name(compileBody,"compileBody");__name(trimWS,"trimWS");escMap={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};__name(replaceChar,"replaceChar");__name(XMLEscape,"XMLEscape");defaultConfig2={autoEscape:!0,autoFilter:!1,autoTrim:[!1,"nl"],cache:!1,cacheFilepaths:!0,debug:!1,escapeFunction:XMLEscape,filterFunction:__name(val2=>String(val2),"filterFunction"),functionHeader:"",parse:{exec:"",interpolate:"=",raw:"~"},plugins:[],rmWhitespace:!1,tags:["<%","%>"],useWith:!1,varName:"it",defaultExtension:".eta"},templateLitReg=/`(?:\\[\s\S]|\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})*}|(?!\${)[^\\`])*`/g,singleQuoteReg=/'(?:\\[\s\w"'\\`]|[^\n\r'\\])*?'/g,doubleQuoteReg=/"(?:\\[\s\w"'\\`]|[^\n\r"\\])*?"/g;__name(escapeRegExp,"escapeRegExp");__name(getLineNo,"getLineNo");__name(parse4,"parse");__name(handleCache,"handleCache");__name(render,"render");__name(renderAsync,"renderAsync");__name(renderString,"renderString");__name(renderStringAsync,"renderStringAsync");Eta$1=class{static{__name(this,"Eta$1")}constructor(customConfig){this.config=void 0,this.RuntimeErr=RuntimeErr,this.compile=compile,this.compileToString=compileToString,this.compileBody=compileBody,this.parse=parse4,this.render=render,this.renderAsync=renderAsync,this.renderString=renderString,this.renderStringAsync=renderStringAsync,this.filepathCache={},this.templatesSync=new Cacher({}),this.templatesAsync=new Cacher({}),this.resolvePath=null,this.readFile=null,customConfig?this.config={...defaultConfig2,...customConfig}:this.config={...defaultConfig2}}configure(customConfig){this.config={...this.config,...customConfig}}withConfig(customConfig){return{...this,config:{...this.config,...customConfig}}}loadTemplate(name,template,options){if(typeof template=="string")(options&&options.async?this.templatesAsync:this.templatesSync).define(name,this.compile(template,options));else{let templates=this.templatesSync;(template.constructor.name==="AsyncFunction"||options&&options.async)&&(templates=this.templatesAsync),templates.define(name,template)}}};__name(readFile,"readFile");__name(resolvePath2,"resolvePath");__name(dirIsChild,"dirIsChild");absolutePathRegExp=/^\\|^\//,Eta=class extends Eta$1{static{__name(this,"Eta")}constructor(...args){super(...args),this.readFile=readFile,this.resolvePath=resolvePath2}}}});import{existsSync as existsSync2}from"node:fs";import{dirname as dirname3,resolve as resolve2}from"node:path";import{fileURLToPath as fileURLToPath4}from"node:url";function assetPath(...segments){return resolve2(PACKAGE_ROOT2,"assets",...segments)}var HERE,IS_BUNDLED,PACKAGE_ROOT2,init_assets=__esm({"src/scripts/utils/assets.ts"(){HERE=dirname3(fileURLToPath4(import.meta.url)),IS_BUNDLED=existsSync2(resolve2(HERE,"bundle.json")),PACKAGE_ROOT2=IS_BUNDLED?resolve2(HERE,"..",".."):resolve2(HERE,"..","..","..");__name(assetPath,"assetPath")}});import{existsSync as existsSync3,mkdirSync as mkdirSync2,readFileSync as readFileSync4,readdirSync as readdirSync2,unlinkSync,writeFileSync as writeFileSync3}from"node:fs";import{dirname as dirname4,join as join5,resolve as resolve3}from"node:path";function getFormFiles(formsDir){return existsSync3(formsDir)?readdirSync2(formsDir).filter(f=>f.endsWith(".json")).map(f=>join5(formsDir,f)):[]}function readForm(path47){try{return JSON.parse(readFileSync4(path47,"utf-8"))}catch{return null}}function generateIndexContent(forms3){let lines=["// AUTO-GENERATED \u26A0\uFE0F \u2014 do not edit by hand",""];for(let form of forms3){let pascal=pascalCase(form.name),varName=pascal.charAt(0).toLowerCase()+pascal.slice(1);lines.push(`export { ${pascal}Schema, submit${pascal}, FORM_ID as ${varName}FormId } from "./${form.name}";`),lines.push(`export type { ${pascal}Data } from "./${form.name}";`)}return lines.push(""),lines.join(`
301
- `)}function syncForms(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),formsDir=resolve3(cwd,FORMS_REL),templatePath2=assetPath("content-templates","form-template.eta"),templateSource=readFileSync4(templatePath2,"utf-8"),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),formFiles=getFormFiles(formsDir),expectedTsFiles=new Set,allForms=[],created=0,updated=0,deleted=0;for(let jsonPath of formFiles){let form=readForm(jsonPath);if(!form){console.error(`Failed to parse form: ${jsonPath}`);continue}form.name||(form.name=jsonPath.split("/").pop().replace(/\.json$/,"")),allForms.push(form);let tsPath=join5(formsDir,`${form.name}.ts`);expectedTsFiles.add(tsPath);try{let content2=eta.renderString(templateSource,{form:{...form,pascal:pascalCase(form.name)}}),dir=dirname4(tsPath);if(existsSync3(dir)||mkdirSync2(dir,{recursive:!0}),!existsSync3(tsPath)){writeFileSync3(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync4(tsPath,"utf-8")!==content2&&(writeFileSync3(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}catch(error){console.error(`Failed to generate ${tsPath}:`,error)}}if(allForms.length>0){let indexPath=join5(formsDir,"index.ts");expectedTsFiles.add(indexPath);let indexContent=generateIndexContent(allForms);(!existsSync3(indexPath)||readFileSync4(indexPath,"utf-8")!==indexContent)&&(writeFileSync3(indexPath,indexContent,"utf-8"),log(`Updated: ${indexPath}`))}if(existsSync3(formsDir)){let allTsFiles=readdirSync2(formsDir).filter(f=>f.endsWith(".ts")).map(f=>join5(formsDir,f));for(let tsFile of allTsFiles)if(!expectedTsFiles.has(tsFile))try{unlinkSync(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}}return(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync forms: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var FORMS_REL,init_sync_forms=__esm({"src/scripts/sync-forms.ts"(){init_dist6();init_eta_module();init_assets();FORMS_REL="src/forms";__name(getFormFiles,"getFormFiles");__name(readForm,"readForm");__name(generateIndexContent,"generateIndexContent");__name(syncForms,"syncForms")}});import{existsSync as existsSync4,mkdirSync as mkdirSync3,readFileSync as readFileSync5,readdirSync as readdirSync3,unlinkSync as unlinkSync2,writeFileSync as writeFileSync4}from"node:fs";import{basename,dirname as dirname5,join as join6,resolve as resolve4}from"node:path";import{z as z67}from"zod";function getSchemaFiles(schemasDir){return existsSync4(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".json")).map(f=>join6(schemasDir,f)):[]}function getGeneratedFiles(schemasDir){return existsSync4(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".ts")&&f!=="index.ts").map(f=>join6(schemasDir,f)):[]}function parseVersion(version){let match=/^(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?(?:\+.*)?$/.exec(version);return match?{parts:[Number(match[1]),Number(match[2]),Number(match[3])],prerelease:match[4]!==void 0}:null}function isVersionAtLeast(version,minimum){let parsed=parseVersion(version),parsedMinimum=parseVersion(minimum);if(!parsed||!parsedMinimum)return!1;for(let index2=0;index2<parsed.parts.length;index2++)if(parsed.parts[index2]!==parsedMinimum.parts[index2])return parsed.parts[index2]>parsedMinimum.parts[index2];return!parsed.prerelease||parsedMinimum.prerelease}function resolveProjectRuntime(cwd){let packagePath=join6(cwd,"node_modules","fimo","package.json");if(!existsSync4(packagePath))throw new Error(`Cannot generate schema clients because the project-local fimo package could not be resolved from ${cwd}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);let version;try{version=JSON.parse(readFileSync5(packagePath,"utf-8")).version}catch{version=null}if(typeof version!="string"||!parseVersion(version))throw new Error(`Cannot generate schema clients with project-local fimo@${typeof version=="string"?version:"unknown"}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return{packageRoot:dirname5(packagePath),version}}function templatePath(runtime,fileName){return runtime&&!isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)?join6(runtime.packageRoot,"assets","content-templates",fileName):assetPath("content-templates",fileName)}function loadSchemas(schemaFiles){let errors=[],schemas3=[],outputOwners=new Map;for(let path47 of schemaFiles){let fileUid=basename(path47,".json"),pascal=pascalCase(fileUid),existingOwner=outputOwners.get(pascal);existingOwner&&existingOwner!==fileUid?errors.push(`${basename(path47)} and ${existingOwner}.json both generate ${pascal}.ts. Rename one schema to keep generated module names unique.`):outputOwners.set(pascal,fileUid);let parsed;try{parsed=JSON.parse(readFileSync5(path47,"utf-8"))}catch(error){errors.push(`${basename(path47)} is invalid JSON: ${error instanceof Error?error.message:String(error)}`);continue}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){errors.push(`${basename(path47)} must contain a JSON object.`);continue}let candidate=parsed;if(typeof candidate.uid!="string"||candidate.uid.length===0){errors.push(`${basename(path47)} is missing "uid". Set it to "${fileUid}".`);continue}if(candidate.uid!==fileUid){errors.push(`${basename(path47)} declares uid "${candidate.uid}". It must match the file name "${fileUid}".`);continue}let validation=SCHEMA_DEFINITION_SCHEMA.safeParse(candidate);if(!validation.success){let details=validation.error.issues.map(issue=>`${issue.path.join(".")||"schema"}: ${issue.message}`).join("; ");errors.push(`${basename(path47)} has an invalid schema shape: ${details}`);continue}schemas3.push({pascal,schema:validation.data})}if(errors.length>0)throw new Error(`Cannot generate schema clients:
301
+ `)}function syncForms(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),formsDir=resolve3(cwd,FORMS_REL),templatePath2=assetPath("content-templates","form-template.eta"),templateSource=readFileSync4(templatePath2,"utf-8"),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),formFiles=getFormFiles(formsDir),expectedTsFiles=new Set,allForms=[],created=0,updated=0,deleted=0;for(let jsonPath of formFiles){let form=readForm(jsonPath);if(!form){console.error(`Failed to parse form: ${jsonPath}`);continue}form.name||(form.name=jsonPath.split("/").pop().replace(/\.json$/,"")),allForms.push(form);let tsPath=join5(formsDir,`${form.name}.ts`);expectedTsFiles.add(tsPath);try{let content2=eta.renderString(templateSource,{form:{...form,pascal:pascalCase(form.name)}}),dir=dirname4(tsPath);if(existsSync3(dir)||mkdirSync2(dir,{recursive:!0}),!existsSync3(tsPath)){writeFileSync3(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync4(tsPath,"utf-8")!==content2&&(writeFileSync3(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}catch(error){console.error(`Failed to generate ${tsPath}:`,error)}}if(allForms.length>0){let indexPath=join5(formsDir,"index.ts");expectedTsFiles.add(indexPath);let indexContent=generateIndexContent(allForms);(!existsSync3(indexPath)||readFileSync4(indexPath,"utf-8")!==indexContent)&&(writeFileSync3(indexPath,indexContent,"utf-8"),log(`Updated: ${indexPath}`))}if(existsSync3(formsDir)){let allTsFiles=readdirSync2(formsDir).filter(f=>f.endsWith(".ts")).map(f=>join5(formsDir,f));for(let tsFile of allTsFiles)if(!expectedTsFiles.has(tsFile))try{unlinkSync(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}}return(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync forms: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var FORMS_REL,init_sync_forms=__esm({"src/scripts/sync-forms.ts"(){init_dist6();init_eta_module();init_assets();FORMS_REL="src/forms";__name(getFormFiles,"getFormFiles");__name(readForm,"readForm");__name(generateIndexContent,"generateIndexContent");__name(syncForms,"syncForms")}});import{existsSync as existsSync4,mkdirSync as mkdirSync3,readFileSync as readFileSync5,readdirSync as readdirSync3,unlinkSync as unlinkSync2,writeFileSync as writeFileSync4}from"node:fs";import{basename,dirname as dirname5,join as join6,resolve as resolve4}from"node:path";import{z as z68}from"zod";function getSchemaFiles(schemasDir){return existsSync4(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".json")).map(f=>join6(schemasDir,f)):[]}function getGeneratedFiles(schemasDir){return existsSync4(schemasDir)?readdirSync3(schemasDir).filter(f=>f.endsWith(".ts")&&f!=="index.ts").map(f=>join6(schemasDir,f)):[]}function parseVersion(version){let match=/^(\d+)\.(\d+)\.(\d+)(?:-([^+]+))?(?:\+.*)?$/.exec(version);return match?{parts:[Number(match[1]),Number(match[2]),Number(match[3])],prerelease:match[4]!==void 0}:null}function isVersionAtLeast(version,minimum){let parsed=parseVersion(version),parsedMinimum=parseVersion(minimum);if(!parsed||!parsedMinimum)return!1;for(let index2=0;index2<parsed.parts.length;index2++)if(parsed.parts[index2]!==parsedMinimum.parts[index2])return parsed.parts[index2]>parsedMinimum.parts[index2];return!parsed.prerelease||parsedMinimum.prerelease}function resolveProjectRuntime(cwd){let packagePath=join6(cwd,"node_modules","fimo","package.json");if(!existsSync4(packagePath))throw new Error(`Cannot generate schema clients because the project-local fimo package could not be resolved from ${cwd}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);let version;try{version=JSON.parse(readFileSync5(packagePath,"utf-8")).version}catch{version=null}if(typeof version!="string"||!parseVersion(version))throw new Error(`Cannot generate schema clients with project-local fimo@${typeof version=="string"?version:"unknown"}. Run \`${CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND}\` in the project, then run \`npx fimo@latest validate\` again. No generated files were changed.`);return{packageRoot:dirname5(packagePath),version}}function templatePath(runtime,fileName){return runtime&&!isVersionAtLeast(runtime.version,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION)?join6(runtime.packageRoot,"assets","content-templates",fileName):assetPath("content-templates",fileName)}function loadSchemas(schemaFiles){let errors=[],schemas3=[],outputOwners=new Map;for(let path47 of schemaFiles){let fileUid=basename(path47,".json"),pascal=pascalCase(fileUid),existingOwner=outputOwners.get(pascal);existingOwner&&existingOwner!==fileUid?errors.push(`${basename(path47)} and ${existingOwner}.json both generate ${pascal}.ts. Rename one schema to keep generated module names unique.`):outputOwners.set(pascal,fileUid);let parsed;try{parsed=JSON.parse(readFileSync5(path47,"utf-8"))}catch(error){errors.push(`${basename(path47)} is invalid JSON: ${error instanceof Error?error.message:String(error)}`);continue}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)){errors.push(`${basename(path47)} must contain a JSON object.`);continue}let candidate=parsed;if(typeof candidate.uid!="string"||candidate.uid.length===0){errors.push(`${basename(path47)} is missing "uid". Set it to "${fileUid}".`);continue}if(candidate.uid!==fileUid){errors.push(`${basename(path47)} declares uid "${candidate.uid}". It must match the file name "${fileUid}".`);continue}let validation=SCHEMA_DEFINITION_SCHEMA.safeParse(candidate);if(!validation.success){let details=validation.error.issues.map(issue=>`${issue.path.join(".")||"schema"}: ${issue.message}`).join("; ");errors.push(`${basename(path47)} has an invalid schema shape: ${details}`);continue}schemas3.push({pascal,schema:validation.data})}if(errors.length>0)throw new Error(`Cannot generate schema clients:
302
302
  - ${errors.join(`
303
303
  - `)}
304
- No generated files were changed.`);return schemas3}function normalizeFields(fields){return Object.fromEntries(Object.entries(fields).map(([key,value])=>{if(!value||typeof value!="object"||Array.isArray(value))return[key,{type:void 0}];let field=value,target=typeof field.target=="string"?field.target:void 0,targets=Array.isArray(field.targets)?field.targets.filter(candidate=>typeof candidate=="string"):void 0;return[key,{...field,type:typeof field.type=="string"?field.type:void 0,target,targetPascal:target?pascalCase(target):void 0,targets:targets&&targets.length>0?targets:void 0,targetRefs:targets&&targets.length>0?targets.map(candidate=>({uid:candidate,pascal:pascalCase(candidate)})):void 0,many:typeof field.many=="boolean"?field.many:void 0,multiple:typeof field.multiple=="boolean"?field.multiple:void 0}]}))}function referenceImportsFor(schema,fields){let imports=new Map;for(let field of Object.values(fields)){if(field.type!=="reference")continue;let targets=field.targets??(field.target?[field.target]:[]);for(let target of targets)target!==schema.uid&&imports.set(target,{uid:target,pascal:pascalCase(target)})}return[...imports.values()].sort((a,b)=>a.pascal.localeCompare(b.pascal))}function schemaToModel(schema,localizedByUid){let fields=normalizeFields(schema.fields??{});return{uid:schema.uid,pascal:pascalCase(schema.uid),isSingleton:schema.isSingleton??!1,localized:schema.i18n?.enabled!==!1,localizedReferenceFields:Object.entries(fields).filter(([,field])=>field.type!=="reference"?!1:(field.targets??(field.target?[field.target]:[])).some(target=>localizedByUid.get(target)!==!1)).map(([fieldName])=>fieldName),fields,referenceImports:referenceImportsFor(schema,fields)}}function syncSchemas(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),schemasDir=resolve4(cwd,SCHEMAS_REL),schemaFiles=getSchemaFiles(schemasDir),schemas3=loadSchemas(schemaFiles),generatedFilesOnDisk=getGeneratedFiles(schemasDir),runtime=schemas3.length>0||generatedFilesOnDisk.length>0?resolveProjectRuntime(cwd):null,templates=[{suffix:".types.ts",path:templatePath(runtime,"types-template.eta")},{suffix:".ts",path:templatePath(runtime,"hooks-template.eta")}].map(template=>({...template,source:readFileSync5(template.path,"utf-8")})),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),localizedByUid=new Map(schemas3.map(({schema})=>[schema.uid,schema.i18n?.enabled!==!1])),expectedTsFiles=new Set,generatedFiles=new Map,created=0,updated=0,deleted=0;for(let{pascal,schema}of schemas3){let model=schemaToModel(schema,localizedByUid);for(let template of templates){let tsPath=join6(schemasDir,`${pascal}${template.suffix}`);expectedTsFiles.add(tsPath),generatedFiles.set(tsPath,eta.renderString(template.source,{model}))}}for(let[tsPath,content2]of generatedFiles){let dir=dirname5(tsPath);if(existsSync4(dir)||mkdirSync3(dir,{recursive:!0}),!existsSync4(tsPath)){writeFileSync4(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync5(tsPath,"utf-8")!==content2&&(writeFileSync4(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}for(let tsFile of generatedFilesOnDisk)if(!expectedTsFiles.has(tsFile))try{unlinkSync2(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}return(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync schemas: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var SCHEMAS_REL,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION,CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND,SCHEMA_DEFINITION_SCHEMA,init_sync_schemas=__esm({"src/scripts/sync-schemas.ts"(){init_dist6();init_eta_module();init_assets();SCHEMAS_REL="src/schemas",MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION="0.7.0",CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND="npm install fimo@latest",SCHEMA_DEFINITION_SCHEMA=z67.object({uid:z67.string().min(1),isSingleton:z67.boolean().optional(),i18n:z67.object({enabled:z67.boolean().optional()}).optional(),fields:z67.record(z67.string(),z67.unknown()).optional()});__name(getSchemaFiles,"getSchemaFiles");__name(getGeneratedFiles,"getGeneratedFiles");__name(parseVersion,"parseVersion");__name(isVersionAtLeast,"isVersionAtLeast");__name(resolveProjectRuntime,"resolveProjectRuntime");__name(templatePath,"templatePath");__name(loadSchemas,"loadSchemas");__name(normalizeFields,"normalizeFields");__name(referenceImportsFor,"referenceImportsFor");__name(schemaToModel,"schemaToModel");__name(syncSchemas,"syncSchemas")}});function renderCrossSurface(findings,p2,opts={}){let lines=[];lines.push(p2.bold("CROSS-SURFACE INTEGRITY")),lines.push(p2.dim(" references that span surfaces"));let errorGlyph=opts.ascii?"!!":"\u203C",arrow=opts.ascii?"->":"\u2192",sep2=opts.ascii?"|":"\xB7";for(let f of findings){let glyph=f.severity==="error"?p2.red("!"):p2.yellow(errorGlyph);lines.push(` ${glyph} ${f.description}`);let trail=`${f.source.surface}:${f.source.key} ${arrow} ${f.target.surface}:${f.target.key}`;lines.push(p2.dim(` ${trail}`)),f.actions.length>0&&lines.push(p2.dim(` actions: ${f.actions.join(` ${sep2} `)}`))}return lines.join(`
304
+ No generated files were changed.`);return schemas3}function normalizeFields(fields){return Object.fromEntries(Object.entries(fields).map(([key,value])=>{if(!value||typeof value!="object"||Array.isArray(value))return[key,{type:void 0}];let field=value,target=typeof field.target=="string"?field.target:void 0,targets=Array.isArray(field.targets)?field.targets.filter(candidate=>typeof candidate=="string"):void 0;return[key,{...field,type:typeof field.type=="string"?field.type:void 0,target,targetPascal:target?pascalCase(target):void 0,targets:targets&&targets.length>0?targets:void 0,targetRefs:targets&&targets.length>0?targets.map(candidate=>({uid:candidate,pascal:pascalCase(candidate)})):void 0,many:typeof field.many=="boolean"?field.many:void 0,multiple:typeof field.multiple=="boolean"?field.multiple:void 0}]}))}function referenceImportsFor(schema,fields){let imports=new Map;for(let field of Object.values(fields)){if(field.type!=="reference")continue;let targets=field.targets??(field.target?[field.target]:[]);for(let target of targets)target!==schema.uid&&imports.set(target,{uid:target,pascal:pascalCase(target)})}return[...imports.values()].sort((a,b)=>a.pascal.localeCompare(b.pascal))}function schemaToModel(schema,localizedByUid){let fields=normalizeFields(schema.fields??{});return{uid:schema.uid,pascal:pascalCase(schema.uid),isSingleton:schema.isSingleton??!1,localized:schema.i18n?.enabled!==!1,localizedReferenceFields:Object.entries(fields).filter(([,field])=>field.type!=="reference"?!1:(field.targets??(field.target?[field.target]:[])).some(target=>localizedByUid.get(target)!==!1)).map(([fieldName])=>fieldName),fields,referenceImports:referenceImportsFor(schema,fields)}}function syncSchemas(options={}){let cwd=options.cwd??process.cwd(),log=__name(msg=>{options.verbose!==!1&&console.log(msg)},"log"),schemasDir=resolve4(cwd,SCHEMAS_REL),schemaFiles=getSchemaFiles(schemasDir),schemas3=loadSchemas(schemaFiles),generatedFilesOnDisk=getGeneratedFiles(schemasDir),runtime=schemas3.length>0||generatedFilesOnDisk.length>0?resolveProjectRuntime(cwd):null,templates=[{suffix:".types.ts",path:templatePath(runtime,"types-template.eta")},{suffix:".ts",path:templatePath(runtime,"hooks-template.eta")}].map(template=>({...template,source:readFileSync5(template.path,"utf-8")})),eta=new Eta({views:void 0,useWith:!0,varName:"it",autoEscape:!1}),localizedByUid=new Map(schemas3.map(({schema})=>[schema.uid,schema.i18n?.enabled!==!1])),expectedTsFiles=new Set,generatedFiles=new Map,created=0,updated=0,deleted=0;for(let{pascal,schema}of schemas3){let model=schemaToModel(schema,localizedByUid);for(let template of templates){let tsPath=join6(schemasDir,`${pascal}${template.suffix}`);expectedTsFiles.add(tsPath),generatedFiles.set(tsPath,eta.renderString(template.source,{model}))}}for(let[tsPath,content2]of generatedFiles){let dir=dirname5(tsPath);if(existsSync4(dir)||mkdirSync3(dir,{recursive:!0}),!existsSync4(tsPath)){writeFileSync4(tsPath,content2,"utf-8"),created++,log(`Created: ${tsPath}`);continue}readFileSync5(tsPath,"utf-8")!==content2&&(writeFileSync4(tsPath,content2,"utf-8"),updated++,log(`Updated: ${tsPath}`))}for(let tsFile of generatedFilesOnDisk)if(!expectedTsFiles.has(tsFile))try{unlinkSync2(tsFile),deleted++,log(`Deleted orphaned: ${tsFile}`)}catch(error){console.error(`Failed to delete orphaned ${tsFile}:`,error)}return(created>0||updated>0||deleted>0)&&options.verbose!==!1&&log(`Sync schemas: ${created} created, ${updated} updated, ${deleted} deleted`),{created,updated,deleted}}var SCHEMAS_REL,MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION,CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND,SCHEMA_DEFINITION_SCHEMA,init_sync_schemas=__esm({"src/scripts/sync-schemas.ts"(){init_dist6();init_eta_module();init_assets();SCHEMAS_REL="src/schemas",MINIMUM_THIN_CONTENT_CLIENT_RUNTIME_VERSION="0.7.0",CONTENT_CLIENT_RUNTIME_UPGRADE_COMMAND="npm install fimo@latest",SCHEMA_DEFINITION_SCHEMA=z68.object({uid:z68.string().min(1),isSingleton:z68.boolean().optional(),i18n:z68.object({enabled:z68.boolean().optional()}).optional(),fields:z68.record(z68.string(),z68.unknown()).optional()});__name(getSchemaFiles,"getSchemaFiles");__name(getGeneratedFiles,"getGeneratedFiles");__name(parseVersion,"parseVersion");__name(isVersionAtLeast,"isVersionAtLeast");__name(resolveProjectRuntime,"resolveProjectRuntime");__name(templatePath,"templatePath");__name(loadSchemas,"loadSchemas");__name(normalizeFields,"normalizeFields");__name(referenceImportsFor,"referenceImportsFor");__name(schemaToModel,"schemaToModel");__name(syncSchemas,"syncSchemas")}});function renderCrossSurface(findings,p2,opts={}){let lines=[];lines.push(p2.bold("CROSS-SURFACE INTEGRITY")),lines.push(p2.dim(" references that span surfaces"));let errorGlyph=opts.ascii?"!!":"\u203C",arrow=opts.ascii?"->":"\u2192",sep2=opts.ascii?"|":"\xB7";for(let f of findings){let glyph=f.severity==="error"?p2.red("!"):p2.yellow(errorGlyph);lines.push(` ${glyph} ${f.description}`);let trail=`${f.source.surface}:${f.source.key} ${arrow} ${f.target.surface}:${f.target.key}`;lines.push(p2.dim(` ${trail}`)),f.actions.length>0&&lines.push(p2.dim(` actions: ${f.actions.join(` ${sep2} `)}`))}return lines.join(`
305
305
  `)}var init_cross_surface=__esm({"src/cli/utils/format/cross-surface.ts"(){__name(renderCrossSurface,"renderCrossSurface")}});function getTerminalWidth(){let w3=process.stdout.columns;return typeof w3=="number"&&w3>0?w3:100}function layoutKeyDetail(args){let{indent,key,keyLength,detail,detailLength=0,width}=args;if(!detail)return`${indent}${key}`;let minGap=args.minGap??2,used=indent.length+keyLength+minGap+detailLength;if(width<80||used>=width)return`${indent}${key}${" ".repeat(minGap)}${detail}`;let padding=width-indent.length-keyLength-detailLength;return`${indent}${key}${" ".repeat(padding)}${detail}`}var init_columns=__esm({"src/cli/utils/format/columns.ts"(){__name(getTerminalWidth,"getTerminalWidth");__name(layoutKeyDetail,"layoutKeyDetail")}});var activations,init_activations=__esm({"src/cli/utils/format/surface-presenters/activations.ts"(){activations={label:"AGENTS",hint:"declared \xB7 active",emptyCopy:" (no agents activated)",groupBy:__name(item=>item.detail??"(no agent)","groupBy"),keyFormatter:__name(item=>{let idx=item.key.indexOf(":");return idx>0?`trigger ${item.key.slice(idx+1)}`:item.key},"keyFormatter"),detailFormatter:__name(()=>{},"detailFormatter")}}});function shortId(id){return id.length>12?`${id.slice(0,8)}\u2026`:id}var assets,init_assets2=__esm({"src/cli/utils/format/surface-presenters/assets.ts"(){assets={label:"ASSETS",hint:"media library",emptyCopy:" (no asset changes)",keyFormatter:__name(item=>item.detail??item.key,"keyFormatter"),detailFormatter:__name(item=>{if(item.detail&&item.key!==item.detail)return shortId(item.key)},"detailFormatter")};__name(shortId,"shortId")}});var code,init_code=__esm({"src/cli/utils/format/surface-presenters/code.ts"(){code={label:"CODE",hint:"git workspace vs HEAD",emptyCopy:" (clean)"}}});var content,init_content=__esm({"src/cli/utils/format/surface-presenters/content.ts"(){content={label:"CONTENT",hint:"entries per collection",emptyCopy:" (no content changes)",groupBy:__name(item=>item.detail??"(unknown)","groupBy"),keyFormatter:__name(item=>{let idx=item.key.indexOf(":");return idx>0?item.key.slice(idx+1):item.key},"keyFormatter"),detailFormatter:__name(()=>{},"detailFormatter")}}});var forms,init_forms=__esm({"src/cli/utils/format/surface-presenters/forms.ts"(){forms={label:"FORMS",hint:"schema changes",emptyCopy:" (no form changes)"}}});var schemas,init_schemas=__esm({"src/cli/utils/format/surface-presenters/schemas.ts"(){schemas={label:"SCHEMAS",hint:"content types",emptyCopy:" (no schema changes)",groupBy:__name(item=>{let idx=item.key.indexOf(".");return idx>0?item.key.slice(0,idx):""},"groupBy"),keyFormatter:__name(item=>{let idx=item.key.indexOf(".");return idx>0?item.key.slice(idx+1):item.key},"keyFormatter")}}});var translations,init_translations=__esm({"src/cli/utils/format/surface-presenters/translations.ts"(){translations={label:"TRANSLATIONS",hint:"per locale",emptyCopy:" (no translation changes)",groupBy:__name(item=>item.detail??"(no locale)","groupBy"),keyFormatter:__name(item=>{let idx=item.key.indexOf(":");return idx>0?item.key.slice(idx+1):item.key},"keyFormatter"),detailFormatter:__name(()=>{},"detailFormatter")}}});var SURFACE_PRESENTERS,init_surface_presenters=__esm({"src/cli/utils/format/surface-presenters/index.ts"(){init_activations();init_assets2();init_code();init_content();init_forms();init_schemas();init_translations();SURFACE_PRESENTERS={code,schemas,content,translations,assets,forms,activations}}});function renderItem(item,p2,opts={}){let glyph=VERB_GLYPHS[item.verb]??"?",colored=item.verb==="added"?p2.green(glyph):item.verb==="removed"?p2.red(glyph):item.verb==="conflict"?p2.yellow(glyph):p2.blue(glyph),indent=opts.indent??" ",displayKey=opts.presenter?.keyFormatter?opts.presenter.keyFormatter(item):item.key,displayDetail=opts.presenter?.detailFormatter?opts.presenter.detailFormatter(item):item.detail,width=opts.width;if(item.origin===void 0)return layoutCore({indent,marker:"",markerLen:0,colored,displayKey,displayDetail,width,p:p2});let marker=item.origin==="local-uncommitted"?p2.yellow("*"):" ";return layoutCore({indent,marker,markerLen:1,colored,displayKey,displayDetail,width,p:p2})}function layoutCore(args){let{indent,marker,markerLen,colored,displayKey,displayDetail,width,p:p2}=args,prefix=`${marker}${colored} ${displayKey}`,prefixLen=markerLen+1+1+displayKey.length;return displayDetail?width===void 0?`${indent}${prefix}${p2.dim(` ${displayDetail}`)}`:layoutKeyDetail({indent,key:prefix,keyLength:prefixLen,detail:p2.dim(displayDetail),detailLength:displayDetail.length,width}):`${indent}${prefix}`}function renderSurface(delta,p2,opts={}){let display=SURFACE_DISPLAY[delta.surface],presenter=SURFACE_PRESENTERS[delta.surface],lines=[],includeHeader=opts.includeHeader??!0,maxItems=opts.maxItems??50,width=opts.width??getTerminalWidth();if(includeHeader&&(lines.push(p2.bold(display.label)),lines.push(p2.dim(` ${display.hint}`))),delta.status==="timed_out")return lines.push(p2.yellow(" (surface check timed out)")),lines.join(`
306
306
  `);if(delta.status==="failed")return lines.push(p2.red(` (surface check failed: ${delta.error??"unknown"})`)),lines.join(`
307
307
  `);if(delta.status==="unchanged"||delta.changedCount===0&&delta.conflictCount===0)return lines.push(p2.dim(display.emptyCopy)),lines.join(`
@@ -595,8 +595,8 @@ Force-exiting. Project may not have been fully cleaned up.
595
595
  Aborted. Deleting project ${projectName}\u2026
596
596
  `),api.deleteProject(projectId).then(()=>{process.stderr.write(`Deleted project ${projectName}.
597
597
  `)}).catch(error=>{process.stderr.write(`Failed to delete project: ${error instanceof Error?error.message:String(error)}
598
- `)}).finally(()=>{process.exit(130)})},"handler");return process.on("SIGINT",handler),()=>{process.off("SIGINT",handler)}}function installArgsForPackageManager(packageManager){return packageManager==="pnpm"?["install","--config.dangerouslyAllowAllBuilds=true"]:["install"]}function formatPackageManagerCommand(packageManager,args){return[packageManager,...args].join(" ")}async function installDependencies(packageManager,targetDir){let args=installArgsForPackageManager(packageManager),command=formatPackageManagerCommand(packageManager,args),installSp=spinner(`Installing dependencies (${command})`);try{return await execFileAsync7(packageManager,args,{cwd:targetDir}),installSp.succeed("Dependencies installed"),{installed:!0,command,error:null}}catch(error){let message=error instanceof Error?error.message:String(error);return installSp.fail(`Failed to install dependencies: ${message}`),{installed:!1,command,error:message}}}function detectPackageManager2(){return isCommandAvailable("pnpm")?"pnpm":isCommandAvailable("bun")?"bun":isCommandAvailable("yarn")?"yarn":"npm"}function isCommandAvailable(command){let probe=process.platform==="win32"?"where":"which";return spawnSync2(probe,[command],{stdio:"ignore"}).status===0}async function resolveOrganization(api,explicit,options={}){if(explicit)return explicit;let activeOrganizationId=readCredentials()?.activeOrganization?.id,nonInteractive2=options.nonInteractive??(currentMode().format==="json"||!isInteractive());if(nonInteractive2&&activeOrganizationId)return activeOrganizationId;let orgs2;try{orgs2=await api.listOrganizations()}catch(error){throw rethrowCliAuthError(error),new ScaffoldError("LIST_ORGS_FAILED",`Failed to list organizations: ${error instanceof Error?error.message:String(error)}`)}if(orgs2.length===0)throw new ScaffoldError("NO_ORGANIZATIONS","No organization found for this account.");if(orgs2.length===1)return orgs2[0].id;if(nonInteractive2)throw new ScaffoldError("ORGANIZATION_REQUIRED","Several organizations are available and no active organization is configured.","Pass --org <organizationId>, or run `fimo orgs switch --org <id-or-slug>` first.");let currentId=orgs2.some(organization=>organization.id===activeOrganizationId)?activeOrganizationId:void 0,selected=await _t({message:"Select an organization for this project",initialValue:currentId,options:orgs2.map(organization=>({value:organization.id,label:organization.name,hint:organization.id===currentId?"current":organization.slug}))});if(q(selected))throw new ScaffoldError("ORGANIZATION_SELECTION_CANCELLED","Organization selection cancelled.");return selected}var execFileAsync7,MAIN_BRANCH,ScaffoldError,init_scaffold_project=__esm({"src/cli/commands/scaffold-project.ts"(){init_dist5();init_dist();init_api();init_auth();init_agents();init_auth_errors();init_git_credential_setup();init_git();init_interactive();init_local_project_files();init_scaffold();init_skills();execFileAsync7=promisify8(execFile8),MAIN_BRANCH="main",ScaffoldError=class extends Error{static{__name(this,"ScaffoldError")}code;hint;constructor(code2,message,hint){super(message),this.name="ScaffoldError",this.code=code2,this.hint=hint}};__name(explainCreateProjectError,"explainCreateProjectError");__name(scaffoldNewProject,"scaffoldNewProject");__name(scaffoldIntoProject,"scaffoldIntoProject");__name(finalizeInitialCommit,"finalizeInitialCommit");__name(installAbortHandler,"installAbortHandler");__name(installArgsForPackageManager,"installArgsForPackageManager");__name(formatPackageManagerCommand,"formatPackageManagerCommand");__name(installDependencies,"installDependencies");__name(detectPackageManager2,"detectPackageManager");__name(isCommandAvailable,"isCommandAvailable");__name(resolveOrganization,"resolveOrganization")}});import fs32 from"node:fs";import path33 from"node:path";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}:{}})}}function isPretty(){return currentMode().format==="pretty"}function nonInteractive(options){return options.yes===!0||currentMode().format==="json"||!isInteractive()}async function initCommand(dirArg,options){isPretty()&&mt("Set up your Fimo project"),emitInitOutcome("init",await runInit(dirArg,options))}async function runInit(dirArg,options){let cfg=loadConfig();if(options.packageManager&&!PACKAGE_MANAGERS.includes(options.packageManager.toLowerCase()))return{status:"error",code:"PACKAGE_MANAGER_INVALID",message:`Unknown package manager "${options.packageManager}".`,hint:`Use one of: ${PACKAGE_MANAGERS.join(", ")}.`};let authAbort=await ensureAuthenticated(cfg,nonInteractive(options));if(authAbort)return authAbort;let api=new FimoApiClient(cfg),creds=readCredentials(cfg),mode2=await resolveUseExisting(options);if(mode2==="cancelled")return{status:"cancelled"};let useExisting=mode2==="existing",planned=await planInit({api,creds,useExisting,dirArg,options});if("status"in planned)return planned;let{plan}=planned,ran=useExisting?await runExisting({api,cfg,projectId:plan.projectId,dirArg,options:plan.options}):await runNew({api,cfg,targetDir:plan.targetDir,displayName:plan.displayName,options:plan.options});if("status"in ran)return ran;let{checkout}=ran.run,scaffoldSummary=ran.run.summary,scaffoldedAgents=ran.run.selectedAgents,pushedInitial=!0,depResult=await maybeInstallDependencies(checkout.targetDir,plan.packageManager);try{({pushedInitial}=await ran.run.finalize(checkout.targetDir))}finally{ran.run.releaseAbort()}let skills2=await maybeInstallSkills(plan.options,scaffoldedAgents),warnings=[];return pushedInitial||warnings.push("Initial commit was not pushed \u2014 the project's remote is empty. Sign in (`fimo login`), then run `fimo deploy` from the project to push it."),depResult.error&&warnings.push(`Dependency install failed: ${depResult.error}`),skills2.error&&warnings.push(skills2.error),{status:"ok",data:{ok:!0,project_id:checkout.projectId,project_name:checkout.projectName,mode:useExisting?"existing":"new",target_dir:checkout.targetDir,relative_dir:checkout.relativeTarget,scaffold:scaffoldSummary,installed_deps:depResult.installed,package_manager:depResult.packageManager,install_error:depResult.error,skills_set_up:skills2.setUp,skills_error:skills2.error,pushed_initial:pushedInitial},renderArgs:{projectName:checkout.projectName,relativeDir:checkout.relativeTarget,isNew:!useExisting,installedDeps:depResult.installed,packageManager:depResult.packageManager,pushedInitial},warnings}}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 project'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 project ${args.projectName} ${args.isNew?"has been created":"is linked"}.`)}`),lines.push(""),lines.push(`${p2.dim("(cd")} ${p2.cyan(args.relativeDir)} ${p2.dim("to navigate to your project 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(`
599
- `)}function renderInitPushFailed(p2,ascii,args){let warn=ascii?"[!]":"\u26A0\uFE0F",steps=[["npx fimo login","to sign in (if you are not already)"],["npx fimo deploy","to push the first commit and finish setup"]],width=Math.max(...steps.map(([c2])=>c2.length)),lines=[];lines.push(`${warn} ${p2.bold(`Your project ${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(""),lines.push(`${p2.dim("(cd")} ${p2.cyan(args.relativeDir)} ${p2.dim("then finish setup:)")}`);for(let[cmd,desc]of steps)lines.push(`${p2.cyan(cmd.padEnd(width))} ${p2.dim(desc)}`);return lines.join(`
598
+ `)}).finally(()=>{process.exit(130)})},"handler");return process.on("SIGINT",handler),()=>{process.off("SIGINT",handler)}}function installArgsForPackageManager(packageManager){return packageManager==="pnpm"?["install","--config.dangerouslyAllowAllBuilds=true"]:["install"]}function formatPackageManagerCommand(packageManager,args){return[packageManager,...args].join(" ")}async function installDependencies(packageManager,targetDir){let args=installArgsForPackageManager(packageManager),command=formatPackageManagerCommand(packageManager,args),installSp=spinner(`Installing dependencies (${command})`);try{return await execFileAsync7(packageManager,args,{cwd:targetDir}),installSp.succeed("Dependencies installed"),{installed:!0,command,error:null}}catch(error){let message=error instanceof Error?error.message:String(error);return installSp.fail(`Failed to install dependencies: ${message}`),{installed:!1,command,error:message}}}function detectPackageManager2(){return isCommandAvailable("pnpm")?"pnpm":isCommandAvailable("bun")?"bun":isCommandAvailable("yarn")?"yarn":"npm"}function isCommandAvailable(command){let probe=process.platform==="win32"?"where":"which";return spawnSync2(probe,[command],{stdio:"ignore"}).status===0}async function resolveOrganization(api,explicit,options={}){if(explicit)return explicit;let activeOrganizationId=readCredentials()?.activeOrganization?.id,nonInteractive2=options.nonInteractive??(currentMode().format==="json"||!isInteractive());if(nonInteractive2&&activeOrganizationId)return activeOrganizationId;let orgs2;try{orgs2=await api.listOrganizations()}catch(error){throw rethrowCliAuthError(error),new ScaffoldError("LIST_ORGS_FAILED",`Failed to list organizations: ${error instanceof Error?error.message:String(error)}`)}if(orgs2.length===0)throw new ScaffoldError("NO_ORGANIZATIONS","No organization found for this account.");if(orgs2.length===1)return orgs2[0].id;if(nonInteractive2)throw new ScaffoldError("ORGANIZATION_REQUIRED","Several organizations are available and no active organization is configured.","Pass --org <organizationId>, or run `fimo orgs switch --org <id-or-slug>` first.");let currentId=orgs2.some(organization=>organization.id===activeOrganizationId)?activeOrganizationId:void 0,selected=await _t({message:"Select an organization for this project",initialValue:currentId,options:orgs2.map(organization=>({value:organization.id,label:organization.name,hint:organization.id===currentId?"current":organization.slug}))});if(q(selected))throw new ScaffoldError("ORGANIZATION_SELECTION_CANCELLED","Organization selection cancelled.");return selected}var execFileAsync7,MAIN_BRANCH,ScaffoldError,init_scaffold_project=__esm({"src/cli/commands/scaffold-project.ts"(){init_dist5();init_dist();init_api();init_auth();init_agents();init_auth_errors();init_git_credential_setup();init_git();init_interactive();init_local_project_files();init_scaffold();init_skills();execFileAsync7=promisify8(execFile8),MAIN_BRANCH="main",ScaffoldError=class extends Error{static{__name(this,"ScaffoldError")}code;hint;constructor(code2,message,hint){super(message),this.name="ScaffoldError",this.code=code2,this.hint=hint}};__name(explainCreateProjectError,"explainCreateProjectError");__name(scaffoldNewProject,"scaffoldNewProject");__name(scaffoldIntoProject,"scaffoldIntoProject");__name(finalizeInitialCommit,"finalizeInitialCommit");__name(installAbortHandler,"installAbortHandler");__name(installArgsForPackageManager,"installArgsForPackageManager");__name(formatPackageManagerCommand,"formatPackageManagerCommand");__name(installDependencies,"installDependencies");__name(detectPackageManager2,"detectPackageManager");__name(isCommandAvailable,"isCommandAvailable");__name(resolveOrganization,"resolveOrganization")}});import fs32 from"node:fs";import path33 from"node:path";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}:{}})}}function isPretty(){return currentMode().format==="pretty"}function nonInteractive(options){return options.yes===!0||currentMode().format==="json"||!isInteractive()}async function initCommand(dirArg,options){isPretty()&&mt("Set up your Fimo project"),emitInitOutcome("init",await runInit(dirArg,options))}async function runInit(dirArg,options){let cfg=loadConfig();if(options.packageManager&&!PACKAGE_MANAGERS.includes(options.packageManager.toLowerCase()))return{status:"error",code:"PACKAGE_MANAGER_INVALID",message:`Unknown package manager "${options.packageManager}".`,hint:`Use one of: ${PACKAGE_MANAGERS.join(", ")}.`};let authAbort=await ensureAuthenticated(cfg,nonInteractive(options));if(authAbort)return authAbort;let api=new FimoApiClient(cfg),creds=readCredentials(cfg),mode2=await resolveUseExisting(options);if(mode2==="cancelled")return{status:"cancelled"};let useExisting=mode2==="existing",planned=await planInit({api,creds,useExisting,dirArg,options});if("status"in planned)return planned;let{plan}=planned,ran=useExisting?await runExisting({api,cfg,projectId:plan.projectId,dirArg,options:plan.options}):await runNew({api,cfg,targetDir:plan.targetDir,displayName:plan.displayName,options:plan.options});if("status"in ran)return ran;let{checkout}=ran.run,scaffoldSummary=ran.run.summary,scaffoldedAgents=ran.run.selectedAgents,pushedInitial=!0,depResult=await maybeInstallDependencies(checkout.targetDir,plan.packageManager);try{({pushedInitial}=await ran.run.finalize(checkout.targetDir))}finally{ran.run.releaseAbort()}let skills2=await maybeInstallSkills(plan.options,scaffoldedAgents),warnings=[];return pushedInitial||warnings.push("Initial commit was not pushed \u2014 the project's remote is empty. Sign in (`fimo login`), then run `fimo deploy` from the project to push it."),depResult.error&&warnings.push(`Dependency install failed: ${depResult.error}`),skills2.error&&warnings.push(skills2.error),{status:"ok",data:{ok:!0,project_id:checkout.projectId,project_name:checkout.projectName,mode:useExisting?"existing":"new",target_dir:checkout.targetDir,relative_dir:checkout.relativeTarget,scaffold:scaffoldSummary,installed_deps:depResult.installed,package_manager:depResult.packageManager,install_error:depResult.error,skills_set_up:skills2.setUp,skills_error:skills2.error,pushed_initial:pushedInitial},renderArgs:{projectName:checkout.projectName,relativeDir:checkout.relativeTarget,isNew:!useExisting,installedDeps:depResult.installed,packageManager:depResult.packageManager,pushedInitial},warnings}}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 project'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 project ${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 project 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(`
599
+ `)}function renderInitPushFailed(p2,ascii,args){let warn=ascii?"[!]":"\u26A0\uFE0F",steps=[["npx fimo login","to sign in (if you are not already)"],["npx fimo deploy","to push the first commit and finish setup"]],width=Math.max(...steps.map(([c2])=>c2.length)),lines=[];lines.push(`${warn} ${p2.bold(`Your project ${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(`
600
600
  `)}async function ensureAuthenticated(cfg,noPrompt){if(readCredentials(cfg)?.access_token)return null;if(noPrompt)return{status:"error",code:"NOT_AUTHENTICATED",message:"You are not signed in to Fimo.",hint:"Run `fimo login` first, then re-run `fimo init`."};isPretty()&&O2.step("You are not signed in yet \u2014 opening your browser to sign in.");try{return await performBrowserLogin(cfg),null}catch(error){if(error instanceof LoginError)return{status:"error",code:error.code,message:error.message};throw error}}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 project"},{value:"existing",label:"Link an existing project"}]});return q(choice)?"cancelled":choice==="existing"?"existing":"new"}async function planInit(args){let{api,creds,useExisting,dirArg,options}=args,projectId,targetDir,displayName,derived={...options};if(useExisting)if(options.projectId)projectId=options.projectId;else{let picked=await selectProjectId({api,activeOrganizationId:creds?.activeOrganization?.id??null,message:"Select a project to link"});if(picked.status==="empty")return{status:"info",message:picked.message};if(picked.status!=="selected")return picked;projectId=picked.projectId}else{let resolved=await resolveTargetDir(dirArg,nonInteractive(options));if("status"in resolved)return resolved;if(targetDir=resolved.targetDir,displayName=resolved.displayName,fs32.existsSync(targetDir)&&fs32.readdirSync(targetDir).length>0){let name=path33.basename(targetDir);return{status:"error",code:"DIRECTORY_NOT_EMPTY",message:`The folder "${name}" already exists and isn't empty.`,hint:`Pick a different directory (e.g. \`fimo init <dir>\`), or empty "${name}" first.`}}try{derived.org=await resolveOrganization(api,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))useExisting&&options.skills===!1&&!derived.agents&&(derived.agents="none");else{let wantSkills;if(options.skills===!0||options.skills===!1)wantSkills=options.skills;else{let alreadySetUp=(await detectAgentsWithFimoSkills()).length>0,answer=await ot2({message:alreadySetUp?"Fimo skills are already set up for your AI agents. Set them up again?":"Set up Fimo skills for your AI coding agents?",initialValue:!alreadySetUp});if(q(answer))return{status:"cancelled"};wantSkills=answer}if(wantSkills){let agents;try{agents=await selectAgents(options,{promptMessage:"Which agents do you want to set up?",detectFn:detectAgentsWithFimoSkills})}catch(err){return{status:"error",code:"AGENT_SELECTION_FAILED",message:err instanceof Error?err.message:String(err)}}derived.skills=!0,derived.agents=agents.length>0?agents.join(","):"none"}else derived.skills=!1,derived.agents="none"}let packageManager=options.install===!1?null:await resolvePackageManager(derived);return{plan:{projectId,targetDir,displayName,packageManager,options:derived}}}async function runExisting(args){let{api,cfg,projectId,dirArg,options}=args;try{let result=await cloneProject({api,cfg,projectId,dir:dirArg,env:options.env});return{run:{checkout:{projectId:result.project.id,projectName:result.project.displayName??result.project.name,targetDir:result.targetDir,relativeTarget:result.relativeTarget},summary:null,selectedAgents:null,finalize:__name(async()=>({pushedInitial:!0}),"finalize"),releaseAbort:__name(()=>{},"releaseAbort")}}}catch(error){if(error instanceof CloneError&&error.code==="EMPTY_REMOTE"&&error.emptyRemote)return adoptEmptyRemote({api,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}}async function adoptEmptyRemote(args){let{api,cfg,ctx,options}=args;isPretty()&&O2.step("This project has no content yet \u2014 scaffolding a starter site and pushing the first commit.");try{let result=await scaffoldIntoProject({project:ctx.project,api,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},summary:null,selectedAgents:result.selectedAgents,finalize:__name(targetDir=>finalizeInitialCommit({targetDir}),"finalize"),releaseAbort:__name(()=>{},"releaseAbort")}}}catch(error){if(error instanceof ScaffoldError)return{status:"error",code:error.code,message:error.message,...error.hint?{hint:error.hint}:{}};throw error}}async function runNew(args){let{api,cfg,targetDir,displayName,options}=args;try{let{scaffold,releaseAbort}=await scaffoldNewProject({api,cfg,targetDir,displayName,options});return{run:{checkout:{projectId:scaffold.project.id,projectName:scaffold.project.displayName??scaffold.project.name,targetDir:scaffold.targetDir,relativeTarget:scaffold.relativeTarget},summary:null,selectedAgents:scaffold.selectedAgents,finalize:__name(dir=>finalizeInitialCommit({targetDir:dir}),"finalize"),releaseAbort}}}catch(error){if(error instanceof ScaffoldError)return{status:"error",code:error.code,message:error.message,...error.hint?{hint:error.hint}:{}};throw error}}async function resolveTargetDir(dirArg,noPrompt){if(dirArg)return{targetDir:path33.resolve(dirArg)};if(noPrompt)return{status:"error",code:"DIRECTORY_REQUIRED",message:"A target directory is required to create a new project.",hint:"Pass [dir] (e.g. `fimo init my-site`), or `--project-id <id>` to link an existing project."};let input=await Ot({message:"Project name",placeholder:"My Fimo Site",validate:__name(value=>value&&value.trim().length>0?void 0:"project name required","validate")});if(q(input))return{status:"cancelled"};let displayName=String(input).trim(),folder=slugifyName(displayName)||"fimo-project";return{targetDir:path33.resolve(folder),displayName}}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}}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}async function maybeInstallSkills(options,scaffoldedAgents){if(options.skills===!1)return{setUp:!1,error:null};if(options.skills!==!0&&nonInteractive(options))return{setUp:!1,error:null};let agentsFlag=options.agents;if(scaffoldedAgents!==null){if(scaffoldedAgents.length===0)return{setUp:!1,error:null};agentsFlag=scaffoldedAgents.join(",")}else if(nonInteractive(options)&&!agentsFlag)return{setUp:!1,error:null};let outcome=await runSkillsInstall({agents:agentsFlag,agent:scaffoldedAgents!==null?void 0:options.agent,yes:!0});return outcome.status==="error"&&outcome.code==="NO_AGENTS_SELECTED"?{setUp:!1,error:null}:outcome.status==="ok"?{setUp:!0,error:outcome.data.ok?null:"Some skills failed to install."}:outcome.status==="cancelled"?{setUp:!1,error:null}:{setUp:!1,error:outcome.message}}var PACKAGE_MANAGERS,MANUAL_INSTALL,init_init=__esm({"src/cli/commands/init.ts"(){init_dist5();init_dist();init_api();init_auth();init_config();init_agents();init_color();init_interactive();init_slug();init_clone();init_login();init_scaffold_project();init_skills();PACKAGE_MANAGERS=["npm","pnpm","yarn","bun"],MANUAL_INSTALL="manual";__name(emitInitOutcome,"emitInitOutcome");__name(isPretty,"isPretty");__name(nonInteractive,"nonInteractive");__name(initCommand,"initCommand");__name(runInit,"runInit");__name(renderInitSuccess,"renderInitSuccess");__name(renderInitPushFailed,"renderInitPushFailed");__name(ensureAuthenticated,"ensureAuthenticated");__name(resolveUseExisting,"resolveUseExisting");__name(planInit,"planInit");__name(runExisting,"runExisting");__name(adoptEmptyRemote,"adoptEmptyRemote");__name(runNew,"runNew");__name(resolveTargetDir,"resolveTargetDir");__name(maybeInstallDependencies,"maybeInstallDependencies");__name(resolvePackageManager,"resolvePackageManager");__name(maybeInstallSkills,"maybeInstallSkills")}});function flattenOptions(options,baseOptions){if(!options)return baseOptions??defaultOpts;let opts={_useHtmlParser2:!!options.xmlMode,...baseOptions,...options};return options.xml?(opts._useHtmlParser2=!0,opts.xmlMode=!0,options.xml!==!0&&Object.assign(opts,options.xml)):options.xmlMode&&(opts._useHtmlParser2=!0),opts}var defaultOpts,init_options=__esm({"../../node_modules/.pnpm/cheerio@1.2.0/node_modules/cheerio/dist/esm/options.js"(){defaultOpts={_useHtmlParser2:!1};__name(flattenOptions,"flattenOptions")}});var esm_exports={};__export(esm_exports,{CDATA:()=>CDATA,Comment:()=>Comment,Directive:()=>Directive,Doctype:()=>Doctype,ElementType:()=>ElementType,Root:()=>Root,Script:()=>Script,Style:()=>Style,Tag:()=>Tag,Text:()=>Text,isTag:()=>isTag});function isTag(elem){return elem.type===ElementType.Tag||elem.type===ElementType.Script||elem.type===ElementType.Style}var ElementType,Root,Text,Directive,Comment,Script,Style,Tag,CDATA,Doctype,init_esm2=__esm({"../../node_modules/.pnpm/domelementtype@2.3.0/node_modules/domelementtype/lib/esm/index.js"(){(function(ElementType2){ElementType2.Root="root",ElementType2.Text="text",ElementType2.Directive="directive",ElementType2.Comment="comment",ElementType2.Script="script",ElementType2.Style="style",ElementType2.Tag="tag",ElementType2.CDATA="cdata",ElementType2.Doctype="doctype"})(ElementType||(ElementType={}));__name(isTag,"isTag");Root=ElementType.Root,Text=ElementType.Text,Directive=ElementType.Directive,Comment=ElementType.Comment,Script=ElementType.Script,Style=ElementType.Style,Tag=ElementType.Tag,CDATA=ElementType.CDATA,Doctype=ElementType.Doctype}});function isTag2(node){return isTag(node)}function isCDATA(node){return node.type===ElementType.CDATA}function isText(node){return node.type===ElementType.Text}function isComment(node){return node.type===ElementType.Comment}function isDirective(node){return node.type===ElementType.Directive}function isDocument(node){return node.type===ElementType.Root}function hasChildren(node){return Object.prototype.hasOwnProperty.call(node,"children")}function cloneNode(node,recursive=!1){let result;if(isText(node))result=new Text2(node.data);else if(isComment(node))result=new Comment2(node.data);else if(isTag2(node)){let children2=recursive?cloneChildren(node.children):[],clone2=new Element(node.name,{...node.attribs},children2);children2.forEach(child=>child.parent=clone2),node.namespace!=null&&(clone2.namespace=node.namespace),node["x-attribsNamespace"]&&(clone2["x-attribsNamespace"]={...node["x-attribsNamespace"]}),node["x-attribsPrefix"]&&(clone2["x-attribsPrefix"]={...node["x-attribsPrefix"]}),result=clone2}else if(isCDATA(node)){let children2=recursive?cloneChildren(node.children):[],clone2=new CDATA2(children2);children2.forEach(child=>child.parent=clone2),result=clone2}else if(isDocument(node)){let children2=recursive?cloneChildren(node.children):[],clone2=new Document(children2);children2.forEach(child=>child.parent=clone2),node["x-mode"]&&(clone2["x-mode"]=node["x-mode"]),result=clone2}else if(isDirective(node)){let instruction=new ProcessingInstruction(node.name,node.data);node["x-name"]!=null&&(instruction["x-name"]=node["x-name"],instruction["x-publicId"]=node["x-publicId"],instruction["x-systemId"]=node["x-systemId"]),result=instruction}else throw new Error(`Not implemented yet: ${node.type}`);return result.startIndex=node.startIndex,result.endIndex=node.endIndex,node.sourceCodeLocation!=null&&(result.sourceCodeLocation=node.sourceCodeLocation),result}function cloneChildren(childs){let children2=childs.map(child=>cloneNode(child,!0));for(let i=1;i<children2.length;i++)children2[i].prev=children2[i-1],children2[i-1].next=children2[i];return children2}var Node,DataNode,Text2,Comment2,ProcessingInstruction,NodeWithChildren,CDATA2,Document,Element,init_node=__esm({"../../node_modules/.pnpm/domhandler@5.0.3/node_modules/domhandler/lib/esm/node.js"(){init_esm2();Node=class{static{__name(this,"Node")}constructor(){this.parent=null,this.prev=null,this.next=null,this.startIndex=null,this.endIndex=null}get parentNode(){return this.parent}set parentNode(parent2){this.parent=parent2}get previousSibling(){return this.prev}set previousSibling(prev2){this.prev=prev2}get nextSibling(){return this.next}set nextSibling(next2){this.next=next2}cloneNode(recursive=!1){return cloneNode(this,recursive)}},DataNode=class extends Node{static{__name(this,"DataNode")}constructor(data2){super(),this.data=data2}get nodeValue(){return this.data}set nodeValue(data2){this.data=data2}},Text2=class extends DataNode{static{__name(this,"Text")}constructor(){super(...arguments),this.type=ElementType.Text}get nodeType(){return 3}},Comment2=class extends DataNode{static{__name(this,"Comment")}constructor(){super(...arguments),this.type=ElementType.Comment}get nodeType(){return 8}},ProcessingInstruction=class extends DataNode{static{__name(this,"ProcessingInstruction")}constructor(name,data2){super(data2),this.name=name,this.type=ElementType.Directive}get nodeType(){return 1}},NodeWithChildren=class extends Node{static{__name(this,"NodeWithChildren")}constructor(children2){super(),this.children=children2}get firstChild(){var _a4;return(_a4=this.children[0])!==null&&_a4!==void 0?_a4:null}get lastChild(){return this.children.length>0?this.children[this.children.length-1]:null}get childNodes(){return this.children}set childNodes(children2){this.children=children2}},CDATA2=class extends NodeWithChildren{static{__name(this,"CDATA")}constructor(){super(...arguments),this.type=ElementType.CDATA}get nodeType(){return 4}},Document=class extends NodeWithChildren{static{__name(this,"Document")}constructor(){super(...arguments),this.type=ElementType.Root}get nodeType(){return 9}},Element=class extends NodeWithChildren{static{__name(this,"Element")}constructor(name,attribs,children2=[],type=name==="script"?ElementType.Script:name==="style"?ElementType.Style:ElementType.Tag){super(children2),this.name=name,this.attribs=attribs,this.type=type}get nodeType(){return 1}get tagName(){return this.name}set tagName(name){this.name=name}get attributes(){return Object.keys(this.attribs).map(name=>{var _a4,_b;return{name,value:this.attribs[name],namespace:(_a4=this["x-attribsNamespace"])===null||_a4===void 0?void 0:_a4[name],prefix:(_b=this["x-attribsPrefix"])===null||_b===void 0?void 0:_b[name]}})}};__name(isTag2,"isTag");__name(isCDATA,"isCDATA");__name(isText,"isText");__name(isComment,"isComment");__name(isDirective,"isDirective");__name(isDocument,"isDocument");__name(hasChildren,"hasChildren");__name(cloneNode,"cloneNode");__name(cloneChildren,"cloneChildren")}});var defaultOpts2,DomHandler,init_esm3=__esm({"../../node_modules/.pnpm/domhandler@5.0.3/node_modules/domhandler/lib/esm/index.js"(){init_esm2();init_node();init_node();defaultOpts2={withStartIndices:!1,withEndIndices:!1,xmlMode:!1},DomHandler=class{static{__name(this,"DomHandler")}constructor(callback,options,elementCB){this.dom=[],this.root=new Document(this.dom),this.done=!1,this.tagStack=[this.root],this.lastNode=null,this.parser=null,typeof options=="function"&&(elementCB=options,options=defaultOpts2),typeof callback=="object"&&(options=callback,callback=void 0),this.callback=callback??null,this.options=options??defaultOpts2,this.elementCB=elementCB??null}onparserinit(parser){this.parser=parser}onreset(){this.dom=[],this.root=new Document(this.dom),this.done=!1,this.tagStack=[this.root],this.lastNode=null,this.parser=null}onend(){this.done||(this.done=!0,this.parser=null,this.handleCallback(null))}onerror(error){this.handleCallback(error)}onclosetag(){this.lastNode=null;let elem=this.tagStack.pop();this.options.withEndIndices&&(elem.endIndex=this.parser.endIndex),this.elementCB&&this.elementCB(elem)}onopentag(name,attribs){let type=this.options.xmlMode?ElementType.Tag:void 0,element=new Element(name,attribs,void 0,type);this.addNode(element),this.tagStack.push(element)}ontext(data2){let{lastNode}=this;if(lastNode&&lastNode.type===ElementType.Text)lastNode.data+=data2,this.options.withEndIndices&&(lastNode.endIndex=this.parser.endIndex);else{let node=new Text2(data2);this.addNode(node),this.lastNode=node}}oncomment(data2){if(this.lastNode&&this.lastNode.type===ElementType.Comment){this.lastNode.data+=data2;return}let node=new Comment2(data2);this.addNode(node),this.lastNode=node}oncommentend(){this.lastNode=null}oncdatastart(){let text3=new Text2(""),node=new CDATA2([text3]);this.addNode(node),text3.parent=node,this.lastNode=text3}oncdataend(){this.lastNode=null}onprocessinginstruction(name,data2){let node=new ProcessingInstruction(name,data2);this.addNode(node)}handleCallback(error){if(typeof this.callback=="function")this.callback(error,this.dom);else if(error)throw error}addNode(node){let parent2=this.tagStack[this.tagStack.length-1],previousSibling=parent2.children[parent2.children.length-1];this.options.withStartIndices&&(node.startIndex=this.parser.startIndex),this.options.withEndIndices&&(node.endIndex=this.parser.endIndex),parent2.children.push(node),previousSibling&&(node.prev=previousSibling,previousSibling.next=node),node.parent=parent2,this.lastNode=null}}}});var decode_data_html_default,init_decode_data_html=__esm({"../../node_modules/.pnpm/entities@4.5.0/node_modules/entities/lib/esm/generated/decode-data-html.js"(){decode_data_html_default=new Uint16Array('\u1D41<\xD5\u0131\u028A\u049D\u057B\u05D0\u0675\u06DE\u07A2\u07D6\u080F\u0A4A\u0A91\u0DA1\u0E6D\u0F09\u0F26\u10CA\u1228\u12E1\u1415\u149D\u14C3\u14DF\u1525\0\0\0\0\0\0\u156B\u16CD\u198D\u1C12\u1DDD\u1F7E\u2060\u21B0\u228D\u23C0\u23FB\u2442\u2824\u2912\u2D08\u2E48\u2FCE\u3016\u32BA\u3639\u37AC\u38FE\u3A28\u3A71\u3AE0\u3B2E\u0800EMabcfglmnoprstu\\bfms\x7F\x84\x8B\x90\x95\x98\xA6\xB3\xB9\xC8\xCFlig\u803B\xC6\u40C6P\u803B&\u4026cute\u803B\xC1\u40C1reve;\u4102\u0100iyx}rc\u803B\xC2\u40C2;\u4410r;\uC000\u{1D504}rave\u803B\xC0\u40C0pha;\u4391acr;\u4100d;\u6A53\u0100gp\x9D\xA1on;\u4104f;\uC000\u{1D538}plyFunction;\u6061ing\u803B\xC5\u40C5\u0100cs\xBE\xC3r;\uC000\u{1D49C}ign;\u6254ilde\u803B\xC3\u40C3ml\u803B\xC4\u40C4\u0400aceforsu\xE5\xFB\xFE\u0117\u011C\u0122\u0127\u012A\u0100cr\xEA\xF2kslash;\u6216\u0176\xF6\xF8;\u6AE7ed;\u6306y;\u4411\u0180crt\u0105\u010B\u0114ause;\u6235noullis;\u612Ca;\u4392r;\uC000\u{1D505}pf;\uC000\u{1D539}eve;\u42D8c\xF2\u0113mpeq;\u624E\u0700HOacdefhilorsu\u014D\u0151\u0156\u0180\u019E\u01A2\u01B5\u01B7\u01BA\u01DC\u0215\u0273\u0278\u027Ecy;\u4427PY\u803B\xA9\u40A9\u0180cpy\u015D\u0162\u017Aute;\u4106\u0100;i\u0167\u0168\u62D2talDifferentialD;\u6145leys;\u612D\u0200aeio\u0189\u018E\u0194\u0198ron;\u410Cdil\u803B\xC7\u40C7rc;\u4108nint;\u6230ot;\u410A\u0100dn\u01A7\u01ADilla;\u40B8terDot;\u40B7\xF2\u017Fi;\u43A7rcle\u0200DMPT\u01C7\u01CB\u01D1\u01D6ot;\u6299inus;\u6296lus;\u6295imes;\u6297o\u0100cs\u01E2\u01F8kwiseContourIntegral;\u6232eCurly\u0100DQ\u0203\u020FoubleQuote;\u601Duote;\u6019\u0200lnpu\u021E\u0228\u0247\u0255on\u0100;e\u0225\u0226\u6237;\u6A74\u0180git\u022F\u0236\u023Aruent;\u6261nt;\u622FourIntegral;\u622E\u0100fr\u024C\u024E;\u6102oduct;\u6210nterClockwiseContourIntegral;\u6233oss;\u6A2Fcr;\uC000\u{1D49E}p\u0100;C\u0284\u0285\u62D3ap;\u624D\u0580DJSZacefios\u02A0\u02AC\u02B0\u02B4\u02B8\u02CB\u02D7\u02E1\u02E6\u0333\u048D\u0100;o\u0179\u02A5trahd;\u6911cy;\u4402cy;\u4405cy;\u440F\u0180grs\u02BF\u02C4\u02C7ger;\u6021r;\u61A1hv;\u6AE4\u0100ay\u02D0\u02D5ron;\u410E;\u4414l\u0100;t\u02DD\u02DE\u6207a;\u4394r;\uC000\u{1D507}\u0100af\u02EB\u0327\u0100cm\u02F0\u0322ritical\u0200ADGT\u0300\u0306\u0316\u031Ccute;\u40B4o\u0174\u030B\u030D;\u42D9bleAcute;\u42DDrave;\u4060ilde;\u42DCond;\u62C4ferentialD;\u6146\u0470\u033D\0\0\0\u0342\u0354\0\u0405f;\uC000\u{1D53B}\u0180;DE\u0348\u0349\u034D\u40A8ot;\u60DCqual;\u6250ble\u0300CDLRUV\u0363\u0372\u0382\u03CF\u03E2\u03F8ontourIntegra\xEC\u0239o\u0274\u0379\0\0\u037B\xBB\u0349nArrow;\u61D3\u0100eo\u0387\u03A4ft\u0180ART\u0390\u0396\u03A1rrow;\u61D0ightArrow;\u61D4e\xE5\u02CAng\u0100LR\u03AB\u03C4eft\u0100AR\u03B3\u03B9rrow;\u67F8ightArrow;\u67FAightArrow;\u67F9ight\u0100AT\u03D8\u03DErrow;\u61D2ee;\u62A8p\u0241\u03E9\0\0\u03EFrrow;\u61D1ownArrow;\u61D5erticalBar;\u6225n\u0300ABLRTa\u0412\u042A\u0430\u045E\u047F\u037Crrow\u0180;BU\u041D\u041E\u0422\u6193ar;\u6913pArrow;\u61F5reve;\u4311eft\u02D2\u043A\0\u0446\0\u0450ightVector;\u6950eeVector;\u695Eector\u0100;B\u0459\u045A\u61BDar;\u6956ight\u01D4\u0467\0\u0471eeVector;\u695Fector\u0100;B\u047A\u047B\u61C1ar;\u6957ee\u0100;A\u0486\u0487\u62A4rrow;\u61A7\u0100ct\u0492\u0497r;\uC000\u{1D49F}rok;\u4110\u0800NTacdfglmopqstux\u04BD\u04C0\u04C4\u04CB\u04DE\u04E2\u04E7\u04EE\u04F5\u0521\u052F\u0536\u0552\u055D\u0560\u0565G;\u414AH\u803B\xD0\u40D0cute\u803B\xC9\u40C9\u0180aiy\u04D2\u04D7\u04DCron;\u411Arc\u803B\xCA\u40CA;\u442Dot;\u4116r;\uC000\u{1D508}rave\u803B\xC8\u40C8ement;\u6208\u0100ap\u04FA\u04FEcr;\u4112ty\u0253\u0506\0\0\u0512mallSquare;\u65FBerySmallSquare;\u65AB\u0100gp\u0526\u052Aon;\u4118f;\uC000\u{1D53C}silon;\u4395u\u0100ai\u053C\u0549l\u0100;T\u0542\u0543\u6A75ilde;\u6242librium;\u61CC\u0100ci\u0557\u055Ar;\u6130m;\u6A73a;\u4397ml\u803B\xCB\u40CB\u0100ip\u056A\u056Fsts;\u6203onentialE;\u6147\u0280cfios\u0585\u0588\u058D\u05B2\u05CCy;\u4424r;\uC000\u{1D509}lled\u0253\u0597\0\0\u05A3mallSquare;\u65FCerySmallSquare;\u65AA\u0370\u05BA\0\u05BF\0\0\u05C4f;\uC000\u{1D53D}All;\u6200riertrf;\u6131c\xF2\u05CB\u0600JTabcdfgorst\u05E8\u05EC\u05EF\u05FA\u0600\u0612\u0616\u061B\u061D\u0623\u066C\u0672cy;\u4403\u803B>\u403Emma\u0100;d\u05F7\u05F8\u4393;\u43DCreve;\u411E\u0180eiy\u0607\u060C\u0610dil;\u4122rc;\u411C;\u4413ot;\u4120r;\uC000\u{1D50A};\u62D9pf;\uC000\u{1D53E}eater\u0300EFGLST\u0635\u0644\u064E\u0656\u065B\u0666qual\u0100;L\u063E\u063F\u6265ess;\u62DBullEqual;\u6267reater;\u6AA2ess;\u6277lantEqual;\u6A7Eilde;\u6273cr;\uC000\u{1D4A2};\u626B\u0400Aacfiosu\u0685\u068B\u0696\u069B\u069E\u06AA\u06BE\u06CARDcy;\u442A\u0100ct\u0690\u0694ek;\u42C7;\u405Eirc;\u4124r;\u610ClbertSpace;\u610B\u01F0\u06AF\0\u06B2f;\u610DizontalLine;\u6500\u0100ct\u06C3\u06C5\xF2\u06A9rok;\u4126mp\u0144\u06D0\u06D8ownHum\xF0\u012Fqual;\u624F\u0700EJOacdfgmnostu\u06FA\u06FE\u0703\u0707\u070E\u071A\u071E\u0721\u0728\u0744\u0778\u078B\u078F\u0795cy;\u4415lig;\u4132cy;\u4401cute\u803B\xCD\u40CD\u0100iy\u0713\u0718rc\u803B\xCE\u40CE;\u4418ot;\u4130r;\u6111rave\u803B\xCC\u40CC\u0180;ap\u0720\u072F\u073F\u0100cg\u0734\u0737r;\u412AinaryI;\u6148lie\xF3\u03DD\u01F4\u0749\0\u0762\u0100;e\u074D\u074E\u622C\u0100gr\u0753\u0758ral;\u622Bsection;\u62C2isible\u0100CT\u076C\u0772omma;\u6063imes;\u6062\u0180gpt\u077F\u0783\u0788on;\u412Ef;\uC000\u{1D540}a;\u4399cr;\u6110ilde;\u4128\u01EB\u079A\0\u079Ecy;\u4406l\u803B\xCF\u40CF\u0280cfosu\u07AC\u07B7\u07BC\u07C2\u07D0\u0100iy\u07B1\u07B5rc;\u4134;\u4419r;\uC000\u{1D50D}pf;\uC000\u{1D541}\u01E3\u07C7\0\u07CCr;\uC000\u{1D4A5}rcy;\u4408kcy;\u4404\u0380HJacfos\u07E4\u07E8\u07EC\u07F1\u07FD\u0802\u0808cy;\u4425cy;\u440Cppa;\u439A\u0100ey\u07F6\u07FBdil;\u4136;\u441Ar;\uC000\u{1D50E}pf;\uC000\u{1D542}cr;\uC000\u{1D4A6}\u0580JTaceflmost\u0825\u0829\u082C\u0850\u0863\u09B3\u09B8\u09C7\u09CD\u0A37\u0A47cy;\u4409\u803B<\u403C\u0280cmnpr\u0837\u083C\u0841\u0844\u084Dute;\u4139bda;\u439Bg;\u67EAlacetrf;\u6112r;\u619E\u0180aey\u0857\u085C\u0861ron;\u413Ddil;\u413B;\u441B\u0100fs\u0868\u0970t\u0500ACDFRTUVar\u087E\u08A9\u08B1\u08E0\u08E6\u08FC\u092F\u095B\u0390\u096A\u0100nr\u0883\u088FgleBracket;\u67E8row\u0180;BR\u0899\u089A\u089E\u6190ar;\u61E4ightArrow;\u61C6eiling;\u6308o\u01F5\u08B7\0\u08C3bleBracket;\u67E6n\u01D4\u08C8\0\u08D2eeVector;\u6961ector\u0100;B\u08DB\u08DC\u61C3ar;\u6959loor;\u630Aight\u0100AV\u08EF\u08F5rrow;\u6194ector;\u694E\u0100er\u0901\u0917e\u0180;AV\u0909\u090A\u0910\u62A3rrow;\u61A4ector;\u695Aiangle\u0180;BE\u0924\u0925\u0929\u62B2ar;\u69CFqual;\u62B4p\u0180DTV\u0937\u0942\u094CownVector;\u6951eeVector;\u6960ector\u0100;B\u0956\u0957\u61BFar;\u6958ector\u0100;B\u0965\u0966\u61BCar;\u6952ight\xE1\u039Cs\u0300EFGLST\u097E\u098B\u0995\u099D\u09A2\u09ADqualGreater;\u62DAullEqual;\u6266reater;\u6276ess;\u6AA1lantEqual;\u6A7Dilde;\u6272r;\uC000\u{1D50F}\u0100;e\u09BD\u09BE\u62D8ftarrow;\u61DAidot;\u413F\u0180npw\u09D4\u0A16\u0A1Bg\u0200LRlr\u09DE\u09F7\u0A02\u0A10eft\u0100AR\u09E6\u09ECrrow;\u67F5ightArrow;\u67F7ightArrow;\u67F6eft\u0100ar\u03B3\u0A0Aight\xE1\u03BFight\xE1\u03CAf;\uC000\u{1D543}er\u0100LR\u0A22\u0A2CeftArrow;\u6199ightArrow;\u6198\u0180cht\u0A3E\u0A40\u0A42\xF2\u084C;\u61B0rok;\u4141;\u626A\u0400acefiosu\u0A5A\u0A5D\u0A60\u0A77\u0A7C\u0A85\u0A8B\u0A8Ep;\u6905y;\u441C\u0100dl\u0A65\u0A6FiumSpace;\u605Flintrf;\u6133r;\uC000\u{1D510}nusPlus;\u6213pf;\uC000\u{1D544}c\xF2\u0A76;\u439C\u0480Jacefostu\u0AA3\u0AA7\u0AAD\u0AC0\u0B14\u0B19\u0D91\u0D97\u0D9Ecy;\u440Acute;\u4143\u0180aey\u0AB4\u0AB9\u0ABEron;\u4147dil;\u4145;\u441D\u0180gsw\u0AC7\u0AF0\u0B0Eative\u0180MTV\u0AD3\u0ADF\u0AE8ediumSpace;\u600Bhi\u0100cn\u0AE6\u0AD8\xEB\u0AD9eryThi\xEE\u0AD9ted\u0100GL\u0AF8\u0B06reaterGreate\xF2\u0673essLes\xF3\u0A48Line;\u400Ar;\uC000\u{1D511}\u0200Bnpt\u0B22\u0B28\u0B37\u0B3Areak;\u6060BreakingSpace;\u40A0f;\u6115\u0680;CDEGHLNPRSTV\u0B55\u0B56\u0B6A\u0B7C\u0BA1\u0BEB\u0C04\u0C5E\u0C84\u0CA6\u0CD8\u0D61\u0D85\u6AEC\u0100ou\u0B5B\u0B64ngruent;\u6262pCap;\u626DoubleVerticalBar;\u6226\u0180lqx\u0B83\u0B8A\u0B9Bement;\u6209ual\u0100;T\u0B92\u0B93\u6260ilde;\uC000\u2242\u0338ists;\u6204reater\u0380;EFGLST\u0BB6\u0BB7\u0BBD\u0BC9\u0BD3\u0BD8\u0BE5\u626Fqual;\u6271ullEqual;\uC000\u2267\u0338reater;\uC000\u226B\u0338ess;\u6279lantEqual;\uC000\u2A7E\u0338ilde;\u6275ump\u0144\u0BF2\u0BFDownHump;\uC000\u224E\u0338qual;\uC000\u224F\u0338e\u0100fs\u0C0A\u0C27tTriangle\u0180;BE\u0C1A\u0C1B\u0C21\u62EAar;\uC000\u29CF\u0338qual;\u62ECs\u0300;EGLST\u0C35\u0C36\u0C3C\u0C44\u0C4B\u0C58\u626Equal;\u6270reater;\u6278ess;\uC000\u226A\u0338lantEqual;\uC000\u2A7D\u0338ilde;\u6274ested\u0100GL\u0C68\u0C79reaterGreater;\uC000\u2AA2\u0338essLess;\uC000\u2AA1\u0338recedes\u0180;ES\u0C92\u0C93\u0C9B\u6280qual;\uC000\u2AAF\u0338lantEqual;\u62E0\u0100ei\u0CAB\u0CB9verseElement;\u620CghtTriangle\u0180;BE\u0CCB\u0CCC\u0CD2\u62EBar;\uC000\u29D0\u0338qual;\u62ED\u0100qu\u0CDD\u0D0CuareSu\u0100bp\u0CE8\u0CF9set\u0100;E\u0CF0\u0CF3\uC000\u228F\u0338qual;\u62E2erset\u0100;E\u0D03\u0D06\uC000\u2290\u0338qual;\u62E3\u0180bcp\u0D13\u0D24\u0D4Eset\u0100;E\u0D1B\u0D1E\uC000\u2282\u20D2qual;\u6288ceeds\u0200;EST\u0D32\u0D33\u0D3B\u0D46\u6281qual;\uC000\u2AB0\u0338lantEqual;\u62E1ilde;\uC000\u227F\u0338erset\u0100;E\u0D58\u0D5B\uC000\u2283\u20D2qual;\u6289ilde\u0200;EFT\u0D6E\u0D6F\u0D75\u0D7F\u6241qual;\u6244ullEqual;\u6247ilde;\u6249erticalBar;\u6224cr;\uC000\u{1D4A9}ilde\u803B\xD1\u40D1;\u439D\u0700Eacdfgmoprstuv\u0DBD\u0DC2\u0DC9\u0DD5\u0DDB\u0DE0\u0DE7\u0DFC\u0E02\u0E20\u0E22\u0E32\u0E3F\u0E44lig;\u4152cute\u803B\xD3\u40D3\u0100iy\u0DCE\u0DD3rc\u803B\xD4\u40D4;\u441Eblac;\u4150r;\uC000\u{1D512}rave\u803B\xD2\u40D2\u0180aei\u0DEE\u0DF2\u0DF6cr;\u414Cga;\u43A9cron;\u439Fpf;\uC000\u{1D546}enCurly\u0100DQ\u0E0E\u0E1AoubleQuote;\u601Cuote;\u6018;\u6A54\u0100cl\u0E27\u0E2Cr;\uC000\u{1D4AA}ash\u803B\xD8\u40D8i\u016C\u0E37\u0E3Cde\u803B\xD5\u40D5es;\u6A37ml\u803B\xD6\u40D6er\u0100BP\u0E4B\u0E60\u0100ar\u0E50\u0E53r;\u603Eac\u0100ek\u0E5A\u0E5C;\u63DEet;\u63B4arenthesis;\u63DC\u0480acfhilors\u0E7F\u0E87\u0E8A\u0E8F\u0E92\u0E94\u0E9D\u0EB0\u0EFCrtialD;\u6202y;\u441Fr;\uC000\u{1D513}i;\u43A6;\u43A0usMinus;\u40B1\u0100ip\u0EA2\u0EADncareplan\xE5\u069Df;\u6119\u0200;eio\u0EB9\u0EBA\u0EE0\u0EE4\u6ABBcedes\u0200;EST\u0EC8\u0EC9\u0ECF\u0EDA\u627Aqual;\u6AAFlantEqual;\u627Cilde;\u627Eme;\u6033\u0100dp\u0EE9\u0EEEuct;\u620Fortion\u0100;a\u0225\u0EF9l;\u621D\u0100ci\u0F01\u0F06r;\uC000\u{1D4AB};\u43A8\u0200Ufos\u0F11\u0F16\u0F1B\u0F1FOT\u803B"\u4022r;\uC000\u{1D514}pf;\u611Acr;\uC000\u{1D4AC}\u0600BEacefhiorsu\u0F3E\u0F43\u0F47\u0F60\u0F73\u0FA7\u0FAA\u0FAD\u1096\u10A9\u10B4\u10BEarr;\u6910G\u803B\xAE\u40AE\u0180cnr\u0F4E\u0F53\u0F56ute;\u4154g;\u67EBr\u0100;t\u0F5C\u0F5D\u61A0l;\u6916\u0180aey\u0F67\u0F6C\u0F71ron;\u4158dil;\u4156;\u4420\u0100;v\u0F78\u0F79\u611Cerse\u0100EU\u0F82\u0F99\u0100lq\u0F87\u0F8Eement;\u620Builibrium;\u61CBpEquilibrium;\u696Fr\xBB\u0F79o;\u43A1ght\u0400ACDFTUVa\u0FC1\u0FEB\u0FF3\u1022\u1028\u105B\u1087\u03D8\u0100nr\u0FC6\u0FD2gleBracket;\u67E9row\u0180;BL\u0FDC\u0FDD\u0FE1\u6192ar;\u61E5eftArrow;\u61C4eiling;\u6309o\u01F5\u0FF9\0\u1005bleBracket;\u67E7n\u01D4\u100A\0\u1014eeVector;\u695Dector\u0100;B\u101D\u101E\u61C2ar;\u6955loor;\u630B\u0100er\u102D\u1043e\u0180;AV\u1035\u1036\u103C\u62A2rrow;\u61A6ector;\u695Biangle\u0180;BE\u1050\u1051\u1055\u62B3ar;\u69D0qual;\u62B5p\u0180DTV\u1063\u106E\u1078ownVector;\u694FeeVector;\u695Cector\u0100;B\u1082\u1083\u61BEar;\u6954ector\u0100;B\u1091\u1092\u61C0ar;\u6953\u0100pu\u109B\u109Ef;\u611DndImplies;\u6970ightarrow;\u61DB\u0100ch\u10B9\u10BCr;\u611B;\u61B1leDelayed;\u69F4\u0680HOacfhimoqstu\u10E4\u10F1\u10F7\u10FD\u1119\u111E\u1151\u1156\u1161\u1167\u11B5\u11BB\u11BF\u0100Cc\u10E9\u10EEHcy;\u4429y;\u4428FTcy;\u442Ccute;\u415A\u0280;aeiy\u1108\u1109\u110E\u1113\u1117\u6ABCron;\u4160dil;\u415Erc;\u415C;\u4421r;\uC000\u{1D516}ort\u0200DLRU\u112A\u1134\u113E\u1149ownArrow\xBB\u041EeftArrow\xBB\u089AightArrow\xBB\u0FDDpArrow;\u6191gma;\u43A3allCircle;\u6218pf;\uC000\u{1D54A}\u0272\u116D\0\0\u1170t;\u621Aare\u0200;ISU\u117B\u117C\u1189\u11AF\u65A1ntersection;\u6293u\u0100bp\u118F\u119Eset\u0100;E\u1197\u1198\u628Fqual;\u6291erset\u0100;E\u11A8\u11A9\u6290qual;\u6292nion;\u6294cr;\uC000\u{1D4AE}ar;\u62C6\u0200bcmp\u11C8\u11DB\u1209\u120B\u0100;s\u11CD\u11CE\u62D0et\u0100;E\u11CD\u11D5qual;\u6286\u0100ch\u11E0\u1205eeds\u0200;EST\u11ED\u11EE\u11F4\u11FF\u627Bqual;\u6AB0lantEqual;\u627Dilde;\u627FTh\xE1\u0F8C;\u6211\u0180;es\u1212\u1213\u1223\u62D1rset\u0100;E\u121C\u121D\u6283qual;\u6287et\xBB\u1213\u0580HRSacfhiors\u123E\u1244\u1249\u1255\u125E\u1271\u1276\u129F\u12C2\u12C8\u12D1ORN\u803B\xDE\u40DEADE;\u6122\u0100Hc\u124E\u1252cy;\u440By;\u4426\u0100bu\u125A\u125C;\u4009;\u43A4\u0180aey\u1265\u126A\u126Fron;\u4164dil;\u4162;\u4422r;\uC000\u{1D517}\u0100ei\u127B\u1289\u01F2\u1280\0\u1287efore;\u6234a;\u4398\u0100cn\u128E\u1298kSpace;\uC000\u205F\u200ASpace;\u6009lde\u0200;EFT\u12AB\u12AC\u12B2\u12BC\u623Cqual;\u6243ullEqual;\u6245ilde;\u6248pf;\uC000\u{1D54B}ipleDot;\u60DB\u0100ct\u12D6\u12DBr;\uC000\u{1D4AF}rok;\u4166\u0AE1\u12F7\u130E\u131A\u1326\0\u132C\u1331\0\0\0\0\0\u1338\u133D\u1377\u1385\0\u13FF\u1404\u140A\u1410\u0100cr\u12FB\u1301ute\u803B\xDA\u40DAr\u0100;o\u1307\u1308\u619Fcir;\u6949r\u01E3\u1313\0\u1316y;\u440Eve;\u416C\u0100iy\u131E\u1323rc\u803B\xDB\u40DB;\u4423blac;\u4170r;\uC000\u{1D518}rave\u803B\xD9\u40D9acr;\u416A\u0100di\u1341\u1369er\u0100BP\u1348\u135D\u0100ar\u134D\u1350r;\u405Fac\u0100ek\u1357\u1359;\u63DFet;\u63B5arenthesis;\u63DDon\u0100;P\u1370\u1371\u62C3lus;\u628E\u0100gp\u137B\u137Fon;\u4172f;\uC000\u{1D54C}\u0400ADETadps\u1395\u13AE\u13B8\u13C4\u03E8\u13D2\u13D7\u13F3rrow\u0180;BD\u1150\u13A0\u13A4ar;\u6912ownArrow;\u61C5ownArrow;\u6195quilibrium;\u696Eee\u0100;A\u13CB\u13CC\u62A5rrow;\u61A5own\xE1\u03F3er\u0100LR\u13DE\u13E8eftArrow;\u6196ightArrow;\u6197i\u0100;l\u13F9\u13FA\u43D2on;\u43A5ing;\u416Ecr;\uC000\u{1D4B0}ilde;\u4168ml\u803B\xDC\u40DC\u0480Dbcdefosv\u1427\u142C\u1430\u1433\u143E\u1485\u148A\u1490\u1496ash;\u62ABar;\u6AEBy;\u4412ash\u0100;l\u143B\u143C\u62A9;\u6AE6\u0100er\u1443\u1445;\u62C1\u0180bty\u144C\u1450\u147Aar;\u6016\u0100;i\u144F\u1455cal\u0200BLST\u1461\u1465\u146A\u1474ar;\u6223ine;\u407Ceparator;\u6758ilde;\u6240ThinSpace;\u600Ar;\uC000\u{1D519}pf;\uC000\u{1D54D}cr;\uC000\u{1D4B1}dash;\u62AA\u0280cefos\u14A7\u14AC\u14B1\u14B6\u14BCirc;\u4174dge;\u62C0r;\uC000\u{1D51A}pf;\uC000\u{1D54E}cr;\uC000\u{1D4B2}\u0200fios\u14CB\u14D0\u14D2\u14D8r;\uC000\u{1D51B};\u439Epf;\uC000\u{1D54F}cr;\uC000\u{1D4B3}\u0480AIUacfosu\u14F1\u14F5\u14F9\u14FD\u1504\u150F\u1514\u151A\u1520cy;\u442Fcy;\u4407cy;\u442Ecute\u803B\xDD\u40DD\u0100iy\u1509\u150Drc;\u4176;\u442Br;\uC000\u{1D51C}pf;\uC000\u{1D550}cr;\uC000\u{1D4B4}ml;\u4178\u0400Hacdefos\u1535\u1539\u153F\u154B\u154F\u155D\u1560\u1564cy;\u4416cute;\u4179\u0100ay\u1544\u1549ron;\u417D;\u4417ot;\u417B\u01F2\u1554\0\u155BoWidt\xE8\u0AD9a;\u4396r;\u6128pf;\u6124cr;\uC000\u{1D4B5}\u0BE1\u1583\u158A\u1590\0\u15B0\u15B6\u15BF\0\0\0\0\u15C6\u15DB\u15EB\u165F\u166D\0\u1695\u169B\u16B2\u16B9\0\u16BEcute\u803B\xE1\u40E1reve;\u4103\u0300;Ediuy\u159C\u159D\u15A1\u15A3\u15A8\u15AD\u623E;\uC000\u223E\u0333;\u623Frc\u803B\xE2\u40E2te\u80BB\xB4\u0306;\u4430lig\u803B\xE6\u40E6\u0100;r\xB2\u15BA;\uC000\u{1D51E}rave\u803B\xE0\u40E0\u0100ep\u15CA\u15D6\u0100fp\u15CF\u15D4sym;\u6135\xE8\u15D3ha;\u43B1\u0100ap\u15DFc\u0100cl\u15E4\u15E7r;\u4101g;\u6A3F\u0264\u15F0\0\0\u160A\u0280;adsv\u15FA\u15FB\u15FF\u1601\u1607\u6227nd;\u6A55;\u6A5Clope;\u6A58;\u6A5A\u0380;elmrsz\u1618\u1619\u161B\u161E\u163F\u164F\u1659\u6220;\u69A4e\xBB\u1619sd\u0100;a\u1625\u1626\u6221\u0461\u1630\u1632\u1634\u1636\u1638\u163A\u163C\u163E;\u69A8;\u69A9;\u69AA;\u69AB;\u69AC;\u69AD;\u69AE;\u69AFt\u0100;v\u1645\u1646\u621Fb\u0100;d\u164C\u164D\u62BE;\u699D\u0100pt\u1654\u1657h;\u6222\xBB\xB9arr;\u637C\u0100gp\u1663\u1667on;\u4105f;\uC000\u{1D552}\u0380;Eaeiop\u12C1\u167B\u167D\u1682\u1684\u1687\u168A;\u6A70cir;\u6A6F;\u624Ad;\u624Bs;\u4027rox\u0100;e\u12C1\u1692\xF1\u1683ing\u803B\xE5\u40E5\u0180cty\u16A1\u16A6\u16A8r;\uC000\u{1D4B6};\u402Amp\u0100;e\u12C1\u16AF\xF1\u0288ilde\u803B\xE3\u40E3ml\u803B\xE4\u40E4\u0100ci\u16C2\u16C8onin\xF4\u0272nt;\u6A11\u0800Nabcdefiklnoprsu\u16ED\u16F1\u1730\u173C\u1743\u1748\u1778\u177D\u17E0\u17E6\u1839\u1850\u170D\u193D\u1948\u1970ot;\u6AED\u0100cr\u16F6\u171Ek\u0200ceps\u1700\u1705\u170D\u1713ong;\u624Cpsilon;\u43F6rime;\u6035im\u0100;e\u171A\u171B\u623Dq;\u62CD\u0176\u1722\u1726ee;\u62BDed\u0100;g\u172C\u172D\u6305e\xBB\u172Drk\u0100;t\u135C\u1737brk;\u63B6\u0100oy\u1701\u1741;\u4431quo;\u601E\u0280cmprt\u1753\u175B\u1761\u1764\u1768aus\u0100;e\u010A\u0109ptyv;\u69B0s\xE9\u170Cno\xF5\u0113\u0180ahw\u176F\u1771\u1773;\u43B2;\u6136een;\u626Cr;\uC000\u{1D51F}g\u0380costuvw\u178D\u179D\u17B3\u17C1\u17D5\u17DB\u17DE\u0180aiu\u1794\u1796\u179A\xF0\u0760rc;\u65EFp\xBB\u1371\u0180dpt\u17A4\u17A8\u17ADot;\u6A00lus;\u6A01imes;\u6A02\u0271\u17B9\0\0\u17BEcup;\u6A06ar;\u6605riangle\u0100du\u17CD\u17D2own;\u65BDp;\u65B3plus;\u6A04e\xE5\u1444\xE5\u14ADarow;\u690D\u0180ako\u17ED\u1826\u1835\u0100cn\u17F2\u1823k\u0180lst\u17FA\u05AB\u1802ozenge;\u69EBriangle\u0200;dlr\u1812\u1813\u1818\u181D\u65B4own;\u65BEeft;\u65C2ight;\u65B8k;\u6423\u01B1\u182B\0\u1833\u01B2\u182F\0\u1831;\u6592;\u65914;\u6593ck;\u6588\u0100eo\u183E\u184D\u0100;q\u1843\u1846\uC000=\u20E5uiv;\uC000\u2261\u20E5t;\u6310\u0200ptwx\u1859\u185E\u1867\u186Cf;\uC000\u{1D553}\u0100;t\u13CB\u1863om\xBB\u13CCtie;\u62C8\u0600DHUVbdhmptuv\u1885\u1896\u18AA\u18BB\u18D7\u18DB\u18EC\u18FF\u1905\u190A\u1910\u1921\u0200LRlr\u188E\u1890\u1892\u1894;\u6557;\u6554;\u6556;\u6553\u0280;DUdu\u18A1\u18A2\u18A4\u18A6\u18A8\u6550;\u6566;\u6569;\u6564;\u6567\u0200LRlr\u18B3\u18B5\u18B7\u18B9;\u655D;\u655A;\u655C;\u6559\u0380;HLRhlr\u18CA\u18CB\u18CD\u18CF\u18D1\u18D3\u18D5\u6551;\u656C;\u6563;\u6560;\u656B;\u6562;\u655Fox;\u69C9\u0200LRlr\u18E4\u18E6\u18E8\u18EA;\u6555;\u6552;\u6510;\u650C\u0280;DUdu\u06BD\u18F7\u18F9\u18FB\u18FD;\u6565;\u6568;\u652C;\u6534inus;\u629Flus;\u629Eimes;\u62A0\u0200LRlr\u1919\u191B\u191D\u191F;\u655B;\u6558;\u6518;\u6514\u0380;HLRhlr\u1930\u1931\u1933\u1935\u1937\u1939\u193B\u6502;\u656A;\u6561;\u655E;\u653C;\u6524;\u651C\u0100ev\u0123\u1942bar\u803B\xA6\u40A6\u0200ceio\u1951\u1956\u195A\u1960r;\uC000\u{1D4B7}mi;\u604Fm\u0100;e\u171A\u171Cl\u0180;bh\u1968\u1969\u196B\u405C;\u69C5sub;\u67C8\u016C\u1974\u197El\u0100;e\u1979\u197A\u6022t\xBB\u197Ap\u0180;Ee\u012F\u1985\u1987;\u6AAE\u0100;q\u06DC\u06DB\u0CE1\u19A7\0\u19E8\u1A11\u1A15\u1A32\0\u1A37\u1A50\0\0\u1AB4\0\0\u1AC1\0\0\u1B21\u1B2E\u1B4D\u1B52\0\u1BFD\0\u1C0C\u0180cpr\u19AD\u19B2\u19DDute;\u4107\u0300;abcds\u19BF\u19C0\u19C4\u19CA\u19D5\u19D9\u6229nd;\u6A44rcup;\u6A49\u0100au\u19CF\u19D2p;\u6A4Bp;\u6A47ot;\u6A40;\uC000\u2229\uFE00\u0100eo\u19E2\u19E5t;\u6041\xEE\u0693\u0200aeiu\u19F0\u19FB\u1A01\u1A05\u01F0\u19F5\0\u19F8s;\u6A4Don;\u410Ddil\u803B\xE7\u40E7rc;\u4109ps\u0100;s\u1A0C\u1A0D\u6A4Cm;\u6A50ot;\u410B\u0180dmn\u1A1B\u1A20\u1A26il\u80BB\xB8\u01ADptyv;\u69B2t\u8100\xA2;e\u1A2D\u1A2E\u40A2r\xE4\u01B2r;\uC000\u{1D520}\u0180cei\u1A3D\u1A40\u1A4Dy;\u4447ck\u0100;m\u1A47\u1A48\u6713ark\xBB\u1A48;\u43C7r\u0380;Ecefms\u1A5F\u1A60\u1A62\u1A6B\u1AA4\u1AAA\u1AAE\u65CB;\u69C3\u0180;el\u1A69\u1A6A\u1A6D\u42C6q;\u6257e\u0261\u1A74\0\0\u1A88rrow\u0100lr\u1A7C\u1A81eft;\u61BAight;\u61BB\u0280RSacd\u1A92\u1A94\u1A96\u1A9A\u1A9F\xBB\u0F47;\u64C8st;\u629Birc;\u629Aash;\u629Dnint;\u6A10id;\u6AEFcir;\u69C2ubs\u0100;u\u1ABB\u1ABC\u6663it\xBB\u1ABC\u02EC\u1AC7\u1AD4\u1AFA\0\u1B0Aon\u0100;e\u1ACD\u1ACE\u403A\u0100;q\xC7\xC6\u026D\u1AD9\0\0\u1AE2a\u0100;t\u1ADE\u1ADF\u402C;\u4040\u0180;fl\u1AE8\u1AE9\u1AEB\u6201\xEE\u1160e\u0100mx\u1AF1\u1AF6ent\xBB\u1AE9e\xF3\u024D\u01E7\u1AFE\0\u1B07\u0100;d\u12BB\u1B02ot;\u6A6Dn\xF4\u0246\u0180fry\u1B10\u1B14\u1B17;\uC000\u{1D554}o\xE4\u0254\u8100\xA9;s\u0155\u1B1Dr;\u6117\u0100ao\u1B25\u1B29rr;\u61B5ss;\u6717\u0100cu\u1B32\u1B37r;\uC000\u{1D4B8}\u0100bp\u1B3C\u1B44\u0100;e\u1B41\u1B42\u6ACF;\u6AD1\u0100;e\u1B49\u1B4A\u6AD0;\u6AD2dot;\u62EF\u0380delprvw\u1B60\u1B6C\u1B77\u1B82\u1BAC\u1BD4\u1BF9arr\u0100lr\u1B68\u1B6A;\u6938;\u6935\u0270\u1B72\0\0\u1B75r;\u62DEc;\u62DFarr\u0100;p\u1B7F\u1B80\u61B6;\u693D\u0300;bcdos\u1B8F\u1B90\u1B96\u1BA1\u1BA5\u1BA8\u622Arcap;\u6A48\u0100au\u1B9B\u1B9Ep;\u6A46p;\u6A4Aot;\u628Dr;\u6A45;\uC000\u222A\uFE00\u0200alrv\u1BB5\u1BBF\u1BDE\u1BE3rr\u0100;m\u1BBC\u1BBD\u61B7;\u693Cy\u0180evw\u1BC7\u1BD4\u1BD8q\u0270\u1BCE\0\0\u1BD2re\xE3\u1B73u\xE3\u1B75ee;\u62CEedge;\u62CFen\u803B\xA4\u40A4earrow\u0100lr\u1BEE\u1BF3eft\xBB\u1B80ight\xBB\u1BBDe\xE4\u1BDD\u0100ci\u1C01\u1C07onin\xF4\u01F7nt;\u6231lcty;\u632D\u0980AHabcdefhijlorstuwz\u1C38\u1C3B\u1C3F\u1C5D\u1C69\u1C75\u1C8A\u1C9E\u1CAC\u1CB7\u1CFB\u1CFF\u1D0D\u1D7B\u1D91\u1DAB\u1DBB\u1DC6\u1DCDr\xF2\u0381ar;\u6965\u0200glrs\u1C48\u1C4D\u1C52\u1C54ger;\u6020eth;\u6138\xF2\u1133h\u0100;v\u1C5A\u1C5B\u6010\xBB\u090A\u016B\u1C61\u1C67arow;\u690Fa\xE3\u0315\u0100ay\u1C6E\u1C73ron;\u410F;\u4434\u0180;ao\u0332\u1C7C\u1C84\u0100gr\u02BF\u1C81r;\u61CAtseq;\u6A77\u0180glm\u1C91\u1C94\u1C98\u803B\xB0\u40B0ta;\u43B4ptyv;\u69B1\u0100ir\u1CA3\u1CA8sht;\u697F;\uC000\u{1D521}ar\u0100lr\u1CB3\u1CB5\xBB\u08DC\xBB\u101E\u0280aegsv\u1CC2\u0378\u1CD6\u1CDC\u1CE0m\u0180;os\u0326\u1CCA\u1CD4nd\u0100;s\u0326\u1CD1uit;\u6666amma;\u43DDin;\u62F2\u0180;io\u1CE7\u1CE8\u1CF8\u40F7de\u8100\xF7;o\u1CE7\u1CF0ntimes;\u62C7n\xF8\u1CF7cy;\u4452c\u026F\u1D06\0\0\u1D0Arn;\u631Eop;\u630D\u0280lptuw\u1D18\u1D1D\u1D22\u1D49\u1D55lar;\u4024f;\uC000\u{1D555}\u0280;emps\u030B\u1D2D\u1D37\u1D3D\u1D42q\u0100;d\u0352\u1D33ot;\u6251inus;\u6238lus;\u6214quare;\u62A1blebarwedg\xE5\xFAn\u0180adh\u112E\u1D5D\u1D67ownarrow\xF3\u1C83arpoon\u0100lr\u1D72\u1D76ef\xF4\u1CB4igh\xF4\u1CB6\u0162\u1D7F\u1D85karo\xF7\u0F42\u026F\u1D8A\0\0\u1D8Ern;\u631Fop;\u630C\u0180cot\u1D98\u1DA3\u1DA6\u0100ry\u1D9D\u1DA1;\uC000\u{1D4B9};\u4455l;\u69F6rok;\u4111\u0100dr\u1DB0\u1DB4ot;\u62F1i\u0100;f\u1DBA\u1816\u65BF\u0100ah\u1DC0\u1DC3r\xF2\u0429a\xF2\u0FA6angle;\u69A6\u0100ci\u1DD2\u1DD5y;\u445Fgrarr;\u67FF\u0900Dacdefglmnopqrstux\u1E01\u1E09\u1E19\u1E38\u0578\u1E3C\u1E49\u1E61\u1E7E\u1EA5\u1EAF\u1EBD\u1EE1\u1F2A\u1F37\u1F44\u1F4E\u1F5A\u0100Do\u1E06\u1D34o\xF4\u1C89\u0100cs\u1E0E\u1E14ute\u803B\xE9\u40E9ter;\u6A6E\u0200aioy\u1E22\u1E27\u1E31\u1E36ron;\u411Br\u0100;c\u1E2D\u1E2E\u6256\u803B\xEA\u40EAlon;\u6255;\u444Dot;\u4117\u0100Dr\u1E41\u1E45ot;\u6252;\uC000\u{1D522}\u0180;rs\u1E50\u1E51\u1E57\u6A9Aave\u803B\xE8\u40E8\u0100;d\u1E5C\u1E5D\u6A96ot;\u6A98\u0200;ils\u1E6A\u1E6B\u1E72\u1E74\u6A99nters;\u63E7;\u6113\u0100;d\u1E79\u1E7A\u6A95ot;\u6A97\u0180aps\u1E85\u1E89\u1E97cr;\u4113ty\u0180;sv\u1E92\u1E93\u1E95\u6205et\xBB\u1E93p\u01001;\u1E9D\u1EA4\u0133\u1EA1\u1EA3;\u6004;\u6005\u6003\u0100gs\u1EAA\u1EAC;\u414Bp;\u6002\u0100gp\u1EB4\u1EB8on;\u4119f;\uC000\u{1D556}\u0180als\u1EC4\u1ECE\u1ED2r\u0100;s\u1ECA\u1ECB\u62D5l;\u69E3us;\u6A71i\u0180;lv\u1EDA\u1EDB\u1EDF\u43B5on\xBB\u1EDB;\u43F5\u0200csuv\u1EEA\u1EF3\u1F0B\u1F23\u0100io\u1EEF\u1E31rc\xBB\u1E2E\u0269\u1EF9\0\0\u1EFB\xED\u0548ant\u0100gl\u1F02\u1F06tr\xBB\u1E5Dess\xBB\u1E7A\u0180aei\u1F12\u1F16\u1F1Als;\u403Dst;\u625Fv\u0100;D\u0235\u1F20D;\u6A78parsl;\u69E5\u0100Da\u1F2F\u1F33ot;\u6253rr;\u6971\u0180cdi\u1F3E\u1F41\u1EF8r;\u612Fo\xF4\u0352\u0100ah\u1F49\u1F4B;\u43B7\u803B\xF0\u40F0\u0100mr\u1F53\u1F57l\u803B\xEB\u40EBo;\u60AC\u0180cip\u1F61\u1F64\u1F67l;\u4021s\xF4\u056E\u0100eo\u1F6C\u1F74ctatio\xEE\u0559nential\xE5\u0579\u09E1\u1F92\0\u1F9E\0\u1FA1\u1FA7\0\0\u1FC6\u1FCC\0\u1FD3\0\u1FE6\u1FEA\u2000\0\u2008\u205Allingdotse\xF1\u1E44y;\u4444male;\u6640\u0180ilr\u1FAD\u1FB3\u1FC1lig;\u8000\uFB03\u0269\u1FB9\0\0\u1FBDg;\u8000\uFB00ig;\u8000\uFB04;\uC000\u{1D523}lig;\u8000\uFB01lig;\uC000fj\u0180alt\u1FD9\u1FDC\u1FE1t;\u666Dig;\u8000\uFB02ns;\u65B1of;\u4192\u01F0\u1FEE\0\u1FF3f;\uC000\u{1D557}\u0100ak\u05BF\u1FF7\u0100;v\u1FFC\u1FFD\u62D4;\u6AD9artint;\u6A0D\u0100ao\u200C\u2055\u0100cs\u2011\u2052\u03B1\u201A\u2030\u2038\u2045\u2048\0\u2050\u03B2\u2022\u2025\u2027\u202A\u202C\0\u202E\u803B\xBD\u40BD;\u6153\u803B\xBC\u40BC;\u6155;\u6159;\u615B\u01B3\u2034\0\u2036;\u6154;\u6156\u02B4\u203E\u2041\0\0\u2043\u803B\xBE\u40BE;\u6157;\u615C5;\u6158\u01B6\u204C\0\u204E;\u615A;\u615D8;\u615El;\u6044wn;\u6322cr;\uC000\u{1D4BB}\u0880Eabcdefgijlnorstv\u2082\u2089\u209F\u20A5\u20B0\u20B4\u20F0\u20F5\u20FA\u20FF\u2103\u2112\u2138\u0317\u213E\u2152\u219E\u0100;l\u064D\u2087;\u6A8C\u0180cmp\u2090\u2095\u209Dute;\u41F5ma\u0100;d\u209C\u1CDA\u43B3;\u6A86reve;\u411F\u0100iy\u20AA\u20AErc;\u411D;\u4433ot;\u4121\u0200;lqs\u063E\u0642\u20BD\u20C9\u0180;qs\u063E\u064C\u20C4lan\xF4\u0665\u0200;cdl\u0665\u20D2\u20D5\u20E5c;\u6AA9ot\u0100;o\u20DC\u20DD\u6A80\u0100;l\u20E2\u20E3\u6A82;\u6A84\u0100;e\u20EA\u20ED\uC000\u22DB\uFE00s;\u6A94r;\uC000\u{1D524}\u0100;g\u0673\u061Bmel;\u6137cy;\u4453\u0200;Eaj\u065A\u210C\u210E\u2110;\u6A92;\u6AA5;\u6AA4\u0200Eaes\u211B\u211D\u2129\u2134;\u6269p\u0100;p\u2123\u2124\u6A8Arox\xBB\u2124\u0100;q\u212E\u212F\u6A88\u0100;q\u212E\u211Bim;\u62E7pf;\uC000\u{1D558}\u0100ci\u2143\u2146r;\u610Am\u0180;el\u066B\u214E\u2150;\u6A8E;\u6A90\u8300>;cdlqr\u05EE\u2160\u216A\u216E\u2173\u2179\u0100ci\u2165\u2167;\u6AA7r;\u6A7Aot;\u62D7Par;\u6995uest;\u6A7C\u0280adels\u2184\u216A\u2190\u0656\u219B\u01F0\u2189\0\u218Epro\xF8\u209Er;\u6978q\u0100lq\u063F\u2196les\xF3\u2088i\xED\u066B\u0100en\u21A3\u21ADrtneqq;\uC000\u2269\uFE00\xC5\u21AA\u0500Aabcefkosy\u21C4\u21C7\u21F1\u21F5\u21FA\u2218\u221D\u222F\u2268\u227Dr\xF2\u03A0\u0200ilmr\u21D0\u21D4\u21D7\u21DBrs\xF0\u1484f\xBB\u2024il\xF4\u06A9\u0100dr\u21E0\u21E4cy;\u444A\u0180;cw\u08F4\u21EB\u21EFir;\u6948;\u61ADar;\u610Firc;\u4125\u0180alr\u2201\u220E\u2213rts\u0100;u\u2209\u220A\u6665it\xBB\u220Alip;\u6026con;\u62B9r;\uC000\u{1D525}s\u0100ew\u2223\u2229arow;\u6925arow;\u6926\u0280amopr\u223A\u223E\u2243\u225E\u2263rr;\u61FFtht;\u623Bk\u0100lr\u2249\u2253eftarrow;\u61A9ightarrow;\u61AAf;\uC000\u{1D559}bar;\u6015\u0180clt\u226F\u2274\u2278r;\uC000\u{1D4BD}as\xE8\u21F4rok;\u4127\u0100bp\u2282\u2287ull;\u6043hen\xBB\u1C5B\u0AE1\u22A3\0\u22AA\0\u22B8\u22C5\u22CE\0\u22D5\u22F3\0\0\u22F8\u2322\u2367\u2362\u237F\0\u2386\u23AA\u23B4cute\u803B\xED\u40ED\u0180;iy\u0771\u22B0\u22B5rc\u803B\xEE\u40EE;\u4438\u0100cx\u22BC\u22BFy;\u4435cl\u803B\xA1\u40A1\u0100fr\u039F\u22C9;\uC000\u{1D526}rave\u803B\xEC\u40EC\u0200;ino\u073E\u22DD\u22E9\u22EE\u0100in\u22E2\u22E6nt;\u6A0Ct;\u622Dfin;\u69DCta;\u6129lig;\u4133\u0180aop\u22FE\u231A\u231D\u0180cgt\u2305\u2308\u2317r;\u412B\u0180elp\u071F\u230F\u2313in\xE5\u078Ear\xF4\u0720h;\u4131f;\u62B7ed;\u41B5\u0280;cfot\u04F4\u232C\u2331\u233D\u2341are;\u6105in\u0100;t\u2338\u2339\u621Eie;\u69DDdo\xF4\u2319\u0280;celp\u0757\u234C\u2350\u235B\u2361al;\u62BA\u0100gr\u2355\u2359er\xF3\u1563\xE3\u234Darhk;\u6A17rod;\u6A3C\u0200cgpt\u236F\u2372\u2376\u237By;\u4451on;\u412Ff;\uC000\u{1D55A}a;\u43B9uest\u803B\xBF\u40BF\u0100ci\u238A\u238Fr;\uC000\u{1D4BE}n\u0280;Edsv\u04F4\u239B\u239D\u23A1\u04F3;\u62F9ot;\u62F5\u0100;v\u23A6\u23A7\u62F4;\u62F3\u0100;i\u0777\u23AElde;\u4129\u01EB\u23B8\0\u23BCcy;\u4456l\u803B\xEF\u40EF\u0300cfmosu\u23CC\u23D7\u23DC\u23E1\u23E7\u23F5\u0100iy\u23D1\u23D5rc;\u4135;\u4439r;\uC000\u{1D527}ath;\u4237pf;\uC000\u{1D55B}\u01E3\u23EC\0\u23F1r;\uC000\u{1D4BF}rcy;\u4458kcy;\u4454\u0400acfghjos\u240B\u2416\u2422\u2427\u242D\u2431\u2435\u243Bppa\u0100;v\u2413\u2414\u43BA;\u43F0\u0100ey\u241B\u2420dil;\u4137;\u443Ar;\uC000\u{1D528}reen;\u4138cy;\u4445cy;\u445Cpf;\uC000\u{1D55C}cr;\uC000\u{1D4C0}\u0B80ABEHabcdefghjlmnoprstuv\u2470\u2481\u2486\u248D\u2491\u250E\u253D\u255A\u2580\u264E\u265E\u2665\u2679\u267D\u269A\u26B2\u26D8\u275D\u2768\u278B\u27C0\u2801\u2812\u0180art\u2477\u247A\u247Cr\xF2\u09C6\xF2\u0395ail;\u691Barr;\u690E\u0100;g\u0994\u248B;\u6A8Bar;\u6962\u0963\u24A5\0\u24AA\0\u24B1\0\0\0\0\0\u24B5\u24BA\0\u24C6\u24C8\u24CD\0\u24F9ute;\u413Amptyv;\u69B4ra\xEE\u084Cbda;\u43BBg\u0180;dl\u088E\u24C1\u24C3;\u6991\xE5\u088E;\u6A85uo\u803B\xAB\u40ABr\u0400;bfhlpst\u0899\u24DE\u24E6\u24E9\u24EB\u24EE\u24F1\u24F5\u0100;f\u089D\u24E3s;\u691Fs;\u691D\xEB\u2252p;\u61ABl;\u6939im;\u6973l;\u61A2\u0180;ae\u24FF\u2500\u2504\u6AABil;\u6919\u0100;s\u2509\u250A\u6AAD;\uC000\u2AAD\uFE00\u0180abr\u2515\u2519\u251Drr;\u690Crk;\u6772\u0100ak\u2522\u252Cc\u0100ek\u2528\u252A;\u407B;\u405B\u0100es\u2531\u2533;\u698Bl\u0100du\u2539\u253B;\u698F;\u698D\u0200aeuy\u2546\u254B\u2556\u2558ron;\u413E\u0100di\u2550\u2554il;\u413C\xEC\u08B0\xE2\u2529;\u443B\u0200cqrs\u2563\u2566\u256D\u257Da;\u6936uo\u0100;r\u0E19\u1746\u0100du\u2572\u2577har;\u6967shar;\u694Bh;\u61B2\u0280;fgqs\u258B\u258C\u0989\u25F3\u25FF\u6264t\u0280ahlrt\u2598\u25A4\u25B7\u25C2\u25E8rrow\u0100;t\u0899\u25A1a\xE9\u24F6arpoon\u0100du\u25AF\u25B4own\xBB\u045Ap\xBB\u0966eftarrows;\u61C7ight\u0180ahs\u25CD\u25D6\u25DErrow\u0100;s\u08F4\u08A7arpoon\xF3\u0F98quigarro\xF7\u21F0hreetimes;\u62CB\u0180;qs\u258B\u0993\u25FAlan\xF4\u09AC\u0280;cdgs\u09AC\u260A\u260D\u261D\u2628c;\u6AA8ot\u0100;o\u2614\u2615\u6A7F\u0100;r\u261A\u261B\u6A81;\u6A83\u0100;e\u2622\u2625\uC000\u22DA\uFE00s;\u6A93\u0280adegs\u2633\u2639\u263D\u2649\u264Bppro\xF8\u24C6ot;\u62D6q\u0100gq\u2643\u2645\xF4\u0989gt\xF2\u248C\xF4\u099Bi\xED\u09B2\u0180ilr\u2655\u08E1\u265Asht;\u697C;\uC000\u{1D529}\u0100;E\u099C\u2663;\u6A91\u0161\u2669\u2676r\u0100du\u25B2\u266E\u0100;l\u0965\u2673;\u696Alk;\u6584cy;\u4459\u0280;acht\u0A48\u2688\u268B\u2691\u2696r\xF2\u25C1orne\xF2\u1D08ard;\u696Bri;\u65FA\u0100io\u269F\u26A4dot;\u4140ust\u0100;a\u26AC\u26AD\u63B0che\xBB\u26AD\u0200Eaes\u26BB\u26BD\u26C9\u26D4;\u6268p\u0100;p\u26C3\u26C4\u6A89rox\xBB\u26C4\u0100;q\u26CE\u26CF\u6A87\u0100;q\u26CE\u26BBim;\u62E6\u0400abnoptwz\u26E9\u26F4\u26F7\u271A\u272F\u2741\u2747\u2750\u0100nr\u26EE\u26F1g;\u67ECr;\u61FDr\xEB\u08C1g\u0180lmr\u26FF\u270D\u2714eft\u0100ar\u09E6\u2707ight\xE1\u09F2apsto;\u67FCight\xE1\u09FDparrow\u0100lr\u2725\u2729ef\xF4\u24EDight;\u61AC\u0180afl\u2736\u2739\u273Dr;\u6985;\uC000\u{1D55D}us;\u6A2Dimes;\u6A34\u0161\u274B\u274Fst;\u6217\xE1\u134E\u0180;ef\u2757\u2758\u1800\u65CAnge\xBB\u2758ar\u0100;l\u2764\u2765\u4028t;\u6993\u0280achmt\u2773\u2776\u277C\u2785\u2787r\xF2\u08A8orne\xF2\u1D8Car\u0100;d\u0F98\u2783;\u696D;\u600Eri;\u62BF\u0300achiqt\u2798\u279D\u0A40\u27A2\u27AE\u27BBquo;\u6039r;\uC000\u{1D4C1}m\u0180;eg\u09B2\u27AA\u27AC;\u6A8D;\u6A8F\u0100bu\u252A\u27B3o\u0100;r\u0E1F\u27B9;\u601Arok;\u4142\u8400<;cdhilqr\u082B\u27D2\u2639\u27DC\u27E0\u27E5\u27EA\u27F0\u0100ci\u27D7\u27D9;\u6AA6r;\u6A79re\xE5\u25F2mes;\u62C9arr;\u6976uest;\u6A7B\u0100Pi\u27F5\u27F9ar;\u6996\u0180;ef\u2800\u092D\u181B\u65C3r\u0100du\u2807\u280Dshar;\u694Ahar;\u6966\u0100en\u2817\u2821rtneqq;\uC000\u2268\uFE00\xC5\u281E\u0700Dacdefhilnopsu\u2840\u2845\u2882\u288E\u2893\u28A0\u28A5\u28A8\u28DA\u28E2\u28E4\u0A83\u28F3\u2902Dot;\u623A\u0200clpr\u284E\u2852\u2863\u287Dr\u803B\xAF\u40AF\u0100et\u2857\u2859;\u6642\u0100;e\u285E\u285F\u6720se\xBB\u285F\u0100;s\u103B\u2868to\u0200;dlu\u103B\u2873\u2877\u287Bow\xEE\u048Cef\xF4\u090F\xF0\u13D1ker;\u65AE\u0100oy\u2887\u288Cmma;\u6A29;\u443Cash;\u6014asuredangle\xBB\u1626r;\uC000\u{1D52A}o;\u6127\u0180cdn\u28AF\u28B4\u28C9ro\u803B\xB5\u40B5\u0200;acd\u1464\u28BD\u28C0\u28C4s\xF4\u16A7ir;\u6AF0ot\u80BB\xB7\u01B5us\u0180;bd\u28D2\u1903\u28D3\u6212\u0100;u\u1D3C\u28D8;\u6A2A\u0163\u28DE\u28E1p;\u6ADB\xF2\u2212\xF0\u0A81\u0100dp\u28E9\u28EEels;\u62A7f;\uC000\u{1D55E}\u0100ct\u28F8\u28FDr;\uC000\u{1D4C2}pos\xBB\u159D\u0180;lm\u2909\u290A\u290D\u43BCtimap;\u62B8\u0C00GLRVabcdefghijlmoprstuvw\u2942\u2953\u297E\u2989\u2998\u29DA\u29E9\u2A15\u2A1A\u2A58\u2A5D\u2A83\u2A95\u2AA4\u2AA8\u2B04\u2B07\u2B44\u2B7F\u2BAE\u2C34\u2C67\u2C7C\u2CE9\u0100gt\u2947\u294B;\uC000\u22D9\u0338\u0100;v\u2950\u0BCF\uC000\u226B\u20D2\u0180elt\u295A\u2972\u2976ft\u0100ar\u2961\u2967rrow;\u61CDightarrow;\u61CE;\uC000\u22D8\u0338\u0100;v\u297B\u0C47\uC000\u226A\u20D2ightarrow;\u61CF\u0100Dd\u298E\u2993ash;\u62AFash;\u62AE\u0280bcnpt\u29A3\u29A7\u29AC\u29B1\u29CCla\xBB\u02DEute;\u4144g;\uC000\u2220\u20D2\u0280;Eiop\u0D84\u29BC\u29C0\u29C5\u29C8;\uC000\u2A70\u0338d;\uC000\u224B\u0338s;\u4149ro\xF8\u0D84ur\u0100;a\u29D3\u29D4\u666El\u0100;s\u29D3\u0B38\u01F3\u29DF\0\u29E3p\u80BB\xA0\u0B37mp\u0100;e\u0BF9\u0C00\u0280aeouy\u29F4\u29FE\u2A03\u2A10\u2A13\u01F0\u29F9\0\u29FB;\u6A43on;\u4148dil;\u4146ng\u0100;d\u0D7E\u2A0Aot;\uC000\u2A6D\u0338p;\u6A42;\u443Dash;\u6013\u0380;Aadqsx\u0B92\u2A29\u2A2D\u2A3B\u2A41\u2A45\u2A50rr;\u61D7r\u0100hr\u2A33\u2A36k;\u6924\u0100;o\u13F2\u13F0ot;\uC000\u2250\u0338ui\xF6\u0B63\u0100ei\u2A4A\u2A4Ear;\u6928\xED\u0B98ist\u0100;s\u0BA0\u0B9Fr;\uC000\u{1D52B}\u0200Eest\u0BC5\u2A66\u2A79\u2A7C\u0180;qs\u0BBC\u2A6D\u0BE1\u0180;qs\u0BBC\u0BC5\u2A74lan\xF4\u0BE2i\xED\u0BEA\u0100;r\u0BB6\u2A81\xBB\u0BB7\u0180Aap\u2A8A\u2A8D\u2A91r\xF2\u2971rr;\u61AEar;\u6AF2\u0180;sv\u0F8D\u2A9C\u0F8C\u0100;d\u2AA1\u2AA2\u62FC;\u62FAcy;\u445A\u0380AEadest\u2AB7\u2ABA\u2ABE\u2AC2\u2AC5\u2AF6\u2AF9r\xF2\u2966;\uC000\u2266\u0338rr;\u619Ar;\u6025\u0200;fqs\u0C3B\u2ACE\u2AE3\u2AEFt\u0100ar\u2AD4\u2AD9rro\xF7\u2AC1ightarro\xF7\u2A90\u0180;qs\u0C3B\u2ABA\u2AEAlan\xF4\u0C55\u0100;s\u0C55\u2AF4\xBB\u0C36i\xED\u0C5D\u0100;r\u0C35\u2AFEi\u0100;e\u0C1A\u0C25i\xE4\u0D90\u0100pt\u2B0C\u2B11f;\uC000\u{1D55F}\u8180\xAC;in\u2B19\u2B1A\u2B36\u40ACn\u0200;Edv\u0B89\u2B24\u2B28\u2B2E;\uC000\u22F9\u0338ot;\uC000\u22F5\u0338\u01E1\u0B89\u2B33\u2B35;\u62F7;\u62F6i\u0100;v\u0CB8\u2B3C\u01E1\u0CB8\u2B41\u2B43;\u62FE;\u62FD\u0180aor\u2B4B\u2B63\u2B69r\u0200;ast\u0B7B\u2B55\u2B5A\u2B5Flle\xEC\u0B7Bl;\uC000\u2AFD\u20E5;\uC000\u2202\u0338lint;\u6A14\u0180;ce\u0C92\u2B70\u2B73u\xE5\u0CA5\u0100;c\u0C98\u2B78\u0100;e\u0C92\u2B7D\xF1\u0C98\u0200Aait\u2B88\u2B8B\u2B9D\u2BA7r\xF2\u2988rr\u0180;cw\u2B94\u2B95\u2B99\u619B;\uC000\u2933\u0338;\uC000\u219D\u0338ghtarrow\xBB\u2B95ri\u0100;e\u0CCB\u0CD6\u0380chimpqu\u2BBD\u2BCD\u2BD9\u2B04\u0B78\u2BE4\u2BEF\u0200;cer\u0D32\u2BC6\u0D37\u2BC9u\xE5\u0D45;\uC000\u{1D4C3}ort\u026D\u2B05\0\0\u2BD6ar\xE1\u2B56m\u0100;e\u0D6E\u2BDF\u0100;q\u0D74\u0D73su\u0100bp\u2BEB\u2BED\xE5\u0CF8\xE5\u0D0B\u0180bcp\u2BF6\u2C11\u2C19\u0200;Ees\u2BFF\u2C00\u0D22\u2C04\u6284;\uC000\u2AC5\u0338et\u0100;e\u0D1B\u2C0Bq\u0100;q\u0D23\u2C00c\u0100;e\u0D32\u2C17\xF1\u0D38\u0200;Ees\u2C22\u2C23\u0D5F\u2C27\u6285;\uC000\u2AC6\u0338et\u0100;e\u0D58\u2C2Eq\u0100;q\u0D60\u2C23\u0200gilr\u2C3D\u2C3F\u2C45\u2C47\xEC\u0BD7lde\u803B\xF1\u40F1\xE7\u0C43iangle\u0100lr\u2C52\u2C5Ceft\u0100;e\u0C1A\u2C5A\xF1\u0C26ight\u0100;e\u0CCB\u2C65\xF1\u0CD7\u0100;m\u2C6C\u2C6D\u43BD\u0180;es\u2C74\u2C75\u2C79\u4023ro;\u6116p;\u6007\u0480DHadgilrs\u2C8F\u2C94\u2C99\u2C9E\u2CA3\u2CB0\u2CB6\u2CD3\u2CE3ash;\u62ADarr;\u6904p;\uC000\u224D\u20D2ash;\u62AC\u0100et\u2CA8\u2CAC;\uC000\u2265\u20D2;\uC000>\u20D2nfin;\u69DE\u0180Aet\u2CBD\u2CC1\u2CC5rr;\u6902;\uC000\u2264\u20D2\u0100;r\u2CCA\u2CCD\uC000<\u20D2ie;\uC000\u22B4\u20D2\u0100At\u2CD8\u2CDCrr;\u6903rie;\uC000\u22B5\u20D2im;\uC000\u223C\u20D2\u0180Aan\u2CF0\u2CF4\u2D02rr;\u61D6r\u0100hr\u2CFA\u2CFDk;\u6923\u0100;o\u13E7\u13E5ear;\u6927\u1253\u1A95\0\0\0\0\0\0\0\0\0\0\0\0\0\u2D2D\0\u2D38\u2D48\u2D60\u2D65\u2D72\u2D84\u1B07\0\0\u2D8D\u2DAB\0\u2DC8\u2DCE\0\u2DDC\u2E19\u2E2B\u2E3E\u2E43\u0100cs\u2D31\u1A97ute\u803B\xF3\u40F3\u0100iy\u2D3C\u2D45r\u0100;c\u1A9E\u2D42\u803B\xF4\u40F4;\u443E\u0280abios\u1AA0\u2D52\u2D57\u01C8\u2D5Alac;\u4151v;\u6A38old;\u69BClig;\u4153\u0100cr\u2D69\u2D6Dir;\u69BF;\uC000\u{1D52C}\u036F\u2D79\0\0\u2D7C\0\u2D82n;\u42DBave\u803B\xF2\u40F2;\u69C1\u0100bm\u2D88\u0DF4ar;\u69B5\u0200acit\u2D95\u2D98\u2DA5\u2DA8r\xF2\u1A80\u0100ir\u2D9D\u2DA0r;\u69BEoss;\u69BBn\xE5\u0E52;\u69C0\u0180aei\u2DB1\u2DB5\u2DB9cr;\u414Dga;\u43C9\u0180cdn\u2DC0\u2DC5\u01CDron;\u43BF;\u69B6pf;\uC000\u{1D560}\u0180ael\u2DD4\u2DD7\u01D2r;\u69B7rp;\u69B9\u0380;adiosv\u2DEA\u2DEB\u2DEE\u2E08\u2E0D\u2E10\u2E16\u6228r\xF2\u1A86\u0200;efm\u2DF7\u2DF8\u2E02\u2E05\u6A5Dr\u0100;o\u2DFE\u2DFF\u6134f\xBB\u2DFF\u803B\xAA\u40AA\u803B\xBA\u40BAgof;\u62B6r;\u6A56lope;\u6A57;\u6A5B\u0180clo\u2E1F\u2E21\u2E27\xF2\u2E01ash\u803B\xF8\u40F8l;\u6298i\u016C\u2E2F\u2E34de\u803B\xF5\u40F5es\u0100;a\u01DB\u2E3As;\u6A36ml\u803B\xF6\u40F6bar;\u633D\u0AE1\u2E5E\0\u2E7D\0\u2E80\u2E9D\0\u2EA2\u2EB9\0\0\u2ECB\u0E9C\0\u2F13\0\0\u2F2B\u2FBC\0\u2FC8r\u0200;ast\u0403\u2E67\u2E72\u0E85\u8100\xB6;l\u2E6D\u2E6E\u40B6le\xEC\u0403\u0269\u2E78\0\0\u2E7Bm;\u6AF3;\u6AFDy;\u443Fr\u0280cimpt\u2E8B\u2E8F\u2E93\u1865\u2E97nt;\u4025od;\u402Eil;\u6030enk;\u6031r;\uC000\u{1D52D}\u0180imo\u2EA8\u2EB0\u2EB4\u0100;v\u2EAD\u2EAE\u43C6;\u43D5ma\xF4\u0A76ne;\u660E\u0180;tv\u2EBF\u2EC0\u2EC8\u43C0chfork\xBB\u1FFD;\u43D6\u0100au\u2ECF\u2EDFn\u0100ck\u2ED5\u2EDDk\u0100;h\u21F4\u2EDB;\u610E\xF6\u21F4s\u0480;abcdemst\u2EF3\u2EF4\u1908\u2EF9\u2EFD\u2F04\u2F06\u2F0A\u2F0E\u402Bcir;\u6A23ir;\u6A22\u0100ou\u1D40\u2F02;\u6A25;\u6A72n\u80BB\xB1\u0E9Dim;\u6A26wo;\u6A27\u0180ipu\u2F19\u2F20\u2F25ntint;\u6A15f;\uC000\u{1D561}nd\u803B\xA3\u40A3\u0500;Eaceinosu\u0EC8\u2F3F\u2F41\u2F44\u2F47\u2F81\u2F89\u2F92\u2F7E\u2FB6;\u6AB3p;\u6AB7u\xE5\u0ED9\u0100;c\u0ECE\u2F4C\u0300;acens\u0EC8\u2F59\u2F5F\u2F66\u2F68\u2F7Eppro\xF8\u2F43urlye\xF1\u0ED9\xF1\u0ECE\u0180aes\u2F6F\u2F76\u2F7Approx;\u6AB9qq;\u6AB5im;\u62E8i\xED\u0EDFme\u0100;s\u2F88\u0EAE\u6032\u0180Eas\u2F78\u2F90\u2F7A\xF0\u2F75\u0180dfp\u0EEC\u2F99\u2FAF\u0180als\u2FA0\u2FA5\u2FAAlar;\u632Eine;\u6312urf;\u6313\u0100;t\u0EFB\u2FB4\xEF\u0EFBrel;\u62B0\u0100ci\u2FC0\u2FC5r;\uC000\u{1D4C5};\u43C8ncsp;\u6008\u0300fiopsu\u2FDA\u22E2\u2FDF\u2FE5\u2FEB\u2FF1r;\uC000\u{1D52E}pf;\uC000\u{1D562}rime;\u6057cr;\uC000\u{1D4C6}\u0180aeo\u2FF8\u3009\u3013t\u0100ei\u2FFE\u3005rnion\xF3\u06B0nt;\u6A16st\u0100;e\u3010\u3011\u403F\xF1\u1F19\xF4\u0F14\u0A80ABHabcdefhilmnoprstux\u3040\u3051\u3055\u3059\u30E0\u310E\u312B\u3147\u3162\u3172\u318E\u3206\u3215\u3224\u3229\u3258\u326E\u3272\u3290\u32B0\u32B7\u0180art\u3047\u304A\u304Cr\xF2\u10B3\xF2\u03DDail;\u691Car\xF2\u1C65ar;\u6964\u0380cdenqrt\u3068\u3075\u3078\u307F\u308F\u3094\u30CC\u0100eu\u306D\u3071;\uC000\u223D\u0331te;\u4155i\xE3\u116Emptyv;\u69B3g\u0200;del\u0FD1\u3089\u308B\u308D;\u6992;\u69A5\xE5\u0FD1uo\u803B\xBB\u40BBr\u0580;abcfhlpstw\u0FDC\u30AC\u30AF\u30B7\u30B9\u30BC\u30BE\u30C0\u30C3\u30C7\u30CAp;\u6975\u0100;f\u0FE0\u30B4s;\u6920;\u6933s;\u691E\xEB\u225D\xF0\u272El;\u6945im;\u6974l;\u61A3;\u619D\u0100ai\u30D1\u30D5il;\u691Ao\u0100;n\u30DB\u30DC\u6236al\xF3\u0F1E\u0180abr\u30E7\u30EA\u30EEr\xF2\u17E5rk;\u6773\u0100ak\u30F3\u30FDc\u0100ek\u30F9\u30FB;\u407D;\u405D\u0100es\u3102\u3104;\u698Cl\u0100du\u310A\u310C;\u698E;\u6990\u0200aeuy\u3117\u311C\u3127\u3129ron;\u4159\u0100di\u3121\u3125il;\u4157\xEC\u0FF2\xE2\u30FA;\u4440\u0200clqs\u3134\u3137\u313D\u3144a;\u6937dhar;\u6969uo\u0100;r\u020E\u020Dh;\u61B3\u0180acg\u314E\u315F\u0F44l\u0200;ips\u0F78\u3158\u315B\u109Cn\xE5\u10BBar\xF4\u0FA9t;\u65AD\u0180ilr\u3169\u1023\u316Esht;\u697D;\uC000\u{1D52F}\u0100ao\u3177\u3186r\u0100du\u317D\u317F\xBB\u047B\u0100;l\u1091\u3184;\u696C\u0100;v\u318B\u318C\u43C1;\u43F1\u0180gns\u3195\u31F9\u31FCht\u0300ahlrst\u31A4\u31B0\u31C2\u31D8\u31E4\u31EErrow\u0100;t\u0FDC\u31ADa\xE9\u30C8arpoon\u0100du\u31BB\u31BFow\xEE\u317Ep\xBB\u1092eft\u0100ah\u31CA\u31D0rrow\xF3\u0FEAarpoon\xF3\u0551ightarrows;\u61C9quigarro\xF7\u30CBhreetimes;\u62CCg;\u42DAingdotse\xF1\u1F32\u0180ahm\u320D\u3210\u3213r\xF2\u0FEAa\xF2\u0551;\u600Foust\u0100;a\u321E\u321F\u63B1che\xBB\u321Fmid;\u6AEE\u0200abpt\u3232\u323D\u3240\u3252\u0100nr\u3237\u323Ag;\u67EDr;\u61FEr\xEB\u1003\u0180afl\u3247\u324A\u324Er;\u6986;\uC000\u{1D563}us;\u6A2Eimes;\u6A35\u0100ap\u325D\u3267r\u0100;g\u3263\u3264\u4029t;\u6994olint;\u6A12ar\xF2\u31E3\u0200achq\u327B\u3280\u10BC\u3285quo;\u603Ar;\uC000\u{1D4C7}\u0100bu\u30FB\u328Ao\u0100;r\u0214\u0213\u0180hir\u3297\u329B\u32A0re\xE5\u31F8mes;\u62CAi\u0200;efl\u32AA\u1059\u1821\u32AB\u65B9tri;\u69CEluhar;\u6968;\u611E\u0D61\u32D5\u32DB\u32DF\u332C\u3338\u3371\0\u337A\u33A4\0\0\u33EC\u33F0\0\u3428\u3448\u345A\u34AD\u34B1\u34CA\u34F1\0\u3616\0\0\u3633cute;\u415Bqu\xEF\u27BA\u0500;Eaceinpsy\u11ED\u32F3\u32F5\u32FF\u3302\u330B\u330F\u331F\u3326\u3329;\u6AB4\u01F0\u32FA\0\u32FC;\u6AB8on;\u4161u\xE5\u11FE\u0100;d\u11F3\u3307il;\u415Frc;\u415D\u0180Eas\u3316\u3318\u331B;\u6AB6p;\u6ABAim;\u62E9olint;\u6A13i\xED\u1204;\u4441ot\u0180;be\u3334\u1D47\u3335\u62C5;\u6A66\u0380Aacmstx\u3346\u334A\u3357\u335B\u335E\u3363\u336Drr;\u61D8r\u0100hr\u3350\u3352\xEB\u2228\u0100;o\u0A36\u0A34t\u803B\xA7\u40A7i;\u403Bwar;\u6929m\u0100in\u3369\xF0nu\xF3\xF1t;\u6736r\u0100;o\u3376\u2055\uC000\u{1D530}\u0200acoy\u3382\u3386\u3391\u33A0rp;\u666F\u0100hy\u338B\u338Fcy;\u4449;\u4448rt\u026D\u3399\0\0\u339Ci\xE4\u1464ara\xEC\u2E6F\u803B\xAD\u40AD\u0100gm\u33A8\u33B4ma\u0180;fv\u33B1\u33B2\u33B2\u43C3;\u43C2\u0400;deglnpr\u12AB\u33C5\u33C9\u33CE\u33D6\u33DE\u33E1\u33E6ot;\u6A6A\u0100;q\u12B1\u12B0\u0100;E\u33D3\u33D4\u6A9E;\u6AA0\u0100;E\u33DB\u33DC\u6A9D;\u6A9Fe;\u6246lus;\u6A24arr;\u6972ar\xF2\u113D\u0200aeit\u33F8\u3408\u340F\u3417\u0100ls\u33FD\u3404lsetm\xE9\u336Ahp;\u6A33parsl;\u69E4\u0100dl\u1463\u3414e;\u6323\u0100;e\u341C\u341D\u6AAA\u0100;s\u3422\u3423\u6AAC;\uC000\u2AAC\uFE00\u0180flp\u342E\u3433\u3442tcy;\u444C\u0100;b\u3438\u3439\u402F\u0100;a\u343E\u343F\u69C4r;\u633Ff;\uC000\u{1D564}a\u0100dr\u344D\u0402es\u0100;u\u3454\u3455\u6660it\xBB\u3455\u0180csu\u3460\u3479\u349F\u0100au\u3465\u346Fp\u0100;s\u1188\u346B;\uC000\u2293\uFE00p\u0100;s\u11B4\u3475;\uC000\u2294\uFE00u\u0100bp\u347F\u348F\u0180;es\u1197\u119C\u3486et\u0100;e\u1197\u348D\xF1\u119D\u0180;es\u11A8\u11AD\u3496et\u0100;e\u11A8\u349D\xF1\u11AE\u0180;af\u117B\u34A6\u05B0r\u0165\u34AB\u05B1\xBB\u117Car\xF2\u1148\u0200cemt\u34B9\u34BE\u34C2\u34C5r;\uC000\u{1D4C8}tm\xEE\xF1i\xEC\u3415ar\xE6\u11BE\u0100ar\u34CE\u34D5r\u0100;f\u34D4\u17BF\u6606\u0100an\u34DA\u34EDight\u0100ep\u34E3\u34EApsilo\xEE\u1EE0h\xE9\u2EAFs\xBB\u2852\u0280bcmnp\u34FB\u355E\u1209\u358B\u358E\u0480;Edemnprs\u350E\u350F\u3511\u3515\u351E\u3523\u352C\u3531\u3536\u6282;\u6AC5ot;\u6ABD\u0100;d\u11DA\u351Aot;\u6AC3ult;\u6AC1\u0100Ee\u3528\u352A;\u6ACB;\u628Alus;\u6ABFarr;\u6979\u0180eiu\u353D\u3552\u3555t\u0180;en\u350E\u3545\u354Bq\u0100;q\u11DA\u350Feq\u0100;q\u352B\u3528m;\u6AC7\u0100bp\u355A\u355C;\u6AD5;\u6AD3c\u0300;acens\u11ED\u356C\u3572\u3579\u357B\u3326ppro\xF8\u32FAurlye\xF1\u11FE\xF1\u11F3\u0180aes\u3582\u3588\u331Bppro\xF8\u331Aq\xF1\u3317g;\u666A\u0680123;Edehlmnps\u35A9\u35AC\u35AF\u121C\u35B2\u35B4\u35C0\u35C9\u35D5\u35DA\u35DF\u35E8\u35ED\u803B\xB9\u40B9\u803B\xB2\u40B2\u803B\xB3\u40B3;\u6AC6\u0100os\u35B9\u35BCt;\u6ABEub;\u6AD8\u0100;d\u1222\u35C5ot;\u6AC4s\u0100ou\u35CF\u35D2l;\u67C9b;\u6AD7arr;\u697Bult;\u6AC2\u0100Ee\u35E4\u35E6;\u6ACC;\u628Blus;\u6AC0\u0180eiu\u35F4\u3609\u360Ct\u0180;en\u121C\u35FC\u3602q\u0100;q\u1222\u35B2eq\u0100;q\u35E7\u35E4m;\u6AC8\u0100bp\u3611\u3613;\u6AD4;\u6AD6\u0180Aan\u361C\u3620\u362Drr;\u61D9r\u0100hr\u3626\u3628\xEB\u222E\u0100;o\u0A2B\u0A29war;\u692Alig\u803B\xDF\u40DF\u0BE1\u3651\u365D\u3660\u12CE\u3673\u3679\0\u367E\u36C2\0\0\0\0\0\u36DB\u3703\0\u3709\u376C\0\0\0\u3787\u0272\u3656\0\0\u365Bget;\u6316;\u43C4r\xEB\u0E5F\u0180aey\u3666\u366B\u3670ron;\u4165dil;\u4163;\u4442lrec;\u6315r;\uC000\u{1D531}\u0200eiko\u3686\u369D\u36B5\u36BC\u01F2\u368B\0\u3691e\u01004f\u1284\u1281a\u0180;sv\u3698\u3699\u369B\u43B8ym;\u43D1\u0100cn\u36A2\u36B2k\u0100as\u36A8\u36AEppro\xF8\u12C1im\xBB\u12ACs\xF0\u129E\u0100as\u36BA\u36AE\xF0\u12C1rn\u803B\xFE\u40FE\u01EC\u031F\u36C6\u22E7es\u8180\xD7;bd\u36CF\u36D0\u36D8\u40D7\u0100;a\u190F\u36D5r;\u6A31;\u6A30\u0180eps\u36E1\u36E3\u3700\xE1\u2A4D\u0200;bcf\u0486\u36EC\u36F0\u36F4ot;\u6336ir;\u6AF1\u0100;o\u36F9\u36FC\uC000\u{1D565}rk;\u6ADA\xE1\u3362rime;\u6034\u0180aip\u370F\u3712\u3764d\xE5\u1248\u0380adempst\u3721\u374D\u3740\u3751\u3757\u375C\u375Fngle\u0280;dlqr\u3730\u3731\u3736\u3740\u3742\u65B5own\xBB\u1DBBeft\u0100;e\u2800\u373E\xF1\u092E;\u625Cight\u0100;e\u32AA\u374B\xF1\u105Aot;\u65ECinus;\u6A3Alus;\u6A39b;\u69CDime;\u6A3Bezium;\u63E2\u0180cht\u3772\u377D\u3781\u0100ry\u3777\u377B;\uC000\u{1D4C9};\u4446cy;\u445Brok;\u4167\u0100io\u378B\u378Ex\xF4\u1777head\u0100lr\u3797\u37A0eftarro\xF7\u084Fightarrow\xBB\u0F5D\u0900AHabcdfghlmoprstuw\u37D0\u37D3\u37D7\u37E4\u37F0\u37FC\u380E\u381C\u3823\u3834\u3851\u385D\u386B\u38A9\u38CC\u38D2\u38EA\u38F6r\xF2\u03EDar;\u6963\u0100cr\u37DC\u37E2ute\u803B\xFA\u40FA\xF2\u1150r\u01E3\u37EA\0\u37EDy;\u445Eve;\u416D\u0100iy\u37F5\u37FArc\u803B\xFB\u40FB;\u4443\u0180abh\u3803\u3806\u380Br\xF2\u13ADlac;\u4171a\xF2\u13C3\u0100ir\u3813\u3818sht;\u697E;\uC000\u{1D532}rave\u803B\xF9\u40F9\u0161\u3827\u3831r\u0100lr\u382C\u382E\xBB\u0957\xBB\u1083lk;\u6580\u0100ct\u3839\u384D\u026F\u383F\0\0\u384Arn\u0100;e\u3845\u3846\u631Cr\xBB\u3846op;\u630Fri;\u65F8\u0100al\u3856\u385Acr;\u416B\u80BB\xA8\u0349\u0100gp\u3862\u3866on;\u4173f;\uC000\u{1D566}\u0300adhlsu\u114B\u3878\u387D\u1372\u3891\u38A0own\xE1\u13B3arpoon\u0100lr\u3888\u388Cef\xF4\u382Digh\xF4\u382Fi\u0180;hl\u3899\u389A\u389C\u43C5\xBB\u13FAon\xBB\u389Aparrows;\u61C8\u0180cit\u38B0\u38C4\u38C8\u026F\u38B6\0\0\u38C1rn\u0100;e\u38BC\u38BD\u631Dr\xBB\u38BDop;\u630Eng;\u416Fri;\u65F9cr;\uC000\u{1D4CA}\u0180dir\u38D9\u38DD\u38E2ot;\u62F0lde;\u4169i\u0100;f\u3730\u38E8\xBB\u1813\u0100am\u38EF\u38F2r\xF2\u38A8l\u803B\xFC\u40FCangle;\u69A7\u0780ABDacdeflnoprsz\u391C\u391F\u3929\u392D\u39B5\u39B8\u39BD\u39DF\u39E4\u39E8\u39F3\u39F9\u39FD\u3A01\u3A20r\xF2\u03F7ar\u0100;v\u3926\u3927\u6AE8;\u6AE9as\xE8\u03E1\u0100nr\u3932\u3937grt;\u699C\u0380eknprst\u34E3\u3946\u394B\u3952\u395D\u3964\u3996app\xE1\u2415othin\xE7\u1E96\u0180hir\u34EB\u2EC8\u3959op\xF4\u2FB5\u0100;h\u13B7\u3962\xEF\u318D\u0100iu\u3969\u396Dgm\xE1\u33B3\u0100bp\u3972\u3984setneq\u0100;q\u397D\u3980\uC000\u228A\uFE00;\uC000\u2ACB\uFE00setneq\u0100;q\u398F\u3992\uC000\u228B\uFE00;\uC000\u2ACC\uFE00\u0100hr\u399B\u399Fet\xE1\u369Ciangle\u0100lr\u39AA\u39AFeft\xBB\u0925ight\xBB\u1051y;\u4432ash\xBB\u1036\u0180elr\u39C4\u39D2\u39D7\u0180;be\u2DEA\u39CB\u39CFar;\u62BBq;\u625Alip;\u62EE\u0100bt\u39DC\u1468a\xF2\u1469r;\uC000\u{1D533}tr\xE9\u39AEsu\u0100bp\u39EF\u39F1\xBB\u0D1C\xBB\u0D59pf;\uC000\u{1D567}ro\xF0\u0EFBtr\xE9\u39B4\u0100cu\u3A06\u3A0Br;\uC000\u{1D4CB}\u0100bp\u3A10\u3A18n\u0100Ee\u3980\u3A16\xBB\u397En\u0100Ee\u3992\u3A1E\xBB\u3990igzag;\u699A\u0380cefoprs\u3A36\u3A3B\u3A56\u3A5B\u3A54\u3A61\u3A6Airc;\u4175\u0100di\u3A40\u3A51\u0100bg\u3A45\u3A49ar;\u6A5Fe\u0100;q\u15FA\u3A4F;\u6259erp;\u6118r;\uC000\u{1D534}pf;\uC000\u{1D568}\u0100;e\u1479\u3A66at\xE8\u1479cr;\uC000\u{1D4CC}\u0AE3\u178E\u3A87\0\u3A8B\0\u3A90\u3A9B\0\0\u3A9D\u3AA8\u3AAB\u3AAF\0\0\u3AC3\u3ACE\0\u3AD8\u17DC\u17DFtr\xE9\u17D1r;\uC000\u{1D535}\u0100Aa\u3A94\u3A97r\xF2\u03C3r\xF2\u09F6;\u43BE\u0100Aa\u3AA1\u3AA4r\xF2\u03B8r\xF2\u09EBa\xF0\u2713is;\u62FB\u0180dpt\u17A4\u3AB5\u3ABE\u0100fl\u3ABA\u17A9;\uC000\u{1D569}im\xE5\u17B2\u0100Aa\u3AC7\u3ACAr\xF2\u03CEr\xF2\u0A01\u0100cq\u3AD2\u17B8r;\uC000\u{1D4CD}\u0100pt\u17D6\u3ADCr\xE9\u17D4\u0400acefiosu\u3AF0\u3AFD\u3B08\u3B0C\u3B11\u3B15\u3B1B\u3B21c\u0100uy\u3AF6\u3AFBte\u803B\xFD\u40FD;\u444F\u0100iy\u3B02\u3B06rc;\u4177;\u444Bn\u803B\xA5\u40A5r;\uC000\u{1D536}cy;\u4457pf;\uC000\u{1D56A}cr;\uC000\u{1D4CE}\u0100cm\u3B26\u3B29y;\u444El\u803B\xFF\u40FF\u0500acdefhiosw\u3B42\u3B48\u3B54\u3B58\u3B64\u3B69\u3B6D\u3B74\u3B7A\u3B80cute;\u417A\u0100ay\u3B4D\u3B52ron;\u417E;\u4437ot;\u417C\u0100et\u3B5D\u3B61tr\xE6\u155Fa;\u43B6r;\uC000\u{1D537}cy;\u4436grarr;\u61DDpf;\uC000\u{1D56B}cr;\uC000\u{1D4CF}\u0100jn\u3B85\u3B87;\u600Dj;\u600C'.split("").map(c2=>c2.charCodeAt(0)))}});var decode_data_xml_default,init_decode_data_xml=__esm({"../../node_modules/.pnpm/entities@4.5.0/node_modules/entities/lib/esm/generated/decode-data-xml.js"(){decode_data_xml_default=new Uint16Array("\u0200aglq \x1B\u026D\0\0p;\u4026os;\u4027t;\u403Et;\u403Cuot;\u4022".split("").map(c2=>c2.charCodeAt(0)))}});function replaceCodePoint(codePoint){var _a4;return codePoint>=55296&&codePoint<=57343||codePoint>1114111?65533:(_a4=decodeMap.get(codePoint))!==null&&_a4!==void 0?_a4:codePoint}var _a,decodeMap,fromCodePoint,init_decode_codepoint=__esm({"../../node_modules/.pnpm/entities@4.5.0/node_modules/entities/lib/esm/decode_codepoint.js"(){decodeMap=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]),fromCodePoint=(_a=String.fromCodePoint)!==null&&_a!==void 0?_a:function(codePoint){let output="";return codePoint>65535&&(codePoint-=65536,output+=String.fromCharCode(codePoint>>>10&1023|55296),codePoint=56320|codePoint&1023),output+=String.fromCharCode(codePoint),output};__name(replaceCodePoint,"replaceCodePoint")}});function isNumber(code2){return code2>=CharCodes.ZERO&&code2<=CharCodes.NINE}function isHexadecimalCharacter(code2){return code2>=CharCodes.UPPER_A&&code2<=CharCodes.UPPER_F||code2>=CharCodes.LOWER_A&&code2<=CharCodes.LOWER_F}function isAsciiAlphaNumeric(code2){return code2>=CharCodes.UPPER_A&&code2<=CharCodes.UPPER_Z||code2>=CharCodes.LOWER_A&&code2<=CharCodes.LOWER_Z||isNumber(code2)}function isEntityInAttributeInvalidEnd(code2){return code2===CharCodes.EQUALS||isAsciiAlphaNumeric(code2)}function getDecoder(decodeTree){let ret="",decoder=new EntityDecoder(decodeTree,str=>ret+=fromCodePoint(str));return __name(function(str,decodeMode){let lastIndex=0,offset=0;for(;(offset=str.indexOf("&",offset))>=0;){ret+=str.slice(lastIndex,offset),decoder.startEntity(decodeMode);let len=decoder.write(str,offset+1);if(len<0){lastIndex=offset+decoder.end();break}lastIndex=offset+len,offset=len===0?lastIndex+1:lastIndex}let result=ret+str.slice(lastIndex);return ret="",result},"decodeWithTrie")}function determineBranch(decodeTree,current,nodeIdx,char){let branchCount=(current&BinTrieFlags.BRANCH_LENGTH)>>7,jumpOffset=current&BinTrieFlags.JUMP_TABLE;if(branchCount===0)return jumpOffset!==0&&char===jumpOffset?nodeIdx:-1;if(jumpOffset){let value=char-jumpOffset;return value<0||value>=branchCount?-1:decodeTree[nodeIdx+value]-1}let lo=nodeIdx,hi=lo+branchCount-1;for(;lo<=hi;){let mid=lo+hi>>>1,midVal=decodeTree[mid];if(midVal<char)lo=mid+1;else if(midVal>char)hi=mid-1;else return decodeTree[mid+branchCount]}return-1}var CharCodes,TO_LOWER_BIT,BinTrieFlags,EntityDecoderState,DecodingMode,EntityDecoder,htmlDecoder,xmlDecoder,init_decode=__esm({"../../node_modules/.pnpm/entities@4.5.0/node_modules/entities/lib/esm/decode.js"(){init_decode_data_html();init_decode_data_xml();init_decode_codepoint();init_decode_codepoint();(function(CharCodes4){CharCodes4[CharCodes4.NUM=35]="NUM",CharCodes4[CharCodes4.SEMI=59]="SEMI",CharCodes4[CharCodes4.EQUALS=61]="EQUALS",CharCodes4[CharCodes4.ZERO=48]="ZERO",CharCodes4[CharCodes4.NINE=57]="NINE",CharCodes4[CharCodes4.LOWER_A=97]="LOWER_A",CharCodes4[CharCodes4.LOWER_F=102]="LOWER_F",CharCodes4[CharCodes4.LOWER_X=120]="LOWER_X",CharCodes4[CharCodes4.LOWER_Z=122]="LOWER_Z",CharCodes4[CharCodes4.UPPER_A=65]="UPPER_A",CharCodes4[CharCodes4.UPPER_F=70]="UPPER_F",CharCodes4[CharCodes4.UPPER_Z=90]="UPPER_Z"})(CharCodes||(CharCodes={}));TO_LOWER_BIT=32;(function(BinTrieFlags3){BinTrieFlags3[BinTrieFlags3.VALUE_LENGTH=49152]="VALUE_LENGTH",BinTrieFlags3[BinTrieFlags3.BRANCH_LENGTH=16256]="BRANCH_LENGTH",BinTrieFlags3[BinTrieFlags3.JUMP_TABLE=127]="JUMP_TABLE"})(BinTrieFlags||(BinTrieFlags={}));__name(isNumber,"isNumber");__name(isHexadecimalCharacter,"isHexadecimalCharacter");__name(isAsciiAlphaNumeric,"isAsciiAlphaNumeric");__name(isEntityInAttributeInvalidEnd,"isEntityInAttributeInvalidEnd");(function(EntityDecoderState3){EntityDecoderState3[EntityDecoderState3.EntityStart=0]="EntityStart",EntityDecoderState3[EntityDecoderState3.NumericStart=1]="NumericStart",EntityDecoderState3[EntityDecoderState3.NumericDecimal=2]="NumericDecimal",EntityDecoderState3[EntityDecoderState3.NumericHex=3]="NumericHex",EntityDecoderState3[EntityDecoderState3.NamedEntity=4]="NamedEntity"})(EntityDecoderState||(EntityDecoderState={}));(function(DecodingMode3){DecodingMode3[DecodingMode3.Legacy=0]="Legacy",DecodingMode3[DecodingMode3.Strict=1]="Strict",DecodingMode3[DecodingMode3.Attribute=2]="Attribute"})(DecodingMode||(DecodingMode={}));EntityDecoder=class{static{__name(this,"EntityDecoder")}constructor(decodeTree,emitCodePoint,errors){this.decodeTree=decodeTree,this.emitCodePoint=emitCodePoint,this.errors=errors,this.state=EntityDecoderState.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=DecodingMode.Strict}startEntity(decodeMode){this.decodeMode=decodeMode,this.state=EntityDecoderState.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1}write(str,offset){switch(this.state){case EntityDecoderState.EntityStart:return str.charCodeAt(offset)===CharCodes.NUM?(this.state=EntityDecoderState.NumericStart,this.consumed+=1,this.stateNumericStart(str,offset+1)):(this.state=EntityDecoderState.NamedEntity,this.stateNamedEntity(str,offset));case EntityDecoderState.NumericStart:return this.stateNumericStart(str,offset);case EntityDecoderState.NumericDecimal:return this.stateNumericDecimal(str,offset);case EntityDecoderState.NumericHex:return this.stateNumericHex(str,offset);case EntityDecoderState.NamedEntity:return this.stateNamedEntity(str,offset)}}stateNumericStart(str,offset){return offset>=str.length?-1:(str.charCodeAt(offset)|TO_LOWER_BIT)===CharCodes.LOWER_X?(this.state=EntityDecoderState.NumericHex,this.consumed+=1,this.stateNumericHex(str,offset+1)):(this.state=EntityDecoderState.NumericDecimal,this.stateNumericDecimal(str,offset))}addToNumericResult(str,start,end2,base){if(start!==end2){let digitCount=end2-start;this.result=this.result*Math.pow(base,digitCount)+parseInt(str.substr(start,digitCount),base),this.consumed+=digitCount}}stateNumericHex(str,offset){let startIdx=offset;for(;offset<str.length;){let char=str.charCodeAt(offset);if(isNumber(char)||isHexadecimalCharacter(char))offset+=1;else return this.addToNumericResult(str,startIdx,offset,16),this.emitNumericEntity(char,3)}return this.addToNumericResult(str,startIdx,offset,16),-1}stateNumericDecimal(str,offset){let startIdx=offset;for(;offset<str.length;){let char=str.charCodeAt(offset);if(isNumber(char))offset+=1;else return this.addToNumericResult(str,startIdx,offset,10),this.emitNumericEntity(char,2)}return this.addToNumericResult(str,startIdx,offset,10),-1}emitNumericEntity(lastCp,expectedLength){var _a4;if(this.consumed<=expectedLength)return(_a4=this.errors)===null||_a4===void 0||_a4.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(lastCp===CharCodes.SEMI)this.consumed+=1;else if(this.decodeMode===DecodingMode.Strict)return 0;return this.emitCodePoint(replaceCodePoint(this.result),this.consumed),this.errors&&(lastCp!==CharCodes.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(str,offset){let{decodeTree}=this,current=decodeTree[this.treeIndex],valueLength=(current&BinTrieFlags.VALUE_LENGTH)>>14;for(;offset<str.length;offset++,this.excess++){let char=str.charCodeAt(offset);if(this.treeIndex=determineBranch(decodeTree,current,this.treeIndex+Math.max(1,valueLength),char),this.treeIndex<0)return this.result===0||this.decodeMode===DecodingMode.Attribute&&(valueLength===0||isEntityInAttributeInvalidEnd(char))?0:this.emitNotTerminatedNamedEntity();if(current=decodeTree[this.treeIndex],valueLength=(current&BinTrieFlags.VALUE_LENGTH)>>14,valueLength!==0){if(char===CharCodes.SEMI)return this.emitNamedEntityData(this.treeIndex,valueLength,this.consumed+this.excess);this.decodeMode!==DecodingMode.Strict&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0)}}return-1}emitNotTerminatedNamedEntity(){var _a4;let{result,decodeTree}=this,valueLength=(decodeTree[result]&BinTrieFlags.VALUE_LENGTH)>>14;return this.emitNamedEntityData(result,valueLength,this.consumed),(_a4=this.errors)===null||_a4===void 0||_a4.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(result,valueLength,consumed){let{decodeTree}=this;return this.emitCodePoint(valueLength===1?decodeTree[result]&~BinTrieFlags.VALUE_LENGTH:decodeTree[result+1],consumed),valueLength===3&&this.emitCodePoint(decodeTree[result+2],consumed),consumed}end(){var _a4;switch(this.state){case EntityDecoderState.NamedEntity:return this.result!==0&&(this.decodeMode!==DecodingMode.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case EntityDecoderState.NumericDecimal:return this.emitNumericEntity(0,2);case EntityDecoderState.NumericHex:return this.emitNumericEntity(0,3);case EntityDecoderState.NumericStart:return(_a4=this.errors)===null||_a4===void 0||_a4.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case EntityDecoderState.EntityStart:return 0}}};__name(getDecoder,"getDecoder");__name(determineBranch,"determineBranch");htmlDecoder=getDecoder(decode_data_html_default),xmlDecoder=getDecoder(decode_data_xml_default)}});function restoreDiff(arr){for(let i=1;i<arr.length;i++)arr[i][0]+=arr[i-1][0]+1;return arr}var encode_html_default,init_encode_html=__esm({"../../node_modules/.pnpm/entities@4.5.0/node_modules/entities/lib/esm/generated/encode-html.js"(){__name(restoreDiff,"restoreDiff");encode_html_default=new Map(restoreDiff([[9,"&Tab;"],[0,"&NewLine;"],[22,"&excl;"],[0,"&quot;"],[0,"&num;"],[0,"&dollar;"],[0,"&percnt;"],[0,"&amp;"],[0,"&apos;"],[0,"&lpar;"],[0,"&rpar;"],[0,"&ast;"],[0,"&plus;"],[0,"&comma;"],[1,"&period;"],[0,"&sol;"],[10,"&colon;"],[0,"&semi;"],[0,{v:"&lt;",n:8402,o:"&nvlt;"}],[0,{v:"&equals;",n:8421,o:"&bne;"}],[0,{v:"&gt;",n:8402,o:"&nvgt;"}],[0,"&quest;"],[0,"&commat;"],[26,"&lbrack;"],[0,"&bsol;"],[0,"&rbrack;"],[0,"&Hat;"],[0,"&lowbar;"],[0,"&DiacriticalGrave;"],[5,{n:106,o:"&fjlig;"}],[20,"&lbrace;"],[0,"&verbar;"],[0,"&rbrace;"],[34,"&nbsp;"],[0,"&iexcl;"],[0,"&cent;"],[0,"&pound;"],[0,"&curren;"],[0,"&yen;"],[0,"&brvbar;"],[0,"&sect;"],[0,"&die;"],[0,"&copy;"],[0,"&ordf;"],[0,"&laquo;"],[0,"&not;"],[0,"&shy;"],[0,"&circledR;"],[0,"&macr;"],[0,"&deg;"],[0,"&PlusMinus;"],[0,"&sup2;"],[0,"&sup3;"],[0,"&acute;"],[0,"&micro;"],[0,"&para;"],[0,"&centerdot;"],[0,"&cedil;"],[0,"&sup1;"],[0,"&ordm;"],[0,"&raquo;"],[0,"&frac14;"],[0,"&frac12;"],[0,"&frac34;"],[0,"&iquest;"],[0,"&Agrave;"],[0,"&Aacute;"],[0,"&Acirc;"],[0,"&Atilde;"],[0,"&Auml;"],[0,"&angst;"],[0,"&AElig;"],[0,"&Ccedil;"],[0,"&Egrave;"],[0,"&Eacute;"],[0,"&Ecirc;"],[0,"&Euml;"],[0,"&Igrave;"],[0,"&Iacute;"],[0,"&Icirc;"],[0,"&Iuml;"],[0,"&ETH;"],[0,"&Ntilde;"],[0,"&Ograve;"],[0,"&Oacute;"],[0,"&Ocirc;"],[0,"&Otilde;"],[0,"&Ouml;"],[0,"&times;"],[0,"&Oslash;"],[0,"&Ugrave;"],[0,"&Uacute;"],[0,"&Ucirc;"],[0,"&Uuml;"],[0,"&Yacute;"],[0,"&THORN;"],[0,"&szlig;"],[0,"&agrave;"],[0,"&aacute;"],[0,"&acirc;"],[0,"&atilde;"],[0,"&auml;"],[0,"&aring;"],[0,"&aelig;"],[0,"&ccedil;"],[0,"&egrave;"],[0,"&eacute;"],[0,"&ecirc;"],[0,"&euml;"],[0,"&igrave;"],[0,"&iacute;"],[0,"&icirc;"],[0,"&iuml;"],[0,"&eth;"],[0,"&ntilde;"],[0,"&ograve;"],[0,"&oacute;"],[0,"&ocirc;"],[0,"&otilde;"],[0,"&ouml;"],[0,"&div;"],[0,"&oslash;"],[0,"&ugrave;"],[0,"&uacute;"],[0,"&ucirc;"],[0,"&uuml;"],[0,"&yacute;"],[0,"&thorn;"],[0,"&yuml;"],[0,"&Amacr;"],[0,"&amacr;"],[0,"&Abreve;"],[0,"&abreve;"],[0,"&Aogon;"],[0,"&aogon;"],[0,"&Cacute;"],[0,"&cacute;"],[0,"&Ccirc;"],[0,"&ccirc;"],[0,"&Cdot;"],[0,"&cdot;"],[0,"&Ccaron;"],[0,"&ccaron;"],[0,"&Dcaron;"],[0,"&dcaron;"],[0,"&Dstrok;"],[0,"&dstrok;"],[0,"&Emacr;"],[0,"&emacr;"],[2,"&Edot;"],[0,"&edot;"],[0,"&Eogon;"],[0,"&eogon;"],[0,"&Ecaron;"],[0,"&ecaron;"],[0,"&Gcirc;"],[0,"&gcirc;"],[0,"&Gbreve;"],[0,"&gbreve;"],[0,"&Gdot;"],[0,"&gdot;"],[0,"&Gcedil;"],[1,"&Hcirc;"],[0,"&hcirc;"],[0,"&Hstrok;"],[0,"&hstrok;"],[0,"&Itilde;"],[0,"&itilde;"],[0,"&Imacr;"],[0,"&imacr;"],[2,"&Iogon;"],[0,"&iogon;"],[0,"&Idot;"],[0,"&imath;"],[0,"&IJlig;"],[0,"&ijlig;"],[0,"&Jcirc;"],[0,"&jcirc;"],[0,"&Kcedil;"],[0,"&kcedil;"],[0,"&kgreen;"],[0,"&Lacute;"],[0,"&lacute;"],[0,"&Lcedil;"],[0,"&lcedil;"],[0,"&Lcaron;"],[0,"&lcaron;"],[0,"&Lmidot;"],[0,"&lmidot;"],[0,"&Lstrok;"],[0,"&lstrok;"],[0,"&Nacute;"],[0,"&nacute;"],[0,"&Ncedil;"],[0,"&ncedil;"],[0,"&Ncaron;"],[0,"&ncaron;"],[0,"&napos;"],[0,"&ENG;"],[0,"&eng;"],[0,"&Omacr;"],[0,"&omacr;"],[2,"&Odblac;"],[0,"&odblac;"],[0,"&OElig;"],[0,"&oelig;"],[0,"&Racute;"],[0,"&racute;"],[0,"&Rcedil;"],[0,"&rcedil;"],[0,"&Rcaron;"],[0,"&rcaron;"],[0,"&Sacute;"],[0,"&sacute;"],[0,"&Scirc;"],[0,"&scirc;"],[0,"&Scedil;"],[0,"&scedil;"],[0,"&Scaron;"],[0,"&scaron;"],[0,"&Tcedil;"],[0,"&tcedil;"],[0,"&Tcaron;"],[0,"&tcaron;"],[0,"&Tstrok;"],[0,"&tstrok;"],[0,"&Utilde;"],[0,"&utilde;"],[0,"&Umacr;"],[0,"&umacr;"],[0,"&Ubreve;"],[0,"&ubreve;"],[0,"&Uring;"],[0,"&uring;"],[0,"&Udblac;"],[0,"&udblac;"],[0,"&Uogon;"],[0,"&uogon;"],[0,"&Wcirc;"],[0,"&wcirc;"],[0,"&Ycirc;"],[0,"&ycirc;"],[0,"&Yuml;"],[0,"&Zacute;"],[0,"&zacute;"],[0,"&Zdot;"],[0,"&zdot;"],[0,"&Zcaron;"],[0,"&zcaron;"],[19,"&fnof;"],[34,"&imped;"],[63,"&gacute;"],[65,"&jmath;"],[142,"&circ;"],[0,"&caron;"],[16,"&breve;"],[0,"&DiacriticalDot;"],[0,"&ring;"],[0,"&ogon;"],[0,"&DiacriticalTilde;"],[0,"&dblac;"],[51,"&DownBreve;"],[127,"&Alpha;"],[0,"&Beta;"],[0,"&Gamma;"],[0,"&Delta;"],[0,"&Epsilon;"],[0,"&Zeta;"],[0,"&Eta;"],[0,"&Theta;"],[0,"&Iota;"],[0,"&Kappa;"],[0,"&Lambda;"],[0,"&Mu;"],[0,"&Nu;"],[0,"&Xi;"],[0,"&Omicron;"],[0,"&Pi;"],[0,"&Rho;"],[1,"&Sigma;"],[0,"&Tau;"],[0,"&Upsilon;"],[0,"&Phi;"],[0,"&Chi;"],[0,"&Psi;"],[0,"&ohm;"],[7,"&alpha;"],[0,"&beta;"],[0,"&gamma;"],[0,"&delta;"],[0,"&epsi;"],[0,"&zeta;"],[0,"&eta;"],[0,"&theta;"],[0,"&iota;"],[0,"&kappa;"],[0,"&lambda;"],[0,"&mu;"],[0,"&nu;"],[0,"&xi;"],[0,"&omicron;"],[0,"&pi;"],[0,"&rho;"],[0,"&sigmaf;"],[0,"&sigma;"],[0,"&tau;"],[0,"&upsi;"],[0,"&phi;"],[0,"&chi;"],[0,"&psi;"],[0,"&omega;"],[7,"&thetasym;"],[0,"&Upsi;"],[2,"&phiv;"],[0,"&piv;"],[5,"&Gammad;"],[0,"&digamma;"],[18,"&kappav;"],[0,"&rhov;"],[3,"&epsiv;"],[0,"&backepsilon;"],[10,"&IOcy;"],[0,"&DJcy;"],[0,"&GJcy;"],[0,"&Jukcy;"],[0,"&DScy;"],[0,"&Iukcy;"],[0,"&YIcy;"],[0,"&Jsercy;"],[0,"&LJcy;"],[0,"&NJcy;"],[0,"&TSHcy;"],[0,"&KJcy;"],[1,"&Ubrcy;"],[0,"&DZcy;"],[0,"&Acy;"],[0,"&Bcy;"],[0,"&Vcy;"],[0,"&Gcy;"],[0,"&Dcy;"],[0,"&IEcy;"],[0,"&ZHcy;"],[0,"&Zcy;"],[0,"&Icy;"],[0,"&Jcy;"],[0,"&Kcy;"],[0,"&Lcy;"],[0,"&Mcy;"],[0,"&Ncy;"],[0,"&Ocy;"],[0,"&Pcy;"],[0,"&Rcy;"],[0,"&Scy;"],[0,"&Tcy;"],[0,"&Ucy;"],[0,"&Fcy;"],[0,"&KHcy;"],[0,"&TScy;"],[0,"&CHcy;"],[0,"&SHcy;"],[0,"&SHCHcy;"],[0,"&HARDcy;"],[0,"&Ycy;"],[0,"&SOFTcy;"],[0,"&Ecy;"],[0,"&YUcy;"],[0,"&YAcy;"],[0,"&acy;"],[0,"&bcy;"],[0,"&vcy;"],[0,"&gcy;"],[0,"&dcy;"],[0,"&iecy;"],[0,"&zhcy;"],[0,"&zcy;"],[0,"&icy;"],[0,"&jcy;"],[0,"&kcy;"],[0,"&lcy;"],[0,"&mcy;"],[0,"&ncy;"],[0,"&ocy;"],[0,"&pcy;"],[0,"&rcy;"],[0,"&scy;"],[0,"&tcy;"],[0,"&ucy;"],[0,"&fcy;"],[0,"&khcy;"],[0,"&tscy;"],[0,"&chcy;"],[0,"&shcy;"],[0,"&shchcy;"],[0,"&hardcy;"],[0,"&ycy;"],[0,"&softcy;"],[0,"&ecy;"],[0,"&yucy;"],[0,"&yacy;"],[1,"&iocy;"],[0,"&djcy;"],[0,"&gjcy;"],[0,"&jukcy;"],[0,"&dscy;"],[0,"&iukcy;"],[0,"&yicy;"],[0,"&jsercy;"],[0,"&ljcy;"],[0,"&njcy;"],[0,"&tshcy;"],[0,"&kjcy;"],[1,"&ubrcy;"],[0,"&dzcy;"],[7074,"&ensp;"],[0,"&emsp;"],[0,"&emsp13;"],[0,"&emsp14;"],[1,"&numsp;"],[0,"&puncsp;"],[0,"&ThinSpace;"],[0,"&hairsp;"],[0,"&NegativeMediumSpace;"],[0,"&zwnj;"],[0,"&zwj;"],[0,"&lrm;"],[0,"&rlm;"],[0,"&dash;"],[2,"&ndash;"],[0,"&mdash;"],[0,"&horbar;"],[0,"&Verbar;"],[1,"&lsquo;"],[0,"&CloseCurlyQuote;"],[0,"&lsquor;"],[1,"&ldquo;"],[0,"&CloseCurlyDoubleQuote;"],[0,"&bdquo;"],[1,"&dagger;"],[0,"&Dagger;"],[0,"&bull;"],[2,"&nldr;"],[0,"&hellip;"],[9,"&permil;"],[0,"&pertenk;"],[0,"&prime;"],[0,"&Prime;"],[0,"&tprime;"],[0,"&backprime;"],[3,"&lsaquo;"],[0,"&rsaquo;"],[3,"&oline;"],[2,"&caret;"],[1,"&hybull;"],[0,"&frasl;"],[10,"&bsemi;"],[7,"&qprime;"],[7,{v:"&MediumSpace;",n:8202,o:"&ThickSpace;"}],[0,"&NoBreak;"],[0,"&af;"],[0,"&InvisibleTimes;"],[0,"&ic;"],[72,"&euro;"],[46,"&tdot;"],[0,"&DotDot;"],[37,"&complexes;"],[2,"&incare;"],[4,"&gscr;"],[0,"&hamilt;"],[0,"&Hfr;"],[0,"&Hopf;"],[0,"&planckh;"],[0,"&hbar;"],[0,"&imagline;"],[0,"&Ifr;"],[0,"&lagran;"],[0,"&ell;"],[1,"&naturals;"],[0,"&numero;"],[0,"&copysr;"],[0,"&weierp;"],[0,"&Popf;"],[0,"&Qopf;"],[0,"&realine;"],[0,"&real;"],[0,"&reals;"],[0,"&rx;"],[3,"&trade;"],[1,"&integers;"],[2,"&mho;"],[0,"&zeetrf;"],[0,"&iiota;"],[2,"&bernou;"],[0,"&Cayleys;"],[1,"&escr;"],[0,"&Escr;"],[0,"&Fouriertrf;"],[1,"&Mellintrf;"],[0,"&order;"],[0,"&alefsym;"],[0,"&beth;"],[0,"&gimel;"],[0,"&daleth;"],[12,"&CapitalDifferentialD;"],[0,"&dd;"],[0,"&ee;"],[0,"&ii;"],[10,"&frac13;"],[0,"&frac23;"],[0,"&frac15;"],[0,"&frac25;"],[0,"&frac35;"],[0,"&frac45;"],[0,"&frac16;"],[0,"&frac56;"],[0,"&frac18;"],[0,"&frac38;"],[0,"&frac58;"],[0,"&frac78;"],[49,"&larr;"],[0,"&ShortUpArrow;"],[0,"&rarr;"],[0,"&darr;"],[0,"&harr;"],[0,"&updownarrow;"],[0,"&nwarr;"],[0,"&nearr;"],[0,"&LowerRightArrow;"],[0,"&LowerLeftArrow;"],[0,"&nlarr;"],[0,"&nrarr;"],[1,{v:"&rarrw;",n:824,o:"&nrarrw;"}],[0,"&Larr;"],[0,"&Uarr;"],[0,"&Rarr;"],[0,"&Darr;"],[0,"&larrtl;"],[0,"&rarrtl;"],[0,"&LeftTeeArrow;"],[0,"&mapstoup;"],[0,"&map;"],[0,"&DownTeeArrow;"],[1,"&hookleftarrow;"],[0,"&hookrightarrow;"],[0,"&larrlp;"],[0,"&looparrowright;"],[0,"&harrw;"],[0,"&nharr;"],[1,"&lsh;"],[0,"&rsh;"],[0,"&ldsh;"],[0,"&rdsh;"],[1,"&crarr;"],[0,"&cularr;"],[0,"&curarr;"],[2,"&circlearrowleft;"],[0,"&circlearrowright;"],[0,"&leftharpoonup;"],[0,"&DownLeftVector;"],[0,"&RightUpVector;"],[0,"&LeftUpVector;"],[0,"&rharu;"],[0,"&DownRightVector;"],[0,"&dharr;"],[0,"&dharl;"],[0,"&RightArrowLeftArrow;"],[0,"&udarr;"],[0,"&LeftArrowRightArrow;"],[0,"&leftleftarrows;"],[0,"&upuparrows;"],[0,"&rightrightarrows;"],[0,"&ddarr;"],[0,"&leftrightharpoons;"],[0,"&Equilibrium;"],[0,"&nlArr;"],[0,"&nhArr;"],[0,"&nrArr;"],[0,"&DoubleLeftArrow;"],[0,"&DoubleUpArrow;"],[0,"&DoubleRightArrow;"],[0,"&dArr;"],[0,"&DoubleLeftRightArrow;"],[0,"&DoubleUpDownArrow;"],[0,"&nwArr;"],[0,"&neArr;"],[0,"&seArr;"],[0,"&swArr;"],[0,"&lAarr;"],[0,"&rAarr;"],[1,"&zigrarr;"],[6,"&larrb;"],[0,"&rarrb;"],[15,"&DownArrowUpArrow;"],[7,"&loarr;"],[0,"&roarr;"],[0,"&hoarr;"],[0,"&forall;"],[0,"&comp;"],[0,{v:"&part;",n:824,o:"&npart;"}],[0,"&exist;"],[0,"&nexist;"],[0,"&empty;"],[1,"&Del;"],[0,"&Element;"],[0,"&NotElement;"],[1,"&ni;"],[0,"&notni;"],[2,"&prod;"],[0,"&coprod;"],[0,"&sum;"],[0,"&minus;"],[0,"&MinusPlus;"],[0,"&dotplus;"],[1,"&Backslash;"],[0,"&lowast;"],[0,"&compfn;"],[1,"&radic;"],[2,"&prop;"],[0,"&infin;"],[0,"&angrt;"],[0,{v:"&ang;",n:8402,o:"&nang;"}],[0,"&angmsd;"],[0,"&angsph;"],[0,"&mid;"],[0,"&nmid;"],[0,"&DoubleVerticalBar;"],[0,"&NotDoubleVerticalBar;"],[0,"&and;"],[0,"&or;"],[0,{v:"&cap;",n:65024,o:"&caps;"}],[0,{v:"&cup;",n:65024,o:"&cups;"}],[0,"&int;"],[0,"&Int;"],[0,"&iiint;"],[0,"&conint;"],[0,"&Conint;"],[0,"&Cconint;"],[0,"&cwint;"],[0,"&ClockwiseContourIntegral;"],[0,"&awconint;"],[0,"&there4;"],[0,"&becaus;"],[0,"&ratio;"],[0,"&Colon;"],[0,"&dotminus;"],[1,"&mDDot;"],[0,"&homtht;"],[0,{v:"&sim;",n:8402,o:"&nvsim;"}],[0,{v:"&backsim;",n:817,o:"&race;"}],[0,{v:"&ac;",n:819,o:"&acE;"}],[0,"&acd;"],[0,"&VerticalTilde;"],[0,"&NotTilde;"],[0,{v:"&eqsim;",n:824,o:"&nesim;"}],[0,"&sime;"],[0,"&NotTildeEqual;"],[0,"&cong;"],[0,"&simne;"],[0,"&ncong;"],[0,"&ap;"],[0,"&nap;"],[0,"&ape;"],[0,{v:"&apid;",n:824,o:"&napid;"}],[0,"&backcong;"],[0,{v:"&asympeq;",n:8402,o:"&nvap;"}],[0,{v:"&bump;",n:824,o:"&nbump;"}],[0,{v:"&bumpe;",n:824,o:"&nbumpe;"}],[0,{v:"&doteq;",n:824,o:"&nedot;"}],[0,"&doteqdot;"],[0,"&efDot;"],[0,"&erDot;"],[0,"&Assign;"],[0,"&ecolon;"],[0,"&ecir;"],[0,"&circeq;"],[1,"&wedgeq;"],[0,"&veeeq;"],[1,"&triangleq;"],[2,"&equest;"],[0,"&ne;"],[0,{v:"&Congruent;",n:8421,o:"&bnequiv;"}],[0,"&nequiv;"],[1,{v:"&le;",n:8402,o:"&nvle;"}],[0,{v:"&ge;",n:8402,o:"&nvge;"}],[0,{v:"&lE;",n:824,o:"&nlE;"}],[0,{v:"&gE;",n:824,o:"&ngE;"}],[0,{v:"&lnE;",n:65024,o:"&lvertneqq;"}],[0,{v:"&gnE;",n:65024,o:"&gvertneqq;"}],[0,{v:"&ll;",n:new Map(restoreDiff([[824,"&nLtv;"],[7577,"&nLt;"]]))}],[0,{v:"&gg;",n:new Map(restoreDiff([[824,"&nGtv;"],[7577,"&nGt;"]]))}],[0,"&between;"],[0,"&NotCupCap;"],[0,"&nless;"],[0,"&ngt;"],[0,"&nle;"],[0,"&nge;"],[0,"&lesssim;"],[0,"&GreaterTilde;"],[0,"&nlsim;"],[0,"&ngsim;"],[0,"&LessGreater;"],[0,"&gl;"],[0,"&NotLessGreater;"],[0,"&NotGreaterLess;"],[0,"&pr;"],[0,"&sc;"],[0,"&prcue;"],[0,"&sccue;"],[0,"&PrecedesTilde;"],[0,{v:"&scsim;",n:824,o:"&NotSucceedsTilde;"}],[0,"&NotPrecedes;"],[0,"&NotSucceeds;"],[0,{v:"&sub;",n:8402,o:"&NotSubset;"}],[0,{v:"&sup;",n:8402,o:"&NotSuperset;"}],[0,"&nsub;"],[0,"&nsup;"],[0,"&sube;"],[0,"&supe;"],[0,"&NotSubsetEqual;"],[0,"&NotSupersetEqual;"],[0,{v:"&subne;",n:65024,o:"&varsubsetneq;"}],[0,{v:"&supne;",n:65024,o:"&varsupsetneq;"}],[1,"&cupdot;"],[0,"&UnionPlus;"],[0,{v:"&sqsub;",n:824,o:"&NotSquareSubset;"}],[0,{v:"&sqsup;",n:824,o:"&NotSquareSuperset;"}],[0,"&sqsube;"],[0,"&sqsupe;"],[0,{v:"&sqcap;",n:65024,o:"&sqcaps;"}],[0,{v:"&sqcup;",n:65024,o:"&sqcups;"}],[0,"&CirclePlus;"],[0,"&CircleMinus;"],[0,"&CircleTimes;"],[0,"&osol;"],[0,"&CircleDot;"],[0,"&circledcirc;"],[0,"&circledast;"],[1,"&circleddash;"],[0,"&boxplus;"],[0,"&boxminus;"],[0,"&boxtimes;"],[0,"&dotsquare;"],[0,"&RightTee;"],[0,"&dashv;"],[0,"&DownTee;"],[0,"&bot;"],[1,"&models;"],[0,"&DoubleRightTee;"],[0,"&Vdash;"],[0,"&Vvdash;"],[0,"&VDash;"],[0,"&nvdash;"],[0,"&nvDash;"],[0,"&nVdash;"],[0,"&nVDash;"],[0,"&prurel;"],[1,"&LeftTriangle;"],[0,"&RightTriangle;"],[0,{v:"&LeftTriangleEqual;",n:8402,o:"&nvltrie;"}],[0,{v:"&RightTriangleEqual;",n:8402,o:"&nvrtrie;"}],[0,"&origof;"],[0,"&imof;"],[0,"&multimap;"],[0,"&hercon;"],[0,"&intcal;"],[0,"&veebar;"],[1,"&barvee;"],[0,"&angrtvb;"],[0,"&lrtri;"],[0,"&bigwedge;"],[0,"&bigvee;"],[0,"&bigcap;"],[0,"&bigcup;"],[0,"&diam;"],[0,"&sdot;"],[0,"&sstarf;"],[0,"&divideontimes;"],[0,"&bowtie;"],[0,"&ltimes;"],[0,"&rtimes;"],[0,"&leftthreetimes;"],[0,"&rightthreetimes;"],[0,"&backsimeq;"],[0,"&curlyvee;"],[0,"&curlywedge;"],[0,"&Sub;"],[0,"&Sup;"],[0,"&Cap;"],[0,"&Cup;"],[0,"&fork;"],[0,"&epar;"],[0,"&lessdot;"],[0,"&gtdot;"],[0,{v:"&Ll;",n:824,o:"&nLl;"}],[0,{v:"&Gg;",n:824,o:"&nGg;"}],[0,{v:"&leg;",n:65024,o:"&lesg;"}],[0,{v:"&gel;",n:65024,o:"&gesl;"}],[2,"&cuepr;"],[0,"&cuesc;"],[0,"&NotPrecedesSlantEqual;"],[0,"&NotSucceedsSlantEqual;"],[0,"&NotSquareSubsetEqual;"],[0,"&NotSquareSupersetEqual;"],[2,"&lnsim;"],[0,"&gnsim;"],[0,"&precnsim;"],[0,"&scnsim;"],[0,"&nltri;"],[0,"&NotRightTriangle;"],[0,"&nltrie;"],[0,"&NotRightTriangleEqual;"],[0,"&vellip;"],[0,"&ctdot;"],[0,"&utdot;"],[0,"&dtdot;"],[0,"&disin;"],[0,"&isinsv;"],[0,"&isins;"],[0,{v:"&isindot;",n:824,o:"&notindot;"}],[0,"&notinvc;"],[0,"&notinvb;"],[1,{v:"&isinE;",n:824,o:"&notinE;"}],[0,"&nisd;"],[0,"&xnis;"],[0,"&nis;"],[0,"&notnivc;"],[0,"&notnivb;"],[6,"&barwed;"],[0,"&Barwed;"],[1,"&lceil;"],[0,"&rceil;"],[0,"&LeftFloor;"],[0,"&rfloor;"],[0,"&drcrop;"],[0,"&dlcrop;"],[0,"&urcrop;"],[0,"&ulcrop;"],[0,"&bnot;"],[1,"&profline;"],[0,"&profsurf;"],[1,"&telrec;"],[0,"&target;"],[5,"&ulcorn;"],[0,"&urcorn;"],[0,"&dlcorn;"],[0,"&drcorn;"],[2,"&frown;"],[0,"&smile;"],[9,"&cylcty;"],[0,"&profalar;"],[7,"&topbot;"],[6,"&ovbar;"],[1,"&solbar;"],[60,"&angzarr;"],[51,"&lmoustache;"],[0,"&rmoustache;"],[2,"&OverBracket;"],[0,"&bbrk;"],[0,"&bbrktbrk;"],[37,"&OverParenthesis;"],[0,"&UnderParenthesis;"],[0,"&OverBrace;"],[0,"&UnderBrace;"],[2,"&trpezium;"],[4,"&elinters;"],[59,"&blank;"],[164,"&circledS;"],[55,"&boxh;"],[1,"&boxv;"],[9,"&boxdr;"],[3,"&boxdl;"],[3,"&boxur;"],[3,"&boxul;"],[3,"&boxvr;"],[7,"&boxvl;"],[7,"&boxhd;"],[7,"&boxhu;"],[7,"&boxvh;"],[19,"&boxH;"],[0,"&boxV;"],[0,"&boxdR;"],[0,"&boxDr;"],[0,"&boxDR;"],[0,"&boxdL;"],[0,"&boxDl;"],[0,"&boxDL;"],[0,"&boxuR;"],[0,"&boxUr;"],[0,"&boxUR;"],[0,"&boxuL;"],[0,"&boxUl;"],[0,"&boxUL;"],[0,"&boxvR;"],[0,"&boxVr;"],[0,"&boxVR;"],[0,"&boxvL;"],[0,"&boxVl;"],[0,"&boxVL;"],[0,"&boxHd;"],[0,"&boxhD;"],[0,"&boxHD;"],[0,"&boxHu;"],[0,"&boxhU;"],[0,"&boxHU;"],[0,"&boxvH;"],[0,"&boxVh;"],[0,"&boxVH;"],[19,"&uhblk;"],[3,"&lhblk;"],[3,"&block;"],[8,"&blk14;"],[0,"&blk12;"],[0,"&blk34;"],[13,"&square;"],[8,"&blacksquare;"],[0,"&EmptyVerySmallSquare;"],[1,"&rect;"],[0,"&marker;"],[2,"&fltns;"],[1,"&bigtriangleup;"],[0,"&blacktriangle;"],[0,"&triangle;"],[2,"&blacktriangleright;"],[0,"&rtri;"],[3,"&bigtriangledown;"],[0,"&blacktriangledown;"],[0,"&dtri;"],[2,"&blacktriangleleft;"],[0,"&ltri;"],[6,"&loz;"],[0,"&cir;"],[32,"&tridot;"],[2,"&bigcirc;"],[8,"&ultri;"],[0,"&urtri;"],[0,"&lltri;"],[0,"&EmptySmallSquare;"],[0,"&FilledSmallSquare;"],[8,"&bigstar;"],[0,"&star;"],[7,"&phone;"],[49,"&female;"],[1,"&male;"],[29,"&spades;"],[2,"&clubs;"],[1,"&hearts;"],[0,"&diamondsuit;"],[3,"&sung;"],[2,"&flat;"],[0,"&natural;"],[0,"&sharp;"],[163,"&check;"],[3,"&cross;"],[8,"&malt;"],[21,"&sext;"],[33,"&VerticalSeparator;"],[25,"&lbbrk;"],[0,"&rbbrk;"],[84,"&bsolhsub;"],[0,"&suphsol;"],[28,"&LeftDoubleBracket;"],[0,"&RightDoubleBracket;"],[0,"&lang;"],[0,"&rang;"],[0,"&Lang;"],[0,"&Rang;"],[0,"&loang;"],[0,"&roang;"],[7,"&longleftarrow;"],[0,"&longrightarrow;"],[0,"&longleftrightarrow;"],[0,"&DoubleLongLeftArrow;"],[0,"&DoubleLongRightArrow;"],[0,"&DoubleLongLeftRightArrow;"],[1,"&longmapsto;"],[2,"&dzigrarr;"],[258,"&nvlArr;"],[0,"&nvrArr;"],[0,"&nvHarr;"],[0,"&Map;"],[6,"&lbarr;"],[0,"&bkarow;"],[0,"&lBarr;"],[0,"&dbkarow;"],[0,"&drbkarow;"],[0,"&DDotrahd;"],[0,"&UpArrowBar;"],[0,"&DownArrowBar;"],[2,"&Rarrtl;"],[2,"&latail;"],[0,"&ratail;"],[0,"&lAtail;"],[0,"&rAtail;"],[0,"&larrfs;"],[0,"&rarrfs;"],[0,"&larrbfs;"],[0,"&rarrbfs;"],[2,"&nwarhk;"],[0,"&nearhk;"],[0,"&hksearow;"],[0,"&hkswarow;"],[0,"&nwnear;"],[0,"&nesear;"],[0,"&seswar;"],[0,"&swnwar;"],[8,{v:"&rarrc;",n:824,o:"&nrarrc;"}],[1,"&cudarrr;"],[0,"&ldca;"],[0,"&rdca;"],[0,"&cudarrl;"],[0,"&larrpl;"],[2,"&curarrm;"],[0,"&cularrp;"],[7,"&rarrpl;"],[2,"&harrcir;"],[0,"&Uarrocir;"],[0,"&lurdshar;"],[0,"&ldrushar;"],[2,"&LeftRightVector;"],[0,"&RightUpDownVector;"],[0,"&DownLeftRightVector;"],[0,"&LeftUpDownVector;"],[0,"&LeftVectorBar;"],[0,"&RightVectorBar;"],[0,"&RightUpVectorBar;"],[0,"&RightDownVectorBar;"],[0,"&DownLeftVectorBar;"],[0,"&DownRightVectorBar;"],[0,"&LeftUpVectorBar;"],[0,"&LeftDownVectorBar;"],[0,"&LeftTeeVector;"],[0,"&RightTeeVector;"],[0,"&RightUpTeeVector;"],[0,"&RightDownTeeVector;"],[0,"&DownLeftTeeVector;"],[0,"&DownRightTeeVector;"],[0,"&LeftUpTeeVector;"],[0,"&LeftDownTeeVector;"],[0,"&lHar;"],[0,"&uHar;"],[0,"&rHar;"],[0,"&dHar;"],[0,"&luruhar;"],[0,"&ldrdhar;"],[0,"&ruluhar;"],[0,"&rdldhar;"],[0,"&lharul;"],[0,"&llhard;"],[0,"&rharul;"],[0,"&lrhard;"],[0,"&udhar;"],[0,"&duhar;"],[0,"&RoundImplies;"],[0,"&erarr;"],[0,"&simrarr;"],[0,"&larrsim;"],[0,"&rarrsim;"],[0,"&rarrap;"],[0,"&ltlarr;"],[1,"&gtrarr;"],[0,"&subrarr;"],[1,"&suplarr;"],[0,"&lfisht;"],[0,"&rfisht;"],[0,"&ufisht;"],[0,"&dfisht;"],[5,"&lopar;"],[0,"&ropar;"],[4,"&lbrke;"],[0,"&rbrke;"],[0,"&lbrkslu;"],[0,"&rbrksld;"],[0,"&lbrksld;"],[0,"&rbrkslu;"],[0,"&langd;"],[0,"&rangd;"],[0,"&lparlt;"],[0,"&rpargt;"],[0,"&gtlPar;"],[0,"&ltrPar;"],[3,"&vzigzag;"],[1,"&vangrt;"],[0,"&angrtvbd;"],[6,"&ange;"],[0,"&range;"],[0,"&dwangle;"],[0,"&uwangle;"],[0,"&angmsdaa;"],[0,"&angmsdab;"],[0,"&angmsdac;"],[0,"&angmsdad;"],[0,"&angmsdae;"],[0,"&angmsdaf;"],[0,"&angmsdag;"],[0,"&angmsdah;"],[0,"&bemptyv;"],[0,"&demptyv;"],[0,"&cemptyv;"],[0,"&raemptyv;"],[0,"&laemptyv;"],[0,"&ohbar;"],[0,"&omid;"],[0,"&opar;"],[1,"&operp;"],[1,"&olcross;"],[0,"&odsold;"],[1,"&olcir;"],[0,"&ofcir;"],[0,"&olt;"],[0,"&ogt;"],[0,"&cirscir;"],[0,"&cirE;"],[0,"&solb;"],[0,"&bsolb;"],[3,"&boxbox;"],[3,"&trisb;"],[0,"&rtriltri;"],[0,{v:"&LeftTriangleBar;",n:824,o:"&NotLeftTriangleBar;"}],[0,{v:"&RightTriangleBar;",n:824,o:"&NotRightTriangleBar;"}],[11,"&iinfin;"],[0,"&infintie;"],[0,"&nvinfin;"],[4,"&eparsl;"],[0,"&smeparsl;"],[0,"&eqvparsl;"],[5,"&blacklozenge;"],[8,"&RuleDelayed;"],[1,"&dsol;"],[9,"&bigodot;"],[0,"&bigoplus;"],[0,"&bigotimes;"],[1,"&biguplus;"],[1,"&bigsqcup;"],[5,"&iiiint;"],[0,"&fpartint;"],[2,"&cirfnint;"],[0,"&awint;"],[0,"&rppolint;"],[0,"&scpolint;"],[0,"&npolint;"],[0,"&pointint;"],[0,"&quatint;"],[0,"&intlarhk;"],[10,"&pluscir;"],[0,"&plusacir;"],[0,"&simplus;"],[0,"&plusdu;"],[0,"&plussim;"],[0,"&plustwo;"],[1,"&mcomma;"],[0,"&minusdu;"],[2,"&loplus;"],[0,"&roplus;"],[0,"&Cross;"],[0,"&timesd;"],[0,"&timesbar;"],[1,"&smashp;"],[0,"&lotimes;"],[0,"&rotimes;"],[0,"&otimesas;"],[0,"&Otimes;"],[0,"&odiv;"],[0,"&triplus;"],[0,"&triminus;"],[0,"&tritime;"],[0,"&intprod;"],[2,"&amalg;"],[0,"&capdot;"],[1,"&ncup;"],[0,"&ncap;"],[0,"&capand;"],[0,"&cupor;"],[0,"&cupcap;"],[0,"&capcup;"],[0,"&cupbrcap;"],[0,"&capbrcup;"],[0,"&cupcup;"],[0,"&capcap;"],[0,"&ccups;"],[0,"&ccaps;"],[2,"&ccupssm;"],[2,"&And;"],[0,"&Or;"],[0,"&andand;"],[0,"&oror;"],[0,"&orslope;"],[0,"&andslope;"],[1,"&andv;"],[0,"&orv;"],[0,"&andd;"],[0,"&ord;"],[1,"&wedbar;"],[6,"&sdote;"],[3,"&simdot;"],[2,{v:"&congdot;",n:824,o:"&ncongdot;"}],[0,"&easter;"],[0,"&apacir;"],[0,{v:"&apE;",n:824,o:"&napE;"}],[0,"&eplus;"],[0,"&pluse;"],[0,"&Esim;"],[0,"&Colone;"],[0,"&Equal;"],[1,"&ddotseq;"],[0,"&equivDD;"],[0,"&ltcir;"],[0,"&gtcir;"],[0,"&ltquest;"],[0,"&gtquest;"],[0,{v:"&leqslant;",n:824,o:"&nleqslant;"}],[0,{v:"&geqslant;",n:824,o:"&ngeqslant;"}],[0,"&lesdot;"],[0,"&gesdot;"],[0,"&lesdoto;"],[0,"&gesdoto;"],[0,"&lesdotor;"],[0,"&gesdotol;"],[0,"&lap;"],[0,"&gap;"],[0,"&lne;"],[0,"&gne;"],[0,"&lnap;"],[0,"&gnap;"],[0,"&lEg;"],[0,"&gEl;"],[0,"&lsime;"],[0,"&gsime;"],[0,"&lsimg;"],[0,"&gsiml;"],[0,"&lgE;"],[0,"&glE;"],[0,"&lesges;"],[0,"&gesles;"],[0,"&els;"],[0,"&egs;"],[0,"&elsdot;"],[0,"&egsdot;"],[0,"&el;"],[0,"&eg;"],[2,"&siml;"],[0,"&simg;"],[0,"&simlE;"],[0,"&simgE;"],[0,{v:"&LessLess;",n:824,o:"&NotNestedLessLess;"}],[0,{v:"&GreaterGreater;",n:824,o:"&NotNestedGreaterGreater;"}],[1,"&glj;"],[0,"&gla;"],[0,"&ltcc;"],[0,"&gtcc;"],[0,"&lescc;"],[0,"&gescc;"],[0,"&smt;"],[0,"&lat;"],[0,{v:"&smte;",n:65024,o:"&smtes;"}],[0,{v:"&late;",n:65024,o:"&lates;"}],[0,"&bumpE;"],[0,{v:"&PrecedesEqual;",n:824,o:"&NotPrecedesEqual;"}],[0,{v:"&sce;",n:824,o:"&NotSucceedsEqual;"}],[2,"&prE;"],[0,"&scE;"],[0,"&precneqq;"],[0,"&scnE;"],[0,"&prap;"],[0,"&scap;"],[0,"&precnapprox;"],[0,"&scnap;"],[0,"&Pr;"],[0,"&Sc;"],[0,"&subdot;"],[0,"&supdot;"],[0,"&subplus;"],[0,"&supplus;"],[0,"&submult;"],[0,"&supmult;"],[0,"&subedot;"],[0,"&supedot;"],[0,{v:"&subE;",n:824,o:"&nsubE;"}],[0,{v:"&supE;",n:824,o:"&nsupE;"}],[0,"&subsim;"],[0,"&supsim;"],[2,{v:"&subnE;",n:65024,o:"&varsubsetneqq;"}],[0,{v:"&supnE;",n:65024,o:"&varsupsetneqq;"}],[2,"&csub;"],[0,"&csup;"],[0,"&csube;"],[0,"&csupe;"],[0,"&subsup;"],[0,"&supsub;"],[0,"&subsub;"],[0,"&supsup;"],[0,"&suphsub;"],[0,"&supdsub;"],[0,"&forkv;"],[0,"&topfork;"],[0,"&mlcp;"],[8,"&Dashv;"],[1,"&Vdashl;"],[0,"&Barv;"],[0,"&vBar;"],[0,"&vBarv;"],[1,"&Vbar;"],[0,"&Not;"],[0,"&bNot;"],[0,"&rnmid;"],[0,"&cirmid;"],[0,"&midcir;"],[0,"&topcir;"],[0,"&nhpar;"],[0,"&parsim;"],[9,{v:"&parsl;",n:8421,o:"&nparsl;"}],[44343,{n:new Map(restoreDiff([[56476,"&Ascr;"],[1,"&Cscr;"],[0,"&Dscr;"],[2,"&Gscr;"],[2,"&Jscr;"],[0,"&Kscr;"],[2,"&Nscr;"],[0,"&Oscr;"],[0,"&Pscr;"],[0,"&Qscr;"],[1,"&Sscr;"],[0,"&Tscr;"],[0,"&Uscr;"],[0,"&Vscr;"],[0,"&Wscr;"],[0,"&Xscr;"],[0,"&Yscr;"],[0,"&Zscr;"],[0,"&ascr;"],[0,"&bscr;"],[0,"&cscr;"],[0,"&dscr;"],[1,"&fscr;"],[1,"&hscr;"],[0,"&iscr;"],[0,"&jscr;"],[0,"&kscr;"],[0,"&lscr;"],[0,"&mscr;"],[0,"&nscr;"],[1,"&pscr;"],[0,"&qscr;"],[0,"&rscr;"],[0,"&sscr;"],[0,"&tscr;"],[0,"&uscr;"],[0,"&vscr;"],[0,"&wscr;"],[0,"&xscr;"],[0,"&yscr;"],[0,"&zscr;"],[52,"&Afr;"],[0,"&Bfr;"],[1,"&Dfr;"],[0,"&Efr;"],[0,"&Ffr;"],[0,"&Gfr;"],[2,"&Jfr;"],[0,"&Kfr;"],[0,"&Lfr;"],[0,"&Mfr;"],[0,"&Nfr;"],[0,"&Ofr;"],[0,"&Pfr;"],[0,"&Qfr;"],[1,"&Sfr;"],[0,"&Tfr;"],[0,"&Ufr;"],[0,"&Vfr;"],[0,"&Wfr;"],[0,"&Xfr;"],[0,"&Yfr;"],[1,"&afr;"],[0,"&bfr;"],[0,"&cfr;"],[0,"&dfr;"],[0,"&efr;"],[0,"&ffr;"],[0,"&gfr;"],[0,"&hfr;"],[0,"&ifr;"],[0,"&jfr;"],[0,"&kfr;"],[0,"&lfr;"],[0,"&mfr;"],[0,"&nfr;"],[0,"&ofr;"],[0,"&pfr;"],[0,"&qfr;"],[0,"&rfr;"],[0,"&sfr;"],[0,"&tfr;"],[0,"&ufr;"],[0,"&vfr;"],[0,"&wfr;"],[0,"&xfr;"],[0,"&yfr;"],[0,"&zfr;"],[0,"&Aopf;"],[0,"&Bopf;"],[1,"&Dopf;"],[0,"&Eopf;"],[0,"&Fopf;"],[0,"&Gopf;"],[1,"&Iopf;"],[0,"&Jopf;"],[0,"&Kopf;"],[0,"&Lopf;"],[0,"&Mopf;"],[1,"&Oopf;"],[3,"&Sopf;"],[0,"&Topf;"],[0,"&Uopf;"],[0,"&Vopf;"],[0,"&Wopf;"],[0,"&Xopf;"],[0,"&Yopf;"],[1,"&aopf;"],[0,"&bopf;"],[0,"&copf;"],[0,"&dopf;"],[0,"&eopf;"],[0,"&fopf;"],[0,"&gopf;"],[0,"&hopf;"],[0,"&iopf;"],[0,"&jopf;"],[0,"&kopf;"],[0,"&lopf;"],[0,"&mopf;"],[0,"&nopf;"],[0,"&oopf;"],[0,"&popf;"],[0,"&qopf;"],[0,"&ropf;"],[0,"&sopf;"],[0,"&topf;"],[0,"&uopf;"],[0,"&vopf;"],[0,"&wopf;"],[0,"&xopf;"],[0,"&yopf;"],[0,"&zopf;"]]))}],[8906,"&fflig;"],[0,"&filig;"],[0,"&fllig;"],[0,"&ffilig;"],[0,"&ffllig;"]]))}});function encodeXML(str){let ret="",lastIdx=0,match;for(;(match=xmlReplacer.exec(str))!==null;){let i=match.index,char=str.charCodeAt(i),next2=xmlCodeMap.get(char);next2!==void 0?(ret+=str.substring(lastIdx,i)+next2,lastIdx=i+1):(ret+=`${str.substring(lastIdx,i)}&#x${getCodePoint(str,i).toString(16)};`,lastIdx=xmlReplacer.lastIndex+=+((char&64512)===55296))}return ret+str.substr(lastIdx)}function getEscaper(regex,map2){return __name(function(data2){let match,lastIdx=0,result="";for(;match=regex.exec(data2);)lastIdx!==match.index&&(result+=data2.substring(lastIdx,match.index)),result+=map2.get(match[0].charCodeAt(0)),lastIdx=match.index+1;return result+data2.substring(lastIdx)},"escape")}var xmlReplacer,xmlCodeMap,getCodePoint,escapeUTF8,escapeAttribute,escapeText,init_escape=__esm({"../../node_modules/.pnpm/entities@4.5.0/node_modules/entities/lib/esm/escape.js"(){xmlReplacer=/["&'<>$\x80-\uFFFF]/g,xmlCodeMap=new Map([[34,"&quot;"],[38,"&amp;"],[39,"&apos;"],[60,"&lt;"],[62,"&gt;"]]),getCodePoint=String.prototype.codePointAt!=null?(str,index2)=>str.codePointAt(index2):(c2,index2)=>(c2.charCodeAt(index2)&64512)===55296?(c2.charCodeAt(index2)-55296)*1024+c2.charCodeAt(index2+1)-56320+65536:c2.charCodeAt(index2);__name(encodeXML,"encodeXML");__name(getEscaper,"getEscaper");escapeUTF8=getEscaper(/[&<>'"]/g,xmlCodeMap),escapeAttribute=getEscaper(/["&\u00A0]/g,new Map([[34,"&quot;"],[38,"&amp;"],[160,"&nbsp;"]])),escapeText=getEscaper(/[&<>\u00A0]/g,new Map([[38,"&amp;"],[60,"&lt;"],[62,"&gt;"],[160,"&nbsp;"]]))}});var init_encode=__esm({"../../node_modules/.pnpm/entities@4.5.0/node_modules/entities/lib/esm/encode.js"(){init_encode_html();init_escape()}});var EntityLevel,EncodingMode,init_esm4=__esm({"../../node_modules/.pnpm/entities@4.5.0/node_modules/entities/lib/esm/index.js"(){init_decode();init_encode();init_escape();init_escape();init_encode();init_decode();(function(EntityLevel2){EntityLevel2[EntityLevel2.XML=0]="XML",EntityLevel2[EntityLevel2.HTML=1]="HTML"})(EntityLevel||(EntityLevel={}));(function(EncodingMode2){EncodingMode2[EncodingMode2.UTF8=0]="UTF8",EncodingMode2[EncodingMode2.ASCII=1]="ASCII",EncodingMode2[EncodingMode2.Extensive=2]="Extensive",EncodingMode2[EncodingMode2.Attribute=3]="Attribute",EncodingMode2[EncodingMode2.Text=4]="Text"})(EncodingMode||(EncodingMode={}))}});var elementNames,attributeNames,init_foreignNames=__esm({"../../node_modules/.pnpm/dom-serializer@2.0.0/node_modules/dom-serializer/lib/esm/foreignNames.js"(){elementNames=new Map(["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","textPath"].map(val2=>[val2.toLowerCase(),val2])),attributeNames=new Map(["definitionURL","attributeName","attributeType","baseFrequency","baseProfile","calcMode","clipPathUnits","diffuseConstant","edgeMode","filterUnits","glyphRef","gradientTransform","gradientUnits","kernelMatrix","kernelUnitLength","keyPoints","keySplines","keyTimes","lengthAdjust","limitingConeAngle","markerHeight","markerUnits","markerWidth","maskContentUnits","maskUnits","numOctaves","pathLength","patternContentUnits","patternTransform","patternUnits","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","refX","refY","repeatCount","repeatDur","requiredExtensions","requiredFeatures","specularConstant","specularExponent","spreadMethod","startOffset","stdDeviation","stitchTiles","surfaceScale","systemLanguage","tableValues","targetX","targetY","textLength","viewBox","viewTarget","xChannelSelector","yChannelSelector","zoomAndPan"].map(val2=>[val2.toLowerCase(),val2]))}});function replaceQuotes(value){return value.replace(/"/g,"&quot;")}function formatAttributes(attributes2,opts){var _a4;if(!attributes2)return;let encode=((_a4=opts.encodeEntities)!==null&&_a4!==void 0?_a4:opts.decodeEntities)===!1?replaceQuotes:opts.xmlMode||opts.encodeEntities!=="utf8"?encodeXML:escapeAttribute;return Object.keys(attributes2).map(key=>{var _a5,_b;let value=(_a5=attributes2[key])!==null&&_a5!==void 0?_a5:"";return opts.xmlMode==="foreign"&&(key=(_b=attributeNames.get(key))!==null&&_b!==void 0?_b:key),!opts.emptyAttrs&&!opts.xmlMode&&value===""?key:`${key}="${encode(value)}"`}).join(" ")}function render2(node,options={}){let nodes="length"in node?node:[node],output="";for(let i=0;i<nodes.length;i++)output+=renderNode(nodes[i],options);return output}function renderNode(node,options){switch(node.type){case Root:return render2(node.children,options);case Doctype:case Directive:return renderDirective(node);case Comment:return renderComment(node);case CDATA:return renderCdata(node);case Script:case Style:case Tag:return renderTag(node,options);case Text:return renderText(node,options)}}function renderTag(elem,opts){var _a4;opts.xmlMode==="foreign"&&(elem.name=(_a4=elementNames.get(elem.name))!==null&&_a4!==void 0?_a4:elem.name,elem.parent&&foreignModeIntegrationPoints.has(elem.parent.name)&&(opts={...opts,xmlMode:!1})),!opts.xmlMode&&foreignElements.has(elem.name)&&(opts={...opts,xmlMode:"foreign"});let tag=`<${elem.name}`,attribs=formatAttributes(elem.attribs,opts);return attribs&&(tag+=` ${attribs}`),elem.children.length===0&&(opts.xmlMode?opts.selfClosingTags!==!1:opts.selfClosingTags&&singleTag.has(elem.name))?(opts.xmlMode||(tag+=" "),tag+="/>"):(tag+=">",elem.children.length>0&&(tag+=render2(elem.children,opts)),(opts.xmlMode||!singleTag.has(elem.name))&&(tag+=`</${elem.name}>`)),tag}function renderDirective(elem){return`<${elem.data}>`}function renderText(elem,opts){var _a4;let data2=elem.data||"";return((_a4=opts.encodeEntities)!==null&&_a4!==void 0?_a4:opts.decodeEntities)!==!1&&!(!opts.xmlMode&&elem.parent&&unencodedElements.has(elem.parent.name))&&(data2=opts.xmlMode||opts.encodeEntities!=="utf8"?encodeXML(data2):escapeText(data2)),data2}function renderCdata(elem){return`<![CDATA[${elem.children[0].data}]]>`}function renderComment(elem){return`<!--${elem.data}-->`}var unencodedElements,singleTag,esm_default,foreignModeIntegrationPoints,foreignElements,init_esm5=__esm({"../../node_modules/.pnpm/dom-serializer@2.0.0/node_modules/dom-serializer/lib/esm/index.js"(){init_esm2();init_esm4();init_foreignNames();unencodedElements=new Set(["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"]);__name(replaceQuotes,"replaceQuotes");__name(formatAttributes,"formatAttributes");singleTag=new Set(["area","base","basefont","br","col","command","embed","frame","hr","img","input","isindex","keygen","link","meta","param","source","track","wbr"]);__name(render2,"render");esm_default=render2;__name(renderNode,"renderNode");foreignModeIntegrationPoints=new Set(["mi","mo","mn","ms","mtext","annotation-xml","foreignObject","desc","title"]),foreignElements=new Set(["svg","math"]);__name(renderTag,"renderTag");__name(renderDirective,"renderDirective");__name(renderText,"renderText");__name(renderCdata,"renderCdata");__name(renderComment,"renderComment")}});function getOuterHTML(node,options){return esm_default(node,options)}function getInnerHTML(node,options){return hasChildren(node)?node.children.map(node2=>getOuterHTML(node2,options)).join(""):""}function getText(node){return Array.isArray(node)?node.map(getText).join(""):isTag2(node)?node.name==="br"?`
601
601
  `:getText(node.children):isCDATA(node)?getText(node.children):isText(node)?node.data:""}function textContent(node){return Array.isArray(node)?node.map(textContent).join(""):hasChildren(node)&&!isComment(node)?textContent(node.children):isText(node)?node.data:""}function innerText(node){return Array.isArray(node)?node.map(innerText).join(""):hasChildren(node)&&(node.type===ElementType.Tag||isCDATA(node))?innerText(node.children):isText(node)?node.data:""}var init_stringify=__esm({"../../node_modules/.pnpm/domutils@3.2.2/node_modules/domutils/lib/esm/stringify.js"(){init_esm3();init_esm5();init_esm2();__name(getOuterHTML,"getOuterHTML");__name(getInnerHTML,"getInnerHTML");__name(getText,"getText");__name(textContent,"textContent");__name(innerText,"innerText")}});function getChildren(elem){return hasChildren(elem)?elem.children:[]}function getParent(elem){return elem.parent||null}function getSiblings(elem){let parent2=getParent(elem);if(parent2!=null)return getChildren(parent2);let siblings2=[elem],{prev:prev2,next:next2}=elem;for(;prev2!=null;)siblings2.unshift(prev2),{prev:prev2}=prev2;for(;next2!=null;)siblings2.push(next2),{next:next2}=next2;return siblings2}function getAttributeValue(elem,name){var _a4;return(_a4=elem.attribs)===null||_a4===void 0?void 0:_a4[name]}function hasAttrib(elem,name){return elem.attribs!=null&&Object.prototype.hasOwnProperty.call(elem.attribs,name)&&elem.attribs[name]!=null}function getName(elem){return elem.name}function nextElementSibling(elem){let{next:next2}=elem;for(;next2!==null&&!isTag2(next2);)({next:next2}=next2);return next2}function prevElementSibling(elem){let{prev:prev2}=elem;for(;prev2!==null&&!isTag2(prev2);)({prev:prev2}=prev2);return prev2}var init_traversal=__esm({"../../node_modules/.pnpm/domutils@3.2.2/node_modules/domutils/lib/esm/traversal.js"(){init_esm3();__name(getChildren,"getChildren");__name(getParent,"getParent");__name(getSiblings,"getSiblings");__name(getAttributeValue,"getAttributeValue");__name(hasAttrib,"hasAttrib");__name(getName,"getName");__name(nextElementSibling,"nextElementSibling");__name(prevElementSibling,"prevElementSibling")}});function removeElement(elem){if(elem.prev&&(elem.prev.next=elem.next),elem.next&&(elem.next.prev=elem.prev),elem.parent){let childs=elem.parent.children,childsIndex=childs.lastIndexOf(elem);childsIndex>=0&&childs.splice(childsIndex,1)}elem.next=null,elem.prev=null,elem.parent=null}function replaceElement(elem,replacement){let prev2=replacement.prev=elem.prev;prev2&&(prev2.next=replacement);let next2=replacement.next=elem.next;next2&&(next2.prev=replacement);let parent2=replacement.parent=elem.parent;if(parent2){let childs=parent2.children;childs[childs.lastIndexOf(elem)]=replacement,elem.parent=null}}function appendChild(parent2,child){if(removeElement(child),child.next=null,child.parent=parent2,parent2.children.push(child)>1){let sibling=parent2.children[parent2.children.length-2];sibling.next=child,child.prev=sibling}else child.prev=null}function append(elem,next2){removeElement(next2);let{parent:parent2}=elem,currNext=elem.next;if(next2.next=currNext,next2.prev=elem,elem.next=next2,next2.parent=parent2,currNext){if(currNext.prev=next2,parent2){let childs=parent2.children;childs.splice(childs.lastIndexOf(currNext),0,next2)}}else parent2&&parent2.children.push(next2)}function prependChild(parent2,child){if(removeElement(child),child.parent=parent2,child.prev=null,parent2.children.unshift(child)!==1){let sibling=parent2.children[1];sibling.prev=child,child.next=sibling}else child.next=null}function prepend(elem,prev2){removeElement(prev2);let{parent:parent2}=elem;if(parent2){let childs=parent2.children;childs.splice(childs.indexOf(elem),0,prev2)}elem.prev&&(elem.prev.next=prev2),prev2.parent=parent2,prev2.prev=elem.prev,prev2.next=elem,elem.prev=prev2}var init_manipulation=__esm({"../../node_modules/.pnpm/domutils@3.2.2/node_modules/domutils/lib/esm/manipulation.js"(){__name(removeElement,"removeElement");__name(replaceElement,"replaceElement");__name(appendChild,"appendChild");__name(append,"append");__name(prependChild,"prependChild");__name(prepend,"prepend")}});function filter(test,node,recurse=!0,limit=1/0){return find(test,Array.isArray(node)?node:[node],recurse,limit)}function find(test,nodes,recurse,limit){let result=[],nodeStack=[Array.isArray(nodes)?nodes:[nodes]],indexStack=[0];for(;;){if(indexStack[0]>=nodeStack[0].length){if(indexStack.length===1)return result;nodeStack.shift(),indexStack.shift();continue}let elem=nodeStack[0][indexStack[0]++];if(test(elem)&&(result.push(elem),--limit<=0))return result;recurse&&hasChildren(elem)&&elem.children.length>0&&(indexStack.unshift(0),nodeStack.unshift(elem.children))}}function findOneChild(test,nodes){return nodes.find(test)}function findOne(test,nodes,recurse=!0){let searchedNodes=Array.isArray(nodes)?nodes:[nodes];for(let i=0;i<searchedNodes.length;i++){let node=searchedNodes[i];if(isTag2(node)&&test(node))return node;if(recurse&&hasChildren(node)&&node.children.length>0){let found=findOne(test,node.children,!0);if(found)return found}}return null}function existsOne(test,nodes){return(Array.isArray(nodes)?nodes:[nodes]).some(node=>isTag2(node)&&test(node)||hasChildren(node)&&existsOne(test,node.children))}function findAll(test,nodes){let result=[],nodeStack=[Array.isArray(nodes)?nodes:[nodes]],indexStack=[0];for(;;){if(indexStack[0]>=nodeStack[0].length){if(nodeStack.length===1)return result;nodeStack.shift(),indexStack.shift();continue}let elem=nodeStack[0][indexStack[0]++];isTag2(elem)&&test(elem)&&result.push(elem),hasChildren(elem)&&elem.children.length>0&&(indexStack.unshift(0),nodeStack.unshift(elem.children))}}var init_querying=__esm({"../../node_modules/.pnpm/domutils@3.2.2/node_modules/domutils/lib/esm/querying.js"(){init_esm3();__name(filter,"filter");__name(find,"find");__name(findOneChild,"findOneChild");__name(findOne,"findOne");__name(existsOne,"existsOne");__name(findAll,"findAll")}});function getAttribCheck(attrib,value){return typeof value=="function"?elem=>isTag2(elem)&&value(elem.attribs[attrib]):elem=>isTag2(elem)&&elem.attribs[attrib]===value}function combineFuncs(a,b){return elem=>a(elem)||b(elem)}function compileTest(options){let funcs=Object.keys(options).map(key=>{let value=options[key];return Object.prototype.hasOwnProperty.call(Checks,key)?Checks[key](value):getAttribCheck(key,value)});return funcs.length===0?null:funcs.reduce(combineFuncs)}function testElement(options,node){let test=compileTest(options);return test?test(node):!0}function getElements(options,nodes,recurse,limit=1/0){let test=compileTest(options);return test?filter(test,nodes,recurse,limit):[]}function getElementById(id,nodes,recurse=!0){return Array.isArray(nodes)||(nodes=[nodes]),findOne(getAttribCheck("id",id),nodes,recurse)}function getElementsByTagName(tagName,nodes,recurse=!0,limit=1/0){return filter(Checks.tag_name(tagName),nodes,recurse,limit)}function getElementsByClassName(className,nodes,recurse=!0,limit=1/0){return filter(getAttribCheck("class",className),nodes,recurse,limit)}function getElementsByTagType(type,nodes,recurse=!0,limit=1/0){return filter(Checks.tag_type(type),nodes,recurse,limit)}var Checks,init_legacy=__esm({"../../node_modules/.pnpm/domutils@3.2.2/node_modules/domutils/lib/esm/legacy.js"(){init_esm3();init_querying();Checks={tag_name(name){return typeof name=="function"?elem=>isTag2(elem)&&name(elem.name):name==="*"?isTag2:elem=>isTag2(elem)&&elem.name===name},tag_type(type){return typeof type=="function"?elem=>type(elem.type):elem=>elem.type===type},tag_contains(data2){return typeof data2=="function"?elem=>isText(elem)&&data2(elem.data):elem=>isText(elem)&&elem.data===data2}};__name(getAttribCheck,"getAttribCheck");__name(combineFuncs,"combineFuncs");__name(compileTest,"compileTest");__name(testElement,"testElement");__name(getElements,"getElements");__name(getElementById,"getElementById");__name(getElementsByTagName,"getElementsByTagName");__name(getElementsByClassName,"getElementsByClassName");__name(getElementsByTagType,"getElementsByTagType")}});function removeSubsets(nodes){let idx=nodes.length;for(;--idx>=0;){let node=nodes[idx];if(idx>0&&nodes.lastIndexOf(node,idx-1)>=0){nodes.splice(idx,1);continue}for(let ancestor=node.parent;ancestor;ancestor=ancestor.parent)if(nodes.includes(ancestor)){nodes.splice(idx,1);break}}return nodes}function compareDocumentPosition(nodeA,nodeB){let aParents=[],bParents=[];if(nodeA===nodeB)return 0;let current=hasChildren(nodeA)?nodeA:nodeA.parent;for(;current;)aParents.unshift(current),current=current.parent;for(current=hasChildren(nodeB)?nodeB:nodeB.parent;current;)bParents.unshift(current),current=current.parent;let maxIdx=Math.min(aParents.length,bParents.length),idx=0;for(;idx<maxIdx&&aParents[idx]===bParents[idx];)idx++;if(idx===0)return DocumentPosition.DISCONNECTED;let sharedParent=aParents[idx-1],siblings2=sharedParent.children,aSibling=aParents[idx],bSibling=bParents[idx];return siblings2.indexOf(aSibling)>siblings2.indexOf(bSibling)?sharedParent===nodeB?DocumentPosition.FOLLOWING|DocumentPosition.CONTAINED_BY:DocumentPosition.FOLLOWING:sharedParent===nodeA?DocumentPosition.PRECEDING|DocumentPosition.CONTAINS:DocumentPosition.PRECEDING}function uniqueSort(nodes){return nodes=nodes.filter((node,i,arr)=>!arr.includes(node,i+1)),nodes.sort((a,b)=>{let relative3=compareDocumentPosition(a,b);return relative3&DocumentPosition.PRECEDING?-1:relative3&DocumentPosition.FOLLOWING?1:0}),nodes}var DocumentPosition,init_helpers=__esm({"../../node_modules/.pnpm/domutils@3.2.2/node_modules/domutils/lib/esm/helpers.js"(){init_esm3();__name(removeSubsets,"removeSubsets");(function(DocumentPosition2){DocumentPosition2[DocumentPosition2.DISCONNECTED=1]="DISCONNECTED",DocumentPosition2[DocumentPosition2.PRECEDING=2]="PRECEDING",DocumentPosition2[DocumentPosition2.FOLLOWING=4]="FOLLOWING",DocumentPosition2[DocumentPosition2.CONTAINS=8]="CONTAINS",DocumentPosition2[DocumentPosition2.CONTAINED_BY=16]="CONTAINED_BY"})(DocumentPosition||(DocumentPosition={}));__name(compareDocumentPosition,"compareDocumentPosition");__name(uniqueSort,"uniqueSort")}});function getFeed(doc){let feedRoot=getOneElement(isValidFeed,doc);return feedRoot?feedRoot.name==="feed"?getAtomFeed(feedRoot):getRssFeed(feedRoot):null}function getAtomFeed(feedRoot){var _a4;let childs=feedRoot.children,feed={type:"atom",items:getElementsByTagName("entry",childs).map(item=>{var _a5;let{children:children2}=item,entry={media:getMediaElements(children2)};addConditionally(entry,"id","id",children2),addConditionally(entry,"title","title",children2);let href2=(_a5=getOneElement("link",children2))===null||_a5===void 0?void 0:_a5.attribs.href;href2&&(entry.link=href2);let description=fetch2("summary",children2)||fetch2("content",children2);description&&(entry.description=description);let pubDate=fetch2("updated",children2);return pubDate&&(entry.pubDate=new Date(pubDate)),entry})};addConditionally(feed,"id","id",childs),addConditionally(feed,"title","title",childs);let href=(_a4=getOneElement("link",childs))===null||_a4===void 0?void 0:_a4.attribs.href;href&&(feed.link=href),addConditionally(feed,"description","subtitle",childs);let updated=fetch2("updated",childs);return updated&&(feed.updated=new Date(updated)),addConditionally(feed,"author","email",childs,!0),feed}function getRssFeed(feedRoot){var _a4,_b;let childs=(_b=(_a4=getOneElement("channel",feedRoot.children))===null||_a4===void 0?void 0:_a4.children)!==null&&_b!==void 0?_b:[],feed={type:feedRoot.name.substr(0,3),id:"",items:getElementsByTagName("item",feedRoot.children).map(item=>{let{children:children2}=item,entry={media:getMediaElements(children2)};addConditionally(entry,"id","guid",children2),addConditionally(entry,"title","title",children2),addConditionally(entry,"link","link",children2),addConditionally(entry,"description","description",children2);let pubDate=fetch2("pubDate",children2)||fetch2("dc:date",children2);return pubDate&&(entry.pubDate=new Date(pubDate)),entry})};addConditionally(feed,"title","title",childs),addConditionally(feed,"link","link",childs),addConditionally(feed,"description","description",childs);let updated=fetch2("lastBuildDate",childs);return updated&&(feed.updated=new Date(updated)),addConditionally(feed,"author","managingEditor",childs,!0),feed}function getMediaElements(where){return getElementsByTagName("media:content",where).map(elem=>{let{attribs}=elem,media={medium:attribs.medium,isDefault:!!attribs.isDefault};for(let attrib of MEDIA_KEYS_STRING)attribs[attrib]&&(media[attrib]=attribs[attrib]);for(let attrib of MEDIA_KEYS_INT)attribs[attrib]&&(media[attrib]=parseInt(attribs[attrib],10));return attribs.expression&&(media.expression=attribs.expression),media})}function getOneElement(tagName,node){return getElementsByTagName(tagName,node,!0,1)[0]}function fetch2(tagName,where,recurse=!1){return textContent(getElementsByTagName(tagName,where,recurse,1)).trim()}function addConditionally(obj,prop2,tagName,where,recurse=!1){let val2=fetch2(tagName,where,recurse);val2&&(obj[prop2]=val2)}function isValidFeed(value){return value==="rss"||value==="feed"||value==="rdf:RDF"}var MEDIA_KEYS_STRING,MEDIA_KEYS_INT,init_feeds=__esm({"../../node_modules/.pnpm/domutils@3.2.2/node_modules/domutils/lib/esm/feeds.js"(){init_stringify();init_legacy();__name(getFeed,"getFeed");__name(getAtomFeed,"getAtomFeed");__name(getRssFeed,"getRssFeed");MEDIA_KEYS_STRING=["url","type","lang"],MEDIA_KEYS_INT=["fileSize","bitrate","framerate","samplingrate","channels","duration","height","width"];__name(getMediaElements,"getMediaElements");__name(getOneElement,"getOneElement");__name(fetch2,"fetch");__name(addConditionally,"addConditionally");__name(isValidFeed,"isValidFeed")}});var esm_exports2={};__export(esm_exports2,{DocumentPosition:()=>DocumentPosition,append:()=>append,appendChild:()=>appendChild,compareDocumentPosition:()=>compareDocumentPosition,existsOne:()=>existsOne,filter:()=>filter,find:()=>find,findAll:()=>findAll,findOne:()=>findOne,findOneChild:()=>findOneChild,getAttributeValue:()=>getAttributeValue,getChildren:()=>getChildren,getElementById:()=>getElementById,getElements:()=>getElements,getElementsByClassName:()=>getElementsByClassName,getElementsByTagName:()=>getElementsByTagName,getElementsByTagType:()=>getElementsByTagType,getFeed:()=>getFeed,getInnerHTML:()=>getInnerHTML,getName:()=>getName,getOuterHTML:()=>getOuterHTML,getParent:()=>getParent,getSiblings:()=>getSiblings,getText:()=>getText,hasAttrib:()=>hasAttrib,hasChildren:()=>hasChildren,innerText:()=>innerText,isCDATA:()=>isCDATA,isComment:()=>isComment,isDocument:()=>isDocument,isTag:()=>isTag2,isText:()=>isText,nextElementSibling:()=>nextElementSibling,prepend:()=>prepend,prependChild:()=>prependChild,prevElementSibling:()=>prevElementSibling,removeElement:()=>removeElement,removeSubsets:()=>removeSubsets,replaceElement:()=>replaceElement,testElement:()=>testElement,textContent:()=>textContent,uniqueSort:()=>uniqueSort});var init_esm6=__esm({"../../node_modules/.pnpm/domutils@3.2.2/node_modules/domutils/lib/esm/index.js"(){init_stringify();init_traversal();init_manipulation();init_querying();init_legacy();init_helpers();init_feeds();init_esm3()}});var static_exports={};__export(static_exports,{contains:()=>contains,extract:()=>extract,html:()=>html,merge:()=>merge,parseHTML:()=>parseHTML,root:()=>root,text:()=>text,xml:()=>xml});function render3(that,dom,options){return that?that(dom??that._root.children,null,void 0,options).toString():""}function isOptions(dom,options){return!options&&typeof dom=="object"&&dom!=null&&!("length"in dom)&&!("type"in dom)}function html(dom,options){let toRender=isOptions(dom)?(options=dom,void 0):dom,opts={...this===null||this===void 0?void 0:this._options,...flattenOptions(options)};return render3(this,toRender,opts)}function xml(dom){let options={...this._options,xmlMode:!0};return render3(this,dom,options)}function text(elements){let elems=elements??(this?this.root():[]),ret="";for(let i=0;i<elems.length;i++)ret+=textContent(elems[i]);return ret}function parseHTML(data2,context,keepScripts=typeof context=="boolean"?context:!1){if(!data2||typeof data2!="string")return null;typeof context=="boolean"&&(keepScripts=context);let parsed=this.load(data2,this._options,!1);return keepScripts||parsed("script").remove(),[...parsed.root()[0].children]}function root(){return this(this._root)}function contains(container,contained){if(contained===container)return!1;let next2=contained;for(;next2&&next2!==next2.parent;)if(next2=next2.parent,next2===container)return!0;return!1}function extract(map2){return this.root().extract(map2)}function merge(arr1,arr2){if(!isArrayLike(arr1)||!isArrayLike(arr2))return;let newLength=arr1.length,len=+arr2.length;for(let i=0;i<len;i++)arr1[newLength++]=arr2[i];return arr1.length=newLength,arr1}function isArrayLike(item){if(Array.isArray(item))return!0;if(typeof item!="object"||item===null||!("length"in item)||typeof item.length!="number"||item.length<0)return!1;for(let i=0;i<item.length;i++)if(!(i in item))return!1;return!0}var init_static=__esm({"../../node_modules/.pnpm/cheerio@1.2.0/node_modules/cheerio/dist/esm/static.js"(){init_esm6();init_options();__name(render3,"render");__name(isOptions,"isOptions");__name(html,"html");__name(xml,"xml");__name(text,"text");__name(parseHTML,"parseHTML");__name(root,"root");__name(contains,"contains");__name(extract,"extract");__name(merge,"merge");__name(isArrayLike,"isArrayLike")}});function isCheerio(maybeCheerio){return maybeCheerio.cheerio!=null}function camelCase(str){return str.replace(/[._-](\w|$)/g,(_,x)=>x.toUpperCase())}function cssCase(str){return str.replace(/[A-Z]/g,"-$&").toLowerCase()}function domEach(array,fn){let len=array.length;for(let i=0;i<len;i++)fn(array[i],i);return array}function isHtml(str){if(typeof str!="string")return!1;let tagStart=str.indexOf("<");if(tagStart===-1||tagStart>str.length-3)return!1;let tagChar=str.charCodeAt(tagStart+1);return(tagChar>=CharacterCode.LowerA&&tagChar<=CharacterCode.LowerZ||tagChar>=CharacterCode.UpperA&&tagChar<=CharacterCode.UpperZ||tagChar===CharacterCode.Exclamation)&&str.includes(">",tagStart+2)}var CharacterCode,init_utils2=__esm({"../../node_modules/.pnpm/cheerio@1.2.0/node_modules/cheerio/dist/esm/utils.js"(){__name(isCheerio,"isCheerio");__name(camelCase,"camelCase");__name(cssCase,"cssCase");__name(domEach,"domEach");(function(CharacterCode2){CharacterCode2[CharacterCode2.LowerA=97]="LowerA",CharacterCode2[CharacterCode2.LowerZ=122]="LowerZ",CharacterCode2[CharacterCode2.UpperA=65]="UpperA",CharacterCode2[CharacterCode2.UpperZ=90]="UpperZ",CharacterCode2[CharacterCode2.Exclamation=33]="Exclamation"})(CharacterCode||(CharacterCode={}));__name(isHtml,"isHtml")}});function replaceCodePoint2(codePoint){var _a4;return codePoint>=55296&&codePoint<=57343||codePoint>1114111?65533:(_a4=decodeMap2.get(codePoint))!==null&&_a4!==void 0?_a4:codePoint}var _a2,decodeMap2,fromCodePoint2,init_decode_codepoint2=__esm({"../../node_modules/.pnpm/entities@7.0.1/node_modules/entities/dist/esm/decode-codepoint.js"(){decodeMap2=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]),fromCodePoint2=(_a2=String.fromCodePoint)!==null&&_a2!==void 0?_a2:(codePoint=>{let output="";return codePoint>65535&&(codePoint-=65536,output+=String.fromCharCode(codePoint>>>10&1023|55296),codePoint=56320|codePoint&1023),output+=String.fromCharCode(codePoint),output});__name(replaceCodePoint2,"replaceCodePoint")}});function decodeBase64(input){let binary=typeof atob=="function"?atob(input):typeof Buffer.from=="function"?Buffer.from(input,"base64").toString("binary"):new Buffer(input,"base64").toString("binary"),evenLength=binary.length&-2,out=new Uint16Array(evenLength/2);for(let index2=0,outIndex=0;index2<evenLength;index2+=2){let lo=binary.charCodeAt(index2),hi=binary.charCodeAt(index2+1);out[outIndex++]=lo|hi<<8}return out}var init_decode_shared=__esm({"../../node_modules/.pnpm/entities@7.0.1/node_modules/entities/dist/esm/internal/decode-shared.js"(){__name(decodeBase64,"decodeBase64")}});var htmlDecodeTree,init_decode_data_html2=__esm({"../../node_modules/.pnpm/entities@7.0.1/node_modules/entities/dist/esm/generated/decode-data-html.js"(){init_decode_shared();htmlDecodeTree=decodeBase64("QR08ALkAAgH6AYsDNQR2BO0EPgXZBQEGLAbdBxMISQrvCmQLfQurDKQNLw4fD4YPpA+6D/IPAAAAAAAAAAAAAAAAKhBMEY8TmxUWF2EYLBkxGuAa3RsJHDscWR8YIC8jSCSIJcMl6ie3Ku8rEC0CLjoupS7kLgAIRU1hYmNmZ2xtbm9wcnN0dVQAWgBeAGUAaQBzAHcAfgCBAIQAhwCSAJoAoACsALMAbABpAGcAO4DGAMZAUAA7gCYAJkBjAHUAdABlADuAwQDBQHIiZXZlAAJhAAFpeW0AcgByAGMAO4DCAMJAEGRyAADgNdgE3XIAYQB2AGUAO4DAAMBA8CFoYZFj4SFjcgBhZAAAoFMqAAFncIsAjgBvAG4ABGFmAADgNdg43fAlbHlGdW5jdGlvbgCgYSBpAG4AZwA7gMUAxUAAAWNzpACoAHIAAOA12Jzc6SFnbgCgVCJpAGwAZABlADuAwwDDQG0AbAA7gMQAxEAABGFjZWZvcnN1xQDYANoA7QDxAPYA+QD8AAABY3LJAM8AayNzbGFzaAAAoBYidgHTANUAAKDnKmUAZAAAoAYjeQARZIABY3J0AOAA5QDrAGEidXNlAACgNSLuI291bGxpcwCgLCFhAJJjcgAA4DXYBd1wAGYAAOA12Dnd5SF2ZdhiYwDyAOoAbSJwZXEAAKBOIgAHSE9hY2RlZmhpbG9yc3UXARoBHwE6AVIBVQFiAWQBZgGCAakB6QHtAfIBYwB5ACdkUABZADuAqQCpQIABY3B5ACUBKAE1AfUhdGUGYWmg0iJ0KGFsRGlmZmVyZW50aWFsRAAAoEUhbCJleXMAAKAtIQACYWVpb0EBRAFKAU0B8iFvbgxhZABpAGwAO4DHAMdAcgBjAAhhbiJpbnQAAKAwIm8AdAAKYQABZG5ZAV0BaSJsbGEAuGB0I2VyRG90ALdg8gA5AWkAp2NyImNsZQAAAkRNUFRwAXQBeQF9AW8AdAAAoJkiaSJudXMAAKCWIuwhdXMAoJUiaSJtZXMAAKCXIm8AAAFjc4cBlAFrKndpc2VDb250b3VySW50ZWdyYWwAAKAyImUjQ3VybHkAAAFEUZwBpAFvJXVibGVRdW90ZQAAoB0gdSJvdGUAAKAZIAACbG5wdbABtgHNAdgBbwBuAGWgNyIAoHQqgAFnaXQAvAHBAcUB8iJ1ZW50AKBhIm4AdAAAoC8i7yV1ckludGVncmFsAKAuIgABZnLRAdMBAKACIe8iZHVjdACgECJuLnRlckNsb2Nrd2lzZUNvbnRvdXJJbnRlZ3JhbAAAoDMi7yFzcwCgLypjAHIAAOA12J7ccABDoNMiYQBwAACgTSKABURKU1phY2VmaW9zAAsCEgIVAhgCGwIsAjQCOQI9AnMCfwNvoEUh9CJyYWhkAKARKWMAeQACZGMAeQAFZGMAeQAPZIABZ3JzACECJQIoAuchZXIAoCEgcgAAoKEhaAB2AACg5CoAAWF5MAIzAvIhb24OYRRkbAB0oAciYQCUY3IAAOA12AfdAAFhZkECawIAAWNtRQJnAvIjaXRpY2FsAAJBREdUUAJUAl8CYwJjInV0ZQC0YG8AdAFZAloC2WJiJGxlQWN1dGUA3WJyImF2ZQBgYGkibGRlANxi7yFuZACgxCJmJWVyZW50aWFsRAAAoEYhcAR9AgAAAAAAAIECjgIAABoDZgAA4DXYO91EoagAhQKJAm8AdAAAoNwgcSJ1YWwAAKBQIuIhbGUAA0NETFJVVpkCqAK1Au8C/wIRA28AbgB0AG8AdQByAEkAbgB0AGUAZwByAGEA7ADEAW8AdAKvAgAAAACwAqhgbiNBcnJvdwAAoNMhAAFlb7kC0AJmAHQAgAFBUlQAwQLGAs0CciJyb3cAAKDQIekkZ2h0QXJyb3cAoNQhZQDlACsCbgBnAAABTFLWAugC5SFmdAABQVLcAuECciJyb3cAAKD4J+kkZ2h0QXJyb3cAoPon6SRnaHRBcnJvdwCg+SdpImdodAAAAUFU9gL7AnIicm93AACg0iFlAGUAAKCoInAAQQIGAwAAAAALA3Iicm93AACg0SFvJHduQXJyb3cAAKDVIWUlcnRpY2FsQmFyAACgJSJuAAADQUJMUlRhJAM2AzoDWgNxA3oDciJyb3cAAKGTIUJVLAMwA2EAcgAAoBMpcCNBcnJvdwAAoPUhciJldmUAEWPlIWZ00gJDAwAASwMAAFIDaSVnaHRWZWN0b3IAAKBQKWUkZVZlY3RvcgAAoF4p5SJjdG9yQqC9IWEAcgAAoFYpaSJnaHQA1AFiAwAAaQNlJGVWZWN0b3IAAKBfKeUiY3RvckKgwSFhAHIAAKBXKWUAZQBBoKQiciJyb3cAAKCnIXIAcgBvAPcAtAIAAWN0gwOHA3IAAOA12J/c8iFvaxBhAAhOVGFjZGZnbG1vcHFzdHV4owOlA6kDsAO/A8IDxgPNA9ID8gP9AwEEFAQeBCAEJQRHAEphSAA7gNAA0EBjAHUAdABlADuAyQDJQIABYWl5ALYDuQO+A/Ihb24aYXIAYwA7gMoAykAtZG8AdAAWYXIAAOA12AjdcgBhAHYAZQA7gMgAyEDlIm1lbnQAoAgiAAFhcNYD2QNjAHIAEmF0AHkAUwLhAwAAAADpA20lYWxsU3F1YXJlAACg+yVlJ3J5U21hbGxTcXVhcmUAAKCrJQABZ3D2A/kDbwBuABhhZgAA4DXYPN3zImlsb26VY3UAAAFhaQYEDgRsAFSgdSppImxkZQAAoEIi7CNpYnJpdW0AoMwhAAFjaRgEGwRyAACgMCFtAACgcyphAJdjbQBsADuAywDLQAABaXApBC0E8yF0cwCgAyLvJG5lbnRpYWxFAKBHIYACY2Zpb3MAPQQ/BEMEXQRyBHkAJGRyAADgNdgJ3WwibGVkAFMCTAQAAAAAVARtJWFsbFNxdWFyZQAAoPwlZSdyeVNtYWxsU3F1YXJlAACgqiVwA2UEAABpBAAAAABtBGYAAOA12D3dwSFsbACgACLyI2llcnRyZgCgMSFjAPIAcQQABkpUYWJjZGZnb3JzdIgEiwSOBJMElwSkBKcEqwStBLIE5QTqBGMAeQADZDuAPgA+QO0hbWFkoJMD3GNyImV2ZQAeYYABZWl5AJ0EoASjBOQhaWwiYXIAYwAcYRNkbwB0ACBhcgAA4DXYCt0AoNkicABmAADgNdg+3eUiYXRlcgADRUZHTFNUvwTIBM8E1QTZBOAEcSJ1YWwATKBlIuUhc3MAoNsidSRsbEVxdWFsAACgZyJyI2VhdGVyAACgoirlIXNzAKB3IuwkYW50RXF1YWwAoH4qaSJsZGUAAKBzImMAcgAA4DXYotwAoGsiAARBYWNmaW9zdfkE/QQFBQgFCwUTBSIFKwVSIkRjeQAqZAABY3QBBQQFZQBrAMdiXmDpIXJjJGFyAACgDCFsJWJlcnRTcGFjZQAAoAsh8AEYBQAAGwVmAACgDSHpJXpvbnRhbExpbmUAoAAlAAFjdCYFKAXyABIF8iFvayZhbQBwAEQBMQU5BW8AdwBuAEgAdQBtAPAAAAFxInVhbAAAoE8iAAdFSk9hY2RmZ21ub3N0dVMFVgVZBVwFYwVtBXAFcwV6BZAFtgXFBckFzQVjAHkAFWTsIWlnMmFjAHkAAWRjAHUAdABlADuAzQDNQAABaXlnBWwFcgBjADuAzgDOQBhkbwB0ADBhcgAAoBEhcgBhAHYAZQA7gMwAzEAAoREhYXB/BYsFAAFjZ4MFhQVyACphaSNuYXJ5SQAAoEghbABpAGUA8wD6AvQBlQUAAKUFZaAsIgABZ3KaBZ4F8iFhbACgKyLzI2VjdGlvbgCgwiJpI3NpYmxlAAABQ1SsBbEFbyJtbWEAAKBjIGkibWVzAACgYiCAAWdwdAC8Bb8FwwVvAG4ALmFmAADgNdhA3WEAmWNjAHIAAKAQIWkibGRlAChh6wHSBQAA1QVjAHkABmRsADuAzwDPQIACY2Zvc3UA4QXpBe0F8gX9BQABaXnlBegFcgBjADRhGWRyAADgNdgN3XAAZgAA4DXYQd3jAfcFAAD7BXIAAOA12KXc8iFjeQhk6yFjeQRkgANISmFjZm9zAAwGDwYSBhUGHQYhBiYGYwB5ACVkYwB5AAxk8CFwYZpjAAFleRkGHAbkIWlsNmEaZHIAAOA12A7dcABmAADgNdhC3WMAcgAA4DXYptyABUpUYWNlZmxtb3N0AD0GQAZDBl4GawZkB2gHcAd0B80H2gdjAHkACWQ7gDwAPECAAmNtbnByAEwGTwZSBlUGWwb1IXRlOWHiIWRhm2NnAACg6ifsI2FjZXRyZgCgEiFyAACgniGAAWFleQBkBmcGagbyIW9uPWHkIWlsO2EbZAABZnNvBjQHdAAABUFDREZSVFVWYXKABp4GpAbGBssG3AYDByEHwQIqBwABbnKEBowGZyVsZUJyYWNrZXQAAKDoJ/Ihb3cAoZAhQlKTBpcGYQByAACg5CHpJGdodEFycm93AKDGIWUjaWxpbmcAAKAII28A9QGqBgAAsgZiJWxlQnJhY2tldAAAoOYnbgDUAbcGAAC+BmUkZVZlY3RvcgAAoGEp5SJjdG9yQqDDIWEAcgAAoFkpbCJvb3IAAKAKI2kiZ2h0AAABQVbSBtcGciJyb3cAAKCUIeUiY3RvcgCgTikAAWVy4AbwBmUAAKGjIkFW5gbrBnIicm93AACgpCHlImN0b3IAoFopaSNhbmdsZQBCorIi+wYAAAAA/wZhAHIAAKDPKXEidWFsAACgtCJwAIABRFRWAAoHEQcYB+8kd25WZWN0b3IAoFEpZSRlVmVjdG9yAACgYCnlImN0b3JCoL8hYQByAACgWCnlImN0b3JCoLwhYQByAACgUilpAGcAaAB0AGEAcgByAG8A9wDMAnMAAANFRkdMU1Q/B0cHTgdUB1gHXwfxJXVhbEdyZWF0ZXIAoNoidSRsbEVxdWFsAACgZiJyI2VhdGVyAACgdiLlIXNzAKChKuwkYW50RXF1YWwAoH0qaSJsZGUAAKByInIAAOA12A/dZaDYIuYjdGFycm93AKDaIWkiZG90AD9hgAFucHcAege1B7kHZwAAAkxSbHKCB5QHmwerB+UhZnQAAUFSiAeNB3Iicm93AACg9SfpJGdodEFycm93AKD3J+kkZ2h0QXJyb3cAoPYn5SFmdAABYXLcAqEHaQBnAGgAdABhAHIAcgBvAPcA5wJpAGcAaAB0AGEAcgByAG8A9wDuAmYAAOA12EPdZQByAAABTFK/B8YHZSRmdEFycm93AACgmSHpJGdodEFycm93AKCYIYABY2h0ANMH1QfXB/IAWgYAoLAh8iFva0FhAKBqIgAEYWNlZmlvc3XpB+wH7gf/BwMICQgOCBEIcAAAoAUpeQAcZAABZGzyB/kHaSR1bVNwYWNlAACgXyBsI2ludHJmAACgMyFyAADgNdgQ3e4jdXNQbHVzAKATInAAZgAA4DXYRN1jAPIA/gecY4AESmFjZWZvc3R1ACEIJAgoCDUIgQiFCDsKQApHCmMAeQAKZGMidXRlAENhgAFhZXkALggxCDQI8iFvbkdh5CFpbEVhHWSAAWdzdwA7CGEIfQjhInRpdmWAAU1UVgBECEwIWQhlJWRpdW1TcGFjZQAAoAsgaABpAAABY25SCFMIawBTAHAAYQBjAOUASwhlAHIAeQBUAGgAaQDuAFQI9CFlZAABR0xnCHUIcgBlAGEAdABlAHIARwByAGUAYQB0AGUA8gDrBGUAcwBzAEwAZQBzAPMA2wdMImluZQAKYHIAAOA12BHdAAJCbnB0jAiRCJkInAhyImVhawAAoGAgwiZyZWFraW5nU3BhY2WgYGYAAKAVIUOq7CqzCMIIzQgAAOcIGwkAAAAAAAAtCQAAbwkAAIcJAACdCcAJGQoAADQKAAFvdbYIvAjuI2dydWVudACgYiJwIkNhcAAAoG0ibyh1YmxlVmVydGljYWxCYXIAAKAmIoABbHF4ANII1wjhCOUibWVudACgCSL1IWFsVKBgImkibGRlAADgQiI4A2kic3RzAACgBCJyI2VhdGVyAACjbyJFRkdMU1T1CPoIAgkJCQ0JFQlxInVhbAAAoHEidSRsbEVxdWFsAADgZyI4A3IjZWF0ZXIAAOBrIjgD5SFzcwCgeSLsJGFudEVxdWFsAOB+KjgDaSJsZGUAAKB1IvUhbXBEASAJJwnvI3duSHVtcADgTiI4A3EidWFsAADgTyI4A2UAAAFmczEJRgn0JFRyaWFuZ2xlQqLqIj0JAAAAAEIJYQByAADgzyk4A3EidWFsAACg7CJzAICibiJFR0xTVABRCVYJXAlhCWkJcSJ1YWwAAKBwInIjZWF0ZXIAAKB4IuUhc3MA4GoiOAPsJGFudEVxdWFsAOB9KjgDaSJsZGUAAKB0IuUic3RlZAABR0x1CX8J8iZlYXRlckdyZWF0ZXIA4KIqOAPlI3NzTGVzcwDgoSo4A/IjZWNlZGVzAKGAIkVTjwmVCXEidWFsAADgryo4A+wkYW50RXF1YWwAoOAiAAFlaaAJqQl2JmVyc2VFbGVtZW50AACgDCLnJWh0VHJpYW5nbGVCousitgkAAAAAuwlhAHIAAODQKTgDcSJ1YWwAAKDtIgABcXXDCeAJdSNhcmVTdQAAAWJwywnVCfMhZXRF4I8iOANxInVhbAAAoOIi5SJyc2V0ReCQIjgDcSJ1YWwAAKDjIoABYmNwAOYJ8AkNCvMhZXRF4IIi0iBxInVhbAAAoIgi4yJlZWRzgKGBIkVTVAD6CQAKBwpxInVhbAAA4LAqOAPsJGFudEVxdWFsAKDhImkibGRlAADgfyI4A+UicnNldEXggyLSIHEidWFsAACgiSJpImxkZQCAoUEiRUZUACIKJwouCnEidWFsAACgRCJ1JGxsRXF1YWwAAKBHImkibGRlAACgSSJlJXJ0aWNhbEJhcgAAoCQiYwByAADgNdip3GkAbABkAGUAO4DRANFAnWMAB0VhY2RmZ21vcHJzdHV2XgphCmgKcgp2CnoKgQqRCpYKqwqtCrsKyArNCuwhaWdSYWMAdQB0AGUAO4DTANNAAAFpeWwKcQpyAGMAO4DUANRAHmRiImxhYwBQYXIAAOA12BLdcgBhAHYAZQA7gNIA0kCAAWFlaQCHCooKjQpjAHIATGFnAGEAqWNjInJvbgCfY3AAZgAA4DXYRt3lI25DdXJseQABRFGeCqYKbyV1YmxlUXVvdGUAAKAcIHUib3RlAACgGCAAoFQqAAFjbLEKtQpyAADgNdiq3GEAcwBoADuA2ADYQGkAbAHACsUKZABlADuA1QDVQGUAcwAAoDcqbQBsADuA1gDWQGUAcgAAAUJQ0wrmCgABYXLXCtoKcgAAoD4gYQBjAAABZWvgCuIKAKDeI2UAdAAAoLQjYSVyZW50aGVzaXMAAKDcI4AEYWNmaGlsb3JzAP0KAwsFCwkLCwsMCxELIwtaC3IjdGlhbEQAAKACInkAH2RyAADgNdgT3WkApmOgY/Ujc01pbnVzsWAAAWlwFQsgC24AYwBhAHIAZQBwAGwAYQBuAOUACgVmAACgGSGAobsqZWlvACoLRQtJC+MiZWRlc4CheiJFU1QANAs5C0ALcSJ1YWwAAKCvKuwkYW50RXF1YWwAoHwiaSJsZGUAAKB+Im0AZQAAoDMgAAFkcE0LUQv1IWN0AKAPIm8jcnRpb24AYaA3ImwAAKAdIgABY2leC2ILcgAA4DXYq9yoYwACVWZvc2oLbwtzC3cLTwBUADuAIgAiQHIAAOA12BTdcABmAACgGiFjAHIAAOA12KzcAAZCRWFjZWZoaW9yc3WPC5MLlwupC7YL2AvbC90LhQyTDJoMowzhIXJyAKAQKUcAO4CuAK5AgAFjbnIAnQugC6ML9SF0ZVRhZwAAoOsncgB0oKAhbAAAoBYpgAFhZXkArwuyC7UL8iFvblhh5CFpbFZhIGR2oBwhZSJyc2UAAAFFVb8LzwsAAWxxwwvIC+UibWVudACgCyL1JGlsaWJyaXVtAKDLIXAmRXF1aWxpYnJpdW0AAKBvKXIAAKAcIW8AoWPnIWh0AARBQ0RGVFVWYewLCgwQDDIMNwxeDHwM9gIAAW5y8Av4C2clbGVCcmFja2V0AACg6SfyIW93AKGSIUJM/wsDDGEAcgAAoOUhZSRmdEFycm93AACgxCFlI2lsaW5nAACgCSNvAPUBFgwAAB4MYiVsZUJyYWNrZXQAAKDnJ24A1AEjDAAAKgxlJGVWZWN0b3IAAKBdKeUiY3RvckKgwiFhAHIAAKBVKWwib29yAACgCyMAAWVyOwxLDGUAAKGiIkFWQQxGDHIicm93AACgpiHlImN0b3IAoFspaSNhbmdsZQBCorMiVgwAAAAAWgxhAHIAAKDQKXEidWFsAACgtSJwAIABRFRWAGUMbAxzDO8kd25WZWN0b3IAoE8pZSRlVmVjdG9yAACgXCnlImN0b3JCoL4hYQByAACgVCnlImN0b3JCoMAhYQByAACgUykAAXB1iQyMDGYAAKAdIe4kZEltcGxpZXMAoHAp6SRnaHRhcnJvdwCg2yEAAWNongyhDHIAAKAbIQCgsSHsJGVEZWxheWVkAKD0KYAGSE9hY2ZoaW1vcXN0dQC/DMgMzAzQDOIM5gwKDQ0NFA0ZDU8NVA1YDQABQ2PDDMYMyCFjeSlkeQAoZEYiVGN5ACxkYyJ1dGUAWmEAorwqYWVpedgM2wzeDOEM8iFvbmBh5CFpbF5hcgBjAFxhIWRyAADgNdgW3e8hcnQAAkRMUlXvDPYM/QwEDW8kd25BcnJvdwAAoJMhZSRmdEFycm93AACgkCHpJGdodEFycm93AKCSIXAjQXJyb3cAAKCRIechbWGjY+EkbGxDaXJjbGUAoBgicABmAADgNdhK3XICHw0AAAAAIg10AACgGiLhIXJlgKGhJUlTVQAqDTINSg3uJXRlcnNlY3Rpb24AoJMidQAAAWJwNw1ADfMhZXRFoI8icSJ1YWwAAKCRIuUicnNldEWgkCJxInVhbAAAoJIibiJpb24AAKCUImMAcgAA4DXYrtxhAHIAAKDGIgACYmNtcF8Nag2ODZANc6DQImUAdABFoNAicSJ1YWwAAKCGIgABY2huDYkNZSJlZHMAgKF7IkVTVAB4DX0NhA1xInVhbAAAoLAq7CRhbnRFcXVhbACgfSJpImxkZQAAoH8iVABoAGEA9ADHCwCgESIAodEiZXOVDZ8NciJzZXQARaCDInEidWFsAACghyJlAHQAAKDRIoAFSFJTYWNmaGlvcnMAtQ27Db8NyA3ODdsN3w3+DRgOHQ4jDk8AUgBOADuA3gDeQMEhREUAoCIhAAFIY8MNxg1jAHkAC2R5ACZkAAFidcwNzQ0JYKRjgAFhZXkA1A3XDdoN8iFvbmRh5CFpbGJhImRyAADgNdgX3QABZWnjDe4N8gHoDQAA7Q3lImZvcmUAoDQiYQCYYwABY27yDfkNayNTcGFjZQAA4F8gCiDTInBhY2UAoAkg7CFkZYChPCJFRlQABw4MDhMOcSJ1YWwAAKBDInUkbGxFcXVhbAAAoEUiaSJsZGUAAKBIInAAZgAA4DXYS93pI3BsZURvdACg2yAAAWN0Jw4rDnIAAOA12K/c8iFva2Zh4QpFDlYOYA5qDgAAbg5yDgAAAAAAAAAAAAB5DnwOqA6zDgAADg8RDxYPGg8AAWNySA5ODnUAdABlADuA2gDaQHIAb6CfIeMhaXIAoEkpcgDjAVsOAABdDnkADmR2AGUAbGEAAWl5Yw5oDnIAYwA7gNsA20AjZGIibGFjAHBhcgAA4DXYGN1yAGEAdgBlADuA2QDZQOEhY3JqYQABZGl/Dp8OZQByAAABQlCFDpcOAAFhcokOiw5yAF9gYQBjAAABZWuRDpMOAKDfI2UAdAAAoLUjYSVyZW50aGVzaXMAAKDdI28AbgBQoMMi7CF1cwCgjiIAAWdwqw6uDm8AbgByYWYAAOA12EzdAARBREVUYWRwc78O0g7ZDuEOBQPqDvMOBw9yInJvdwDCoZEhyA4AAMwOYQByAACgEilvJHduQXJyb3cAAKDFIW8kd25BcnJvdwAAoJUhcSV1aWxpYnJpdW0AAKBuKWUAZQBBoKUiciJyb3cAAKClIW8AdwBuAGEAcgByAG8A9wAQA2UAcgAAAUxS+Q4AD2UkZnRBcnJvdwAAoJYh6SRnaHRBcnJvdwCglyFpAGyg0gNvAG4ApWPpIW5nbmFjAHIAAOA12LDcaSJsZGUAaGFtAGwAO4DcANxAgAREYmNkZWZvc3YALQ8xDzUPNw89D3IPdg97D4AP4SFzaACgqyJhAHIAAKDrKnkAEmThIXNobKCpIgCg5ioAAWVyQQ9DDwCgwSKAAWJ0eQBJD00Paw9hAHIAAKAWIGmgFiDjIWFsAAJCTFNUWA9cD18PZg9hAHIAAKAjIukhbmV8YGUkcGFyYXRvcgAAoFgnaSJsZGUAAKBAItQkaGluU3BhY2UAoAogcgAA4DXYGd1wAGYAAOA12E3dYwByAADgNdix3GQiYXNoAACgqiKAAmNlZm9zAI4PkQ+VD5kPng/pIXJjdGHkIWdlAKDAInIAAOA12BrdcABmAADgNdhO3WMAcgAA4DXYstwAAmZpb3OqD64Prw+0D3IAAOA12BvdnmNwAGYAAOA12E/dYwByAADgNdiz3IAEQUlVYWNmb3N1AMgPyw/OD9EP2A/gD+QP6Q/uD2MAeQAvZGMAeQAHZGMAeQAuZGMAdQB0AGUAO4DdAN1AAAFpedwP3w9yAGMAdmErZHIAAOA12BzdcABmAADgNdhQ3WMAcgAA4DXYtNxtAGwAeGEABEhhY2RlZm9z/g8BEAUQDRAQEB0QIBAkEGMAeQAWZGMidXRlAHlhAAFheQkQDBDyIW9ufWEXZG8AdAB7YfIBFRAAABwQbwBXAGkAZAB0AOgAVAhhAJZjcgAAoCghcABmAACgJCFjAHIAAOA12LXc4QtCEEkQTRAAAGcQbRByEAAAAAAAAAAAeRCKEJcQ8hD9EAAAGxEhETIROREAAD4RYwB1AHQAZQA7gOEA4UByImV2ZQADYYCiPiJFZGl1eQBWEFkQWxBgEGUQAOA+IjMDAKA/InIAYwA7gOIA4kB0AGUAO4C0ALRAMGRsAGkAZwA7gOYA5kByoGEgAOA12B7dcgBhAHYAZQA7gOAA4EAAAWVwfBCGEAABZnCAEIQQ8yF5bQCgNSHoAIMQaABhALFjAAFhcI0QWwAAAWNskRCTEHIAAWFnAACgPypkApwQAAAAALEQAKInImFkc3ajEKcQqRCuEG4AZAAAoFUqAKBcKmwib3BlAACgWCoAoFoqAKMgImVsbXJzersQvRDAEN0Q5RDtEACgpCllAACgICJzAGQAYaAhImEEzhDQENIQ1BDWENgQ2hDcEACgqCkAoKkpAKCqKQCgqykAoKwpAKCtKQCgrikAoK8pdAB2oB8iYgBkoL4iAKCdKQABcHTpEOwQaAAAoCIixWDhIXJyAKB8IwABZ3D1EPgQbwBuAAVhZgAA4DXYUt0Ao0giRWFlaW9wBxEJEQ0RDxESERQRAKBwKuMhaXIAoG8qAKBKImQAAKBLInMAJ2DyIW94ZaBIIvEADhFpAG4AZwA7gOUA5UCAAWN0eQAmESoRKxFyAADgNdi23CpgbQBwAGWgSCLxAPgBaQBsAGQAZQA7gOMA40BtAGwAO4DkAORAAAFjaUERRxFvAG4AaQBuAPQA6AFuAHQAAKARKgAITmFiY2RlZmlrbG5vcHJzdWQRaBGXEZ8RpxGrEdIR1hErEjASexKKEn0RThNbE3oTbwB0AACg7SoAAWNybBGJEWsAAAJjZXBzdBF4EX0RghHvIW5nAKBMInAjc2lsb24A9mNyImltZQAAoDUgaQBtAGWgPSJxAACgzSJ2AY0RkRFlAGUAAKC9ImUAZABnoAUjZQAAoAUjcgBrAHSgtSPiIXJrAKC2IwABb3mjEaYRbgDnAHcRMWTxIXVvAKAeIIACY21wcnQAtBG5Eb4RwRHFEeEhdXPloDUi5ABwInR5dgAAoLApcwDpAH0RbgBvAPUA6gCAAWFodwDLEcwRzhGyYwCgNiHlIWVuAKBsInIAAOA12B/dZwCAA2Nvc3R1dncA4xHyEQUSEhIhEiYSKRKAAWFpdQDpEesR7xHwAKMFcgBjAACg7yVwAACgwyKAAWRwdAD4EfwRABJvAHQAAKAAKuwhdXMAoAEqaSJtZXMAAKACKnECCxIAAAAADxLjIXVwAKAGKmEAcgAAoAUm8iNpYW5nbGUAAWR1GhIeEu8hd24AoL0lcAAAoLMlcCJsdXMAAKAEKmUA5QBCD+UAkg9hInJvdwAAoA0pgAFha28ANhJoEncSAAFjbjoSZRJrAIABbHN0AEESRxJNEm8jemVuZ2UAAKDrKXEAdQBhAHIA5QBcBPIjaWFuZ2xlgKG0JWRscgBYElwSYBLvIXduAKC+JeUhZnQAoMIlaSJnaHQAAKC4JWsAAKAjJLEBbRIAAHUSsgFxEgAAcxIAoJIlAKCRJTQAAKCTJWMAawAAoIglAAFlb38ShxJx4D0A5SD1IWl2AOBhIuUgdAAAoBAjAAJwdHd4kRKVEpsSnxJmAADgNdhT3XSgpSJvAG0AAKClIvQhaWUAoMgiAAZESFVWYmRobXB0dXayEsES0RLgEvcS+xIKExoTHxMjEygTNxMAAkxSbHK5ErsSvRK/EgCgVyUAoFQlAKBWJQCgUyUAolAlRFVkdckSyxLNEs8SAKBmJQCgaSUAoGQlAKBnJQACTFJsctgS2hLcEt4SAKBdJQCgWiUAoFwlAKBZJQCjUSVITFJobHLrEu0S7xLxEvMS9RIAoGwlAKBjJQCgYCUAoGslAKBiJQCgXyVvAHgAAKDJKQACTFJscgITBBMGEwgTAKBVJQCgUiUAoBAlAKAMJQCiACVEVWR1EhMUExYTGBMAoGUlAKBoJQCgLCUAoDQlaSJudXMAAKCfIuwhdXMAoJ4iaSJtZXMAAKCgIgACTFJsci8TMRMzEzUTAKBbJQCgWCUAoBglAKAUJQCjAiVITFJobHJCE0QTRhNIE0oTTBMAoGolAKBhJQCgXiUAoDwlAKAkJQCgHCUAAWV2UhNVE3YA5QD5AGIAYQByADuApgCmQAACY2Vpb2ITZhNqE24TcgAA4DXYt9xtAGkAAKBPIG0A5aA9IogRbAAAoVwAYmh0E3YTAKDFKfMhdWIAoMgnbAF+E4QTbABloCIgdAAAoCIgcAAAoU4iRWWJE4sTAKCuKvGgTyI8BeEMqRMAAN8TABQDFB8UAAAjFDQUAAAAAIUUAAAAAI0UAAAAANcU4xT3FPsUAACIFQAAlhWAAWNwcgCuE7ET1RP1IXRlB2GAoikiYWJjZHMAuxO/E8QTzhPSE24AZAAAoEQqciJjdXAAAKBJKgABYXXIE8sTcAAAoEsqcAAAoEcqbwB0AACgQCoA4CkiAP4AAWVv2RPcE3QAAKBBIO4ABAUAAmFlaXXlE+8T9RP4E/AB6hMAAO0TcwAAoE0qbwBuAA1hZABpAGwAO4DnAOdAcgBjAAlhcABzAHOgTCptAACgUCpvAHQAC2GAAWRtbgAIFA0UEhRpAGwAO4C4ALhAcCJ0eXYAAKCyKXQAAIGiADtlGBQZFKJAcgBkAG8A9ABiAXIAAOA12CDdgAFjZWkAKBQqFDIUeQBHZGMAawBtoBMn4SFyawCgEyfHY3IAAKPLJUVjZWZtcz8UQRRHFHcUfBSAFACgwykAocYCZWxGFEkUcQAAoFciZQBhAlAUAAAAAGAUciJyb3cAAAFsclYUWhTlIWZ0AKC6IWkiZ2h0AACguyGAAlJTYWNkAGgUaRRrFG8UcxSuYACgyCRzAHQAAKCbIukhcmMAoJoi4SFzaACgnSJuImludAAAoBAqaQBkAACg7yrjIWlyAKDCKfUhYnN1oGMmaQB0AACgYybsApMUmhS2FAAAwxRvAG4AZaA6APGgVCKrAG0CnxQAAAAAoxRhAHSgLABAYAChASJmbKcUqRTuABMNZQAAAW14rhSyFOUhbnQAoAEiZQDzANIB5wG6FAAAwBRkoEUibwB0AACgbSpuAPQAzAGAAWZyeQDIFMsUzhQA4DXYVN1vAOQA1wEAgakAO3MeAdMUcgAAoBchAAFhb9oU3hRyAHIAAKC1IXMAcwAAoBcnAAFjdeYU6hRyAADgNdi43AABYnDuFPIUZaDPKgCg0SploNAqAKDSKuQhb3QAoO8igANkZWxwcnZ3AAYVEBUbFSEVRBVlFYQV4SFycgABbHIMFQ4VAKA4KQCgNSlwAhYVAAAAABkVcgAAoN4iYwAAoN8i4SFycnCgtiEAoD0pgKIqImJjZG9zACsVMBU6FT4VQRVyImNhcAAAoEgqAAFhdTQVNxVwAACgRipwAACgSipvAHQAAKCNInIAAKBFKgDgKiIA/gACYWxydksVURVuFXMVcgByAG2gtyEAoDwpeQCAAWV2dwBYFWUVaRVxAHACXxUAAAAAYxVyAGUA4wAXFXUA4wAZFWUAZQAAoM4iZSJkZ2UAAKDPImUAbgA7gKQApEBlI2Fycm93AAABbHJ7FX8V5SFmdACgtiFpImdodAAAoLchZQDkAG0VAAFjaYsVkRVvAG4AaQBuAPQAkwFuAHQAAKAxImwiY3R5AACgLSOACUFIYWJjZGVmaGlqbG9yc3R1d3oAuBW7Fb8V1RXgFegV+RUKFhUWHxZUFlcWZRbFFtsW7xb7FgUXChdyAPIAtAJhAHIAAKBlKQACZ2xyc8YVyhXOFdAV5yFlcgCgICDlIXRoAKA4IfIA9QxoAHagECAAoKMiawHZFd4VYSJyb3cAAKAPKWEA4wBfAgABYXnkFecV8iFvbg9hNGQAoUYhYW/tFfQVAAFnciEC8RVyAACgyiF0InNlcQAAoHcqgAFnbG0A/xUCFgUWO4CwALBAdABhALRjcCJ0eXYAAKCxKQABaXIOFhIW8yFodACgfykA4DXYId1hAHIAAAFschsWHRYAoMMhAKDCIYACYWVnc3YAKBauAjYWOhY+Fm0AAKHEIm9zLhY0Fm4AZABzoMQi9SFpdACgZiZhIm1tYQDdY2kAbgAAoPIiAKH3AGlvQxZRFmQAZQAAgfcAO29KFksW90BuI3RpbWVzAACgxyJuAPgAUBZjAHkAUmRjAG8CXhYAAAAAYhZyAG4AAKAeI28AcAAAoA0jgAJscHR1dwBuFnEWdRaSFp4W7CFhciRgZgAA4DXYVd0AotkCZW1wc30WhBaJFo0WcQBkoFAibwB0AACgUSJpIm51cwAAoDgi7CF1cwCgFCLxInVhcmUAoKEiYgBsAGUAYgBhAHIAdwBlAGQAZwDlANcAbgCAAWFkaAClFqoWtBZyAHIAbwD3APUMbwB3AG4AYQByAHIAbwB3APMA8xVhI3Jwb29uAAABbHK8FsAWZQBmAPQAHBZpAGcAaAD0AB4WYgHJFs8WawBhAHIAbwD3AJILbwLUFgAAAADYFnIAbgAAoB8jbwBwAACgDCOAAWNvdADhFukW7BYAAXJ55RboFgDgNdi53FVkbAAAoPYp8iFvaxFhAAFkcvMW9xZvAHQAAKDxImkA5qC/JVsSAAFhaP8WAhdyAPIANQNhAPIA1wvhIm5nbGUAoKYpAAFjaQ4XEBd5AF9k5yJyYXJyAKD/JwAJRGFjZGVmZ2xtbm9wcXJzdHV4MRc4F0YXWxcyBF4XaRd5F40XrBe0F78X2RcVGCEYLRg1GEAYAAFEbzUXgRZvAPQA+BUAAWNzPBdCF3UAdABlADuA6QDpQPQhZXIAoG4qAAJhaW95TRdQF1YXWhfyIW9uG2FyAGOgViI7gOoA6kDsIW9uAKBVIk1kbwB0ABdhAAFEcmIXZhdvAHQAAKBSIgDgNdgi3XKhmipuF3QXYQB2AGUAO4DoAOhAZKCWKm8AdAAAoJgqgKGZKmlscwCAF4UXhxfuInRlcnMAoOcjAKATIWSglSpvAHQAAKCXKoABYXBzAJMXlheiF2MAcgATYXQAeQBzogUinxcAAAAAoRdlAHQAAKAFInAAMaADIDMBqRerFwCgBCAAoAUgAAFnc7AXsRdLYXAAAKACIAABZ3C4F7sXbwBuABlhZgAA4DXYVt2AAWFscwDFF8sXzxdyAHOg1SJsAACg4yl1AHMAAKBxKmkAAKG1A2x21RfYF28AbgC1Y/VjAAJjc3V24BfoF/0XEBgAAWlv5BdWF3IAYwAAoFYiaQLuFwAAAADwF+0ADQThIW50AAFnbPUX+Rd0AHIAAKCWKuUhc3MAoJUqgAFhZWkAAxgGGAoYbABzAD1gcwB0AACgXyJ2AESgYSJEAACgeCrwImFyc2wAoOUpAAFEYRkYHRhvAHQAAKBTInIAcgAAoHEpgAFjZGkAJxgqGO0XcgAAoC8hbwD0AIwCAAFhaDEYMhi3YzuA8ADwQAABbXI5GD0YbAA7gOsA60BvAACgrCCAAWNpcABGGEgYSxhsACFgcwD0ACwEAAFlb08YVxhjAHQAYQB0AGkAbwDuABoEbgBlAG4AdABpAGEAbADlADME4Ql1GAAAgRgAAIMYiBgAAAAAoRilGAAAqhgAALsYvhjRGAAA1xgnGWwAbABpAG4AZwBkAG8AdABzAGUA8QBlF3kARGRtImFsZQAAoEAmgAFpbHIAjRiRGJ0Y7CFpZwCgA/tpApcYAAAAAJoYZwAAoAD7aQBnAACgBPsA4DXYI93sIWlnAKAB++whaWcA4GYAagCAAWFsdACvGLIYthh0AACgbSZpAGcAAKAC+24AcwAAoLElbwBmAJJh8AHCGAAAxhhmAADgNdhX3QABYWvJGMwYbADsAGsEdqDUIgCg2SphI3J0aW50AACgDSoAAWFv2hgiGQABY3PeGB8ZsQPnGP0YBRkSGRUZAAAdGbID7xjyGPQY9xj5GAAA+xg7gL0AvUAAoFMhO4C8ALxAAKBVIQCgWSEAoFshswEBGQAAAxkAoFQhAKBWIbQCCxkOGQAAAAAQGTuAvgC+QACgVyEAoFwhNQAAoFghtgEZGQAAGxkAoFohAKBdITgAAKBeIWwAAKBEIHcAbgAAoCIjYwByAADgNdi73IAIRWFiY2RlZmdpamxub3JzdHYARhlKGVoZXhlmGWkZkhmWGZkZnRmgGa0ZxhnLGc8Z4BkjGmygZyIAoIwqgAFjbXAAUBlTGVgZ9SF0ZfVhbQBhAOSgswM6FgCghipyImV2ZQAfYQABaXliGWUZcgBjAB1hM2RvAHQAIWGAoWUibHFzAMYEcBl6GfGhZSLOBAAAdhlsAGEAbgD0AN8EgKF+KmNkbACBGYQZjBljAACgqSpvAHQAb6CAKmyggioAoIQqZeDbIgD+cwAAoJQqcgAA4DXYJN3noGsirATtIWVsAKA3IWMAeQBTZIChdyJFYWoApxmpGasZAKCSKgCgpSoAoKQqAAJFYWVztBm2Gb0ZwhkAoGkicABwoIoq8iFveACgiipxoIgq8aCIKrUZaQBtAACg5yJwAGYAAOA12FjdYQB2AOUAYwIAAWNp0xnWGXIAAKAKIW0AAKFzImVs3BneGQCgjioAoJAqAIM+ADtjZGxxco0E6xn0GfgZ/BkBGgABY2nvGfEZAKCnKnIAAKB6Km8AdAAAoNci0CFhcgCglSl1ImVzdAAAoHwqgAJhZGVscwAKGvQZFhrVBCAa8AEPGgAAFBpwAHIAbwD4AFkZcgAAoHgpcQAAAWxxxAQbGmwAZQBzAPMASRlpAO0A5AQAAWVuJxouGnIjdG5lcXEAAOBpIgD+xQAsGgAFQWFiY2Vma29zeUAaQxpmGmoabRqDGocalhrCGtMacgDyAMwCAAJpbG1yShpOGlAaVBpyAHMA8ABxD2YAvWBpAGwA9AASBQABZHJYGlsaYwB5AEpkAKGUIWN3YBpkGmkAcgAAoEgpAKCtIWEAcgAAoA8h6SFyYyVhgAFhbHIAcxp7Gn8a8iF0c3WgZSZpAHQAAKBlJuwhaXAAoCYg4yFvbgCguSJyAADgNdgl3XMAAAFld4wakRphInJvdwAAoCUpYSJyb3cAAKAmKYACYW1vcHIAnxqjGqcauhq+GnIAcgAAoP8h9CFodACgOyJrAAABbHKsGrMaZSRmdGFycm93AACgqSHpJGdodGFycm93AKCqIWYAAOA12Fnd4iFhcgCgFSCAAWNsdADIGswa0BpyAADgNdi93GEAcwDoAGka8iFvaydhAAFicNca2xr1IWxsAKBDIOghZW4AoBAg4Qr2GgAA/RoAAAgbExsaGwAAIRs7GwAAAAA+G2IbmRuVG6sbAACyG80b0htjAHUAdABlADuA7QDtQAChYyBpeQEbBhtyAGMAO4DuAO5AOGQAAWN4CxsNG3kANWRjAGwAO4ChAKFAAAFmcssCFhsA4DXYJt1yAGEAdgBlADuA7ADsQIChSCFpbm8AJxsyGzYbAAFpbisbLxtuAHQAAKAMKnQAAKAtIuYhaW4AoNwpdABhAACgKSHsIWlnM2GAAWFvcABDG1sbXhuAAWNndABJG0sbWRtyACthgAFlbHAAcQVRG1UbaQBuAOUAyAVhAHIA9AByBWgAMWFmAACgtyJlAGQAtWEAoggiY2ZvdGkbbRt1G3kb4SFyZQCgBSFpAG4AdKAeImkAZQAAoN0pZABvAPQAWxsAoisiY2VscIEbhRuPG5QbYQBsAACguiIAAWdyiRuNG2UAcgDzACMQ4wCCG2EicmhrAACgFyryIW9kAKA8KgACY2dwdJ8boRukG6gbeQBRZG8AbgAvYWYAAOA12FrdYQC5Y3UAZQBzAHQAO4C/AL9AAAFjabUbuRtyAADgNdi+3G4AAKIIIkVkc3bCG8QbyBvQAwCg+SJvAHQAAKD1Inag9CIAoPMiaaBiIOwhZGUpYesB1hsAANkbYwB5AFZkbAA7gO8A70AAA2NmbW9zdeYb7hvyG/Ub+hsFHAABaXnqG+0bcgBjADVhOWRyAADgNdgn3eEhdGg3YnAAZgAA4DXYW93jAf8bAAADHHIAAOA12L/c8iFjeVhk6yFjeVRkAARhY2ZnaGpvcxUcGhwiHCYcKhwtHDAcNRzwIXBhdqC6A/BjAAFleR4cIRzkIWlsN2E6ZHIAAOA12CjdciJlZW4AOGFjAHkARWRjAHkAXGRwAGYAAOA12FzdYwByAADgNdjA3IALQUJFSGFiY2RlZmdoamxtbm9wcnN0dXYAXhxtHHEcdRx5HN8cBx0dHTwd3B3tHfEdAR4EHh0eLB5FHrwewx7hHgkfPR9LH4ABYXJ0AGQcZxxpHHIA8gBvB/IAxQLhIWlsAKAbKeEhcnIAoA4pZ6BmIgCgiyphAHIAAKBiKWMJjRwAAJAcAACVHAAAAAAAAAAAAACZHJwcAACmHKgcrRwAANIc9SF0ZTph7SJwdHl2AKC0KXIAYQDuAFoG4iFkYbtjZwAAoegnZGyhHKMcAKCRKeUAiwYAoIUqdQBvADuAqwCrQHIAgKOQIWJmaGxwc3QAuhy/HMIcxBzHHMoczhxmoOQhcwAAoB8pcwAAoB0p6wCyGnAAAKCrIWwAAKA5KWkAbQAAoHMpbAAAoKIhAKGrKmFl1hzaHGkAbAAAoBkpc6CtKgDgrSoA/oABYWJyAOUc6RztHHIAcgAAoAwpcgBrAACgcicAAWFr8Rz4HGMAAAFla/Yc9xx7YFtgAAFlc/wc/hwAoIspbAAAAWR1Ax0FHQCgjykAoI0pAAJhZXV5Dh0RHRodHB3yIW9uPmEAAWRpFR0YHWkAbAA8YewAowbiAPccO2QAAmNxcnMkHScdLB05HWEAAKA2KXUAbwDyoBwgqhEAAWR1MB00HeghYXIAoGcpcyJoYXIAAKBLKWgAAKCyIQCiZCJmZ3FzRB1FB5Qdnh10AIACYWhscnQATh1WHWUdbB2NHXIicm93AHSgkCFhAOkAzxxhI3Jwb29uAAABZHVeHWId7yF3bgCgvSFwAACgvCHlJGZ0YXJyb3dzAKDHIWkiZ2h0AIABYWhzAHUdex2DHXIicm93APOglCGdBmEAcgBwAG8AbwBuAPMAzgtxAHUAaQBnAGEAcgByAG8A9wBlGugkcmVldGltZXMAoMsi8aFkIk0HAACaHWwAYQBuAPQAXgcAon0qY2Rnc6YdqR2xHbcdYwAAoKgqbwB0AG+gfypyoIEqAKCDKmXg2iIA/nMAAKCTKoACYWRlZ3MAwB3GHcod1h3ZHXAAcAByAG8A+ACmHG8AdAAAoNYicQAAAWdxzx3SHXQA8gBGB2cAdADyAHQcdADyAFMHaQDtAGMHgAFpbHIA4h3mHeod8yFodACgfClvAG8A8gDKBgDgNdgp3UWgdiIAoJEqYQH1Hf4dcgAAAWR1YB35HWygvCEAoGopbABrAACghCVjAHkAWWQAomoiYWNodAweDx4VHhkecgDyAGsdbwByAG4AZQDyAGAW4SFyZACgaylyAGkAAKD6JQABaW8hHiQe5CFvdEBh9SFzdGGgsCPjIWhlAKCwIwACRWFlczMeNR48HkEeAKBoInAAcKCJKvIhb3gAoIkqcaCHKvGghyo0HmkAbQAAoOYiAARhYm5vcHR3elIeXB5fHoUelh6mHqsetB4AAW5yVh5ZHmcAAKDsJ3IAAKD9IXIA6wCwBmcAgAFsbXIAZh52Hnse5SFmdAABYXKIB2weaQBnAGgAdABhAHIAcgBvAPcAkwfhInBzdG8AoPwnaQBnAGgAdABhAHIAcgBvAPcAmgdwI2Fycm93AAABbHKNHpEeZQBmAPQAxhxpImdodAAAoKwhgAFhZmwAnB6fHqIecgAAoIUpAOA12F3ddQBzAACgLSppIm1lcwAAoDQqYQGvHrMecwB0AACgFyLhAIoOZaHKJbkeRhLuIWdlAKDKJWEAcgBsoCgAdAAAoJMpgAJhY2htdADMHs8e1R7bHt0ecgDyAJ0GbwByAG4AZQDyANYWYQByAGSgyyEAoG0pAKAOIHIAaQAAoL8iAANhY2hpcXTrHu8e1QfzHv0eBh/xIXVvAKA5IHIAAOA12MHcbQDloXIi+h4AAPweAKCNKgCgjyoAAWJ19xwBH28AcqAYIACgGiDyIW9rQmEAhDwAO2NkaGlscXJCBhcfxh0gHyQfKB8sHzEfAAFjaRsfHR8AoKYqcgAAoHkqcgBlAOUAkx3tIWVzAKDJIuEhcnIAoHYpdSJlc3QAAKB7KgABUGk1HzkfYQByAACglillocMlAgdfEnIAAAFkdUIfRx9zImhhcgAAoEop6CFhcgCgZikAAWVuTx9WH3IjdG5lcXEAAOBoIgD+xQBUHwAHRGFjZGVmaGlsbm9wc3VuH3Ifoh+rH68ftx+7H74f5h/uH/MfBwj/HwsgxCFvdACgOiIAAmNscHJ5H30fiR+eH3IAO4CvAK9AAAFldIEfgx8AoEImZaAgJ3MAZQAAoCAnc6CmIXQAbwCAoaYhZGx1AJQfmB+cH28AdwDuAHkDZQBmAPQA6gbwAOkO6yFlcgCgriUAAW95ph+qH+0hbWEAoCkqPGThIXNoAKAUIOElc3VyZWRhbmdsZQCgISJyAADgNdgq3W8AAKAnIYABY2RuAMQfyR/bH3IAbwA7gLUAtUBhoiMi0B8AANMf1x9zAPQAKxFpAHIAAKDwKm8AdAA7gLcAt0B1AHMA4qESIh4TAADjH3WgOCIAoCoqYwHqH+0fcAAAoNsq8gB+GnAAbAB1APMACAgAAWRw9x/7H+UhbHMAoKciZgAA4DXYXt0AAWN0AyAHIHIAAOA12MLc8CFvcwCgPiJsobwDECAVIPQiaW1hcACguCJhAPAAEyAADEdMUlZhYmNkZWZnaGlqbG1vcHJzdHV2dzwgRyBmIG0geSCqILgg2iDeIBEhFSEyIUMhTSFQIZwhnyHSIQAiIyKLIrEivyIUIwABZ3RAIEMgAODZIjgD9uBrItIgBwmAAWVsdABNIF8gYiBmAHQAAAFhclMgWCByInJvdwAAoM0h6SRnaHRhcnJvdwCgziEA4NgiOAP24Goi0iBfCekkZ2h0YXJyb3cAoM8hAAFEZHEgdSDhIXNoAKCvIuEhc2gAoK4igAJiY25wdACCIIYgiSCNIKIgbABhAACgByL1IXRlRGFnAADgICLSIACiSSJFaW9wlSCYIJwgniAA4HAqOANkAADgSyI4A3MASWFyAG8A+AAyCnUAcgBhoG4mbADzoG4mmwjzAa8gAACzIHAAO4CgAKBAbQBwAOXgTiI4AyoJgAJhZW91eQDBIMogzSDWINkg8AHGIAAAyCAAoEMqbwBuAEhh5CFpbEZhbgBnAGSgRyJvAHQAAOBtKjgDcAAAoEIqPWThIXNoAKATIACjYCJBYWRxc3jpIO0g+SD+IAIhDCFyAHIAAKDXIXIAAAFocvIg9SBrAACgJClvoJch9wAGD28AdAAA4FAiOAN1AGkA9gC7CAABZWkGIQohYQByAACgKCntAN8I6SFzdPOgBCLlCHIAAOA12CvdAAJFZXN0/wgcISshLiHxoXEiIiEAABMJ8aFxIgAJAAAnIWwAYQBuAPQAEwlpAO0AGQlyoG8iAKBvIoABQWFwADghOyE/IXIA8gBeIHIAcgAAoK4hYQByAACg8ipzogsiSiEAAAAAxwtkoPwiAKD6ImMAeQBaZIADQUVhZGVzdABcIV8hYiFmIWkhkyGWIXIA8gBXIADgZiI4A3IAcgAAoJohcgAAoCUggKFwImZxcwBwIYQhjiF0AAABYXJ1IXohcgByAG8A9wBlIWkAZwBoAHQAYQByAHIAbwD3AD4h8aFwImAhAACKIWwAYQBuAPQAZwlz4H0qOAMAoG4iaQDtAG0JcqBuImkA5aDqIkUJaQDkADoKAAFwdKMhpyFmAADgNdhf3YCBrAA7aW4AriGvIcchrEBuAIChCSJFZHYAtyG6Ib8hAOD5IjgDbwB0AADg9SI4A+EB1gjEIcYhAKD3IgCg9iJpAHagDCLhAagJzyHRIQCg/iIAoP0igAFhb3IA2CHsIfEhcgCAoSYiYXN0AOAh5SHpIWwAbABlAOwAywhsAADg/SrlIADgAiI4A2wiaW50AACgFCrjoYAi9yEAAPohdQDlAJsJY+CvKjgDZaCAIvEAkwkAAkFhaXQHIgoiFyIeInIA8gBsIHIAcgAAoZshY3cRIhQiAOAzKTgDAOCdITgDZyRodGFycm93AACgmyFyAGkA5aDrIr4JgANjaGltcHF1AC8iPCJHIpwhTSJQIloigKGBImNlcgA2Iv0JOSJ1AOUABgoA4DXYw9zvIXJ0bQKdIQAAAABEImEAcgDhAOEhbQBloEEi8aBEIiYKYQDyAMsIcwB1AAABYnBWIlgi5QDUCeUA3wmAAWJjcABgInMieCKAoYQiRWVzAGci7glqIgDgxSo4A2UAdABl4IIi0iBxAPGgiCJoImMAZaCBIvEA/gmAoYUiRWVzAH8iFgqCIgDgxio4A2UAdABl4IMi0iBxAPGgiSKAIgACZ2lscpIilCKaIpwi7AAMCWwAZABlADuA8QDxQOcAWwlpI2FuZ2xlAAABbHKkIqoi5SFmdGWg6iLxAEUJaSJnaHQAZaDrIvEAvgltoL0DAKEjAGVzuCK8InIAbwAAoBYhcAAAoAcggARESGFkZ2lscnMAziLSItYi2iLeIugi7SICIw8j4SFzaACgrSLhIXJyAKAEKXAAAOBNItIg4SFzaACgrCIAAWV04iLlIgDgZSLSIADgPgDSIG4iZmluAACg3imAAUFldADzIvci+iJyAHIAAKACKQDgZCLSIHLgPADSIGkAZQAA4LQi0iAAAUF0BiMKI3IAcgAAoAMp8iFpZQDgtSLSIGkAbQAA4Dwi0iCAAUFhbgAaIx4jKiNyAHIAAKDWIXIAAAFociMjJiNrAACgIylvoJYh9wD/DuUhYXIAoCcpUxJqFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVCMAAF4jaSN/I4IjjSOeI8AUAAAAAKYjwCMAANoj3yMAAO8jHiQvJD8kRCQAAWNzVyNsFHUAdABlADuA8wDzQAABaXlhI2cjcgBjoJoiO4D0APRAPmSAAmFiaW9zAHEjdCN3I3EBeiNzAOgAdhTsIWFjUWF2AACgOCrvIWxkAKC8KewhaWdTYQABY3KFI4kjaQByAACgvykA4DXYLN1vA5QjAAAAAJYjAACcI24A22JhAHYAZQA7gPIA8kAAoMEpAAFibaEjjAphAHIAAKC1KQACYWNpdKwjryO6I70jcgDyAFkUAAFpcrMjtiNyAACgvinvIXNzAKC7KW4A5QDZCgCgwCmAAWFlaQDFI8gjyyNjAHIATWFnAGEAyWOAAWNkbgDRI9Qj1iPyIW9uv2MAoLYpdQDzAHgBcABmAADgNdhg3YABYWVsAOQj5yPrI3IAAKC3KXIAcAAAoLkpdQDzAHwBAKMoImFkaW9zdvkj/CMPJBMkFiQbJHIA8gBeFIChXSplZm0AAyQJJAwkcgBvoDQhZgAAoDQhO4CqAKpAO4C6ALpA5yFvZgCgtiJyAACgVipsIm9wZQAAoFcqAKBbKoABY2xvACMkJSQrJPIACCRhAHMAaAA7gPgA+EBsAACgmCJpAGwBMyQ4JGQAZQA7gPUA9UBlAHMAYaCXInMAAKA2Km0AbAA7gPYA9kDiIWFyAKA9I+EKXiQAAHokAAB8JJQkAACYJKkkAAAAALUkEQsAAPAkAAAAAAQleiUAAIMlcgCAoSUiYXN0AGUkbyQBCwCBtgA7bGokayS2QGwAZQDsABgDaQJ1JAAAAAB4JG0AAKDzKgCg/Sp5AD9kcgCAAmNpbXB0AIUkiCSLJJkSjyRuAHQAJWBvAGQALmBpAGwAAKAwIOUhbmsAoDEgcgAA4DXYLd2AAWltbwCdJKAkpCR2oMYD1WNtAGEA9AD+B24AZQAAoA4m9KHAA64kAAC0JGMjaGZvcmsAAKDUItZjAAFhdbgkxCRuAAABY2u9JMIkawBooA8hAKAOIfYAaRpzAACkKwBhYmNkZW1zdNMkIRPXJNsk4STjJOck6yTjIWlyAKAjKmkAcgAAoCIqAAFvdYsW3yQAoCUqAKByKm4AO4CxALFAaQBtAACgJip3AG8AAKAnKoABaXB1APUk+iT+JO4idGludACgFSpmAADgNdhh3W4AZAA7gKMAo0CApHoiRWFjZWlub3N1ABMlFSUYJRslTCVRJVklSSV1JQCgsypwAACgtyp1AOUAPwtjoK8qgKJ6ImFjZW5zACclLSU0JTYlSSVwAHAAcgBvAPgAFyV1AHIAbAB5AGUA8QA/C/EAOAuAAWFlcwA8JUElRSXwInByb3gAoLkqcQBxAACgtSppAG0AAKDoImkA7QBEC20AZQDzoDIgIguAAUVhcwBDJVclRSXwAEAlgAFkZnAATwtfJXElgAFhbHMAZSVpJW0l7CFhcgCgLiPpIW5lAKASI/UhcmYAoBMjdKAdIu8AWQvyIWVsAKCwIgABY2l9JYElcgAA4DXYxdzIY24iY3NwAACgCCAAA2Zpb3BzdZElKxuVJZolnyWkJXIAAOA12C7dcABmAADgNdhi3XIiaW1lAACgVyBjAHIAAOA12MbcgAFhZW8AqiW6JcAldAAAAWVpryW2JXIAbgBpAG8AbgDzABkFbgB0AACgFipzAHQAZaA/APEACRj0AG0LgApBQkhhYmNkZWZoaWxtbm9wcnN0dXgA4yXyJfYl+iVpJpAmpia9JtUm5ib4JlonaCdxJ3UnnietJ7EnyCfiJ+cngAFhcnQA6SXsJe4lcgDyAJkM8gD6AuEhaWwAoBwpYQByAPIA3BVhAHIAAKBkKYADY2RlbnFydAAGJhAmEyYYJiYmKyZaJgABZXUKJg0mAOA9IjEDdABlAFVhaQDjACAN7SJwdHl2AKCzKWcAgKHpJ2RlbAAgJiImJCYAoJIpAKClKeUA9wt1AG8AO4C7ALtAcgAApZIhYWJjZmhscHN0dz0mQCZFJkcmSiZMJk4mUSZVJlgmcAAAoHUpZqDlIXMAAKAgKQCgMylzAACgHinrALka8ACVHmwAAKBFKWkAbQAAoHQpbAAAoKMhAKCdIQABYWleJmImaQBsAACgGilvAG6gNiJhAGwA8wB2C4ABYWJyAG8mciZ2JnIA8gAvEnIAawAAoHMnAAFha3omgSZjAAABZWt/JoAmfWBdYAABZXOFJocmAKCMKWwAAAFkdYwmjiYAoI4pAKCQKQACYWV1eZcmmiajJqUm8iFvbllhAAFkaZ4moSZpAGwAV2HsAA8M4gCAJkBkAAJjbHFzrSawJrUmuiZhAACgNylkImhhcgAAoGkpdQBvAPKgHSCjAWgAAKCzIYABYWNnAMMm0iaUC2wAgKEcIWlwcwDLJs4migxuAOUAoAxhAHIA9ADaC3QAAKCtJYABaWxyANsm3ybjJvMhaHQAoH0pbwBvAPIANgwA4DXYL90AAWFv6ib1JnIAAAFkde8m8SYAoMEhbKDAIQCgbCl2oMED8WOAAWducwD+Jk4nUCdoAHQAAANhaGxyc3QKJxInISc1Jz0nRydyInJvdwB0oJIhYQDpAFYmYSNycG9vbgAAAWR1GiceJ28AdwDuAPAmcAAAoMAh5SFmdAABYWgnJy0ncgByAG8AdwDzAAkMYQByAHAAbwBvAG4A8wATBGklZ2h0YXJyb3dzAACgySFxAHUAaQBnAGEAcgByAG8A9wBZJugkcmVldGltZXMAoMwiZwDaYmkAbgBnAGQAbwB0AHMAZQDxABwYgAFhaG0AYCdjJ2YncgDyAAkMYQDyABMEAKAPIG8idXN0AGGgsSPjIWhlAKCxI+0haWQAoO4qAAJhYnB0fCeGJ4knmScAAW5ygCeDJ2cAAKDtJ3IAAKD+IXIA6wAcDIABYWZsAI8nkieVJ3IAAKCGKQDgNdhj3XUAcwAAoC4qaSJtZXMAAKA1KgABYXCiJ6gncgBnoCkAdAAAoJQp7yJsaW50AKASKmEAcgDyADwnAAJhY2hxuCe8J6EMwCfxIXVvAKA6IHIAAOA12MfcAAFidYAmxCdvAPKgGSCoAYABaGlyAM4n0ifWJ3IAZQDlAE0n7SFlcwCgyiJpAIChuSVlZmwAXAxjEt4n9CFyaQCgzinsInVoYXIAoGgpAKAeIWENBSgJKA0oSyhVKIYoAACLKLAoAAAAAOMo5ygAABApJCkxKW0pcSmHKaYpAACYKgAAAACxKmMidXRlAFthcQB1AO8ABR+ApHsiRWFjZWlucHN5ABwoHignKCooLygyKEEoRihJKACgtCrwASMoAAAlKACguCpvAG4AYWF1AOUAgw1koLAqaQBsAF9hcgBjAF1hgAFFYXMAOCg6KD0oAKC2KnAAAKC6KmkAbQAAoOki7yJsaW50AKATKmkA7QCIDUFkbwB0AGKixSKRFgAAAABTKACgZiqAA0FhY21zdHgAYChkKG8ocyh1KHkogihyAHIAAKDYIXIAAAFocmkoayjrAJAab6CYIfcAzAd0ADuApwCnQGkAO2D3IWFyAKApKW0AAAFpbn4ozQBuAHUA8wDOAHQAAKA2J3IA7+A12DDdIxkAAmFjb3mRKJUonSisKHIAcAAAoG8mAAFoeZkonChjAHkASWRIZHIAdABtAqUoAAAAAKgoaQDkAFsPYQByAGEA7ABsJDuArQCtQAABZ22zKLsobQBhAAChwwNmdroouijCY4CjPCJkZWdsbnByAMgozCjPKNMo1yjaKN4obwB0AACgairxoEMiCw5FoJ4qAKCgKkWgnSoAoJ8qZQAAoEYi7CF1cwCgJCrhIXJyAKByKWEAcgDyAPwMAAJhZWl07Sj8KAEpCCkAAWxz8Sj4KGwAcwBlAHQAbQDpAH8oaABwAACgMyrwImFyc2wAoOQpAAFkbFoPBSllAACgIyNloKoqc6CsKgDgrCoA/oABZmxwABUpGCkfKfQhY3lMZGKgLwBhoMQpcgAAoD8jZgAA4DXYZN1hAAABZHIoKRcDZQBzAHWgYCZpAHQAAKBgJoABY3N1ADYpRilhKQABYXU6KUApcABzoJMiAOCTIgD+cABzoJQiAOCUIgD+dQAAAWJwSylWKQChjyJlcz4NUCllAHQAZaCPIvEAPw0AoZAiZXNIDVspZQB0AGWgkCLxAEkNAKGhJWFmZilbBHIAZQFrKVwEAKChJWEAcgDyAAMNAAJjZW10dyl7KX8pgilyAADgNdjI3HQAbQDuAM4AaQDsAAYpYQByAOYAVw0AAWFyiimOKXIA5qAGJhESAAFhbpIpoylpImdodAAAAWVwmSmgKXAAcwBpAGwAbwDuANkXaADpAKAkcwCvYIACYmNtbnAArin8KY4NJSooKgCkgiJFZGVtbnByc7wpvinCKcgpzCnUKdgp3CkAoMUqbwB0AACgvSpkoIYibwB0AACgwyr1IWx0AKDBKgABRWXQKdIpAKDLKgCgiiLsIXVzAKC/KuEhcnIAoHkpgAFlaXUA4inxKfQpdAAAoYIiZW7oKewpcQDxoIYivSllAHEA8aCKItEpbQAAoMcqAAFicPgp+ikAoNUqAKDTKmMAgKJ7ImFjZW5zAAcqDSoUKhYqRihwAHAAcgBvAPgAIyh1AHIAbAB5AGUA8QCDDfEAfA2AAWFlcwAcKiIqPShwAHAAcgBvAPgAPChxAPEAOShnAACgaiYApoMiMTIzRWRlaGxtbnBzPCo/KkIqRSpHKlIqWCpjKmcqaypzKncqO4C5ALlAO4CyALJAO4CzALNAAKDGKgABb3NLKk4qdAAAoL4qdQBiAACg2CpkoIcibwB0AACgxCpzAAABb3VdKmAqbAAAoMknYgAAoNcq4SFycgCgeyn1IWx0AKDCKgABRWVvKnEqAKDMKgCgiyLsIXVzAKDAKoABZWl1AH0qjCqPKnQAAKGDImVugyqHKnEA8aCHIkYqZQBxAPGgiyJwKm0AAKDIKgABYnCTKpUqAKDUKgCg1iqAAUFhbgCdKqEqrCpyAHIAAKDZIXIAAAFocqYqqCrrAJUab6CZIfcAxQf3IWFyAKAqKWwAaQBnADuA3wDfQOELzyrZKtwq6SrsKvEqAAD1KjQrAAAAAAAAAAAAAEwrbCsAAHErvSsAAAAAAADRK3IC1CoAAAAA2CrnIWV0AKAWI8RjcgDrAOUKgAFhZXkA4SrkKucq8iFvbmVh5CFpbGNhQmRvAPQAIg5sInJlYwAAoBUjcgAA4DXYMd0AAmVpa2/7KhIrKCsuK/IBACsAAAkrZQAAATRm6g0EK28AcgDlAOsNYQBzorgDECsAAAAAEit5AG0A0WMAAWNuFislK2sAAAFhcxsrIStwAHAAcgBvAPgAFw5pAG0AAKA8InMA8AD9DQABYXMsKyEr8AAXDnIAbgA7gP4A/kDsATgrOyswG2QA5QBnAmUAcwCAgdcAO2JkAEMrRCtJK9dAYaCgInIAAKAxKgCgMCqAAWVwcwBRK1MraSvhAAkh4qKkIlsrXysAAAAAYytvAHQAAKA2I2kAcgAAoPEqb+A12GXdcgBrAACg2irhAHgociJpbWUAAKA0IIABYWlwAHYreSu3K2QA5QC+DYADYWRlbXBzdACFK6MrmiunK6wrsCuzK24iZ2xlAACitSVkbHFykCuUK5ornCvvIXduAKC/JeUhZnRloMMl8QACBwCgXCJpImdodABloLkl8QBdDG8AdAAAoOwlaSJudXMAAKA6KuwhdXMAoDkqYgAAoM0p6SFtZQCgOyrlInppdW0AoOIjgAFjaHQAwivKK80rAAFyecYrySsA4DXYydxGZGMAeQBbZPIhb2tnYQABaW/UK9creAD0ANERaCJlYWQAAAFsct4r5ytlAGYAdABhAHIAcgBvAPcAXQbpJGdodGFycm93AKCgIQAJQUhhYmNkZmdobG1vcHJzdHV3CiwNLBEsHSwnLDEsQCxLLFIsYix6LIQsjyzLLOgs7Sz/LAotcgDyAAkDYQByAACgYykAAWNyFSwbLHUAdABlADuA+gD6QPIACQ1yAOMBIywAACUseQBeZHYAZQBtYQABaXkrLDAscgBjADuA+wD7QENkgAFhYmgANyw6LD0scgDyANEO7CFhY3FhYQDyAOAOAAFpckQsSCzzIWh0AKB+KQDgNdgy3XIAYQB2AGUAO4D5APlAYQFWLF8scgAAAWxyWixcLACgvyEAoL4hbABrAACggCUAAWN0Zix2LG8CbCwAAAAAcyxyAG4AZaAcI3IAAKAcI28AcAAAoA8jcgBpAACg+CUAAWFsfiyBLGMAcgBrYTuAqACoQAABZ3CILIssbwBuAHNhZgAA4DXYZt0AA2FkaGxzdZksniynLLgsuyzFLHIAcgBvAPcACQ1vAHcAbgBhAHIAcgBvAPcA2A5hI3Jwb29uAAABbHKvLLMsZQBmAPQAWyxpAGcAaAD0AF0sdQDzAKYOaQAAocUDaGzBLMIs0mNvAG4AxWPwI2Fycm93cwCgyCGAAWNpdADRLOEs5CxvAtcsAAAAAN4scgBuAGWgHSNyAACgHSNvAHAAAKAOI24AZwBvYXIAaQAAoPklYwByAADgNdjK3IABZGlyAPMs9yz6LG8AdAAAoPAi7CFkZWlhaQBmoLUlAKC0JQABYW0DLQYtcgDyAMosbAA7gPwA/EDhIm5nbGUAoKcpgAdBQkRhY2RlZmxub3Byc3oAJy0qLTAtNC2bLZ0toS2/LcMtxy3TLdgt3C3gLfwtcgDyABADYQByAHag6CoAoOkqYQBzAOgA/gIAAW5yOC08LechcnQAoJwpgANla25wcnN0AJkpSC1NLVQtXi1iLYItYQBwAHAA4QAaHG8AdABoAGkAbgDnAKEXgAFoaXIAoSmzJFotbwBwAPQAdCVooJUh7wD4JgABaXVmLWotZwBtAOEAuygAAWJwbi14LXMjZXRuZXEAceCKIgD+AODLKgD+cyNldG5lcQBx4IsiAP4A4MwqAP4AAWhyhi2KLWUAdADhABIraSNhbmdsZQAAAWxyki2WLeUhZnQAoLIiaSJnaHQAAKCzInkAMmThIXNoAKCiIoABZWxyAKcttC24LWKiKCKuLQAAAACyLWEAcgAAoLsicQAAoFoi7CFpcACg7iIAAWJ0vC1eD2EA8gBfD3IAAOA12DPddAByAOkAlS1zAHUAAAFicM0t0C0A4IIi0iAA4IMi0iBwAGYAAOA12GfdcgBvAPAAWQt0AHIA6QCaLQABY3XkLegtcgAA4DXYy9wAAWJw7C30LW4AAAFFZXUt8S0A4IoiAP5uAAABRWV/LfktAOCLIgD+6SJnemFnAKCaKYADY2Vmb3BycwANLhAuJS4pLiMuLi40LukhcmN1YQABZGkULiEuAAFiZxguHC5hAHIAAKBfKmUAcaAnIgCgWSLlIXJwAKAYIXIAAOA12DTdcABmAADgNdho3WWgQCJhAHQA6ABqD2MAcgAA4DXYzNzjCuQRUC4AAFQuAABYLmIuAAAAAGMubS5wLnQuAAAAAIguki4AAJouJxIqEnQAcgDpAB0ScgAA4DXYNd0AAUFhWy5eLnIA8gDnAnIA8gCTB75jAAFBYWYuaS5yAPIA4AJyAPIAjAdhAPAAeh5pAHMAAKD7IoABZHB0APgReS6DLgABZmx9LoAuAOA12GnddQDzAP8RaQBtAOUABBIAAUFhiy6OLnIA8gDuAnIA8gCaBwABY3GVLgoScgAA4DXYzdwAAXB0nS6hLmwAdQDzACUScgDpACASAARhY2VmaW9zdbEuvC7ELsguzC7PLtQu2S5jAAABdXm2LrsudABlADuA/QD9QE9kAAFpecAuwy5yAGMAd2FLZG4AO4ClAKVAcgAA4DXYNt1jAHkAV2RwAGYAAOA12GrdYwByAADgNdjO3AABY23dLt8ueQBOZGwAO4D/AP9AAAVhY2RlZmhpb3N38y73Lv8uAi8MLxAvEy8YLx0vIi9jInV0ZQB6YQABYXn7Lv4u8iFvbn5hN2RvAHQAfGEAAWV0Bi8KL3QAcgDmAB8QYQC2Y3IAAOA12DfdYwB5ADZk5yJyYXJyAKDdIXAAZgAA4DXYa91jAHIAAOA12M/cAAFqbiYvKC8AoA0gagAAoAwg")}});var xmlDecodeTree,init_decode_data_xml2=__esm({"../../node_modules/.pnpm/entities@7.0.1/node_modules/entities/dist/esm/generated/decode-data-xml.js"(){init_decode_shared();xmlDecodeTree=decodeBase64("AAJhZ2xxBwARABMAFQBtAg0AAAAAAA8AcAAmYG8AcwAnYHQAPmB0ADxg9SFvdCJg")}});var BinTrieFlags2,init_bin_trie_flags=__esm({"../../node_modules/.pnpm/entities@7.0.1/node_modules/entities/dist/esm/internal/bin-trie-flags.js"(){(function(BinTrieFlags3){BinTrieFlags3[BinTrieFlags3.VALUE_LENGTH=49152]="VALUE_LENGTH",BinTrieFlags3[BinTrieFlags3.FLAG13=8192]="FLAG13",BinTrieFlags3[BinTrieFlags3.BRANCH_LENGTH=8064]="BRANCH_LENGTH",BinTrieFlags3[BinTrieFlags3.JUMP_TABLE=127]="JUMP_TABLE"})(BinTrieFlags2||(BinTrieFlags2={}))}});function isNumber2(code2){return code2>=CharCodes2.ZERO&&code2<=CharCodes2.NINE}function isHexadecimalCharacter2(code2){return code2>=CharCodes2.UPPER_A&&code2<=CharCodes2.UPPER_F||code2>=CharCodes2.LOWER_A&&code2<=CharCodes2.LOWER_F}function isAsciiAlphaNumeric2(code2){return code2>=CharCodes2.UPPER_A&&code2<=CharCodes2.UPPER_Z||code2>=CharCodes2.LOWER_A&&code2<=CharCodes2.LOWER_Z||isNumber2(code2)}function isEntityInAttributeInvalidEnd2(code2){return code2===CharCodes2.EQUALS||isAsciiAlphaNumeric2(code2)}function determineBranch2(decodeTree,current,nodeIndex,char){let branchCount=(current&BinTrieFlags2.BRANCH_LENGTH)>>7,jumpOffset=current&BinTrieFlags2.JUMP_TABLE;if(branchCount===0)return jumpOffset!==0&&char===jumpOffset?nodeIndex:-1;if(jumpOffset){let value=char-jumpOffset;return value<0||value>=branchCount?-1:decodeTree[nodeIndex+value]-1}let packedKeySlots=branchCount+1>>1,lo=0,hi=branchCount-1;for(;lo<=hi;){let mid=lo+hi>>>1,slot=mid>>1,midKey=decodeTree[nodeIndex+slot]>>(mid&1)*8&255;if(midKey<char)lo=mid+1;else if(midKey>char)hi=mid-1;else return decodeTree[nodeIndex+packedKeySlots+mid]}return-1}var CharCodes2,TO_LOWER_BIT2,EntityDecoderState2,DecodingMode2,EntityDecoder2,init_decode2=__esm({"../../node_modules/.pnpm/entities@7.0.1/node_modules/entities/dist/esm/decode.js"(){init_decode_codepoint2();init_decode_data_html2();init_decode_data_xml2();init_bin_trie_flags();init_decode_codepoint2();init_decode_data_html2();init_decode_data_xml2();(function(CharCodes4){CharCodes4[CharCodes4.NUM=35]="NUM",CharCodes4[CharCodes4.SEMI=59]="SEMI",CharCodes4[CharCodes4.EQUALS=61]="EQUALS",CharCodes4[CharCodes4.ZERO=48]="ZERO",CharCodes4[CharCodes4.NINE=57]="NINE",CharCodes4[CharCodes4.LOWER_A=97]="LOWER_A",CharCodes4[CharCodes4.LOWER_F=102]="LOWER_F",CharCodes4[CharCodes4.LOWER_X=120]="LOWER_X",CharCodes4[CharCodes4.LOWER_Z=122]="LOWER_Z",CharCodes4[CharCodes4.UPPER_A=65]="UPPER_A",CharCodes4[CharCodes4.UPPER_F=70]="UPPER_F",CharCodes4[CharCodes4.UPPER_Z=90]="UPPER_Z"})(CharCodes2||(CharCodes2={}));TO_LOWER_BIT2=32;__name(isNumber2,"isNumber");__name(isHexadecimalCharacter2,"isHexadecimalCharacter");__name(isAsciiAlphaNumeric2,"isAsciiAlphaNumeric");__name(isEntityInAttributeInvalidEnd2,"isEntityInAttributeInvalidEnd");(function(EntityDecoderState3){EntityDecoderState3[EntityDecoderState3.EntityStart=0]="EntityStart",EntityDecoderState3[EntityDecoderState3.NumericStart=1]="NumericStart",EntityDecoderState3[EntityDecoderState3.NumericDecimal=2]="NumericDecimal",EntityDecoderState3[EntityDecoderState3.NumericHex=3]="NumericHex",EntityDecoderState3[EntityDecoderState3.NamedEntity=4]="NamedEntity"})(EntityDecoderState2||(EntityDecoderState2={}));(function(DecodingMode3){DecodingMode3[DecodingMode3.Legacy=0]="Legacy",DecodingMode3[DecodingMode3.Strict=1]="Strict",DecodingMode3[DecodingMode3.Attribute=2]="Attribute"})(DecodingMode2||(DecodingMode2={}));EntityDecoder2=class{static{__name(this,"EntityDecoder")}constructor(decodeTree,emitCodePoint,errors){this.decodeTree=decodeTree,this.emitCodePoint=emitCodePoint,this.errors=errors,this.state=EntityDecoderState2.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=DecodingMode2.Strict,this.runConsumed=0}startEntity(decodeMode){this.decodeMode=decodeMode,this.state=EntityDecoderState2.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1,this.runConsumed=0}write(input,offset){switch(this.state){case EntityDecoderState2.EntityStart:return input.charCodeAt(offset)===CharCodes2.NUM?(this.state=EntityDecoderState2.NumericStart,this.consumed+=1,this.stateNumericStart(input,offset+1)):(this.state=EntityDecoderState2.NamedEntity,this.stateNamedEntity(input,offset));case EntityDecoderState2.NumericStart:return this.stateNumericStart(input,offset);case EntityDecoderState2.NumericDecimal:return this.stateNumericDecimal(input,offset);case EntityDecoderState2.NumericHex:return this.stateNumericHex(input,offset);case EntityDecoderState2.NamedEntity:return this.stateNamedEntity(input,offset)}}stateNumericStart(input,offset){return offset>=input.length?-1:(input.charCodeAt(offset)|TO_LOWER_BIT2)===CharCodes2.LOWER_X?(this.state=EntityDecoderState2.NumericHex,this.consumed+=1,this.stateNumericHex(input,offset+1)):(this.state=EntityDecoderState2.NumericDecimal,this.stateNumericDecimal(input,offset))}stateNumericHex(input,offset){for(;offset<input.length;){let char=input.charCodeAt(offset);if(isNumber2(char)||isHexadecimalCharacter2(char)){let digit=char<=CharCodes2.NINE?char-CharCodes2.ZERO:(char|TO_LOWER_BIT2)-CharCodes2.LOWER_A+10;this.result=this.result*16+digit,this.consumed++,offset++}else return this.emitNumericEntity(char,3)}return-1}stateNumericDecimal(input,offset){for(;offset<input.length;){let char=input.charCodeAt(offset);if(isNumber2(char))this.result=this.result*10+(char-CharCodes2.ZERO),this.consumed++,offset++;else return this.emitNumericEntity(char,2)}return-1}emitNumericEntity(lastCp,expectedLength){var _a4;if(this.consumed<=expectedLength)return(_a4=this.errors)===null||_a4===void 0||_a4.absenceOfDigitsInNumericCharacterReference(this.consumed),0;if(lastCp===CharCodes2.SEMI)this.consumed+=1;else if(this.decodeMode===DecodingMode2.Strict)return 0;return this.emitCodePoint(replaceCodePoint2(this.result),this.consumed),this.errors&&(lastCp!==CharCodes2.SEMI&&this.errors.missingSemicolonAfterCharacterReference(),this.errors.validateNumericCharacterReference(this.result)),this.consumed}stateNamedEntity(input,offset){let{decodeTree}=this,current=decodeTree[this.treeIndex],valueLength=(current&BinTrieFlags2.VALUE_LENGTH)>>14;for(;offset<input.length;){if(valueLength===0&&(current&BinTrieFlags2.FLAG13)!==0){let runLength=(current&BinTrieFlags2.BRANCH_LENGTH)>>7;if(this.runConsumed===0){let firstChar=current&BinTrieFlags2.JUMP_TABLE;if(input.charCodeAt(offset)!==firstChar)return this.result===0?0:this.emitNotTerminatedNamedEntity();offset++,this.excess++,this.runConsumed++}for(;this.runConsumed<runLength;){if(offset>=input.length)return-1;let charIndexInPacked=this.runConsumed-1,packedWord=decodeTree[this.treeIndex+1+(charIndexInPacked>>1)],expectedChar=charIndexInPacked%2===0?packedWord&255:packedWord>>8&255;if(input.charCodeAt(offset)!==expectedChar)return this.runConsumed=0,this.result===0?0:this.emitNotTerminatedNamedEntity();offset++,this.excess++,this.runConsumed++}this.runConsumed=0,this.treeIndex+=1+(runLength>>1),current=decodeTree[this.treeIndex],valueLength=(current&BinTrieFlags2.VALUE_LENGTH)>>14}if(offset>=input.length)break;let char=input.charCodeAt(offset);if(char===CharCodes2.SEMI&&valueLength!==0&&(current&BinTrieFlags2.FLAG13)!==0)return this.emitNamedEntityData(this.treeIndex,valueLength,this.consumed+this.excess);if(this.treeIndex=determineBranch2(decodeTree,current,this.treeIndex+Math.max(1,valueLength),char),this.treeIndex<0)return this.result===0||this.decodeMode===DecodingMode2.Attribute&&(valueLength===0||isEntityInAttributeInvalidEnd2(char))?0:this.emitNotTerminatedNamedEntity();if(current=decodeTree[this.treeIndex],valueLength=(current&BinTrieFlags2.VALUE_LENGTH)>>14,valueLength!==0){if(char===CharCodes2.SEMI)return this.emitNamedEntityData(this.treeIndex,valueLength,this.consumed+this.excess);this.decodeMode!==DecodingMode2.Strict&&(current&BinTrieFlags2.FLAG13)===0&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0)}offset++,this.excess++}return-1}emitNotTerminatedNamedEntity(){var _a4;let{result,decodeTree}=this,valueLength=(decodeTree[result]&BinTrieFlags2.VALUE_LENGTH)>>14;return this.emitNamedEntityData(result,valueLength,this.consumed),(_a4=this.errors)===null||_a4===void 0||_a4.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(result,valueLength,consumed){let{decodeTree}=this;return this.emitCodePoint(valueLength===1?decodeTree[result]&~(BinTrieFlags2.VALUE_LENGTH|BinTrieFlags2.FLAG13):decodeTree[result+1],consumed),valueLength===3&&this.emitCodePoint(decodeTree[result+2],consumed),consumed}end(){var _a4;switch(this.state){case EntityDecoderState2.NamedEntity:return this.result!==0&&(this.decodeMode!==DecodingMode2.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case EntityDecoderState2.NumericDecimal:return this.emitNumericEntity(0,2);case EntityDecoderState2.NumericHex:return this.emitNumericEntity(0,3);case EntityDecoderState2.NumericStart:return(_a4=this.errors)===null||_a4===void 0||_a4.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case EntityDecoderState2.EntityStart:return 0}}};__name(determineBranch2,"determineBranch")}});function isWhitespace(c2){return c2===CharCodes3.Space||c2===CharCodes3.NewLine||c2===CharCodes3.Tab||c2===CharCodes3.FormFeed||c2===CharCodes3.CarriageReturn}function isEndOfTagSection(c2){return c2===CharCodes3.Slash||c2===CharCodes3.Gt||isWhitespace(c2)}function isASCIIAlpha(c2){return c2>=CharCodes3.LowerA&&c2<=CharCodes3.LowerZ||c2>=CharCodes3.UpperA&&c2<=CharCodes3.UpperZ}var CharCodes3,State,QuoteType,Sequences,Tokenizer,init_Tokenizer=__esm({"../../node_modules/.pnpm/htmlparser2@10.1.0/node_modules/htmlparser2/dist/esm/Tokenizer.js"(){init_decode2();(function(CharCodes4){CharCodes4[CharCodes4.Tab=9]="Tab",CharCodes4[CharCodes4.NewLine=10]="NewLine",CharCodes4[CharCodes4.FormFeed=12]="FormFeed",CharCodes4[CharCodes4.CarriageReturn=13]="CarriageReturn",CharCodes4[CharCodes4.Space=32]="Space",CharCodes4[CharCodes4.ExclamationMark=33]="ExclamationMark",CharCodes4[CharCodes4.Number=35]="Number",CharCodes4[CharCodes4.Amp=38]="Amp",CharCodes4[CharCodes4.SingleQuote=39]="SingleQuote",CharCodes4[CharCodes4.DoubleQuote=34]="DoubleQuote",CharCodes4[CharCodes4.Dash=45]="Dash",CharCodes4[CharCodes4.Slash=47]="Slash",CharCodes4[CharCodes4.Zero=48]="Zero",CharCodes4[CharCodes4.Nine=57]="Nine",CharCodes4[CharCodes4.Semi=59]="Semi",CharCodes4[CharCodes4.Lt=60]="Lt",CharCodes4[CharCodes4.Eq=61]="Eq",CharCodes4[CharCodes4.Gt=62]="Gt",CharCodes4[CharCodes4.Questionmark=63]="Questionmark",CharCodes4[CharCodes4.UpperA=65]="UpperA",CharCodes4[CharCodes4.LowerA=97]="LowerA",CharCodes4[CharCodes4.UpperF=70]="UpperF",CharCodes4[CharCodes4.LowerF=102]="LowerF",CharCodes4[CharCodes4.UpperZ=90]="UpperZ",CharCodes4[CharCodes4.LowerZ=122]="LowerZ",CharCodes4[CharCodes4.LowerX=120]="LowerX",CharCodes4[CharCodes4.OpeningSquareBracket=91]="OpeningSquareBracket"})(CharCodes3||(CharCodes3={}));(function(State2){State2[State2.Text=1]="Text",State2[State2.BeforeTagName=2]="BeforeTagName",State2[State2.InTagName=3]="InTagName",State2[State2.InSelfClosingTag=4]="InSelfClosingTag",State2[State2.BeforeClosingTagName=5]="BeforeClosingTagName",State2[State2.InClosingTagName=6]="InClosingTagName",State2[State2.AfterClosingTagName=7]="AfterClosingTagName",State2[State2.BeforeAttributeName=8]="BeforeAttributeName",State2[State2.InAttributeName=9]="InAttributeName",State2[State2.AfterAttributeName=10]="AfterAttributeName",State2[State2.BeforeAttributeValue=11]="BeforeAttributeValue",State2[State2.InAttributeValueDq=12]="InAttributeValueDq",State2[State2.InAttributeValueSq=13]="InAttributeValueSq",State2[State2.InAttributeValueNq=14]="InAttributeValueNq",State2[State2.BeforeDeclaration=15]="BeforeDeclaration",State2[State2.InDeclaration=16]="InDeclaration",State2[State2.InProcessingInstruction=17]="InProcessingInstruction",State2[State2.BeforeComment=18]="BeforeComment",State2[State2.CDATASequence=19]="CDATASequence",State2[State2.InSpecialComment=20]="InSpecialComment",State2[State2.InCommentLike=21]="InCommentLike",State2[State2.BeforeSpecialS=22]="BeforeSpecialS",State2[State2.BeforeSpecialT=23]="BeforeSpecialT",State2[State2.SpecialStartSequence=24]="SpecialStartSequence",State2[State2.InSpecialTag=25]="InSpecialTag",State2[State2.InEntity=26]="InEntity"})(State||(State={}));__name(isWhitespace,"isWhitespace");__name(isEndOfTagSection,"isEndOfTagSection");__name(isASCIIAlpha,"isASCIIAlpha");(function(QuoteType2){QuoteType2[QuoteType2.NoValue=0]="NoValue",QuoteType2[QuoteType2.Unquoted=1]="Unquoted",QuoteType2[QuoteType2.Single=2]="Single",QuoteType2[QuoteType2.Double=3]="Double"})(QuoteType||(QuoteType={}));Sequences={Cdata:new Uint8Array([67,68,65,84,65,91]),CdataEnd:new Uint8Array([93,93,62]),CommentEnd:new Uint8Array([45,45,62]),ScriptEnd:new Uint8Array([60,47,115,99,114,105,112,116]),StyleEnd:new Uint8Array([60,47,115,116,121,108,101]),TitleEnd:new Uint8Array([60,47,116,105,116,108,101]),TextareaEnd:new Uint8Array([60,47,116,101,120,116,97,114,101,97]),XmpEnd:new Uint8Array([60,47,120,109,112])},Tokenizer=class{static{__name(this,"Tokenizer")}constructor({xmlMode=!1,decodeEntities=!0},cbs){this.cbs=cbs,this.state=State.Text,this.buffer="",this.sectionStart=0,this.index=0,this.entityStart=0,this.baseState=State.Text,this.isSpecial=!1,this.running=!0,this.offset=0,this.currentSequence=void 0,this.sequenceIndex=0,this.xmlMode=xmlMode,this.decodeEntities=decodeEntities,this.entityDecoder=new EntityDecoder2(xmlMode?xmlDecodeTree:htmlDecodeTree,(cp2,consumed)=>this.emitCodePoint(cp2,consumed))}reset(){this.state=State.Text,this.buffer="",this.sectionStart=0,this.index=0,this.baseState=State.Text,this.currentSequence=void 0,this.running=!0,this.offset=0}write(chunk){this.offset+=this.buffer.length,this.buffer=chunk,this.parse()}end(){this.running&&this.finish()}pause(){this.running=!1}resume(){this.running=!0,this.index<this.buffer.length+this.offset&&this.parse()}stateText(c2){c2===CharCodes3.Lt||!this.decodeEntities&&this.fastForwardTo(CharCodes3.Lt)?(this.index>this.sectionStart&&this.cbs.ontext(this.sectionStart,this.index),this.state=State.BeforeTagName,this.sectionStart=this.index):this.decodeEntities&&c2===CharCodes3.Amp&&this.startEntity()}stateSpecialStartSequence(c2){let isEnd=this.sequenceIndex===this.currentSequence.length;if(!(isEnd?isEndOfTagSection(c2):(c2|32)===this.currentSequence[this.sequenceIndex]))this.isSpecial=!1;else if(!isEnd){this.sequenceIndex++;return}this.sequenceIndex=0,this.state=State.InTagName,this.stateInTagName(c2)}stateInSpecialTag(c2){if(this.sequenceIndex===this.currentSequence.length){if(c2===CharCodes3.Gt||isWhitespace(c2)){let endOfText=this.index-this.currentSequence.length;if(this.sectionStart<endOfText){let actualIndex=this.index;this.index=endOfText,this.cbs.ontext(this.sectionStart,endOfText),this.index=actualIndex}this.isSpecial=!1,this.sectionStart=endOfText+2,this.stateInClosingTagName(c2);return}this.sequenceIndex=0}(c2|32)===this.currentSequence[this.sequenceIndex]?this.sequenceIndex+=1:this.sequenceIndex===0?this.currentSequence===Sequences.TitleEnd?this.decodeEntities&&c2===CharCodes3.Amp&&this.startEntity():this.fastForwardTo(CharCodes3.Lt)&&(this.sequenceIndex=1):this.sequenceIndex=+(c2===CharCodes3.Lt)}stateCDATASequence(c2){c2===Sequences.Cdata[this.sequenceIndex]?++this.sequenceIndex===Sequences.Cdata.length&&(this.state=State.InCommentLike,this.currentSequence=Sequences.CdataEnd,this.sequenceIndex=0,this.sectionStart=this.index+1):(this.sequenceIndex=0,this.state=State.InDeclaration,this.stateInDeclaration(c2))}fastForwardTo(c2){for(;++this.index<this.buffer.length+this.offset;)if(this.buffer.charCodeAt(this.index-this.offset)===c2)return!0;return this.index=this.buffer.length+this.offset-1,!1}stateInCommentLike(c2){c2===this.currentSequence[this.sequenceIndex]?++this.sequenceIndex===this.currentSequence.length&&(this.currentSequence===Sequences.CdataEnd?this.cbs.oncdata(this.sectionStart,this.index,2):this.cbs.oncomment(this.sectionStart,this.index,2),this.sequenceIndex=0,this.sectionStart=this.index+1,this.state=State.Text):this.sequenceIndex===0?this.fastForwardTo(this.currentSequence[0])&&(this.sequenceIndex=1):c2!==this.currentSequence[this.sequenceIndex-1]&&(this.sequenceIndex=0)}isTagStartChar(c2){return this.xmlMode?!isEndOfTagSection(c2):isASCIIAlpha(c2)}startSpecial(sequence,offset){this.isSpecial=!0,this.currentSequence=sequence,this.sequenceIndex=offset,this.state=State.SpecialStartSequence}stateBeforeTagName(c2){if(c2===CharCodes3.ExclamationMark)this.state=State.BeforeDeclaration,this.sectionStart=this.index+1;else if(c2===CharCodes3.Questionmark)this.state=State.InProcessingInstruction,this.sectionStart=this.index+1;else if(this.isTagStartChar(c2)){let lower=c2|32;this.sectionStart=this.index,this.xmlMode?this.state=State.InTagName:lower===Sequences.ScriptEnd[2]?this.state=State.BeforeSpecialS:lower===Sequences.TitleEnd[2]||lower===Sequences.XmpEnd[2]?this.state=State.BeforeSpecialT:this.state=State.InTagName}else c2===CharCodes3.Slash?this.state=State.BeforeClosingTagName:(this.state=State.Text,this.stateText(c2))}stateInTagName(c2){isEndOfTagSection(c2)&&(this.cbs.onopentagname(this.sectionStart,this.index),this.sectionStart=-1,this.state=State.BeforeAttributeName,this.stateBeforeAttributeName(c2))}stateBeforeClosingTagName(c2){isWhitespace(c2)||(c2===CharCodes3.Gt?this.state=State.Text:(this.state=this.isTagStartChar(c2)?State.InClosingTagName:State.InSpecialComment,this.sectionStart=this.index))}stateInClosingTagName(c2){(c2===CharCodes3.Gt||isWhitespace(c2))&&(this.cbs.onclosetag(this.sectionStart,this.index),this.sectionStart=-1,this.state=State.AfterClosingTagName,this.stateAfterClosingTagName(c2))}stateAfterClosingTagName(c2){(c2===CharCodes3.Gt||this.fastForwardTo(CharCodes3.Gt))&&(this.state=State.Text,this.sectionStart=this.index+1)}stateBeforeAttributeName(c2){c2===CharCodes3.Gt?(this.cbs.onopentagend(this.index),this.isSpecial?(this.state=State.InSpecialTag,this.sequenceIndex=0):this.state=State.Text,this.sectionStart=this.index+1):c2===CharCodes3.Slash?this.state=State.InSelfClosingTag:isWhitespace(c2)||(this.state=State.InAttributeName,this.sectionStart=this.index)}stateInSelfClosingTag(c2){c2===CharCodes3.Gt?(this.cbs.onselfclosingtag(this.index),this.state=State.Text,this.sectionStart=this.index+1,this.isSpecial=!1):isWhitespace(c2)||(this.state=State.BeforeAttributeName,this.stateBeforeAttributeName(c2))}stateInAttributeName(c2){(c2===CharCodes3.Eq||isEndOfTagSection(c2))&&(this.cbs.onattribname(this.sectionStart,this.index),this.sectionStart=this.index,this.state=State.AfterAttributeName,this.stateAfterAttributeName(c2))}stateAfterAttributeName(c2){c2===CharCodes3.Eq?this.state=State.BeforeAttributeValue:c2===CharCodes3.Slash||c2===CharCodes3.Gt?(this.cbs.onattribend(QuoteType.NoValue,this.sectionStart),this.sectionStart=-1,this.state=State.BeforeAttributeName,this.stateBeforeAttributeName(c2)):isWhitespace(c2)||(this.cbs.onattribend(QuoteType.NoValue,this.sectionStart),this.state=State.InAttributeName,this.sectionStart=this.index)}stateBeforeAttributeValue(c2){c2===CharCodes3.DoubleQuote?(this.state=State.InAttributeValueDq,this.sectionStart=this.index+1):c2===CharCodes3.SingleQuote?(this.state=State.InAttributeValueSq,this.sectionStart=this.index+1):isWhitespace(c2)||(this.sectionStart=this.index,this.state=State.InAttributeValueNq,this.stateInAttributeValueNoQuotes(c2))}handleInAttributeValue(c2,quote2){c2===quote2||!this.decodeEntities&&this.fastForwardTo(quote2)?(this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(quote2===CharCodes3.DoubleQuote?QuoteType.Double:QuoteType.Single,this.index+1),this.state=State.BeforeAttributeName):this.decodeEntities&&c2===CharCodes3.Amp&&this.startEntity()}stateInAttributeValueDoubleQuotes(c2){this.handleInAttributeValue(c2,CharCodes3.DoubleQuote)}stateInAttributeValueSingleQuotes(c2){this.handleInAttributeValue(c2,CharCodes3.SingleQuote)}stateInAttributeValueNoQuotes(c2){isWhitespace(c2)||c2===CharCodes3.Gt?(this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=-1,this.cbs.onattribend(QuoteType.Unquoted,this.index),this.state=State.BeforeAttributeName,this.stateBeforeAttributeName(c2)):this.decodeEntities&&c2===CharCodes3.Amp&&this.startEntity()}stateBeforeDeclaration(c2){c2===CharCodes3.OpeningSquareBracket?(this.state=State.CDATASequence,this.sequenceIndex=0):this.state=c2===CharCodes3.Dash?State.BeforeComment:State.InDeclaration}stateInDeclaration(c2){(c2===CharCodes3.Gt||this.fastForwardTo(CharCodes3.Gt))&&(this.cbs.ondeclaration(this.sectionStart,this.index),this.state=State.Text,this.sectionStart=this.index+1)}stateInProcessingInstruction(c2){(c2===CharCodes3.Gt||this.fastForwardTo(CharCodes3.Gt))&&(this.cbs.onprocessinginstruction(this.sectionStart,this.index),this.state=State.Text,this.sectionStart=this.index+1)}stateBeforeComment(c2){c2===CharCodes3.Dash?(this.state=State.InCommentLike,this.currentSequence=Sequences.CommentEnd,this.sequenceIndex=2,this.sectionStart=this.index+1):this.state=State.InDeclaration}stateInSpecialComment(c2){(c2===CharCodes3.Gt||this.fastForwardTo(CharCodes3.Gt))&&(this.cbs.oncomment(this.sectionStart,this.index,0),this.state=State.Text,this.sectionStart=this.index+1)}stateBeforeSpecialS(c2){let lower=c2|32;lower===Sequences.ScriptEnd[3]?this.startSpecial(Sequences.ScriptEnd,4):lower===Sequences.StyleEnd[3]?this.startSpecial(Sequences.StyleEnd,4):(this.state=State.InTagName,this.stateInTagName(c2))}stateBeforeSpecialT(c2){switch(c2|32){case Sequences.TitleEnd[3]:{this.startSpecial(Sequences.TitleEnd,4);break}case Sequences.TextareaEnd[3]:{this.startSpecial(Sequences.TextareaEnd,4);break}case Sequences.XmpEnd[3]:{this.startSpecial(Sequences.XmpEnd,4);break}default:this.state=State.InTagName,this.stateInTagName(c2)}}startEntity(){this.baseState=this.state,this.state=State.InEntity,this.entityStart=this.index,this.entityDecoder.startEntity(this.xmlMode?DecodingMode2.Strict:this.baseState===State.Text||this.baseState===State.InSpecialTag?DecodingMode2.Legacy:DecodingMode2.Attribute)}stateInEntity(){let indexInBuffer=this.index-this.offset,length=this.entityDecoder.write(this.buffer,indexInBuffer);if(length>=0)this.state=this.baseState,length===0&&(this.index-=1);else{if(indexInBuffer<this.buffer.length&&this.buffer.charCodeAt(indexInBuffer)===CharCodes3.Amp){this.state=this.baseState,this.index-=1;return}this.index=this.offset+this.buffer.length-1}}cleanup(){this.running&&this.sectionStart!==this.index&&(this.state===State.Text||this.state===State.InSpecialTag&&this.sequenceIndex===0?(this.cbs.ontext(this.sectionStart,this.index),this.sectionStart=this.index):(this.state===State.InAttributeValueDq||this.state===State.InAttributeValueSq||this.state===State.InAttributeValueNq)&&(this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=this.index))}shouldContinue(){return this.index<this.buffer.length+this.offset&&this.running}parse(){for(;this.shouldContinue();){let c2=this.buffer.charCodeAt(this.index-this.offset);switch(this.state){case State.Text:{this.stateText(c2);break}case State.SpecialStartSequence:{this.stateSpecialStartSequence(c2);break}case State.InSpecialTag:{this.stateInSpecialTag(c2);break}case State.CDATASequence:{this.stateCDATASequence(c2);break}case State.InAttributeValueDq:{this.stateInAttributeValueDoubleQuotes(c2);break}case State.InAttributeName:{this.stateInAttributeName(c2);break}case State.InCommentLike:{this.stateInCommentLike(c2);break}case State.InSpecialComment:{this.stateInSpecialComment(c2);break}case State.BeforeAttributeName:{this.stateBeforeAttributeName(c2);break}case State.InTagName:{this.stateInTagName(c2);break}case State.InClosingTagName:{this.stateInClosingTagName(c2);break}case State.BeforeTagName:{this.stateBeforeTagName(c2);break}case State.AfterAttributeName:{this.stateAfterAttributeName(c2);break}case State.InAttributeValueSq:{this.stateInAttributeValueSingleQuotes(c2);break}case State.BeforeAttributeValue:{this.stateBeforeAttributeValue(c2);break}case State.BeforeClosingTagName:{this.stateBeforeClosingTagName(c2);break}case State.AfterClosingTagName:{this.stateAfterClosingTagName(c2);break}case State.BeforeSpecialS:{this.stateBeforeSpecialS(c2);break}case State.BeforeSpecialT:{this.stateBeforeSpecialT(c2);break}case State.InAttributeValueNq:{this.stateInAttributeValueNoQuotes(c2);break}case State.InSelfClosingTag:{this.stateInSelfClosingTag(c2);break}case State.InDeclaration:{this.stateInDeclaration(c2);break}case State.BeforeDeclaration:{this.stateBeforeDeclaration(c2);break}case State.BeforeComment:{this.stateBeforeComment(c2);break}case State.InProcessingInstruction:{this.stateInProcessingInstruction(c2);break}case State.InEntity:{this.stateInEntity();break}}this.index++}this.cleanup()}finish(){this.state===State.InEntity&&(this.entityDecoder.end(),this.state=this.baseState),this.handleTrailingData(),this.cbs.onend()}handleTrailingData(){let endIndex=this.buffer.length+this.offset;this.sectionStart>=endIndex||(this.state===State.InCommentLike?this.currentSequence===Sequences.CdataEnd?this.cbs.oncdata(this.sectionStart,endIndex,0):this.cbs.oncomment(this.sectionStart,endIndex,0):this.state===State.InTagName||this.state===State.BeforeAttributeName||this.state===State.BeforeAttributeValue||this.state===State.AfterAttributeName||this.state===State.InAttributeName||this.state===State.InAttributeValueSq||this.state===State.InAttributeValueDq||this.state===State.InAttributeValueNq||this.state===State.InClosingTagName||this.cbs.ontext(this.sectionStart,endIndex))}emitCodePoint(cp2,consumed){this.baseState!==State.Text&&this.baseState!==State.InSpecialTag?(this.sectionStart<this.entityStart&&this.cbs.onattribdata(this.sectionStart,this.entityStart),this.sectionStart=this.entityStart+consumed,this.index=this.sectionStart-1,this.cbs.onattribentity(cp2)):(this.sectionStart<this.entityStart&&this.cbs.ontext(this.sectionStart,this.entityStart),this.sectionStart=this.entityStart+consumed,this.index=this.sectionStart-1,this.cbs.ontextentity(cp2,this.sectionStart))}}}});var formTags,pTag,tableSectionTags,ddtTags,rtpTags,openImpliesClose,voidElements,foreignContextElements,htmlIntegrationElements,reNameEnd,Parser,init_Parser=__esm({"../../node_modules/.pnpm/htmlparser2@10.1.0/node_modules/htmlparser2/dist/esm/Parser.js"(){init_Tokenizer();init_decode2();formTags=new Set(["input","option","optgroup","select","button","datalist","textarea"]),pTag=new Set(["p"]),tableSectionTags=new Set(["thead","tbody"]),ddtTags=new Set(["dd","dt"]),rtpTags=new Set(["rt","rp"]),openImpliesClose=new Map([["tr",new Set(["tr","th","td"])],["th",new Set(["th"])],["td",new Set(["thead","th","td"])],["body",new Set(["head","link","script"])],["li",new Set(["li"])],["p",pTag],["h1",pTag],["h2",pTag],["h3",pTag],["h4",pTag],["h5",pTag],["h6",pTag],["select",formTags],["input",formTags],["output",formTags],["button",formTags],["datalist",formTags],["textarea",formTags],["option",new Set(["option"])],["optgroup",new Set(["optgroup","option"])],["dd",ddtTags],["dt",ddtTags],["address",pTag],["article",pTag],["aside",pTag],["blockquote",pTag],["details",pTag],["div",pTag],["dl",pTag],["fieldset",pTag],["figcaption",pTag],["figure",pTag],["footer",pTag],["form",pTag],["header",pTag],["hr",pTag],["main",pTag],["nav",pTag],["ol",pTag],["pre",pTag],["section",pTag],["table",pTag],["ul",pTag],["rt",rtpTags],["rp",rtpTags],["tbody",tableSectionTags],["tfoot",tableSectionTags]]),voidElements=new Set(["area","base","basefont","br","col","command","embed","frame","hr","img","input","isindex","keygen","link","meta","param","source","track","wbr"]),foreignContextElements=new Set(["math","svg"]),htmlIntegrationElements=new Set(["mi","mo","mn","ms","mtext","annotation-xml","foreignobject","desc","title"]),reNameEnd=/\s|\//,Parser=class{static{__name(this,"Parser")}constructor(cbs,options={}){var _a4,_b,_c,_d,_e2,_f;this.options=options,this.startIndex=0,this.endIndex=0,this.openTagStart=0,this.tagname="",this.attribname="",this.attribvalue="",this.attribs=null,this.stack=[],this.buffers=[],this.bufferOffset=0,this.writeIndex=0,this.ended=!1,this.cbs=cbs??{},this.htmlMode=!this.options.xmlMode,this.lowerCaseTagNames=(_a4=options.lowerCaseTags)!==null&&_a4!==void 0?_a4:this.htmlMode,this.lowerCaseAttributeNames=(_b=options.lowerCaseAttributeNames)!==null&&_b!==void 0?_b:this.htmlMode,this.recognizeSelfClosing=(_c=options.recognizeSelfClosing)!==null&&_c!==void 0?_c:!this.htmlMode,this.tokenizer=new((_d=options.Tokenizer)!==null&&_d!==void 0?_d:Tokenizer)(this.options,this),this.foreignContext=[!this.htmlMode],(_f=(_e2=this.cbs).onparserinit)===null||_f===void 0||_f.call(_e2,this)}ontext(start,endIndex){var _a4,_b;let data2=this.getSlice(start,endIndex);this.endIndex=endIndex-1,(_b=(_a4=this.cbs).ontext)===null||_b===void 0||_b.call(_a4,data2),this.startIndex=endIndex}ontextentity(cp2,endIndex){var _a4,_b;this.endIndex=endIndex-1,(_b=(_a4=this.cbs).ontext)===null||_b===void 0||_b.call(_a4,fromCodePoint2(cp2)),this.startIndex=endIndex}isVoidElement(name){return this.htmlMode&&voidElements.has(name)}onopentagname(start,endIndex){this.endIndex=endIndex;let name=this.getSlice(start,endIndex);this.lowerCaseTagNames&&(name=name.toLowerCase()),this.emitOpenTag(name)}emitOpenTag(name){var _a4,_b,_c,_d;this.openTagStart=this.startIndex,this.tagname=name;let impliesClose=this.htmlMode&&openImpliesClose.get(name);if(impliesClose)for(;this.stack.length>0&&impliesClose.has(this.stack[0]);){let element=this.stack.shift();(_b=(_a4=this.cbs).onclosetag)===null||_b===void 0||_b.call(_a4,element,!0)}this.isVoidElement(name)||(this.stack.unshift(name),this.htmlMode&&(foreignContextElements.has(name)?this.foreignContext.unshift(!0):htmlIntegrationElements.has(name)&&this.foreignContext.unshift(!1))),(_d=(_c=this.cbs).onopentagname)===null||_d===void 0||_d.call(_c,name),this.cbs.onopentag&&(this.attribs={})}endOpenTag(isImplied){var _a4,_b;this.startIndex=this.openTagStart,this.attribs&&((_b=(_a4=this.cbs).onopentag)===null||_b===void 0||_b.call(_a4,this.tagname,this.attribs,isImplied),this.attribs=null),this.cbs.onclosetag&&this.isVoidElement(this.tagname)&&this.cbs.onclosetag(this.tagname,!0),this.tagname=""}onopentagend(endIndex){this.endIndex=endIndex,this.endOpenTag(!1),this.startIndex=endIndex+1}onclosetag(start,endIndex){var _a4,_b,_c,_d,_e2,_f,_g,_h;this.endIndex=endIndex;let name=this.getSlice(start,endIndex);if(this.lowerCaseTagNames&&(name=name.toLowerCase()),this.htmlMode&&(foreignContextElements.has(name)||htmlIntegrationElements.has(name))&&this.foreignContext.shift(),this.isVoidElement(name))this.htmlMode&&name==="br"&&((_d=(_c=this.cbs).onopentagname)===null||_d===void 0||_d.call(_c,"br"),(_f=(_e2=this.cbs).onopentag)===null||_f===void 0||_f.call(_e2,"br",{},!0),(_h=(_g=this.cbs).onclosetag)===null||_h===void 0||_h.call(_g,"br",!1));else{let pos=this.stack.indexOf(name);if(pos!==-1)for(let index2=0;index2<=pos;index2++){let element=this.stack.shift();(_b=(_a4=this.cbs).onclosetag)===null||_b===void 0||_b.call(_a4,element,index2!==pos)}else this.htmlMode&&name==="p"&&(this.emitOpenTag("p"),this.closeCurrentTag(!0))}this.startIndex=endIndex+1}onselfclosingtag(endIndex){this.endIndex=endIndex,this.recognizeSelfClosing||this.foreignContext[0]?(this.closeCurrentTag(!1),this.startIndex=endIndex+1):this.onopentagend(endIndex)}closeCurrentTag(isOpenImplied){var _a4,_b;let name=this.tagname;this.endOpenTag(isOpenImplied),this.stack[0]===name&&((_b=(_a4=this.cbs).onclosetag)===null||_b===void 0||_b.call(_a4,name,!isOpenImplied),this.stack.shift())}onattribname(start,endIndex){this.startIndex=start;let name=this.getSlice(start,endIndex);this.attribname=this.lowerCaseAttributeNames?name.toLowerCase():name}onattribdata(start,endIndex){this.attribvalue+=this.getSlice(start,endIndex)}onattribentity(cp2){this.attribvalue+=fromCodePoint2(cp2)}onattribend(quote2,endIndex){var _a4,_b;this.endIndex=endIndex,(_b=(_a4=this.cbs).onattribute)===null||_b===void 0||_b.call(_a4,this.attribname,this.attribvalue,quote2===QuoteType.Double?'"':quote2===QuoteType.Single?"'":quote2===QuoteType.NoValue?void 0:null),this.attribs&&!Object.prototype.hasOwnProperty.call(this.attribs,this.attribname)&&(this.attribs[this.attribname]=this.attribvalue),this.attribvalue=""}getInstructionName(value){let index2=value.search(reNameEnd),name=index2<0?value:value.substr(0,index2);return this.lowerCaseTagNames&&(name=name.toLowerCase()),name}ondeclaration(start,endIndex){this.endIndex=endIndex;let value=this.getSlice(start,endIndex);if(this.cbs.onprocessinginstruction){let name=this.getInstructionName(value);this.cbs.onprocessinginstruction(`!${name}`,`!${value}`)}this.startIndex=endIndex+1}onprocessinginstruction(start,endIndex){this.endIndex=endIndex;let value=this.getSlice(start,endIndex);if(this.cbs.onprocessinginstruction){let name=this.getInstructionName(value);this.cbs.onprocessinginstruction(`?${name}`,`?${value}`)}this.startIndex=endIndex+1}oncomment(start,endIndex,offset){var _a4,_b,_c,_d;this.endIndex=endIndex,(_b=(_a4=this.cbs).oncomment)===null||_b===void 0||_b.call(_a4,this.getSlice(start,endIndex-offset)),(_d=(_c=this.cbs).oncommentend)===null||_d===void 0||_d.call(_c),this.startIndex=endIndex+1}oncdata(start,endIndex,offset){var _a4,_b,_c,_d,_e2,_f,_g,_h,_j,_k;this.endIndex=endIndex;let value=this.getSlice(start,endIndex-offset);!this.htmlMode||this.options.recognizeCDATA?((_b=(_a4=this.cbs).oncdatastart)===null||_b===void 0||_b.call(_a4),(_d=(_c=this.cbs).ontext)===null||_d===void 0||_d.call(_c,value),(_f=(_e2=this.cbs).oncdataend)===null||_f===void 0||_f.call(_e2)):((_h=(_g=this.cbs).oncomment)===null||_h===void 0||_h.call(_g,`[CDATA[${value}]]`),(_k=(_j=this.cbs).oncommentend)===null||_k===void 0||_k.call(_j)),this.startIndex=endIndex+1}onend(){var _a4,_b;if(this.cbs.onclosetag){this.endIndex=this.startIndex;for(let index2=0;index2<this.stack.length;index2++)this.cbs.onclosetag(this.stack[index2],!0)}(_b=(_a4=this.cbs).onend)===null||_b===void 0||_b.call(_a4)}reset(){var _a4,_b,_c,_d;(_b=(_a4=this.cbs).onreset)===null||_b===void 0||_b.call(_a4),this.tokenizer.reset(),this.tagname="",this.attribname="",this.attribs=null,this.stack.length=0,this.startIndex=0,this.endIndex=0,(_d=(_c=this.cbs).onparserinit)===null||_d===void 0||_d.call(_c,this),this.buffers.length=0,this.foreignContext.length=0,this.foreignContext.unshift(!this.htmlMode),this.bufferOffset=0,this.writeIndex=0,this.ended=!1}parseComplete(data2){this.reset(),this.end(data2)}getSlice(start,end2){for(;start-this.bufferOffset>=this.buffers[0].length;)this.shiftBuffer();let slice2=this.buffers[0].slice(start-this.bufferOffset,end2-this.bufferOffset);for(;end2-this.bufferOffset>this.buffers[0].length;)this.shiftBuffer(),slice2+=this.buffers[0].slice(0,end2-this.bufferOffset);return slice2}shiftBuffer(){this.bufferOffset+=this.buffers[0].length,this.writeIndex--,this.buffers.shift()}write(chunk){var _a4,_b;if(this.ended){(_b=(_a4=this.cbs).onerror)===null||_b===void 0||_b.call(_a4,new Error(".write() after done!"));return}this.buffers.push(chunk),this.tokenizer.running&&(this.tokenizer.write(chunk),this.writeIndex++)}end(chunk){var _a4,_b;if(this.ended){(_b=(_a4=this.cbs).onerror)===null||_b===void 0||_b.call(_a4,new Error(".end() after done!"));return}chunk&&this.write(chunk),this.ended=!0,this.tokenizer.end()}pause(){this.tokenizer.pause()}resume(){for(this.tokenizer.resume();this.tokenizer.running&&this.writeIndex<this.buffers.length;)this.tokenizer.write(this.buffers[this.writeIndex++]);this.ended&&this.tokenizer.end()}parseChunk(chunk){this.write(chunk)}done(chunk){this.end(chunk)}}}});function parseDocument(data2,options){let handler=new DomHandler(void 0,options);return new Parser(handler,options).end(data2),handler.root}var init_esm7=__esm({"../../node_modules/.pnpm/htmlparser2@10.1.0/node_modules/htmlparser2/dist/esm/index.js"(){init_Parser();init_Parser();init_esm3();init_esm3();init_Tokenizer();init_esm2();init_esm6();init_esm6();init_esm6();__name(parseDocument,"parseDocument")}});var attributes_exports={};__export(attributes_exports,{addClass:()=>addClass,attr:()=>attr,data:()=>data,hasClass:()=>hasClass,prop:()=>prop,removeAttr:()=>removeAttr,removeClass:()=>removeClass,toggleClass:()=>toggleClass,val:()=>val});function getAttr(elem,name,xmlMode){var _a4;if(!(!elem||!isTag2(elem))){if((_a4=elem.attribs)!==null&&_a4!==void 0||(elem.attribs={}),!name)return elem.attribs;if(hasOwn(elem.attribs,name))return!xmlMode&&rboolean.test(name)?name:elem.attribs[name];if(elem.name==="option"&&name==="value")return text(elem.children);if(elem.name==="input"&&(elem.attribs.type==="radio"||elem.attribs.type==="checkbox")&&name==="value")return"on"}}function setAttr(el,name,value){value===null?removeAttribute(el,name):el.attribs[name]=`${value}`}function attr(name,value){if(typeof name=="object"||value!==void 0){if(typeof value=="function"){if(typeof name!="string")throw new Error("Bad combination of arguments.");return domEach(this,(el,i)=>{isTag2(el)&&setAttr(el,name,value.call(el,i,el.attribs[name]))})}return domEach(this,el=>{if(isTag2(el))if(typeof name=="object")for(let objName of Object.keys(name)){let objValue=name[objName];setAttr(el,objName,objValue)}else setAttr(el,name,value)})}return arguments.length>1?this:getAttr(this[0],name,this.options.xmlMode)}function getProp(el,name,xmlMode){return name in el?el[name]:!xmlMode&&rboolean.test(name)?getAttr(el,name,!1)!==void 0:getAttr(el,name,xmlMode)}function setProp(el,name,value,xmlMode){name in el?el[name]=value:setAttr(el,name,!xmlMode&&rboolean.test(name)?value?"":null:`${value}`)}function prop(name,value){var _a4;if(typeof name=="string"&&value===void 0){let el=this[0];if(!el)return;switch(name){case"style":{let property=this.css(),keys=Object.keys(property);for(let i=0;i<keys.length;i++)property[i]=keys[i];return property.length=keys.length,property}case"tagName":case"nodeName":return isTag2(el)?el.name.toUpperCase():void 0;case"href":case"src":{if(!isTag2(el))return;let prop2=(_a4=el.attribs)===null||_a4===void 0?void 0:_a4[name];return typeof URL<"u"&&(name==="href"&&(el.tagName==="a"||el.tagName==="link")||name==="src"&&(el.tagName==="img"||el.tagName==="iframe"||el.tagName==="audio"||el.tagName==="video"||el.tagName==="source"))&&prop2!==void 0&&this.options.baseURI?new URL(prop2,this.options.baseURI).href:prop2}case"innerText":return innerText(el);case"textContent":return textContent(el);case"outerHTML":return el.type===esm_exports.Root?this.html():this.clone().wrap("<container />").parent().html();case"innerHTML":return this.html();default:return isTag2(el)?getProp(el,name,this.options.xmlMode):void 0}}if(typeof name=="object"||value!==void 0){if(typeof value=="function"){if(typeof name=="object")throw new TypeError("Bad combination of arguments.");return domEach(this,(el,i)=>{isTag2(el)&&setProp(el,name,value.call(el,i,getProp(el,name,this.options.xmlMode)),this.options.xmlMode)})}return domEach(this,el=>{if(isTag2(el))if(typeof name=="object")for(let key of Object.keys(name)){let val2=name[key];setProp(el,key,val2,this.options.xmlMode)}else setProp(el,name,value,this.options.xmlMode)})}}function setData(elem,name,value){var _a4;(_a4=elem.data)!==null&&_a4!==void 0||(elem.data={}),typeof name=="object"?Object.assign(elem.data,name):typeof name=="string"&&value!==void 0&&(elem.data[name]=value)}function readAllData(el){for(let domName of Object.keys(el.attribs)){if(!domName.startsWith(dataAttrPrefix))continue;let jsName=camelCase(domName.slice(dataAttrPrefix.length));hasOwn(el.data,jsName)||(el.data[jsName]=parseDataValue(el.attribs[domName]))}return el.data}function readData(el,name){let domName=dataAttrPrefix+cssCase(name),data2=el.data;if(hasOwn(data2,name))return data2[name];if(hasOwn(el.attribs,domName))return data2[name]=parseDataValue(el.attribs[domName])}function parseDataValue(value){if(value==="null")return null;if(value==="true")return!0;if(value==="false")return!1;let num=Number(value);if(value===String(num))return num;if(rbrace.test(value))try{return JSON.parse(value)}catch{}return value}function data(name,value){var _a4;let elem=this[0];if(!elem||!isTag2(elem))return;let dataEl=elem;return(_a4=dataEl.data)!==null&&_a4!==void 0||(dataEl.data={}),name==null?readAllData(dataEl):typeof name=="object"||value!==void 0?(domEach(this,el=>{isTag2(el)&&(typeof name=="object"?setData(el,name):setData(el,name,value))}),this):readData(dataEl,name)}function val(value){let querying=arguments.length===0,element=this[0];if(!element||!isTag2(element))return querying?void 0:this;switch(element.name){case"textarea":return this.text(value);case"select":{let option=this.find("option:selected");if(!querying){if(this.attr("multiple")==null&&typeof value=="object")return this;this.find("option").removeAttr("selected");let values=typeof value=="object"?value:[value];for(let val2 of values)this.find(`option[value="${val2}"]`).attr("selected","");return this}return this.attr("multiple")?option.toArray().map(el=>text(el.children)):option.attr("value")}case"button":case"input":case"option":return querying?this.attr("value"):this.attr("value",value)}}function removeAttribute(elem,name){!elem.attribs||!hasOwn(elem.attribs,name)||delete elem.attribs[name]}function splitNames(names){return names?names.trim().split(rspace):[]}function removeAttr(name){let attrNames=splitNames(name);for(let attrName of attrNames)domEach(this,elem=>{isTag2(elem)&&removeAttribute(elem,attrName)});return this}function hasClass(className){return this.toArray().some(elem=>{let clazz=isTag2(elem)&&elem.attribs.class,idx=-1;if(clazz&&className.length>0)for(;(idx=clazz.indexOf(className,idx+1))>-1;){let end2=idx+className.length;if((idx===0||rspace.test(clazz[idx-1]))&&(end2===clazz.length||rspace.test(clazz[end2])))return!0}return!1})}function addClass(value){if(typeof value=="function")return domEach(this,(el,i)=>{if(isTag2(el)){let className=el.attribs.class||"";addClass.call([el],value.call(el,i,className))}});if(!value||typeof value!="string")return this;let classNames=value.split(rspace),numElements=this.length;for(let i=0;i<numElements;i++){let el=this[i];if(!isTag2(el))continue;let className=getAttr(el,"class",!1);if(className){let setClass=` ${className} `;for(let cn of classNames){let appendClass=`${cn} `;setClass.includes(` ${appendClass}`)||(setClass+=appendClass)}setAttr(el,"class",setClass.trim())}else setAttr(el,"class",classNames.join(" ").trim())}return this}function removeClass(name){if(typeof name=="function")return domEach(this,(el,i)=>{isTag2(el)&&removeClass.call([el],name.call(el,i,el.attribs.class||""))});let classes=splitNames(name),numClasses=classes.length,removeAll=arguments.length===0;return domEach(this,el=>{if(isTag2(el))if(removeAll)el.attribs.class="";else{let elClasses=splitNames(el.attribs.class),changed=!1;for(let j2=0;j2<numClasses;j2++){let index2=elClasses.indexOf(classes[j2]);index2!==-1&&(elClasses.splice(index2,1),changed=!0,j2--)}changed&&(el.attribs.class=elClasses.join(" "))}})}function toggleClass(value,stateVal){if(typeof value=="function")return domEach(this,(el,i)=>{isTag2(el)&&toggleClass.call([el],value.call(el,i,el.attribs.class||"",stateVal),stateVal)});if(!value||typeof value!="string")return this;let classNames=value.split(rspace),numClasses=classNames.length,state=typeof stateVal=="boolean"?stateVal?1:-1:0,numElements=this.length;for(let i=0;i<numElements;i++){let el=this[i];if(!isTag2(el))continue;let elementClasses=splitNames(el.attribs.class);for(let j2=0;j2<numClasses;j2++){let index2=elementClasses.indexOf(classNames[j2]);state>=0&&index2===-1?elementClasses.push(classNames[j2]):state<=0&&index2!==-1&&elementClasses.splice(index2,1)}el.attribs.class=elementClasses.join(" ")}return this}var _a3,hasOwn,rspace,dataAttrPrefix,rboolean,rbrace,init_attributes=__esm({"../../node_modules/.pnpm/cheerio@1.2.0/node_modules/cheerio/dist/esm/api/attributes.js"(){init_static();init_utils2();init_esm3();init_esm6();init_esm7();hasOwn=(_a3=Object.hasOwn)!==null&&_a3!==void 0?_a3:((object,prop2)=>Object.prototype.hasOwnProperty.call(object,prop2)),rspace=/\s+/,dataAttrPrefix="data-",rboolean=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,rbrace=/^{[^]*}$|^\[[^]*]$/;__name(getAttr,"getAttr");__name(setAttr,"setAttr");__name(attr,"attr");__name(getProp,"getProp");__name(setProp,"setProp");__name(prop,"prop");__name(setData,"setData");__name(readAllData,"readAllData");__name(readData,"readData");__name(parseDataValue,"parseDataValue");__name(data,"data");__name(val,"val");__name(removeAttribute,"removeAttribute");__name(splitNames,"splitNames");__name(removeAttr,"removeAttr");__name(hasClass,"hasClass");__name(addClass,"addClass");__name(removeClass,"removeClass");__name(toggleClass,"toggleClass")}});var SelectorType,AttributeAction,init_types2=__esm({"../../node_modules/.pnpm/css-what@6.2.2/node_modules/css-what/lib/es/types.js"(){(function(SelectorType2){SelectorType2.Attribute="attribute",SelectorType2.Pseudo="pseudo",SelectorType2.PseudoElement="pseudo-element",SelectorType2.Tag="tag",SelectorType2.Universal="universal",SelectorType2.Adjacent="adjacent",SelectorType2.Child="child",SelectorType2.Descendant="descendant",SelectorType2.Parent="parent",SelectorType2.Sibling="sibling",SelectorType2.ColumnCombinator="column-combinator"})(SelectorType||(SelectorType={}));(function(AttributeAction2){AttributeAction2.Any="any",AttributeAction2.Element="element",AttributeAction2.End="end",AttributeAction2.Equals="equals",AttributeAction2.Exists="exists",AttributeAction2.Hyphen="hyphen",AttributeAction2.Not="not",AttributeAction2.Start="start"})(AttributeAction||(AttributeAction={}))}});function isTraversal(selector){switch(selector.type){case SelectorType.Adjacent:case SelectorType.Child:case SelectorType.Descendant:case SelectorType.Parent:case SelectorType.Sibling:case SelectorType.ColumnCombinator:return!0;default:return!1}}function funescape(_,escaped,escapedWhitespace){let high=parseInt(escaped,16)-65536;return high!==high||escapedWhitespace?escaped:high<0?String.fromCharCode(high+65536):String.fromCharCode(high>>10|55296,high&1023|56320)}function unescapeCSS(str){return str.replace(reEscape,funescape)}function isQuote(c2){return c2===39||c2===34}function isWhitespace2(c2){return c2===32||c2===9||c2===10||c2===12||c2===13}function parse9(selector){let subselects2=[],endIndex=parseSelector(subselects2,`${selector}`,0);if(endIndex<selector.length)throw new Error(`Unmatched selector: ${selector.slice(endIndex)}`);return subselects2}function parseSelector(subselects2,selector,selectorIndex){let tokens=[];function getName2(offset){let match=selector.slice(selectorIndex+offset).match(reName);if(!match)throw new Error(`Expected name, found ${selector.slice(selectorIndex)}`);let[name]=match;return selectorIndex+=offset+name.length,unescapeCSS(name)}__name(getName2,"getName");function stripWhitespace(offset){for(selectorIndex+=offset;selectorIndex<selector.length&&isWhitespace2(selector.charCodeAt(selectorIndex));)selectorIndex++}__name(stripWhitespace,"stripWhitespace");function readValueWithParenthesis(){selectorIndex+=1;let start=selectorIndex,counter=1;for(;counter>0&&selectorIndex<selector.length;selectorIndex++)selector.charCodeAt(selectorIndex)===40&&!isEscaped(selectorIndex)?counter++:selector.charCodeAt(selectorIndex)===41&&!isEscaped(selectorIndex)&&counter--;if(counter)throw new Error("Parenthesis not matched");return unescapeCSS(selector.slice(start,selectorIndex-1))}__name(readValueWithParenthesis,"readValueWithParenthesis");function isEscaped(pos){let slashCount=0;for(;selector.charCodeAt(--pos)===92;)slashCount++;return(slashCount&1)===1}__name(isEscaped,"isEscaped");function ensureNotTraversal(){if(tokens.length>0&&isTraversal(tokens[tokens.length-1]))throw new Error("Did not expect successive traversals.")}__name(ensureNotTraversal,"ensureNotTraversal");function addTraversal(type){if(tokens.length>0&&tokens[tokens.length-1].type===SelectorType.Descendant){tokens[tokens.length-1].type=type;return}ensureNotTraversal(),tokens.push({type})}__name(addTraversal,"addTraversal");function addSpecialAttribute(name,action){tokens.push({type:SelectorType.Attribute,name,action,value:getName2(1),namespace:null,ignoreCase:"quirks"})}__name(addSpecialAttribute,"addSpecialAttribute");function finalizeSubselector(){if(tokens.length&&tokens[tokens.length-1].type===SelectorType.Descendant&&tokens.pop(),tokens.length===0)throw new Error("Empty sub-selector");subselects2.push(tokens)}if(__name(finalizeSubselector,"finalizeSubselector"),stripWhitespace(0),selector.length===selectorIndex)return selectorIndex;loop:for(;selectorIndex<selector.length;){let firstChar=selector.charCodeAt(selectorIndex);switch(firstChar){case 32:case 9:case 10:case 12:case 13:{(tokens.length===0||tokens[0].type!==SelectorType.Descendant)&&(ensureNotTraversal(),tokens.push({type:SelectorType.Descendant})),stripWhitespace(1);break}case 62:{addTraversal(SelectorType.Child),stripWhitespace(1);break}case 60:{addTraversal(SelectorType.Parent),stripWhitespace(1);break}case 126:{addTraversal(SelectorType.Sibling),stripWhitespace(1);break}case 43:{addTraversal(SelectorType.Adjacent),stripWhitespace(1);break}case 46:{addSpecialAttribute("class",AttributeAction.Element);break}case 35:{addSpecialAttribute("id",AttributeAction.Equals);break}case 91:{stripWhitespace(1);let name,namespace=null;selector.charCodeAt(selectorIndex)===124?name=getName2(1):selector.startsWith("*|",selectorIndex)?(namespace="*",name=getName2(2)):(name=getName2(0),selector.charCodeAt(selectorIndex)===124&&selector.charCodeAt(selectorIndex+1)!==61&&(namespace=name,name=getName2(1))),stripWhitespace(0);let action=AttributeAction.Exists,possibleAction=actionTypes.get(selector.charCodeAt(selectorIndex));if(possibleAction){if(action=possibleAction,selector.charCodeAt(selectorIndex+1)!==61)throw new Error("Expected `=`");stripWhitespace(2)}else selector.charCodeAt(selectorIndex)===61&&(action=AttributeAction.Equals,stripWhitespace(1));let value="",ignoreCase=null;if(action!=="exists"){if(isQuote(selector.charCodeAt(selectorIndex))){let quote2=selector.charCodeAt(selectorIndex),sectionEnd=selectorIndex+1;for(;sectionEnd<selector.length&&(selector.charCodeAt(sectionEnd)!==quote2||isEscaped(sectionEnd));)sectionEnd+=1;if(selector.charCodeAt(sectionEnd)!==quote2)throw new Error("Attribute value didn't end");value=unescapeCSS(selector.slice(selectorIndex+1,sectionEnd)),selectorIndex=sectionEnd+1}else{let valueStart=selectorIndex;for(;selectorIndex<selector.length&&(!isWhitespace2(selector.charCodeAt(selectorIndex))&&selector.charCodeAt(selectorIndex)!==93||isEscaped(selectorIndex));)selectorIndex+=1;value=unescapeCSS(selector.slice(valueStart,selectorIndex))}stripWhitespace(0);let forceIgnore=selector.charCodeAt(selectorIndex)|32;forceIgnore===115?(ignoreCase=!1,stripWhitespace(1)):forceIgnore===105&&(ignoreCase=!0,stripWhitespace(1))}if(selector.charCodeAt(selectorIndex)!==93)throw new Error("Attribute selector didn't terminate");selectorIndex+=1;let attributeSelector={type:SelectorType.Attribute,name,action,value,namespace,ignoreCase};tokens.push(attributeSelector);break}case 58:{if(selector.charCodeAt(selectorIndex+1)===58){tokens.push({type:SelectorType.PseudoElement,name:getName2(2).toLowerCase(),data:selector.charCodeAt(selectorIndex)===40?readValueWithParenthesis():null});continue}let name=getName2(1).toLowerCase(),data2=null;if(selector.charCodeAt(selectorIndex)===40)if(unpackPseudos.has(name)){if(isQuote(selector.charCodeAt(selectorIndex+1)))throw new Error(`Pseudo-selector ${name} cannot be quoted`);if(data2=[],selectorIndex=parseSelector(data2,selector,selectorIndex+1),selector.charCodeAt(selectorIndex)!==41)throw new Error(`Missing closing parenthesis in :${name} (${selector})`);selectorIndex+=1}else{if(data2=readValueWithParenthesis(),stripQuotesFromPseudos.has(name)){let quot=data2.charCodeAt(0);quot===data2.charCodeAt(data2.length-1)&&isQuote(quot)&&(data2=data2.slice(1,-1))}data2=unescapeCSS(data2)}tokens.push({type:SelectorType.Pseudo,name,data:data2});break}case 44:{finalizeSubselector(),tokens=[],stripWhitespace(1);break}default:{if(selector.startsWith("/*",selectorIndex)){let endIndex=selector.indexOf("*/",selectorIndex+2);if(endIndex<0)throw new Error("Comment was not terminated");selectorIndex=endIndex+2,tokens.length===0&&stripWhitespace(0);break}let namespace=null,name;if(firstChar===42)selectorIndex+=1,name="*";else if(firstChar===124){if(name="",selector.charCodeAt(selectorIndex+1)===124){addTraversal(SelectorType.ColumnCombinator),stripWhitespace(2);break}}else if(reName.test(selector.slice(selectorIndex)))name=getName2(0);else break loop;selector.charCodeAt(selectorIndex)===124&&selector.charCodeAt(selectorIndex+1)!==124&&(namespace=name,selector.charCodeAt(selectorIndex+1)===42?(name="*",selectorIndex+=2):name=getName2(1)),tokens.push(name==="*"?{type:SelectorType.Universal,namespace}:{type:SelectorType.Tag,name,namespace})}}}return finalizeSubselector(),selectorIndex}var reName,reEscape,actionTypes,unpackPseudos,stripQuotesFromPseudos,init_parse=__esm({"../../node_modules/.pnpm/css-what@6.2.2/node_modules/css-what/lib/es/parse.js"(){init_types2();reName=/^[^\\#]?(?:\\(?:[\da-f]{1,6}\s?|.)|[\w\-\u00b0-\uFFFF])+/,reEscape=/\\([\da-f]{1,6}\s?|(\s)|.)/gi,actionTypes=new Map([[126,AttributeAction.Element],[94,AttributeAction.Start],[36,AttributeAction.End],[42,AttributeAction.Any],[33,AttributeAction.Not],[124,AttributeAction.Hyphen]]),unpackPseudos=new Set(["has","not","matches","is","where","host","host-context"]);__name(isTraversal,"isTraversal");stripQuotesFromPseudos=new Set(["contains","icontains"]);__name(funescape,"funescape");__name(unescapeCSS,"unescapeCSS");__name(isQuote,"isQuote");__name(isWhitespace2,"isWhitespace");__name(parse9,"parse");__name(parseSelector,"parseSelector")}});var init_es=__esm({"../../node_modules/.pnpm/css-what@6.2.2/node_modules/css-what/lib/es/index.js"(){init_types2();init_parse()}});var require_boolbase=__commonJS({"../../node_modules/.pnpm/boolbase@1.0.0/node_modules/boolbase/index.js"(exports2,module2){module2.exports={trueFunc:__name(function(){return!0},"trueFunc"),falseFunc:__name(function(){return!1},"falseFunc")}}});function isTraversal2(token){return!procedure.has(token.type)}function sortByProcedure(arr){let procs=arr.map(getProcedure);for(let i=1;i<arr.length;i++){let procNew=procs[i];if(!(procNew<0))for(let j2=i-1;j2>=0&&procNew<procs[j2];j2--){let token=arr[j2+1];arr[j2+1]=arr[j2],arr[j2]=token,procs[j2+1]=procs[j2],procs[j2]=procNew}}}function getProcedure(token){var _a4,_b;let proc=(_a4=procedure.get(token.type))!==null&&_a4!==void 0?_a4:-1;return token.type===SelectorType.Attribute?(proc=(_b=attributes.get(token.action))!==null&&_b!==void 0?_b:4,token.action===AttributeAction.Equals&&token.name==="id"&&(proc=9),token.ignoreCase&&(proc>>=1)):token.type===SelectorType.Pseudo&&(token.data?token.name==="has"||token.name==="contains"?proc=0:Array.isArray(token.data)?(proc=Math.min(...token.data.map(d3=>Math.min(...d3.map(getProcedure)))),proc<0&&(proc=0)):proc=2:proc=3),proc}var procedure,attributes,init_sort=__esm({"../../node_modules/.pnpm/css-select@5.2.2/node_modules/css-select/lib/esm/sort.js"(){init_es();procedure=new Map([[SelectorType.Universal,50],[SelectorType.Tag,30],[SelectorType.Attribute,1],[SelectorType.Pseudo,0]]);__name(isTraversal2,"isTraversal");attributes=new Map([[AttributeAction.Exists,10],[AttributeAction.Equals,8],[AttributeAction.Not,7],[AttributeAction.Start,6],[AttributeAction.End,6],[AttributeAction.Any,5]]);__name(sortByProcedure,"sortByProcedure");__name(getProcedure,"getProcedure")}});function escapeRegex2(value){return value.replace(reChars,"\\$&")}function shouldIgnoreCase(selector,options){return typeof selector.ignoreCase=="boolean"?selector.ignoreCase:selector.ignoreCase==="quirks"?!!options.quirksMode:!options.xmlMode&&caseInsensitiveAttributes.has(selector.name)}var import_boolbase,reChars,caseInsensitiveAttributes,attributeRules,init_attributes2=__esm({"../../node_modules/.pnpm/css-select@5.2.2/node_modules/css-select/lib/esm/attributes.js"(){import_boolbase=__toESM(require_boolbase(),1),reChars=/[-[\]{}()*+?.,\\^$|#\s]/g;__name(escapeRegex2,"escapeRegex");caseInsensitiveAttributes=new Set(["accept","accept-charset","align","alink","axis","bgcolor","charset","checked","clear","codetype","color","compact","declare","defer","dir","direction","disabled","enctype","face","frame","hreflang","http-equiv","lang","language","link","media","method","multiple","nohref","noresize","noshade","nowrap","readonly","rel","rev","rules","scope","scrolling","selected","shape","target","text","type","valign","valuetype","vlink"]);__name(shouldIgnoreCase,"shouldIgnoreCase");attributeRules={equals(next2,data2,options){let{adapter}=options,{name}=data2,{value}=data2;return shouldIgnoreCase(data2,options)?(value=value.toLowerCase(),elem=>{let attr2=adapter.getAttributeValue(elem,name);return attr2!=null&&attr2.length===value.length&&attr2.toLowerCase()===value&&next2(elem)}):elem=>adapter.getAttributeValue(elem,name)===value&&next2(elem)},hyphen(next2,data2,options){let{adapter}=options,{name}=data2,{value}=data2,len=value.length;return shouldIgnoreCase(data2,options)?(value=value.toLowerCase(),__name(function(elem){let attr2=adapter.getAttributeValue(elem,name);return attr2!=null&&(attr2.length===len||attr2.charAt(len)==="-")&&attr2.substr(0,len).toLowerCase()===value&&next2(elem)},"hyphenIC")):__name(function(elem){let attr2=adapter.getAttributeValue(elem,name);return attr2!=null&&(attr2.length===len||attr2.charAt(len)==="-")&&attr2.substr(0,len)===value&&next2(elem)},"hyphen")},element(next2,data2,options){let{adapter}=options,{name,value}=data2;if(/\s/.test(value))return import_boolbase.default.falseFunc;let regex=new RegExp(`(?:^|\\s)${escapeRegex2(value)}(?:$|\\s)`,shouldIgnoreCase(data2,options)?"i":"");return __name(function(elem){let attr2=adapter.getAttributeValue(elem,name);return attr2!=null&&attr2.length>=value.length&&regex.test(attr2)&&next2(elem)},"element")},exists(next2,{name},{adapter}){return elem=>adapter.hasAttrib(elem,name)&&next2(elem)},start(next2,data2,options){let{adapter}=options,{name}=data2,{value}=data2,len=value.length;return len===0?import_boolbase.default.falseFunc:shouldIgnoreCase(data2,options)?(value=value.toLowerCase(),elem=>{let attr2=adapter.getAttributeValue(elem,name);return attr2!=null&&attr2.length>=len&&attr2.substr(0,len).toLowerCase()===value&&next2(elem)}):elem=>{var _a4;return!!(!((_a4=adapter.getAttributeValue(elem,name))===null||_a4===void 0)&&_a4.startsWith(value))&&next2(elem)}},end(next2,data2,options){let{adapter}=options,{name}=data2,{value}=data2,len=-value.length;return len===0?import_boolbase.default.falseFunc:shouldIgnoreCase(data2,options)?(value=value.toLowerCase(),elem=>{var _a4;return((_a4=adapter.getAttributeValue(elem,name))===null||_a4===void 0?void 0:_a4.substr(len).toLowerCase())===value&&next2(elem)}):elem=>{var _a4;return!!(!((_a4=adapter.getAttributeValue(elem,name))===null||_a4===void 0)&&_a4.endsWith(value))&&next2(elem)}},any(next2,data2,options){let{adapter}=options,{name,value}=data2;if(value==="")return import_boolbase.default.falseFunc;if(shouldIgnoreCase(data2,options)){let regex=new RegExp(escapeRegex2(value),"i");return __name(function(elem){let attr2=adapter.getAttributeValue(elem,name);return attr2!=null&&attr2.length>=value.length&&regex.test(attr2)&&next2(elem)},"anyIC")}return elem=>{var _a4;return!!(!((_a4=adapter.getAttributeValue(elem,name))===null||_a4===void 0)&&_a4.includes(value))&&next2(elem)}},not(next2,data2,options){let{adapter}=options,{name}=data2,{value}=data2;return value===""?elem=>!!adapter.getAttributeValue(elem,name)&&next2(elem):shouldIgnoreCase(data2,options)?(value=value.toLowerCase(),elem=>{let attr2=adapter.getAttributeValue(elem,name);return(attr2==null||attr2.length!==value.length||attr2.toLowerCase()!==value)&&next2(elem)}):elem=>adapter.getAttributeValue(elem,name)!==value&&next2(elem)}}}});function parse10(formula){if(formula=formula.trim().toLowerCase(),formula==="even")return[2,0];if(formula==="odd")return[2,1];let idx=0,a=0,sign=readSign(),number=readNumber();if(idx<formula.length&&formula.charAt(idx)==="n"&&(idx++,a=sign*(number??1),skipWhitespace(),idx<formula.length?(sign=readSign(),skipWhitespace(),number=readNumber()):sign=number=0),number===null||idx<formula.length)throw new Error(`n-th rule couldn't be parsed ('${formula}')`);return[a,sign*number];function readSign(){return formula.charAt(idx)==="-"?(idx++,-1):(formula.charAt(idx)==="+"&&idx++,1)}function readNumber(){let start=idx,value=0;for(;idx<formula.length&&formula.charCodeAt(idx)>=ZERO&&formula.charCodeAt(idx)<=NINE;)value=value*10+(formula.charCodeAt(idx)-ZERO),idx++;return idx===start?null:value}function skipWhitespace(){for(;idx<formula.length&&whitespace.has(formula.charCodeAt(idx));)idx++}}var whitespace,ZERO,NINE,init_parse2=__esm({"../../node_modules/.pnpm/nth-check@2.1.1/node_modules/nth-check/lib/esm/parse.js"(){whitespace=new Set([9,10,12,13,32]),ZERO=48,NINE=57;__name(parse10,"parse")}});function compile2(parsed){let a=parsed[0],b=parsed[1]-1;if(b<0&&a<=0)return import_boolbase2.default.falseFunc;if(a===-1)return index2=>index2<=b;if(a===0)return index2=>index2===b;if(a===1)return b<0?import_boolbase2.default.trueFunc:index2=>index2>=b;let absA=Math.abs(a),bMod=(b%absA+absA)%absA;return a>1?index2=>index2>=b&&index2%absA===bMod:index2=>index2<=b&&index2%absA===bMod}var import_boolbase2,init_compile=__esm({"../../node_modules/.pnpm/nth-check@2.1.1/node_modules/nth-check/lib/esm/compile.js"(){import_boolbase2=__toESM(require_boolbase(),1);__name(compile2,"compile")}});function nthCheck(formula){return compile2(parse10(formula))}var init_esm8=__esm({"../../node_modules/.pnpm/nth-check@2.1.1/node_modules/nth-check/lib/esm/index.js"(){init_parse2();init_compile();__name(nthCheck,"nthCheck")}});function getChildFunc(next2,adapter){return elem=>{let parent2=adapter.getParent(elem);return parent2!=null&&adapter.isTag(parent2)&&next2(elem)}}function dynamicStatePseudo(name){return __name(function(next2,_rule,{adapter}){let func=adapter[name];return typeof func!="function"?import_boolbase3.default.falseFunc:__name(function(elem){return func(elem)&&next2(elem)},"active")},"dynamicPseudo")}var import_boolbase3,filters,init_filters=__esm({"../../node_modules/.pnpm/css-select@5.2.2/node_modules/css-select/lib/esm/pseudo-selectors/filters.js"(){init_esm8();import_boolbase3=__toESM(require_boolbase(),1);__name(getChildFunc,"getChildFunc");filters={contains(next2,text3,{adapter}){return __name(function(elem){return next2(elem)&&adapter.getText(elem).includes(text3)},"contains")},icontains(next2,text3,{adapter}){let itext=text3.toLowerCase();return __name(function(elem){return next2(elem)&&adapter.getText(elem).toLowerCase().includes(itext)},"icontains")},"nth-child"(next2,rule,{adapter,equals}){let func=nthCheck(rule);return func===import_boolbase3.default.falseFunc?import_boolbase3.default.falseFunc:func===import_boolbase3.default.trueFunc?getChildFunc(next2,adapter):__name(function(elem){let siblings2=adapter.getSiblings(elem),pos=0;for(let i=0;i<siblings2.length&&!equals(elem,siblings2[i]);i++)adapter.isTag(siblings2[i])&&pos++;return func(pos)&&next2(elem)},"nthChild")},"nth-last-child"(next2,rule,{adapter,equals}){let func=nthCheck(rule);return func===import_boolbase3.default.falseFunc?import_boolbase3.default.falseFunc:func===import_boolbase3.default.trueFunc?getChildFunc(next2,adapter):__name(function(elem){let siblings2=adapter.getSiblings(elem),pos=0;for(let i=siblings2.length-1;i>=0&&!equals(elem,siblings2[i]);i--)adapter.isTag(siblings2[i])&&pos++;return func(pos)&&next2(elem)},"nthLastChild")},"nth-of-type"(next2,rule,{adapter,equals}){let func=nthCheck(rule);return func===import_boolbase3.default.falseFunc?import_boolbase3.default.falseFunc:func===import_boolbase3.default.trueFunc?getChildFunc(next2,adapter):__name(function(elem){let siblings2=adapter.getSiblings(elem),pos=0;for(let i=0;i<siblings2.length;i++){let currentSibling=siblings2[i];if(equals(elem,currentSibling))break;adapter.isTag(currentSibling)&&adapter.getName(currentSibling)===adapter.getName(elem)&&pos++}return func(pos)&&next2(elem)},"nthOfType")},"nth-last-of-type"(next2,rule,{adapter,equals}){let func=nthCheck(rule);return func===import_boolbase3.default.falseFunc?import_boolbase3.default.falseFunc:func===import_boolbase3.default.trueFunc?getChildFunc(next2,adapter):__name(function(elem){let siblings2=adapter.getSiblings(elem),pos=0;for(let i=siblings2.length-1;i>=0;i--){let currentSibling=siblings2[i];if(equals(elem,currentSibling))break;adapter.isTag(currentSibling)&&adapter.getName(currentSibling)===adapter.getName(elem)&&pos++}return func(pos)&&next2(elem)},"nthLastOfType")},root(next2,_rule,{adapter}){return elem=>{let parent2=adapter.getParent(elem);return(parent2==null||!adapter.isTag(parent2))&&next2(elem)}},scope(next2,rule,options,context){let{equals}=options;return!context||context.length===0?filters.root(next2,rule,options):context.length===1?elem=>equals(context[0],elem)&&next2(elem):elem=>context.includes(elem)&&next2(elem)},hover:dynamicStatePseudo("isHovered"),visited:dynamicStatePseudo("isVisited"),active:dynamicStatePseudo("isActive")};__name(dynamicStatePseudo,"dynamicStatePseudo")}});function verifyPseudoArgs(func,name,subselect,argIndex){if(subselect===null){if(func.length>argIndex)throw new Error(`Pseudo-class :${name} requires an argument`)}else if(func.length===argIndex)throw new Error(`Pseudo-class :${name} doesn't have any arguments`)}var pseudos,init_pseudos=__esm({"../../node_modules/.pnpm/css-select@5.2.2/node_modules/css-select/lib/esm/pseudo-selectors/pseudos.js"(){pseudos={empty(elem,{adapter}){return!adapter.getChildren(elem).some(elem2=>adapter.isTag(elem2)||adapter.getText(elem2)!=="")},"first-child"(elem,{adapter,equals}){if(adapter.prevElementSibling)return adapter.prevElementSibling(elem)==null;let firstChild=adapter.getSiblings(elem).find(elem2=>adapter.isTag(elem2));return firstChild!=null&&equals(elem,firstChild)},"last-child"(elem,{adapter,equals}){let siblings2=adapter.getSiblings(elem);for(let i=siblings2.length-1;i>=0;i--){if(equals(elem,siblings2[i]))return!0;if(adapter.isTag(siblings2[i]))break}return!1},"first-of-type"(elem,{adapter,equals}){let siblings2=adapter.getSiblings(elem),elemName=adapter.getName(elem);for(let i=0;i<siblings2.length;i++){let currentSibling=siblings2[i];if(equals(elem,currentSibling))return!0;if(adapter.isTag(currentSibling)&&adapter.getName(currentSibling)===elemName)break}return!1},"last-of-type"(elem,{adapter,equals}){let siblings2=adapter.getSiblings(elem),elemName=adapter.getName(elem);for(let i=siblings2.length-1;i>=0;i--){let currentSibling=siblings2[i];if(equals(elem,currentSibling))return!0;if(adapter.isTag(currentSibling)&&adapter.getName(currentSibling)===elemName)break}return!1},"only-of-type"(elem,{adapter,equals}){let elemName=adapter.getName(elem);return adapter.getSiblings(elem).every(sibling=>equals(elem,sibling)||!adapter.isTag(sibling)||adapter.getName(sibling)!==elemName)},"only-child"(elem,{adapter,equals}){return adapter.getSiblings(elem).every(sibling=>equals(elem,sibling)||!adapter.isTag(sibling))}};__name(verifyPseudoArgs,"verifyPseudoArgs")}});var aliases,init_aliases=__esm({"../../node_modules/.pnpm/css-select@5.2.2/node_modules/css-select/lib/esm/pseudo-selectors/aliases.js"(){aliases={"any-link":":is(a, area, link)[href]",link:":any-link:not(:visited)",disabled:`:is(
602
602
  :is(button, input, select, textarea, optgroup, option)[disabled],
@@ -1084,7 +1084,7 @@ ${html3}`.toLowerCase();return haystack.includes("webflow")||haystack.includes("
1084
1084
  `)}function readGeneratedArtifacts(cwd){let artifactsPath=path40.join(cwd,GENERATED_ARTIFACTS_PATH);if(!fs37.existsSync(artifactsPath))return null;try{return JSON.parse(fs37.readFileSync(artifactsPath,"utf8"))}catch{return null}}function readMediaMap(cwd,manifest){let mediaMapPath=manifest.assets.manifest;if(!mediaMapPath)return[];let fullPath=path40.join(cwd,mediaMapPath);if(!fs37.existsSync(fullPath))return[];try{let parsed=JSON.parse(fs37.readFileSync(fullPath,"utf8"));return Array.isArray(parsed)?parsed.filter(isMigrationMediaMapAsset):[]}catch{return[]}}function isMigrationMediaMapAsset(value){return isRecord2(value)&&typeof value.sourceUrl=="string"&&(typeof value.fileName=="string"||value.fileName===void 0)&&(typeof value.localPath=="string"||value.localPath===null)&&typeof value.status=="string"}function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function resolveGeneratedPageModule(cwd,routePath,generatedArtifacts){let expected=path40.join(cwd,"src","pages","migrated",`${pageComponentName2(routePath)}.tsx`);if(fs37.existsSync(expected))return expected;let pageFiles=generatedArtifacts?.pageFiles??[],expectedBase=`${pageComponentName2(routePath)}.tsx`,fallback=pageFiles.map(relativePath=>path40.join(cwd,relativePath)).find(filePath=>path40.basename(filePath)===expectedBase);return fallback&&fs37.existsSync(fallback)?fallback:null}function detectCurrentTemplate(targetModule){return!targetModule||!fs37.existsSync(targetModule)?"custom-or-missing":fs37.readFileSync(targetModule,"utf8").includes("MigrationPageTemplate")?"generic-migration-template":"custom-or-missing"}function routeToBriefFile(routePath){return routePath==="/"?"home":slugify3(routePath.replace(/^\//,"").replace(/\//g,"-"))||"page"}function normalizeRoute(routePath){if(!routePath)return"/";let trimmed=routePath.trim();return trimmed==="/"?"/":`/${trimmed.replace(/^\/+/,"").replace(/\/+$/,"")}`}function normalizeUrlForMatch(value){try{let url=new URL(value);return url.hash="",url.toString()}catch{return value}}function cleanText3(value){return value.replace(/\s+/g," ").trim()}function shouldKeepAction(label){return label.length>=2&&label.length<=80}function absolutizeHref(value,baseUrl){if(!value||value.startsWith("#")||value.startsWith("javascript:")||value.startsWith("mailto:"))return value;try{return new URL(value,baseUrl).toString()}catch{return value}}function writeFile3(cwd,relativePath,content2,written){let fullPath=path40.join(cwd,relativePath);fs37.mkdirSync(path40.dirname(fullPath),{recursive:!0}),fs37.writeFileSync(fullPath,content2,"utf8"),written.push(relativePath)}function unique3(values){let seen=new Set,result=[];for(let value of values){let normalized=value.trim();!normalized||seen.has(normalized)||(seen.add(normalized),result.push(normalized))}return result}function uniqueLinkObjects(values){let seen=new Set,result=[];for(let value of values){let key=`${value.label}::${value.href??""}`;seen.has(key)||(seen.add(key),result.push(value))}return result}function uniqueActionObjects(values){let seen=new Set,result=[];for(let value of values){let key=`${value.kind}::${value.label}::${value.href??""}`;seen.has(key)||(seen.add(key),result.push(value))}return result}function uniqueImageObjects3(values){let seen=new Set,result=[];for(let value of values){let key=`${value.src}::${value.alt??""}`;seen.has(key)||(seen.add(key),result.push(value))}return result}function pageComponentName2(routePath){if(routePath==="/")return"HomePage";let normalized=`${routePath.replace(/^\//,"").split("/").filter(Boolean).map(part=>titleize3(part).replace(/\s+/g,"")).join("")||"Page"}Page`;return/^[A-Za-z_$]/.test(normalized)?normalized:`Route${normalized}`}function titleize3(value){return value.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,match=>match.toUpperCase())}function slugify3(value){return value.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function toPosix3(value){return value.split(path40.sep).join("/")}var REFINE_ROOT,PAGE_BRIEFS_DIR,GENERATED_ARTIFACTS_PATH,init_migrate_refine=__esm({"src/cli/commands/migrate-refine.ts"(){init_dist();init_slim();init_migrate();REFINE_ROOT=path40.join(MIGRATION_DIR2,"refine"),PAGE_BRIEFS_DIR=path40.join(REFINE_ROOT,"pages"),GENERATED_ARTIFACTS_PATH=path40.join(MIGRATION_DIR2,"generated","artifacts.json");__name(migrateRefineCommand,"migrateRefineCommand");__name(prepareMigrationRefineArtifacts,"prepareMigrationRefineArtifacts");__name(selectPagesForRefine,"selectPagesForRefine");__name(writePageBrief,"writePageBrief");__name(analyzeSourceHtml,"analyzeSourceHtml");__name(buildPageBrief,"buildPageBrief");__name(buildAgentPrompt,"buildAgentPrompt");__name(readGeneratedArtifacts,"readGeneratedArtifacts");__name(readMediaMap,"readMediaMap");__name(isMigrationMediaMapAsset,"isMigrationMediaMapAsset");__name(isRecord2,"isRecord");__name(resolveGeneratedPageModule,"resolveGeneratedPageModule");__name(detectCurrentTemplate,"detectCurrentTemplate");__name(routeToBriefFile,"routeToBriefFile");__name(normalizeRoute,"normalizeRoute");__name(normalizeUrlForMatch,"normalizeUrlForMatch");__name(cleanText3,"cleanText");__name(shouldKeepAction,"shouldKeepAction");__name(absolutizeHref,"absolutizeHref");__name(writeFile3,"writeFile");__name(unique3,"unique");__name(uniqueLinkObjects,"uniqueLinkObjects");__name(uniqueActionObjects,"uniqueActionObjects");__name(uniqueImageObjects3,"uniqueImageObjects");__name(pageComponentName2,"pageComponentName");__name(titleize3,"titleize");__name(slugify3,"slugify");__name(toPosix3,"toPosix")}});function syncStateColor(state,p2){switch(state){case"in-sync":return p2.green("in sync");case"ahead":return p2.blue("ahead");case"behind":return p2.yellow("behind");case"diverged":return p2.red("diverged");default:return p2.dim("unknown")}}function renderStatus2(report,p2,opts={}){let lines=[],sep2=opts.ascii?"|":"\xB7",header=`${p2.bold(`env: ${report.env}`)} ${p2.dim(`vs ${report.vs} ${sep2}`)} ${syncStateColor(report.syncState,p2)}`;if(lines.push(header),lines.push(""),opts.short){for(let name of SURFACE_NAMES){if(opts.surface&&opts.surface!==name)continue;let delta=report.surfaces.find(s=>s.surface===name);if(!delta)continue;let innerSep=opts.ascii?"|":"\xB7",counts=`${delta.changedCount} changed${delta.conflictCount>0?` ${innerSep} ${delta.conflictCount} conflicts`:""}`,truncatedHint=delta.truncated&&delta.items&&delta.items.length<delta.changedCount?p2.dim(` ${innerSep} ${delta.items.length} of ${delta.changedCount} shown`):"";lines.push(` ${p2.bold(name.padEnd(14))} ${p2.dim(counts)}${truncatedHint}`)}return lines.join(`
1085
1085
  `)}let surfaceOpts={ascii:opts.ascii,...opts.all?{maxItems:Number.MAX_SAFE_INTEGER}:{}};for(let name of SURFACE_NAMES){if(opts.surface&&opts.surface!==name)continue;let delta=report.surfaces.find(s=>s.surface===name);delta&&(lines.push(renderSurface(delta,p2,surfaceOpts)),lines.push(""))}if(!opts.surface&&report.crossSurface&&report.crossSurface.length>0&&(lines.push(renderCrossSurface(report.crossSurface,p2,{ascii:opts.ascii})),lines.push("")),report.agents&&report.agents.length>0){lines.push(p2.bold("AGENTS")),lines.push(p2.dim(" declared \xB7 active \xB7 last run"));for(let agent of report.agents){let status=agent.status==="active"?p2.green("active"):agent.status==="paused"?p2.yellow("paused"):p2.red("failed"),lastRun=agent.lastRunAt?p2.dim(new Date(agent.lastRunAt).toISOString().slice(0,19)+"Z"):p2.dim("never");lines.push(` ${agent.name.padEnd(18)} ${status.padEnd(7)} ${lastRun}`)}lines.push("")}return lines.join(`
1086
1086
  `).replace(/\n+$/,"")}var init_render_status=__esm({"src/cli/utils/format/render-status.ts"(){init_esm();init_cross_surface();init_surface();__name(syncStateColor,"syncStateColor");__name(renderStatus2,"renderStatus")}});function pickSurfaces(opts){let selected=[["code","code"],["content","content"],["i18n","translations"],["agents","activations"],["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(resolve9=>{let t2=setTimeout(()=>resolve9({kind:"timeout"}),ms);p2.then(value=>{clearTimeout(t2),resolve9({kind:"ok",value})},error=>{clearTimeout(t2),resolve9({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(`
1087
- `).filter(Boolean).map(line=>{let code2=line.slice(0,2),path47=line.slice(3).trim();return{verb:code2.startsWith("A")||code2.startsWith("?")?"added":code2.startsWith("D")?"removed":"changed",key:path47,origin:"local-uncommitted"}});return{surface:"code",status:items.length===0?"unchanged":"ok",changedCount:items.length,conflictCount:0,items}}catch{return{surface:"code",status:"unchanged",changedCount:0,conflictCount:0,items:[]}}}function mergeCodeSurfaces(serverCode,local){if(!serverCode)return local;if(serverCode.status==="failed"||serverCode.status==="timed_out")return{...serverCode,items:[...serverCode.items??[],...local.items??[]],changedCount:serverCode.changedCount+local.changedCount};let items=[...serverCode.items??[],...local.items??[]],changedCount=serverCode.changedCount+local.changedCount,conflictCount=serverCode.conflictCount+local.conflictCount;return{surface:"code",status:changedCount>0||conflictCount>0?"ok":"unchanged",durationMs:serverCode.durationMs,changedCount,conflictCount,items}}async function statusCommand2(arg1,maybeCmd){let cmd=maybeCmd??arg1,options=maybeCmd?arg1:cmd.opts(),program2=cmd.parent??cmd,envOverride2=envOverrideFromCommand(program2),ctx=await getProjectContext({cwd:options.cwd,envOverride:envOverride2}),api=new FimoApiClient().withEnv(ctx.env),cwd=resolveProjectCwd(options.cwd),surfaces=pickSurfaces(options),codePromise=localCodeSurface(cwd),serverPromise=withSoftTimeout(api.getEnvStatus(ctx.projectId,ctx.env,{against:options.vs,surfaces}),SOFT_TIMEOUT_MS*15),[local,serverResult]=await Promise.all([codePromise,serverPromise]);if(serverResult.kind==="timeout"){ui.error({command:"status",code:"STATUS_TIMEOUT",message:`Server did not respond within ${SOFT_TIMEOUT_MS*15/1e3}s. Try again, or run \`fimo diff\` to drill in.`});return}if(serverResult.kind==="error"){let err=serverResult.error,message=err instanceof Error?err.message:String(err);ui.error({command:"status",code:"STATUS_REQUEST_FAILED",message:`Failed to fetch status: ${message}`});return}let server=serverResult.value,serverCode=server.surfaces.find(s=>s.surface==="code"),code2=mergeCodeSurfaces(serverCode,local),merged={...server,surfaces:[code2,...server.surfaces.filter(s=>s.surface!=="code")]};ui.result({command:"status",data:merged,render:__name(rctx=>{let p2=rctx.color?palette:makeColorPalette({forceDisable:!0});return renderStatus2(merged,p2,{short:options.short,surface:surfaces?.length===1?surfaces[0]:void 0,all:options.all,ascii:rctx.ascii})},"render")})}var SOFT_TIMEOUT_MS,init_status=__esm({"src/cli/commands/status.ts"(){init_dist();init_api();init_color();init_render_status();init_git();init_project_context();init_project();SOFT_TIMEOUT_MS=2e3;__name(pickSurfaces,"pickSurfaces");__name(withSoftTimeout,"withSoftTimeout");__name(localCodeSurface,"localCodeSurface");__name(mergeCodeSurfaces,"mergeCodeSurfaces");__name(statusCommand2,"statusCommand")}});init_dist();import fs42 from"node:fs";import path46 from"node:path";var import_index=__toESM(require_commander(),1),{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import_index.default;init_api();import fs7 from"node:fs";import path7 from"node:path";var import_yaml=__toESM(require_dist(),1);import{createHash as createHash2}from"node:crypto";import{promises}from"node:fs";import path4 from"node:path";import{z as z61}from"zod";var CapabilityTokenSchema=z61.string().min(1).regex(/^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?$/,{error:"capability tokens must match verb:noun or verb:noun:qualifier (lowercase + digits + underscores; must start with a letter)"}),CapabilitiesFileSchema=z61.array(CapabilityTokenSchema);import{z as z62}from"zod";var CronTriggerSchema=z62.object({type:z62.literal("schedule"),cron:z62.string().min(1,"cron expression required"),tz:z62.string().optional()}),ManualTriggerSchema2=z62.object({type:z62.literal("manual")}),WebhookTriggerSchema2=z62.object({type:z62.literal("webhook"),path:z62.string().min(1).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z62.discriminatedUnion("type",[ManualTriggerSchema2,CronTriggerSchema,WebhookTriggerSchema2]),SubAgentRefSchema=z62.object({name:z62.string().min(1),capability_grant:z62.enum(["inherit","explicit"]).optional(),explicit_grants:z62.array(z62.string()).optional()}).refine(v=>v.capability_grant!=="explicit"||Array.isArray(v.explicit_grants)&&v.explicit_grants.length>0,{message:"`explicit_grants` is required when `capability_grant: explicit`",path:["explicit_grants"]}),CompositionConfigSchema=z62.object({"sub-agents":z62.array(SubAgentRefSchema)}),RuntimeConfigSchema=z62.object({cloud:z62.boolean().optional(),dev:z62.boolean().optional(),long_running:z62.boolean().optional()}),DataSourceSchema=z62.enum(["main","prod"]),ConfigValueKeySchema=z62.string().min(1).max(255).regex(/^[A-Z_][A-Z0-9_]*$/,"secret keys must be UPPER_SNAKE_CASE and start with a letter or underscore"),PUBLIC_CONFIG_PREFIX=/^(PUBLIC_|VITE_|NEXT_PUBLIC_)/,AgentSecretRequestSchema=z62.preprocess(value=>typeof value=="string"?{key:value}:value,z62.object({key:ConfigValueKeySchema.refine(key=>!PUBLIC_CONFIG_PREFIX.test(key),{message:"agent secrets cannot use public variable prefixes (PUBLIC_, VITE_, NEXT_PUBLIC_)"}),required:z62.boolean().default(!0),delivery:z62.literal("process_env").default("process_env")})),IntegrationKeySchema=z62.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*$/,"integration keys must be lowercase alphanumeric with optional _ or -"),IntegrationToolKeySchema=z62.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)*$/,"integration tool keys must be lowercase dot-separated identifiers with optional _ or -"),IntegrationPolicyEntrySchema=z62.preprocess(value=>typeof value=="boolean"?{enabled:value}:value,z62.object({enabled:z62.boolean().default(!0),tools:z62.record(IntegrationToolKeySchema,z62.boolean()).optional()})),IntegrationPolicySchema=z62.record(IntegrationKeySchema,IntegrationPolicyEntrySchema),AgentConfigSchema=z62.object({version:z62.literal(1),description:z62.string().min(1).max(280).optional(),runtime:RuntimeConfigSchema.optional(),triggers:z62.array(TriggerSchema2).optional(),composition:CompositionConfigSchema.optional(),data_sources:z62.array(DataSourceSchema).optional(),secrets:z62.array(AgentSecretRequestSchema).optional(),integrations:IntegrationPolicySchema.optional(),integration_policy:IntegrationPolicySchema.optional()}).refine(config=>!(config.integrations&&config.integration_policy),{message:"use either `integrations` or legacy `integration_policy`, not both",path:["integrations"]});function _define_property(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property,"_define_property");var BundleParseError=class extends Error{static{__name(this,"BundleParseError")}constructor(bundlePath,file,message,cause){super(`[${file}] ${message}`),_define_property(this,"bundlePath",void 0),_define_property(this,"file",void 0),_define_property(this,"cause",void 0),this.name="BundleParseError",this.bundlePath=bundlePath,this.file=file,this.cause=cause}};async function fileExists(file){try{return(await promises.stat(file)).isFile()}catch{return!1}}__name(fileExists,"fileExists");async function readFileOrNull(file){try{return await promises.readFile(file,"utf8")}catch(err){if(err.code==="ENOENT")return null;throw err}}__name(readFileOrNull,"readFileOrNull");async function listDir(dir){try{return(await promises.readdir(dir,{withFileTypes:!0,recursive:!0})).filter(e=>e.isFile()).map(e=>{let parentPath=e.parentPath??e.path??dir;return path4.relative(dir,path4.join(parentPath,e.name))}).sort()}catch(err){if(err.code==="ENOENT")return[];throw err}}__name(listDir,"listDir");function parseYamlStrict(text3,file,bundlePath){try{return(0,import_yaml.parse)(text3)}catch(err){throw new BundleParseError(bundlePath,file,`invalid YAML: ${err.message}`,err)}}__name(parseYamlStrict,"parseYamlStrict");function formatZodIssue(issue){return`${issue.path.length===0?"(root)":issue.path.join(".")}: ${issue.message}`}__name(formatZodIssue,"formatZodIssue");async function parseBundle(bundlePath,opts={}){let name=path4.basename(bundlePath),goalPath=path4.join(bundlePath,"GOAL.md"),goal=await readFileOrNull(goalPath);if(goal===null)throw new BundleParseError(bundlePath,"GOAL.md","GOAL.md is required but missing");if(goal.trim().length===0)throw new BundleParseError(bundlePath,"GOAL.md","GOAL.md is empty");let configPath=path4.join(bundlePath,"config.yaml"),configRaw=await readFileOrNull(configPath),config;if(configRaw===null){if(!opts.defaultConfig)throw new BundleParseError(bundlePath,"config.yaml","config.yaml is required but missing");config={version:1}}else{let yamlData=parseYamlStrict(configRaw,"config.yaml",bundlePath),parsed=AgentConfigSchema.safeParse(yamlData);if(!parsed.success){let issues=parsed.error.issues.map(formatZodIssue).join("; ");throw new BundleParseError(bundlePath,"config.yaml",`schema validation failed: ${issues}`)}config=parsed.data}let soul=await readFileOrNull(path4.join(bundlePath,"SOUL.md")),capsPath=path4.join(bundlePath,"capabilities.yaml"),capsRaw=await readFileOrNull(capsPath),capabilities=[];if(capsRaw!==null){let candidate=parseYamlStrict(capsRaw,"capabilities.yaml",bundlePath)??[],parsed=CapabilitiesFileSchema.safeParse(candidate);if(!parsed.success){let issues=parsed.error.issues.map(formatZodIssue).join("; ");throw new BundleParseError(bundlePath,"capabilities.yaml",`schema validation failed: ${issues} \u2014 file must be a bare YAML list of capability tokens`)}capabilities=parsed.data}let[scripts2,references,assets3]=await Promise.all([listDir(path4.join(bundlePath,"scripts")),listDir(path4.join(bundlePath,"references")),listDir(path4.join(bundlePath,"assets"))]),warnings=[],pluginsDir=path4.join(bundlePath,"plugins");try{(await promises.stat(pluginsDir)).isDirectory()&&warnings.push({pointer:"plugins/",message:"`plugins/` is reserved for v1.x and will be ignored at runtime."})}catch{}let checksum=await computeBundleChecksum(bundlePath,{goal,soul,configRaw,capsRaw,scripts:scripts2,references,assets:assets3});return{name,path:bundlePath,goal,soul,config,capabilities,scripts:scripts2,references,assets:assets3,checksum,warnings}}__name(parseBundle,"parseBundle");async function computeBundleChecksum(bundlePath,parts){let hash=createHash2("sha256");hash.update("GOAL.md\0"),hash.update(parts.goal),hash.update("\0config.yaml\0"),hash.update(parts.configRaw??""),parts.capsRaw!==null&&(hash.update("\0capabilities.yaml\0"),hash.update(parts.capsRaw)),parts.soul!==null&&(hash.update("\0SOUL.md\0"),hash.update(parts.soul));let dirs=[["scripts",parts.scripts],["references",parts.references],["assets",parts.assets]];for(let[dirName,files]of dirs)for(let rel of files){let filePath=path4.join(bundlePath,dirName,rel);try{let buf=await promises.readFile(filePath);hash.update(`\0${dirName}/${rel}\0`),hash.update(buf)}catch{}}return hash.digest("hex")}__name(computeBundleChecksum,"computeBundleChecksum");async function listBundles(agentsDir){let entries2=[];try{entries2=await promises.readdir(agentsDir,{withFileTypes:!0})}catch(err){if(err.code==="ENOENT")return[];throw err}let bundles=[];for(let entry of entries2){if(!entry.isDirectory())continue;let bundlePath=path4.join(agentsDir,entry.name);if(await fileExists(path4.join(bundlePath,"GOAL.md")))try{bundles.push(await parseBundle(bundlePath))}catch{}}return bundles.sort((a,b)=>a.name.localeCompare(b.name))}__name(listBundles,"listBundles");var ENTRIES=[{token:"files:read",risk:"low",description:"Read project files"},{token:"files:write",risk:"medium",description:"Write or delete project files"},{token:"cms:read",risk:"low",description:"Read CMS content"},{token:"cms:write",risk:"medium",description:"Create, update, or delete CMS entries"},{token:"cms:schema:read",risk:"low",description:"Read CMS schemas"},{token:"cms:schema:write",risk:"high",description:"Modify CMS schemas (destructive \u2014 alters all entries of the type)"},{token:"assets:read",risk:"low",description:"Read uploaded media"},{token:"assets:write",risk:"medium",description:"Upload, replace, or delete media"},{token:"i18n:read",risk:"low",description:"Read translation catalogs"},{token:"i18n:write",risk:"medium",description:"Modify translation catalogs via the fimo i18n CLI"},{token:"forms:read",risk:"low",description:"Read form schemas and submissions"},{token:"forms:write",risk:"medium",description:"Modify form schemas or clear submissions"},{token:"git:read",risk:"low",description:"Read git state"},{token:"git:branch",risk:"medium",description:"Create agent-proposed branches off main"},{token:"git:commit",risk:"medium",description:"Commit changes to an agent branch"},{token:"git:push",risk:"high",description:"Push to the project remote (main push is intercepted)"},{token:"git:tag",risk:"high",runtimeOnly:!0,description:"Used by runtime for prod release tags; agents cannot call directly"},{token:"fimo:deploy",risk:"critical",description:"Trigger a production deploy"},{token:"fimo:logs:read",risk:"low",description:"Read production logs"},{token:"fimo:analytics:read",risk:"low",description:"Read analytics data"},{token:"fimo:preview:read",risk:"low",description:"Read a current preview URL for an env (no commit, no deploy)"},{token:"net:fetch",risk:"medium",description:"Make outbound HTTP requests"},{token:"shell:exec",risk:"high",description:"Run arbitrary shell commands inside the sandbox"},{token:"agent:delegate",risk:"medium",description:"Invoke declared sub-agents"},{token:"runtime:long_running",risk:"high",description:"Run autonomously past the default 30 min limit (up to 4h walltime / 12h ceiling)"},{token:"runtime:auto_merge",risk:"critical",description:"Auto-merge trivial proposed branches to main without per-change human review"}],BY_TOKEN=new Map(ENTRIES.map(e=>[e.token,e])),CAPABILITY_VOCABULARY=ENTRIES;function getCapability(token){return BY_TOKEN.get(token)??null}__name(getCapability,"getCapability");function isKnownCapability(token){return BY_TOKEN.has(token)}__name(isKnownCapability,"isKnownCapability");function isHighRisk(token){let def=getCapability(token);return def?.risk==="high"||def?.risk==="critical"}__name(isHighRisk,"isHighRisk");function isRuntimeOnly(token){return getCapability(token)?.runtimeOnly===!0}__name(isRuntimeOnly,"isRuntimeOnly");function validateBundle(bundle,opts={}){let issues=[],available=new Map((opts.availableAgents??[]).map(b=>[b.name,b]));for(let i=0;i<bundle.capabilities.length;i++){let token=bundle.capabilities[i];if(token!==void 0){if(!isKnownCapability(token)){issues.push({pointer:`capabilities.yaml:[${i}]`,message:`unknown capability token: ${token}`,severity:"error"});continue}isRuntimeOnly(token)&&issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is runtime-orchestration-only; agents cannot declare it (the runtime intercepts)`,severity:"error"}),getCapability(token)?.risk==="critical"&&issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is critical-risk; requires project policy + install-time confirmation`,severity:"warning"})}}let subAgents=bundle.config.composition?.["sub-agents"]??[];subAgents.length>0&&!bundle.capabilities.includes("agent:delegate")&&issues.push({pointer:"capabilities.yaml",message:"`composition.sub-agents` is declared but `agent:delegate` capability is missing",severity:"error"});for(let i=0;i<subAgents.length;i++){let sub=subAgents[i];sub&&opts.availableAgents&&!available.has(sub.name)&&issues.push({pointer:`config.yaml:composition.sub-agents[${i}].name`,message:`sub-agent '${sub.name}' is not present in the project's agents directory`,severity:"error"})}if(opts.availableAgents&&subAgents.length>0){let cycle=detectCycle(bundle,available);cycle&&issues.push({pointer:"config.yaml:composition",message:`composition cycle detected: ${cycle.join(" \u2192 ")}`,severity:"error"})}let webhookPaths=new Set,triggers=bundle.config.triggers??[];for(let i=0;i<triggers.length;i++){let t2=triggers[i];t2&&t2.type==="webhook"&&(webhookPaths.has(t2.path)&&issues.push({pointer:`config.yaml:triggers[${i}].path`,message:`duplicate webhook path '${t2.path}' within bundle`,severity:"error"}),webhookPaths.add(t2.path))}return bundle.config.data_sources&&bundle.config.data_sources.length===0&&issues.push({pointer:"config.yaml:data_sources",message:'data_sources is empty; omit the field to default to ["main"]',severity:"warning"}),issues}__name(validateBundle,"validateBundle");function detectCycle(start,available){let color=new Map,parent2=new Map;function visit2(name){color.set(name,1);let children2=available.get(name)?.config.composition?.["sub-agents"]??[];for(let child of children2){if(!child)continue;let c2=color.get(child.name)??0;if(c2===1){let cycle=[child.name],curr=name;for(;curr&&curr!==child.name;)cycle.unshift(curr),curr=parent2.get(curr)??null;return cycle.unshift(child.name),cycle}if(c2===0&&available.has(child.name)){parent2.set(child.name,name);let found=visit2(child.name);if(found)return found}}return color.set(name,2),null}return __name(visit2,"visit"),visit2(start.name)}__name(detectCycle,"detectCycle");function agentIntegrationPolicy(config){return config.integrations??config.integration_policy??{}}__name(agentIntegrationPolicy,"agentIntegrationPolicy");function agentAllowsIntegrationTool(policy,integrationKey,toolKey){let entry=policy[integrationKey];return entry?.enabled?entry.tools?.[toolKey]===!0:!1}__name(agentAllowsIntegrationTool,"agentAllowsIntegrationTool");function enabledAgentIntegrationTools(entry){return entry?.enabled?Object.entries(entry.tools??{}).filter(([,enabled])=>enabled).map(([tool])=>tool).sort((a,b)=>a.localeCompare(b)):[]}__name(enabledAgentIntegrationTools,"enabledAgentIntegrationTools");function _define_property2(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property2,"_define_property");var CapabilityDeniedError=class extends Error{static{__name(this,"CapabilityDeniedError")}constructor(required,granted){let def=getCapability(required),what=def?.description?` (${def.description})`:"";super(`capability '${required}'${what} denied \u2014 granted: [${granted.join(", ")}]`),_define_property2(this,"required",void 0),_define_property2(this,"granted",void 0),this.name="CapabilityDeniedError",this.required=required,this.granted=granted}};function assertCapability(required,granted){if(!granted.includes(required))throw new CapabilityDeniedError(required,granted)}__name(assertCapability,"assertCapability");function resolveSubCallCapabilities(parentGranted,subDeclared,ref){if((ref.capability_grant??"inherit")==="explicit"){let explicit=ref.explicit_grants??[];return subDeclared.filter(t2=>explicit.includes(t2))}return[...subDeclared]}__name(resolveSubCallCapabilities,"resolveSubCallCapabilities");function _define_property3(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property3,"_define_property");var BundleError=class extends Error{static{__name(this,"BundleError")}constructor(message,remediation,bundlePath){super(message),_define_property3(this,"remediation",void 0),_define_property3(this,"bundlePath",void 0),this.name=this.constructor.name,this.remediation=remediation,this.bundlePath=bundlePath}},BundleValidationError=class extends BundleError{static{__name(this,"BundleValidationError")}constructor(message,options={}){super(message,options.remediation??"Fix the file in the bundle and re-run `fimo agents validate`.",options.bundlePath),_define_property3(this,"code","bundle.validation"),_define_property3(this,"file",void 0),_define_property3(this,"cause",void 0),this.file=options.file,this.cause=options.cause}};var BundleInvalidCapabilityError=class extends BundleError{static{__name(this,"BundleInvalidCapabilityError")}constructor(token,reason,options={}){let remediation=reason==="runtime_only"?`'${token}' is reserved for the runtime \u2014 drop it from capabilities.yaml.`:options.suggestion?`Unknown capability '${token}'. Did you mean '${options.suggestion}'?`:`Unknown capability '${token}'. Run \`fimo agents list-capabilities\` to see the vocabulary.`;super(reason==="runtime_only"?`Capability '${token}' is runtime-orchestration-only and cannot be declared.`:`Capability '${token}' is not in the closed vocabulary.`,remediation,options.bundlePath),_define_property3(this,"code","bundle.invalid_capability"),_define_property3(this,"token",void 0),_define_property3(this,"reason",void 0),this.token=token,this.reason=reason}},BundleCompositionCycleError=class extends BundleError{static{__name(this,"BundleCompositionCycleError")}constructor(cycle,options={}){super(`Composition cycle detected: ${cycle.join(" \u2192 ")}`,"Break the cycle by removing one of the sub-agent references in the chain.",options.bundlePath),_define_property3(this,"code","bundle.composition_cycle"),_define_property3(this,"cycle",void 0),this.cycle=[...cycle]}},BundleTemplateNotFoundError=class extends BundleError{static{__name(this,"BundleTemplateNotFoundError")}constructor(templateName,available){super(`Template '${templateName}' not found.`,available.length>0?`Available templates: ${available.join(", ")}. Use \`fimo agents list-templates\` to see all options.`:"No templates are bundled with this CLI. Use the empty default by omitting --template."),_define_property3(this,"code","bundle.template_not_found"),_define_property3(this,"templateName",void 0),_define_property3(this,"available",void 0),this.templateName=templateName,this.available=[...available]}};function isBundleError(err){return err instanceof BundleError}__name(isBundleError,"isBundleError");function detectCompositionCycle(input){let{root:root2,agentMap}=input,WHITE=0,GRAY=1,BLACK=2,color=new Map,parent2=new Map,visit2=__name(name=>{color.set(name,GRAY);let children2=agentMap.get(name)?.config.composition?.["sub-agents"]??[];for(let child of children2){if(!child)continue;let c2=color.get(child.name)??WHITE;if(c2===GRAY){let cycle=[child.name],curr=name;for(;curr&&curr!==child.name;)cycle.unshift(curr),curr=parent2.get(curr)??null;return cycle.unshift(child.name),cycle}if(c2===WHITE&&agentMap.has(child.name)){parent2.set(child.name,name);let found=visit2(child.name);if(found)return found}}return color.set(name,BLACK),null},"visit");return visit2(root2.name)}__name(detectCompositionCycle,"detectCompositionCycle");function validateAgainstVocabulary(tokens,vocab=CAPABILITY_VOCABULARY){let byToken=new Map(vocab.map(v=>[v.token,v])),unknown=[],runtimeOnly=[],highRisk=[];for(let token of tokens){let def=byToken.get(token);if(!def){unknown.push(token);continue}def.runtimeOnly&&runtimeOnly.push(token),(def.risk==="high"||def.risk==="critical")&&highRisk.push(token)}return{ok:unknown.length===0&&runtimeOnly.length===0,unknown,runtimeOnly,highRisk}}__name(validateAgainstVocabulary,"validateAgainstVocabulary");function suggestCapability(token,vocab=CAPABILITY_VOCABULARY){let best=null,bestDistance=1/0;for(let def of vocab){let d3=levenshtein(token,def.token);d3<bestDistance&&(bestDistance=d3,best=def.token)}return bestDistance<=2?best:null}__name(suggestCapability,"suggestCapability");function levenshtein(a,b){if(a===b)return 0;let al=a.length,bl=b.length;if(al===0)return bl;if(bl===0)return al;let prev2=Array.from({length:bl+1},(_,i)=>i);for(let i=1;i<=al;i++){let curr=new Array(bl+1);curr[0]=i;for(let j2=1;j2<=bl;j2++){let cost=a[i-1]===b[j2-1]?0:1;curr[j2]=Math.min((prev2[j2]??0)+1,(curr[j2-1]??0)+1,(prev2[j2-1]??0)+cost)}prev2=curr}return prev2[bl]??0}__name(levenshtein,"levenshtein");import{z as z63}from"zod";var SurfaceGuardPolicySchema=z63.enum(["block","warn","allow"]),ClassificationSchema=z63.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z63.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z63.object({enabled:z63.boolean(),allowed_skills:z63.array(z63.string().min(1)).default([]),allowed_classifications:z63.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z63.enum(["off","daily","weekly"]),NotificationFormatSchema=z63.object({markdown:z63.boolean().default(!0),html:z63.boolean().default(!1)}),NotificationsPolicySchema=z63.object({email_recipients:z63.array(z63.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z63.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z63.object({agents:FimoAgentsConfigSchema.optional()}).passthrough();function parseFimoConfig(jsonOrText,opts={}){let raw;if(typeof jsonOrText=="string")try{raw=JSON.parse(jsonOrText)}catch(err){throw new BundleValidationError(`${opts.path??"fimo.config.json"} is not valid JSON: ${err.message}`,{remediation:"Run the file through `jq .` or your editor JSON validator and fix the syntax.",file:opts.path??"fimo.config.json",cause:err})}else raw=jsonOrText;let parsed=FimoConfigSchema.safeParse(raw);if(!parsed.success){let issues=parsed.error.issues.map(i=>`${i.path.join(".")||"(root)"}: ${i.message}`).join("; ");throw new BundleValidationError(`${opts.path??"fimo.config.json"} schema validation failed: ${issues}`,{remediation:"See `fimo.config.json` shape in the lifecycle docs (`fimo agents docs lifecycle` or visit lifecycle.html#config).",file:opts.path??"fimo.config.json"})}let data2=parsed.data;if(data2.agents?.auto_merge?.enabled===!0&&(data2.agents.auto_merge.allowed_classifications??[]).length===0)throw new BundleValidationError("`agents.auto_merge.enabled: true` but `allowed_classifications` is empty \u2014 nothing would ever auto-merge.",{remediation:'Either set `allowed_classifications: ["trivial"]` (or any subset) or set `enabled: false`.',file:opts.path??"fimo.config.json"});return data2}__name(parseFimoConfig,"parseFimoConfig");function requireCloudActivationNotifications(config){let recipients=config?.agents?.notifications?.email_recipients??[];if(recipients.length===0)throw new BundleValidationError("Activating a cloud-time trigger requires `agents.notifications.email_recipients` to be non-empty.",{remediation:"Add at least one email to `fimo-config.json` \u2192 `agents.notifications.email_recipients`. This is where lifecycle proposal emails are sent (mandatory per ADR-0009).",file:"fimo-config.json"});return recipients}__name(requireCloudActivationNotifications,"requireCloudActivationNotifications");import{z as z64}from"zod";function toSpec(def){return{token:def.token,riskTier:def.risk,description:def.description,...def.runtimeOnly?{runtimeOnly:!0}:{}}}__name(toSpec,"toSpec");var VOCABULARY=Object.freeze(Object.fromEntries(CAPABILITY_VOCABULARY.filter(d3=>!d3.runtimeOnly).map(d3=>[d3.token,toSpec(d3)]))),CapabilityToken=z64.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z64.array(CapabilityToken);function riskTierOf(cap){let def=VOCABULARY[cap];if(!def)throw new Error(`riskTierOf: '${cap}' is not in the vocabulary`);return def.riskTier}__name(riskTierOf,"riskTierOf");function isCapability(token){return Object.prototype.hasOwnProperty.call(VOCABULARY,token)}__name(isCapability,"isCapability");function partitionCapabilities(tokens){let caps=[],unknown=[];for(let t2 of tokens)isCapability(t2)?caps.push(t2):unknown.push(t2);return{caps,unknown}}__name(partitionCapabilities,"partitionCapabilities");function isCritical(cap){return riskTierOf(cap)==="critical"}__name(isCritical,"isCritical");var OPERATION_CAP={"cms.list":"cms:read","cms.get":"cms:read","cms.query":"cms:read","cms.create":"cms:write","cms.update":"cms:write","cms.delete":"cms:write","cms.bulk_create":"cms:write","cms.bulk_update":"cms:write","cms.bulk_delete":"cms:write","cms.schema.list":"cms:schema:read","cms.schema.get":"cms:schema:read","cms.schema.push":"cms:schema:write","cms.schema.delete":"cms:schema:write","assets.list":"assets:read","assets.get":"assets:read","assets.upload":"assets:write","assets.generate":"assets:write","assets.create_folder":"assets:write","assets.move":"assets:write","assets.delete":"assets:write","i18n.list":"i18n:read","i18n.get":"i18n:read","i18n.create":"i18n:write","i18n.update":"i18n:write","i18n.delete":"i18n:write","forms.list":"forms:read","forms.get":"forms:read","forms.push":"forms:write","forms.delete":"forms:write","files.read":"files:read","files.write":"files:write","git.push":"git:push","shell.exec":"shell:exec","fimo.deploy":"fimo:deploy","fimo.logs.read":"fimo:logs:read","fimo.analytics.read":"fimo:analytics:read","fimo.preview.url":"fimo:preview:read","net.fetch":"net:fetch","agent.delegate":"agent:delegate","runtime.long_running":"runtime:long_running","runtime.auto_merge":"runtime:auto_merge"};function capabilityFor(op){return OPERATION_CAP[op]}__name(capabilityFor,"capabilityFor");function hasOperation(op){return Object.prototype.hasOwnProperty.call(OPERATION_CAP,op)}__name(hasOperation,"hasOperation");var import_yaml2=__toESM(require_dist(),1);function parseCapabilities(yaml){if(yaml==null||yaml.trim().length===0)return{caps:[],errors:[]};let raw;try{raw=(0,import_yaml2.parse)(yaml)}catch(cause){return{caps:[],errors:[{code:"MALFORMED_YAML",message:`invalid YAML: ${cause.message}`,cause}]}}if(raw==null)return{caps:[],errors:[]};if(!Array.isArray(raw))return{caps:[],errors:[{code:"WRONG_SHAPE",message:"capabilities.yaml must be a bare YAML list of capability tokens (not an object)"}]};let caps=[],errors=[];for(let item of raw){if(typeof item!="string"){errors.push({code:"WRONG_SHAPE",message:`expected a string capability token, got ${typeof item}`});continue}if(!isCapability(item)){if(CAPABILITY_VOCABULARY.find(d3=>d3.token===item)?.runtimeOnly){errors.push({code:"RUNTIME_ONLY_CAPABILITY",message:`'${item}' is runtime-orchestration-only \u2014 agents cannot declare it`,token:item});continue}let suggestion=suggestCapability(item)??void 0;errors.push({code:"UNKNOWN_CAPABILITY",message:suggestion?`unknown capability token '${item}' \u2014 did you mean '${suggestion}'?`:`unknown capability token '${item}'`,token:item,...suggestion?{suggestion}:{}});continue}caps.push(item)}return{caps,errors}}__name(parseCapabilities,"parseCapabilities");function _define_property4(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property4,"_define_property");var CapabilityDenied=class extends Error{static{__name(this,"CapabilityDenied")}constructor(detail){let def=getCapability(detail.cap),description=def?.description?` (${def.description})`:"";super(`capability denied: ${detail.cap}${description} \u2014 reason: ${detail.reason}`),_define_property4(this,"cap",void 0),_define_property4(this,"reason",void 0),_define_property4(this,"granted",void 0),_define_property4(this,"sessionId",void 0),_define_property4(this,"fixHint",void 0),this.name="CapabilityDenied",this.cap=detail.cap,this.reason=detail.reason,this.granted=detail.granted??[],this.sessionId=detail.sessionId,this.fixHint=fixHintFor(detail)}};function fixHintFor(detail){switch(detail.reason){case"not-declared":return`Add '${detail.cap}' to the agent's capabilities.yaml and re-activate.`;case"session-not-found":return`Session '${detail.sessionId??"<unknown>"}' does not exist or has expired.`;case"snapshot-stale":return"Session capability snapshot is corrupted. Restart the agent session.";case"runtime-only":return`'${detail.cap}' is reserved for the platform \u2014 drop it from capabilities.yaml.`;case"auto-merge-blocked":return"runtime:auto_merge is declared but blocked by project policy (fimo.config.json \u2192 agents.auto_merge)."}}__name(fixHintFor,"fixHintFor");var configured=null;async function auditCapabilityDecision(event){if(!configured)return;let row2={...event,ts:new Date().toISOString()};if(event.decision==="deny"){try{await configured.transport.write(row2)}catch(err){throw configured.breadcrumb?.({category:"audit",level:"error",message:"audit deny row write failed",data:{cap:event.cap,error:err.message}}),err}configured.breadcrumb?.({category:"audit",level:"warning",message:`capability denied: ${event.cap}`,data:{sessionId:event.sessionId,cap:event.cap,reason:event.reason}});return}configured.transport.write(row2).catch(err=>{configured?.breadcrumb?.({category:"audit",level:"warning",message:"audit allow row write failed (best-effort)",data:{cap:event.cap,error:err.message}})})}__name(auditCapabilityDecision,"auditCapabilityDecision");var composition_exports={};__export(composition_exports,{CompositionError:()=>CompositionError,InvalidExplicitGrantsError:()=>InvalidExplicitGrantsError,MAX_DELEGATION_DEPTH:()=>MAX_DELEGATION_DEPTH,MaxDelegationDepthError:()=>MaxDelegationDepthError,SubAgentInvocationError:()=>SubAgentInvocationError,SubAgentNotInProjectError:()=>SubAgentNotInProjectError,UnknownSubAgentError:()=>UnknownSubAgentError,createDelegateTool:()=>createDelegateTool,delegate:()=>delegate,detectCompositionCycle:()=>detectCompositionCycle,detectCycle:()=>detectCycle2,isCompositionError:()=>isCompositionError,resolveSubCallCapabilities:()=>resolveSubCallCapabilities2,resolveSubCallCapabilitiesLenient:()=>resolveSubCallCapabilities,resolveTransitiveCapabilities:()=>resolveTransitiveCapabilities,validateComposition:()=>validateComposition});function resolveTransitiveCapabilities(bundle,allBundles){let union=new Set,missing=[],visited=new Set,visit2=__name(b=>{if(visited.has(b.name))return;visited.add(b.name);for(let token of b.capabilities)isCapability(token)&&union.add(token);let subAgents=b.config.composition?.["sub-agents"]??[];for(let ref of subAgents){let sub=allBundles.get(ref.name);if(!sub){missing.includes(ref.name)||missing.push(ref.name);continue}visit2(sub)}},"visit");return visit2(bundle),{union:Array.from(union).sort(),missing}}__name(resolveTransitiveCapabilities,"resolveTransitiveCapabilities");function detectCycle2(rootKey,nodes){if(!new Map(nodes.map(n=>[n.key,n])).get(rootKey))return null;let bundleMap=new Map;for(let node of nodes)bundleMap.set(node.key,{name:node.key,capabilities:[],config:{version:1,composition:{"sub-agents":node.subAgentKeys.map(k=>({name:k}))}}});let root2=bundleMap.get(rootKey);return detectCompositionCycle({root:root2,agentMap:bundleMap})}__name(detectCycle2,"detectCycle");function validateComposition(root2,allBundles){let cycle=detectCompositionCycle({root:root2,agentMap:allBundles}),missing=[],invalidGrants=[],capUnion=new Set,visited=new Set,visit2=__name(bundle=>{if(visited.has(bundle.name))return;visited.add(bundle.name);for(let token of bundle.capabilities)isCapability(token)&&capUnion.add(token);let subAgents=bundle.config.composition?.["sub-agents"]??[];for(let ref of subAgents){let sub=allBundles.get(ref.name);if(!sub){missing.includes(ref.name)||missing.push(ref.name);continue}if(ref.capability_grant==="explicit"){let declaredSet=new Set(sub.capabilities),invalid=(ref.explicit_grants??[]).filter(t2=>!declaredSet.has(t2));invalid.length>0&&invalidGrants.push({subAgentName:ref.name,invalid,declared:[...sub.capabilities]})}visit2(sub)}},"visit");if(!cycle)visit2(root2);else for(let token of root2.capabilities)isCapability(token)&&capUnion.add(token);let declaredDelegate=root2.capabilities.includes("agent:delegate");return{cycle,missing,transitiveCapabilities:Array.from(capUnion).sort(),declaredDelegate,invalidGrants}}__name(validateComposition,"validateComposition");function _define_property5(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property5,"_define_property");var CompositionError=class extends Error{static{__name(this,"CompositionError")}},InvalidExplicitGrantsError=class extends CompositionError{static{__name(this,"InvalidExplicitGrantsError")}constructor(subAgentName,invalid,declared){super(`composition.sub-agents[name=${subAgentName}].explicit_grants references capabilities the sub-agent never declared: [${invalid.join(", ")}]. Declared by sub-agent: [${declared.join(", ")}]`),_define_property5(this,"code","composition.invalid_explicit_grants"),_define_property5(this,"subAgentName",void 0),_define_property5(this,"invalid",void 0),_define_property5(this,"declared",void 0),this.name="InvalidExplicitGrantsError",this.subAgentName=subAgentName,this.invalid=invalid,this.declared=declared}},SubAgentInvocationError=class extends CompositionError{static{__name(this,"SubAgentInvocationError")}constructor(subAgentName,cause){super(`sub-agent '${subAgentName}' threw during invocation: ${cause?.message??String(cause)}`),_define_property5(this,"code","composition.sub_agent_invocation_failed"),_define_property5(this,"subAgentName",void 0),this.name="SubAgentInvocationError",this.subAgentName=subAgentName,this.cause=cause}};function isCompositionError(err){return err instanceof CompositionError?!0:err instanceof Error?err.name==="MaxDelegationDepthError"||err.name==="UnknownSubAgentError"||err.name==="SubAgentNotInProjectError":!1}__name(isCompositionError,"isCompositionError");function resolveSubCallCapabilities2(input){let{parentCapabilities,subAgentDeclared,ref}=input;if((ref.capability_grant??"inherit")==="explicit"){let explicitGrants=ref.explicit_grants??[],declaredSet=new Set(subAgentDeclared),invalid=explicitGrants.filter(t2=>!declaredSet.has(t2));if(invalid.length>0)throw new InvalidExplicitGrantsError(ref.name,invalid,subAgentDeclared)}return resolveSubCallCapabilities(parentCapabilities,subAgentDeclared,ref)}__name(resolveSubCallCapabilities2,"resolveSubCallCapabilities");function _define_property6(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property6,"_define_property");var MAX_DELEGATION_DEPTH=5,MaxDelegationDepthError=class extends Error{static{__name(this,"MaxDelegationDepthError")}constructor(depth){super(`max delegation depth ${depth} reached (limit ${MAX_DELEGATION_DEPTH})`),_define_property6(this,"depth",void 0),this.name="MaxDelegationDepthError",this.depth=depth}},UnknownSubAgentError=class extends Error{static{__name(this,"UnknownSubAgentError")}constructor(name){super(`sub-agent '${name}' is not declared in composition.sub-agents`),_define_property6(this,"name_",void 0),this.name="UnknownSubAgentError",this.name_=name}},SubAgentNotInProjectError=class extends Error{static{__name(this,"SubAgentNotInProjectError")}constructor(name){super(`sub-agent '${name}' is declared but not present in agents/ directory`),_define_property6(this,"name_",void 0),this.name="SubAgentNotInProjectError",this.name_=name}};async function delegate(input,ctx,runSubAgent){if(assertCapability("agent:delegate",ctx.parentCapabilities),ctx.depth>=MAX_DELEGATION_DEPTH)throw new MaxDelegationDepthError(ctx.depth);let ref=(ctx.parentBundle.config.composition?.["sub-agents"]??[]).find(r=>r.name===input.name);if(!ref)throw new UnknownSubAgentError(input.name);let sub=ctx.projectBundles.find(b=>b.name===ref.name);if(!sub)throw new SubAgentNotInProjectError(ref.name);let subCallCapabilities=resolveSubCallCapabilities(ctx.parentCapabilities,sub.capabilities,ref);return{result:await runSubAgent(sub,subCallCapabilities,input.args),subCallCapabilities}}__name(delegate,"delegate");function createDelegateTool(opts){return __name(async function(input){let{session,runSubAgent,audit}=opts,started=Date.now(),parentCaps=session.capabilityStack[session.capabilityStack.length-1]??session.parentBundle.capabilities,ctx={parentBundle:session.parentBundle,parentCapabilities:parentCaps,depth:session.depth,projectBundles:session.projectBundles};try{let grantMode=(session.parentBundle.config.composition?.["sub-agents"]??[]).find(r=>r.name===input.name)?.capability_grant??"inherit";session.depth+=1;let result=await delegate(input,ctx,__name(async(sub,capabilities,args)=>{session.capabilityStack.push([...capabilities]);try{return await runSubAgent(sub,capabilities,args)}finally{session.capabilityStack.pop()}},"wrappedRunSubAgent"));return await audit?.emit({subAgentName:input.name,grantMode,resolvedCapabilities:result.subCallCapabilities,args:input.args,durationMs:Date.now()-started,depth:ctx.depth}),result}catch(err){let wrapped=err instanceof SubAgentInvocationError?err:new SubAgentInvocationError(input.name,err);throw await audit?.emit({subAgentName:input.name,grantMode:"inherit",resolvedCapabilities:[],args:input.args,durationMs:Date.now()-started,depth:ctx.depth,error:{name:err.name??"Error",message:err.message??String(err)}}),wrapped}finally{session.depth-=1}},"delegateFn")}__name(createDelegateTool,"createDelegateTool");init_dist();init_api();init_config();init_project();var MAX_TYPE_TO_CONFIRM_ATTEMPTS=3;async function runConsent(input){let{caps,allowShell=!1,quiet=!1,io}=input,{caps:known}=partitionCapabilities(caps);if(renderCapabilityList(known,io),quiet)return known.some(isCritical)?(io.print("! critical-tier capabilities require interactive consent (use --allow-critical only when you understand the risk)"),{decision:"denied",approved:[]}):{decision:"allowed",approved:[...known]};let highRisk=known.filter(isHighRisk);if(highRisk.length===0){let ok=await io.promptYesNo(`? Proceed with install of ${input.agentName}? [y/N]`);return{decision:ok?"allowed":"denied",approved:ok?[...known]:[]}}let approved=known.filter(cap=>!isHighRisk(cap)),denied=[];for(let cap of highRisk.filter(c2=>!isCritical(c2))){if(cap==="shell:exec"&&allowShell){approved.push(cap),io.print(` \u2713 ${cap} (--allow-shell)`);continue}await io.promptYesNo(`? Allow ${cap} for ${input.agentName}? [y/n]`)?approved.push(cap):denied.push(cap)}if(denied.length>0)return io.print(`! aborting install \u2014 denied: ${denied.join(", ")}`),{decision:"denied",approved:[]};for(let cap of highRisk.filter(isCritical)){if(!await typeToConfirm(cap,input.agentName,io))return io.print(`! aborting install \u2014 failed to confirm ${cap}`),{decision:"denied",approved:[]};approved.push(cap)}return{decision:"allowed",approved}}__name(runConsent,"runConsent");async function typeToConfirm(cap,agentName,io){io.print(""),io.print(`! ${agentName} declares the CRITICAL capability '${cap}'`),io.print(" Type the literal token to confirm; anything else aborts.");for(let attempt=1;attempt<=MAX_TYPE_TO_CONFIRM_ATTEMPTS;attempt++){if(await io.promptText(` type '${cap}' (${attempt}/${MAX_TYPE_TO_CONFIRM_ATTEMPTS}): `)===cap)return!0;io.print(" mismatch.")}return!1}__name(typeToConfirm,"typeToConfirm");function renderCapabilityList(caps,io){if(caps.length===0){io.print(" (no capabilities declared \u2014 read-only default trio will apply at runtime)");return}io.print(""),io.print("This agent declares the following capabilities:");let byTier={low:[],medium:[],high:[],critical:[]};for(let cap of caps)byTier[riskTierOf(cap)].push(cap);let ORDER=["low","medium","high","critical"];for(let tier of ORDER){let list=byTier[tier];if(list.length!==0)for(let cap of list.sort())io.print(` \u25CF ${tier.padEnd(8)} ${cap}`)}io.print("")}__name(renderCapabilityList,"renderCapabilityList");function defaultConsentIO(){return{print(line){process.stdout.write(`${line}
1087
+ `).filter(Boolean).map(line=>{let code2=line.slice(0,2),path47=line.slice(3).trim();return{verb:code2.startsWith("A")||code2.startsWith("?")?"added":code2.startsWith("D")?"removed":"changed",key:path47,origin:"local-uncommitted"}});return{surface:"code",status:items.length===0?"unchanged":"ok",changedCount:items.length,conflictCount:0,items}}catch{return{surface:"code",status:"unchanged",changedCount:0,conflictCount:0,items:[]}}}function mergeCodeSurfaces(serverCode,local){if(!serverCode)return local;if(serverCode.status==="failed"||serverCode.status==="timed_out")return{...serverCode,items:[...serverCode.items??[],...local.items??[]],changedCount:serverCode.changedCount+local.changedCount};let items=[...serverCode.items??[],...local.items??[]],changedCount=serverCode.changedCount+local.changedCount,conflictCount=serverCode.conflictCount+local.conflictCount;return{surface:"code",status:changedCount>0||conflictCount>0?"ok":"unchanged",durationMs:serverCode.durationMs,changedCount,conflictCount,items}}async function statusCommand2(arg1,maybeCmd){let cmd=maybeCmd??arg1,options=maybeCmd?arg1:cmd.opts(),program2=cmd.parent??cmd,envOverride2=envOverrideFromCommand(program2),ctx=await getProjectContext({cwd:options.cwd,envOverride:envOverride2}),api=new FimoApiClient().withEnv(ctx.env),cwd=resolveProjectCwd(options.cwd),surfaces=pickSurfaces(options),codePromise=localCodeSurface(cwd),serverPromise=withSoftTimeout(api.getEnvStatus(ctx.projectId,ctx.env,{against:options.vs,surfaces}),SOFT_TIMEOUT_MS*15),[local,serverResult]=await Promise.all([codePromise,serverPromise]);if(serverResult.kind==="timeout"){ui.error({command:"status",code:"STATUS_TIMEOUT",message:`Server did not respond within ${SOFT_TIMEOUT_MS*15/1e3}s. Try again, or run \`fimo diff\` to drill in.`});return}if(serverResult.kind==="error"){let err=serverResult.error,message=err instanceof Error?err.message:String(err);ui.error({command:"status",code:"STATUS_REQUEST_FAILED",message:`Failed to fetch status: ${message}`});return}let server=serverResult.value,serverCode=server.surfaces.find(s=>s.surface==="code"),code2=mergeCodeSurfaces(serverCode,local),merged={...server,surfaces:[code2,...server.surfaces.filter(s=>s.surface!=="code")]};ui.result({command:"status",data:merged,render:__name(rctx=>{let p2=rctx.color?palette:makeColorPalette({forceDisable:!0});return renderStatus2(merged,p2,{short:options.short,surface:surfaces?.length===1?surfaces[0]:void 0,all:options.all,ascii:rctx.ascii})},"render")})}var SOFT_TIMEOUT_MS,init_status=__esm({"src/cli/commands/status.ts"(){init_dist();init_api();init_color();init_render_status();init_git();init_project_context();init_project();SOFT_TIMEOUT_MS=2e3;__name(pickSurfaces,"pickSurfaces");__name(withSoftTimeout,"withSoftTimeout");__name(localCodeSurface,"localCodeSurface");__name(mergeCodeSurfaces,"mergeCodeSurfaces");__name(statusCommand2,"statusCommand")}});init_dist();import fs42 from"node:fs";import path46 from"node:path";var import_index=__toESM(require_commander(),1),{program,createCommand,createArgument,createOption,CommanderError,InvalidArgumentError,InvalidOptionArgumentError,Command,Argument,Option,Help}=import_index.default;init_api();import fs7 from"node:fs";import path7 from"node:path";var import_yaml=__toESM(require_dist(),1);import{createHash as createHash2}from"node:crypto";import{promises}from"node:fs";import path4 from"node:path";import{z as z62}from"zod";var CapabilityTokenSchema=z62.string().min(1).regex(/^[a-z][a-z0-9_]*:[a-z][a-z0-9_]*(?::[a-z][a-z0-9_]*)?$/,{error:"capability tokens must match verb:noun or verb:noun:qualifier (lowercase + digits + underscores; must start with a letter)"}),CapabilitiesFileSchema=z62.array(CapabilityTokenSchema);import{z as z63}from"zod";var CronTriggerSchema=z63.object({type:z63.literal("schedule"),cron:z63.string().min(1,"cron expression required"),tz:z63.string().optional()}),ManualTriggerSchema2=z63.object({type:z63.literal("manual")}),WebhookTriggerSchema2=z63.object({type:z63.literal("webhook"),path:z63.string().min(1).regex(/^[a-z0-9][a-z0-9_/-]*$/i,"webhook path must be lowercase alphanumeric with optional / - _")}),TriggerSchema2=z63.discriminatedUnion("type",[ManualTriggerSchema2,CronTriggerSchema,WebhookTriggerSchema2]),SubAgentRefSchema=z63.object({name:z63.string().min(1),capability_grant:z63.enum(["inherit","explicit"]).optional(),explicit_grants:z63.array(z63.string()).optional()}).refine(v=>v.capability_grant!=="explicit"||Array.isArray(v.explicit_grants)&&v.explicit_grants.length>0,{message:"`explicit_grants` is required when `capability_grant: explicit`",path:["explicit_grants"]}),CompositionConfigSchema=z63.object({"sub-agents":z63.array(SubAgentRefSchema)}),RuntimeConfigSchema=z63.object({cloud:z63.boolean().optional(),dev:z63.boolean().optional(),long_running:z63.boolean().optional()}),DataSourceSchema=z63.enum(["main","prod"]),ConfigValueKeySchema=z63.string().min(1).max(255).regex(/^[A-Z_][A-Z0-9_]*$/,"secret keys must be UPPER_SNAKE_CASE and start with a letter or underscore"),PUBLIC_CONFIG_PREFIX=/^(PUBLIC_|VITE_|NEXT_PUBLIC_)/,AgentSecretRequestSchema=z63.preprocess(value=>typeof value=="string"?{key:value}:value,z63.object({key:ConfigValueKeySchema.refine(key=>!PUBLIC_CONFIG_PREFIX.test(key),{message:"agent secrets cannot use public variable prefixes (PUBLIC_, VITE_, NEXT_PUBLIC_)"}),required:z63.boolean().default(!0),delivery:z63.literal("process_env").default("process_env")})),IntegrationKeySchema=z63.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*$/,"integration keys must be lowercase alphanumeric with optional _ or -"),IntegrationToolKeySchema=z63.string().min(1).max(120).regex(/^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)*$/,"integration tool keys must be lowercase dot-separated identifiers with optional _ or -"),IntegrationPolicyEntrySchema=z63.preprocess(value=>typeof value=="boolean"?{enabled:value}:value,z63.object({enabled:z63.boolean().default(!0),tools:z63.record(IntegrationToolKeySchema,z63.boolean()).optional()})),IntegrationPolicySchema=z63.record(IntegrationKeySchema,IntegrationPolicyEntrySchema),AgentConfigSchema=z63.object({version:z63.literal(1),description:z63.string().min(1).max(280).optional(),runtime:RuntimeConfigSchema.optional(),triggers:z63.array(TriggerSchema2).optional(),composition:CompositionConfigSchema.optional(),data_sources:z63.array(DataSourceSchema).optional(),secrets:z63.array(AgentSecretRequestSchema).optional(),integrations:IntegrationPolicySchema.optional(),integration_policy:IntegrationPolicySchema.optional()}).refine(config=>!(config.integrations&&config.integration_policy),{message:"use either `integrations` or legacy `integration_policy`, not both",path:["integrations"]});function _define_property(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property,"_define_property");var BundleParseError=class extends Error{static{__name(this,"BundleParseError")}constructor(bundlePath,file,message,cause){super(`[${file}] ${message}`),_define_property(this,"bundlePath",void 0),_define_property(this,"file",void 0),_define_property(this,"cause",void 0),this.name="BundleParseError",this.bundlePath=bundlePath,this.file=file,this.cause=cause}};async function fileExists(file){try{return(await promises.stat(file)).isFile()}catch{return!1}}__name(fileExists,"fileExists");async function readFileOrNull(file){try{return await promises.readFile(file,"utf8")}catch(err){if(err.code==="ENOENT")return null;throw err}}__name(readFileOrNull,"readFileOrNull");async function listDir(dir){try{return(await promises.readdir(dir,{withFileTypes:!0,recursive:!0})).filter(e=>e.isFile()).map(e=>{let parentPath=e.parentPath??e.path??dir;return path4.relative(dir,path4.join(parentPath,e.name))}).sort()}catch(err){if(err.code==="ENOENT")return[];throw err}}__name(listDir,"listDir");function parseYamlStrict(text3,file,bundlePath){try{return(0,import_yaml.parse)(text3)}catch(err){throw new BundleParseError(bundlePath,file,`invalid YAML: ${err.message}`,err)}}__name(parseYamlStrict,"parseYamlStrict");function formatZodIssue(issue){return`${issue.path.length===0?"(root)":issue.path.join(".")}: ${issue.message}`}__name(formatZodIssue,"formatZodIssue");async function parseBundle(bundlePath,opts={}){let name=path4.basename(bundlePath),goalPath=path4.join(bundlePath,"GOAL.md"),goal=await readFileOrNull(goalPath);if(goal===null)throw new BundleParseError(bundlePath,"GOAL.md","GOAL.md is required but missing");if(goal.trim().length===0)throw new BundleParseError(bundlePath,"GOAL.md","GOAL.md is empty");let configPath=path4.join(bundlePath,"config.yaml"),configRaw=await readFileOrNull(configPath),config;if(configRaw===null){if(!opts.defaultConfig)throw new BundleParseError(bundlePath,"config.yaml","config.yaml is required but missing");config={version:1}}else{let yamlData=parseYamlStrict(configRaw,"config.yaml",bundlePath),parsed=AgentConfigSchema.safeParse(yamlData);if(!parsed.success){let issues=parsed.error.issues.map(formatZodIssue).join("; ");throw new BundleParseError(bundlePath,"config.yaml",`schema validation failed: ${issues}`)}config=parsed.data}let soul=await readFileOrNull(path4.join(bundlePath,"SOUL.md")),capsPath=path4.join(bundlePath,"capabilities.yaml"),capsRaw=await readFileOrNull(capsPath),capabilities=[];if(capsRaw!==null){let candidate=parseYamlStrict(capsRaw,"capabilities.yaml",bundlePath)??[],parsed=CapabilitiesFileSchema.safeParse(candidate);if(!parsed.success){let issues=parsed.error.issues.map(formatZodIssue).join("; ");throw new BundleParseError(bundlePath,"capabilities.yaml",`schema validation failed: ${issues} \u2014 file must be a bare YAML list of capability tokens`)}capabilities=parsed.data}let[scripts2,references,assets3]=await Promise.all([listDir(path4.join(bundlePath,"scripts")),listDir(path4.join(bundlePath,"references")),listDir(path4.join(bundlePath,"assets"))]),warnings=[],pluginsDir=path4.join(bundlePath,"plugins");try{(await promises.stat(pluginsDir)).isDirectory()&&warnings.push({pointer:"plugins/",message:"`plugins/` is reserved for v1.x and will be ignored at runtime."})}catch{}let checksum=await computeBundleChecksum(bundlePath,{goal,soul,configRaw,capsRaw,scripts:scripts2,references,assets:assets3});return{name,path:bundlePath,goal,soul,config,capabilities,scripts:scripts2,references,assets:assets3,checksum,warnings}}__name(parseBundle,"parseBundle");async function computeBundleChecksum(bundlePath,parts){let hash=createHash2("sha256");hash.update("GOAL.md\0"),hash.update(parts.goal),hash.update("\0config.yaml\0"),hash.update(parts.configRaw??""),parts.capsRaw!==null&&(hash.update("\0capabilities.yaml\0"),hash.update(parts.capsRaw)),parts.soul!==null&&(hash.update("\0SOUL.md\0"),hash.update(parts.soul));let dirs=[["scripts",parts.scripts],["references",parts.references],["assets",parts.assets]];for(let[dirName,files]of dirs)for(let rel of files){let filePath=path4.join(bundlePath,dirName,rel);try{let buf=await promises.readFile(filePath);hash.update(`\0${dirName}/${rel}\0`),hash.update(buf)}catch{}}return hash.digest("hex")}__name(computeBundleChecksum,"computeBundleChecksum");async function listBundles(agentsDir){let entries2=[];try{entries2=await promises.readdir(agentsDir,{withFileTypes:!0})}catch(err){if(err.code==="ENOENT")return[];throw err}let bundles=[];for(let entry of entries2){if(!entry.isDirectory())continue;let bundlePath=path4.join(agentsDir,entry.name);if(await fileExists(path4.join(bundlePath,"GOAL.md")))try{bundles.push(await parseBundle(bundlePath))}catch{}}return bundles.sort((a,b)=>a.name.localeCompare(b.name))}__name(listBundles,"listBundles");var ENTRIES=[{token:"files:read",risk:"low",description:"Read project files"},{token:"files:write",risk:"medium",description:"Write or delete project files"},{token:"cms:read",risk:"low",description:"Read CMS content"},{token:"cms:write",risk:"medium",description:"Create, update, or delete CMS entries"},{token:"cms:schema:read",risk:"low",description:"Read CMS schemas"},{token:"cms:schema:write",risk:"high",description:"Modify CMS schemas (destructive \u2014 alters all entries of the type)"},{token:"assets:read",risk:"low",description:"Read uploaded media"},{token:"assets:write",risk:"medium",description:"Upload, replace, or delete media"},{token:"i18n:read",risk:"low",description:"Read translation catalogs"},{token:"i18n:write",risk:"medium",description:"Modify translation catalogs via the fimo i18n CLI"},{token:"forms:read",risk:"low",description:"Read form schemas and submissions"},{token:"forms:write",risk:"medium",description:"Modify form schemas or clear submissions"},{token:"git:read",risk:"low",description:"Read git state"},{token:"git:branch",risk:"medium",description:"Create agent-proposed branches off main"},{token:"git:commit",risk:"medium",description:"Commit changes to an agent branch"},{token:"git:push",risk:"high",description:"Push to the project remote (main push is intercepted)"},{token:"git:tag",risk:"high",runtimeOnly:!0,description:"Used by runtime for prod release tags; agents cannot call directly"},{token:"fimo:deploy",risk:"critical",description:"Trigger a production deploy"},{token:"fimo:logs:read",risk:"low",description:"Read production logs"},{token:"fimo:analytics:read",risk:"low",description:"Read analytics data"},{token:"fimo:preview:read",risk:"low",description:"Read a current preview URL for an env (no commit, no deploy)"},{token:"net:fetch",risk:"medium",description:"Make outbound HTTP requests"},{token:"shell:exec",risk:"high",description:"Run arbitrary shell commands inside the sandbox"},{token:"agent:delegate",risk:"medium",description:"Invoke declared sub-agents"},{token:"runtime:long_running",risk:"high",description:"Run autonomously past the default 30 min limit (up to 4h walltime / 12h ceiling)"},{token:"runtime:auto_merge",risk:"critical",description:"Auto-merge trivial proposed branches to main without per-change human review"}],BY_TOKEN=new Map(ENTRIES.map(e=>[e.token,e])),CAPABILITY_VOCABULARY=ENTRIES;function getCapability(token){return BY_TOKEN.get(token)??null}__name(getCapability,"getCapability");function isKnownCapability(token){return BY_TOKEN.has(token)}__name(isKnownCapability,"isKnownCapability");function isHighRisk(token){let def=getCapability(token);return def?.risk==="high"||def?.risk==="critical"}__name(isHighRisk,"isHighRisk");function isRuntimeOnly(token){return getCapability(token)?.runtimeOnly===!0}__name(isRuntimeOnly,"isRuntimeOnly");function validateBundle(bundle,opts={}){let issues=[],available=new Map((opts.availableAgents??[]).map(b=>[b.name,b]));for(let i=0;i<bundle.capabilities.length;i++){let token=bundle.capabilities[i];if(token!==void 0){if(!isKnownCapability(token)){issues.push({pointer:`capabilities.yaml:[${i}]`,message:`unknown capability token: ${token}`,severity:"error"});continue}isRuntimeOnly(token)&&issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is runtime-orchestration-only; agents cannot declare it (the runtime intercepts)`,severity:"error"}),getCapability(token)?.risk==="critical"&&issues.push({pointer:`capabilities.yaml:[${i}]`,message:`${token} is critical-risk; requires project policy + install-time confirmation`,severity:"warning"})}}let subAgents=bundle.config.composition?.["sub-agents"]??[];subAgents.length>0&&!bundle.capabilities.includes("agent:delegate")&&issues.push({pointer:"capabilities.yaml",message:"`composition.sub-agents` is declared but `agent:delegate` capability is missing",severity:"error"});for(let i=0;i<subAgents.length;i++){let sub=subAgents[i];sub&&opts.availableAgents&&!available.has(sub.name)&&issues.push({pointer:`config.yaml:composition.sub-agents[${i}].name`,message:`sub-agent '${sub.name}' is not present in the project's agents directory`,severity:"error"})}if(opts.availableAgents&&subAgents.length>0){let cycle=detectCycle(bundle,available);cycle&&issues.push({pointer:"config.yaml:composition",message:`composition cycle detected: ${cycle.join(" \u2192 ")}`,severity:"error"})}let webhookPaths=new Set,triggers=bundle.config.triggers??[];for(let i=0;i<triggers.length;i++){let t2=triggers[i];t2&&t2.type==="webhook"&&(webhookPaths.has(t2.path)&&issues.push({pointer:`config.yaml:triggers[${i}].path`,message:`duplicate webhook path '${t2.path}' within bundle`,severity:"error"}),webhookPaths.add(t2.path))}return bundle.config.data_sources&&bundle.config.data_sources.length===0&&issues.push({pointer:"config.yaml:data_sources",message:'data_sources is empty; omit the field to default to ["main"]',severity:"warning"}),issues}__name(validateBundle,"validateBundle");function detectCycle(start,available){let color=new Map,parent2=new Map;function visit2(name){color.set(name,1);let children2=available.get(name)?.config.composition?.["sub-agents"]??[];for(let child of children2){if(!child)continue;let c2=color.get(child.name)??0;if(c2===1){let cycle=[child.name],curr=name;for(;curr&&curr!==child.name;)cycle.unshift(curr),curr=parent2.get(curr)??null;return cycle.unshift(child.name),cycle}if(c2===0&&available.has(child.name)){parent2.set(child.name,name);let found=visit2(child.name);if(found)return found}}return color.set(name,2),null}return __name(visit2,"visit"),visit2(start.name)}__name(detectCycle,"detectCycle");function agentIntegrationPolicy(config){return config.integrations??config.integration_policy??{}}__name(agentIntegrationPolicy,"agentIntegrationPolicy");function agentAllowsIntegrationTool(policy,integrationKey,toolKey){let entry=policy[integrationKey];return entry?.enabled?entry.tools?.[toolKey]===!0:!1}__name(agentAllowsIntegrationTool,"agentAllowsIntegrationTool");function enabledAgentIntegrationTools(entry){return entry?.enabled?Object.entries(entry.tools??{}).filter(([,enabled])=>enabled).map(([tool])=>tool).sort((a,b)=>a.localeCompare(b)):[]}__name(enabledAgentIntegrationTools,"enabledAgentIntegrationTools");function _define_property2(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property2,"_define_property");var CapabilityDeniedError=class extends Error{static{__name(this,"CapabilityDeniedError")}constructor(required,granted){let def=getCapability(required),what=def?.description?` (${def.description})`:"";super(`capability '${required}'${what} denied \u2014 granted: [${granted.join(", ")}]`),_define_property2(this,"required",void 0),_define_property2(this,"granted",void 0),this.name="CapabilityDeniedError",this.required=required,this.granted=granted}};function assertCapability(required,granted){if(!granted.includes(required))throw new CapabilityDeniedError(required,granted)}__name(assertCapability,"assertCapability");function resolveSubCallCapabilities(parentGranted,subDeclared,ref){if((ref.capability_grant??"inherit")==="explicit"){let explicit=ref.explicit_grants??[];return subDeclared.filter(t2=>explicit.includes(t2))}return[...subDeclared]}__name(resolveSubCallCapabilities,"resolveSubCallCapabilities");function _define_property3(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property3,"_define_property");var BundleError=class extends Error{static{__name(this,"BundleError")}constructor(message,remediation,bundlePath){super(message),_define_property3(this,"remediation",void 0),_define_property3(this,"bundlePath",void 0),this.name=this.constructor.name,this.remediation=remediation,this.bundlePath=bundlePath}},BundleValidationError=class extends BundleError{static{__name(this,"BundleValidationError")}constructor(message,options={}){super(message,options.remediation??"Fix the file in the bundle and re-run `fimo agents validate`.",options.bundlePath),_define_property3(this,"code","bundle.validation"),_define_property3(this,"file",void 0),_define_property3(this,"cause",void 0),this.file=options.file,this.cause=options.cause}};var BundleInvalidCapabilityError=class extends BundleError{static{__name(this,"BundleInvalidCapabilityError")}constructor(token,reason,options={}){let remediation=reason==="runtime_only"?`'${token}' is reserved for the runtime \u2014 drop it from capabilities.yaml.`:options.suggestion?`Unknown capability '${token}'. Did you mean '${options.suggestion}'?`:`Unknown capability '${token}'. Run \`fimo agents list-capabilities\` to see the vocabulary.`;super(reason==="runtime_only"?`Capability '${token}' is runtime-orchestration-only and cannot be declared.`:`Capability '${token}' is not in the closed vocabulary.`,remediation,options.bundlePath),_define_property3(this,"code","bundle.invalid_capability"),_define_property3(this,"token",void 0),_define_property3(this,"reason",void 0),this.token=token,this.reason=reason}},BundleCompositionCycleError=class extends BundleError{static{__name(this,"BundleCompositionCycleError")}constructor(cycle,options={}){super(`Composition cycle detected: ${cycle.join(" \u2192 ")}`,"Break the cycle by removing one of the sub-agent references in the chain.",options.bundlePath),_define_property3(this,"code","bundle.composition_cycle"),_define_property3(this,"cycle",void 0),this.cycle=[...cycle]}},BundleTemplateNotFoundError=class extends BundleError{static{__name(this,"BundleTemplateNotFoundError")}constructor(templateName,available){super(`Template '${templateName}' not found.`,available.length>0?`Available templates: ${available.join(", ")}. Use \`fimo agents list-templates\` to see all options.`:"No templates are bundled with this CLI. Use the empty default by omitting --template."),_define_property3(this,"code","bundle.template_not_found"),_define_property3(this,"templateName",void 0),_define_property3(this,"available",void 0),this.templateName=templateName,this.available=[...available]}};function isBundleError(err){return err instanceof BundleError}__name(isBundleError,"isBundleError");function detectCompositionCycle(input){let{root:root2,agentMap}=input,WHITE=0,GRAY=1,BLACK=2,color=new Map,parent2=new Map,visit2=__name(name=>{color.set(name,GRAY);let children2=agentMap.get(name)?.config.composition?.["sub-agents"]??[];for(let child of children2){if(!child)continue;let c2=color.get(child.name)??WHITE;if(c2===GRAY){let cycle=[child.name],curr=name;for(;curr&&curr!==child.name;)cycle.unshift(curr),curr=parent2.get(curr)??null;return cycle.unshift(child.name),cycle}if(c2===WHITE&&agentMap.has(child.name)){parent2.set(child.name,name);let found=visit2(child.name);if(found)return found}}return color.set(name,BLACK),null},"visit");return visit2(root2.name)}__name(detectCompositionCycle,"detectCompositionCycle");function validateAgainstVocabulary(tokens,vocab=CAPABILITY_VOCABULARY){let byToken=new Map(vocab.map(v=>[v.token,v])),unknown=[],runtimeOnly=[],highRisk=[];for(let token of tokens){let def=byToken.get(token);if(!def){unknown.push(token);continue}def.runtimeOnly&&runtimeOnly.push(token),(def.risk==="high"||def.risk==="critical")&&highRisk.push(token)}return{ok:unknown.length===0&&runtimeOnly.length===0,unknown,runtimeOnly,highRisk}}__name(validateAgainstVocabulary,"validateAgainstVocabulary");function suggestCapability(token,vocab=CAPABILITY_VOCABULARY){let best=null,bestDistance=1/0;for(let def of vocab){let d3=levenshtein(token,def.token);d3<bestDistance&&(bestDistance=d3,best=def.token)}return bestDistance<=2?best:null}__name(suggestCapability,"suggestCapability");function levenshtein(a,b){if(a===b)return 0;let al=a.length,bl=b.length;if(al===0)return bl;if(bl===0)return al;let prev2=Array.from({length:bl+1},(_,i)=>i);for(let i=1;i<=al;i++){let curr=new Array(bl+1);curr[0]=i;for(let j2=1;j2<=bl;j2++){let cost=a[i-1]===b[j2-1]?0:1;curr[j2]=Math.min((prev2[j2]??0)+1,(curr[j2-1]??0)+1,(prev2[j2-1]??0)+cost)}prev2=curr}return prev2[bl]??0}__name(levenshtein,"levenshtein");import{z as z64}from"zod";var SurfaceGuardPolicySchema=z64.enum(["block","warn","allow"]),ClassificationSchema=z64.enum(["trivial","low_risk","needs_review"]),SurfaceGuardsSchema=z64.object({code:SurfaceGuardPolicySchema.optional(),content:SurfaceGuardPolicySchema.optional(),translations:SurfaceGuardPolicySchema.optional(),assets:SurfaceGuardPolicySchema.optional()}),AutoMergePolicySchema=z64.object({enabled:z64.boolean(),allowed_skills:z64.array(z64.string().min(1)).default([]),allowed_classifications:z64.array(ClassificationSchema).default([]),surface_guards:SurfaceGuardsSchema.default({})}),NotificationDigestSchema=z64.enum(["off","daily","weekly"]),NotificationFormatSchema=z64.object({markdown:z64.boolean().default(!0),html:z64.boolean().default(!1)}),NotificationsPolicySchema=z64.object({email_recipients:z64.array(z64.string().email("invalid email address")).default([]),format:NotificationFormatSchema.default({markdown:!0,html:!1}),digest:NotificationDigestSchema.default("off")}),FimoAgentsConfigSchema=z64.object({auto_merge:AutoMergePolicySchema.optional(),notifications:NotificationsPolicySchema.optional()}),FimoConfigSchema=z64.object({agents:FimoAgentsConfigSchema.optional()}).passthrough();function parseFimoConfig(jsonOrText,opts={}){let raw;if(typeof jsonOrText=="string")try{raw=JSON.parse(jsonOrText)}catch(err){throw new BundleValidationError(`${opts.path??"fimo.config.json"} is not valid JSON: ${err.message}`,{remediation:"Run the file through `jq .` or your editor JSON validator and fix the syntax.",file:opts.path??"fimo.config.json",cause:err})}else raw=jsonOrText;let parsed=FimoConfigSchema.safeParse(raw);if(!parsed.success){let issues=parsed.error.issues.map(i=>`${i.path.join(".")||"(root)"}: ${i.message}`).join("; ");throw new BundleValidationError(`${opts.path??"fimo.config.json"} schema validation failed: ${issues}`,{remediation:"See `fimo.config.json` shape in the lifecycle docs (`fimo agents docs lifecycle` or visit lifecycle.html#config).",file:opts.path??"fimo.config.json"})}let data2=parsed.data;if(data2.agents?.auto_merge?.enabled===!0&&(data2.agents.auto_merge.allowed_classifications??[]).length===0)throw new BundleValidationError("`agents.auto_merge.enabled: true` but `allowed_classifications` is empty \u2014 nothing would ever auto-merge.",{remediation:'Either set `allowed_classifications: ["trivial"]` (or any subset) or set `enabled: false`.',file:opts.path??"fimo.config.json"});return data2}__name(parseFimoConfig,"parseFimoConfig");function requireCloudActivationNotifications(config){let recipients=config?.agents?.notifications?.email_recipients??[];if(recipients.length===0)throw new BundleValidationError("Activating a cloud-time trigger requires `agents.notifications.email_recipients` to be non-empty.",{remediation:"Add at least one email to `fimo-config.json` \u2192 `agents.notifications.email_recipients`. This is where lifecycle proposal emails are sent (mandatory per ADR-0009).",file:"fimo-config.json"});return recipients}__name(requireCloudActivationNotifications,"requireCloudActivationNotifications");import{z as z65}from"zod";function toSpec(def){return{token:def.token,riskTier:def.risk,description:def.description,...def.runtimeOnly?{runtimeOnly:!0}:{}}}__name(toSpec,"toSpec");var VOCABULARY=Object.freeze(Object.fromEntries(CAPABILITY_VOCABULARY.filter(d3=>!d3.runtimeOnly).map(d3=>[d3.token,toSpec(d3)]))),CapabilityToken=z65.enum(Object.keys(VOCABULARY)),CapabilitiesArraySchema=z65.array(CapabilityToken);function riskTierOf(cap){let def=VOCABULARY[cap];if(!def)throw new Error(`riskTierOf: '${cap}' is not in the vocabulary`);return def.riskTier}__name(riskTierOf,"riskTierOf");function isCapability(token){return Object.prototype.hasOwnProperty.call(VOCABULARY,token)}__name(isCapability,"isCapability");function partitionCapabilities(tokens){let caps=[],unknown=[];for(let t2 of tokens)isCapability(t2)?caps.push(t2):unknown.push(t2);return{caps,unknown}}__name(partitionCapabilities,"partitionCapabilities");function isCritical(cap){return riskTierOf(cap)==="critical"}__name(isCritical,"isCritical");var OPERATION_CAP={"cms.list":"cms:read","cms.get":"cms:read","cms.query":"cms:read","cms.create":"cms:write","cms.update":"cms:write","cms.delete":"cms:write","cms.bulk_create":"cms:write","cms.bulk_update":"cms:write","cms.bulk_delete":"cms:write","cms.schema.list":"cms:schema:read","cms.schema.get":"cms:schema:read","cms.schema.push":"cms:schema:write","cms.schema.delete":"cms:schema:write","assets.list":"assets:read","assets.get":"assets:read","assets.upload":"assets:write","assets.generate":"assets:write","assets.create_folder":"assets:write","assets.move":"assets:write","assets.delete":"assets:write","i18n.list":"i18n:read","i18n.get":"i18n:read","i18n.create":"i18n:write","i18n.update":"i18n:write","i18n.delete":"i18n:write","forms.list":"forms:read","forms.get":"forms:read","forms.push":"forms:write","forms.delete":"forms:write","files.read":"files:read","files.write":"files:write","git.push":"git:push","shell.exec":"shell:exec","fimo.deploy":"fimo:deploy","fimo.logs.read":"fimo:logs:read","fimo.analytics.read":"fimo:analytics:read","fimo.preview.url":"fimo:preview:read","net.fetch":"net:fetch","agent.delegate":"agent:delegate","runtime.long_running":"runtime:long_running","runtime.auto_merge":"runtime:auto_merge"};function capabilityFor(op){return OPERATION_CAP[op]}__name(capabilityFor,"capabilityFor");function hasOperation(op){return Object.prototype.hasOwnProperty.call(OPERATION_CAP,op)}__name(hasOperation,"hasOperation");var import_yaml2=__toESM(require_dist(),1);function parseCapabilities(yaml){if(yaml==null||yaml.trim().length===0)return{caps:[],errors:[]};let raw;try{raw=(0,import_yaml2.parse)(yaml)}catch(cause){return{caps:[],errors:[{code:"MALFORMED_YAML",message:`invalid YAML: ${cause.message}`,cause}]}}if(raw==null)return{caps:[],errors:[]};if(!Array.isArray(raw))return{caps:[],errors:[{code:"WRONG_SHAPE",message:"capabilities.yaml must be a bare YAML list of capability tokens (not an object)"}]};let caps=[],errors=[];for(let item of raw){if(typeof item!="string"){errors.push({code:"WRONG_SHAPE",message:`expected a string capability token, got ${typeof item}`});continue}if(!isCapability(item)){if(CAPABILITY_VOCABULARY.find(d3=>d3.token===item)?.runtimeOnly){errors.push({code:"RUNTIME_ONLY_CAPABILITY",message:`'${item}' is runtime-orchestration-only \u2014 agents cannot declare it`,token:item});continue}let suggestion=suggestCapability(item)??void 0;errors.push({code:"UNKNOWN_CAPABILITY",message:suggestion?`unknown capability token '${item}' \u2014 did you mean '${suggestion}'?`:`unknown capability token '${item}'`,token:item,...suggestion?{suggestion}:{}});continue}caps.push(item)}return{caps,errors}}__name(parseCapabilities,"parseCapabilities");function _define_property4(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property4,"_define_property");var CapabilityDenied=class extends Error{static{__name(this,"CapabilityDenied")}constructor(detail){let def=getCapability(detail.cap),description=def?.description?` (${def.description})`:"";super(`capability denied: ${detail.cap}${description} \u2014 reason: ${detail.reason}`),_define_property4(this,"cap",void 0),_define_property4(this,"reason",void 0),_define_property4(this,"granted",void 0),_define_property4(this,"sessionId",void 0),_define_property4(this,"fixHint",void 0),this.name="CapabilityDenied",this.cap=detail.cap,this.reason=detail.reason,this.granted=detail.granted??[],this.sessionId=detail.sessionId,this.fixHint=fixHintFor(detail)}};function fixHintFor(detail){switch(detail.reason){case"not-declared":return`Add '${detail.cap}' to the agent's capabilities.yaml and re-activate.`;case"session-not-found":return`Session '${detail.sessionId??"<unknown>"}' does not exist or has expired.`;case"snapshot-stale":return"Session capability snapshot is corrupted. Restart the agent session.";case"runtime-only":return`'${detail.cap}' is reserved for the platform \u2014 drop it from capabilities.yaml.`;case"auto-merge-blocked":return"runtime:auto_merge is declared but blocked by project policy (fimo.config.json \u2192 agents.auto_merge)."}}__name(fixHintFor,"fixHintFor");var configured=null;async function auditCapabilityDecision(event){if(!configured)return;let row2={...event,ts:new Date().toISOString()};if(event.decision==="deny"){try{await configured.transport.write(row2)}catch(err){throw configured.breadcrumb?.({category:"audit",level:"error",message:"audit deny row write failed",data:{cap:event.cap,error:err.message}}),err}configured.breadcrumb?.({category:"audit",level:"warning",message:`capability denied: ${event.cap}`,data:{sessionId:event.sessionId,cap:event.cap,reason:event.reason}});return}configured.transport.write(row2).catch(err=>{configured?.breadcrumb?.({category:"audit",level:"warning",message:"audit allow row write failed (best-effort)",data:{cap:event.cap,error:err.message}})})}__name(auditCapabilityDecision,"auditCapabilityDecision");var composition_exports={};__export(composition_exports,{CompositionError:()=>CompositionError,InvalidExplicitGrantsError:()=>InvalidExplicitGrantsError,MAX_DELEGATION_DEPTH:()=>MAX_DELEGATION_DEPTH,MaxDelegationDepthError:()=>MaxDelegationDepthError,SubAgentInvocationError:()=>SubAgentInvocationError,SubAgentNotInProjectError:()=>SubAgentNotInProjectError,UnknownSubAgentError:()=>UnknownSubAgentError,createDelegateTool:()=>createDelegateTool,delegate:()=>delegate,detectCompositionCycle:()=>detectCompositionCycle,detectCycle:()=>detectCycle2,isCompositionError:()=>isCompositionError,resolveSubCallCapabilities:()=>resolveSubCallCapabilities2,resolveSubCallCapabilitiesLenient:()=>resolveSubCallCapabilities,resolveTransitiveCapabilities:()=>resolveTransitiveCapabilities,validateComposition:()=>validateComposition});function resolveTransitiveCapabilities(bundle,allBundles){let union=new Set,missing=[],visited=new Set,visit2=__name(b=>{if(visited.has(b.name))return;visited.add(b.name);for(let token of b.capabilities)isCapability(token)&&union.add(token);let subAgents=b.config.composition?.["sub-agents"]??[];for(let ref of subAgents){let sub=allBundles.get(ref.name);if(!sub){missing.includes(ref.name)||missing.push(ref.name);continue}visit2(sub)}},"visit");return visit2(bundle),{union:Array.from(union).sort(),missing}}__name(resolveTransitiveCapabilities,"resolveTransitiveCapabilities");function detectCycle2(rootKey,nodes){if(!new Map(nodes.map(n=>[n.key,n])).get(rootKey))return null;let bundleMap=new Map;for(let node of nodes)bundleMap.set(node.key,{name:node.key,capabilities:[],config:{version:1,composition:{"sub-agents":node.subAgentKeys.map(k=>({name:k}))}}});let root2=bundleMap.get(rootKey);return detectCompositionCycle({root:root2,agentMap:bundleMap})}__name(detectCycle2,"detectCycle");function validateComposition(root2,allBundles){let cycle=detectCompositionCycle({root:root2,agentMap:allBundles}),missing=[],invalidGrants=[],capUnion=new Set,visited=new Set,visit2=__name(bundle=>{if(visited.has(bundle.name))return;visited.add(bundle.name);for(let token of bundle.capabilities)isCapability(token)&&capUnion.add(token);let subAgents=bundle.config.composition?.["sub-agents"]??[];for(let ref of subAgents){let sub=allBundles.get(ref.name);if(!sub){missing.includes(ref.name)||missing.push(ref.name);continue}if(ref.capability_grant==="explicit"){let declaredSet=new Set(sub.capabilities),invalid=(ref.explicit_grants??[]).filter(t2=>!declaredSet.has(t2));invalid.length>0&&invalidGrants.push({subAgentName:ref.name,invalid,declared:[...sub.capabilities]})}visit2(sub)}},"visit");if(!cycle)visit2(root2);else for(let token of root2.capabilities)isCapability(token)&&capUnion.add(token);let declaredDelegate=root2.capabilities.includes("agent:delegate");return{cycle,missing,transitiveCapabilities:Array.from(capUnion).sort(),declaredDelegate,invalidGrants}}__name(validateComposition,"validateComposition");function _define_property5(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property5,"_define_property");var CompositionError=class extends Error{static{__name(this,"CompositionError")}},InvalidExplicitGrantsError=class extends CompositionError{static{__name(this,"InvalidExplicitGrantsError")}constructor(subAgentName,invalid,declared){super(`composition.sub-agents[name=${subAgentName}].explicit_grants references capabilities the sub-agent never declared: [${invalid.join(", ")}]. Declared by sub-agent: [${declared.join(", ")}]`),_define_property5(this,"code","composition.invalid_explicit_grants"),_define_property5(this,"subAgentName",void 0),_define_property5(this,"invalid",void 0),_define_property5(this,"declared",void 0),this.name="InvalidExplicitGrantsError",this.subAgentName=subAgentName,this.invalid=invalid,this.declared=declared}},SubAgentInvocationError=class extends CompositionError{static{__name(this,"SubAgentInvocationError")}constructor(subAgentName,cause){super(`sub-agent '${subAgentName}' threw during invocation: ${cause?.message??String(cause)}`),_define_property5(this,"code","composition.sub_agent_invocation_failed"),_define_property5(this,"subAgentName",void 0),this.name="SubAgentInvocationError",this.subAgentName=subAgentName,this.cause=cause}};function isCompositionError(err){return err instanceof CompositionError?!0:err instanceof Error?err.name==="MaxDelegationDepthError"||err.name==="UnknownSubAgentError"||err.name==="SubAgentNotInProjectError":!1}__name(isCompositionError,"isCompositionError");function resolveSubCallCapabilities2(input){let{parentCapabilities,subAgentDeclared,ref}=input;if((ref.capability_grant??"inherit")==="explicit"){let explicitGrants=ref.explicit_grants??[],declaredSet=new Set(subAgentDeclared),invalid=explicitGrants.filter(t2=>!declaredSet.has(t2));if(invalid.length>0)throw new InvalidExplicitGrantsError(ref.name,invalid,subAgentDeclared)}return resolveSubCallCapabilities(parentCapabilities,subAgentDeclared,ref)}__name(resolveSubCallCapabilities2,"resolveSubCallCapabilities");function _define_property6(obj,key,value){return key in obj?Object.defineProperty(obj,key,{value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}__name(_define_property6,"_define_property");var MAX_DELEGATION_DEPTH=5,MaxDelegationDepthError=class extends Error{static{__name(this,"MaxDelegationDepthError")}constructor(depth){super(`max delegation depth ${depth} reached (limit ${MAX_DELEGATION_DEPTH})`),_define_property6(this,"depth",void 0),this.name="MaxDelegationDepthError",this.depth=depth}},UnknownSubAgentError=class extends Error{static{__name(this,"UnknownSubAgentError")}constructor(name){super(`sub-agent '${name}' is not declared in composition.sub-agents`),_define_property6(this,"name_",void 0),this.name="UnknownSubAgentError",this.name_=name}},SubAgentNotInProjectError=class extends Error{static{__name(this,"SubAgentNotInProjectError")}constructor(name){super(`sub-agent '${name}' is declared but not present in agents/ directory`),_define_property6(this,"name_",void 0),this.name="SubAgentNotInProjectError",this.name_=name}};async function delegate(input,ctx,runSubAgent){if(assertCapability("agent:delegate",ctx.parentCapabilities),ctx.depth>=MAX_DELEGATION_DEPTH)throw new MaxDelegationDepthError(ctx.depth);let ref=(ctx.parentBundle.config.composition?.["sub-agents"]??[]).find(r=>r.name===input.name);if(!ref)throw new UnknownSubAgentError(input.name);let sub=ctx.projectBundles.find(b=>b.name===ref.name);if(!sub)throw new SubAgentNotInProjectError(ref.name);let subCallCapabilities=resolveSubCallCapabilities(ctx.parentCapabilities,sub.capabilities,ref);return{result:await runSubAgent(sub,subCallCapabilities,input.args),subCallCapabilities}}__name(delegate,"delegate");function createDelegateTool(opts){return __name(async function(input){let{session,runSubAgent,audit}=opts,started=Date.now(),parentCaps=session.capabilityStack[session.capabilityStack.length-1]??session.parentBundle.capabilities,ctx={parentBundle:session.parentBundle,parentCapabilities:parentCaps,depth:session.depth,projectBundles:session.projectBundles};try{let grantMode=(session.parentBundle.config.composition?.["sub-agents"]??[]).find(r=>r.name===input.name)?.capability_grant??"inherit";session.depth+=1;let result=await delegate(input,ctx,__name(async(sub,capabilities,args)=>{session.capabilityStack.push([...capabilities]);try{return await runSubAgent(sub,capabilities,args)}finally{session.capabilityStack.pop()}},"wrappedRunSubAgent"));return await audit?.emit({subAgentName:input.name,grantMode,resolvedCapabilities:result.subCallCapabilities,args:input.args,durationMs:Date.now()-started,depth:ctx.depth}),result}catch(err){let wrapped=err instanceof SubAgentInvocationError?err:new SubAgentInvocationError(input.name,err);throw await audit?.emit({subAgentName:input.name,grantMode:"inherit",resolvedCapabilities:[],args:input.args,durationMs:Date.now()-started,depth:ctx.depth,error:{name:err.name??"Error",message:err.message??String(err)}}),wrapped}finally{session.depth-=1}},"delegateFn")}__name(createDelegateTool,"createDelegateTool");init_dist();init_api();init_config();init_project();var MAX_TYPE_TO_CONFIRM_ATTEMPTS=3;async function runConsent(input){let{caps,allowShell=!1,quiet=!1,io}=input,{caps:known}=partitionCapabilities(caps);if(renderCapabilityList(known,io),quiet)return known.some(isCritical)?(io.print("! critical-tier capabilities require interactive consent (use --allow-critical only when you understand the risk)"),{decision:"denied",approved:[]}):{decision:"allowed",approved:[...known]};let highRisk=known.filter(isHighRisk);if(highRisk.length===0){let ok=await io.promptYesNo(`? Proceed with install of ${input.agentName}? [y/N]`);return{decision:ok?"allowed":"denied",approved:ok?[...known]:[]}}let approved=known.filter(cap=>!isHighRisk(cap)),denied=[];for(let cap of highRisk.filter(c2=>!isCritical(c2))){if(cap==="shell:exec"&&allowShell){approved.push(cap),io.print(` \u2713 ${cap} (--allow-shell)`);continue}await io.promptYesNo(`? Allow ${cap} for ${input.agentName}? [y/n]`)?approved.push(cap):denied.push(cap)}if(denied.length>0)return io.print(`! aborting install \u2014 denied: ${denied.join(", ")}`),{decision:"denied",approved:[]};for(let cap of highRisk.filter(isCritical)){if(!await typeToConfirm(cap,input.agentName,io))return io.print(`! aborting install \u2014 failed to confirm ${cap}`),{decision:"denied",approved:[]};approved.push(cap)}return{decision:"allowed",approved}}__name(runConsent,"runConsent");async function typeToConfirm(cap,agentName,io){io.print(""),io.print(`! ${agentName} declares the CRITICAL capability '${cap}'`),io.print(" Type the literal token to confirm; anything else aborts.");for(let attempt=1;attempt<=MAX_TYPE_TO_CONFIRM_ATTEMPTS;attempt++){if(await io.promptText(` type '${cap}' (${attempt}/${MAX_TYPE_TO_CONFIRM_ATTEMPTS}): `)===cap)return!0;io.print(" mismatch.")}return!1}__name(typeToConfirm,"typeToConfirm");function renderCapabilityList(caps,io){if(caps.length===0){io.print(" (no capabilities declared \u2014 read-only default trio will apply at runtime)");return}io.print(""),io.print("This agent declares the following capabilities:");let byTier={low:[],medium:[],high:[],critical:[]};for(let cap of caps)byTier[riskTierOf(cap)].push(cap);let ORDER=["low","medium","high","critical"];for(let tier of ORDER){let list=byTier[tier];if(list.length!==0)for(let cap of list.sort())io.print(` \u25CF ${tier.padEnd(8)} ${cap}`)}io.print("")}__name(renderCapabilityList,"renderCapabilityList");function defaultConsentIO(){return{print(line){process.stdout.write(`${line}
1088
1088
  `)},async promptYesNo(question){let answer=(await readLine(`${question} `)).trim().toLowerCase();return answer==="y"||answer==="yes"},async promptText(question){return(await readLine(question)).trim()}}}__name(defaultConsentIO,"defaultConsentIO");async function readLine(prompt){let readline=await import("node:readline");return new Promise(resolve9=>{let rl=readline.createInterface({input:process.stdin,output:process.stdout});rl.question(prompt,answer=>{rl.close(),resolve9(answer)})})}__name(readLine,"readLine");import fs6 from"node:fs";import path6 from"node:path";init_dist();init_auth_errors();var NAME_RE=/^[a-z][a-z0-9-]*$/;function isValidAgentName(name){return name.length===0||name.length>64?!1:NAME_RE.test(name)}__name(isValidAgentName,"isValidAgentName");var InvalidAgentNameError=class extends Error{static{__name(this,"InvalidAgentNameError")}name="InvalidAgentNameError";attempted;constructor(attempted){super(`'${attempted}' is not a valid agent name. Names must be lowercase, start with a letter, and contain only letters/digits/hyphens.`),this.attempted=attempted}};function resolveProjectRoot(cwd=process.cwd()){let dir=path6.resolve(cwd);for(let i=0;i<8;i++){if(fs6.existsSync(path6.join(dir,"fimo.config.json"))||fs6.existsSync(path6.join(dir,"package.json")))return dir;let parent2=path6.dirname(dir);if(parent2===dir)break;dir=parent2}throw new Error(`Could not find a project root (no fimo.config.json or package.json) under ${cwd}. Run \`fimo agents *\` from inside a project.`)}__name(resolveProjectRoot,"resolveProjectRoot");function resolveFimoProject(cwd=process.cwd()){let dir=path6.resolve(cwd);for(let i=0;i<8;i++){let settingsPath=path6.join(dir,".fimo.settings.json");if(fs6.existsSync(settingsPath))try{let settings=JSON.parse(fs6.readFileSync(settingsPath,"utf8"));return{projectRoot:dir,settings}}catch{return null}let parent2=path6.dirname(dir);if(parent2===dir)break;dir=parent2}return null}__name(resolveFimoProject,"resolveFimoProject");function printBundleError(command,err){if(rethrowCliAuthError(err),isBundleError(err)){let e=err,hintParts=[];e.remediation&&hintParts.push(`fix: ${e.remediation}`),e.bundlePath&&hintParts.push(`at: ${e.bundlePath}`),ui.error({command,code:"AGENT_BUNDLE_ERROR",message:e.message,hint:hintParts.length>0?hintParts.join(" \xB7 "):void 0})}else ui.error({command,code:"AGENT_BUNDLE_ERROR",message:err.message??String(err)})}__name(printBundleError,"printBundleError");var CLOUD_TRIGGERS=new Set(["schedule","webhook"]);async function activateAgent(opts){let cwd=opts.cwd??process.cwd(),projectRoot=resolveFimoProject(cwd)?.projectRoot??resolveProjectRoot(cwd),bundle=await parseBundle(path7.join(projectRoot,"agents",opts.name)),policy=readFimoConfig(projectRoot),triggerEntries=(bundle.config.triggers??[]).map((trigger,index2)=>({trigger,index:index2})).filter(entry=>!opts.trigger||entry.trigger.type===opts.trigger);triggerEntries.some(entry=>CLOUD_TRIGGERS.has(entry.trigger.type))&&requireCloudActivationNotifications(policy);let warnings=[],allBundles=await listBundles(path7.join(projectRoot,"agents")),allByName=new Map(allBundles.map(b=>[b.name,b])),transitive=resolveTransitiveCapabilities(bundle,allByName),vocab=validateAgainstVocabulary(transitive.union,CAPABILITY_VOCABULARY);if(vocab.unknown.length>0&&warnings.push(`Transitive caps contain unknown tokens: ${vocab.unknown.join(", ")}. Fix capabilities.yaml first.`),transitive.missing.length>0&&warnings.push(`Sub-agents not found in this project: ${transitive.missing.join(", ")}.`),transitive.union.length>0){let io=opts.consentIO??defaultConsentIO();if((await runConsent({caps:transitive.union,agentName:opts.name,allowShell:opts.allowShell,quiet:opts.quiet,io})).decision!=="allowed")return{activated:[],warnings:[...warnings,"Install consent denied \u2014 no activations created."],consentDenied:!0}}if(triggerEntries.length===0)return warnings.push(opts.trigger?`No triggers of type '${opts.trigger}' declared in bundle.`:"Bundle declares no triggers."),{activated:[],warnings};let env=opts.env??"main",projectId=opts.projectId??readProjectId(projectRoot);if(!projectId)throw new Error("Could not determine project id. Pass --project, or run from a linked project directory (one containing `.fimo.settings.json`).");let cfg=loadConfig(),api=new FimoApiClient(cfg);try{return{activated:(await api.activateAgent(projectId,env,opts.name,{triggerIndices:triggerEntries.map(entry=>entry.index)})).map(row2=>({trigger:row2.triggerKind,env:row2.env})),warnings}}catch(err){throw err instanceof ApiRequestError?new Error(`Failed to activate '${opts.name}' (HTTP ${err.status}): ${err.detail}`):err}}__name(activateAgent,"activateAgent");function readProjectId(projectRoot){try{return loadProjectSettings(projectRoot).projectId}catch{return}}__name(readProjectId,"readProjectId");function readFimoConfig(projectRoot){for(let file of["fimo-config.json","fimo.config.json"]){let p2=path7.join(projectRoot,file);if(fs7.existsSync(p2))return parseFimoConfig(fs7.readFileSync(p2,"utf8"),{path:file})}}__name(readFimoConfig,"readFimoConfig");async function activateAgentCommand(name,options){try{let result=await activateAgent({name,trigger:options.trigger,env:options.env,cwd:options.cwd,projectId:options.project,quiet:options.quiet,allowShell:options.allowShell});if(result.activated.length===0&&result.warnings.length>0){ui.error({command:"agents activate",code:result.consentDenied?"CONSENT_DENIED":"NO_ACTIVATIONS_CREATED",message:result.warnings.join(`
1089
1089
  `)});return}let data2={agent:name,activated:result.activated,activated_count:result.activated.length};if(result.activated.length===0){ui.info({command:"agents activate",message:`(no triggers activated for '${name}')`});return}ui.ok({command:"agents activate",headline:`activated ${result.activated.length} trigger${result.activated.length===1?"":"s"} for ${name}`,details:data2,warnings:result.warnings.length>0?result.warnings:void 0})}catch(err){printBundleError("agents activate",err)}}__name(activateAgentCommand,"activateAgentCommand");import fs10 from"node:fs";import path10 from"node:path";init_dist();init_scaffold();async function createAgent(opts){if(!isValidAgentName(opts.name))throw new InvalidAgentNameError(opts.name);let cwd=opts.cwd??process.cwd(),projectRoot;if(opts.requireFimoProject){let resolved=resolveFimoProject(cwd);if(!resolved)return{ok:!1,error:"Not inside a Fimo project (no .fimo.settings.json found). Run from inside a Fimo project, or pass -C <dir>."};projectRoot=resolved.projectRoot}else projectRoot=resolveProjectRoot(cwd);let targetDir=path10.join(projectRoot,"agents",opts.name);if(fs10.existsSync(targetDir))return{ok:!1,error:`agents/${opts.name}/ already exists. Pick a different name or remove the existing directory first.`};let templateName=opts.template??"_default",templateRoot;try{templateRoot=resolveAgentTemplate(templateName)}catch{let available=listAgentTemplates().map(t2=>t2.name);throw new BundleTemplateNotFoundError(templateName,available)}await copyAgentTemplate(templateRoot,targetDir),opts.description!==void 0&&writeDescriptionToConfig(path10.join(targetDir,"config.yaml"),opts.description);let capsPath=path10.join(targetDir,"capabilities.yaml"),capsYaml=fs10.existsSync(capsPath)?fs10.readFileSync(capsPath,"utf8"):"",declared=parseCapabilities(capsYaml).caps;if(declared.length===0)return{ok:!0,agentDir:targetDir};let io=opts.consentIO??defaultConsentIO();return(await runConsent({caps:declared,agentName:opts.name,allowShell:opts.allowShell,quiet:opts.quiet,io})).decision!=="allowed"?{ok:!0,agentDir:targetDir,consentDenied:!0,error:"Install consent denied. The bundle was scaffolded but no activations were created."}:{ok:!0,agentDir:targetDir}}__name(createAgent,"createAgent");function writeDescriptionToConfig(configPath,description){let content2=fs10.readFileSync(configPath,"utf8"),line=`description: ${JSON.stringify(description)}`,next2;/^description:.*$/m.test(content2)?next2=content2.replace(/^description:.*$/m,line):/^version:\s*\d+.*$/m.test(content2)?next2=content2.replace(/^(version:\s*\d+.*)$/m,`$1
1090
1090
  ${line}`):next2=(content2.endsWith(`
@@ -1099,7 +1099,7 @@ ${report}`,"render")})}catch(err){printBundleError("agents report",err)}}__name(
1099
1099
  ${result.driftLines.map(l=>` ${l}`).join(`
1100
1100
  `)}`,hint:"Run `fimo deploy` to push them first, or `fimo agents run --skip-drift-check` to dispatch the deployed version anyway."});return}if(result.skipped){ui.info({command:"agents run",message:`Dispatch was skipped: ${result.skipped}`});return}if(result.sessionId){ui.ok({command:"agents run",headline:`Triggered ${name} (session ${result.sessionId})`,details:{agent:name,session_id:result.sessionId},hint:`Watch progress: fimo agents runs ${name}`});return}ui.error({command:"agents run",code:"UNEXPECTED_RUN_RESPONSE",message:"Unexpected response from server (no sessionId, no skipped)."})}catch(err){printBundleError("agents run",err)}}__name(runAgentCommand,"runAgentCommand");init_dist();init_api();init_config();init_project();async function agentRunsCommand(name,options){try{let projectRoot=resolveProjectRoot(options.cwd??process.cwd()),projectId=options.project??readProjectId4(projectRoot);if(!projectId){ui.error({command:"agents runs",code:"NO_PROJECT_ID",message:"Could not determine project id.",hint:"Pass --project, or run from a linked project directory (one containing `.fimo.settings.json`)."});return}let limit=options.limit??20,cfg=loadConfig(),api=new FimoApiClient(cfg),sessions;try{sessions=await api.listAgentSessions(projectId,{agentName:name,env:options.env,limit})}catch(err){if(err instanceof ApiRequestError){ui.error({command:"agents runs",code:"AGENT_SESSIONS_FETCH_FAILED",message:`Failed to fetch sessions (HTTP ${err.status}): ${err.detail}`});return}throw err}if(sessions.length===0){ui.info({command:"agents runs",message:`(no recent sessions for '${name}'${options.env?` on env '${options.env}'`:""})`});return}let rows=sessions.map(session=>({id:session.id.slice(0,8),started:formatStartedAt(session.startedAt),duration:formatDuration(session.startedAt,session.finishedAt??session.cancelledAt),status:session.status,trigger:session.triggerKind,env:session.env,cost:`$${session.costUsd.toFixed(4)}`}));ui.table({command:"agents runs",columns:[{key:"id",label:"ID"},{key:"started",label:"STARTED"},{key:"duration",label:"DURATION"},{key:"status",label:"STATUS"},{key:"trigger",label:"TRIGGER"},{key:"env",label:"ENV"},{key:"cost",label:"COST"}],rows,cellStyle:__name((row2,column)=>{if(column==="status")return statusRole(row2.status);if(column==="cost")return"dim"},"cellStyle")})}catch(err){printBundleError("agents runs",err)}}__name(agentRunsCommand,"agentRunsCommand");function readProjectId4(projectRoot){try{return loadProjectSettings(projectRoot).projectId}catch{return}}__name(readProjectId4,"readProjectId");function statusRole(status){switch(status){case"finished":return"success";case"errored":return"error";case"cancelled":return"warn";case"running":return"accent";default:return}}__name(statusRole,"statusRole");function formatStartedAt(startedAt){if(!startedAt)return"\u2014";let date=startedAt instanceof Date?startedAt:new Date(startedAt);return Number.isNaN(date.getTime())?"\u2014":date.toISOString().slice(0,16).replace("T"," ")}__name(formatStartedAt,"formatStartedAt");function formatDuration(startedAt,endedAt){if(!startedAt||!endedAt)return"\u2014";let start=startedAt instanceof Date?startedAt:new Date(startedAt),ms=(endedAt instanceof Date?endedAt:new Date(endedAt)).getTime()-start.getTime();if(Number.isNaN(ms)||ms<0)return"\u2014";if(ms<1e3)return`${ms}ms`;let secs=Math.floor(ms/1e3);if(secs<60)return`${secs}s`;let mins=Math.floor(secs/60),remainingSecs=secs%60;return`${mins}m${remainingSecs.toString().padStart(2,"0")}s`}__name(formatDuration,"formatDuration");init_dist();var import_yaml3=__toESM(require_dist(),1);import fs11 from"node:fs";import path14 from"node:path";var SECRET_KEY_RE=/^[A-Z_][A-Z0-9_]*$/,PUBLIC_CONFIG_PREFIX2=/^(PUBLIC_|VITE_|NEXT_PUBLIC_)/;async function agentSecretsListCommand(name,opts){try{let config=readAgentConfig(name,opts.cwd),secrets=normalizeSecrets(config.secrets);if(secrets.length===0){ui.info({command:"agents secrets list",message:`No secrets requested by agent '${name}'.`});return}ui.table({command:"agents secrets list",columns:[{key:"key",label:"KEY"},{key:"requirement",label:"REQUIREMENT"},{key:"delivery",label:"DELIVERY"}],rows:secrets.map(secret=>({key:secret.key,requirement:secret.required===!1?"optional":"required",delivery:secret.delivery??"process_env"}))})}catch(err){printBundleError("agents secrets list",err)}}__name(agentSecretsListCommand,"agentSecretsListCommand");async function agentSecretsAddCommand(name,key,opts){try{validateSecretKey(key);let{filePath,config}=readAgentConfigWithPath(name,opts.cwd),secrets=normalizeSecrets(config.secrets);secrets.some(secret=>secret.key===key)||(secrets.push({key,required:!opts.optional,delivery:"process_env"}),config.secrets=secrets,fs11.writeFileSync(filePath,(0,import_yaml3.stringify)(config))),ui.ok({command:"agents secrets add",headline:`Agent '${name}' now requests secret ${key}`,details:{agent:name,key,optional:opts.optional===!0}})}catch(err){printBundleError("agents secrets add",err)}}__name(agentSecretsAddCommand,"agentSecretsAddCommand");async function agentSecretsRemoveCommand(name,key,opts){try{let{filePath,config}=readAgentConfigWithPath(name,opts.cwd),after2=normalizeSecrets(config.secrets).filter(secret=>secret.key!==key);config.secrets=after2,fs11.writeFileSync(filePath,(0,import_yaml3.stringify)(config)),ui.ok({command:"agents secrets remove",headline:`Agent '${name}' no longer requests secret ${key}`,details:{agent:name,key}})}catch(err){printBundleError("agents secrets remove",err)}}__name(agentSecretsRemoveCommand,"agentSecretsRemoveCommand");function normalizeSecrets(raw){if(!Array.isArray(raw))return[];let out=[];for(let item of raw){if(typeof item=="string"){out.push({key:item,required:!0,delivery:"process_env"});continue}if(item&&typeof item=="object"&&typeof item.key=="string"){let entry=item;out.push({key:entry.key,required:typeof entry.required=="boolean"?entry.required:!0,delivery:(entry.delivery==="process_env","process_env")})}}return out}__name(normalizeSecrets,"normalizeSecrets");function validateSecretKey(key){if(!SECRET_KEY_RE.test(key))throw new Error(`Secret key '${key}' must be UPPER_SNAKE_CASE.`);if(PUBLIC_CONFIG_PREFIX2.test(key))throw new Error(`Secret key '${key}' uses a public variable prefix. Use project variables for public values.`)}__name(validateSecretKey,"validateSecretKey");function readAgentConfig(name,cwd){return readAgentConfigWithPath(name,cwd).config}__name(readAgentConfig,"readAgentConfig");function readAgentConfigWithPath(name,cwd){let projectRoot=resolveProjectRoot(cwd??process.cwd()),filePath=path14.join(projectRoot,"agents",name,"config.yaml");if(!fs11.existsSync(filePath))throw new Error(`Agent '${name}' does not have a config.yaml at ${filePath}.`);let parsed=(0,import_yaml3.parse)(fs11.readFileSync(filePath,"utf8")),config=parsed&&typeof parsed=="object"&&!Array.isArray(parsed)?parsed:{};return{filePath,config}}__name(readAgentConfigWithPath,"readAgentConfigWithPath");init_dist();init_scaffold();async function listTemplatesCommand(){let templates=listAgentTemplates();if(templates.length===0){ui.info({command:"agents list-templates",message:"No agent templates bundled with this CLI."});return}ui.result({command:"agents list-templates",data:{templates},render:__name(()=>{let lines=["Available templates:"],longest=templates.reduce((acc,t2)=>Math.max(acc,t2.name.length),0);for(let t2 of templates){let padded=t2.name.padEnd(longest);lines.push(` ${padded} ${t2.goalFirstLine??"(no GOAL.md)"}`)}return lines.push(""),lines.push(" Use `fimo agents create <name> --template <template>` to scaffold."),lines.join(`
1101
1101
  `)},"render")})}__name(listTemplatesCommand,"listTemplatesCommand");import fs12 from"node:fs";import path15 from"node:path";init_dist();init_api();init_auth();init_config();init_project();async function runValidateAgents(opts){let projectRoot=resolveProjectRoot(opts.cwd??process.cwd()),agentsDir=path15.join(projectRoot,"agents"),policy=validatePolicy(path15.join(projectRoot,"fimo.config.json")),bundleList=[];if(opts.name){if(!isValidAgentName(opts.name))return{ok:!1,policy,bundles:[{name:opts.name,ok:!1,phases:{parse:{ok:!1,issues:[{pointer:"name",message:`Invalid agent name '${opts.name}'.`}]},capabilities:{ok:!0,issues:[]},composition:{ok:!0,issues:[]},semantics:{ok:!0,issues:[]}},warnings:[]}]};let bundle=await safeParse(path15.join(agentsDir,opts.name));if(!bundle.ok)return{ok:!1,policy,bundles:[{name:opts.name,ok:!1,phases:{parse:{ok:!1,issues:[bundle.issue]},capabilities:{ok:!0,issues:[]},composition:{ok:!0,issues:[]},semantics:{ok:!0,issues:[]}},warnings:[]}]};bundleList=[bundle.bundle]}else bundleList=await listBundles(agentsDir);let reports=[];for(let bundle of bundleList)reports.push(validateOneBundle(bundle,bundleList));return{ok:(policy?.ok??!0)&&reports.every(r=>r.ok),policy,bundles:reports}}__name(runValidateAgents,"runValidateAgents");function validatePolicy(policyPath){if(!fs12.existsSync(policyPath))return null;try{let text3=fs12.readFileSync(policyPath,"utf8");return parseFimoConfig(text3,{path:"fimo.config.json"}),{ok:!0,issues:[]}}catch(err){return{ok:!1,issues:[{pointer:"fimo.config.json",message:err.message,remediation:err.remediation}]}}}__name(validatePolicy,"validatePolicy");async function safeParse(bundlePath){try{return{ok:!0,bundle:await parseBundle(bundlePath)}}catch(err){return{ok:!1,issue:{pointer:path15.basename(bundlePath),message:err.message,remediation:err.remediation}}}}__name(safeParse,"safeParse");function validateOneBundle(bundle,allBundles){let phases={parse:{ok:!0,issues:[]},capabilities:{ok:!0,issues:[]},composition:{ok:!0,issues:[]},semantics:{ok:!0,issues:[]}},vocab=validateAgainstVocabulary(bundle.capabilities,CAPABILITY_VOCABULARY);for(let token of vocab.unknown){let suggestion=suggestCapability(token),err=new BundleInvalidCapabilityError(token,"unknown",{suggestion:suggestion??void 0});phases.capabilities.ok=!1,phases.capabilities.issues.push({pointer:`capabilities.yaml: ${token}`,message:err.message,remediation:err.remediation})}for(let token of vocab.runtimeOnly){let err=new BundleInvalidCapabilityError(token,"runtime_only");phases.capabilities.ok=!1,phases.capabilities.issues.push({pointer:`capabilities.yaml: ${token}`,message:err.message,remediation:err.remediation})}let agentMap=new Map(allBundles.map(b=>[b.name,b])),compositionResult=composition_exports.validateComposition(bundle,agentMap);if(compositionResult.cycle){let err=new BundleCompositionCycleError(compositionResult.cycle);phases.composition.ok=!1,phases.composition.issues.push({pointer:"config.yaml:composition",message:err.message,remediation:err.remediation})}for(let missingName of compositionResult.missing)phases.composition.ok=!1,phases.composition.issues.push({pointer:`config.yaml:composition.sub-agents[name=${missingName}]`,message:`Sub-agent '${missingName}' is referenced but not present in the project's agents/ directory.`,remediation:`Run \`fimo agents create ${missingName}\` or remove the reference from composition.sub-agents.`});for(let invalid of compositionResult.invalidGrants)phases.composition.ok=!1,phases.composition.issues.push({pointer:`config.yaml:composition.sub-agents[name=${invalid.subAgentName}].explicit_grants`,message:`explicit_grants references capabilities the sub-agent never declared: [${invalid.invalid.join(", ")}]. Declared: [${invalid.declared.join(", ")}].`,remediation:"Remove the undeclared tokens from explicit_grants, or add them to the sub-agent's capabilities.yaml."});if(!compositionResult.cycle){let cycle=detectCompositionCycle({root:bundle,agentMap});if(cycle){let err=new BundleCompositionCycleError(cycle);phases.composition.ok=!1,phases.composition.issues.push({pointer:"config.yaml:composition",message:err.message,remediation:err.remediation})}}let issues=validateBundle(bundle,{availableAgents:allBundles}),warnings=[...bundle.warnings];for(let issue of issues){if(issue.severity==="warning"){warnings.push({pointer:issue.pointer,message:issue.message});continue}issue.pointer.startsWith("capabilities.yaml")||issue.pointer.startsWith("config.yaml:composition")||(phases.semantics.ok=!1,phases.semantics.issues.push({pointer:issue.pointer,message:issue.message}))}let ok=phases.parse.ok&&phases.capabilities.ok&&phases.composition.ok&&phases.semantics.ok;return{name:bundle.name,ok,phases,warnings}}__name(validateOneBundle,"validateOneBundle");async function runAvailabilityChecks(cwd){let projectRoot=resolveProjectRoot(cwd),projectId;try{projectId=loadProjectSettings(projectRoot).projectId}catch{if(projectId=process.env.FIMO_PROJECT_ID?.trim()??"",!projectId)return{ok:!0,skippedReason:"not-linked",issues:[]}}if(!process.env.FIMO_API_TOKEN?.trim()&&!readCredentials())return{ok:!0,skippedReason:"not-signed-in",issues:[]};let api=new FimoApiClient(loadConfig()),bundles=await listBundles(path15.join(projectRoot,"agents")),issues=[],integrationsByAgent=bundles.map(bundle=>({name:bundle.name,integrations:Object.entries(agentIntegrationPolicy(bundle.config)).map(([integrationKey,entry])=>({integrationKey,enabled:entry.enabled,tools:enabledAgentIntegrationTools(entry)})).filter(entry=>entry.enabled)})).filter(entry=>entry.integrations.length>0);if(integrationsByAgent.length>0){let statuses=await api.listProjectIntegrations(projectId),statusByKey=new Map(statuses.map(status=>[status.integrationKey,status])),infoByKey=new Map;for(let agent of integrationsByAgent)for(let integration of agent.integrations){let file=`agents/${agent.name}/config.yaml`,status=statusByKey.get(integration.integrationKey);if(!status){issues.push({pointer:file,message:`${agent.name} allows unsupported integration ${integration.integrationKey}.`});continue}integration.tools.length===0&&issues.push({pointer:file,message:`${agent.name} enables ${integration.integrationKey}, but no tools are allowed. Set at least one integrations.${integration.integrationKey}.tools.<tool>: true entry.`}),status.enabled||issues.push({pointer:file,message:`${agent.name} allows ${integration.integrationKey}, but the project integration is not enabled. Run: fimo integrations enable ${integration.integrationKey}`});let info=infoByKey.get(integration.integrationKey)??await api.getProjectIntegrationInfo(projectId,integration.integrationKey);infoByKey.set(integration.integrationKey,info);let knownTools=new Set(info.tools.map(tool=>tool.key));for(let tool of integration.tools)knownTools.has(tool)||issues.push({pointer:file,message:`${agent.name} allows unknown ${integration.integrationKey}.${tool} tool. Supported tools: ${[...knownTools].sort().join(", ")}`})}}let secretsByAgent=bundles.map(bundle=>({name:bundle.name,keys:(bundle.config.secrets??[]).filter(secret=>secret.required!==!1).map(secret=>secret.key)})).filter(entry=>entry.keys.length>0);if(secretsByAgent.length>0){let defined=new Set((await api.listProjectSecretEntries(projectId,{kind:"secret"})).map(secret=>secret.key));for(let entry of secretsByAgent)for(let key of entry.keys)defined.has(key)||issues.push({pointer:`agents/${entry.name}/config.yaml`,message:`${entry.name} requires project secret ${key}, but it is not set. Run: fimo secrets add ${key} --stdin`})}return{ok:issues.length===0,skippedReason:null,issues}}__name(runAvailabilityChecks,"runAvailabilityChecks");async function validateAgentsCommand(opts){let report;try{report=await runValidateAgents(opts)}catch(err){throw printBundleError("agents validate",err),opts.noExit||(process.exitCode=1),err}return report.bundles.length===0&&!report.policy?(ui.info({command:"agents validate",message:"No bundles or fimo.config.json found."}),report):(report.availability=await runAvailabilityChecks(opts.cwd??process.cwd()),report.availability.ok||(report.ok=!1),ui.result({command:"agents validate",data:report,render:__name(()=>renderReportHuman(report),"render")}),!report.ok&&!opts.noExit&&(process.exitCode=1),report)}__name(validateAgentsCommand,"validateAgentsCommand");function renderReportHuman(report){let lines=[];if(report.policy)if(report.policy.ok)lines.push(" \u2713 fimo.config.json policy ok");else{lines.push(" \u2717 fimo.config.json");for(let issue of report.policy.issues)lines.push(` \u2717 ${issue.message}`),issue.remediation&&lines.push(` fix: ${issue.remediation}`)}for(let bundle of report.bundles)if(bundle.ok){lines.push(` \u2713 ${bundle.name} all phases ok`);for(let w3 of bundle.warnings)lines.push(` ! ${w3.pointer}: ${w3.message}`)}else{lines.push(` \u2717 ${bundle.name}`);for(let phase of["parse","capabilities","composition","semantics"])for(let issue of bundle.phases[phase].issues)lines.push(` \u2717 [${phase}] ${issue.message}`),issue.remediation&&lines.push(` fix: ${issue.remediation}`)}if(report.availability)if(report.availability.skippedReason){let why=report.availability.skippedReason==="not-signed-in"?"not signed in \u2014 run `fimo login`":"no linked project";lines.push(` \u21B7 integrations & secrets \u2014 skipped (${why})`)}else if(report.availability.ok)lines.push(" \u2713 integrations & secrets available");else{lines.push(" \u2717 integrations & secrets");for(let issue of report.availability.issues)lines.push(` \u2717 ${issue.message}`)}return lines.join(`
1102
- `)}__name(renderReportHuman,"renderReportHuman");function registerAgentsCommands(program2){let agents=program2.command("agents").description("AI agent bundle management (M13)");agents.command("create <name>").description("Scaffold agents/<name>/ from a template").option("--template <name>","Template to copy from (default: _default)").option("--description <text>","Short tagline written to config.yaml (one line, up to 280 chars)").option("-C, --cwd <dir>","Project directory").option("--quiet","Skip the install-consent flow (critical caps still abort)").option("--allow-shell","Auto-allow shell:exec without prompting").action((name,opts)=>createAgentCommand(name,opts)),agents.command("list").description("List agents declared under <project>/agents/").option("-C, --cwd <dir>","Project directory").option("--project <id>","Project id (accepted for parity with cloud-scoped subcommands)").action(opts=>listAgentsCommand(opts)),agents.command("list-templates").alias("templates").description("List the bundled starter-catalog templates").action(()=>listTemplatesCommand()),agents.command("validate [name]").description("Validate one or every bundle (parse, capabilities, composition, policy)").option("--json","Emit structured ValidationReport (for CI)").option("-C, --cwd <dir>","Project directory").action(async(name,opts)=>{await validateAgentsCommand({name,json:opts.json,cwd:opts.cwd})}),agents.command("integrations <name>").description("Preview local integration access policy for an agent").option("--project <id>","Project id (defaults to the project linked in .fimo.settings.json when available)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentIntegrationsCommand(name,opts)),agents.command("run <name>").description("Trigger a manual run on the server (returns sessionId)").option("--env <env>","Target env (default: main)").option("--project <id>","Project id (defaults to .fimo.settings.json projectId)").option("-C, --cwd <dir>","Project directory").option("--skip-drift-check","Dispatch even when the bundle has uncommitted local changes").action((name,opts)=>runAgentCommand(name,opts)),agents.command("activate <name>").description("Activate one or every trigger on a project env (M14 install consent applies)").option("--trigger <type>","Activate only triggers of this type (manual/schedule/webhook)").option("--env <env>","Target env (default: main)").option("--project <id>","Project id (defaults to the project linked in .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").option("--quiet","Skip the install-consent flow (critical caps still abort)").option("--allow-shell","Auto-allow shell:exec without prompting").action((name,opts)=>activateAgentCommand(name,opts)),agents.command("deactivate <name>").description("Remove activation rows for this agent").option("--trigger <type>","Filter to a single trigger type").option("--env <env>","Target env (default: main)").option("--project <id>","Project id (defaults to the project linked in .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>deactivateAgentCommand(name,opts)),agents.command("logs <name>").description("Stream the most recent session log").option("--session <id>","Specific session id to target").option("-C, --cwd <dir>","Project directory").option("--project <id>","Project id (defaults to the project linked in .fimo.settings.json)").action((name,opts)=>agentLogsCommand(name,opts)),agents.command("runs <name>").description("Paginated session list").option("--limit <n>","Max sessions to show (default: 20)",v=>Number.parseInt(v,10)).option("--env <env>","Filter sessions to a specific env").option("--project <id>","Project id (defaults to the project linked in .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentRunsCommand(name,opts)),agents.command("report <name>").description("Print a run's report (the agent's final message); latest run unless --session is given").option("--session <id>","Target a specific session id").option("--env <env>","Pick the latest run on a specific env").option("--project <id>","Project id (defaults to the project linked in .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentReportCommand(name,opts));let secrets=agents.command("secrets").description("Edit the secrets requested in an agent config.yaml");secrets.command("list <name>").description("List secret keys requested by an agent config").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentSecretsListCommand(name,opts)),secrets.command("add <name> <key>").description("Add a secret key request to an agent config").option("-C, --cwd <dir>","Project directory").option("--optional","Mark the secret as optional").action((name,key,opts)=>agentSecretsAddCommand(name,key,opts)),secrets.command("remove <name> <key>").alias("rm").description("Remove a secret key request from an agent config").option("-C, --cwd <dir>","Project directory").action((name,key,opts)=>agentSecretsRemoveCommand(name,key,opts))}__name(registerAgentsCommands,"registerAgentsCommands");init_dist();init_project_context();function parseRangeOptions(options){let params={};if(options.preset&&(params.preset=options.preset),options.groupBy&&(params.groupBy=options.groupBy),options.from&&(params.from=options.from),options.to&&(params.to=options.to),options.days!==void 0){let n=Number(options.days);if(!Number.isFinite(n))throw new Error(`Invalid --days value: ${options.days}`);params.days=n}return params}__name(parseRangeOptions,"parseRangeOptions");function renderPrettyJson(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson,"renderPrettyJson");async function analyticsPageviewsCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params);ui.result({command:"analytics pageviews",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsPageviewsCommand,"analyticsPageviewsCommand");var TOP_DIMENSIONS=["pages","browsers","devices","countries","sources"];function dimensionField(dimension){return`top${dimension.charAt(0).toUpperCase()}${dimension.slice(1)}`}__name(dimensionField,"dimensionField");async function analyticsTopCommand(dimension,options,cmd){if(!TOP_DIMENSIONS.includes(dimension))throw new Error(`Unknown dimension: ${dimension}. Expected one of: ${TOP_DIMENSIONS.join(", ")}`);let{ctx,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params),field=dimensionField(dimension),items=Array.isArray(result[field])?result[field]:[],limit;if(options.limit!==void 0){let n=Number(options.limit);if(!Number.isFinite(n)||n<1)throw new Error(`Invalid --limit value: ${options.limit}`);limit=n}let trimmed=limit!==void 0?items.slice(0,limit):items;ui.result({command:"analytics top",data:{dimension,items:trimmed},render:__name(()=>renderPrettyJson(trimmed),"render")})}__name(analyticsTopCommand,"analyticsTopCommand");async function analyticsAnnotationsListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params),annotations2=Array.isArray(result.annotations)?result.annotations:[];ui.result({command:"analytics annotations list",data:{annotations:annotations2},render:__name(()=>renderPrettyJson(annotations2),"render")})}__name(analyticsAnnotationsListCommand,"analyticsAnnotationsListCommand");async function analyticsAnnotationsSetCommand(date,content2,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd),result=await api.setAnalyticsAnnotation(ctx.projectId,date,content2);ui.result({command:"analytics annotations set",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsAnnotationsSetCommand,"analyticsAnnotationsSetCommand");async function analyticsAnnotationsDeleteCommand(date,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await api.deleteAnalyticsAnnotation(ctx.projectId,date),ui.ok({command:"analytics annotations delete",headline:`Deleted annotation for ${date}.`,details:{date}})}__name(analyticsAnnotationsDeleteCommand,"analyticsAnnotationsDeleteCommand");init_dist();import{spawn}from"node:child_process";import{mkdirSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{dirname,extname,isAbsolute,join as join2,resolve as resolvePath}from"node:path";var ENV_SESSION="FIMO_AGENT_SESSION",ENV_CAPS_FALLBACK="FIMO_AGENT_CAPABILITIES";function currentAgentSession(){let id=process.env[ENV_SESSION];return id&&id.length>0?id:void 0}__name(currentAgentSession,"currentAgentSession");async function defaultFetchSessionCapabilities(_sessionId){let raw=process.env[ENV_CAPS_FALLBACK];return raw?raw.split(",").map(s=>s.trim()).filter(s=>s.length>0):[]}__name(defaultFetchSessionCapabilities,"defaultFetchSessionCapabilities");async function requireCapability(cap,ctx={}){let sessionId=currentAgentSession();if(!sessionId)return{ok:!0,bypassed:!0};let granted=await(ctx.fetchSessionCapabilities??defaultFetchSessionCapabilities)(sessionId);if(!granted.includes(cap)){try{await auditCapabilityDecision({sessionId,cap,decision:"deny",reason:granted.length===0?"session-not-found":"not-declared",projectId:ctx.projectId,env:ctx.env})}catch{}throw new CapabilityDenied({cap,reason:granted.length===0?"session-not-found":"not-declared",granted,sessionId})}return auditCapabilityDecision({sessionId,cap,decision:"allow",projectId:ctx.projectId,env:ctx.env}),{ok:!0,bypassed:!1}}__name(requireCapability,"requireCapability");async function requireOperation(op,ctx={}){if(!hasOperation(op))throw new Error(`requireOperation: unknown operation id '${op}' \u2014 register it in @fimo/agents capabilities/operation-map.ts`);let cap=capabilityFor(op);return requireCapability(cap,ctx)}__name(requireOperation,"requireOperation");init_project_context();init_project();function extensionFor(asset){let fromName=extname(asset.name);if(fromName&&fromName.length<=6)return fromName;let mime=asset.mimeType??"";return mime.startsWith("image/")?"."+(mime.split("/")[1]??"bin"):mime.startsWith("video/")?"."+(mime.split("/")[1]??"mp4"):mime.startsWith("audio/")?"."+(mime.split("/")[1]??"mp3"):""}__name(extensionFor,"extensionFor");function defaultDownloadPath(asset){let ext=extensionFor(asset);return join2(tmpdir(),"fimo-assets",`${asset.id}${ext}`)}__name(defaultDownloadPath,"defaultDownloadPath");async function downloadToPath(url,dest){let response=await fetch(url);if(!response.ok)throw new Error(`Failed to download asset: HTTP ${response.status} ${response.statusText}`);let arrayBuffer=await response.arrayBuffer();mkdirSync(dirname(dest),{recursive:!0}),writeFileSync(dest,new Uint8Array(arrayBuffer))}__name(downloadToPath,"downloadToPath");function spawnBrowser(url){let command=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(process.platform==="win32"?spawn("cmd",["/c","start","",url],{detached:!0,stdio:"ignore"}):spawn(command,[url],{detached:!0,stdio:"ignore"})).unref()}__name(spawnBrowser,"spawnBrowser");function renderPrettyJson2(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson2,"renderPrettyJson");async function assetsOpenCommand(id,options,cmd){if(options.download&&options.browser)throw new Error("--download and --browser are mutually exclusive \u2014 pick one");let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.get",{projectId:ctx.projectId,env:ctx.env});let cwd=resolveProjectCwd(options.cwd),{data:asset}=await api.getAsset(ctx.projectId,id);if(asset.type==="folder")throw new Error(`Asset ${id} is a folder; can only open files`);if(!asset.url)throw new Error(`Asset ${id} has no public URL \u2014 it may not have finished uploading`);if(options.browser){spawnBrowser(asset.url);let payload2={opened:asset.url};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}if(options.download){let dest=options.path?isAbsolute(options.path)?options.path:resolvePath(cwd,options.path):defaultDownloadPath(asset);await downloadToPath(asset.url,dest);let payload2={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,path:dest,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,aiAltText:asset.aiAltText??null};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}let payload={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,caption:asset.caption??null,aiAltText:asset.aiAltText??null,aiCaption:asset.aiCaption??null,aiTags:asset.aiTags??null};ui.result({command:"assets open",data:payload,render:__name(()=>renderPrettyJson2(payload),"render")})}__name(assetsOpenCommand,"assetsOpenCommand");init_dist();import fs13 from"node:fs";import path16 from"node:path";init_project_context();init_project();function renderPrettyJson3(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson3,"renderPrettyJson");function unwrapAssetRows(result){if(Array.isArray(result))return result.filter(isAssetRow);let data2=result?.data;return Array.isArray(data2)?data2.filter(isAssetRow):[]}__name(unwrapAssetRows,"unwrapAssetRows");function unwrapAsset(result){if(isAssetRow(result))return result;let data2=result?.data;return isAssetRow(data2)?data2:null}__name(unwrapAsset,"unwrapAsset");function isAssetRow(value){let asset=value;return!!asset&&typeof asset.id=="string"&&typeof asset.name=="string"&&(asset.type==="file"||asset.type==="folder")}__name(isAssetRow,"isAssetRow");function parseFolderPath(folderPath){let segments=folderPath.split("/").map(segment=>segment.trim()).filter(Boolean);if(segments.length===0)throw new Error("--folder-path must contain at least one folder name");let unsafeSegment=segments.find(segment=>segment==="."||segment==="..");if(unsafeSegment)throw new Error(`Invalid folder segment in --folder-path: ${unsafeSegment}`);return segments}__name(parseFolderPath,"parseFolderPath");async function findFolder(api,projectId,name,parentId){let params={parentId:parentId??"",search:name,type:"folder",limit:"100"},result=await api.listAssets(projectId,params);return unwrapAssetRows(result).find(asset=>asset.type==="folder"&&asset.name===name&&(asset.parentId??null)===parentId)??null}__name(findFolder,"findFolder");async function ensureFolderPath(api,projectId,folderPath){let parentId=null;for(let segment of parseFolderPath(folderPath)){let existing=await findFolder(api,projectId,segment,parentId);if(existing){parentId=existing.id;continue}let created=unwrapAsset(await api.createFolder(projectId,segment,parentId??void 0));if(!created||created.type!=="folder")throw new Error(`Failed to create media folder: ${segment}`);parentId=created.id}if(!parentId)throw new Error(`Failed to resolve media folder path: ${folderPath}`);return parentId}__name(ensureFolderPath,"ensureFolderPath");async function assetsListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.list",{projectId:ctx.projectId,env:ctx.env});let mimePrefix=options.mimePrefix;mimePrefix||(options.image?mimePrefix="image/":options.video?mimePrefix="video/":options.audio&&(mimePrefix="audio/"));let params={};options.parentId&&(params.parentId=options.parentId),options.search&&(params.search=options.search),options.type&&(params.type=options.type),mimePrefix&&(params.mimePrefix=mimePrefix),options.sortBy&&(params.sortBy=options.sortBy),options.limit&&(params.limit=options.limit),options.offset&&(params.offset=options.offset);let result=await api.listAssets(ctx.projectId,Object.keys(params).length>0?params:void 0);ui.result({command:"assets list",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsListCommand,"assetsListCommand");async function assetsUploadCommand(file,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.upload",{projectId:ctx.projectId,env:ctx.env});let cwd=resolveProjectCwd(options.cwd);if(options.parentId&&options.folderPath)throw new Error("Use either --parent-id or --folder-path, not both");let filePath=path16.resolve(cwd,file);if(!fs13.existsSync(filePath))throw new Error(`File not found: ${filePath}`);let fileBuffer=fs13.readFileSync(filePath),fileName=options.name??path16.basename(filePath),formData=new FormData;formData.append("file",new Blob([fileBuffer]),fileName),options.name&&formData.append("name",options.name);let parentId=options.folderPath?await ensureFolderPath(api,ctx.projectId,options.folderPath):options.parentId;parentId&&formData.append("parentId",parentId);let result=await api.uploadAsset(ctx.projectId,formData);ui.result({command:"assets upload",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsUploadCommand,"assetsUploadCommand");async function assetsCreateFolderCommand(name,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.create_folder",{projectId:ctx.projectId,env:ctx.env});let result=await api.createFolder(ctx.projectId,name,options.parentId);ui.result({command:"assets create-folder",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsCreateFolderCommand,"assetsCreateFolderCommand");async function assetsMoveCommand(id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.move",{projectId:ctx.projectId,env:ctx.env});let result=await api.moveAsset(ctx.projectId,id,options.parentId);ui.result({command:"assets move",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsMoveCommand,"assetsMoveCommand");async function assetsDeleteCommand(id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.delete",{projectId:ctx.projectId,env:ctx.env});let result=await api.deleteAsset(ctx.projectId,id);ui.result({command:"assets delete",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsDeleteCommand,"assetsDeleteCommand");init_esm();init_dist();init_api();init_git();init_project_context();init_project();function envOverride(program2){return envOverrideFromCommand(program2)}__name(envOverride,"envOverride");async function branchListCommand(cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({envOverride:envOverride(program2)}),envs=await new FimoApiClient().withEnv(ctx.env).listEnvs(ctx.projectId,{includeDeleted:opts.verbose});if(envs.length===0){ui.info({command:"branch",message:"(no envs yet)",hint:"Run `fimo branch <name>` to create one."});return}ui.table({command:"branch",columns:opts.verbose?[{key:"env",label:"ENV"},{key:"status",label:"STATUS"},{key:"parent",label:"PARENT"},{key:"preview",label:"PREVIEW"}]:[{key:"env",label:"ENV"},{key:"status",label:"STATUS"},{key:"parent",label:"PARENT"}],rows:envs.map(e=>({env:e.env,status:e.status,parent:e.parentEnv??"\u2014",preview:opts.verbose?e.previewUrl??"":void 0})),isActive:__name(row2=>row2.env===ctx.env,"isActive")})}__name(branchListCommand,"branchListCommand");async function branchCreateCommand(name,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env),parentEnv=opts.from??ctx.env;if(isProductionEnv(name)||isProductionEnv(parentEnv)){ui.error({command:"branch",code:"PROTECTED_ENV",message:`The '${PRODUCTION_ENV}' env is protected \u2014 it cannot be created or forked from.`});return}let parentValidation=await validateParentEnv(api,ctx.projectId,parentEnv,ctx,opts.from);if(!parentValidation.ok){ui.error({command:"branch",code:"ENV_NOT_FOUND",message:parentValidation.message});return}let created=await api.createEnv(ctx.projectId,{env:name,parentEnv});ui.ok({command:"branch",headline:`Created env '${created.env}' (status: ${created.status})`,details:{env:created.env,parent_env:parentEnv,status:created.status,preview_url:created.previewUrl??null}})}__name(branchCreateCommand,"branchCreateCommand");async function branchDeleteCommand(name,cmd){let program2=cmd.parent??cmd,ctx=await getProjectContext({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env);if(name===DEFAULT_ENV){ui.error({command:"branch",code:"PROTECTED_ENV",message:`Refusing to delete the default env '${DEFAULT_ENV}'.`});return}if(isProductionEnv(name)){ui.error({command:"branch",code:"PROTECTED_ENV",message:`The '${PRODUCTION_ENV}' env is protected and cannot be deleted.`});return}await api.deleteEnv(ctx.projectId,name),ui.ok({command:"branch",headline:`Deleted env '${name}'`,details:{env:name}})}__name(branchDeleteCommand,"branchDeleteCommand");async function checkoutCommand(name,_options,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env),cwd=resolveProjectCwd();if(isProductionEnv(name)){ui.error({command:"checkout",code:"PROTECTED_ENV",message:`The '${PRODUCTION_ENV}' env is protected and cannot be checked out.`});return}let created=!1;if(opts.create){let parentEnv=opts.from??ctx.env,parentValidation=await validateParentEnv(api,ctx.projectId,parentEnv,ctx,opts.from);if(!parentValidation.ok){ui.error({command:"checkout",code:"ENV_NOT_FOUND",message:parentValidation.message});return}await api.createEnv(ctx.projectId,{env:name,parentEnv}),created=!0}else await api.getEnv(ctx.projectId,name);let gitSwitched=!1;if(await isGitRepo(cwd))try{await runGit(["checkout",name],cwd),gitSwitched=!0}catch(err){let stderr=err instanceof Error&&"stderr"in err?String(err.stderr):"";if(/did not match any file|pathspec/i.test(stderr))await runGit(["checkout","-b",name],cwd),gitSwitched=!0;else throw err}ui.ok({command:"checkout",headline:`Now on env '${name}'`,details:{env:name,created,git_switched:gitSwitched,parent_env:opts.from??null}})}__name(checkoutCommand,"checkoutCommand");async function pullCommand(_options,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env),{env,conflicts}=await api.syncEnv(ctx.projectId,ctx.env,{from:opts.from}),warnings=conflicts>0?[`Resolved ${conflicts} conflict(s) (parent-wins for now \u2014 M12 conflict UI will add per-row picks)`]:void 0;ui.ok({command:"pull",headline:`Env '${env.env}' synced`,details:{env:env.env,from:opts.from??null,conflicts},warnings})}__name(pullCommand,"pullCommand");async function validateParentEnv(api,projectId,parentEnv,ctx,fromFlag){try{return await api.getEnv(projectId,parentEnv),{ok:!0}}catch(err){if(!(err instanceof ApiRequestError)||err.status!==404)throw err;let origin=fromFlag?`the \`--from ${fromFlag}\` flag`:ctx.source==="branch"?`your active env (\`${ctx.env}\`)`:ctx.source==="flag"?`the \`--env ${ctx.env}\` flag`:ctx.source==="tag"?`the release tag \`${ctx.env}\``:`the project default (\`${ctx.env}\`)`,fixes=[];return fromFlag?fixes.push(`pass an existing env via \`--from <env>\` (try \`--from ${DEFAULT_ENV}\`)`):ctx.source==="branch"?(fixes.push(`switch envs first: \`fimo checkout ${DEFAULT_ENV}\``),fixes.push(`or pass \`--from ${DEFAULT_ENV}\` to override for this command`)):ctx.source==="flag"?fixes.push(`use a different \`--env <existing>\` (try \`--env ${DEFAULT_ENV}\`)`):fixes.push(`pass \`--from ${DEFAULT_ENV}\` to fork from main`),{ok:!1,message:`Cannot create env: parent env '${parentEnv}' doesn't exist on this project. The CLI resolved the parent from ${origin}. Fix: ${fixes.join(", or ")}.`}}}__name(validateParentEnv,"validateParentEnv");init_dist();init_api();init_config();init_project();function registerChannelsCommands(program2){program2.command("channels").description("Manage project channel bindings").addHelpText("after",`
1102
+ `)}__name(renderReportHuman,"renderReportHuman");function registerAgentsCommands(program2){let agents=program2.command("agents").description("AI agent bundle management (M13)");agents.command("create <name>").description("Scaffold agents/<name>/ from a template").option("--template <name>","Template to copy from (default: _default)").option("--description <text>","Short tagline written to config.yaml (one line, up to 280 chars)").option("-C, --cwd <dir>","Project directory").option("--quiet","Skip the install-consent flow (critical caps still abort)").option("--allow-shell","Auto-allow shell:exec without prompting").action((name,opts)=>createAgentCommand(name,opts)),agents.command("list").description("List agents declared under <project>/agents/").option("-C, --cwd <dir>","Project directory").option("--project <id>","Project id (accepted for parity with cloud-scoped subcommands)").action(opts=>listAgentsCommand(opts)),agents.command("list-templates").alias("templates").description("List the bundled starter-catalog templates").action(()=>listTemplatesCommand()),agents.command("validate [name]").description("Validate one or every bundle (parse, capabilities, composition, policy)").option("--json","Emit structured ValidationReport (for CI)").option("-C, --cwd <dir>","Project directory").action(async(name,opts)=>{await validateAgentsCommand({name,json:opts.json,cwd:opts.cwd})}),agents.command("integrations <name>").description("Preview local integration access policy for an agent").option("--project <id>","Project id (defaults to the project linked in .fimo.settings.json when available)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentIntegrationsCommand(name,opts)),agents.command("run <name>").description("Trigger a manual run on the server (returns sessionId)").option("--env <env>","Target env (default: main)").option("--project <id>","Project id (defaults to .fimo.settings.json projectId)").option("-C, --cwd <dir>","Project directory").option("--skip-drift-check","Dispatch even when the bundle has uncommitted local changes").action((name,opts)=>runAgentCommand(name,opts)),agents.command("activate <name>").description("Activate one or every trigger on a project env (M14 install consent applies)").option("--trigger <type>","Activate only triggers of this type (manual/schedule/webhook)").option("--env <env>","Target env (default: main)").option("--project <id>","Project id (defaults to the project linked in .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").option("--quiet","Skip the install-consent flow (critical caps still abort)").option("--allow-shell","Auto-allow shell:exec without prompting").action((name,opts)=>activateAgentCommand(name,opts)),agents.command("deactivate <name>").description("Remove activation rows for this agent").option("--trigger <type>","Filter to a single trigger type").option("--env <env>","Target env (default: main)").option("--project <id>","Project id (defaults to the project linked in .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>deactivateAgentCommand(name,opts)),agents.command("logs <name>").description("Stream the most recent session log").option("--session <id>","Specific session id to target").option("-C, --cwd <dir>","Project directory").option("--project <id>","Project id (defaults to the project linked in .fimo.settings.json)").action((name,opts)=>agentLogsCommand(name,opts)),agents.command("runs <name>").description("Paginated session list").option("--limit <n>","Max sessions to show (default: 20)",v=>Number.parseInt(v,10)).option("--env <env>","Filter sessions to a specific env").option("--project <id>","Project id (defaults to the project linked in .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentRunsCommand(name,opts)),agents.command("report <name>").description("Print a run's report (the agent's final message); latest run unless --session is given").option("--session <id>","Target a specific session id").option("--env <env>","Pick the latest run on a specific env").option("--project <id>","Project id (defaults to the project linked in .fimo.settings.json)").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentReportCommand(name,opts));let secrets=agents.command("secrets").description("Edit the secrets requested in an agent config.yaml");secrets.command("list <name>").description("List secret keys requested by an agent config").option("-C, --cwd <dir>","Project directory").action((name,opts)=>agentSecretsListCommand(name,opts)),secrets.command("add <name> <key>").description("Add a secret key request to an agent config").option("-C, --cwd <dir>","Project directory").option("--optional","Mark the secret as optional").action((name,key,opts)=>agentSecretsAddCommand(name,key,opts)),secrets.command("remove <name> <key>").alias("rm").description("Remove a secret key request from an agent config").option("-C, --cwd <dir>","Project directory").action((name,key,opts)=>agentSecretsRemoveCommand(name,key,opts))}__name(registerAgentsCommands,"registerAgentsCommands");init_dist();init_project_context();function parseRangeOptions(options){let params={};if(options.preset&&(params.preset=options.preset),options.groupBy&&(params.groupBy=options.groupBy),options.from&&(params.from=options.from),options.to&&(params.to=options.to),options.days!==void 0){let n=Number(options.days);if(!Number.isFinite(n))throw new Error(`Invalid --days value: ${options.days}`);params.days=n}return params}__name(parseRangeOptions,"parseRangeOptions");function renderPrettyJson(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson,"renderPrettyJson");async function analyticsPageviewsCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params);ui.result({command:"analytics pageviews",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsPageviewsCommand,"analyticsPageviewsCommand");var TOP_DIMENSIONS=["pages","browsers","devices","countries","sources"];function dimensionField(dimension){return`top${dimension.charAt(0).toUpperCase()}${dimension.slice(1)}`}__name(dimensionField,"dimensionField");async function analyticsTopCommand(dimension,options,cmd){if(!TOP_DIMENSIONS.includes(dimension))throw new Error(`Unknown dimension: ${dimension}. Expected one of: ${TOP_DIMENSIONS.join(", ")}`);let{ctx,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params),field=dimensionField(dimension),items=Array.isArray(result[field])?result[field]:[],limit;if(options.limit!==void 0){let n=Number(options.limit);if(!Number.isFinite(n)||n<1)throw new Error(`Invalid --limit value: ${options.limit}`);limit=n}let trimmed=limit!==void 0?items.slice(0,limit):items;ui.result({command:"analytics top",data:{dimension,items:trimmed},render:__name(()=>renderPrettyJson(trimmed),"render")})}__name(analyticsTopCommand,"analyticsTopCommand");async function analyticsAnnotationsListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd),params=parseRangeOptions(options),result=await api.getProjectAnalytics(ctx.projectId,params),annotations2=Array.isArray(result.annotations)?result.annotations:[];ui.result({command:"analytics annotations list",data:{annotations:annotations2},render:__name(()=>renderPrettyJson(annotations2),"render")})}__name(analyticsAnnotationsListCommand,"analyticsAnnotationsListCommand");async function analyticsAnnotationsSetCommand(date,content2,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd),result=await api.setAnalyticsAnnotation(ctx.projectId,date,content2);ui.result({command:"analytics annotations set",data:result,render:__name(()=>renderPrettyJson(result),"render")})}__name(analyticsAnnotationsSetCommand,"analyticsAnnotationsSetCommand");async function analyticsAnnotationsDeleteCommand(date,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await api.deleteAnalyticsAnnotation(ctx.projectId,date),ui.ok({command:"analytics annotations delete",headline:`Deleted annotation for ${date}.`,details:{date}})}__name(analyticsAnnotationsDeleteCommand,"analyticsAnnotationsDeleteCommand");init_dist();import{spawn}from"node:child_process";import{mkdirSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{dirname,extname,isAbsolute,join as join2,resolve as resolvePath}from"node:path";var ENV_SESSION="FIMO_AGENT_SESSION",ENV_CAPS_FALLBACK="FIMO_AGENT_CAPABILITIES";function currentAgentSession(){let id=process.env[ENV_SESSION];return id&&id.length>0?id:void 0}__name(currentAgentSession,"currentAgentSession");async function defaultFetchSessionCapabilities(_sessionId){let raw=process.env[ENV_CAPS_FALLBACK];return raw?raw.split(",").map(s=>s.trim()).filter(s=>s.length>0):[]}__name(defaultFetchSessionCapabilities,"defaultFetchSessionCapabilities");async function requireCapability(cap,ctx={}){let sessionId=currentAgentSession();if(!sessionId)return{ok:!0,bypassed:!0};let granted=await(ctx.fetchSessionCapabilities??defaultFetchSessionCapabilities)(sessionId);if(!granted.includes(cap)){try{await auditCapabilityDecision({sessionId,cap,decision:"deny",reason:granted.length===0?"session-not-found":"not-declared",projectId:ctx.projectId,env:ctx.env})}catch{}throw new CapabilityDenied({cap,reason:granted.length===0?"session-not-found":"not-declared",granted,sessionId})}return auditCapabilityDecision({sessionId,cap,decision:"allow",projectId:ctx.projectId,env:ctx.env}),{ok:!0,bypassed:!1}}__name(requireCapability,"requireCapability");async function requireOperation(op,ctx={}){if(!hasOperation(op))throw new Error(`requireOperation: unknown operation id '${op}' \u2014 register it in @fimo/agents capabilities/operation-map.ts`);let cap=capabilityFor(op);return requireCapability(cap,ctx)}__name(requireOperation,"requireOperation");init_project_context();init_project();function extensionFor(asset){let fromName=extname(asset.name);if(fromName&&fromName.length<=6)return fromName;let mime=asset.mimeType??"";return mime.startsWith("image/")?"."+(mime.split("/")[1]??"bin"):mime.startsWith("video/")?"."+(mime.split("/")[1]??"mp4"):mime.startsWith("audio/")?"."+(mime.split("/")[1]??"mp3"):""}__name(extensionFor,"extensionFor");function defaultDownloadPath(asset){let ext=extensionFor(asset);return join2(tmpdir(),"fimo-assets",`${asset.id}${ext}`)}__name(defaultDownloadPath,"defaultDownloadPath");async function downloadToPath(url,dest){let response=await fetch(url);if(!response.ok)throw new Error(`Failed to download asset: HTTP ${response.status} ${response.statusText}`);let arrayBuffer=await response.arrayBuffer();mkdirSync(dirname(dest),{recursive:!0}),writeFileSync(dest,new Uint8Array(arrayBuffer))}__name(downloadToPath,"downloadToPath");function spawnBrowser(url){let command=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(process.platform==="win32"?spawn("cmd",["/c","start","",url],{detached:!0,stdio:"ignore"}):spawn(command,[url],{detached:!0,stdio:"ignore"})).unref()}__name(spawnBrowser,"spawnBrowser");function renderPrettyJson2(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson2,"renderPrettyJson");async function assetsOpenCommand(id,options,cmd){if(options.download&&options.browser)throw new Error("--download and --browser are mutually exclusive \u2014 pick one");let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.get",{projectId:ctx.projectId,env:ctx.env});let cwd=resolveProjectCwd(options.cwd),{data:asset}=await api.getAsset(ctx.projectId,id);if(asset.type==="folder")throw new Error(`Asset ${id} is a folder; can only open files`);if(!asset.url)throw new Error(`Asset ${id} has no public URL \u2014 it may not have finished uploading`);if(options.browser){spawnBrowser(asset.url);let payload2={opened:asset.url};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}if(options.download){let dest=options.path?isAbsolute(options.path)?options.path:resolvePath(cwd,options.path):defaultDownloadPath(asset);await downloadToPath(asset.url,dest);let payload2={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,path:dest,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,aiAltText:asset.aiAltText??null};ui.result({command:"assets open",data:payload2,render:__name(()=>renderPrettyJson2(payload2),"render")});return}let payload={id:asset.id,name:asset.name,mimeType:asset.mimeType,fileSize:asset.fileSize,url:asset.url,width:asset.width??null,height:asset.height??null,altText:asset.altText??null,caption:asset.caption??null,aiAltText:asset.aiAltText??null,aiCaption:asset.aiCaption??null,aiTags:asset.aiTags??null};ui.result({command:"assets open",data:payload,render:__name(()=>renderPrettyJson2(payload),"render")})}__name(assetsOpenCommand,"assetsOpenCommand");init_dist();import fs13 from"node:fs";import path16 from"node:path";init_project_context();init_project();function renderPrettyJson3(data2){return JSON.stringify(data2,null,2)}__name(renderPrettyJson3,"renderPrettyJson");async function assetsListCommand(options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd);await requireOperation("assets.list",{projectId:ctx.projectId,env:ctx.env});let mimePrefix=options.mimePrefix;mimePrefix||(options.image?mimePrefix="image/":options.video?mimePrefix="video/":options.audio&&(mimePrefix="audio/"));let params={};options.parentId&&(params.parentId=options.parentId),options.search&&(params.search=options.search),options.type&&(params.type=options.type),mimePrefix&&(params.mimePrefix=mimePrefix),options.sortBy&&(params.sortBy=options.sortBy),options.limit&&(params.limit=options.limit),options.offset&&(params.offset=options.offset);let result=await api.listAssets(ctx.projectId,Object.keys(params).length>0?params:void 0);ui.result({command:"assets list",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsListCommand,"assetsListCommand");async function assetsUploadCommand(file,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.upload",{projectId:ctx.projectId,env:ctx.env});let cwd=resolveProjectCwd(options.cwd);if(options.parentId&&options.folderPath)throw new Error("Use either --parent-id or --folder-path, not both");let filePath=path16.resolve(cwd,file);if(!fs13.existsSync(filePath))throw new Error(`File not found: ${filePath}`);let fileBuffer=fs13.readFileSync(filePath),fileName=options.name??path16.basename(filePath),formData=new FormData;formData.append("file",new Blob([fileBuffer]),fileName),options.name&&formData.append("name",options.name),options.parentId&&formData.append("parentId",options.parentId),options.folderPath&&formData.append("folderPath",options.folderPath);let result=await api.uploadAsset(ctx.projectId,formData);ui.result({command:"assets upload",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsUploadCommand,"assetsUploadCommand");async function assetsCreateFolderCommand(name,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.create_folder",{projectId:ctx.projectId,env:ctx.env});let result=await api.createFolder(ctx.projectId,name,options.parentId);ui.result({command:"assets create-folder",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsCreateFolderCommand,"assetsCreateFolderCommand");async function assetsMoveCommand(id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.move",{projectId:ctx.projectId,env:ctx.env});let result=await api.moveAsset(ctx.projectId,id,options.parentId);ui.result({command:"assets move",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsMoveCommand,"assetsMoveCommand");async function assetsDeleteCommand(id,options,cmd){let{ctx,api}=await bootstrapProjectCommand(options,cmd,{refuseReadOnly:!0});await requireOperation("assets.delete",{projectId:ctx.projectId,env:ctx.env});let result=await api.deleteAsset(ctx.projectId,id);ui.result({command:"assets delete",data:result,render:__name(()=>renderPrettyJson3(result),"render")})}__name(assetsDeleteCommand,"assetsDeleteCommand");init_esm();init_dist();init_api();init_git();init_project_context();init_project();function envOverride(program2){return envOverrideFromCommand(program2)}__name(envOverride,"envOverride");async function branchListCommand(cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({envOverride:envOverride(program2)}),envs=await new FimoApiClient().withEnv(ctx.env).listEnvs(ctx.projectId,{includeDeleted:opts.verbose});if(envs.length===0){ui.info({command:"branch",message:"(no envs yet)",hint:"Run `fimo branch <name>` to create one."});return}ui.table({command:"branch",columns:opts.verbose?[{key:"env",label:"ENV"},{key:"status",label:"STATUS"},{key:"parent",label:"PARENT"},{key:"preview",label:"PREVIEW"}]:[{key:"env",label:"ENV"},{key:"status",label:"STATUS"},{key:"parent",label:"PARENT"}],rows:envs.map(e=>({env:e.env,status:e.status,parent:e.parentEnv??"\u2014",preview:opts.verbose?e.previewUrl??"":void 0})),isActive:__name(row2=>row2.env===ctx.env,"isActive")})}__name(branchListCommand,"branchListCommand");async function branchCreateCommand(name,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env),parentEnv=opts.from??ctx.env;if(isProductionEnv(name)||isProductionEnv(parentEnv)){ui.error({command:"branch",code:"PROTECTED_ENV",message:`The '${PRODUCTION_ENV}' env is protected \u2014 it cannot be created or forked from.`});return}let parentValidation=await validateParentEnv(api,ctx.projectId,parentEnv,ctx,opts.from);if(!parentValidation.ok){ui.error({command:"branch",code:"ENV_NOT_FOUND",message:parentValidation.message});return}let created=await api.createEnv(ctx.projectId,{env:name,parentEnv});ui.ok({command:"branch",headline:`Created env '${created.env}' (status: ${created.status})`,details:{env:created.env,parent_env:parentEnv,status:created.status,preview_url:created.previewUrl??null}})}__name(branchCreateCommand,"branchCreateCommand");async function branchDeleteCommand(name,cmd){let program2=cmd.parent??cmd,ctx=await getProjectContext({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env);if(name===DEFAULT_ENV){ui.error({command:"branch",code:"PROTECTED_ENV",message:`Refusing to delete the default env '${DEFAULT_ENV}'.`});return}if(isProductionEnv(name)){ui.error({command:"branch",code:"PROTECTED_ENV",message:`The '${PRODUCTION_ENV}' env is protected and cannot be deleted.`});return}await api.deleteEnv(ctx.projectId,name),ui.ok({command:"branch",headline:`Deleted env '${name}'`,details:{env:name}})}__name(branchDeleteCommand,"branchDeleteCommand");async function checkoutCommand(name,_options,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env),cwd=resolveProjectCwd();if(isProductionEnv(name)){ui.error({command:"checkout",code:"PROTECTED_ENV",message:`The '${PRODUCTION_ENV}' env is protected and cannot be checked out.`});return}let created=!1;if(opts.create){let parentEnv=opts.from??ctx.env,parentValidation=await validateParentEnv(api,ctx.projectId,parentEnv,ctx,opts.from);if(!parentValidation.ok){ui.error({command:"checkout",code:"ENV_NOT_FOUND",message:parentValidation.message});return}await api.createEnv(ctx.projectId,{env:name,parentEnv}),created=!0}else await api.getEnv(ctx.projectId,name);let gitSwitched=!1;if(await isGitRepo(cwd))try{await runGit(["checkout",name],cwd),gitSwitched=!0}catch(err){let stderr=err instanceof Error&&"stderr"in err?String(err.stderr):"";if(/did not match any file|pathspec/i.test(stderr))await runGit(["checkout","-b",name],cwd),gitSwitched=!0;else throw err}ui.ok({command:"checkout",headline:`Now on env '${name}'`,details:{env:name,created,git_switched:gitSwitched,parent_env:opts.from??null}})}__name(checkoutCommand,"checkoutCommand");async function pullCommand(_options,cmd){let program2=cmd.parent??cmd,opts=cmd.opts(),ctx=await getProjectContext({envOverride:envOverride(program2)}),api=new FimoApiClient().withEnv(ctx.env),{env,conflicts}=await api.syncEnv(ctx.projectId,ctx.env,{from:opts.from}),warnings=conflicts>0?[`Resolved ${conflicts} conflict(s) (parent-wins for now \u2014 M12 conflict UI will add per-row picks)`]:void 0;ui.ok({command:"pull",headline:`Env '${env.env}' synced`,details:{env:env.env,from:opts.from??null,conflicts},warnings})}__name(pullCommand,"pullCommand");async function validateParentEnv(api,projectId,parentEnv,ctx,fromFlag){try{return await api.getEnv(projectId,parentEnv),{ok:!0}}catch(err){if(!(err instanceof ApiRequestError)||err.status!==404)throw err;let origin=fromFlag?`the \`--from ${fromFlag}\` flag`:ctx.source==="branch"?`your active env (\`${ctx.env}\`)`:ctx.source==="flag"?`the \`--env ${ctx.env}\` flag`:ctx.source==="tag"?`the release tag \`${ctx.env}\``:`the project default (\`${ctx.env}\`)`,fixes=[];return fromFlag?fixes.push(`pass an existing env via \`--from <env>\` (try \`--from ${DEFAULT_ENV}\`)`):ctx.source==="branch"?(fixes.push(`switch envs first: \`fimo checkout ${DEFAULT_ENV}\``),fixes.push(`or pass \`--from ${DEFAULT_ENV}\` to override for this command`)):ctx.source==="flag"?fixes.push(`use a different \`--env <existing>\` (try \`--env ${DEFAULT_ENV}\`)`):fixes.push(`pass \`--from ${DEFAULT_ENV}\` to fork from main`),{ok:!1,message:`Cannot create env: parent env '${parentEnv}' doesn't exist on this project. The CLI resolved the parent from ${origin}. Fix: ${fixes.join(", or ")}.`}}}__name(validateParentEnv,"validateParentEnv");init_dist();init_api();init_config();init_project();function registerChannelsCommands(program2){program2.command("channels").description("Manage project channel bindings").addHelpText("after",`
1103
1103
  Examples:
1104
1104
  fimo integrations connect slack
1105
1105
  fimo channels bind slack:#launch