@nextblock-cms/cortex 0.14.4 → 0.14.6

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.
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("ai"),hn=require("./ai-global-agent-db-tools.cjs.js"),yn=require("./ai-global-agent-custom-block-tools.cjs.js"),Pt=require("./editor-document-from-html.cjs.js");require("./zod-config.cjs.js");const i=require("zod"),G=["text","heading","image","button","posts_grid","video_embed","section","form","testimonial","product_grid","featured_product","cart","checkout","product_details"],_n=1e4,bn={arabic:"ar",chinese:"zh",dutch:"nl",english:"en",french:"fr",francaise:"fr",francais:"fr",german:"de",italian:"it",japanese:"ja",korean:"ko",portuguese:"pt",russian:"ru",spanish:"es"},Nt=i.z.string().trim().min(1).max(2048).refine(e=>e.startsWith("/")||e.startsWith("#")||e.startsWith("http://")||e.startsWith("https://")||e.startsWith("mailto:")||e.startsWith("tel:"),"URL must be a relative path, hash link, http(s) URL, mailto URL, or tel URL."),yt=i.z.strictObject({label:i.z.string().trim().min(1).max(120),target:i.z.enum(["_self","_blank"]).optional(),url:Nt}),qe=yt.extend({children:i.z.array(yt).max(20).optional()}),kn=i.z.strictObject({label:i.z.string().trim().min(1).max(120).optional(),url:Nt.optional()}).refine(e=>!!(e.label||e.url),{message:"Navigation item match requires label or url."}),Q=i.z.strictObject({items:i.z.array(qe).min(1).max(30),languageCode:i.z.string().trim().min(2).max(80).default("en").describe('Locale code or language name, for example "en", "fr", "English", or "French".'),match:kn.optional().describe('For mode "update", identifies the existing navigation item to update.'),mode:i.z.enum(["append","replace","update"]).default("append")}),Z=i.z.strictObject({copyright:i.z.record(i.z.string().trim().min(2).max(12),i.z.string().trim().min(1).max(500)).optional(),languageCode:i.z.string().trim().min(2).max(80).default("en").describe('Locale code or language name, for example "en", "fr", "English", or "French".'),links:i.z.array(qe).min(1).max(30).optional()}),xe=i.z.strictObject({limit:i.z.number().int().min(1).max(8).default(4),query:i.z.string().trim().min(2).max(300)}),Re=i.z.object({currency:i.z.string().trim().min(3).max(3).optional().describe("Optional currency code for currency-specific monetary reports (e.g., USD, CAD). Do not set this for plain order-status counts unless the user asks for a currency."),query:i.z.string().describe("The analytical question about orders, products, or revenue."),reportType:i.z.enum(["revenue","orders","products","general"]).optional().default("general").describe("The focus area of the statistical report."),timeRange:i.z.enum(["today","this_month","last_7_days","last_30_days","last_month","last_90_days","all_time"]).optional().default("all_time").describe("The time period for the report. Use all_time for current order-status counts unless the user names a specific period.")}),Me=i.z.strictObject({contentType:i.z.enum(["page","post","product"]),currentEditor:i.z.strictObject({blockId:i.z.union([i.z.number().int().positive(),i.z.string().trim().min(1).max(120)]).nullable().optional(),blockType:i.z.string().trim().min(1).max(80).nullable().optional(),field:i.z.string().trim().min(1).max(120).nullable().optional()}).optional(),entityId:i.z.union([i.z.number().int().positive(),i.z.string().trim().min(1).max(120)]),languageId:i.z.number().int().positive().nullable().optional(),slug:i.z.string().trim().min(1).max(300).nullable().optional(),title:i.z.string().trim().min(1).max(300).nullable().optional(),translationGroupId:i.z.string().trim().min(1).max(120).nullable().optional()}),De=i.z.strictObject({includeBlockContent:i.z.boolean().default(!1),includeBlocks:i.z.boolean().default(!0)}),ee=i.z.strictObject({fields:i.z.strictObject({description_json:i.z.unknown().optional(),excerpt:i.z.string().max(2e3).nullable().optional(),feature_image_id:i.z.string().trim().min(1).max(2048).nullable().optional(),label:i.z.string().max(120).nullable().optional(),meta_description:i.z.string().max(500).nullable().optional(),meta_title:i.z.string().max(160).nullable().optional(),published_at:i.z.string().max(80).nullable().optional(),short_description:i.z.string().max(2e3).nullable().optional(),slug:i.z.string().trim().min(1).max(300).optional(),status:i.z.enum(["draft","published","active","archived"]).optional(),subtitle:i.z.string().max(300).nullable().optional(),title:i.z.string().trim().min(1).max(300).optional()}).partial()}),te=i.z.strictObject({blockId:i.z.number().int().positive(),blockType:i.z.enum(G).optional(),content:i.z.record(i.z.string(),i.z.unknown())}),ne=i.z.strictObject({blockIndex:i.z.number().int().min(0),blockType:i.z.enum(G).optional(),columnIndex:i.z.number().int().min(0),content:i.z.record(i.z.string(),i.z.unknown()),parentBlockId:i.z.number().int().positive()}),wn=i.z.enum(["page","post","product"]),H=i.z.strictObject({contentType:wn.optional(),entityId:i.z.union([i.z.number().int().positive(),i.z.string().trim().min(1).max(120)]).optional(),slug:i.z.string().trim().min(1).max(300).optional(),title:i.z.string().trim().min(1).max(300).optional()}),oe=i.z.strictObject({blockType:i.z.enum(G),content:i.z.record(i.z.string(),i.z.unknown()),order:i.z.number().int().min(0).optional()}),re=H.extend({images:i.z.array(i.z.string().trim().min(1).max(2048)).min(1).max(12).describe("External https image URLs (imported into the media library automatically) and/or existing media library ids. The first entry is the feature image (pages/posts) or the main product image (products).")}),ie=H.extend({anchorBlockId:i.z.number().int().positive().optional(),anchorBlockType:i.z.enum(G).optional(),block:oe,position:i.z.enum(["before","after","start","end"]).default("end")}),ae=i.z.strictObject({blocks:i.z.array(oe).max(20).optional(),contactEmail:i.z.string().email().optional(),feature_image_id:i.z.string().trim().min(1).max(2048).nullable().optional(),languageCode:i.z.string().trim().min(2).max(80).optional(),meta_description:i.z.string().max(500).nullable().optional(),meta_title:i.z.string().max(160).nullable().optional(),slug:i.z.string().trim().min(1).max(300).optional(),status:i.z.enum(["draft","published","archived"]).default("draft"),title:i.z.string().trim().min(1).max(300),translationGroupId:i.z.string().trim().min(1).max(120).optional()}),se=i.z.strictObject({blocks:i.z.array(oe).max(20).optional(),excerpt:i.z.string().max(2e3).nullable().optional(),feature_image_id:i.z.string().trim().min(1).max(2048).nullable().optional(),label:i.z.string().max(120).nullable().optional(),languageCode:i.z.string().trim().min(2).max(80).optional(),meta_description:i.z.string().max(500).nullable().optional(),meta_title:i.z.string().max(160).nullable().optional(),published_at:i.z.string().max(80).nullable().optional(),slug:i.z.string().trim().min(1).max(300).optional(),status:i.z.enum(["draft","published","archived"]).default("draft"),subtitle:i.z.string().max(300).nullable().optional(),title:i.z.string().trim().min(1).max(300),translationGroupId:i.z.string().trim().min(1).max(120).optional()}),ce=i.z.strictObject({blocks:i.z.array(oe).max(20).optional().describe("Content blocks for the product description area, same block vocabulary as create_cms_page. Rendered on the public product page in place of the plain description."),description_html:i.z.string().max(6e4).optional().describe("The product body as an HTML fragment (headings, paragraphs, lists, bold/italic/links). Converted to the editor document automatically. Prefer this over description_json."),description_json:i.z.unknown().optional(),freemius_plan_id:i.z.string().optional(),freemius_product_id:i.z.string().optional(),images:i.z.array(i.z.string().trim().min(1).max(2048)).max(12).optional().describe("Product images, in order: the first becomes the main product image and the rest the gallery. Each entry is either an external https image URL (imported into the media library automatically) or an existing media library id."),is_taxable:i.z.boolean().default(!0),languageCode:i.z.string().trim().min(2).max(80).optional(),meta_description:i.z.string().max(500).nullable().optional(),meta_title:i.z.string().max(160).nullable().optional(),payment_provider:i.z.enum(["stripe","freemius"]).default("stripe"),price:i.z.number().min(0).default(0),prices:i.z.record(i.z.string(),i.z.number().min(0)).optional(),product_type:i.z.enum(["physical","digital"]).default("physical"),sale_price:i.z.number().min(0).nullable().optional(),sale_prices:i.z.record(i.z.string(),i.z.number().min(0).nullable()).optional(),short_description:i.z.string().max(2e3).nullable().optional(),sku:i.z.string().trim().min(1).max(120).optional(),slug:i.z.string().trim().min(1).max(300).optional(),status:i.z.enum(["draft","active","archived"]).default("draft"),stock:i.z.number().int().min(0).default(0),title:i.z.string().trim().min(1).max(300),trial_period_days:i.z.number().int().min(0).default(0),trial_requires_payment_method:i.z.boolean().default(!1),translationGroupId:i.z.string().trim().min(1).max(120).optional(),upc:i.z.string().max(120).nullable().optional()}),le=H.extend({currencyCode:i.z.string().trim().min(3).max(3).optional(),endsAt:i.z.string().max(80).nullable().optional(),field:i.z.string().trim().min(1).max(120),startsAt:i.z.string().max(80).nullable().optional(),value:i.z.unknown()}),Ge=H,ue=H,Ut=i.z.discriminatedUnion("tool",[i.z.strictObject({input:ae,tool:i.z.literal("create_cms_page")}),i.z.strictObject({input:se,tool:i.z.literal("create_cms_post")}),i.z.strictObject({input:ce,tool:i.z.literal("create_cms_product")}),i.z.strictObject({input:ue,tool:i.z.literal("delete_cms_item")}),i.z.strictObject({input:le,tool:i.z.literal("update_cms_item_field")}),i.z.strictObject({input:te,tool:i.z.literal("update_content_block")}),i.z.strictObject({input:ie,tool:i.z.literal("insert_content_block")}),i.z.strictObject({input:ee,tool:i.z.literal("update_current_cms_fields")}),i.z.strictObject({input:Z,tool:i.z.literal("update_footer")}),i.z.strictObject({input:Q,tool:i.z.literal("update_navigation_bar")}),i.z.strictObject({input:ne,tool:i.z.literal("update_section_column_block")}),i.z.strictObject({input:re,tool:i.z.literal("set_content_images")})]),In=i.z.union([ae.extend({tool:i.z.literal("create_cms_page")}).transform(({tool:e,...t})=>({input:t,tool:e})),se.extend({tool:i.z.literal("create_cms_post")}).transform(({tool:e,...t})=>({input:t,tool:e})),ce.extend({tool:i.z.literal("create_cms_product")}).transform(({tool:e,...t})=>({input:t,tool:e})),ue.extend({tool:i.z.literal("delete_cms_item")}).transform(({tool:e,...t})=>({input:t,tool:e})),le.extend({tool:i.z.literal("update_cms_item_field")}).transform(({tool:e,...t})=>({input:t,tool:e})),te.extend({tool:i.z.literal("update_content_block")}).transform(({tool:e,...t})=>({input:t,tool:e})),ie.extend({tool:i.z.literal("insert_content_block")}).transform(({tool:e,...t})=>({input:t,tool:e})),ee.extend({tool:i.z.literal("update_current_cms_fields")}).transform(({tool:e,...t})=>({input:t,tool:e})),Z.extend({tool:i.z.literal("update_footer")}).transform(({tool:e,...t})=>({input:t,tool:e})),Q.extend({tool:i.z.literal("update_navigation_bar")}).transform(({tool:e,...t})=>({input:t,tool:e})),ne.extend({tool:i.z.literal("update_section_column_block")}).transform(({tool:e,...t})=>({input:t,tool:e})),re.extend({tool:i.z.literal("set_content_images")}).transform(({tool:e,...t})=>({input:t,tool:e}))]),Tn=i.z.string().transform((e,t)=>{const n=vn(e);return n.success?n.action:(t.addIssue({code:"custom",message:n.message}),i.z.NEVER)}),xn=i.z.union([Ut,In,Tn]),Ke=i.z.strictObject({actions:i.z.array(xn).min(1).max(8),summary:i.z.string().trim().min(1).max(500).optional()});function zn(e){const t=[];let n="",o=0,r=null,a=!1;for(const s of e){if(r){n+=s,a?a=!1:s==="\\"?a=!0:s===r&&(r=null);continue}if(s==='"'||s==="'"){r=s,n+=s;continue}if(s==="["||s==="{"||s==="("){o++,n+=s;continue}if(s==="]"||s==="}"||s===")"){o=Math.max(0,o-1),n+=s;continue}if(s===","&&o===0){n.trim()&&t.push(n.trim()),n="";continue}n+=s}return n.trim()&&t.push(n.trim()),t}function _t(e){let t="";for(let n=0;n<e.length;n++){const o=e[n];if(o!=="'"){t+=o;continue}let r="",a=!1;for(n++;n<e.length;n++){const s=e[n];if(a){r+=s,a=!1;continue}if(s==="\\"){a=!0;continue}if(s==="'")break;r+=s}t+=JSON.stringify(r)}return t.replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false").replace(/\bNone\b/g,"null")}function Cn(e){const t=e.trim();return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')||t.startsWith("[")||t.startsWith("{")?JSON.parse(_t(t)):/^-?\d+(?:\.\d+)?$/.test(t)?Number(t):t==="true"||t==="True"?!0:t==="false"||t==="False"?!1:t==="null"||t==="None"?null:t}function Sn(e){const t={};for(const n of zn(e)){const o=n.indexOf("=");if(o<=0)throw new Error(`Expected key=value argument, received "${n}".`);const r=n.slice(0,o).trim();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new Error(`Invalid argument name "${r}".`);t[r]=Cn(n.slice(o+1))}return t}function vn(e){const n=e.trim().match(/^([a-z_]+)\(([\s\S]*)\)$/);if(!n)return{message:'Action plan actions must be JSON objects like { "tool": "create_cms_page", "input": { ... } }, not freeform text.',success:!1};const o=n[1];let r;try{r=Sn(n[2])}catch(c){return{message:c instanceof Error?c.message:"Could not parse action-plan command arguments.",success:!1}}const a={input:r,tool:o},s=Ut.safeParse(a);return s.success?{action:s.data,success:!0}:{message:`Invalid action-plan command "${o}": ${s.error.issues.map(c=>c.message).join("; ")}`,success:!1}}function En(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/\s+/g," ").trim()}function fe(e,t){return t.some(n=>e.includes(n))}function $n(e){const t=En(e),n=fe(t,["add ","insert ","put ","create "]),o=fe(t,["title","heading","description","intro","copy","paragraph"]),r=t.includes("form")&&fe(t,["above","before"]),a=t.includes("contact page")||t.includes("contact pages")||t.includes("contact us")||t.includes("contactez-nous"),s=t.includes("english")&&fe(t,["french","francais","francaise"]);return!n||!o||!r||!a||!s?null:{actions:[{input:{anchorBlockType:"form",block:{blockType:"text",content:{html_content:"<h2>Let us help you move faster</h2><p>Have a question, project idea, or need help choosing the right next step? Send us a message and the NextBlock team will get back to you soon.</p>"}},contentType:"page",position:"before",slug:"contact-us"},tool:"insert_content_block"},{input:{anchorBlockType:"form",block:{blockType:"text",content:{html_content:"<h2>Parlons de votre projet</h2><p>Vous avez une question, une idee de projet ou besoin d'aide pour avancer? Envoyez-nous un message et l'equipe NextBlock vous repondra rapidement.</p>"}},contentType:"page",position:"before",slug:"contactez-nous"},tool:"insert_content_block"}],summary:"Add visible title and description copy above the forms on the English and French Contact pages."}}const An=i.z.enum(G),bt=i.z.object({direction:i.z.string().optional(),stops:i.z.array(i.z.object({color:i.z.string(),position:i.z.number()})),type:i.z.enum(["linear","radial"])}),Pn=i.z.object({gradient:bt.optional(),image:i.z.object({alt_text:i.z.string().optional(),blur_data_url:i.z.string().optional(),external_url:i.z.string().optional(),height:i.z.number().optional(),media_id:i.z.string().optional(),object_key:i.z.string().optional(),overlay:i.z.object({gradient:bt,type:i.z.literal("gradient")}).optional(),position:i.z.enum(["center","top","bottom","left","right"]),quality:i.z.number().nullable().optional(),size:i.z.enum(["cover","contain"]),width:i.z.number().optional()}).optional(),min_height:i.z.string().optional(),solid_color:i.z.string().optional(),theme:i.z.enum(["primary","secondary","muted","accent","destructive"]).optional(),type:i.z.enum(["none","theme","solid","gradient","image"])}),Nn=i.z.object({block_type:An,content:i.z.record(i.z.string(),i.z.any()),temp_id:i.z.string().optional()}),Un=i.z.object({background:Pn,column_blocks:i.z.array(i.z.array(Nn)),column_gap:i.z.enum(["none","sm","md","lg","xl"]),container_type:i.z.enum(["full-width","container","container-sm","container-lg","container-xl"]),padding:i.z.object({bottom:i.z.enum(["none","sm","md","lg","xl"]),top:i.z.enum(["none","sm","md","lg","xl"])}),responsive_columns:i.z.object({desktop:i.z.union([i.z.literal(1),i.z.literal(2),i.z.literal(3),i.z.literal(4)]),mobile:i.z.union([i.z.literal(1),i.z.literal(2)]),tablet:i.z.union([i.z.literal(1),i.z.literal(2),i.z.literal(3)])}),vertical_alignment:i.z.enum(["start","center","end","stretch"]).optional()}),Fn={button:i.z.object({position:i.z.enum(["left","center","right"]).optional(),size:i.z.enum(["default","sm","lg","full"]).optional(),text:i.z.string(),url:i.z.string(),variant:i.z.enum(["default","outline","secondary","ghost","link"]).optional()}),cart:i.z.object({}),checkout:i.z.object({}),featured_product:i.z.object({imagePosition:i.z.enum(["left","right"]).default("left"),productId:i.z.string().min(1),showBackground:i.z.boolean().default(!1)}),form:i.z.object({fields:i.z.array(i.z.object({field_type:i.z.enum(["text","email","textarea","select","radio","checkbox"]),is_required:i.z.boolean(),label:i.z.string(),options:i.z.array(i.z.object({label:i.z.string(),value:i.z.string()})).optional(),placeholder:i.z.string().optional(),temp_id:i.z.string()})),recipient_email:i.z.string().email(),submit_button_text:i.z.string(),success_message:i.z.string()}),heading:i.z.object({level:i.z.union([i.z.literal(1),i.z.literal(2),i.z.literal(3),i.z.literal(4),i.z.literal(5),i.z.literal(6)]),textAlign:i.z.enum(["left","center","right","justify"]).optional(),textColor:i.z.union([i.z.enum(["foreground","primary","secondary","accent","muted","destructive","background"]),i.z.string().regex(/^(#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})|rgba?\([^)]+\)|hsla?\([^)]+\))$/i,"Must be a hex, rgb(a) or hsl(a) colour")]).optional().describe("Prefer a theme token so the heading adapts to dark mode; use a CSS colour only when the brand requires an exact value"),text_content:i.z.string()}),image:i.z.object({alt_text:i.z.string().optional(),caption:i.z.string().optional(),external_url:i.z.string().nullable().optional(),height:i.z.number().nullable().optional(),media_id:i.z.string().nullable().optional(),object_key:i.z.string().nullable().optional(),width:i.z.number().nullable().optional()}),posts_grid:i.z.object({columns:i.z.number().min(1).max(6),postsPerPage:i.z.number().min(1).max(50),showPagination:i.z.boolean(),title:i.z.string().optional()}),product_details:i.z.object({}),product_grid:i.z.object({categoryId:i.z.string().optional(),categoryIds:i.z.array(i.z.string()).max(20).optional(),limit:i.z.number().min(0).max(48).default(6),productIds:i.z.array(i.z.string()).max(24).optional(),showPagination:i.z.boolean().default(!1),title:i.z.string().optional(),type:i.z.enum(["latest","category","manual"]).default("latest")}),section:Un,testimonial:i.z.object({author_name:i.z.string().min(1),author_title:i.z.string().optional(),image_url:i.z.string().url().optional().or(i.z.literal("")),quote:i.z.string().min(1)}),text:i.z.object({html_content:i.z.string()}),video_embed:i.z.object({autoplay:i.z.boolean().optional(),controls:i.z.boolean().optional(),title:i.z.string().optional(),url:i.z.string()})};function On(e){return G.includes(e)}function jn(e){return typeof e?.validateBlockContent=="function"?e.validateBlockContent:null}function Bn(e,t,n){const o=jn(n);if(o)return o(e,t);const r=Fn[e].safeParse(t);return r.success?{errors:[],isValid:!0,warnings:[]}:{errors:r.error.issues.map(a=>{const s=a.path.join(".");return s?`${s}: ${a.message}`:a.message}),isValid:!1,warnings:[]}}function kt(){return i.z.object({content:i.z.array(i.z.any()).optional(),type:i.z.literal("doc")})}function He(){try{const{revalidatePath:e}=require("next/cache");return e}catch{return null}}function z(e){if(!e?.supabase)throw new Error("A Supabase service client is required to execute Cortex AI global tools.");return e.supabase}function Ln(e,t,n){let o;const r=new Promise(a=>{o=setTimeout(()=>a(n()),t)});return Promise.race([e.finally(()=>{o&&clearTimeout(o)}),r])}function V(e){const t=Me.safeParse(e?.pageContext);if(!t.success)throw new Error("No current CMS page context is available. Open a page, post, or product edit screen before using this editing tool.");return t.data}function Ve(e){const t=typeof e.entityId=="number"?e.entityId:Number.parseInt(e.entityId,10);if(!Number.isInteger(t)||t<=0)throw new Error(`Current ${e.contentType} id must be a positive integer.`);return t}function Ft(e){const t=String(e.entityId||"").trim();if(!t)throw new Error(`Current ${e.contentType} id is missing.`);return t}function ze(e){return e.contentType==="product"?Ft(e):Ve(e)}const qn=/^https?:\/\//i,Rn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function de(e,t,n){if(typeof e!="string")return null;const o=e.trim();if(!o)return null;if(!qn.test(o)){if(Rn.test(o))return o;throw new Error(`"${o}" is not a usable image reference — provide an https:// image URL or a media library id.`)}const r=t?.importExternalImage;if(!r)throw new Error("I can only attach an image from a URL when media import is available here. Please pick an image from the media library instead.");const a=await r({altText:n,url:o});if("error"in a)throw new Error(`I could not import the image from that URL: ${a.error}`);return a.id}async function Ot(e,t,n){const o=[];for(let r=0;r<e.length;r+=1){const a=await de(e[r],t,`${n} image ${r+1}`);a&&o.push(a)}return o}async function Mn(e){const t=[...new Set(e.mediaIds)],{error:n}=await e.supabase.from("product_media").delete().eq("product_id",e.productId);if(n)throw new Error(`Could not clear the product's existing images: ${_(n)}`);if(t.length>0){const{error:o}=await e.supabase.from("product_media").insert(t.map((r,a)=>({media_id:r,product_id:e.productId,sort_order:a})));if(o)throw new Error(`Could not save the product images: ${_(o)}`)}return t}async function Ce(e){if(!e.productId)return!1;const{data:t,error:n}=await e.supabase.from("product_drafts").select("id, blocks, meta").eq("product_id",e.productId).maybeSingle();if(n||!t)return!1;const o=e.patch({blocks:Array.isArray(t.blocks)?D(t.blocks):[],meta:E(t.meta)?D(t.meta):{}}),r={updated_at:new Date().toISOString()};if(o.blocks&&(r.blocks=o.blocks),o.meta&&(r.meta=o.meta),Object.keys(r).length===1)return!1;const{error:a}=await e.supabase.from("product_drafts").update(r).eq("id",t.id);if(a)throw new Error(`The product was updated, but its open draft could not be kept in sync: ${_(a)}. Publishing that draft would undo this change — publish or discard it in the product editor first.`);return!0}function jt(e){return typeof e=="string"?e.trim().replace(/^\/+|\/+$/g,""):""}function Dn(e,t){const n=jt(t??e.slug);return n?e.contentType==="page"?n==="home"?"/":`/${n}`:e.contentType==="post"?`/article/${n}`:`/product/${n}`:null}function Gn(e){const t=String(e.entityId);return e.contentType==="page"?`/cms/pages/${t}/edit`:e.contentType==="post"?`/cms/posts/${t}/edit`:`/cms/products/${t}/edit`}function N(e,t,n){const o=e?.revalidatePath??He();if(!o)return;o(Gn(t));const r=Dn(t,n);r&&o(r),t.contentType==="page"&&r!=="/"&&o("/"),t.contentType==="product"&&o("/cms/products")}function Bt(e){const t=e?.revalidatePath??He();t&&(t("/","layout"),t("/cms/navigation"))}function _(e){return e?typeof e=="object"&&"message"in e?String(e.message||"Unknown database error."):String(e):"Unknown database error."}async function Kn(){return Promise.resolve().then(()=>require("./ai-global-agent-ecommerce.cjs.js"))}function Pe(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(t=>Pe(t)).join(",")}]`:`{${Object.keys(e).filter(t=>t!=="temp_id").sort().map(t=>`${JSON.stringify(t)}:${Pe(e[t])}`).join(",")}}`}function Hn(e){let t=2166136261;const n=Pe(e);for(let o=0;o<n.length;o++)t^=n.charCodeAt(o),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function Ne(e){return e.replace(/\s+/g," ").trim().toUpperCase()}function Vn(e,t,n){return`${Ne(`CONFIRM ${e} ${t}`)} #${Hn(n)}`}function Lt(e){return{confirmationPhrase:Vn(e.action,e.subject,e.payload),mutationExecuted:!1,preview:e.preview,requiresConfirmation:!0,success:!0}}function U(e,t){const n=e[t];return typeof n=="string"&&n.trim()?n.trim():null}function R(e,t){const n=Number(e[t]);return Number.isFinite(n)?n:null}function P(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function Wn(e,t){const n=U(t,"summary");if(n)return n;const o=U(t,"title"),r=U(t,"slug"),a=U(t,"status"),s=U(t,"contentType"),c=U(t,"field"),u=U(t,"mode"),d=U(t,"languageCode"),l=R(t,"blockCount"),m=R(t,"itemCount"),h=R(t,"affectedCount");if(e==="create_cms_page"||e==="create_cms_post")return`Create ${a||"draft"} ${e==="create_cms_page"?"page":"post"} "${o||r||"Untitled"}"${r?` at slug "${r}"`:""}${l!==null?` with ${P(l,"content block")}`:""}.`;if(e==="create_cms_product"){const p=R(t,"imageCount"),g=R(t,"blockCount"),f=[p?P(p,"image"):null,g?P(g,"description block"):R(t,"descriptionLength")?"a full description":null].filter(Boolean);return`Create ${a||"draft"} product "${o||r||"Untitled"}"${r?` at slug "${r}"`:""}${f.length?` with ${f.join(" and ")}`:""}.`}if(e==="update_cms_item_field")return`Update ${c||"one field"} on the ${s||"CMS item"} "${o||r||"selected item"}".`;if(e==="update_navigation_bar")return`${u==="append"?"Add":u==="update"?"Update":"Replace"} ${m!==null?P(m,"navigation item"):"navigation items"} in the ${d||"selected"} header navigation.`;if(e==="update_footer"){const p=R(t,"linkCount");return`Update the ${d||"selected"} footer${p!==null?` with ${P(p,"link")}`:""}.`}return e==="update_content_block"?`Update the selected ${U(t,"blockType")||"content"} block.`:e==="insert_content_block"?`Insert ${U(t,"blockType")||"content"} block on the ${s||"CMS item"} "${o||r||"selected item"}".`:e==="update_section_column_block"?`Update the selected nested ${U(t,"nestedBlockType")||"section"} block.`:e==="delete_cms_item"||e==="prepare_delete_cms_item"?`Delete ${h!==null?P(h,s||"CMS item"):`the selected ${s||"CMS item"}`}${o||r?` for "${o||r}"`:""}.`:"Complete the requested CMS change."}function A(e){if(e.context?.skipConfirmation)return null;const t=Lt(e),n=Ne(e.context?.latestUserMessage||""),o=Ne(t.confirmationPhrase);return n.includes(o)?null:t}function We(e){const t=e?.actorUserId;if(!t)throw new Error("A confirmed CMS mutation requires an authenticated admin actor.");return t}function Je(){return globalThis.crypto?.randomUUID?.()||`id-${Date.now()}-${Math.random().toString(36).slice(2)}`}function L(e){return e.toLowerCase().trim().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,300)}function Ye(e){return(e||"USD").trim().toUpperCase()}const Jn=new Set(["BIF","CLP","DJF","GNF","JPY","KMF","KRW","MGA","PYG","RWF","UGX","VND","VUV","XAF","XOF","XPF"]);function Yn(e){return Jn.has(Ye(e))?0:2}function qt(e,t){return Math.round(e*10**Yn(t))}function Xn(e,t){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.entries(e).reduce((n,[o,r])=>{if(typeof r=="number"&&Number.isFinite(r)&&r>=0){const a=Ye(o||t);n[a]=qt(r,a)}return n},{})}function pe(e,t){if(!E(e))throw new Error(`${t} content must be a JSON object.`);return JSON.parse(JSON.stringify(e))}function D(e){return JSON.parse(JSON.stringify(e))}function E(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function Ue(e,t){const n=D(e);for(const[o,r]of Object.entries(t))if(r!==void 0){if(E(r)&&E(n[o])){n[o]=Ue(n[o],r);continue}n[o]=D(r)}return n}function Rt(e,t){if(t.contentType==="product"){if(String(e.product_id??"")!==String(Ft(t)))throw new Error(`Block ${e.id} does not belong to the current product being edited.`);return}const n=Ve(t);if((t.contentType==="page"?Number(e.page_id):Number(e.post_id))!==n)throw new Error(`Block ${e.id} does not belong to the current ${t.contentType} being edited.`)}function be(e,t){const n=typeof e=="string"?e:"";if(!On(n))throw new Error(`${t} has unsupported block type "${n||"unknown"}".`);return n}function Mt(e,t,n){if(e&&e!==t)throw new Error(`${n} is a "${t}" block. Refusing to update it as "${e}".`)}function M(e,t,n,o){const r=Bn(e,t,o);if(!r.isValid)throw new Error(`${n} content is invalid for block type "${e}": ${r.errors.join("; ")}`)}function Dt(e){return e==="section"}function Qn(e){return typeof e.html_content=="string"?"text":typeof e.text=="string"&&typeof e.url=="string"?"button":typeof e.text_content=="string"?"heading":"media_id"in e||"object_key"in e||"external_url"in e?"image":typeof e.quote=="string"&&typeof e.author_name=="string"?"testimonial":typeof e.url=="string"&&("controls"in e||"autoplay"in e||"title"in e)?"video_embed":Array.isArray(e.fields)||typeof e.recipient_email=="string"?"form":"postsPerPage"in e||"showPagination"in e?"posts_grid":typeof e.productId=="string"?"featured_product":"limit"in e&&"type"in e?"product_grid":null}function ke(e){return`ai-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Fe(e,t,n){if(!E(e))throw new Error(`${t} must be a JSON object.`);const o=e.block_type??e.blockType,r=be(o,t);if(Dt(r))throw new Error(`${t} cannot be a nested ${r} block.`);const a=Vt(r,pe(e.content,t),t,n),s=e.temp_id??e.tempId,c=typeof s=="string"&&s.trim()?s:ke(r);return{block_type:r,content:a,temp_id:c}}function Zn(e,t){const n=[];if("append_block"in e&&n.push(Fe(e.append_block,"Nested block to append",t)),"append_blocks"in e){const o=e.append_blocks;if(!Array.isArray(o))throw new Error("append_blocks must be an array of nested block objects.");o.forEach((r,a)=>{n.push(Fe(r,`Nested block to append ${a}`,t))})}return n}function eo(e,t){if("append_block"in e||"append_blocks"in e||"background"in e||"column_blocks"in e||"column_gap"in e||"container_type"in e||"padding"in e||"responsive_columns"in e||"vertical_alignment"in e)return null;const n=Qn(e);if(!n)return null;const o=pe(e,`Nested ${n} block`);return M(n,o,`Nested ${n} block`,t),{block_type:n,content:o,temp_id:ke(n)}}function to(e,t){const n=e.append_column_index??e.column_index;if(n===void 0)return 0;if(typeof n!="number"||!Number.isInteger(n)||n<0)throw new Error("append_column_index must be a non-negative integer.");if(t>0&&n>=t)throw new Error(`append_column_index ${n} is outside the existing ${t} column(s).`);return n}function no(e,t,n,o){if(!Dt(e))return Ue(t,n);const r={...n},a=Zn(r,o),s=eo(r,o);s&&a.push(s),delete r.append_block,delete r.append_blocks,delete r.append_column_index,delete r.column_index;const c=Ue(t,r);if(a.length>0){const u=Array.isArray(t.column_blocks)?D(t.column_blocks):[],d=to(n,u.length),l=u.length>0?u:[[]];for(;l.length<=d;)l.push([]);l[d]=[...l[d]||[],...a],c.column_blocks=l}return c}function oo(e,t){return{blockType:e.block_type,content:t?e.content:void 0,id:e.id,languageId:e.language_id,order:e.order,pageId:e.page_id,postId:e.post_id}}function K(e){return typeof e=="string"?e.trim().toLowerCase():""}function wt(e){return typeof e=="string"?e.trim().toLowerCase():""}function Gt(e){return e.reduce((t,n)=>t+1+(n.children?.length||0),0)}function _e(e){return typeof e=="string"?e.trim().toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,""):""}async function W(e,t){const n=t.trim(),o=_e(n),r=bn[o],{data:a,error:s}=await e.from("languages").select("id, code, name, is_active");if(s)throw new Error(`Failed to load language "${t}": ${_(s)}`);const u=(Array.isArray(a)?a:[]).filter(l=>l.is_active!==!1),d=u.find(l=>{const m=_e(l.code),h=_e(l.name);return m===o||m===r||h===o});if(!d?.id||!d?.code){const l=u.map(m=>m.code).filter(Boolean).join(", ");throw new Error(`Language "${t}" was not found.${l?` Available languages: ${l}.`:""}`)}return{code:String(d.code),id:Number(d.id)}}async function Se(e,t){if(t)return W(e,t);const{data:n,error:o}=await e.from("languages").select("id, code, name, is_active, is_default");if(o)throw new Error(`Failed to load active languages: ${_(o)}`);const r=(Array.isArray(n)?n:[]).filter(s=>s.is_active!==!1),a=r.find(s=>s.is_default)||r.find(s=>_e(s.code)==="en")||r[0];if(!a?.id||!a?.code)throw new Error("No active CMS language is available for Cortex AI content creation.");return{code:String(a.code),id:Number(a.id)}}async function It(e){try{const{data:t,error:n}=await e.from("currencies").select("code, is_default, is_active").eq("is_active",!0);if(n)return"USD";const o=Array.isArray(t)?t:[],r=o.find(a=>a.is_default)||o[0];return Ye(r?.code||"USD")}catch{return"USD"}}async function ro(e){const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products";let n="id",o=e.entityId;if(o===void 0&&e.slug&&(n="slug",o=e.slug),o===void 0&&e.title&&(n="title",o=e.title),o===void 0)throw new Error(`A ${e.contentType} target requires an id, slug, title, or current edit context.`);const{data:r,error:a}=await e.supabase.from(t).select("*").eq(n,o);if(a)throw new Error(`Failed to resolve ${e.contentType}: ${_(a)}`);const s=Array.isArray(r)?r:r?[r]:[];if(s.length!==1)throw new Error(s.length===0?`No ${e.contentType} matched ${n} "${String(o)}".`:`Multiple ${e.contentType}s matched ${n} "${String(o)}"; use an exact id.`);return s[0]}async function me(e,t){const n=Me.safeParse(t?.pageContext).success?t?.pageContext:null,o=e.contentType||n?.contentType;if(!o)throw new Error("Target contentType is required when no current CMS edit context exists.");const r=e.entityId!==void 0||!!e.slug||!!e.title,a=e.entityId??(r?void 0:n?.entityId),s=e.slug??(r?void 0:n?.slug??void 0),c=e.title??(r?void 0:n?.title??void 0),u=await ro({contentType:o,entityId:a,slug:a===void 0&&s||void 0,supabase:z(t),title:a===void 0&&!s&&c||void 0});return{contentType:o,item:u}}async function we(e){const t=await ao({item:e.item,languageId:e.languageId,menuKey:e.menuKey,supabase:e.supabase}),n={label:e.item.label,language_id:e.languageId,menu_key:e.menuKey,order:e.order,page_id:t?.pageId??null,parent_id:e.parentId??null,...t?.navigationTranslationGroupId?{translation_group_id:t.navigationTranslationGroupId}:{},url:e.item.url},{data:o,error:r}=await e.supabase.from("navigation_items").insert(n).select("id").single();if(r)throw new Error(`Failed to insert ${e.menuKey} navigation item: ${_(r)}`);return Number(o.id)}function io(e){const t=e.trim();if(!t.startsWith("/")||t.startsWith("//"))return null;const n=t.split("?")[0]?.split("#")[0]||"",o=n==="/"?"home":n.replace(/^\/+|\/+$/g,"");return o&&!o.includes("/")?o:null}async function ao(e){const t=io(e.item.url);if(!t)return null;const{data:n,error:o}=await e.supabase.from("pages").select("id, slug, translation_group_id, language_id").eq("slug",t).eq("language_id",e.languageId);if(o)throw new Error(`Failed to resolve linked page for navigation item: ${_(o)}`);const r=Array.isArray(n)?n[0]:n;if(!r?.id)return null;let a=Je();if(r.translation_group_id){const{data:s,error:c}=await e.supabase.from("pages").select("id").eq("translation_group_id",r.translation_group_id);if(c)throw new Error(`Failed to inspect linked page translations for navigation item: ${_(c)}`);const u=new Set((Array.isArray(s)?s:[]).map(h=>String(h.id)).filter(Boolean)),{data:d,error:l}=await e.supabase.from("navigation_items").select("id, page_id, translation_group_id, menu_key").eq("menu_key",e.menuKey);if(l)throw new Error(`Failed to inspect related navigation translations: ${_(l)}`);const m=(Array.isArray(d)?d:[]).find(h=>h.translation_group_id&&u.has(String(h.page_id)));m?.translation_group_id&&(a=m.translation_group_id)}return{navigationTranslationGroupId:a,pageId:Number(r.id)}}async function Kt(e){const t=await W(e.supabase,e.languageCode),{data:n,error:o}=await e.supabase.from("navigation_items").select("id, parent_id").eq("menu_key",e.menuKey).eq("language_id",t.id);if(o)throw new Error(`Failed to inspect existing ${e.menuKey} navigation items: ${_(o)}`);const r=Array.isArray(n)?n:[],a=r.filter(d=>d.parent_id==null).length,s=Gt(e.items);Ht({existingItemCount:r.length,existingTopLevelCount:a,languageCode:t.code,menuKey:e.menuKey,replacementItemCount:s});const{error:c}=await e.supabase.from("navigation_items").delete().eq("menu_key",e.menuKey).eq("language_id",t.id);if(c)throw new Error(`Failed to clear ${e.menuKey} navigation items: ${_(c)}`);let u=0;for(const[d,l]of e.items.entries()){const m=await we({item:l,languageId:t.id,menuKey:e.menuKey,order:d,supabase:e.supabase});u++;for(const[h,p]of(l.children??[]).entries())await we({item:p,languageId:t.id,menuKey:e.menuKey,order:h,parentId:m,supabase:e.supabase}),u++}return{insertedCount:u,languageCode:t.code,menuKey:e.menuKey,skippedCount:0,updatedCount:0}}function Ht(e){if(!(e.existingItemCount===0||e.replacementItemCount>=e.existingItemCount))throw new Error(`Refusing destructive ${e.menuKey} navigation replacement for ${e.languageCode}: existing menu has ${e.existingItemCount} items (${e.existingTopLevelCount} top-level), but the replacement only contains ${e.replacementItemCount}. Use mode "update" for renaming or changing a single link, or provide the full menu.`)}async function so(e){const t=await W(e.supabase,e.languageCode),{data:n,error:o}=await e.supabase.from("navigation_items").select("id, parent_id").eq("menu_key",e.menuKey).eq("language_id",t.id);if(o)throw new Error(`Failed to inspect existing ${e.menuKey} navigation items: ${_(o)}`);const r=Array.isArray(n)?n:[];Ht({existingItemCount:r.length,existingTopLevelCount:r.filter(a=>a.parent_id==null).length,languageCode:t.code,menuKey:e.menuKey,replacementItemCount:Gt(e.items)})}async function co(e){if(e.items.length!==1)throw new Error('mode "update" requires exactly one navigation item.');const t=await W(e.supabase,e.languageCode),n=e.items[0],o=K(e.match?.url)||K(n.url),r=wt(e.match?.label),{data:a,error:s}=await e.supabase.from("navigation_items").select("id, label, url, parent_id, order").eq("menu_key",e.menuKey).eq("language_id",t.id);if(s)throw new Error(`Failed to load existing ${e.menuKey} navigation items: ${_(s)}`);const u=(Array.isArray(a)?a:[]).find(l=>{const m=K(l.url),h=wt(l.label);return!!(o&&m===o||r&&h===r)});if(!u?.id)throw new Error(`Could not find a ${e.menuKey} navigation item to update in ${t.code}. Use a matching label or url.`);const{error:d}=await e.supabase.from("navigation_items").update({label:n.label,url:n.url}).eq("id",u.id);if(d)throw new Error(`Failed to update ${e.menuKey} navigation item: ${_(d)}`);return{insertedCount:0,languageCode:t.code,menuKey:e.menuKey,skippedCount:0,updatedCount:1}}async function lo(e){const t=await W(e.supabase,e.languageCode),{data:n,error:o}=await e.supabase.from("navigation_items").select("id, url, parent_id, order").eq("menu_key",e.menuKey).eq("language_id",t.id);if(o)throw new Error(`Failed to load existing ${e.menuKey} navigation items: ${_(o)}`);let r=0,a=0;const s=Array.isArray(n)?n:[],c=new Set(s.map(l=>K(l.url)).filter(Boolean)),u=s.filter(l=>l.parent_id==null).map(l=>Number(l.order)).filter(Number.isFinite);let d=u.length>0?Math.max(...u)+1:s.length;for(const l of e.items){const m=K(l.url);if(m&&c.has(m)){a++;continue}const h=await we({item:l,languageId:t.id,menuKey:e.menuKey,order:d,supabase:e.supabase});r++,d++,m&&c.add(m);let p=0;for(const g of l.children??[]){const f=K(g.url);if(f&&c.has(f)){a++;continue}await we({item:g,languageId:t.id,menuKey:e.menuKey,order:p,parentId:h,supabase:e.supabase}),r++,p++,f&&c.add(f)}}return{insertedCount:r,languageCode:t.code,menuKey:e.menuKey,skippedCount:a,updatedCount:0}}function S(e){return typeof e=="string"&&e.trim()?e.trim():""}function uo(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function po(e){const t=S(e.field_type??e.fieldType??e.type??e.input_type).toLowerCase().replace(/\s+/g,"_"),n=S(e.label??e.name??e.placeholder).toLowerCase();return["email","textarea","select","radio","checkbox","text"].includes(t)?t:n.includes("email")?"email":n.includes("message")||n.includes("comment")||n.includes("details")?"textarea":"text"}function mo(e){return(Array.isArray(e)&&e.length>0?e:[{field_type:"text",is_required:!0,label:"Name",placeholder:"Your name"},{field_type:"email",is_required:!0,label:"Email",placeholder:"you@example.com"},{field_type:"textarea",is_required:!0,label:"Message",placeholder:"How can we help?"}]).map((n,o)=>{const r=E(n)?n:{},a=S(r.label??r.name)||(o===0?"Name":o===1?"Email":"Message"),s=po({...r,label:a}),c=r.is_required??r.isRequired??r.required;return{field_type:s,is_required:typeof c=="boolean"?c:!0,label:a,options:Array.isArray(r.options)?r.options:void 0,placeholder:S(r.placeholder)||void 0,temp_id:S(r.temp_id??r.tempId??r.id)||`field-${o+1}`}})}const go=new Set(["none","sm","md","lg","xl"]),Tt=new Set(["none","sm","md","lg","xl"]),fo=new Set(["full-width","container","container-sm","container-lg","container-xl"]),ho=new Set(["start","center","end","stretch"]),yo=new Set(["none","theme","solid","gradient","image"]),_o=new Set(["primary","secondary","muted","accent","destructive"]),bo=new Set(["center","top","bottom","left","right"]);function ko(e){return typeof e=="string"&&/^https?:\/\//i.test(e.trim())}function B(e,t,n){return typeof e=="string"&&t.has(e)?e:n}function wo(e){return Number.isFinite(e)?Math.min(4,Math.max(1,Math.round(e))):1}function Io(e){const t=[{color:"#1e3a8a",position:0},{color:"#3b82f6",position:100}];if(!E(e))return{direction:"to bottom right",stops:t,type:"linear"};const n=e.type==="radial"?"radial":"linear",o=Array.isArray(e.stops)&&e.stops.length>=2?e.stops:t;return{direction:typeof e.direction=="string"&&e.direction.trim()?e.direction:n==="radial"?"circle at center":"to bottom right",stops:o,type:n}}function To(e){if(!E(e))return{type:"none"};const t=B(e.type,yo,"none"),n=typeof e.min_height=="string"&&e.min_height.trim()?{min_height:e.min_height}:{};if(t==="theme")return{theme:B(e.theme,_o,"muted"),type:t,...n};if(t==="solid")return typeof e.solid_color=="string"&&e.solid_color.trim()?{solid_color:e.solid_color,type:t,...n}:{type:"none"};if(t==="gradient")return{gradient:Io(e.gradient),type:t,...n};if(t==="image"){const o=E(e.image)?e.image:null,r=o&&ko(o.external_url)?o.external_url.trim():null,a=!!(o&&typeof o.media_id=="string"&&o.media_id.trim()&&typeof o.object_key=="string"&&o.object_key.trim());return o&&(r||a)?{image:{...o,...r?{external_url:r}:{},position:B(o.position,bo,"center"),size:o.size==="contain"?"contain":"cover"},type:t,...n}:{type:"none"}}return{type:"none",...n}}function xo(e,t,n){const o=e.is_hero===!0;let r=Array.isArray(e.column_blocks)?e.column_blocks:[];r.length>0&&r.every(f=>E(f)&&!Array.isArray(f))&&(r=[r]);const a=r.map((f,k)=>(Array.isArray(f)?f:[]).map((w,b)=>Fe(w,`${t} column ${k} block ${b}`,n))),s=a.length>0?a:[[]],c=wo(s.length),u=E(e.responsive_columns)?e.responsive_columns:{},d=Number(u.tablet),l=Number(u.mobile),m=Number.isFinite(d)?Math.min(3,Math.max(1,Math.min(c,d))):Math.min(3,c),h=Number.isFinite(l)?Math.min(2,Math.max(1,l)):1,p=E(e.padding)?e.padding:{},g={...e,background:To(e.background),column_blocks:s,column_gap:B(e.column_gap,go,"lg"),container_type:B(e.container_type,fo,"container"),padding:{bottom:B(p.bottom,Tt,"xl"),top:B(p.top,Tt,"xl")},responsive_columns:{desktop:c,mobile:h,tablet:m},vertical_alignment:B(e.vertical_alignment,ho,o?"center":"start")};return g.slider===!0&&!(Array.isArray(g.slides)&&g.slides.length>0)&&(g.slider=!1),g}function Vt(e,t,n,o){if(e==="section"){const a=xo(t,n,o);return M(e,a,n,o),a}const r=D(t);if(e==="heading"&&(r.text_content=S(r.text_content)||S(r.text)||S(r.title)||S(r.heading)||"Untitled",r.level=typeof r.level=="number"?r.level:1),e==="text"){const a=S(r.html_content)||S(r.html)||S(r.content)||S(r.text);a&&(r.html_content=/<\/?[a-z][\s\S]*>/i.test(a)?a:`<p>${uo(a)}</p>`)}return e==="button"&&(r.text=S(r.text)||S(r.label)||S(r.title)||"Learn More",r.url=S(r.url)||S(r.href)||S(r.link)||"#"),e==="form"&&(r.fields=mo(r.fields),r.submit_button_text=S(r.submit_button_text??r.submitButtonText??r.button_text)||"Send Message",r.success_message=S(r.success_message??r.successMessage)||"Thanks for reaching out. We will reply as soon as possible."),M(e,r,n,o),r}function Ie(e,t,n){const o=Vt(e.blockType,pe(e.content,`Block ${t}`),`Block ${t}`,n);return{block_type:e.blockType,content:o,order:e.order??t}}function zo(e,t="Contact Us",n){return[Ie({blockType:"section",content:{is_hero:!0,background:{type:"none"},column_blocks:[[{block_type:"heading",content:{level:1,textAlign:"center",text_content:t},temp_id:ke("heading")},{block_type:"text",content:{html_content:"<p>Have a question, project, or support request? Send us a note and we will get back to you soon.</p>"},temp_id:ke("text")}]],column_gap:"lg",container_type:"container",padding:{bottom:"xl",top:"xl"},responsive_columns:{desktop:1,mobile:1,tablet:1},vertical_alignment:"center"}},0,n),Ie({blockType:"form",content:{fields:[{field_type:"text",is_required:!0,label:"Name",placeholder:"Your name",temp_id:"field-name"},{field_type:"email",is_required:!0,label:"Email",placeholder:"you@example.com",temp_id:"field-email"},{field_type:"textarea",is_required:!0,label:"Message",placeholder:"How can we help?",temp_id:"field-message"}],recipient_email:e,submit_button_text:"Send Message",success_message:"Thanks for reaching out. We will reply as soon as possible."}},1,n)]}function ve(e,t,n,o){return(!e||e.length===0)&&t?zo(t,n,o):(e||[]).map((r,a)=>Ie(r,a,o))}async function Xe(e){const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products",{data:n,error:o}=await e.supabase.from(t).select("id, title, slug, language_id").eq("slug",e.slug).eq("language_id",e.languageId);if(o)throw new Error(`Failed to check ${e.contentType} slug uniqueness: ${_(o)}`);const r=Array.isArray(n)?n:[];return r.length>0?{duplicate:!0,existingItem:r[0],mutationExecuted:!1,success:!1,message:`A ${e.contentType} with slug "${e.slug}" already exists for this language.`}:null}async function Qe(e){if(!e.suppliedTranslationGroupId)return{translationGroupId:void 0};const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products",{data:n,error:o}=await e.supabase.from(t).select("id, title, slug, language_id, translation_group_id").eq("translation_group_id",e.suppliedTranslationGroupId);if(o)throw new Error(`Failed to inspect ${e.contentType} translation group: ${_(o)}`);const r=Array.isArray(n)?n:[];if(r.length===0)return{result:{message:`The ${e.contentType} translation group "${e.suppliedTranslationGroupId}" was not found.`,mutationExecuted:!1,success:!1},translationGroupId:e.suppliedTranslationGroupId};const a=r.find(s=>Number(s.language_id)===e.languageId);return a?{result:{duplicateTranslation:!0,existingItem:a,message:`A ${e.contentType} translation already exists for ${e.languageCode} in this translation group.`,mutationExecuted:!1,success:!1},translationGroupId:e.suppliedTranslationGroupId}:{translationGroupId:e.suppliedTranslationGroupId}}async function Ze(e){if(e.blocks.length===0)return[];const t=e.blocks.map((r,a)=>({block_type:r.block_type,content:r.content,language_id:e.languageId,order:r.order??a,page_id:e.contentType==="page"?e.itemId:null,post_id:e.contentType==="post"?e.itemId:null,product_id:e.contentType==="product"?e.itemId:null})),{data:n,error:o}=await e.supabase.from("blocks").insert(t).select("*");if(o)throw new Error(`Failed to insert ${e.contentType} blocks: ${_(o)}`);return ge(e.blocks,e.supabase),Array.isArray(n)?n:[]}async function et(e){const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products";await e.supabase.from(t).delete().eq("id",e.itemId)}function tt(e,t){return e==="page"?`/cms/pages/${t}/edit`:e==="post"?`/cms/posts/${t}/edit`:`/cms/products/${t}/edit`}function xt(e){return e==="page"?"/cms/pages":e==="post"?"/cms/posts":"/cms/products"}async function nt(e,t){const n=Q.parse(e),o=z(t);n.mode==="replace"&&await so({items:n.items,languageCode:n.languageCode,menuKey:"HEADER",supabase:o});const r=A({action:"UPDATE NAVIGATION",context:t,payload:{input:n,tool:"update_navigation_bar"},preview:{itemCount:n.items.length,languageCode:n.languageCode,mode:n.mode,target:"header navigation"},subject:`${n.mode} header`});if(r)return r;const a=n.mode==="update"?await co({items:n.items,languageCode:n.languageCode,match:n.match,menuKey:"HEADER",supabase:o}):n.mode==="append"?await lo({items:n.items,languageCode:n.languageCode,menuKey:"HEADER",supabase:o}):await Kt({items:n.items,languageCode:n.languageCode,menuKey:"HEADER",supabase:o});return Bt(t),{...a,mutationExecuted:!0,mode:n.mode,success:!0}}async function ot(e,t){const n=Z.parse(e);if(!n.links?.length&&!n.copyright)throw new Error("update_footer requires links or copyright.");const o=z(t),r=A({action:"UPDATE FOOTER",context:t,payload:{input:n,tool:"update_footer"},preview:{copyrightUpdated:!!n.copyright,linkCount:n.links?.length||0,languageCode:n.languageCode,target:"footer"},subject:n.languageCode});if(r)return r;let a=null;if(n.links?.length&&(a=await Kt({items:n.links,languageCode:n.languageCode,menuKey:"FOOTER",supabase:o})),n.copyright){const{error:s}=await o.from("site_settings").upsert({key:"footer_copyright",value:n.copyright});if(s)throw new Error(`Failed to update footer copyright: ${_(s)}`)}return Bt(t),{copyrightUpdated:!!n.copyright,footerNavigation:a,mutationExecuted:!0,success:!0}}function Wt(e){return typeof e=="string"?e.toLowerCase():""}function Co(e,t){const n=t.map(Wt).join(" ");return e.reduce((o,r)=>o+(n.includes(r)?1:0),0)}function zt(e,t){return(e.find(n=>t.some(o=>Wt(n).includes(o)))||e.find(n=>n.trim().length>0)||"No excerpt available.").slice(0,500)}async function Jt(e,t){const n=xe.parse(e),o=z(t),r=n.query.toLowerCase().split(/\s+/).map(l=>l.trim()).filter(Boolean),[a,s]=await Promise.all([o.from("posts").select("id, title, slug, excerpt, subtitle, meta_description, status, updated_at").eq("status","published").limit(100),o.from("pages").select("id, title, slug, meta_description, status, updated_at").eq("status","published").limit(100)]);if(a.error)throw new Error(`Failed to search documentation posts: ${_(a.error)}`);if(s.error)throw new Error(`Failed to search documentation pages: ${_(s.error)}`);const c=(a.data??[]).map(l=>({excerpt:zt([l.excerpt,l.subtitle,l.meta_description,l.slug].filter(Boolean),r),source:"post",title:l.title,url:`/article/${l.slug}`})),u=(s.data??[]).map(l=>({excerpt:zt([l.meta_description,l.slug].filter(Boolean),r),source:"page",title:l.title,url:l.slug==="home"?"/":`/${l.slug}`})),d=[...c,...u].map(l=>({...l,score:Co(r,[l.title,l.excerpt,l.url])})).filter(l=>l.score>0).sort((l,m)=>m.score-l.score).slice(0,n.limit).map(l=>({excerpt:l.excerpt,source:l.source,title:l.title,url:l.url}));return{query:n.query,results:d,success:!0}}async function Yt(e,t,n=_n){const o=xe.safeParse(e),r=o.success?o.data.query:"";return Ln(Jt(e,t),n,()=>({message:"Documentation search took too long to respond. Please try again or ask a more specific question.",query:r,results:[],success:!1,timedOut:!0}))}const So=["pending","trial","paid","shipped","cancelled","refunded","failed"],vo={awaiting:"pending",canceled:"cancelled",cancelled:"cancelled",complete:"paid",completed:"paid",failed:"failed",paid:"paid",payment_pending:"pending",pending:"pending",refund:"refunded",refunded:"refunded",refunds:"refunded",shipped:"shipped",trial:"trial",trials:"trial"};function Eo(e){return String(e??"unknown").trim().toLowerCase()||"unknown"}function Ct(e){const t=Object.fromEntries(So.map(n=>[n,0]));for(const n of e){const o=Eo(n.status);t[o]=(t[o]??0)+1}return t}function $o(e){const n=e.toLowerCase().replace(/[^a-z0-9_]+/g," ").split(/\s+/).filter(Boolean);for(const o of n){const r=vo[o];if(r)return r}return null}function X(e){const t=Number(e);return Number.isFinite(t)?t:0}async function Xt(e,t){const n=Re.parse(e),o=z(t),r=new Date;let a=null,s=null;switch(n.timeRange){case"today":a=new Date(r.getFullYear(),r.getMonth(),r.getDate());break;case"this_month":a=new Date(r.getFullYear(),r.getMonth(),1);break;case"last_7_days":a=new Date(r.getTime()-10080*60*1e3);break;case"last_30_days":a=new Date(r.getTime()-720*60*60*1e3);break;case"last_month":a=new Date(r.getFullYear(),r.getMonth()-1,1),s=new Date(r.getFullYear(),r.getMonth(),0,23,59,59,999);break;case"last_90_days":a=new Date(r.getTime()-2160*60*60*1e3);break;case"all_time":a=null;break}const c=n.currency?.toUpperCase(),u=$o(n.query),d=o.from("orders").select("id, status, total, currency, created_at, paid_at");c&&d.eq("currency",c),a&&d.gte("created_at",a.toISOString()),s&&d.lte("created_at",s.toISOString());const m=n.reportType==="products"||n.reportType==="revenue"||n.reportType==="general"?o.from("order_items").select(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const x=require("ai"),_n=require("./ai-global-agent-db-tools.cjs.js"),bn=require("./ai-global-agent-custom-block-tools.cjs.js"),Ut=require("./editor-document-from-html.cjs.js");require("./zod-config.cjs.js");const i=require("zod"),H=["text","heading","image","button","posts_grid","video_embed","section","form","testimonial","product_grid","featured_product","cart","checkout","product_details"];async function W(e,t,n){if(e?.recordRevision)try{return await e.recordRevision({contentType:t,entityId:n,phase:"capture"})}catch(o){console.error("Cortex AI: failed to capture revision baseline",o);return}}async function G(e,t,n,o){if(!(!e?.recordRevision||o===void 0))try{await e.recordRevision({baseline:o,contentType:t,entityId:n,phase:"commit"})}catch(r){console.error("Cortex AI: failed to record revision",r)}}const kn=1e4,wn={arabic:"ar",chinese:"zh",dutch:"nl",english:"en",french:"fr",francaise:"fr",francais:"fr",german:"de",italian:"it",japanese:"ja",korean:"ko",portuguese:"pt",russian:"ru",spanish:"es"},Ft=i.z.string().trim().min(1).max(2048).refine(e=>e.startsWith("/")||e.startsWith("#")||e.startsWith("http://")||e.startsWith("https://")||e.startsWith("mailto:")||e.startsWith("tel:"),"URL must be a relative path, hash link, http(s) URL, mailto URL, or tel URL."),bt=i.z.strictObject({label:i.z.string().trim().min(1).max(120),target:i.z.enum(["_self","_blank"]).optional(),url:Ft}),Me=bt.extend({children:i.z.array(bt).max(20).optional()}),In=i.z.strictObject({label:i.z.string().trim().min(1).max(120).optional(),url:Ft.optional()}).refine(e=>!!(e.label||e.url),{message:"Navigation item match requires label or url."}),te=i.z.strictObject({items:i.z.array(Me).min(1).max(30),languageCode:i.z.string().trim().min(2).max(80).default("en").describe('Locale code or language name, for example "en", "fr", "English", or "French".'),match:In.optional().describe('For mode "update", identifies the existing navigation item to update.'),mode:i.z.enum(["append","replace","update"]).default("append")}),ne=i.z.strictObject({copyright:i.z.record(i.z.string().trim().min(2).max(12),i.z.string().trim().min(1).max(500)).optional(),languageCode:i.z.string().trim().min(2).max(80).default("en").describe('Locale code or language name, for example "en", "fr", "English", or "French".'),links:i.z.array(Me).min(1).max(30).optional()}),Se=i.z.strictObject({limit:i.z.number().int().min(1).max(8).default(4),query:i.z.string().trim().min(2).max(300)}),De=i.z.object({currency:i.z.string().trim().min(3).max(3).optional().describe("Optional currency code for currency-specific monetary reports (e.g., USD, CAD). Do not set this for plain order-status counts unless the user asks for a currency."),query:i.z.string().describe("The analytical question about orders, products, or revenue."),reportType:i.z.enum(["revenue","orders","products","general"]).optional().default("general").describe("The focus area of the statistical report."),timeRange:i.z.enum(["today","this_month","last_7_days","last_30_days","last_month","last_90_days","all_time"]).optional().default("all_time").describe("The time period for the report. Use all_time for current order-status counts unless the user names a specific period.")}),Ge=i.z.strictObject({contentType:i.z.enum(["page","post","product"]),currentEditor:i.z.strictObject({blockId:i.z.union([i.z.number().int().positive(),i.z.string().trim().min(1).max(120)]).nullable().optional(),blockType:i.z.string().trim().min(1).max(80).nullable().optional(),field:i.z.string().trim().min(1).max(120).nullable().optional()}).optional(),entityId:i.z.union([i.z.number().int().positive(),i.z.string().trim().min(1).max(120)]),languageId:i.z.number().int().positive().nullable().optional(),slug:i.z.string().trim().min(1).max(300).nullable().optional(),title:i.z.string().trim().min(1).max(300).nullable().optional(),translationGroupId:i.z.string().trim().min(1).max(120).nullable().optional()}),Ke=i.z.strictObject({includeBlockContent:i.z.boolean().default(!1),includeBlocks:i.z.boolean().default(!0)}),oe=i.z.strictObject({fields:i.z.strictObject({description_json:i.z.unknown().optional(),excerpt:i.z.string().max(2e3).nullable().optional(),feature_image_id:i.z.string().trim().min(1).max(2048).nullable().optional(),label:i.z.string().max(120).nullable().optional(),meta_description:i.z.string().max(500).nullable().optional(),meta_title:i.z.string().max(160).nullable().optional(),published_at:i.z.string().max(80).nullable().optional(),short_description:i.z.string().max(2e3).nullable().optional(),slug:i.z.string().trim().min(1).max(300).optional(),status:i.z.enum(["draft","published","active","archived"]).optional(),subtitle:i.z.string().max(300).nullable().optional(),title:i.z.string().trim().min(1).max(300).optional()}).partial()}),re=i.z.strictObject({blockId:i.z.number().int().positive(),blockType:i.z.enum(H).optional(),content:i.z.record(i.z.string(),i.z.unknown())}),ie=i.z.strictObject({blockIndex:i.z.number().int().min(0),blockType:i.z.enum(H).optional(),columnIndex:i.z.number().int().min(0),content:i.z.record(i.z.string(),i.z.unknown()),parentBlockId:i.z.number().int().positive()}),Tn=i.z.enum(["page","post","product"]),J=i.z.strictObject({contentType:Tn.optional(),entityId:i.z.union([i.z.number().int().positive(),i.z.string().trim().min(1).max(120)]).optional(),slug:i.z.string().trim().min(1).max(300).optional(),title:i.z.string().trim().min(1).max(300).optional()}),ae=i.z.strictObject({blockType:i.z.enum(H),content:i.z.record(i.z.string(),i.z.unknown()),order:i.z.number().int().min(0).optional()}),se=J.extend({images:i.z.array(i.z.string().trim().min(1).max(2048)).min(1).max(12).describe("External https image URLs (imported into the media library automatically) and/or existing media library ids. The first entry is the feature image (pages/posts) or the main product image (products).")}),ce=J.extend({anchorBlockId:i.z.number().int().positive().optional(),anchorBlockType:i.z.enum(H).optional(),block:ae,position:i.z.enum(["before","after","start","end"]).default("end")}),le=i.z.strictObject({blocks:i.z.array(ae).max(20).optional(),contactEmail:i.z.string().email().optional(),feature_image_id:i.z.string().trim().min(1).max(2048).nullable().optional(),languageCode:i.z.string().trim().min(2).max(80).optional(),meta_description:i.z.string().max(500).nullable().optional(),meta_title:i.z.string().max(160).nullable().optional(),slug:i.z.string().trim().min(1).max(300).optional(),status:i.z.enum(["draft","published","archived"]).default("draft"),title:i.z.string().trim().min(1).max(300),translationGroupId:i.z.string().trim().min(1).max(120).optional()}),ue=i.z.strictObject({blocks:i.z.array(ae).max(20).optional(),excerpt:i.z.string().max(2e3).nullable().optional(),feature_image_id:i.z.string().trim().min(1).max(2048).nullable().optional(),label:i.z.string().max(120).nullable().optional(),languageCode:i.z.string().trim().min(2).max(80).optional(),meta_description:i.z.string().max(500).nullable().optional(),meta_title:i.z.string().max(160).nullable().optional(),published_at:i.z.string().max(80).nullable().optional(),slug:i.z.string().trim().min(1).max(300).optional(),status:i.z.enum(["draft","published","archived"]).default("draft"),subtitle:i.z.string().max(300).nullable().optional(),title:i.z.string().trim().min(1).max(300),translationGroupId:i.z.string().trim().min(1).max(120).optional()}),de=i.z.strictObject({blocks:i.z.array(ae).max(20).optional().describe("Content blocks for the product description area, same block vocabulary as create_cms_page. Rendered on the public product page in place of the plain description."),description_html:i.z.string().max(6e4).optional().describe("The product body as an HTML fragment (headings, paragraphs, lists, bold/italic/links). Converted to the editor document automatically. Prefer this over description_json."),description_json:i.z.unknown().optional(),freemius_plan_id:i.z.string().optional(),freemius_product_id:i.z.string().optional(),images:i.z.array(i.z.string().trim().min(1).max(2048)).max(12).optional().describe("Product images, in order: the first becomes the main product image and the rest the gallery. Each entry is either an external https image URL (imported into the media library automatically) or an existing media library id."),is_taxable:i.z.boolean().default(!0),languageCode:i.z.string().trim().min(2).max(80).optional(),meta_description:i.z.string().max(500).nullable().optional(),meta_title:i.z.string().max(160).nullable().optional(),payment_provider:i.z.enum(["stripe","freemius"]).default("stripe"),price:i.z.number().min(0).default(0),prices:i.z.record(i.z.string(),i.z.number().min(0)).optional(),product_type:i.z.enum(["physical","digital"]).default("physical"),sale_price:i.z.number().min(0).nullable().optional(),sale_prices:i.z.record(i.z.string(),i.z.number().min(0).nullable()).optional(),short_description:i.z.string().max(2e3).nullable().optional(),sku:i.z.string().trim().min(1).max(120).optional(),slug:i.z.string().trim().min(1).max(300).optional(),status:i.z.enum(["draft","active","archived"]).default("draft"),stock:i.z.number().int().min(0).default(0),title:i.z.string().trim().min(1).max(300),trial_period_days:i.z.number().int().min(0).default(0),trial_requires_payment_method:i.z.boolean().default(!1),translationGroupId:i.z.string().trim().min(1).max(120).optional(),upc:i.z.string().max(120).nullable().optional()}),pe=J.extend({currencyCode:i.z.string().trim().min(3).max(3).optional(),endsAt:i.z.string().max(80).nullable().optional(),field:i.z.string().trim().min(1).max(120),startsAt:i.z.string().max(80).nullable().optional(),value:i.z.unknown()}),He=J,me=J,Ot=i.z.discriminatedUnion("tool",[i.z.strictObject({input:le,tool:i.z.literal("create_cms_page")}),i.z.strictObject({input:ue,tool:i.z.literal("create_cms_post")}),i.z.strictObject({input:de,tool:i.z.literal("create_cms_product")}),i.z.strictObject({input:me,tool:i.z.literal("delete_cms_item")}),i.z.strictObject({input:pe,tool:i.z.literal("update_cms_item_field")}),i.z.strictObject({input:re,tool:i.z.literal("update_content_block")}),i.z.strictObject({input:ce,tool:i.z.literal("insert_content_block")}),i.z.strictObject({input:oe,tool:i.z.literal("update_current_cms_fields")}),i.z.strictObject({input:ne,tool:i.z.literal("update_footer")}),i.z.strictObject({input:te,tool:i.z.literal("update_navigation_bar")}),i.z.strictObject({input:ie,tool:i.z.literal("update_section_column_block")}),i.z.strictObject({input:se,tool:i.z.literal("set_content_images")})]),Cn=i.z.union([le.extend({tool:i.z.literal("create_cms_page")}).transform(({tool:e,...t})=>({input:t,tool:e})),ue.extend({tool:i.z.literal("create_cms_post")}).transform(({tool:e,...t})=>({input:t,tool:e})),de.extend({tool:i.z.literal("create_cms_product")}).transform(({tool:e,...t})=>({input:t,tool:e})),me.extend({tool:i.z.literal("delete_cms_item")}).transform(({tool:e,...t})=>({input:t,tool:e})),pe.extend({tool:i.z.literal("update_cms_item_field")}).transform(({tool:e,...t})=>({input:t,tool:e})),re.extend({tool:i.z.literal("update_content_block")}).transform(({tool:e,...t})=>({input:t,tool:e})),ce.extend({tool:i.z.literal("insert_content_block")}).transform(({tool:e,...t})=>({input:t,tool:e})),oe.extend({tool:i.z.literal("update_current_cms_fields")}).transform(({tool:e,...t})=>({input:t,tool:e})),ne.extend({tool:i.z.literal("update_footer")}).transform(({tool:e,...t})=>({input:t,tool:e})),te.extend({tool:i.z.literal("update_navigation_bar")}).transform(({tool:e,...t})=>({input:t,tool:e})),ie.extend({tool:i.z.literal("update_section_column_block")}).transform(({tool:e,...t})=>({input:t,tool:e})),se.extend({tool:i.z.literal("set_content_images")}).transform(({tool:e,...t})=>({input:t,tool:e}))]),zn=i.z.string().transform((e,t)=>{const n=$n(e);return n.success?n.action:(t.addIssue({code:"custom",message:n.message}),i.z.NEVER)}),xn=i.z.union([Ot,Cn,zn]),Ve=i.z.strictObject({actions:i.z.array(xn).min(1).max(8),summary:i.z.string().trim().min(1).max(500).optional()});function Sn(e){const t=[];let n="",o=0,r=null,a=!1;for(const s of e){if(r){n+=s,a?a=!1:s==="\\"?a=!0:s===r&&(r=null);continue}if(s==='"'||s==="'"){r=s,n+=s;continue}if(s==="["||s==="{"||s==="("){o++,n+=s;continue}if(s==="]"||s==="}"||s===")"){o=Math.max(0,o-1),n+=s;continue}if(s===","&&o===0){n.trim()&&t.push(n.trim()),n="";continue}n+=s}return n.trim()&&t.push(n.trim()),t}function kt(e){let t="";for(let n=0;n<e.length;n++){const o=e[n];if(o!=="'"){t+=o;continue}let r="",a=!1;for(n++;n<e.length;n++){const s=e[n];if(a){r+=s,a=!1;continue}if(s==="\\"){a=!0;continue}if(s==="'")break;r+=s}t+=JSON.stringify(r)}return t.replace(/\bTrue\b/g,"true").replace(/\bFalse\b/g,"false").replace(/\bNone\b/g,"null")}function vn(e){const t=e.trim();return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')||t.startsWith("[")||t.startsWith("{")?JSON.parse(kt(t)):/^-?\d+(?:\.\d+)?$/.test(t)?Number(t):t==="true"||t==="True"?!0:t==="false"||t==="False"?!1:t==="null"||t==="None"?null:t}function En(e){const t={};for(const n of Sn(e)){const o=n.indexOf("=");if(o<=0)throw new Error(`Expected key=value argument, received "${n}".`);const r=n.slice(0,o).trim();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw new Error(`Invalid argument name "${r}".`);t[r]=vn(n.slice(o+1))}return t}function $n(e){const n=e.trim().match(/^([a-z_]+)\(([\s\S]*)\)$/);if(!n)return{message:'Action plan actions must be JSON objects like { "tool": "create_cms_page", "input": { ... } }, not freeform text.',success:!1};const o=n[1];let r;try{r=En(n[2])}catch(c){return{message:c instanceof Error?c.message:"Could not parse action-plan command arguments.",success:!1}}const a={input:r,tool:o},s=Ot.safeParse(a);return s.success?{action:s.data,success:!0}:{message:`Invalid action-plan command "${o}": ${s.error.issues.map(c=>c.message).join("; ")}`,success:!1}}function An(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/\s+/g," ").trim()}function _e(e,t){return t.some(n=>e.includes(n))}function Pn(e){const t=An(e),n=_e(t,["add ","insert ","put ","create "]),o=_e(t,["title","heading","description","intro","copy","paragraph"]),r=t.includes("form")&&_e(t,["above","before"]),a=t.includes("contact page")||t.includes("contact pages")||t.includes("contact us")||t.includes("contactez-nous"),s=t.includes("english")&&_e(t,["french","francais","francaise"]);return!n||!o||!r||!a||!s?null:{actions:[{input:{anchorBlockType:"form",block:{blockType:"text",content:{html_content:"<h2>Let us help you move faster</h2><p>Have a question, project idea, or need help choosing the right next step? Send us a message and the NextBlock team will get back to you soon.</p>"}},contentType:"page",position:"before",slug:"contact-us"},tool:"insert_content_block"},{input:{anchorBlockType:"form",block:{blockType:"text",content:{html_content:"<h2>Parlons de votre projet</h2><p>Vous avez une question, une idee de projet ou besoin d'aide pour avancer? Envoyez-nous un message et l'equipe NextBlock vous repondra rapidement.</p>"}},contentType:"page",position:"before",slug:"contactez-nous"},tool:"insert_content_block"}],summary:"Add visible title and description copy above the forms on the English and French Contact pages."}}const Nn=i.z.enum(H),wt=i.z.object({direction:i.z.string().optional(),stops:i.z.array(i.z.object({color:i.z.string(),position:i.z.number()})),type:i.z.enum(["linear","radial"])}),Un=i.z.object({gradient:wt.optional(),image:i.z.object({alt_text:i.z.string().optional(),blur_data_url:i.z.string().optional(),external_url:i.z.string().optional(),height:i.z.number().optional(),media_id:i.z.string().optional(),object_key:i.z.string().optional(),overlay:i.z.object({gradient:wt,type:i.z.literal("gradient")}).optional(),position:i.z.enum(["center","top","bottom","left","right"]),quality:i.z.number().nullable().optional(),size:i.z.enum(["cover","contain"]),width:i.z.number().optional()}).optional(),min_height:i.z.string().optional(),solid_color:i.z.string().optional(),theme:i.z.enum(["primary","secondary","muted","accent","destructive"]).optional(),type:i.z.enum(["none","theme","solid","gradient","image"])}),Fn=i.z.object({block_type:Nn,content:i.z.record(i.z.string(),i.z.any()),temp_id:i.z.string().optional()}),On=i.z.object({background:Un,column_blocks:i.z.array(i.z.array(Fn)),column_gap:i.z.enum(["none","sm","md","lg","xl"]),container_type:i.z.enum(["full-width","container","container-sm","container-lg","container-xl"]),padding:i.z.object({bottom:i.z.enum(["none","sm","md","lg","xl"]),top:i.z.enum(["none","sm","md","lg","xl"])}),responsive_columns:i.z.object({desktop:i.z.union([i.z.literal(1),i.z.literal(2),i.z.literal(3),i.z.literal(4)]),mobile:i.z.union([i.z.literal(1),i.z.literal(2)]),tablet:i.z.union([i.z.literal(1),i.z.literal(2),i.z.literal(3)])}),vertical_alignment:i.z.enum(["start","center","end","stretch"]).optional()}),Bn={button:i.z.object({position:i.z.enum(["left","center","right"]).optional(),size:i.z.enum(["default","sm","lg","full"]).optional(),text:i.z.string(),url:i.z.string(),variant:i.z.enum(["default","outline","secondary","ghost","link"]).optional()}),cart:i.z.object({}),checkout:i.z.object({}),featured_product:i.z.object({imagePosition:i.z.enum(["left","right"]).default("left"),productId:i.z.string().min(1),showBackground:i.z.boolean().default(!1)}),form:i.z.object({fields:i.z.array(i.z.object({field_type:i.z.enum(["text","email","textarea","select","radio","checkbox"]),is_required:i.z.boolean(),label:i.z.string(),options:i.z.array(i.z.object({label:i.z.string(),value:i.z.string()})).optional(),placeholder:i.z.string().optional(),temp_id:i.z.string()})),recipient_email:i.z.string().email(),submit_button_text:i.z.string(),success_message:i.z.string()}),heading:i.z.object({level:i.z.union([i.z.literal(1),i.z.literal(2),i.z.literal(3),i.z.literal(4),i.z.literal(5),i.z.literal(6)]),textAlign:i.z.enum(["left","center","right","justify"]).optional(),textColor:i.z.union([i.z.enum(["foreground","primary","secondary","accent","muted","destructive","background"]),i.z.string().regex(/^(#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})|rgba?\([^)]+\)|hsla?\([^)]+\))$/i,"Must be a hex, rgb(a) or hsl(a) colour")]).optional().describe("Prefer a theme token so the heading adapts to dark mode; use a CSS colour only when the brand requires an exact value"),text_content:i.z.string()}),image:i.z.object({alt_text:i.z.string().optional(),caption:i.z.string().optional(),external_url:i.z.string().nullable().optional(),height:i.z.number().nullable().optional(),media_id:i.z.string().nullable().optional(),object_key:i.z.string().nullable().optional(),width:i.z.number().nullable().optional()}),posts_grid:i.z.object({columns:i.z.number().min(1).max(6),postsPerPage:i.z.number().min(1).max(50),showPagination:i.z.boolean(),title:i.z.string().optional()}),product_details:i.z.object({}),product_grid:i.z.object({categoryId:i.z.string().optional(),categoryIds:i.z.array(i.z.string()).max(20).optional(),limit:i.z.number().min(0).max(48).default(6),productIds:i.z.array(i.z.string()).max(24).optional(),showPagination:i.z.boolean().default(!1),title:i.z.string().optional(),type:i.z.enum(["latest","category","manual"]).default("latest")}),section:On,testimonial:i.z.object({author_name:i.z.string().min(1),author_title:i.z.string().optional(),image_url:i.z.string().url().optional().or(i.z.literal("")),quote:i.z.string().min(1)}),text:i.z.object({html_content:i.z.string()}),video_embed:i.z.object({autoplay:i.z.boolean().optional(),controls:i.z.boolean().optional(),title:i.z.string().optional(),url:i.z.string()})};function jn(e){return H.includes(e)}function Ln(e){return typeof e?.validateBlockContent=="function"?e.validateBlockContent:null}function qn(e,t,n){const o=Ln(n);if(o)return o(e,t);const r=Bn[e].safeParse(t);return r.success?{errors:[],isValid:!0,warnings:[]}:{errors:r.error.issues.map(a=>{const s=a.path.join(".");return s?`${s}: ${a.message}`:a.message}),isValid:!1,warnings:[]}}function It(){return i.z.object({content:i.z.array(i.z.any()).optional(),type:i.z.literal("doc")})}function We(){try{const{revalidatePath:e}=require("next/cache");return e}catch{return null}}function z(e){if(!e?.supabase)throw new Error("A Supabase service client is required to execute Cortex AI global tools.");return e.supabase}function Rn(e,t,n){let o;const r=new Promise(a=>{o=setTimeout(()=>a(n()),t)});return Promise.race([e.finally(()=>{o&&clearTimeout(o)}),r])}function Y(e){const t=Ge.safeParse(e?.pageContext);if(!t.success)throw new Error("No current CMS page context is available. Open a page, post, or product edit screen before using this editing tool.");return t.data}function Je(e){const t=typeof e.entityId=="number"?e.entityId:Number.parseInt(e.entityId,10);if(!Number.isInteger(t)||t<=0)throw new Error(`Current ${e.contentType} id must be a positive integer.`);return t}function Bt(e){const t=String(e.entityId||"").trim();if(!t)throw new Error(`Current ${e.contentType} id is missing.`);return t}function q(e){return e.contentType==="product"?Bt(e):Je(e)}const Mn=/^https?:\/\//i,Dn=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function ge(e,t,n){if(typeof e!="string")return null;const o=e.trim();if(!o)return null;if(!Mn.test(o)){if(Dn.test(o))return o;throw new Error(`"${o}" is not a usable image reference — provide an https:// image URL or a media library id.`)}const r=t?.importExternalImage;if(!r)throw new Error("I can only attach an image from a URL when media import is available here. Please pick an image from the media library instead.");const a=await r({altText:n,url:o});if("error"in a)throw new Error(`I could not import the image from that URL: ${a.error}`);return a.id}async function jt(e,t,n){const o=[];for(let r=0;r<e.length;r+=1){const a=await ge(e[r],t,`${n} image ${r+1}`);a&&o.push(a)}return o}async function Gn(e){const t=[...new Set(e.mediaIds)],{error:n}=await e.supabase.from("product_media").delete().eq("product_id",e.productId);if(n)throw new Error(`Could not clear the product's existing images: ${y(n)}`);if(t.length>0){const{error:o}=await e.supabase.from("product_media").insert(t.map((r,a)=>({media_id:r,product_id:e.productId,sort_order:a})));if(o)throw new Error(`Could not save the product images: ${y(o)}`)}return t}async function ve(e){if(!e.productId)return!1;const{data:t,error:n}=await e.supabase.from("product_drafts").select("id, blocks, meta").eq("product_id",e.productId).maybeSingle();if(n||!t)return!1;const o=e.patch({blocks:Array.isArray(t.blocks)?K(t.blocks):[],meta:v(t.meta)?K(t.meta):{}}),r={updated_at:new Date().toISOString()};if(o.blocks&&(r.blocks=o.blocks),o.meta&&(r.meta=o.meta),Object.keys(r).length===1)return!1;const{error:a}=await e.supabase.from("product_drafts").update(r).eq("id",t.id);if(a)throw new Error(`The product was updated, but its open draft could not be kept in sync: ${y(a)}. Publishing that draft would undo this change — publish or discard it in the product editor first.`);return!0}function Lt(e){return typeof e=="string"?e.trim().replace(/^\/+|\/+$/g,""):""}function Kn(e,t){const n=Lt(t??e.slug);return n?e.contentType==="page"?n==="home"?"/":`/${n}`:e.contentType==="post"?`/article/${n}`:`/product/${n}`:null}function Hn(e){const t=String(e.entityId);return e.contentType==="page"?`/cms/pages/${t}/edit`:e.contentType==="post"?`/cms/posts/${t}/edit`:`/cms/products/${t}/edit`}function U(e,t,n){const o=e?.revalidatePath??We();if(!o)return;o(Hn(t));const r=Kn(t,n);r&&o(r),t.contentType==="page"&&r!=="/"&&o("/"),t.contentType==="product"&&o("/cms/products")}function qt(e){const t=e?.revalidatePath??We();t&&(t("/","layout"),t("/cms/navigation"))}function y(e){return e?typeof e=="object"&&"message"in e?String(e.message||"Unknown database error."):String(e):"Unknown database error."}async function Vn(){return Promise.resolve().then(()=>require("./ai-global-agent-ecommerce.cjs.js"))}function Ue(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(t=>Ue(t)).join(",")}]`:`{${Object.keys(e).filter(t=>t!=="temp_id").sort().map(t=>`${JSON.stringify(t)}:${Ue(e[t])}`).join(",")}}`}function Wn(e){let t=2166136261;const n=Ue(e);for(let o=0;o<n.length;o++)t^=n.charCodeAt(o),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function Fe(e){return e.replace(/\s+/g," ").trim().toUpperCase()}function Jn(e,t,n){return`${Fe(`CONFIRM ${e} ${t}`)} #${Wn(n)}`}function Rt(e){return{confirmationPhrase:Jn(e.action,e.subject,e.payload),mutationExecuted:!1,preview:e.preview,requiresConfirmation:!0,success:!0}}function F(e,t){const n=e[t];return typeof n=="string"&&n.trim()?n.trim():null}function M(e,t){const n=Number(e[t]);return Number.isFinite(n)?n:null}function N(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function Yn(e,t){const n=F(t,"summary");if(n)return n;const o=F(t,"title"),r=F(t,"slug"),a=F(t,"status"),s=F(t,"contentType"),c=F(t,"field"),u=F(t,"mode"),d=F(t,"languageCode"),l=M(t,"blockCount"),m=M(t,"itemCount"),h=M(t,"affectedCount");if(e==="create_cms_page"||e==="create_cms_post")return`Create ${a||"draft"} ${e==="create_cms_page"?"page":"post"} "${o||r||"Untitled"}"${r?` at slug "${r}"`:""}${l!==null?` with ${N(l,"content block")}`:""}.`;if(e==="create_cms_product"){const p=M(t,"imageCount"),f=M(t,"blockCount"),g=[p?N(p,"image"):null,f?N(f,"description block"):M(t,"descriptionLength")?"a full description":null].filter(Boolean);return`Create ${a||"draft"} product "${o||r||"Untitled"}"${r?` at slug "${r}"`:""}${g.length?` with ${g.join(" and ")}`:""}.`}if(e==="update_cms_item_field")return`Update ${c||"one field"} on the ${s||"CMS item"} "${o||r||"selected item"}".`;if(e==="update_navigation_bar")return`${u==="append"?"Add":u==="update"?"Update":"Replace"} ${m!==null?N(m,"navigation item"):"navigation items"} in the ${d||"selected"} header navigation.`;if(e==="update_footer"){const p=M(t,"linkCount");return`Update the ${d||"selected"} footer${p!==null?` with ${N(p,"link")}`:""}.`}return e==="update_content_block"?`Update the selected ${F(t,"blockType")||"content"} block.`:e==="insert_content_block"?`Insert ${F(t,"blockType")||"content"} block on the ${s||"CMS item"} "${o||r||"selected item"}".`:e==="update_section_column_block"?`Update the selected nested ${F(t,"nestedBlockType")||"section"} block.`:e==="delete_cms_item"||e==="prepare_delete_cms_item"?`Delete ${h!==null?N(h,s||"CMS item"):`the selected ${s||"CMS item"}`}${o||r?` for "${o||r}"`:""}.`:"Complete the requested CMS change."}function P(e){if(e.context?.skipConfirmation)return null;const t=Rt(e),n=Fe(e.context?.latestUserMessage||""),o=Fe(t.confirmationPhrase);return n.includes(o)?null:t}function Ye(e){const t=e?.actorUserId;if(!t)throw new Error("A confirmed CMS mutation requires an authenticated admin actor.");return t}function Xe(){return globalThis.crypto?.randomUUID?.()||`id-${Date.now()}-${Math.random().toString(36).slice(2)}`}function R(e){return e.toLowerCase().trim().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"").slice(0,300)}function Qe(e){return(e||"USD").trim().toUpperCase()}const Xn=new Set(["BIF","CLP","DJF","GNF","JPY","KMF","KRW","MGA","PYG","RWF","UGX","VND","VUV","XAF","XOF","XPF"]);function Qn(e){return Xn.has(Qe(e))?0:2}function Mt(e,t){return Math.round(e*10**Qn(t))}function Zn(e,t){return!e||typeof e!="object"||Array.isArray(e)?{}:Object.entries(e).reduce((n,[o,r])=>{if(typeof r=="number"&&Number.isFinite(r)&&r>=0){const a=Qe(o||t);n[a]=Mt(r,a)}return n},{})}function fe(e,t){if(!v(e))throw new Error(`${t} content must be a JSON object.`);return JSON.parse(JSON.stringify(e))}function K(e){return JSON.parse(JSON.stringify(e))}function v(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function Oe(e,t){const n=K(e);for(const[o,r]of Object.entries(t))if(r!==void 0){if(v(r)&&v(n[o])){n[o]=Oe(n[o],r);continue}n[o]=K(r)}return n}function Dt(e,t){if(t.contentType==="product"){if(String(e.product_id??"")!==String(Bt(t)))throw new Error(`Block ${e.id} does not belong to the current product being edited.`);return}const n=Je(t);if((t.contentType==="page"?Number(e.page_id):Number(e.post_id))!==n)throw new Error(`Block ${e.id} does not belong to the current ${t.contentType} being edited.`)}function Ie(e,t){const n=typeof e=="string"?e:"";if(!jn(n))throw new Error(`${t} has unsupported block type "${n||"unknown"}".`);return n}function Gt(e,t,n){if(e&&e!==t)throw new Error(`${n} is a "${t}" block. Refusing to update it as "${e}".`)}function D(e,t,n,o){const r=qn(e,t,o);if(!r.isValid)throw new Error(`${n} content is invalid for block type "${e}": ${r.errors.join("; ")}`)}function Kt(e){return e==="section"}function eo(e){return typeof e.html_content=="string"?"text":typeof e.text=="string"&&typeof e.url=="string"?"button":typeof e.text_content=="string"?"heading":"media_id"in e||"object_key"in e||"external_url"in e?"image":typeof e.quote=="string"&&typeof e.author_name=="string"?"testimonial":typeof e.url=="string"&&("controls"in e||"autoplay"in e||"title"in e)?"video_embed":Array.isArray(e.fields)||typeof e.recipient_email=="string"?"form":"postsPerPage"in e||"showPagination"in e?"posts_grid":typeof e.productId=="string"?"featured_product":"limit"in e&&"type"in e?"product_grid":null}function Te(e){return`ai-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Be(e,t,n){if(!v(e))throw new Error(`${t} must be a JSON object.`);const o=e.block_type??e.blockType,r=Ie(o,t);if(Kt(r))throw new Error(`${t} cannot be a nested ${r} block.`);const a=Jt(r,fe(e.content,t),t,n),s=e.temp_id??e.tempId,c=typeof s=="string"&&s.trim()?s:Te(r);return{block_type:r,content:a,temp_id:c}}function to(e,t){const n=[];if("append_block"in e&&n.push(Be(e.append_block,"Nested block to append",t)),"append_blocks"in e){const o=e.append_blocks;if(!Array.isArray(o))throw new Error("append_blocks must be an array of nested block objects.");o.forEach((r,a)=>{n.push(Be(r,`Nested block to append ${a}`,t))})}return n}function no(e,t){if("append_block"in e||"append_blocks"in e||"background"in e||"column_blocks"in e||"column_gap"in e||"container_type"in e||"padding"in e||"responsive_columns"in e||"vertical_alignment"in e)return null;const n=eo(e);if(!n)return null;const o=fe(e,`Nested ${n} block`);return D(n,o,`Nested ${n} block`,t),{block_type:n,content:o,temp_id:Te(n)}}function oo(e,t){const n=e.append_column_index??e.column_index;if(n===void 0)return 0;if(typeof n!="number"||!Number.isInteger(n)||n<0)throw new Error("append_column_index must be a non-negative integer.");if(t>0&&n>=t)throw new Error(`append_column_index ${n} is outside the existing ${t} column(s).`);return n}function ro(e,t,n,o){if(!Kt(e))return Oe(t,n);const r={...n},a=to(r,o),s=no(r,o);s&&a.push(s),delete r.append_block,delete r.append_blocks,delete r.append_column_index,delete r.column_index;const c=Oe(t,r);if(a.length>0){const u=Array.isArray(t.column_blocks)?K(t.column_blocks):[],d=oo(n,u.length),l=u.length>0?u:[[]];for(;l.length<=d;)l.push([]);l[d]=[...l[d]||[],...a],c.column_blocks=l}return c}function io(e,t){return{blockType:e.block_type,content:t?e.content:void 0,id:e.id,languageId:e.language_id,order:e.order,pageId:e.page_id,postId:e.post_id}}function V(e){return typeof e=="string"?e.trim().toLowerCase():""}function Tt(e){return typeof e=="string"?e.trim().toLowerCase():""}function Ht(e){return e.reduce((t,n)=>t+1+(n.children?.length||0),0)}function we(e){return typeof e=="string"?e.trim().toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,""):""}async function X(e,t){const n=t.trim(),o=we(n),r=wn[o],{data:a,error:s}=await e.from("languages").select("id, code, name, is_active");if(s)throw new Error(`Failed to load language "${t}": ${y(s)}`);const u=(Array.isArray(a)?a:[]).filter(l=>l.is_active!==!1),d=u.find(l=>{const m=we(l.code),h=we(l.name);return m===o||m===r||h===o});if(!d?.id||!d?.code){const l=u.map(m=>m.code).filter(Boolean).join(", ");throw new Error(`Language "${t}" was not found.${l?` Available languages: ${l}.`:""}`)}return{code:String(d.code),id:Number(d.id)}}async function Ee(e,t){if(t)return X(e,t);const{data:n,error:o}=await e.from("languages").select("id, code, name, is_active, is_default");if(o)throw new Error(`Failed to load active languages: ${y(o)}`);const r=(Array.isArray(n)?n:[]).filter(s=>s.is_active!==!1),a=r.find(s=>s.is_default)||r.find(s=>we(s.code)==="en")||r[0];if(!a?.id||!a?.code)throw new Error("No active CMS language is available for Cortex AI content creation.");return{code:String(a.code),id:Number(a.id)}}async function Ct(e){try{const{data:t,error:n}=await e.from("currencies").select("code, is_default, is_active").eq("is_active",!0);if(n)return"USD";const o=Array.isArray(t)?t:[],r=o.find(a=>a.is_default)||o[0];return Qe(r?.code||"USD")}catch{return"USD"}}async function ao(e){const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products";let n="id",o=e.entityId;if(o===void 0&&e.slug&&(n="slug",o=e.slug),o===void 0&&e.title&&(n="title",o=e.title),o===void 0)throw new Error(`A ${e.contentType} target requires an id, slug, title, or current edit context.`);const{data:r,error:a}=await e.supabase.from(t).select("*").eq(n,o);if(a)throw new Error(`Failed to resolve ${e.contentType}: ${y(a)}`);const s=Array.isArray(r)?r:r?[r]:[];if(s.length!==1)throw new Error(s.length===0?`No ${e.contentType} matched ${n} "${String(o)}".`:`Multiple ${e.contentType}s matched ${n} "${String(o)}"; use an exact id.`);return s[0]}async function he(e,t){const n=Ge.safeParse(t?.pageContext).success?t?.pageContext:null,o=e.contentType||n?.contentType;if(!o)throw new Error("Target contentType is required when no current CMS edit context exists.");const r=e.entityId!==void 0||!!e.slug||!!e.title,a=e.entityId??(r?void 0:n?.entityId),s=e.slug??(r?void 0:n?.slug??void 0),c=e.title??(r?void 0:n?.title??void 0),u=await ao({contentType:o,entityId:a,slug:a===void 0&&s||void 0,supabase:z(t),title:a===void 0&&!s&&c||void 0});return{contentType:o,item:u}}async function Ce(e){const t=await co({item:e.item,languageId:e.languageId,menuKey:e.menuKey,supabase:e.supabase}),n={label:e.item.label,language_id:e.languageId,menu_key:e.menuKey,order:e.order,page_id:t?.pageId??null,parent_id:e.parentId??null,...t?.navigationTranslationGroupId?{translation_group_id:t.navigationTranslationGroupId}:{},url:e.item.url},{data:o,error:r}=await e.supabase.from("navigation_items").insert(n).select("id").single();if(r)throw new Error(`Failed to insert ${e.menuKey} navigation item: ${y(r)}`);return Number(o.id)}function so(e){const t=e.trim();if(!t.startsWith("/")||t.startsWith("//"))return null;const n=t.split("?")[0]?.split("#")[0]||"",o=n==="/"?"home":n.replace(/^\/+|\/+$/g,"");return o&&!o.includes("/")?o:null}async function co(e){const t=so(e.item.url);if(!t)return null;const{data:n,error:o}=await e.supabase.from("pages").select("id, slug, translation_group_id, language_id").eq("slug",t).eq("language_id",e.languageId);if(o)throw new Error(`Failed to resolve linked page for navigation item: ${y(o)}`);const r=Array.isArray(n)?n[0]:n;if(!r?.id)return null;let a=Xe();if(r.translation_group_id){const{data:s,error:c}=await e.supabase.from("pages").select("id").eq("translation_group_id",r.translation_group_id);if(c)throw new Error(`Failed to inspect linked page translations for navigation item: ${y(c)}`);const u=new Set((Array.isArray(s)?s:[]).map(h=>String(h.id)).filter(Boolean)),{data:d,error:l}=await e.supabase.from("navigation_items").select("id, page_id, translation_group_id, menu_key").eq("menu_key",e.menuKey);if(l)throw new Error(`Failed to inspect related navigation translations: ${y(l)}`);const m=(Array.isArray(d)?d:[]).find(h=>h.translation_group_id&&u.has(String(h.page_id)));m?.translation_group_id&&(a=m.translation_group_id)}return{navigationTranslationGroupId:a,pageId:Number(r.id)}}async function Vt(e){const t=await X(e.supabase,e.languageCode),{data:n,error:o}=await e.supabase.from("navigation_items").select("id, parent_id").eq("menu_key",e.menuKey).eq("language_id",t.id);if(o)throw new Error(`Failed to inspect existing ${e.menuKey} navigation items: ${y(o)}`);const r=Array.isArray(n)?n:[],a=r.filter(d=>d.parent_id==null).length,s=Ht(e.items);Wt({existingItemCount:r.length,existingTopLevelCount:a,languageCode:t.code,menuKey:e.menuKey,replacementItemCount:s});const{error:c}=await e.supabase.from("navigation_items").delete().eq("menu_key",e.menuKey).eq("language_id",t.id);if(c)throw new Error(`Failed to clear ${e.menuKey} navigation items: ${y(c)}`);let u=0;for(const[d,l]of e.items.entries()){const m=await Ce({item:l,languageId:t.id,menuKey:e.menuKey,order:d,supabase:e.supabase});u++;for(const[h,p]of(l.children??[]).entries())await Ce({item:p,languageId:t.id,menuKey:e.menuKey,order:h,parentId:m,supabase:e.supabase}),u++}return{insertedCount:u,languageCode:t.code,menuKey:e.menuKey,skippedCount:0,updatedCount:0}}function Wt(e){if(!(e.existingItemCount===0||e.replacementItemCount>=e.existingItemCount))throw new Error(`Refusing destructive ${e.menuKey} navigation replacement for ${e.languageCode}: existing menu has ${e.existingItemCount} items (${e.existingTopLevelCount} top-level), but the replacement only contains ${e.replacementItemCount}. Use mode "update" for renaming or changing a single link, or provide the full menu.`)}async function lo(e){const t=await X(e.supabase,e.languageCode),{data:n,error:o}=await e.supabase.from("navigation_items").select("id, parent_id").eq("menu_key",e.menuKey).eq("language_id",t.id);if(o)throw new Error(`Failed to inspect existing ${e.menuKey} navigation items: ${y(o)}`);const r=Array.isArray(n)?n:[];Wt({existingItemCount:r.length,existingTopLevelCount:r.filter(a=>a.parent_id==null).length,languageCode:t.code,menuKey:e.menuKey,replacementItemCount:Ht(e.items)})}async function uo(e){if(e.items.length!==1)throw new Error('mode "update" requires exactly one navigation item.');const t=await X(e.supabase,e.languageCode),n=e.items[0],o=V(e.match?.url)||V(n.url),r=Tt(e.match?.label),{data:a,error:s}=await e.supabase.from("navigation_items").select("id, label, url, parent_id, order").eq("menu_key",e.menuKey).eq("language_id",t.id);if(s)throw new Error(`Failed to load existing ${e.menuKey} navigation items: ${y(s)}`);const u=(Array.isArray(a)?a:[]).find(l=>{const m=V(l.url),h=Tt(l.label);return!!(o&&m===o||r&&h===r)});if(!u?.id)throw new Error(`Could not find a ${e.menuKey} navigation item to update in ${t.code}. Use a matching label or url.`);const{error:d}=await e.supabase.from("navigation_items").update({label:n.label,url:n.url}).eq("id",u.id);if(d)throw new Error(`Failed to update ${e.menuKey} navigation item: ${y(d)}`);return{insertedCount:0,languageCode:t.code,menuKey:e.menuKey,skippedCount:0,updatedCount:1}}async function po(e){const t=await X(e.supabase,e.languageCode),{data:n,error:o}=await e.supabase.from("navigation_items").select("id, url, parent_id, order").eq("menu_key",e.menuKey).eq("language_id",t.id);if(o)throw new Error(`Failed to load existing ${e.menuKey} navigation items: ${y(o)}`);let r=0,a=0;const s=Array.isArray(n)?n:[],c=new Set(s.map(l=>V(l.url)).filter(Boolean)),u=s.filter(l=>l.parent_id==null).map(l=>Number(l.order)).filter(Number.isFinite);let d=u.length>0?Math.max(...u)+1:s.length;for(const l of e.items){const m=V(l.url);if(m&&c.has(m)){a++;continue}const h=await Ce({item:l,languageId:t.id,menuKey:e.menuKey,order:d,supabase:e.supabase});r++,d++,m&&c.add(m);let p=0;for(const f of l.children??[]){const g=V(f.url);if(g&&c.has(g)){a++;continue}await Ce({item:f,languageId:t.id,menuKey:e.menuKey,order:p,parentId:h,supabase:e.supabase}),r++,p++,g&&c.add(g)}}return{insertedCount:r,languageCode:t.code,menuKey:e.menuKey,skippedCount:a,updatedCount:0}}function S(e){return typeof e=="string"&&e.trim()?e.trim():""}function mo(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function go(e){const t=S(e.field_type??e.fieldType??e.type??e.input_type).toLowerCase().replace(/\s+/g,"_"),n=S(e.label??e.name??e.placeholder).toLowerCase();return["email","textarea","select","radio","checkbox","text"].includes(t)?t:n.includes("email")?"email":n.includes("message")||n.includes("comment")||n.includes("details")?"textarea":"text"}function fo(e){return(Array.isArray(e)&&e.length>0?e:[{field_type:"text",is_required:!0,label:"Name",placeholder:"Your name"},{field_type:"email",is_required:!0,label:"Email",placeholder:"you@example.com"},{field_type:"textarea",is_required:!0,label:"Message",placeholder:"How can we help?"}]).map((n,o)=>{const r=v(n)?n:{},a=S(r.label??r.name)||(o===0?"Name":o===1?"Email":"Message"),s=go({...r,label:a}),c=r.is_required??r.isRequired??r.required;return{field_type:s,is_required:typeof c=="boolean"?c:!0,label:a,options:Array.isArray(r.options)?r.options:void 0,placeholder:S(r.placeholder)||void 0,temp_id:S(r.temp_id??r.tempId??r.id)||`field-${o+1}`}})}const ho=new Set(["none","sm","md","lg","xl"]),zt=new Set(["none","sm","md","lg","xl"]),yo=new Set(["full-width","container","container-sm","container-lg","container-xl"]),_o=new Set(["start","center","end","stretch"]),bo=new Set(["none","theme","solid","gradient","image"]),ko=new Set(["primary","secondary","muted","accent","destructive"]),wo=new Set(["center","top","bottom","left","right"]);function Io(e){return typeof e=="string"&&/^https?:\/\//i.test(e.trim())}function L(e,t,n){return typeof e=="string"&&t.has(e)?e:n}function To(e){return Number.isFinite(e)?Math.min(4,Math.max(1,Math.round(e))):1}function Co(e){const t=[{color:"#1e3a8a",position:0},{color:"#3b82f6",position:100}];if(!v(e))return{direction:"to bottom right",stops:t,type:"linear"};const n=e.type==="radial"?"radial":"linear",o=Array.isArray(e.stops)&&e.stops.length>=2?e.stops:t;return{direction:typeof e.direction=="string"&&e.direction.trim()?e.direction:n==="radial"?"circle at center":"to bottom right",stops:o,type:n}}function zo(e){if(!v(e))return{type:"none"};const t=L(e.type,bo,"none"),n=typeof e.min_height=="string"&&e.min_height.trim()?{min_height:e.min_height}:{};if(t==="theme")return{theme:L(e.theme,ko,"muted"),type:t,...n};if(t==="solid")return typeof e.solid_color=="string"&&e.solid_color.trim()?{solid_color:e.solid_color,type:t,...n}:{type:"none"};if(t==="gradient")return{gradient:Co(e.gradient),type:t,...n};if(t==="image"){const o=v(e.image)?e.image:null,r=o&&Io(o.external_url)?o.external_url.trim():null,a=!!(o&&typeof o.media_id=="string"&&o.media_id.trim()&&typeof o.object_key=="string"&&o.object_key.trim());return o&&(r||a)?{image:{...o,...r?{external_url:r}:{},position:L(o.position,wo,"center"),size:o.size==="contain"?"contain":"cover"},type:t,...n}:{type:"none"}}return{type:"none",...n}}function xo(e,t,n){const o=e.is_hero===!0;let r=Array.isArray(e.column_blocks)?e.column_blocks:[];r.length>0&&r.every(g=>v(g)&&!Array.isArray(g))&&(r=[r]);const a=r.map((g,b)=>(Array.isArray(g)?g:[]).map((k,w)=>Be(k,`${t} column ${b} block ${w}`,n))),s=a.length>0?a:[[]],c=To(s.length),u=v(e.responsive_columns)?e.responsive_columns:{},d=Number(u.tablet),l=Number(u.mobile),m=Number.isFinite(d)?Math.min(3,Math.max(1,Math.min(c,d))):Math.min(3,c),h=Number.isFinite(l)?Math.min(2,Math.max(1,l)):1,p=v(e.padding)?e.padding:{},f={...e,background:zo(e.background),column_blocks:s,column_gap:L(e.column_gap,ho,"lg"),container_type:L(e.container_type,yo,"container"),padding:{bottom:L(p.bottom,zt,"xl"),top:L(p.top,zt,"xl")},responsive_columns:{desktop:c,mobile:h,tablet:m},vertical_alignment:L(e.vertical_alignment,_o,o?"center":"start")};return f.slider===!0&&!(Array.isArray(f.slides)&&f.slides.length>0)&&(f.slider=!1),f}function Jt(e,t,n,o){if(e==="section"){const a=xo(t,n,o);return D(e,a,n,o),a}const r=K(t);if(e==="heading"&&(r.text_content=S(r.text_content)||S(r.text)||S(r.title)||S(r.heading)||"Untitled",r.level=typeof r.level=="number"?r.level:1),e==="text"){const a=S(r.html_content)||S(r.html)||S(r.content)||S(r.text);a&&(r.html_content=/<\/?[a-z][\s\S]*>/i.test(a)?a:`<p>${mo(a)}</p>`)}return e==="button"&&(r.text=S(r.text)||S(r.label)||S(r.title)||"Learn More",r.url=S(r.url)||S(r.href)||S(r.link)||"#"),e==="form"&&(r.fields=fo(r.fields),r.submit_button_text=S(r.submit_button_text??r.submitButtonText??r.button_text)||"Send Message",r.success_message=S(r.success_message??r.successMessage)||"Thanks for reaching out. We will reply as soon as possible."),D(e,r,n,o),r}function ze(e,t,n){const o=Jt(e.blockType,fe(e.content,`Block ${t}`),`Block ${t}`,n);return{block_type:e.blockType,content:o,order:e.order??t}}function So(e,t="Contact Us",n){return[ze({blockType:"section",content:{is_hero:!0,background:{type:"none"},column_blocks:[[{block_type:"heading",content:{level:1,textAlign:"center",text_content:t},temp_id:Te("heading")},{block_type:"text",content:{html_content:"<p>Have a question, project, or support request? Send us a note and we will get back to you soon.</p>"},temp_id:Te("text")}]],column_gap:"lg",container_type:"container",padding:{bottom:"xl",top:"xl"},responsive_columns:{desktop:1,mobile:1,tablet:1},vertical_alignment:"center"}},0,n),ze({blockType:"form",content:{fields:[{field_type:"text",is_required:!0,label:"Name",placeholder:"Your name",temp_id:"field-name"},{field_type:"email",is_required:!0,label:"Email",placeholder:"you@example.com",temp_id:"field-email"},{field_type:"textarea",is_required:!0,label:"Message",placeholder:"How can we help?",temp_id:"field-message"}],recipient_email:e,submit_button_text:"Send Message",success_message:"Thanks for reaching out. We will reply as soon as possible."}},1,n)]}function $e(e,t,n,o){return(!e||e.length===0)&&t?So(t,n,o):(e||[]).map((r,a)=>ze(r,a,o))}async function Ze(e){const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products",{data:n,error:o}=await e.supabase.from(t).select("id, title, slug, language_id").eq("slug",e.slug).eq("language_id",e.languageId);if(o)throw new Error(`Failed to check ${e.contentType} slug uniqueness: ${y(o)}`);const r=Array.isArray(n)?n:[];return r.length>0?{duplicate:!0,existingItem:r[0],mutationExecuted:!1,success:!1,message:`A ${e.contentType} with slug "${e.slug}" already exists for this language.`}:null}async function et(e){if(!e.suppliedTranslationGroupId)return{translationGroupId:void 0};const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products",{data:n,error:o}=await e.supabase.from(t).select("id, title, slug, language_id, translation_group_id").eq("translation_group_id",e.suppliedTranslationGroupId);if(o)throw new Error(`Failed to inspect ${e.contentType} translation group: ${y(o)}`);const r=Array.isArray(n)?n:[];if(r.length===0)return{result:{message:`The ${e.contentType} translation group "${e.suppliedTranslationGroupId}" was not found.`,mutationExecuted:!1,success:!1},translationGroupId:e.suppliedTranslationGroupId};const a=r.find(s=>Number(s.language_id)===e.languageId);return a?{result:{duplicateTranslation:!0,existingItem:a,message:`A ${e.contentType} translation already exists for ${e.languageCode} in this translation group.`,mutationExecuted:!1,success:!1},translationGroupId:e.suppliedTranslationGroupId}:{translationGroupId:e.suppliedTranslationGroupId}}async function tt(e){if(e.blocks.length===0)return[];const t=e.blocks.map((r,a)=>({block_type:r.block_type,content:r.content,language_id:e.languageId,order:r.order??a,page_id:e.contentType==="page"?e.itemId:null,post_id:e.contentType==="post"?e.itemId:null,product_id:e.contentType==="product"?e.itemId:null})),{data:n,error:o}=await e.supabase.from("blocks").insert(t).select("*");if(o)throw new Error(`Failed to insert ${e.contentType} blocks: ${y(o)}`);return ye(e.blocks,e.supabase),Array.isArray(n)?n:[]}async function nt(e){const t=e.contentType==="page"?"pages":e.contentType==="post"?"posts":"products";await e.supabase.from(t).delete().eq("id",e.itemId)}function ot(e,t){return e==="page"?`/cms/pages/${t}/edit`:e==="post"?`/cms/posts/${t}/edit`:`/cms/products/${t}/edit`}function xt(e){return e==="page"?"/cms/pages":e==="post"?"/cms/posts":"/cms/products"}async function rt(e,t){const n=te.parse(e),o=z(t);n.mode==="replace"&&await lo({items:n.items,languageCode:n.languageCode,menuKey:"HEADER",supabase:o});const r=P({action:"UPDATE NAVIGATION",context:t,payload:{input:n,tool:"update_navigation_bar"},preview:{itemCount:n.items.length,languageCode:n.languageCode,mode:n.mode,target:"header navigation"},subject:`${n.mode} header`});if(r)return r;const a=n.mode==="update"?await uo({items:n.items,languageCode:n.languageCode,match:n.match,menuKey:"HEADER",supabase:o}):n.mode==="append"?await po({items:n.items,languageCode:n.languageCode,menuKey:"HEADER",supabase:o}):await Vt({items:n.items,languageCode:n.languageCode,menuKey:"HEADER",supabase:o});return qt(t),{...a,mutationExecuted:!0,mode:n.mode,success:!0}}async function it(e,t){const n=ne.parse(e);if(!n.links?.length&&!n.copyright)throw new Error("update_footer requires links or copyright.");const o=z(t),r=P({action:"UPDATE FOOTER",context:t,payload:{input:n,tool:"update_footer"},preview:{copyrightUpdated:!!n.copyright,linkCount:n.links?.length||0,languageCode:n.languageCode,target:"footer"},subject:n.languageCode});if(r)return r;let a=null;if(n.links?.length&&(a=await Vt({items:n.links,languageCode:n.languageCode,menuKey:"FOOTER",supabase:o})),n.copyright){const{error:s}=await o.from("site_settings").upsert({key:"footer_copyright",value:n.copyright});if(s)throw new Error(`Failed to update footer copyright: ${y(s)}`)}return qt(t),{copyrightUpdated:!!n.copyright,footerNavigation:a,mutationExecuted:!0,success:!0}}function Yt(e){return typeof e=="string"?e.toLowerCase():""}function vo(e,t){const n=t.map(Yt).join(" ");return e.reduce((o,r)=>o+(n.includes(r)?1:0),0)}function St(e,t){return(e.find(n=>t.some(o=>Yt(n).includes(o)))||e.find(n=>n.trim().length>0)||"No excerpt available.").slice(0,500)}async function Xt(e,t){const n=Se.parse(e),o=z(t),r=n.query.toLowerCase().split(/\s+/).map(l=>l.trim()).filter(Boolean),[a,s]=await Promise.all([o.from("posts").select("id, title, slug, excerpt, subtitle, meta_description, status, updated_at").eq("status","published").limit(100),o.from("pages").select("id, title, slug, meta_description, status, updated_at").eq("status","published").limit(100)]);if(a.error)throw new Error(`Failed to search documentation posts: ${y(a.error)}`);if(s.error)throw new Error(`Failed to search documentation pages: ${y(s.error)}`);const c=(a.data??[]).map(l=>({excerpt:St([l.excerpt,l.subtitle,l.meta_description,l.slug].filter(Boolean),r),source:"post",title:l.title,url:`/article/${l.slug}`})),u=(s.data??[]).map(l=>({excerpt:St([l.meta_description,l.slug].filter(Boolean),r),source:"page",title:l.title,url:l.slug==="home"?"/":`/${l.slug}`})),d=[...c,...u].map(l=>({...l,score:vo(r,[l.title,l.excerpt,l.url])})).filter(l=>l.score>0).sort((l,m)=>m.score-l.score).slice(0,n.limit).map(l=>({excerpt:l.excerpt,source:l.source,title:l.title,url:l.url}));return{query:n.query,results:d,success:!0}}async function Qt(e,t,n=kn){const o=Se.safeParse(e),r=o.success?o.data.query:"";return Rn(Xt(e,t),n,()=>({message:"Documentation search took too long to respond. Please try again or ask a more specific question.",query:r,results:[],success:!1,timedOut:!0}))}const Eo=["pending","trial","paid","shipped","cancelled","refunded","failed"],$o={awaiting:"pending",canceled:"cancelled",cancelled:"cancelled",complete:"paid",completed:"paid",failed:"failed",paid:"paid",payment_pending:"pending",pending:"pending",refund:"refunded",refunded:"refunded",refunds:"refunded",shipped:"shipped",trial:"trial",trials:"trial"};function Ao(e){return String(e??"unknown").trim().toLowerCase()||"unknown"}function vt(e){const t=Object.fromEntries(Eo.map(n=>[n,0]));for(const n of e){const o=Ao(n.status);t[o]=(t[o]??0)+1}return t}function Po(e){const n=e.toLowerCase().replace(/[^a-z0-9_]+/g," ").split(/\s+/).filter(Boolean);for(const o of n){const r=$o[o];if(r)return r}return null}function ee(e){const t=Number(e);return Number.isFinite(t)?t:0}async function Zt(e,t){const n=De.parse(e),o=z(t),r=new Date;let a=null,s=null;switch(n.timeRange){case"today":a=new Date(r.getFullYear(),r.getMonth(),r.getDate());break;case"this_month":a=new Date(r.getFullYear(),r.getMonth(),1);break;case"last_7_days":a=new Date(r.getTime()-10080*60*1e3);break;case"last_30_days":a=new Date(r.getTime()-720*60*60*1e3);break;case"last_month":a=new Date(r.getFullYear(),r.getMonth()-1,1),s=new Date(r.getFullYear(),r.getMonth(),0,23,59,59,999);break;case"last_90_days":a=new Date(r.getTime()-2160*60*60*1e3);break;case"all_time":a=null;break}const c=n.currency?.toUpperCase(),u=Po(n.query),d=o.from("orders").select("id, status, total, currency, created_at, paid_at");c&&d.eq("currency",c),a&&d.gte("created_at",a.toISOString()),s&&d.lte("created_at",s.toISOString());const m=n.reportType==="products"||n.reportType==="revenue"||n.reportType==="general"?o.from("order_items").select(`
2
2
  quantity,
3
3
  price_at_purchase,
4
4
  products!inner (
@@ -12,4 +12,4 @@
12
12
  paid_at,
13
13
  currency
14
14
  )
15
- `).eq("orders.status","paid"):null;m&&(c&&m.eq("orders.currency",c),a&&m.gte("orders.paid_at",a.toISOString()),s&&m.lte("orders.paid_at",s.toISOString()));const p=n.timeRange!=="all_time"&&(n.reportType==="orders"||u)?o.from("orders").select("id, status, currency"):null;p&&c&&p.eq("currency",c);const[{data:g,error:f},{data:k,error:y},w]=await Promise.all([d,m??Promise.resolve({data:[],error:null}),p??Promise.resolve({data:null,error:null})]);if(f)throw new Error(`Failed to fetch ecommerce stats: ${_(f)}`);if(y)throw new Error(`Failed to fetch ecommerce stats: ${_(y)}`);if(w.error)throw new Error(`Failed to fetch ecommerce stats: ${_(w.error)}`);const b=Array.isArray(g)?g:[],I=Array.isArray(k)?k:[],x=Ct(b),v=Array.isArray(w.data)?w.data:null,j=v?Ct(v):null,q={};for(const T of I){const $=Array.isArray(T.orders)?T.orders[0]:T.orders,O=String($?.currency||c||"unknown").toUpperCase();q[O]=(q[O]??0)+X(T.quantity)*X(T.price_at_purchase)/100}const J={currency:c??null,currencyFiltered:!!c,orderStatusCounts:x,paidOrderCount:x.paid??0,query:n.query,reportType:n.reportType,revenueByCurrency:q,timeRange:n.timeRange,totalOrders:b.length,totalRevenue:Object.values(q).reduce((T,$)=>T+$,0)};if(j&&(J.allTimeOrderStatusCounts=j),u&&(J.matchingOrderStatus={allTimeCount:j?.[u]??x[u]??0,count:x[u]??0,status:u,timeRange:n.timeRange}),n.reportType==="products"||n.reportType==="revenue"||n.reportType==="general"){const T={};for(const $ of I){const O=Array.isArray($.products)?$.products[0]:$.products;if(!O?.id)continue;const Y=O.id;T[Y]||(T[Y]={id:Y,quantity:0,revenue:0,title:O.title,type:O.product_type}),T[Y].quantity+=X($.quantity),T[Y].revenue+=X($.quantity)*X($.price_at_purchase)/100}J.topProducts=Object.values(T).sort(($,O)=>O.revenue-$.revenue).slice(0,10)}return{report:J,success:!0}}async function Qt(e,t){const n=De.parse(e),o=z(t),r=V(t),a=ze(r),s=r.contentType==="page"?"pages":r.contentType==="post"?"posts":"products",{data:c,error:u}=await o.from(s).select("*").eq("id",a).single();if(u||!c)throw new Error(`Failed to read current ${r.contentType}: ${_(u)}`);let d=[];if(n.includeBlocks){const l=r.contentType==="page"?"page_id":r.contentType==="post"?"post_id":"product_id",{data:m,error:h}=await o.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq(l,a);if(h)throw new Error(`Failed to read current ${r.contentType} blocks: ${_(h)}`);d=(Array.isArray(m)?m:[]).slice().sort((p,g)=>Number(p.order)-Number(g.order)).map(p=>oo(p,n.includeBlockContent))}return{blocks:d,context:r,item:c,success:!0}}const Zt=new Set(["feature_image_id","language_id","meta_description","meta_title","slug","status","title"]),en=new Set(["excerpt","feature_image_id","label","language_id","meta_description","meta_title","published_at","slug","status","subtitle","title"]),Ao=new Set(["description_json","language_id","meta_description","meta_title","short_description","slug","status","title"]),Po=new Set(["excerpt","feature_image_id","label","meta_description","meta_title","published_at","short_description","subtitle"]);function No(e){return e==="page"?Zt:e==="post"?en:Ao}function tn(e,t){return Po.has(e)&&t===""?null:t}function Oe(e,t){if(typeof t!="string")return;const n=e==="product"?["active","archived","draft"]:["archived","draft","published"];if(!n.includes(t))throw new Error(`Status "${t}" is not valid for ${e}. Allowed statuses: ${n.join(", ")}.`)}function Uo(e,t){const n=No(t.contentType),o={};for(const[r,a]of Object.entries(e))if(a!==void 0){if(!n.has(r))throw new Error(`Field "${r}" cannot be updated for ${t.contentType} content.`);r==="status"&&Oe(t.contentType,a),o[r]=tn(r,a)}return o}async function rt(e,t){const n=ee.parse(e),o=z(t),r=V(t),a=ze(r),s=Uo(n.fields,r),c=Object.keys(s);if(c.length===0)throw new Error("update_current_cms_fields requires at least one supported field.");const u=A({action:"UPDATE CMS FIELDS",context:t,payload:{contentType:r.contentType,entityId:a,fields:s,tool:"update_current_cms_fields"},preview:{contentType:r.contentType,entityId:a,fields:c,slug:r.slug,title:r.title},subject:`${r.contentType} ${String(a)}`});if(u)return u;typeof s.feature_image_id=="string"&&(s.feature_image_id=await de(s.feature_image_id,t,typeof r.title=="string"?r.title:void 0));const d=r.contentType==="page"?"pages":r.contentType==="post"?"posts":"products",{data:l,error:m}=await o.from(d).update({...s,updated_at:new Date().toISOString()}).eq("id",a).select("id, language_id, slug, status, title").single();if(m||!l)throw new Error(`Failed to update current ${r.contentType}: ${_(m)}`);return N(t,r,l.slug),{contentType:r.contentType,entityId:a,mutationExecuted:!0,slug:l.slug,success:!0,updatedFields:c}}async function it(e,t){const n=te.parse(e),o=z(t),r=V(t),{data:a,error:s}=await o.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq("id",n.blockId).single();if(s||!a)throw new Error(`Failed to read block ${n.blockId}: ${_(s)}`);Rt(a,r);const c=be(a.block_type,`Block ${n.blockId}`);Mt(n.blockType,c,`Block ${n.blockId}`);const u=pe(a.content,`Block ${n.blockId}`),d=no(c,u,n.content,t);M(c,d,`Block ${n.blockId}`,t);const l=A({action:"UPDATE CONTENT BLOCK",context:t,payload:{blockId:n.blockId,blockType:c,content:d,tool:"update_content_block"},preview:{blockId:n.blockId,blockType:c,contentType:r.contentType,entityId:ze(r)},subject:`${c} block ${n.blockId}`});if(l)return l;const{data:m,error:h}=await o.from("blocks").update({content:d,updated_at:new Date().toISOString()}).eq("id",n.blockId).select("id, block_type, order").single();if(h||!m)throw new Error(`Failed to update block ${n.blockId}: ${_(h)}`);return await Ce({patch:({blocks:p})=>({blocks:p.map(g=>String(g?.id)===String(n.blockId)?{...g,content:d}:g)}),productId:a.product_id,supabase:o}),ge([{content:d}],o),N(t,r),{blockId:m.id,blockType:m.block_type,contentUpdated:!0,mutationExecuted:!0,success:!0}}async function at(e,t){const n=ie.parse(e),o=z(t),r=await me(n,t),a=r.contentType==="product"?r.item.id:Number(r.item.id),s=r.contentType==="page"?"page_id":r.contentType==="post"?"post_id":"product_id",c=async()=>{const{data:b,error:I}=await o.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq(s,a);if(I)throw new Error(`Failed to read ${r.contentType} blocks: ${_(I)}`);return(Array.isArray(b)?b:[]).sort((x,v)=>Number(x.order)-Number(v.order))},u=b=>{if(n.position==="start")return 0;if(n.position==="end"){const v=b.map(j=>Number(j.order)).filter(Number.isFinite);return v.length>0?Math.max(...v)+1:0}const I=n.anchorBlockId?b.find(v=>Number(v.id)===n.anchorBlockId):n.anchorBlockType?b.find(v=>v.block_type===n.anchorBlockType):null;if(!I)throw new Error(n.anchorBlockType?`Could not find a ${n.anchorBlockType} block to insert ${n.position}.`:`Could not find block ${n.anchorBlockId} to insert ${n.position}.`);const x=Number(I.order);return n.position==="before"?x:x+1},d=Ie(n.block,0,t),l=await c(),m=u(l),h={contentType:r.contentType,entityId:r.item.id,languageId:r.item.language_id,slug:r.item.slug,title:r.item.title,translationGroupId:r.item.translation_group_id},p=A({action:"INSERT CONTENT BLOCK",context:t,payload:{block:d,order:m,target:{contentType:r.contentType,id:r.item.id,slug:r.item.slug},tool:"insert_content_block"},preview:{anchorBlockId:n.anchorBlockId,anchorBlockType:n.anchorBlockType,blockType:d.block_type,contentType:r.contentType,entityId:r.item.id,position:n.position,slug:r.item.slug,summary:`Insert ${d.block_type} block ${n.position} ${n.anchorBlockType?`the first ${n.anchorBlockType} block`:n.anchorBlockId?`block ${n.anchorBlockId}`:"the content"} on ${r.contentType} "${r.item.title||r.item.slug}".`,title:r.item.title},subject:`${d.block_type} block on ${r.contentType} ${r.item.id}`});if(p)return p;const g=await c(),f=u(g),k=g.filter(b=>Number(b.order)>=f).sort((b,I)=>Number(I.order)-Number(b.order));for(const b of k){const{error:I}=await o.from("blocks").update({order:Number(b.order)+1,updated_at:new Date().toISOString()}).eq("id",b.id);if(I)throw new Error(`Failed to shift block ${b.id}: ${_(I)}`)}const{data:y,error:w}=await o.from("blocks").insert({block_type:d.block_type,content:d.content,language_id:r.item.language_id,order:f,page_id:r.contentType==="page"?a:null,post_id:r.contentType==="post"?a:null,product_id:r.contentType==="product"?a:null}).select("id, block_type, order").single();if(w||!y)throw new Error(`Failed to insert content block: ${_(w)}`);return r.contentType==="product"&&await Ce({patch:({blocks:b})=>({blocks:[...b.map(I=>Number(I?.order)>=f?{...I,order:Number(I.order)+1}:I),{block_type:d.block_type,content:d.content,id:y.id,language_id:r.item.language_id,order:f,page_id:null,post_id:null,product_id:a}].sort((I,x)=>Number(I.order)-Number(x.order))}),productId:a,supabase:o}),ge([d],o),N(t,h),{blockId:y.id,blockType:y.block_type,contentType:r.contentType,entityId:r.item.id,mutationExecuted:!0,order:y.order,success:!0}}async function st(e,t){const n=ne.parse(e),o=z(t),r=V(t),{data:a,error:s}=await o.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq("id",n.parentBlockId).single();if(s||!a)throw new Error(`Failed to read parent block ${n.parentBlockId}: ${_(s)}`);Rt(a,r);const c=be(a.block_type,`Parent block ${n.parentBlockId}`);if(c!=="section")throw new Error(`Parent block ${n.parentBlockId} must be a section block, not "${c}".`);const u=pe(a.content,`Parent block ${n.parentBlockId}`);M(c,u,`Parent block ${n.parentBlockId}`,t);const l=u.column_blocks?.[n.columnIndex]?.[n.blockIndex];if(!l)throw new Error(`Nested block was not found at column ${n.columnIndex}, index ${n.blockIndex}.`);const m=be(l.block_type,`Nested block ${n.columnIndex}:${n.blockIndex}`);Mt(n.blockType,m,`Nested block ${n.columnIndex}:${n.blockIndex}`),M(m,n.content,`Nested block ${n.columnIndex}:${n.blockIndex}`,t);const h=u.column_blocks.map((y,w)=>w===n.columnIndex?y.map((b,I)=>I===n.blockIndex?{...b,content:n.content}:b):y),p={...u,column_blocks:h};M(c,p,`Updated parent block ${n.parentBlockId}`,t);const g=A({action:"UPDATE NESTED BLOCK",context:t,payload:{blockIndex:n.blockIndex,columnIndex:n.columnIndex,content:n.content,nestedBlockType:m,parentBlockId:n.parentBlockId,tool:"update_section_column_block"},preview:{blockIndex:n.blockIndex,columnIndex:n.columnIndex,nestedBlockType:m,parentBlockId:n.parentBlockId,parentBlockType:c},subject:`${m} nested block ${n.columnIndex}:${n.blockIndex}`});if(g)return g;const{data:f,error:k}=await o.from("blocks").update({content:p,updated_at:new Date().toISOString()}).eq("id",n.parentBlockId).select("id, block_type").single();if(k||!f)throw new Error(`Failed to update parent block ${n.parentBlockId}: ${_(k)}`);return await Ce({patch:({blocks:y})=>({blocks:y.map(w=>String(w?.id)===String(n.parentBlockId)?{...w,content:p}:w)}),productId:a.product_id,supabase:o}),N(t,r),{blockIndex:n.blockIndex,columnIndex:n.columnIndex,mutationExecuted:!0,nestedBlockType:m,parentBlockId:f.id,parentBlockType:f.block_type,success:!0}}async function Ee(e,t){const n=ae.parse(e),o=z(t),r=We(t),a=await Se(o,n.languageCode),s=L(n.slug||n.title),c=ve(n.blocks,n.contactEmail,n.title,t),u=await Xe({contentType:"page",languageId:a.id,slug:s,supabase:o});if(u)return u;const d=await Qe({contentType:"page",languageCode:a.code,languageId:a.id,suppliedTranslationGroupId:n.translationGroupId,supabase:o});if(d.result)return d.result;const l={blocks:c,item:{feature_image_id:n.feature_image_id??null,language_id:a.id,meta_description:n.meta_description??null,meta_title:n.meta_title??null,slug:s,status:n.status,title:n.title,translation_group_id:d.translationGroupId},tool:"create_cms_page"},m=A({action:"CREATE PAGE",context:t,payload:l,preview:{blockCount:c.length,languageCode:a.code,slug:s,status:n.status,title:n.title,translationGroupId:d.translationGroupId},subject:s});if(m)return m;const h=d.translationGroupId||Je(),p=await de(l.item.feature_image_id,t,n.title),{data:g,error:f}=await o.from("pages").insert({...l.item,author_id:r,feature_image_id:p,translation_group_id:h}).select("id, language_id, slug, status, title, translation_group_id").single();if(f||!g?.id)throw new Error(`Failed to create page: ${_(f)}`);try{await Ze({blocks:c,contentType:"page",itemId:Number(g.id),languageId:a.id,supabase:o})}catch(k){throw await et({contentType:"page",itemId:Number(g.id),supabase:o}),k}return N(t,{contentType:"page",entityId:Number(g.id),languageId:a.id,slug:s,title:n.title},s),t?.revalidatePath?.("/cms/pages"),{blockCount:c.length,contentType:"page",editPath:tt("page",g.id),entityId:g.id,mutationExecuted:!0,slug:s,success:!0,title:n.title,translationGroupId:g.translation_group_id}}async function $e(e,t){const n=se.parse(e),o=z(t),r=We(t),a=await Se(o,n.languageCode),s=L(n.slug||n.title),c=ve(n.blocks,void 0,void 0,t),u=await Xe({contentType:"post",languageId:a.id,slug:s,supabase:o});if(u)return u;const d=await Qe({contentType:"post",languageCode:a.code,languageId:a.id,suppliedTranslationGroupId:n.translationGroupId,supabase:o});if(d.result)return d.result;const l=n.published_at&&!Number.isNaN(new Date(n.published_at).getTime())?new Date(n.published_at).toISOString():n.published_at??null,m={blocks:c,item:{excerpt:n.excerpt??null,feature_image_id:n.feature_image_id??null,label:n.label??null,language_id:a.id,meta_description:n.meta_description??null,meta_title:n.meta_title??null,published_at:l,slug:s,status:n.status,subtitle:n.subtitle??null,title:n.title,translation_group_id:d.translationGroupId},tool:"create_cms_post"},h=A({action:"CREATE POST",context:t,payload:m,preview:{blockCount:c.length,languageCode:a.code,slug:s,status:n.status,title:n.title,translationGroupId:d.translationGroupId},subject:s});if(h)return h;const p=d.translationGroupId||Je(),g=await de(m.item.feature_image_id,t,n.title),{data:f,error:k}=await o.from("posts").insert({...m.item,author_id:r,feature_image_id:g,translation_group_id:p}).select("id, language_id, slug, status, title, translation_group_id").single();if(k||!f?.id)throw new Error(`Failed to create post: ${_(k)}`);try{await Ze({blocks:c,contentType:"post",itemId:Number(f.id),languageId:a.id,supabase:o})}catch(y){throw await et({contentType:"post",itemId:Number(f.id),supabase:o}),y}return N(t,{contentType:"post",entityId:Number(f.id),languageId:a.id,slug:s,title:n.title},s),t?.revalidatePath?.("/cms/posts"),t?.revalidatePath?.("/articles"),{blockCount:c.length,contentType:"post",editPath:tt("post",f.id),entityId:f.id,mutationExecuted:!0,slug:s,success:!0,title:n.title,translationGroupId:f.translation_group_id}}function Fo(e,t){return(t||L(e)||"product").replace(/-/g,"").slice(0,24).toUpperCase()}function nn(e){if(e==null)return;if(typeof e=="string")return Pt.editorDocumentFromHtml(e)??void 0;const t=Array.isArray(e)?{content:e,type:"doc"}:E(e)&&e.type!=="doc"&&Array.isArray(e.content)?{...e,type:"doc"}:e,n=kt().safeParse(t);if(!n.success){if(E(e)&&typeof e.type=="string"){const o=kt().safeParse({content:[e],type:"doc"});if(o.success)return o.data}throw new Error(`Product description_json must be an editor document like { "type": "doc", "content": [ { "type": "paragraph", "content": [ { "type": "text", "text": "..." } ] } ] }, or simply an HTML string. Received: ${n.error.issues.map(o=>o.message).join("; ")}`)}return n.data}function Oo(e){const t=r=>!!(r&&Array.isArray(r.content)&&r.content.length>0),n=nn(e.description_json);if(t(n))return n;const o=e.description_html?Pt.editorDocumentFromHtml(e.description_html):null;return t(o)?o:void 0}async function ct(e,t){const n=ce.parse(e),o=z(t),r=await Se(o,n.languageCode),a=L(n.slug||n.title),s=ve(n.blocks,void 0,void 0,t),c=await Xe({contentType:"product",languageId:r.id,slug:a,supabase:o});if(c)return c;const u=await Qe({contentType:"product",languageCode:r.code,languageId:r.id,suppliedTranslationGroupId:n.translationGroupId,supabase:o});if(u.result)return u.result;const{createProduct:d,productSchema:l}=await Kn(),h=n.product_type==="digital"&&n.payment_provider==="freemius"?n.trial_period_days:0,p=l.parse({description_json:Oo(n),freemius_plan_id:n.freemius_plan_id||"",freemius_product_id:n.freemius_product_id||"",is_taxable:n.is_taxable,language_id:r.id,meta_description:n.meta_description??"",meta_title:n.meta_title??"",payment_provider:n.payment_provider,price:n.price,prices:n.prices||{},product_media:[],product_type:n.product_type,sale_price:n.sale_price??null,sale_prices:n.sale_prices||{},short_description:n.short_description??"",sku:n.sku||Fo(n.title,a),slug:a,status:n.status,stock:n.stock,title:n.title,trial_period_days:h,trial_requires_payment_method:h>0?n.trial_requires_payment_method:!1,translation_group_id:u.translationGroupId,upc:n.upc??"",variation_attributes:[],variants:[]}),g=n.images??[],f=A({action:"CREATE PRODUCT",context:t,payload:{blocks:s,images:g,item:p,tool:"create_cms_product"},preview:{blockCount:s.length,descriptionLength:p.description_json?JSON.stringify(p.description_json).length:0,imageCount:g.length,languageCode:r.code,price:p.price,sku:p.sku,slug:a,status:p.status,stock:p.stock,title:p.title,translationGroupId:u.translationGroupId},subject:a});if(f)return f;let k=[],y=null;if(g.length>0)try{if(k=[...new Set(await Ot(g,t,n.title))],k.length===0)throw new Error("None of the provided images could be resolved to a media item.")}catch(b){y=b instanceof Error?b.message:String(b)}const w=await d(o,{...p,product_media:k.map(b=>({media_id:b}))});if(!w?.id)throw new Error("Failed to create product.");try{await Ze({blocks:s,contentType:"product",itemId:w.id,languageId:r.id,supabase:o})}catch(b){throw await et({contentType:"product",itemId:w.id,supabase:o}),b}return N(t,{contentType:"product",entityId:w.id,languageId:r.id,slug:a,title:n.title},a),t?.revalidatePath?.("/cms/products"),{blockCount:s.length,contentType:"product",editPath:tt("product",w.id),entityId:w.id,imageCount:k.length,...y?{imageError:y}:{},mutationExecuted:!0,slug:a,success:!0,title:n.title,translationGroupId:w.translation_group_id}}function lt(e){return e.trim().replace(/[\s-]+/g,"_").toLowerCase()}function jo(e,t){const n=typeof t=="string"?lt(t):t;return e==="product"?n==="public"||n==="publish"||n==="published"?"active":n:n==="public"||n==="active"||n==="publish"?"published":n}function Bo(e){const t=lt(e.field);return!!(e.startsAt||e.endsAt||t.includes("start")||t.includes("end")||t.includes("schedule")||t.includes("special_date"))}async function Lo(e,t,n){if(e==="price"||e==="sale_price"){if(t==null)return{[e]:null};const o=await It(n);return{[e]:qt(Number(t),o)}}if(e==="prices"||e==="sale_prices"){const o=await It(n);return{[e]:Xn(t,o)}}return e==="description_json"?{description_json:nn(t)}:{[e]:t}}function qo(e,t){const n=lt(e.field),o=n==="status"?jo(t.contentType,e.value):e.value,a={description:"description_json",feature_image:"feature_image_id",feature_image_id:"feature_image_id",language:"language_id",meta_description:"meta_description",meta_title:"meta_title",payment:"payment_provider",provider:"payment_provider",regular_price:"price",sale:"sale_price",sale_price:"sale_price",short_description:"short_description",taxable:"is_taxable",trial:"trial_period_days",trial_days:"trial_period_days",trial_payment_method_required:"trial_requires_payment_method",type:"product_type"}[n]||n;if(t.contentType!=="product"){if(!(t.contentType==="page"?Zt:en).has(a))throw new Error(`Field "${e.field}" cannot be updated for ${t.contentType}.`);return a==="status"&&Oe(t.contentType,o),{field:a,payload:{[a]:tn(a,o)}}}if(!new Set(["description_json","freemius_plan_id","freemius_product_id","is_taxable","language_id","meta_description","meta_title","payment_provider","price","prices","product_type","sale_price","sale_prices","short_description","sku","slug","status","stock","title","trial_period_days","trial_requires_payment_method","upc"]).has(a))throw new Error(`Field "${e.field}" cannot be updated for product.`);if(a==="status"&&Oe("product",o),(a==="price"||a==="sale_price")&&o!==null&&(typeof o!="number"||o<0))throw new Error(`${a} must be a non-negative number or null.`);if(a==="stock"&&(!Number.isInteger(o)||Number(o)<0))throw new Error("stock must be a non-negative integer.");if(a==="trial_period_days"&&(!Number.isInteger(o)||Number(o)<0))throw new Error("trial_period_days must be a non-negative integer.");if(a==="trial_requires_payment_method"&&typeof o!="boolean")throw new Error("trial_requires_payment_method must be a boolean.");return{field:a,payload:{[a]:o}}}async function ut(e,t){const n=le.parse(e);if(Bo(n))return{message:"Scheduled product specials are not supported by the current product schema yet. I can set or clear sale_price now, but not start/end dates.",mutationExecuted:!1,success:!1,unsupported:!0};const o=await me(n,t),r=qo(n,o),a=r.field;let s=r.payload;if(a==="language_id"&&typeof s.language_id=="string"){const m=await W(z(t),s.language_id);s={...s,language_id:m.id}}const c=A({action:"UPDATE FIELD",context:t,payload:{contentType:o.contentType,entityId:o.item.id,field:a,payload:s,tool:"update_cms_item_field"},preview:{contentType:o.contentType,field:a,from:o.item[a],slug:o.item.slug,title:o.item.title,to:s[a]},subject:`${o.contentType} ${o.item.slug||o.item.id} ${a}`});if(c)return c;if(o.contentType==="product"){const m=z(t),h=await Lo(a,s[a],m),{data:p,error:g}=await m.from("products").update({...h,updated_at:new Date().toISOString()}).eq("id",o.item.id).select("id, language_id, slug, status, title").single();if(g||!p)throw new Error(`Failed to update product: ${_(g)}`);return N(t,{contentType:"product",entityId:String(p.id),languageId:p.language_id,slug:p.slug,title:p.title},p.slug),{contentType:"product",entityId:p.id,field:a,mutationExecuted:!0,slug:p.slug,success:!0,updatedFields:[a]}}a==="feature_image_id"&&typeof s.feature_image_id=="string"&&(s={...s,feature_image_id:await de(s.feature_image_id,t,typeof o.item.title=="string"?o.item.title:void 0)});const u=o.contentType==="page"?"pages":"posts",{data:d,error:l}=await z(t).from(u).update({...s,updated_at:new Date().toISOString()}).eq("id",o.item.id).select("id, language_id, slug, status, title").single();if(l||!d)throw new Error(`Failed to update ${o.contentType}: ${_(l)}`);return N(t,{contentType:o.contentType,entityId:Number(d.id),languageId:d.language_id,slug:d.slug,title:d.title},d.slug),{contentType:o.contentType,entityId:d.id,field:a,mutationExecuted:!0,slug:d.slug,success:!0,updatedFields:[a]}}async function on(e,t){const n=Ge.parse(e),o=await me(n,t);if(o.contentType==="product")return{affectedCount:1,collectionPath:xt("product"),contentType:"product",item:o.item,navigationLinkCount:0,publicPaths:o.item.slug?[`/product/${o.item.slug}`]:[],targetIds:[o.item.id]};const r=o.contentType==="page"?"pages":"posts",{data:a,error:s}=await z(t).from(r).select("id, slug, title, translation_group_id").eq("translation_group_id",o.item.translation_group_id);if(s)throw new Error(`Failed to inspect related ${o.contentType}s: ${_(s)}`);const c=Array.isArray(a)?a:[],u=c.map(p=>o.contentType==="page"?p.slug==="home"?"/":`/${p.slug}`:`/article/${p.slug}`).filter(Boolean),d=new Set(u),{data:l,error:m}=await z(t).from("navigation_items").select("id, url");if(m)throw new Error(`Failed to inspect related navigation links: ${_(m)}`);const h=(Array.isArray(l)?l:[]).filter(p=>d.has(p.url)).length;return{affectedCount:c.length,collectionPath:xt(o.contentType),contentType:o.contentType,item:o.item,navigationLinkCount:h,publicPaths:u,targetIds:c.map(p=>p.id)}}function rn(e){const t=e.item.title||e.item.slug||"selected item",n=e.item.slug?` (${e.item.slug})`:"";if(e.contentType==="product")return`Delete product "${t}"${n}.`;const o=[`${P(e.affectedCount,"language version")}`,e.navigationLinkCount>0?`${P(e.navigationLinkCount,"navigation link")}`:null].filter(Boolean);return`Delete ${e.contentType} "${t}"${n}, including ${o.join(" and ")}.`}async function an(e,t){const n=await on(e,t);return{...Lt({action:`DELETE ${n.contentType}`,payload:{affectedCount:n.affectedCount,contentType:n.contentType,targetIds:n.targetIds,tool:"delete_cms_item"},preview:{affectedCount:n.affectedCount,collectionPath:n.collectionPath,contentType:n.contentType,navigationLinkCount:n.navigationLinkCount,publicPaths:n.publicPaths,slug:n.item.slug,summary:rn(n),title:n.item.title},subject:`${n.item.id} ${n.item.slug||""}`}),preparedDelete:!0}}async function dt(e,t){const n=ue.parse(e),o=await on(n,t),r=A({action:`DELETE ${o.contentType}`,context:t,payload:{affectedCount:o.affectedCount,contentType:o.contentType,targetIds:o.targetIds,tool:"delete_cms_item"},preview:{affectedCount:o.affectedCount,collectionPath:o.collectionPath,contentType:o.contentType,navigationLinkCount:o.navigationLinkCount,publicPaths:o.publicPaths,slug:o.item.slug,summary:rn(o),title:o.item.title},subject:`${o.item.id} ${o.item.slug||""}`});if(r)return r;const a=z(t);if(o.contentType==="product"){const{error:c}=await a.from("products").delete().eq("id",o.item.id);if(c)throw new Error(`Failed to delete product: ${_(c)}`)}else{for(const d of o.publicPaths)await a.from("navigation_items").delete().eq("url",d);const c=o.contentType==="page"?"pages":"posts",{error:u}=await a.from(c).delete().eq("translation_group_id",o.item.translation_group_id);if(u)throw new Error(`Failed to delete ${o.contentType}: ${_(u)}`)}const s=t?.revalidatePath??He();return s&&(s(o.collectionPath),s("/cms/navigation"),o.publicPaths.forEach(c=>s(c))),{affectedCount:o.affectedCount,collectionPath:o.collectionPath,contentType:o.contentType,mutationExecuted:!0,redirectPath:o.collectionPath,success:!0}}async function St(e,t){switch(e.tool){case"create_cms_page":return Ee(e.input,t);case"create_cms_post":return $e(e.input,t);case"create_cms_product":return ct(e.input,t);case"delete_cms_item":return dt(e.input,t);case"update_cms_item_field":return ut(e.input,t);case"update_content_block":return it(e.input,t);case"insert_content_block":return at(e.input,t);case"update_current_cms_fields":return rt(e.input,t);case"update_footer":return ot(e.input,t);case"update_navigation_bar":return nt(e.input,t);case"update_section_column_block":return st(e.input,t);case"set_content_images":return ht(e.input,t)}}function Ro(e,t){if(e.tool!=="create_cms_page"&&e.tool!=="create_cms_post"&&e.tool!=="create_cms_product"||e.input.translationGroupId||!e.input.languageCode)return e;const n=t[e.tool];return n?{...e,input:{...e.input,translationGroupId:n}}:e}function vt(e){return e==="create_cms_page"?"page":e==="create_cms_post"?"post":"product"}function Mo(e,t,n){if(e.tool!=="set_content_images")return e;const o=e.input;if(o.entityId!==void 0)return e;const r=o.slug?t.get(`${o.contentType||"product"}:${L(o.slug)}`):n;return r?{...e,input:{...o,contentType:r.contentType,entityId:r.entityId}}:e}async function sn(e,t){const n=Ke.parse(e),o=new Set(n.actions.filter(p=>p.tool==="create_cms_page"||p.tool==="create_cms_post"||p.tool==="create_cms_product").map(p=>{const g=p.input;return`${vt(p.tool)}:${L(g.slug||g.title||"")}`})),r=p=>{if(p.tool!=="set_content_images")return!1;const g=p.input;return g.slug?o.has(`${g.contentType||"product"}:${L(g.slug)}`):o.size>0};if(!t?.skipConfirmation){const p=[];for(const k of n.actions){if(r(k)){const w=k.input;p.push(`Set ${P(w.images.length,"image")} on the ${w.slug?`"${w.slug}"`:"new"} item created in this plan.`);continue}const y=await St(k,{...t,latestUserMessage:null});if(!y||typeof y!="object")return{message:`Could not prepare action ${p.length+1}.`,mutationExecuted:!1,success:!1};if(y.success===!1||y.unsupported===!0)return y;y.requiresConfirmation===!0&&y.preview?p.push(Wn(k.tool,y.preview)):p.push(`Run ${k.tool.replace(/_/g," ")}.`)}const g=n.summary||`Complete ${P(n.actions.length,"CMS action")}.`,f=A({action:"EXECUTE CMS ACTION PLAN",context:t,payload:{actions:n.actions,tool:"execute_cms_action_plan"},preview:{actionCount:n.actions.length,actionSummaries:p,summary:g},subject:`${n.actions.length} actions`});if(f)return f}const a={...t,skipConfirmation:!0},s=[];let c=!1,u=null,d=null;const l={},m=new Map;let h=null;for(const[p,g]of n.actions.entries()){const f=Mo(Ro(g,l),m,h),k=await St(f,a);if(s.push({output:k,tool:f.tool}),k&&typeof k=="object"){const y=k;if(y.mutationExecuted===!0&&(c=!0),!u&&typeof y.editPath=="string"&&(u=y.editPath),typeof y.redirectPath=="string"&&(d=y.redirectPath),(f.tool==="create_cms_page"||f.tool==="create_cms_post"||f.tool==="create_cms_product")&&(typeof y.translationGroupId=="string"&&(l[f.tool]=y.translationGroupId),y.entityId!==void 0&&y.entityId!==null)){const w=vt(f.tool),b={contentType:w,entityId:y.entityId};h=b,typeof y.slug=="string"&&m.set(`${w}:${y.slug}`,b)}if(y.success===!1||y.unsupported===!0)return{actionCount:n.actions.length,failedActionIndex:p,failedTool:f.tool,message:typeof y.message=="string"?y.message:`Action ${p+1} failed.`,mutationExecuted:c,results:s,success:!1,...u?{editPath:u}:{},...d?{redirectPath:d}:{}}}}return{actionCount:n.actions.length,editPath:d?void 0:u??void 0,mutationExecuted:c,redirectPath:d??void 0,results:s,success:!0,summary:n.summary??null}}const pt=i.z.strictObject({maxChars:i.z.number().int().min(500).max(2e4).default(8e3).describe("Maximum characters of readable body text to return."),url:i.z.string().trim().min(1).max(2048).refine(e=>/^https?:\/\//i.test(e),"URL must start with http:// or https://.")}),Do=12e3,Et=2e6;function $t(e){const t=e.trim().toLowerCase().replace(/\.$/,"").replace(/^\[|\]$/g,"");if(!t||t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal")||t==="metadata.google.internal"||t==="0.0.0.0"||t==="::1"||t.startsWith("fe80:")||t.startsWith("fc")||t.startsWith("fd"))return!0;const n=t.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(n){const o=Number(n[1]),r=Number(n[2]);if(o===10||o===127||o===0||o===192&&r===168||o===169&&r===254||o===172&&r>=16&&r<=31)return!0}return!1}function he(e){return e.replace(/<[^>]+>/g," ").replace(/&nbsp;/gi," ").replace(/&amp;/gi,"&").replace(/&lt;/gi,"<").replace(/&gt;/gi,">").replace(/&quot;/gi,'"').replace(/&#39;/gi,"'").replace(/\s+/g," ").trim()}function Go(e){return e.trim().replace(/&amp;/gi,"&").replace(/&#38;/g,"&").replace(/&quot;/gi,'"').replace(/&#39;/g,"'")}const cn=/\.(avif|gif|jpe?g|png|webp)(?:[?#]|$)/i,ln=/(?:^|[/_-])(?:sprite|icon|favicon|logo|placeholder|pixel|spacer|blank|avatar|badge|flag|loader|spinner|1x1|transparent|watermark|payment|visa|mastercard|paypal|amex|social|share|facebook|twitter|instagram|youtube|pinterest|linkedin)(?:[/_.-]|$)/i;function Te(e,t){if(typeof e!="string")return null;const n=Go(e);if(!n||n.startsWith("data:"))return null;try{const o=new URL(n,t);return o.protocol!=="http:"&&o.protocol!=="https:"?null:o.toString()}catch{return null}}function Ko(e){let t=null;for(const n of e.split(",")){const o=n.trim().split(/\s+/),r=o[0];if(!r)continue;const a=o[1]||"",s=a.match(/^(\d+(?:\.\d+)?)w$/i),c=a.match(/^(\d+(?:\.\d+)?)x$/i),u=s?Number(s[1]):c?Number(c[1])*1e3:1;(!t||u>t.weight)&&(t={url:r,weight:u})}return t?.url??null}function F(e,t){const n=e.match(new RegExp(`\\b${t}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`,"i"));return n?n[1]??n[2]??n[3]??null:null}function Ho(e,t){const n=[],o=[],r=(c,u)=>{if(typeof c=="string"){const d=Te(c,t);d&&u.push(d);return}if(Array.isArray(c)){for(const d of c)r(d,u);return}c&&typeof c=="object"&&(r(c.url,u),r(c.contentUrl,u))},a=(c,u)=>{if(u>8||!c||typeof c!="object")return;if(Array.isArray(c)){for(const p of c)a(p,u+1);return}const d=c,l=d["@type"],h=(Array.isArray(l)?l:[l]).filter(p=>typeof p=="string").map(p=>p.toLowerCase()).some(p=>p==="product"||p==="productgroup"||p==="itempage");"image"in d&&r(d.image,h?n:o);for(const p of Object.values(d))a(p,u+1)},s=e.matchAll(/<script\b[^>]*type\s*=\s*["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi);for(const c of s){const u=(c[1]||"").trim();if(u)try{a(JSON.parse(u),0)}catch{}}return[...n,...o]}const un=/(?:^|[/_-])(?:thumbnails?|thumbs?|small|mini)(?:[/_.-]|$)/i;function dn(e){try{const{pathname:t}=new URL(e);return decodeURIComponent(t.slice(t.lastIndexOf("/")+1)).toLowerCase()||null}catch{return null}}function Vo(e,t){const n=new Map;for(const o of e.matchAll(/<a\b[^>]*>/gi)){const r=Te(F(o[0],"href"),t);if(!r||!cn.test(r)||un.test(r)||ln.test(r))continue;const a=dn(r);a&&!n.has(a)&&n.set(a,r)}return n}function Wo(e,t){const n=[...Ho(e,t)],o=[/<meta\b[^>]*\b(?:property|name)\s*=\s*["'](?:og:image:secure_url|og:image:url|og:image)["'][^>]*>/gi,/<meta\b[^>]*\b(?:property|name)\s*=\s*["'](?:twitter:image:src|twitter:image)["'][^>]*>/gi,/<meta\b[^>]*\bitemprop\s*=\s*["']image["'][^>]*>/gi,/<link\b[^>]*\brel\s*=\s*["']image_src["'][^>]*>/gi];for(const l of o)for(const m of e.matchAll(l)){const h=m[0],p=Te(F(h,"content")||F(h,"href"),t);p&&n.push(p)}const r=[];for(const l of e.matchAll(/<img\b[^>]*>/gi)){const m=l[0],h=F(m,"srcset")||F(m,"data-srcset"),p=[h?Ko(h):null,F(m,"src"),F(m,"data-src"),F(m,"data-original"),F(m,"data-lazy-src"),F(m,"data-image")];let g=null;for(const k of p)if(g=Te(k,t),g)break;if(!g||ln.test(g))continue;const f=Number(F(m,"width"));Number.isFinite(f)&&f>0&&f<200||r.push(g)}const a=l=>cn.test(l);n.push(...r.filter(a),...r.filter(l=>!a(l)));const s=Vo(e,t),c=l=>{if(!un.test(l))return l;const m=dn(l);return m&&s.get(m)||l},u=new Set,d=[];for(const l of n){const m=c(l);if(!u.has(m)&&(u.add(m),d.push(m),d.length>=12))break}return{images:d,mainImage:d[0]??null}}function Jo(e,t,n){const o=e.replace(/<script\b[\s\S]*?<\/script>/gi," ").replace(/<style\b[\s\S]*?<\/style>/gi," ").replace(/<noscript\b[\s\S]*?<\/noscript>/gi," ").replace(/<svg\b[\s\S]*?<\/svg>/gi," "),{images:r,mainImage:a}=Wo(e,n),s=e.match(/<title\b[^>]*>([\s\S]*?)<\/title>/i),c=e.match(/<meta[^>]+name=["']description["'][^>]*content=["']([^"']*)["'][^>]*>/i)||e.match(/<meta[^>]+content=["']([^"']*)["'][^>]*name=["']description["'][^>]*>/i),u=[...o.matchAll(/<h([1-3])\b[^>]*>([\s\S]*?)<\/h\1>/gi)].map(m=>he(m[2])).filter(Boolean).slice(0,40),d=o.match(/<body\b[^>]*>([\s\S]*?)<\/body>/i),l=he(d?.[1]??o);return{description:c?he(c[1]):"",headings:u,images:r,mainImage:a,text:l.slice(0,t),title:s?he(s[1]):"",truncated:l.length>t}}async function pn(e){const t=pt.parse(e);let n;try{n=new URL(t.url)}catch{return{message:`"${t.url}" is not a valid URL.`,success:!1,url:t.url}}if(n.protocol!=="http:"&&n.protocol!=="https:")return{message:"Only http and https URLs can be fetched.",success:!1,url:t.url};if($t(n.hostname))return{message:"Refusing to fetch a local, private, or internal address.",success:!1,url:t.url};const o=new AbortController,r=setTimeout(()=>o.abort(),Do);try{const a=await fetch(n.toString(),{headers:{accept:"text/html,application/xhtml+xml,text/plain","user-agent":"NextBlockCortexAI/1.0 (+https://nextblock.dev)"},redirect:"follow",signal:o.signal});if(!a.ok)return{message:`The URL responded with HTTP ${a.status}.`,status:a.status,success:!1,url:t.url};const s=a.url||n.toString();try{if($t(new URL(s).hostname))return{message:"The URL redirected to a blocked internal address.",success:!1,url:t.url}}catch{}const c=a.headers.get("content-type")||"";if(!/text\/html|text\/plain|application\/xhtml/i.test(c))return{contentType:c,message:`The URL is not an HTML or text page (content-type: ${c||"unknown"}).`,success:!1,url:t.url};const u=await a.text(),d=u.length>Et?u.slice(0,Et):u,l=Jo(d,t.maxChars,s);return!l.text&&!l.title?{message:"The URL returned no readable text content.",success:!1,url:t.url}:{description:l.description,finalUrl:s,headings:l.headings,images:l.images,mainImage:l.mainImage,success:!0,text:l.text,title:l.title,truncated:l.truncated,url:t.url}}catch(a){return{message:a instanceof Error&&(a.name==="AbortError"||/abort/i.test(a.message))?"Fetching the URL timed out.":`Failed to fetch the URL: ${_(a)}`,success:!1,url:t.url}}finally{clearTimeout(r)}}const mt=i.z.strictObject({count:i.z.number().int().min(1).max(15).default(6),orientation:i.z.enum(["landscape","portrait","square"]).optional().describe("Preferred image orientation. Use landscape for hero/section backgrounds."),query:i.z.string().trim().min(2).max(200).describe('What the photos should depict, e.g. "herbal supplements".')}),Yo=12e3;async function Ae(e){let t=null,n=null;if(e)try{const{CORTEX_AI_PEXELS_SETTING_KEY:r,CORTEX_AI_UNSPLASH_SETTING_KEY:a,decryptStoredOpenRouterApiKey:s}=await Promise.resolve().then(()=>require("./ai-config.cjs.js")),c=l=>{if(!l)return null;try{const m=s(l);return typeof m=="string"&&m.trim()?m.trim():null}catch{return null}},{data:u}=await e.from("site_settings").select("key, value").in("key",[r,a]),d=Array.isArray(u)?u:[];t=c(d.find(l=>l.key===r)?.value),n=c(d.find(l=>l.key===a)?.value)}catch{}t||(t=process.env.PEXELS_API_KEY?.trim()||null),n||(n=process.env.UNSPLASH_ACCESS_KEY?.trim()||null);const o=[];return t&&o.push({apiKey:t,provider:"pexels"}),n&&o.push({apiKey:n,provider:"unsplash"}),o}async function Xo(e){return(await Ae(e))[0]??null}async function Qo(e){if(e)try{const{CORTEX_AI_UNSPLASH_APP_NAME_SETTING_KEY:t}=await Promise.resolve().then(()=>require("./ai-config.cjs.js")),{data:n}=await e.from("site_settings").select("value").eq("key",t).maybeSingle(),o=n?.value;if(typeof o=="string"&&o.trim())return o.trim()}catch{}return process.env.UNSPLASH_APP_NAME?.trim()||null}async function At(e,t){const n=new AbortController,o=setTimeout(()=>n.abort(),Yo);try{const r=await fetch(e,{headers:t,signal:n.signal});if(!r.ok)throw new Error(`Stock photo provider responded with HTTP ${r.status}.`);return await r.json()}finally{clearTimeout(o)}}function ye(e){const t=Number(e);return Number.isFinite(t)&&t>0?t:null}function je(e,t){if(!E(e))return;const n=o=>{E(o)&&o.provider==="unsplash"&&typeof o.downloadLocation=="string"&&o.downloadLocation.trim()&&t.add(o.downloadLocation.trim())};if(n(e.attribution),E(e.background)&&E(e.background.image)&&n(e.background.image.attribution),Array.isArray(e.column_blocks)){for(const o of e.column_blocks)if(Array.isArray(o))for(const r of o)E(r)&&je(r.content,t)}if(Array.isArray(e.slides))for(const o of e.slides)je(o,t)}async function ge(e,t){try{const n=new Set;for(const a of e)je(a?.content,n);if(n.size===0)return;const r=(await Ae(t)).find(a=>a.provider==="unsplash");if(!r)return;await Promise.all([...n].map(a=>fetch(a,{headers:{Authorization:`Client-ID ${r.apiKey}`}}).catch(()=>{})))}catch{}}async function Zo(e,t,n){const o=new URLSearchParams({per_page:String(t.count),query:t.query});if(t.orientation&&o.set("orientation",t.orientation),e.provider==="pexels"){const a=await At(`https://api.pexels.com/v1/search?${o.toString()}`,{Authorization:e.apiKey});return(Array.isArray(a?.photos)?a.photos:[]).map(s=>{const c=typeof s?.photographer=="string"?s.photographer:null;return{alt:typeof s?.alt=="string"&&s.alt.trim()?s.alt.trim():t.query,credit:c?`Photo by ${c} on Pexels`:"Photo on Pexels",downloadLocation:null,height:ye(s?.height),photographer:c,photographerUrl:typeof s?.photographer_url=="string"?s.photographer_url:null,provider:"pexels",sourceUrl:typeof s?.url=="string"?s.url:null,thumbnailUrl:s?.src?.medium||s?.src?.large||null,url:s?.src?.large2x||s?.src?.large||s?.src?.original||null,width:ye(s?.width)}}).filter(s=>typeof s.url=="string")}const r=await At(`https://api.unsplash.com/search/photos?${o.toString()}`,{Authorization:`Client-ID ${e.apiKey}`});return(Array.isArray(r?.results)?r.results:[]).map(a=>{const s=typeof a?.user?.name=="string"?a.user.name:null;return{alt:typeof a?.alt_description=="string"&&a.alt_description.trim()||typeof a?.description=="string"&&a.description.trim()||t.query,credit:s?`Photo by ${s} on Unsplash`:"Photo on Unsplash",downloadLocation:typeof a?.links?.download_location=="string"?a.links.download_location:null,height:ye(a?.height),photographer:s,photographerUrl:typeof a?.user?.links?.html=="string"?a.user.links.html:null,provider:"unsplash",sourceUrl:typeof a?.links?.html=="string"?a.links.html:null,thumbnailUrl:a?.urls?.small||a?.urls?.thumb||null,url:a?.urls?.regular||a?.urls?.full||a?.urls?.raw||null,utmSource:n||null,width:ye(a?.width)}}).filter(a=>typeof a.url=="string")}async function mn(e,t){const n=mt.parse(e),o=await Ae(t?.supabase);if(o.length===0)return{message:"No stock photo provider is configured. Add a free Pexels or Unsplash API key in /cms/settings/cortex-ai (or set PEXELS_API_KEY / UNSPLASH_ACCESS_KEY).",photos:[],success:!1};const r=o.some(c=>c.provider==="unsplash")?await Qo(t?.supabase):null,a=[];let s=null;for(const c of o){a.push(c.provider);try{const u=await Zo(c,n,r);if(u.length>0)return{attemptedProviders:a,photos:u,provider:c.provider,query:n.query,success:!0,usageGuidance:c.provider==="unsplash"?'Unsplash photos: keep them hotlinked (use `url` as external_url; never save an Unsplash photo to the media library) and attribute each one — copy the photo\'s attribution fields into the image content\'s `attribution` (photographer, photographerUrl, sourceUrl, downloadLocation, utmSource, provider "unsplash"). The site renders the "Photo by … on Unsplash" credit from `attribution` automatically, so do NOT also copy the credit into `caption` (leave caption empty unless you have a genuine descriptive caption).':'Set the image content\'s `attribution` (photographer, photographerUrl, sourceUrl, provider "pexels"). The site renders the "Photo by … on Pexels" credit from `attribution` automatically, so do NOT also copy the credit into `caption` (leave caption empty unless you have a genuine descriptive caption). Pexels attribution is appreciated but optional.'}}catch(u){s=u}}return{attemptedProviders:a,message:s?`Stock photo search failed across ${a.join(", ")}: ${_(s)}`:`No matching stock photos found for "${n.query}".`,photos:[],success:!1}}const gt=H.extend({blocks:i.z.array(oe).min(1).max(20),meta:i.z.strictObject({meta_description:i.z.string().max(500).nullable().optional(),meta_title:i.z.string().max(160).nullable().optional(),slug:i.z.string().trim().min(1).max(300).optional(),status:i.z.enum(["draft","published","archived"]).optional(),title:i.z.string().trim().min(1).max(300).optional()}).partial().optional()}),er=["custom_canonical","excerpt","feature_image_id","label","language_id","meta_description","meta_title","published_at","slug","status","subtitle","title","translation_group_id"];function tr(e){const t={};for(const n of er)n in e&&e[n]!==void 0&&(t[n]=e[n]);return t}function nr(e,t){if(!t)return null;const n=e==="page"?t==="home"?"/":`/${t}`:`/article/${t}`;return`/api/draft/start?path=${encodeURIComponent(n)}`}async function gn(e,t){const n=gt.parse(e),o=z(t),r=We(t),a=await me(n,t);if(a.contentType==="product")throw new Error("rewrite_page_draft supports pages and posts only. Products use description_json, not page blocks.");const s=a.contentType,c=Number(a.item.id);if(!Number.isInteger(c)||c<=0)throw new Error("Could not resolve a valid page/post id for the draft rewrite.");const u=Number(a.item.language_id);if(!Number.isInteger(u)||u<=0)throw new Error("The target page/post is missing a language id.");const l=ve(n.blocks,void 0,void 0,t).map((x,v)=>({block_type:x.block_type,content:x.content,language_id:u,order:v,page_id:s==="page"?c:null,post_id:s==="post"?c:null,product_id:null})),m=tr(a.item);if(n.meta)for(const[x,v]of Object.entries(n.meta))v!==void 0&&(m[x]=v);const h=jt(typeof m.slug=="string"?m.slug:a.item.slug),p=typeof m.title=="string"&&m.title.trim()?m.title:String(a.item.title||h||"Untitled"),g=s==="page"?`/cms/pages/${c}/edit`:`/cms/posts/${c}/edit`,f=nr(s,h),y=A({action:"REWRITE DRAFT",context:t,payload:{blocks:l,meta:m,parent_id:c,parent_type:s,tool:"rewrite_page_draft"},preview:{blockCount:l.length,contentType:s,slug:h,summary:`Stage a Live Draft that replaces the ${s} "${p}" with ${P(l.length,"new block")}. Nothing goes live until you review the draft and click Publish (which also saves a revision snapshot).`,title:p},subject:`${s}-${c}`});if(y)return y;const w=Number(a.item.version)||1,{error:b}=await o.from("content_drafts").delete().eq("parent_type",s).eq("parent_id",c);if(b)throw new Error(`Failed to clear the existing draft: ${_(b)}`);const{error:I}=await o.from("content_drafts").insert({author_id:r,base_version:w,blocks:l,meta:m,parent_id:c,parent_type:s});if(I)throw new Error(`Failed to save the draft: ${_(I)}`);return ge(l,o),N(t,{contentType:s,entityId:c,slug:h},h),{blockCount:l.length,contentType:s,draftPreviewPath:f,editPath:g,entityId:c,isDraft:!0,mutationExecuted:!0,slug:h,success:!0,title:p}}const or=new Set(["alt_text","author_name","author_title","caption","html_content","label","placeholder","quote","submit_button_text","success_message","text","text_content","title"]);function Be(e,t,n){if(!e)return e;if(Object.prototype.hasOwnProperty.call(t,e))return t[e];const o=e.trim();if(o!==e&&Object.prototype.hasOwnProperty.call(t,o))return e.replace(o,t[o]);let r=e;for(const[a,s]of n)a&&r.includes(a)&&(r=r.split(a).join(s));return r}function Le(e,t,n){if(Array.isArray(e))return e.map(o=>Le(o,t,n));if(e&&typeof e=="object"){const o={};for(const[r,a]of Object.entries(e))typeof a=="string"&&or.has(r)?o[r]=Be(a,t,n):a&&typeof a=="object"?o[r]=Le(a,t,n):o[r]=a;return o}return e}const ft=i.z.strictObject({targetLanguageCode:i.z.string().trim().min(2).max(80).describe('Target language code or name, e.g. "fr" or "French".'),title:i.z.string().trim().min(1).max(300).optional().describe("Translated page title (defaults to translating the source title)."),translations:i.z.record(i.z.string(),i.z.string()).describe('Map of every visible source string to its translation, e.g. { "Explore Our Products": "Explorez nos produits" }. Include headings, paragraph text, button labels, image alt text, captions, and form labels.')});async function fn(e,t){const n=ft.parse(e),o=V(t);if(o.contentType==="product")throw new Error("translate_page supports pages and posts only.");const r=z(t),a=Ve(o),s=o.contentType==="page"?"pages":"posts",c=o.contentType==="page"?"page_id":"post_id",{data:u,error:d}=await r.from(s).select("*").eq("id",a).single();if(d||!u)throw new Error(`Could not read the source ${o.contentType} to translate: ${_(d)}`);const{data:l,error:m}=await r.from("blocks").select("id, block_type, content, order").eq(c,a);if(m)throw new Error(`Could not read the source blocks: ${_(m)}`);const h=(Array.isArray(l)?l:[]).slice().sort((T,$)=>Number(T.order)-Number($.order));if(h.length===0)throw new Error(`The source ${o.contentType} has no content blocks to translate.`);const p=n.translations||{},g=Object.entries(p).filter(([T])=>!!T).sort((T,$)=>$[0].length-T[0].length),f=h.map((T,$)=>({blockType:T.block_type,content:Le(D(T.content),p,g),order:$})),k=await Se(r,n.targetLanguageCode),y=String(u.title||""),w=n.title||Be(y,p,g)||y||"Untitled",b=T=>typeof T=="string"&&T.trim()?Be(T,p,g):void 0,I=L(w)||u.slug||"translated-page",x={blocks:f,feature_image_id:u.feature_image_id??void 0,languageCode:k.code,meta_description:b(u.meta_description),meta_title:b(u.meta_title),slug:I,status:"published",title:w,translationGroupId:u.translation_group_id||void 0},v=o.contentType==="post"?{...x,excerpt:b(u.excerpt),label:b(u.label),published_at:u.published_at??new Date().toISOString(),subtitle:b(u.subtitle)}:x,j=A({action:"TRANSLATE",context:t,payload:{createInput:v,sourceId:u.id,tool:"translate_page"},preview:{blockCount:f.length,contentType:o.contentType,languageCode:k.code,slug:x.slug,status:x.status,summary:`Publish a ${k.code.toUpperCase()} translation of "${y}" — it goes live immediately, linked to the original ${o.contentType}, at /${x.slug} with ${P(f.length,"translated block")}.`,title:w},subject:`translate ${o.contentType} ${u.id} to ${k.code}`});if(j)return j;const q={...t,skipConfirmation:!0};return{...o.contentType==="post"?await $e(v,q):await Ee(v,q),isTranslation:!0,languageCode:k.code}}async function ht(e,t){const n=re.parse(e),o=n.entityId!==void 0||!!n.slug||!!n.title,r=z(t);let a,s;if(o){const g=await me({contentType:n.contentType,entityId:n.entityId,slug:n.slug,title:n.title},t),f=g.item;s=f.id,a={contentType:g.contentType,entityId:s,slug:typeof f.slug=="string"?f.slug:"",title:typeof f.title=="string"?f.title:""}}else a=V(t),s=ze(a);const c=a.title||a.slug||"current item",u=a.contentType==="product",d=A({action:"SET IMAGES",context:t,payload:{contentType:a.contentType,entityId:String(s),images:n.images,tool:"set_content_images"},preview:{contentType:a.contentType,imageCount:n.images.length,slug:a.slug,summary:u?`Set ${P(n.images.length,"image")} on product "${c}" (the first becomes the main product image, the rest the gallery).`:`Set the feature image on the ${a.contentType} "${c}".`,title:a.title},subject:`set images on ${a.contentType} ${String(s)}`});if(d)return d;const l=await Ot(n.images,t,c);if(l.length===0)throw new Error("None of the provided images could be resolved to a media item.");if(u){const{data:g,error:f}=await r.from("products").select("id, slug, language_id, title").eq("id",s).maybeSingle();if(f||!g)throw new Error(`Could not load the product to set images: ${_(f)}`);const k=await Mn({mediaIds:l,productId:s,supabase:r});return await Ce({patch:({meta:y})=>Array.isArray(y.product_media)?{meta:{...y,product_media:k.map((w,b)=>({media_id:w,sort_order:b}))}}:{},productId:s,supabase:r}),N(t,{contentType:"product",entityId:String(s),languageId:g.language_id,slug:g.slug,title:g.title},g.slug),t?.revalidatePath?.("/cms/products"),{contentType:"product",entityId:s,imageCount:k.length,mutationExecuted:!0,slug:g.slug,success:!0}}const m=a.contentType==="page"?"pages":"posts",{data:h,error:p}=await r.from(m).update({feature_image_id:l[0],updated_at:new Date().toISOString()}).eq("id",s).select("id, language_id, slug, status, title").single();if(p||!h)throw new Error(`Failed to set the feature image: ${_(p)}`);return N(t,a,h.slug),{contentType:a.contentType,entityId:s,extraImagesIgnored:l.length-1,imageCount:1,mutationExecuted:!0,slug:h.slug,success:!0}}function rr(e){return{...hn.createCortexDatabaseAgentTools(e),...yn.createCortexCustomBlockTools(e),fetch_ecommerce_stats:C.tool({description:"Fetch quantitative ecommerce statistics and reports from the database. Use this to answer questions about revenue, order counts, order status counts such as pending or trial, and top-selling products over a time range. This tool is read-only and does not require confirmation.",execute:t=>Xt(t,e),inputSchema:Re,strict:!0}),read_current_cms_item:C.tool({description:"Read the CMS item currently being edited. Requires pageContext and returns page/post/product metadata plus page/post block summaries or content.",execute:t=>Qt(t,e),inputSchema:De,strict:!0}),search_documentation:C.tool({description:"Search the NextBlock documentation database and return concise source snippets for factual CMS guidance.",execute:t=>Yt(t,e),inputSchema:xe,strict:!0}),fetch_url_content:C.tool({description:"Fetch an external web page and return its title, meta description, headings, body text, AND its images: `mainImage` (the page's subject image — schema.org Product image, else og:image, else the best in-body <img>) plus a ranked `images` list, all as absolute URLs. Read-only, no confirmation. Use this first whenever the user references an external URL to copy, adapt, clone, or draw inspiration from. To reuse the source page's image, pass `mainImage` straight into create_cms_product `images` or a page/post `feature_image_id` — it is imported into the media library automatically. Never invent an image URL: if `mainImage` is null, the page had none.",execute:t=>pn(t),inputSchema:pt,strict:!0}),search_stock_photos:C.tool({description:"Find relevant, free, high-quality stock photos (Unsplash/Pexels) for page imagery. Returns a list of photos each with a direct image `url`, `width`, `height`, `alt`, and `photographer`. Read-only, zero cost. Use the returned `url` directly as an image block's external_url or a section image background's image.external_url when building or revamping pages, so layouts show real photos instantly. Set orientation \"landscape\" for hero/section backgrounds.",execute:t=>mn(t,e),inputSchema:mt,strict:!0}),rewrite_page_draft:C.tool({description:'Replace ALL blocks of an existing page or post with a brand-new set of blocks, staged as a Live Draft (content_drafts) that the user previews before publishing. Use this for whole-page redesigns/rewrites such as "rewrite my home page with 5 sections". Provide the complete new list of top-level blocks in `blocks` (usually section blocks for a landing/home page, each with nested heading/text/button blocks). Nothing goes live until the user publishes the draft, and publishing auto-creates a revision snapshot so the change is reversible. Mutating: first returns a confirmation phrase; only stages the draft after the user replies with the exact phrase.',execute:t=>gn(t,e),inputSchema:gt,strict:!0}),translate_page:C.tool({description:'Translate the CURRENT page or post into another language. This copies the source page\'s entire structure, layout, and images automatically and links the new page to the original as a translation — you ONLY supply the text translations. Provide targetLanguageCode (e.g. "fr") and a `translations` map of every visible source string to its translation (headings, paragraph text, button labels, image alt text, captions, form labels). Do NOT rebuild the layout or call search_stock_photos for a translation. Requires an open page/post. Mutating: first returns a confirmation phrase; only creates the translation after exact confirmation.',execute:t=>fn(t,e),inputSchema:ft,strict:!0}),set_content_images:C.tool({description:"Set the feature image for a page or post, or the image gallery for a product. Pass `images`: a list of image URLs (e.g. `mainImage` from fetch_url_content or `url` values from search_stock_photos) and/or existing media library IDs. External URLs are imported into the media library automatically — NEVER put an image URL directly into feature_image_id. The FIRST image becomes the feature image (pages/posts) or the main product image (products); for a product the remaining images become its gallery in order (this REPLACES the product's current images). Targets the currently open page/post/product by default; to target any other item (for example a product you just created from the dashboard) pass contentType plus slug, entityId, or title — no open editor needed. Mutating: first returns a confirmation phrase; only applies after exact confirmation.",execute:t=>ht(t,e),inputSchema:re,strict:!0}),create_cms_page:C.tool({description:"Create a new CMS page with metadata and optional validated page blocks. Mutating: first returns a confirmation phrase; only executes after the user replies with the exact phrase. For translations, pass translationGroupId from the source page/post/product context so the new language is linked to the same backend translation group. For contact pages, provide contactEmail or a form block with recipient_email and fields.",execute:t=>Ee(t,e),inputSchema:ae,strict:!0}),create_cms_post:C.tool({description:"Create a new CMS post with metadata and optional validated post blocks. Mutating: first returns a confirmation phrase; only executes after the user replies with the exact phrase. For translations, pass translationGroupId from the source post context so the new language is linked to the same backend translation group.",execute:t=>$e(t,e),inputSchema:se,strict:!0}),create_cms_product:C.tool({description:"Create a new draft-capable product, complete with its images and its body copy in ONE call. Pass `images` to set the main product image and gallery (external https URLs are imported into the media library automatically — use `mainImage` from fetch_url_content to reuse a source page's photo). Pass `blocks` to build the product's \"Product Description Blocks\" — the SAME block vocabulary and section-based design rules as create_cms_page, rendered on the public product page. This is the richest product body and is what you should produce whenever the user asks to copy or write real product content. Also pass `short_description` for the one-line summary shown on product cards. `description_html` is a plain-HTML fallback body used only when no blocks are supplied. Defaults missing fields safely: physical Stripe product, generated SKU, price 0, stock 0, taxable, draft. `price` is in major units (25 = $25.00). For translations, pass translationGroupId from the source product context. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>ct(t,e),inputSchema:ce,strict:!0}),delete_cms_item:C.tool({description:"Delete a resolved page, post, or product after exact confirmation. Pages/posts delete all translations in the translation group and related navigation links. Mutating: refuses unless the latest user message includes the exact confirmation phrase.",execute:t=>dt(t,e),inputSchema:ue,strict:!0}),prepare_delete_cms_item:C.tool({description:"Inspect the page, post, or product that would be deleted and return the exact confirmation phrase. This tool does not mutate data.",execute:t=>an(t,e),inputSchema:Ge,strict:!0}),update_footer:C.tool({description:"Replace the public footer links and/or footer copyright settings for a locale. Use links for footer navigation and copyright for locale text templates. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>ot(t,e),inputSchema:Z,strict:!0}),update_content_block:C.tool({description:'Update the JSON content of an existing top-level page/post block that belongs to the current CMS edit context. Content is merged with the existing block before validation. For section blocks, add nested blocks with content.append_block or content.append_blocks using objects like { block_type: "button", content: { text: "Contact Us", url: "/contact" } }; existing column_blocks and layout fields are preserved. Mutating: first returns a confirmation phrase; only executes after exact confirmation.',execute:t=>it(t,e),inputSchema:te,strict:!0}),insert_content_block:C.tool({description:'Insert a new validated top-level page/post block before or after an existing block, or at the start/end. Use this for visible content additions like adding a rich text title and paragraph above a form. For "above the form", use position "before" with anchorBlockType "form" and blockType "text" containing html_content. Mutating: first returns a confirmation phrase; only executes after exact confirmation.',execute:t=>at(t,e),inputSchema:ie,strict:!0}),update_current_cms_fields:C.tool({description:"Update validated metadata fields on the current page, post, or product. For products, description_json must be a valid NextBlock editor document JSON object. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>rt(t,e),inputSchema:ee,strict:!0}),update_cms_item_field:C.tool({description:"Update one field on a page, post, or product, resolving by current edit context, id, slug, or exact title. Use this for requests like changing price, stock, title, slug, status, sale_price, or meta fields. Interpret public as published for pages/posts and active for products. Scheduled sale date ranges are not supported and will be refused without mutation. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>ut(t,e),inputSchema:le,strict:!0}),update_navigation_bar:C.tool({description:'Update the public header navigation bar for a locale. Use mode "append" when adding links while preserving existing navigation. Use mode "update" when renaming or changing an existing single link. Use mode "replace" only when the user asks to rebuild the complete header and you provide the full menu; destructive partial replacements are refused. Mutating: first returns a confirmation phrase; only executes after exact confirmation.',execute:t=>nt(t,e),inputSchema:Q,strict:!0}),update_section_column_block:C.tool({description:"Update the content of one existing nested block inside a section block that belongs to the current CMS edit context. This tool must not change the nested block type. To add a new nested block, update the parent section with update_content_block and preserve existing column_blocks. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>st(t,e),inputSchema:ne,strict:!0}),execute_cms_action_plan:C.tool({description:"Execute multiple CMS mutations as one confirmed plan. Use this whenever the user asks for more than one change in the same prompt, such as creating a page and adding a navigation link. First returns one combined confirmation preview and Confirm button; after confirmation, runs each action in order and stops on the first failure.",execute:t=>sn(t,e),inputSchema:Ke,strict:!0})}}exports.availableCortexAiBlockTypes=G;exports.buildVisibleContactIntroActionPlan=$n;exports.cortexAiPageContextSchema=Me;exports.createCmsPageInputSchema=ae;exports.createCmsPostInputSchema=se;exports.createCmsProductInputSchema=ce;exports.createCortexGlobalAgentTools=rr;exports.deleteCmsItemInputSchema=ue;exports.executeCmsActionPlan=sn;exports.executeCmsActionPlanInputSchema=Ke;exports.executeCreateCmsPage=Ee;exports.executeCreateCmsPost=$e;exports.executeCreateCmsProduct=ct;exports.executeDeleteCmsItem=dt;exports.executeFetchEcommerceStats=Xt;exports.executeFetchUrlContent=pn;exports.executeInsertContentBlock=at;exports.executePrepareDeleteCmsItem=an;exports.executeReadCurrentCmsItem=Qt;exports.executeRewritePageDraft=gn;exports.executeSearchDocumentation=Jt;exports.executeSearchDocumentationWithTimeout=Yt;exports.executeSearchStockPhotos=mn;exports.executeSetContentImages=ht;exports.executeTranslatePage=fn;exports.executeUpdateCmsItemField=ut;exports.executeUpdateContentBlock=it;exports.executeUpdateCurrentCmsFields=rt;exports.executeUpdateFooter=ot;exports.executeUpdateNavigationBar=nt;exports.executeUpdateSectionColumnBlock=st;exports.fetchEcommerceStatsInputSchema=Re;exports.fetchUrlContentInputSchema=pt;exports.insertContentBlockInputSchema=ie;exports.maybeTriggerStockPhotoDownloads=ge;exports.navigationItemInputSchema=qe;exports.prepareDeleteCmsItemInputSchema=Ge;exports.readCurrentCmsItemInputSchema=De;exports.resolveCortexAiStockPhotoProvider=Xo;exports.resolveCortexAiStockPhotoProviders=Ae;exports.rewritePageDraftInputSchema=gt;exports.searchDocumentationInputSchema=xe;exports.searchStockPhotosInputSchema=mt;exports.setContentImagesInputSchema=re;exports.translatePageInputSchema=ft;exports.updateCmsItemFieldInputSchema=le;exports.updateContentBlockInputSchema=te;exports.updateCurrentCmsFieldsInputSchema=ee;exports.updateFooterInputSchema=Z;exports.updateNavigationBarInputSchema=Q;exports.updateSectionColumnBlockInputSchema=ne;
15
+ `).eq("orders.status","paid"):null;m&&(c&&m.eq("orders.currency",c),a&&m.gte("orders.paid_at",a.toISOString()),s&&m.lte("orders.paid_at",s.toISOString()));const p=n.timeRange!=="all_time"&&(n.reportType==="orders"||u)?o.from("orders").select("id, status, currency"):null;p&&c&&p.eq("currency",c);const[{data:f,error:g},{data:b,error:_},k]=await Promise.all([d,m??Promise.resolve({data:[],error:null}),p??Promise.resolve({data:null,error:null})]);if(g)throw new Error(`Failed to fetch ecommerce stats: ${y(g)}`);if(_)throw new Error(`Failed to fetch ecommerce stats: ${y(_)}`);if(k.error)throw new Error(`Failed to fetch ecommerce stats: ${y(k.error)}`);const w=Array.isArray(f)?f:[],T=Array.isArray(b)?b:[],I=vt(w),E=Array.isArray(k.data)?k.data:null,A=E?vt(E):null,B={};for(const C of T){const $=Array.isArray(C.orders)?C.orders[0]:C.orders,j=String($?.currency||c||"unknown").toUpperCase();B[j]=(B[j]??0)+ee(C.quantity)*ee(C.price_at_purchase)/100}const Q={currency:c??null,currencyFiltered:!!c,orderStatusCounts:I,paidOrderCount:I.paid??0,query:n.query,reportType:n.reportType,revenueByCurrency:B,timeRange:n.timeRange,totalOrders:w.length,totalRevenue:Object.values(B).reduce((C,$)=>C+$,0)};if(A&&(Q.allTimeOrderStatusCounts=A),u&&(Q.matchingOrderStatus={allTimeCount:A?.[u]??I[u]??0,count:I[u]??0,status:u,timeRange:n.timeRange}),n.reportType==="products"||n.reportType==="revenue"||n.reportType==="general"){const C={};for(const $ of T){const j=Array.isArray($.products)?$.products[0]:$.products;if(!j?.id)continue;const Z=j.id;C[Z]||(C[Z]={id:Z,quantity:0,revenue:0,title:j.title,type:j.product_type}),C[Z].quantity+=ee($.quantity),C[Z].revenue+=ee($.quantity)*ee($.price_at_purchase)/100}Q.topProducts=Object.values(C).sort(($,j)=>j.revenue-$.revenue).slice(0,10)}return{report:Q,success:!0}}async function en(e,t){const n=Ke.parse(e),o=z(t),r=Y(t),a=q(r),s=r.contentType==="page"?"pages":r.contentType==="post"?"posts":"products",{data:c,error:u}=await o.from(s).select("*").eq("id",a).single();if(u||!c)throw new Error(`Failed to read current ${r.contentType}: ${y(u)}`);let d=[];if(n.includeBlocks){const l=r.contentType==="page"?"page_id":r.contentType==="post"?"post_id":"product_id",{data:m,error:h}=await o.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq(l,a);if(h)throw new Error(`Failed to read current ${r.contentType} blocks: ${y(h)}`);d=(Array.isArray(m)?m:[]).slice().sort((p,f)=>Number(p.order)-Number(f.order)).map(p=>io(p,n.includeBlockContent))}return{blocks:d,context:r,item:c,success:!0}}const tn=new Set(["feature_image_id","language_id","meta_description","meta_title","slug","status","title"]),nn=new Set(["excerpt","feature_image_id","label","language_id","meta_description","meta_title","published_at","slug","status","subtitle","title"]),No=new Set(["description_json","language_id","meta_description","meta_title","short_description","slug","status","title"]),Uo=new Set(["excerpt","feature_image_id","label","meta_description","meta_title","published_at","short_description","subtitle"]);function Fo(e){return e==="page"?tn:e==="post"?nn:No}function on(e,t){return Uo.has(e)&&t===""?null:t}function je(e,t){if(typeof t!="string")return;const n=e==="product"?["active","archived","draft"]:["archived","draft","published"];if(!n.includes(t))throw new Error(`Status "${t}" is not valid for ${e}. Allowed statuses: ${n.join(", ")}.`)}function Oo(e,t){const n=Fo(t.contentType),o={};for(const[r,a]of Object.entries(e))if(a!==void 0){if(!n.has(r))throw new Error(`Field "${r}" cannot be updated for ${t.contentType} content.`);r==="status"&&je(t.contentType,a),o[r]=on(r,a)}return o}async function at(e,t){const n=oe.parse(e),o=z(t),r=Y(t),a=q(r),s=Oo(n.fields,r),c=Object.keys(s);if(c.length===0)throw new Error("update_current_cms_fields requires at least one supported field.");const u=P({action:"UPDATE CMS FIELDS",context:t,payload:{contentType:r.contentType,entityId:a,fields:s,tool:"update_current_cms_fields"},preview:{contentType:r.contentType,entityId:a,fields:c,slug:r.slug,title:r.title},subject:`${r.contentType} ${String(a)}`});if(u)return u;const d=await W(t,r.contentType,a);typeof s.feature_image_id=="string"&&(s.feature_image_id=await ge(s.feature_image_id,t,typeof r.title=="string"?r.title:void 0));const l=r.contentType==="page"?"pages":r.contentType==="post"?"posts":"products",{data:m,error:h}=await o.from(l).update({...s,updated_at:new Date().toISOString()}).eq("id",a).select("id, language_id, slug, status, title").single();if(h||!m)throw new Error(`Failed to update current ${r.contentType}: ${y(h)}`);return await G(t,r.contentType,a,d),U(t,r,m.slug),{contentType:r.contentType,entityId:a,mutationExecuted:!0,slug:m.slug,success:!0,updatedFields:c}}async function st(e,t){const n=re.parse(e),o=z(t),r=Y(t),{data:a,error:s}=await o.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq("id",n.blockId).single();if(s||!a)throw new Error(`Failed to read block ${n.blockId}: ${y(s)}`);Dt(a,r);const c=Ie(a.block_type,`Block ${n.blockId}`);Gt(n.blockType,c,`Block ${n.blockId}`);const u=fe(a.content,`Block ${n.blockId}`),d=ro(c,u,n.content,t);D(c,d,`Block ${n.blockId}`,t);const l=P({action:"UPDATE CONTENT BLOCK",context:t,payload:{blockId:n.blockId,blockType:c,content:d,tool:"update_content_block"},preview:{blockId:n.blockId,blockType:c,contentType:r.contentType,entityId:q(r)},subject:`${c} block ${n.blockId}`});if(l)return l;const m=await W(t,r.contentType,q(r)),{data:h,error:p}=await o.from("blocks").update({content:d,updated_at:new Date().toISOString()}).eq("id",n.blockId).select("id, block_type, order").single();if(p||!h)throw new Error(`Failed to update block ${n.blockId}: ${y(p)}`);return await G(t,r.contentType,q(r),m),await ve({patch:({blocks:f})=>({blocks:f.map(g=>String(g?.id)===String(n.blockId)?{...g,content:d}:g)}),productId:a.product_id,supabase:o}),ye([{content:d}],o),U(t,r),{blockId:h.id,blockType:h.block_type,contentUpdated:!0,mutationExecuted:!0,success:!0}}async function ct(e,t){const n=ce.parse(e),o=z(t),r=await he(n,t),a=r.contentType==="product"?r.item.id:Number(r.item.id),s=r.contentType==="page"?"page_id":r.contentType==="post"?"post_id":"product_id",c=async()=>{const{data:T,error:I}=await o.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq(s,a);if(I)throw new Error(`Failed to read ${r.contentType} blocks: ${y(I)}`);return(Array.isArray(T)?T:[]).sort((E,A)=>Number(E.order)-Number(A.order))},u=T=>{if(n.position==="start")return 0;if(n.position==="end"){const A=T.map(B=>Number(B.order)).filter(Number.isFinite);return A.length>0?Math.max(...A)+1:0}const I=n.anchorBlockId?T.find(A=>Number(A.id)===n.anchorBlockId):n.anchorBlockType?T.find(A=>A.block_type===n.anchorBlockType):null;if(!I)throw new Error(n.anchorBlockType?`Could not find a ${n.anchorBlockType} block to insert ${n.position}.`:`Could not find block ${n.anchorBlockId} to insert ${n.position}.`);const E=Number(I.order);return n.position==="before"?E:E+1},d=ze(n.block,0,t),l=await c(),m=u(l),h={contentType:r.contentType,entityId:r.item.id,languageId:r.item.language_id,slug:r.item.slug,title:r.item.title,translationGroupId:r.item.translation_group_id},p=P({action:"INSERT CONTENT BLOCK",context:t,payload:{block:d,order:m,target:{contentType:r.contentType,id:r.item.id,slug:r.item.slug},tool:"insert_content_block"},preview:{anchorBlockId:n.anchorBlockId,anchorBlockType:n.anchorBlockType,blockType:d.block_type,contentType:r.contentType,entityId:r.item.id,position:n.position,slug:r.item.slug,summary:`Insert ${d.block_type} block ${n.position} ${n.anchorBlockType?`the first ${n.anchorBlockType} block`:n.anchorBlockId?`block ${n.anchorBlockId}`:"the content"} on ${r.contentType} "${r.item.title||r.item.slug}".`,title:r.item.title},subject:`${d.block_type} block on ${r.contentType} ${r.item.id}`});if(p)return p;const f=await c(),g=u(f),b=f.filter(T=>Number(T.order)>=g).sort((T,I)=>Number(I.order)-Number(T.order)),_=await W(t,r.contentType,a);for(const T of b){const{error:I}=await o.from("blocks").update({order:Number(T.order)+1,updated_at:new Date().toISOString()}).eq("id",T.id);if(I)throw new Error(`Failed to shift block ${T.id}: ${y(I)}`)}const{data:k,error:w}=await o.from("blocks").insert({block_type:d.block_type,content:d.content,language_id:r.item.language_id,order:g,page_id:r.contentType==="page"?a:null,post_id:r.contentType==="post"?a:null,product_id:r.contentType==="product"?a:null}).select("id, block_type, order").single();if(w||!k)throw new Error(`Failed to insert content block: ${y(w)}`);return r.contentType==="product"&&await ve({patch:({blocks:T})=>({blocks:[...T.map(I=>Number(I?.order)>=g?{...I,order:Number(I.order)+1}:I),{block_type:d.block_type,content:d.content,id:k.id,language_id:r.item.language_id,order:g,page_id:null,post_id:null,product_id:a}].sort((I,E)=>Number(I.order)-Number(E.order))}),productId:a,supabase:o}),await G(t,r.contentType,a,_),ye([d],o),U(t,h),{blockId:k.id,blockType:k.block_type,contentType:r.contentType,entityId:r.item.id,mutationExecuted:!0,order:k.order,success:!0}}async function lt(e,t){const n=ie.parse(e),o=z(t),r=Y(t),{data:a,error:s}=await o.from("blocks").select("id, page_id, post_id, product_id, language_id, block_type, content, order").eq("id",n.parentBlockId).single();if(s||!a)throw new Error(`Failed to read parent block ${n.parentBlockId}: ${y(s)}`);Dt(a,r);const c=Ie(a.block_type,`Parent block ${n.parentBlockId}`);if(c!=="section")throw new Error(`Parent block ${n.parentBlockId} must be a section block, not "${c}".`);const u=fe(a.content,`Parent block ${n.parentBlockId}`);D(c,u,`Parent block ${n.parentBlockId}`,t);const l=u.column_blocks?.[n.columnIndex]?.[n.blockIndex];if(!l)throw new Error(`Nested block was not found at column ${n.columnIndex}, index ${n.blockIndex}.`);const m=Ie(l.block_type,`Nested block ${n.columnIndex}:${n.blockIndex}`);Gt(n.blockType,m,`Nested block ${n.columnIndex}:${n.blockIndex}`),D(m,n.content,`Nested block ${n.columnIndex}:${n.blockIndex}`,t);const h=u.column_blocks.map((k,w)=>w===n.columnIndex?k.map((T,I)=>I===n.blockIndex?{...T,content:n.content}:T):k),p={...u,column_blocks:h};D(c,p,`Updated parent block ${n.parentBlockId}`,t);const f=P({action:"UPDATE NESTED BLOCK",context:t,payload:{blockIndex:n.blockIndex,columnIndex:n.columnIndex,content:n.content,nestedBlockType:m,parentBlockId:n.parentBlockId,tool:"update_section_column_block"},preview:{blockIndex:n.blockIndex,columnIndex:n.columnIndex,nestedBlockType:m,parentBlockId:n.parentBlockId,parentBlockType:c},subject:`${m} nested block ${n.columnIndex}:${n.blockIndex}`});if(f)return f;const g=await W(t,r.contentType,q(r)),{data:b,error:_}=await o.from("blocks").update({content:p,updated_at:new Date().toISOString()}).eq("id",n.parentBlockId).select("id, block_type").single();if(_||!b)throw new Error(`Failed to update parent block ${n.parentBlockId}: ${y(_)}`);return await ve({patch:({blocks:k})=>({blocks:k.map(w=>String(w?.id)===String(n.parentBlockId)?{...w,content:p}:w)}),productId:a.product_id,supabase:o}),await G(t,r.contentType,q(r),g),U(t,r),{blockIndex:n.blockIndex,columnIndex:n.columnIndex,mutationExecuted:!0,nestedBlockType:m,parentBlockId:b.id,parentBlockType:b.block_type,success:!0}}async function Ae(e,t){const n=le.parse(e),o=z(t),r=Ye(t),a=await Ee(o,n.languageCode),s=R(n.slug||n.title),c=$e(n.blocks,n.contactEmail,n.title,t),u=await Ze({contentType:"page",languageId:a.id,slug:s,supabase:o});if(u)return u;const d=await et({contentType:"page",languageCode:a.code,languageId:a.id,suppliedTranslationGroupId:n.translationGroupId,supabase:o});if(d.result)return d.result;const l={blocks:c,item:{feature_image_id:n.feature_image_id??null,language_id:a.id,meta_description:n.meta_description??null,meta_title:n.meta_title??null,slug:s,status:n.status,title:n.title,translation_group_id:d.translationGroupId},tool:"create_cms_page"},m=P({action:"CREATE PAGE",context:t,payload:l,preview:{blockCount:c.length,languageCode:a.code,slug:s,status:n.status,title:n.title,translationGroupId:d.translationGroupId},subject:s});if(m)return m;const h=d.translationGroupId||Xe(),p=await ge(l.item.feature_image_id,t,n.title),{data:f,error:g}=await o.from("pages").insert({...l.item,author_id:r,feature_image_id:p,translation_group_id:h}).select("id, language_id, slug, status, title, translation_group_id").single();if(g||!f?.id)throw new Error(`Failed to create page: ${y(g)}`);try{await tt({blocks:c,contentType:"page",itemId:Number(f.id),languageId:a.id,supabase:o})}catch(b){throw await nt({contentType:"page",itemId:Number(f.id),supabase:o}),b}return U(t,{contentType:"page",entityId:Number(f.id),languageId:a.id,slug:s,title:n.title},s),t?.revalidatePath?.("/cms/pages"),{blockCount:c.length,contentType:"page",editPath:ot("page",f.id),entityId:f.id,mutationExecuted:!0,slug:s,success:!0,title:n.title,translationGroupId:f.translation_group_id}}async function Pe(e,t){const n=ue.parse(e),o=z(t),r=Ye(t),a=await Ee(o,n.languageCode),s=R(n.slug||n.title),c=$e(n.blocks,void 0,void 0,t),u=await Ze({contentType:"post",languageId:a.id,slug:s,supabase:o});if(u)return u;const d=await et({contentType:"post",languageCode:a.code,languageId:a.id,suppliedTranslationGroupId:n.translationGroupId,supabase:o});if(d.result)return d.result;const l=n.published_at&&!Number.isNaN(new Date(n.published_at).getTime())?new Date(n.published_at).toISOString():n.published_at??null,m={blocks:c,item:{excerpt:n.excerpt??null,feature_image_id:n.feature_image_id??null,label:n.label??null,language_id:a.id,meta_description:n.meta_description??null,meta_title:n.meta_title??null,published_at:l,slug:s,status:n.status,subtitle:n.subtitle??null,title:n.title,translation_group_id:d.translationGroupId},tool:"create_cms_post"},h=P({action:"CREATE POST",context:t,payload:m,preview:{blockCount:c.length,languageCode:a.code,slug:s,status:n.status,title:n.title,translationGroupId:d.translationGroupId},subject:s});if(h)return h;const p=d.translationGroupId||Xe(),f=await ge(m.item.feature_image_id,t,n.title),{data:g,error:b}=await o.from("posts").insert({...m.item,author_id:r,feature_image_id:f,translation_group_id:p}).select("id, language_id, slug, status, title, translation_group_id").single();if(b||!g?.id)throw new Error(`Failed to create post: ${y(b)}`);try{await tt({blocks:c,contentType:"post",itemId:Number(g.id),languageId:a.id,supabase:o})}catch(_){throw await nt({contentType:"post",itemId:Number(g.id),supabase:o}),_}return U(t,{contentType:"post",entityId:Number(g.id),languageId:a.id,slug:s,title:n.title},s),t?.revalidatePath?.("/cms/posts"),t?.revalidatePath?.("/articles"),{blockCount:c.length,contentType:"post",editPath:ot("post",g.id),entityId:g.id,mutationExecuted:!0,slug:s,success:!0,title:n.title,translationGroupId:g.translation_group_id}}function Bo(e,t){return(t||R(e)||"product").replace(/-/g,"").slice(0,24).toUpperCase()}function rn(e){if(e==null)return;if(typeof e=="string")return Ut.editorDocumentFromHtml(e)??void 0;const t=Array.isArray(e)?{content:e,type:"doc"}:v(e)&&e.type!=="doc"&&Array.isArray(e.content)?{...e,type:"doc"}:e,n=It().safeParse(t);if(!n.success){if(v(e)&&typeof e.type=="string"){const o=It().safeParse({content:[e],type:"doc"});if(o.success)return o.data}throw new Error(`Product description_json must be an editor document like { "type": "doc", "content": [ { "type": "paragraph", "content": [ { "type": "text", "text": "..." } ] } ] }, or simply an HTML string. Received: ${n.error.issues.map(o=>o.message).join("; ")}`)}return n.data}function jo(e){const t=r=>!!(r&&Array.isArray(r.content)&&r.content.length>0),n=rn(e.description_json);if(t(n))return n;const o=e.description_html?Ut.editorDocumentFromHtml(e.description_html):null;return t(o)?o:void 0}async function ut(e,t){const n=de.parse(e),o=z(t),r=await Ee(o,n.languageCode),a=R(n.slug||n.title),s=$e(n.blocks,void 0,void 0,t),c=await Ze({contentType:"product",languageId:r.id,slug:a,supabase:o});if(c)return c;const u=await et({contentType:"product",languageCode:r.code,languageId:r.id,suppliedTranslationGroupId:n.translationGroupId,supabase:o});if(u.result)return u.result;const{createProduct:d,productSchema:l}=await Vn(),h=n.product_type==="digital"&&n.payment_provider==="freemius"?n.trial_period_days:0,p=l.parse({description_json:jo(n),freemius_plan_id:n.freemius_plan_id||"",freemius_product_id:n.freemius_product_id||"",is_taxable:n.is_taxable,language_id:r.id,meta_description:n.meta_description??"",meta_title:n.meta_title??"",payment_provider:n.payment_provider,price:n.price,prices:n.prices||{},product_media:[],product_type:n.product_type,sale_price:n.sale_price??null,sale_prices:n.sale_prices||{},short_description:n.short_description??"",sku:n.sku||Bo(n.title,a),slug:a,status:n.status,stock:n.stock,title:n.title,trial_period_days:h,trial_requires_payment_method:h>0?n.trial_requires_payment_method:!1,translation_group_id:u.translationGroupId,upc:n.upc??"",variation_attributes:[],variants:[]}),f=n.images??[],g=P({action:"CREATE PRODUCT",context:t,payload:{blocks:s,images:f,item:p,tool:"create_cms_product"},preview:{blockCount:s.length,descriptionLength:p.description_json?JSON.stringify(p.description_json).length:0,imageCount:f.length,languageCode:r.code,price:p.price,sku:p.sku,slug:a,status:p.status,stock:p.stock,title:p.title,translationGroupId:u.translationGroupId},subject:a});if(g)return g;let b=[],_=null;if(f.length>0)try{if(b=[...new Set(await jt(f,t,n.title))],b.length===0)throw new Error("None of the provided images could be resolved to a media item.")}catch(w){_=w instanceof Error?w.message:String(w)}const k=await d(o,{...p,product_media:b.map(w=>({media_id:w}))});if(!k?.id)throw new Error("Failed to create product.");try{await tt({blocks:s,contentType:"product",itemId:k.id,languageId:r.id,supabase:o})}catch(w){throw await nt({contentType:"product",itemId:k.id,supabase:o}),w}return U(t,{contentType:"product",entityId:k.id,languageId:r.id,slug:a,title:n.title},a),t?.revalidatePath?.("/cms/products"),{blockCount:s.length,contentType:"product",editPath:ot("product",k.id),entityId:k.id,imageCount:b.length,..._?{imageError:_}:{},mutationExecuted:!0,slug:a,success:!0,title:n.title,translationGroupId:k.translation_group_id}}function dt(e){return e.trim().replace(/[\s-]+/g,"_").toLowerCase()}function Lo(e,t){const n=typeof t=="string"?dt(t):t;return e==="product"?n==="public"||n==="publish"||n==="published"?"active":n:n==="public"||n==="active"||n==="publish"?"published":n}function qo(e){const t=dt(e.field);return!!(e.startsAt||e.endsAt||t.includes("start")||t.includes("end")||t.includes("schedule")||t.includes("special_date"))}async function Ro(e,t,n){if(e==="price"||e==="sale_price"){if(t==null)return{[e]:null};const o=await Ct(n);return{[e]:Mt(Number(t),o)}}if(e==="prices"||e==="sale_prices"){const o=await Ct(n);return{[e]:Zn(t,o)}}return e==="description_json"?{description_json:rn(t)}:{[e]:t}}function Mo(e,t){const n=dt(e.field),o=n==="status"?Lo(t.contentType,e.value):e.value,a={description:"description_json",feature_image:"feature_image_id",feature_image_id:"feature_image_id",language:"language_id",meta_description:"meta_description",meta_title:"meta_title",payment:"payment_provider",provider:"payment_provider",regular_price:"price",sale:"sale_price",sale_price:"sale_price",short_description:"short_description",taxable:"is_taxable",trial:"trial_period_days",trial_days:"trial_period_days",trial_payment_method_required:"trial_requires_payment_method",type:"product_type"}[n]||n;if(t.contentType!=="product"){if(!(t.contentType==="page"?tn:nn).has(a))throw new Error(`Field "${e.field}" cannot be updated for ${t.contentType}.`);return a==="status"&&je(t.contentType,o),{field:a,payload:{[a]:on(a,o)}}}if(!new Set(["description_json","freemius_plan_id","freemius_product_id","is_taxable","language_id","meta_description","meta_title","payment_provider","price","prices","product_type","sale_price","sale_prices","short_description","sku","slug","status","stock","title","trial_period_days","trial_requires_payment_method","upc"]).has(a))throw new Error(`Field "${e.field}" cannot be updated for product.`);if(a==="status"&&je("product",o),(a==="price"||a==="sale_price")&&o!==null&&(typeof o!="number"||o<0))throw new Error(`${a} must be a non-negative number or null.`);if(a==="stock"&&(!Number.isInteger(o)||Number(o)<0))throw new Error("stock must be a non-negative integer.");if(a==="trial_period_days"&&(!Number.isInteger(o)||Number(o)<0))throw new Error("trial_period_days must be a non-negative integer.");if(a==="trial_requires_payment_method"&&typeof o!="boolean")throw new Error("trial_requires_payment_method must be a boolean.");return{field:a,payload:{[a]:o}}}async function pt(e,t){const n=pe.parse(e);if(qo(n))return{message:"Scheduled product specials are not supported by the current product schema yet. I can set or clear sale_price now, but not start/end dates.",mutationExecuted:!1,success:!1,unsupported:!0};const o=await he(n,t),r=Mo(n,o),a=r.field;let s=r.payload;if(a==="language_id"&&typeof s.language_id=="string"){const h=await X(z(t),s.language_id);s={...s,language_id:h.id}}const c=P({action:"UPDATE FIELD",context:t,payload:{contentType:o.contentType,entityId:o.item.id,field:a,payload:s,tool:"update_cms_item_field"},preview:{contentType:o.contentType,field:a,from:o.item[a],slug:o.item.slug,title:o.item.title,to:s[a]},subject:`${o.contentType} ${o.item.slug||o.item.id} ${a}`});if(c)return c;const u=await W(t,o.contentType,o.item.id);if(o.contentType==="product"){const h=z(t),p=await Ro(a,s[a],h),{data:f,error:g}=await h.from("products").update({...p,updated_at:new Date().toISOString()}).eq("id",o.item.id).select("id, language_id, slug, status, title").single();if(g||!f)throw new Error(`Failed to update product: ${y(g)}`);return U(t,{contentType:"product",entityId:String(f.id),languageId:f.language_id,slug:f.slug,title:f.title},f.slug),await G(t,"product",f.id,u),{contentType:"product",entityId:f.id,field:a,mutationExecuted:!0,slug:f.slug,success:!0,updatedFields:[a]}}a==="feature_image_id"&&typeof s.feature_image_id=="string"&&(s={...s,feature_image_id:await ge(s.feature_image_id,t,typeof o.item.title=="string"?o.item.title:void 0)});const d=o.contentType==="page"?"pages":"posts",{data:l,error:m}=await z(t).from(d).update({...s,updated_at:new Date().toISOString()}).eq("id",o.item.id).select("id, language_id, slug, status, title").single();if(m||!l)throw new Error(`Failed to update ${o.contentType}: ${y(m)}`);return U(t,{contentType:o.contentType,entityId:Number(l.id),languageId:l.language_id,slug:l.slug,title:l.title},l.slug),await G(t,o.contentType,l.id,u),{contentType:o.contentType,entityId:l.id,field:a,mutationExecuted:!0,slug:l.slug,success:!0,updatedFields:[a]}}async function an(e,t){const n=He.parse(e),o=await he(n,t);if(o.contentType==="product")return{affectedCount:1,collectionPath:xt("product"),contentType:"product",item:o.item,navigationLinkCount:0,publicPaths:o.item.slug?[`/product/${o.item.slug}`]:[],targetIds:[o.item.id]};const r=o.contentType==="page"?"pages":"posts",{data:a,error:s}=await z(t).from(r).select("id, slug, title, translation_group_id").eq("translation_group_id",o.item.translation_group_id);if(s)throw new Error(`Failed to inspect related ${o.contentType}s: ${y(s)}`);const c=Array.isArray(a)?a:[],u=c.map(p=>o.contentType==="page"?p.slug==="home"?"/":`/${p.slug}`:`/article/${p.slug}`).filter(Boolean),d=new Set(u),{data:l,error:m}=await z(t).from("navigation_items").select("id, url");if(m)throw new Error(`Failed to inspect related navigation links: ${y(m)}`);const h=(Array.isArray(l)?l:[]).filter(p=>d.has(p.url)).length;return{affectedCount:c.length,collectionPath:xt(o.contentType),contentType:o.contentType,item:o.item,navigationLinkCount:h,publicPaths:u,targetIds:c.map(p=>p.id)}}function sn(e){const t=e.item.title||e.item.slug||"selected item",n=e.item.slug?` (${e.item.slug})`:"";if(e.contentType==="product")return`Delete product "${t}"${n}.`;const o=[`${N(e.affectedCount,"language version")}`,e.navigationLinkCount>0?`${N(e.navigationLinkCount,"navigation link")}`:null].filter(Boolean);return`Delete ${e.contentType} "${t}"${n}, including ${o.join(" and ")}.`}async function cn(e,t){const n=await an(e,t);return{...Rt({action:`DELETE ${n.contentType}`,payload:{affectedCount:n.affectedCount,contentType:n.contentType,targetIds:n.targetIds,tool:"delete_cms_item"},preview:{affectedCount:n.affectedCount,collectionPath:n.collectionPath,contentType:n.contentType,navigationLinkCount:n.navigationLinkCount,publicPaths:n.publicPaths,slug:n.item.slug,summary:sn(n),title:n.item.title},subject:`${n.item.id} ${n.item.slug||""}`}),preparedDelete:!0}}async function mt(e,t){const n=me.parse(e),o=await an(n,t),r=P({action:`DELETE ${o.contentType}`,context:t,payload:{affectedCount:o.affectedCount,contentType:o.contentType,targetIds:o.targetIds,tool:"delete_cms_item"},preview:{affectedCount:o.affectedCount,collectionPath:o.collectionPath,contentType:o.contentType,navigationLinkCount:o.navigationLinkCount,publicPaths:o.publicPaths,slug:o.item.slug,summary:sn(o),title:o.item.title},subject:`${o.item.id} ${o.item.slug||""}`});if(r)return r;const a=z(t);if(o.contentType==="product"){const{error:c}=await a.from("products").delete().eq("id",o.item.id);if(c)throw new Error(`Failed to delete product: ${y(c)}`)}else{for(const d of o.publicPaths)await a.from("navigation_items").delete().eq("url",d);const c=o.contentType==="page"?"pages":"posts",{error:u}=await a.from(c).delete().eq("translation_group_id",o.item.translation_group_id);if(u)throw new Error(`Failed to delete ${o.contentType}: ${y(u)}`)}const s=t?.revalidatePath??We();return s&&(s(o.collectionPath),s("/cms/navigation"),o.publicPaths.forEach(c=>s(c))),{affectedCount:o.affectedCount,collectionPath:o.collectionPath,contentType:o.contentType,mutationExecuted:!0,redirectPath:o.collectionPath,success:!0}}async function Et(e,t){switch(e.tool){case"create_cms_page":return Ae(e.input,t);case"create_cms_post":return Pe(e.input,t);case"create_cms_product":return ut(e.input,t);case"delete_cms_item":return mt(e.input,t);case"update_cms_item_field":return pt(e.input,t);case"update_content_block":return st(e.input,t);case"insert_content_block":return ct(e.input,t);case"update_current_cms_fields":return at(e.input,t);case"update_footer":return it(e.input,t);case"update_navigation_bar":return rt(e.input,t);case"update_section_column_block":return lt(e.input,t);case"set_content_images":return _t(e.input,t)}}function Do(e,t){if(e.tool!=="create_cms_page"&&e.tool!=="create_cms_post"&&e.tool!=="create_cms_product"||e.input.translationGroupId||!e.input.languageCode)return e;const n=t[e.tool];return n?{...e,input:{...e.input,translationGroupId:n}}:e}function $t(e){return e==="create_cms_page"?"page":e==="create_cms_post"?"post":"product"}function Go(e,t,n){if(e.tool!=="set_content_images")return e;const o=e.input;if(o.entityId!==void 0)return e;const r=o.slug?t.get(`${o.contentType||"product"}:${R(o.slug)}`):n;return r?{...e,input:{...o,contentType:r.contentType,entityId:r.entityId}}:e}async function ln(e,t){const n=Ve.parse(e),o=new Set(n.actions.filter(p=>p.tool==="create_cms_page"||p.tool==="create_cms_post"||p.tool==="create_cms_product").map(p=>{const f=p.input;return`${$t(p.tool)}:${R(f.slug||f.title||"")}`})),r=p=>{if(p.tool!=="set_content_images")return!1;const f=p.input;return f.slug?o.has(`${f.contentType||"product"}:${R(f.slug)}`):o.size>0};if(!t?.skipConfirmation){const p=[];for(const b of n.actions){if(r(b)){const k=b.input;p.push(`Set ${N(k.images.length,"image")} on the ${k.slug?`"${k.slug}"`:"new"} item created in this plan.`);continue}const _=await Et(b,{...t,latestUserMessage:null});if(!_||typeof _!="object")return{message:`Could not prepare action ${p.length+1}.`,mutationExecuted:!1,success:!1};if(_.success===!1||_.unsupported===!0)return _;_.requiresConfirmation===!0&&_.preview?p.push(Yn(b.tool,_.preview)):p.push(`Run ${b.tool.replace(/_/g," ")}.`)}const f=n.summary||`Complete ${N(n.actions.length,"CMS action")}.`,g=P({action:"EXECUTE CMS ACTION PLAN",context:t,payload:{actions:n.actions,tool:"execute_cms_action_plan"},preview:{actionCount:n.actions.length,actionSummaries:p,summary:f},subject:`${n.actions.length} actions`});if(g)return g}const a={...t,skipConfirmation:!0},s=[];let c=!1,u=null,d=null;const l={},m=new Map;let h=null;for(const[p,f]of n.actions.entries()){const g=Go(Do(f,l),m,h),b=await Et(g,a);if(s.push({output:b,tool:g.tool}),b&&typeof b=="object"){const _=b;if(_.mutationExecuted===!0&&(c=!0),!u&&typeof _.editPath=="string"&&(u=_.editPath),typeof _.redirectPath=="string"&&(d=_.redirectPath),(g.tool==="create_cms_page"||g.tool==="create_cms_post"||g.tool==="create_cms_product")&&(typeof _.translationGroupId=="string"&&(l[g.tool]=_.translationGroupId),_.entityId!==void 0&&_.entityId!==null)){const k=$t(g.tool),w={contentType:k,entityId:_.entityId};h=w,typeof _.slug=="string"&&m.set(`${k}:${_.slug}`,w)}if(_.success===!1||_.unsupported===!0)return{actionCount:n.actions.length,failedActionIndex:p,failedTool:g.tool,message:typeof _.message=="string"?_.message:`Action ${p+1} failed.`,mutationExecuted:c,results:s,success:!1,...u?{editPath:u}:{},...d?{redirectPath:d}:{}}}}return{actionCount:n.actions.length,editPath:d?void 0:u??void 0,mutationExecuted:c,redirectPath:d??void 0,results:s,success:!0,summary:n.summary??null}}const gt=i.z.strictObject({maxChars:i.z.number().int().min(500).max(2e4).default(8e3).describe("Maximum characters of readable body text to return."),url:i.z.string().trim().min(1).max(2048).refine(e=>/^https?:\/\//i.test(e),"URL must start with http:// or https://.")}),Ko=12e3,At=2e6;function Pt(e){const t=e.trim().toLowerCase().replace(/\.$/,"").replace(/^\[|\]$/g,"");if(!t||t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal")||t==="metadata.google.internal"||t==="0.0.0.0"||t==="::1"||t.startsWith("fe80:")||t.startsWith("fc")||t.startsWith("fd"))return!0;const n=t.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(n){const o=Number(n[1]),r=Number(n[2]);if(o===10||o===127||o===0||o===192&&r===168||o===169&&r===254||o===172&&r>=16&&r<=31)return!0}return!1}function be(e){return e.replace(/<[^>]+>/g," ").replace(/&nbsp;/gi," ").replace(/&amp;/gi,"&").replace(/&lt;/gi,"<").replace(/&gt;/gi,">").replace(/&quot;/gi,'"').replace(/&#39;/gi,"'").replace(/\s+/g," ").trim()}function Ho(e){return e.trim().replace(/&amp;/gi,"&").replace(/&#38;/g,"&").replace(/&quot;/gi,'"').replace(/&#39;/g,"'")}const un=/\.(avif|gif|jpe?g|png|webp)(?:[?#]|$)/i,dn=/(?:^|[/_-])(?:sprite|icon|favicon|logo|placeholder|pixel|spacer|blank|avatar|badge|flag|loader|spinner|1x1|transparent|watermark|payment|visa|mastercard|paypal|amex|social|share|facebook|twitter|instagram|youtube|pinterest|linkedin)(?:[/_.-]|$)/i;function xe(e,t){if(typeof e!="string")return null;const n=Ho(e);if(!n||n.startsWith("data:"))return null;try{const o=new URL(n,t);return o.protocol!=="http:"&&o.protocol!=="https:"?null:o.toString()}catch{return null}}function Vo(e){let t=null;for(const n of e.split(",")){const o=n.trim().split(/\s+/),r=o[0];if(!r)continue;const a=o[1]||"",s=a.match(/^(\d+(?:\.\d+)?)w$/i),c=a.match(/^(\d+(?:\.\d+)?)x$/i),u=s?Number(s[1]):c?Number(c[1])*1e3:1;(!t||u>t.weight)&&(t={url:r,weight:u})}return t?.url??null}function O(e,t){const n=e.match(new RegExp(`\\b${t}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`,"i"));return n?n[1]??n[2]??n[3]??null:null}function Wo(e,t){const n=[],o=[],r=(c,u)=>{if(typeof c=="string"){const d=xe(c,t);d&&u.push(d);return}if(Array.isArray(c)){for(const d of c)r(d,u);return}c&&typeof c=="object"&&(r(c.url,u),r(c.contentUrl,u))},a=(c,u)=>{if(u>8||!c||typeof c!="object")return;if(Array.isArray(c)){for(const p of c)a(p,u+1);return}const d=c,l=d["@type"],h=(Array.isArray(l)?l:[l]).filter(p=>typeof p=="string").map(p=>p.toLowerCase()).some(p=>p==="product"||p==="productgroup"||p==="itempage");"image"in d&&r(d.image,h?n:o);for(const p of Object.values(d))a(p,u+1)},s=e.matchAll(/<script\b[^>]*type\s*=\s*["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi);for(const c of s){const u=(c[1]||"").trim();if(u)try{a(JSON.parse(u),0)}catch{}}return[...n,...o]}const pn=/(?:^|[/_-])(?:thumbnails?|thumbs?|small|mini)(?:[/_.-]|$)/i;function mn(e){try{const{pathname:t}=new URL(e);return decodeURIComponent(t.slice(t.lastIndexOf("/")+1)).toLowerCase()||null}catch{return null}}function Jo(e,t){const n=new Map;for(const o of e.matchAll(/<a\b[^>]*>/gi)){const r=xe(O(o[0],"href"),t);if(!r||!un.test(r)||pn.test(r)||dn.test(r))continue;const a=mn(r);a&&!n.has(a)&&n.set(a,r)}return n}function Yo(e,t){const n=[...Wo(e,t)],o=[/<meta\b[^>]*\b(?:property|name)\s*=\s*["'](?:og:image:secure_url|og:image:url|og:image)["'][^>]*>/gi,/<meta\b[^>]*\b(?:property|name)\s*=\s*["'](?:twitter:image:src|twitter:image)["'][^>]*>/gi,/<meta\b[^>]*\bitemprop\s*=\s*["']image["'][^>]*>/gi,/<link\b[^>]*\brel\s*=\s*["']image_src["'][^>]*>/gi];for(const l of o)for(const m of e.matchAll(l)){const h=m[0],p=xe(O(h,"content")||O(h,"href"),t);p&&n.push(p)}const r=[];for(const l of e.matchAll(/<img\b[^>]*>/gi)){const m=l[0],h=O(m,"srcset")||O(m,"data-srcset"),p=[h?Vo(h):null,O(m,"src"),O(m,"data-src"),O(m,"data-original"),O(m,"data-lazy-src"),O(m,"data-image")];let f=null;for(const b of p)if(f=xe(b,t),f)break;if(!f||dn.test(f))continue;const g=Number(O(m,"width"));Number.isFinite(g)&&g>0&&g<200||r.push(f)}const a=l=>un.test(l);n.push(...r.filter(a),...r.filter(l=>!a(l)));const s=Jo(e,t),c=l=>{if(!pn.test(l))return l;const m=mn(l);return m&&s.get(m)||l},u=new Set,d=[];for(const l of n){const m=c(l);if(!u.has(m)&&(u.add(m),d.push(m),d.length>=12))break}return{images:d,mainImage:d[0]??null}}function Xo(e,t,n){const o=e.replace(/<script\b[\s\S]*?<\/script>/gi," ").replace(/<style\b[\s\S]*?<\/style>/gi," ").replace(/<noscript\b[\s\S]*?<\/noscript>/gi," ").replace(/<svg\b[\s\S]*?<\/svg>/gi," "),{images:r,mainImage:a}=Yo(e,n),s=e.match(/<title\b[^>]*>([\s\S]*?)<\/title>/i),c=e.match(/<meta[^>]+name=["']description["'][^>]*content=["']([^"']*)["'][^>]*>/i)||e.match(/<meta[^>]+content=["']([^"']*)["'][^>]*name=["']description["'][^>]*>/i),u=[...o.matchAll(/<h([1-3])\b[^>]*>([\s\S]*?)<\/h\1>/gi)].map(m=>be(m[2])).filter(Boolean).slice(0,40),d=o.match(/<body\b[^>]*>([\s\S]*?)<\/body>/i),l=be(d?.[1]??o);return{description:c?be(c[1]):"",headings:u,images:r,mainImage:a,text:l.slice(0,t),title:s?be(s[1]):"",truncated:l.length>t}}async function gn(e){const t=gt.parse(e);let n;try{n=new URL(t.url)}catch{return{message:`"${t.url}" is not a valid URL.`,success:!1,url:t.url}}if(n.protocol!=="http:"&&n.protocol!=="https:")return{message:"Only http and https URLs can be fetched.",success:!1,url:t.url};if(Pt(n.hostname))return{message:"Refusing to fetch a local, private, or internal address.",success:!1,url:t.url};const o=new AbortController,r=setTimeout(()=>o.abort(),Ko);try{const a=await fetch(n.toString(),{headers:{accept:"text/html,application/xhtml+xml,text/plain","user-agent":"NextBlockCortexAI/1.0 (+https://nextblock.dev)"},redirect:"follow",signal:o.signal});if(!a.ok)return{message:`The URL responded with HTTP ${a.status}.`,status:a.status,success:!1,url:t.url};const s=a.url||n.toString();try{if(Pt(new URL(s).hostname))return{message:"The URL redirected to a blocked internal address.",success:!1,url:t.url}}catch{}const c=a.headers.get("content-type")||"";if(!/text\/html|text\/plain|application\/xhtml/i.test(c))return{contentType:c,message:`The URL is not an HTML or text page (content-type: ${c||"unknown"}).`,success:!1,url:t.url};const u=await a.text(),d=u.length>At?u.slice(0,At):u,l=Xo(d,t.maxChars,s);return!l.text&&!l.title?{message:"The URL returned no readable text content.",success:!1,url:t.url}:{description:l.description,finalUrl:s,headings:l.headings,images:l.images,mainImage:l.mainImage,success:!0,text:l.text,title:l.title,truncated:l.truncated,url:t.url}}catch(a){return{message:a instanceof Error&&(a.name==="AbortError"||/abort/i.test(a.message))?"Fetching the URL timed out.":`Failed to fetch the URL: ${y(a)}`,success:!1,url:t.url}}finally{clearTimeout(r)}}const ft=i.z.strictObject({count:i.z.number().int().min(1).max(15).default(6),orientation:i.z.enum(["landscape","portrait","square"]).optional().describe("Preferred image orientation. Use landscape for hero/section backgrounds."),query:i.z.string().trim().min(2).max(200).describe('What the photos should depict, e.g. "herbal supplements".')}),Qo=12e3;async function Ne(e){let t=null,n=null;if(e)try{const{CORTEX_AI_PEXELS_SETTING_KEY:r,CORTEX_AI_UNSPLASH_SETTING_KEY:a,decryptStoredOpenRouterApiKey:s}=await Promise.resolve().then(()=>require("./ai-config.cjs.js")),c=l=>{if(!l)return null;try{const m=s(l);return typeof m=="string"&&m.trim()?m.trim():null}catch{return null}},{data:u}=await e.from("site_settings").select("key, value").in("key",[r,a]),d=Array.isArray(u)?u:[];t=c(d.find(l=>l.key===r)?.value),n=c(d.find(l=>l.key===a)?.value)}catch{}t||(t=process.env.PEXELS_API_KEY?.trim()||null),n||(n=process.env.UNSPLASH_ACCESS_KEY?.trim()||null);const o=[];return t&&o.push({apiKey:t,provider:"pexels"}),n&&o.push({apiKey:n,provider:"unsplash"}),o}async function Zo(e){return(await Ne(e))[0]??null}async function er(e){if(e)try{const{CORTEX_AI_UNSPLASH_APP_NAME_SETTING_KEY:t}=await Promise.resolve().then(()=>require("./ai-config.cjs.js")),{data:n}=await e.from("site_settings").select("value").eq("key",t).maybeSingle(),o=n?.value;if(typeof o=="string"&&o.trim())return o.trim()}catch{}return process.env.UNSPLASH_APP_NAME?.trim()||null}async function Nt(e,t){const n=new AbortController,o=setTimeout(()=>n.abort(),Qo);try{const r=await fetch(e,{headers:t,signal:n.signal});if(!r.ok)throw new Error(`Stock photo provider responded with HTTP ${r.status}.`);return await r.json()}finally{clearTimeout(o)}}function ke(e){const t=Number(e);return Number.isFinite(t)&&t>0?t:null}function Le(e,t){if(!v(e))return;const n=o=>{v(o)&&o.provider==="unsplash"&&typeof o.downloadLocation=="string"&&o.downloadLocation.trim()&&t.add(o.downloadLocation.trim())};if(n(e.attribution),v(e.background)&&v(e.background.image)&&n(e.background.image.attribution),Array.isArray(e.column_blocks)){for(const o of e.column_blocks)if(Array.isArray(o))for(const r of o)v(r)&&Le(r.content,t)}if(Array.isArray(e.slides))for(const o of e.slides)Le(o,t)}async function ye(e,t){try{const n=new Set;for(const a of e)Le(a?.content,n);if(n.size===0)return;const r=(await Ne(t)).find(a=>a.provider==="unsplash");if(!r)return;await Promise.all([...n].map(a=>fetch(a,{headers:{Authorization:`Client-ID ${r.apiKey}`}}).catch(()=>{})))}catch{}}async function tr(e,t,n){const o=new URLSearchParams({per_page:String(t.count),query:t.query});if(t.orientation&&o.set("orientation",t.orientation),e.provider==="pexels"){const a=await Nt(`https://api.pexels.com/v1/search?${o.toString()}`,{Authorization:e.apiKey});return(Array.isArray(a?.photos)?a.photos:[]).map(s=>{const c=typeof s?.photographer=="string"?s.photographer:null;return{alt:typeof s?.alt=="string"&&s.alt.trim()?s.alt.trim():t.query,credit:c?`Photo by ${c} on Pexels`:"Photo on Pexels",downloadLocation:null,height:ke(s?.height),photographer:c,photographerUrl:typeof s?.photographer_url=="string"?s.photographer_url:null,provider:"pexels",sourceUrl:typeof s?.url=="string"?s.url:null,thumbnailUrl:s?.src?.medium||s?.src?.large||null,url:s?.src?.large2x||s?.src?.large||s?.src?.original||null,width:ke(s?.width)}}).filter(s=>typeof s.url=="string")}const r=await Nt(`https://api.unsplash.com/search/photos?${o.toString()}`,{Authorization:`Client-ID ${e.apiKey}`});return(Array.isArray(r?.results)?r.results:[]).map(a=>{const s=typeof a?.user?.name=="string"?a.user.name:null;return{alt:typeof a?.alt_description=="string"&&a.alt_description.trim()||typeof a?.description=="string"&&a.description.trim()||t.query,credit:s?`Photo by ${s} on Unsplash`:"Photo on Unsplash",downloadLocation:typeof a?.links?.download_location=="string"?a.links.download_location:null,height:ke(a?.height),photographer:s,photographerUrl:typeof a?.user?.links?.html=="string"?a.user.links.html:null,provider:"unsplash",sourceUrl:typeof a?.links?.html=="string"?a.links.html:null,thumbnailUrl:a?.urls?.small||a?.urls?.thumb||null,url:a?.urls?.regular||a?.urls?.full||a?.urls?.raw||null,utmSource:n||null,width:ke(a?.width)}}).filter(a=>typeof a.url=="string")}async function fn(e,t){const n=ft.parse(e),o=await Ne(t?.supabase);if(o.length===0)return{message:"No stock photo provider is configured. Add a free Pexels or Unsplash API key in /cms/settings/cortex-ai (or set PEXELS_API_KEY / UNSPLASH_ACCESS_KEY).",photos:[],success:!1};const r=o.some(c=>c.provider==="unsplash")?await er(t?.supabase):null,a=[];let s=null;for(const c of o){a.push(c.provider);try{const u=await tr(c,n,r);if(u.length>0)return{attemptedProviders:a,photos:u,provider:c.provider,query:n.query,success:!0,usageGuidance:c.provider==="unsplash"?'Unsplash photos: keep them hotlinked (use `url` as external_url; never save an Unsplash photo to the media library) and attribute each one — copy the photo\'s attribution fields into the image content\'s `attribution` (photographer, photographerUrl, sourceUrl, downloadLocation, utmSource, provider "unsplash"). The site renders the "Photo by … on Unsplash" credit from `attribution` automatically, so do NOT also copy the credit into `caption` (leave caption empty unless you have a genuine descriptive caption).':'Set the image content\'s `attribution` (photographer, photographerUrl, sourceUrl, provider "pexels"). The site renders the "Photo by … on Pexels" credit from `attribution` automatically, so do NOT also copy the credit into `caption` (leave caption empty unless you have a genuine descriptive caption). Pexels attribution is appreciated but optional.'}}catch(u){s=u}}return{attemptedProviders:a,message:s?`Stock photo search failed across ${a.join(", ")}: ${y(s)}`:`No matching stock photos found for "${n.query}".`,photos:[],success:!1}}const ht=J.extend({blocks:i.z.array(ae).min(1).max(20),meta:i.z.strictObject({meta_description:i.z.string().max(500).nullable().optional(),meta_title:i.z.string().max(160).nullable().optional(),slug:i.z.string().trim().min(1).max(300).optional(),status:i.z.enum(["draft","published","archived"]).optional(),title:i.z.string().trim().min(1).max(300).optional()}).partial().optional()}),nr=["custom_canonical","excerpt","feature_image_id","label","language_id","meta_description","meta_title","published_at","slug","status","subtitle","title","translation_group_id"];function or(e){const t={};for(const n of nr)n in e&&e[n]!==void 0&&(t[n]=e[n]);return t}function rr(e,t){if(!t)return null;const n=e==="page"?t==="home"?"/":`/${t}`:`/article/${t}`;return`/api/draft/start?path=${encodeURIComponent(n)}`}async function hn(e,t){const n=ht.parse(e),o=z(t),r=Ye(t),a=await he(n,t);if(a.contentType==="product")throw new Error("rewrite_page_draft supports pages and posts only. Products use description_json, not page blocks.");const s=a.contentType,c=Number(a.item.id);if(!Number.isInteger(c)||c<=0)throw new Error("Could not resolve a valid page/post id for the draft rewrite.");const u=Number(a.item.language_id);if(!Number.isInteger(u)||u<=0)throw new Error("The target page/post is missing a language id.");const l=$e(n.blocks,void 0,void 0,t).map((I,E)=>({block_type:I.block_type,content:I.content,language_id:u,order:E,page_id:s==="page"?c:null,post_id:s==="post"?c:null,product_id:null})),m=or(a.item);if(n.meta)for(const[I,E]of Object.entries(n.meta))E!==void 0&&(m[I]=E);const h=Lt(typeof m.slug=="string"?m.slug:a.item.slug),p=typeof m.title=="string"&&m.title.trim()?m.title:String(a.item.title||h||"Untitled"),f=s==="page"?`/cms/pages/${c}/edit`:`/cms/posts/${c}/edit`,g=rr(s,h),_=P({action:"REWRITE DRAFT",context:t,payload:{blocks:l,meta:m,parent_id:c,parent_type:s,tool:"rewrite_page_draft"},preview:{blockCount:l.length,contentType:s,slug:h,summary:`Stage a Live Draft that replaces the ${s} "${p}" with ${N(l.length,"new block")}. Nothing goes live until you review the draft and click Publish (which also saves a revision snapshot).`,title:p},subject:`${s}-${c}`});if(_)return _;const k=Number(a.item.version)||1,{error:w}=await o.from("content_drafts").delete().eq("parent_type",s).eq("parent_id",c);if(w)throw new Error(`Failed to clear the existing draft: ${y(w)}`);const{error:T}=await o.from("content_drafts").insert({author_id:r,base_version:k,blocks:l,meta:m,parent_id:c,parent_type:s});if(T)throw new Error(`Failed to save the draft: ${y(T)}`);return ye(l,o),U(t,{contentType:s,entityId:c,slug:h},h),{blockCount:l.length,contentType:s,draftPreviewPath:g,editPath:f,entityId:c,isDraft:!0,mutationExecuted:!0,slug:h,success:!0,title:p}}const ir=new Set(["alt_text","author_name","author_title","caption","html_content","label","placeholder","quote","submit_button_text","success_message","text","text_content","title"]);function qe(e,t,n){if(!e)return e;if(Object.prototype.hasOwnProperty.call(t,e))return t[e];const o=e.trim();if(o!==e&&Object.prototype.hasOwnProperty.call(t,o))return e.replace(o,t[o]);let r=e;for(const[a,s]of n)a&&r.includes(a)&&(r=r.split(a).join(s));return r}function Re(e,t,n){if(Array.isArray(e))return e.map(o=>Re(o,t,n));if(e&&typeof e=="object"){const o={};for(const[r,a]of Object.entries(e))typeof a=="string"&&ir.has(r)?o[r]=qe(a,t,n):a&&typeof a=="object"?o[r]=Re(a,t,n):o[r]=a;return o}return e}const yt=i.z.strictObject({targetLanguageCode:i.z.string().trim().min(2).max(80).describe('Target language code or name, e.g. "fr" or "French".'),title:i.z.string().trim().min(1).max(300).optional().describe("Translated page title (defaults to translating the source title)."),translations:i.z.record(i.z.string(),i.z.string()).describe('Map of every visible source string to its translation, e.g. { "Explore Our Products": "Explorez nos produits" }. Include headings, paragraph text, button labels, image alt text, captions, and form labels.')});async function yn(e,t){const n=yt.parse(e),o=Y(t);if(o.contentType==="product")throw new Error("translate_page supports pages and posts only.");const r=z(t),a=Je(o),s=o.contentType==="page"?"pages":"posts",c=o.contentType==="page"?"page_id":"post_id",{data:u,error:d}=await r.from(s).select("*").eq("id",a).single();if(d||!u)throw new Error(`Could not read the source ${o.contentType} to translate: ${y(d)}`);const{data:l,error:m}=await r.from("blocks").select("id, block_type, content, order").eq(c,a);if(m)throw new Error(`Could not read the source blocks: ${y(m)}`);const h=(Array.isArray(l)?l:[]).slice().sort((C,$)=>Number(C.order)-Number($.order));if(h.length===0)throw new Error(`The source ${o.contentType} has no content blocks to translate.`);const p=n.translations||{},f=Object.entries(p).filter(([C])=>!!C).sort((C,$)=>$[0].length-C[0].length),g=h.map((C,$)=>({blockType:C.block_type,content:Re(K(C.content),p,f),order:$})),b=await Ee(r,n.targetLanguageCode),_=String(u.title||""),k=n.title||qe(_,p,f)||_||"Untitled",w=C=>typeof C=="string"&&C.trim()?qe(C,p,f):void 0,T=R(k)||u.slug||"translated-page",I={blocks:g,feature_image_id:u.feature_image_id??void 0,languageCode:b.code,meta_description:w(u.meta_description),meta_title:w(u.meta_title),slug:T,status:"published",title:k,translationGroupId:u.translation_group_id||void 0},E=o.contentType==="post"?{...I,excerpt:w(u.excerpt),label:w(u.label),published_at:u.published_at??new Date().toISOString(),subtitle:w(u.subtitle)}:I,A=P({action:"TRANSLATE",context:t,payload:{createInput:E,sourceId:u.id,tool:"translate_page"},preview:{blockCount:g.length,contentType:o.contentType,languageCode:b.code,slug:I.slug,status:I.status,summary:`Publish a ${b.code.toUpperCase()} translation of "${_}" — it goes live immediately, linked to the original ${o.contentType}, at /${I.slug} with ${N(g.length,"translated block")}.`,title:k},subject:`translate ${o.contentType} ${u.id} to ${b.code}`});if(A)return A;const B={...t,skipConfirmation:!0};return{...o.contentType==="post"?await Pe(E,B):await Ae(E,B),isTranslation:!0,languageCode:b.code}}async function _t(e,t){const n=se.parse(e),o=n.entityId!==void 0||!!n.slug||!!n.title,r=z(t);let a,s;if(o){const g=await he({contentType:n.contentType,entityId:n.entityId,slug:n.slug,title:n.title},t),b=g.item;s=b.id,a={contentType:g.contentType,entityId:s,slug:typeof b.slug=="string"?b.slug:"",title:typeof b.title=="string"?b.title:""}}else a=Y(t),s=q(a);const c=a.title||a.slug||"current item",u=a.contentType==="product",d=P({action:"SET IMAGES",context:t,payload:{contentType:a.contentType,entityId:String(s),images:n.images,tool:"set_content_images"},preview:{contentType:a.contentType,imageCount:n.images.length,slug:a.slug,summary:u?`Set ${N(n.images.length,"image")} on product "${c}" (the first becomes the main product image, the rest the gallery).`:`Set the feature image on the ${a.contentType} "${c}".`,title:a.title},subject:`set images on ${a.contentType} ${String(s)}`});if(d)return d;const l=await jt(n.images,t,c);if(l.length===0)throw new Error("None of the provided images could be resolved to a media item.");if(u){const{data:g,error:b}=await r.from("products").select("id, slug, language_id, title").eq("id",s).maybeSingle();if(b||!g)throw new Error(`Could not load the product to set images: ${y(b)}`);const _=await Gn({mediaIds:l,productId:s,supabase:r});return await ve({patch:({meta:k})=>Array.isArray(k.product_media)?{meta:{...k,product_media:_.map((w,T)=>({media_id:w,sort_order:T}))}}:{},productId:s,supabase:r}),U(t,{contentType:"product",entityId:String(s),languageId:g.language_id,slug:g.slug,title:g.title},g.slug),t?.revalidatePath?.("/cms/products"),{contentType:"product",entityId:s,imageCount:_.length,mutationExecuted:!0,slug:g.slug,success:!0}}const m=await W(t,a.contentType,s),h=a.contentType==="page"?"pages":"posts",{data:p,error:f}=await r.from(h).update({feature_image_id:l[0],updated_at:new Date().toISOString()}).eq("id",s).select("id, language_id, slug, status, title").single();if(f||!p)throw new Error(`Failed to set the feature image: ${y(f)}`);return await G(t,a.contentType,s,m),U(t,a,p.slug),{contentType:a.contentType,entityId:s,extraImagesIgnored:l.length-1,imageCount:1,mutationExecuted:!0,slug:p.slug,success:!0}}function ar(e){return{..._n.createCortexDatabaseAgentTools(e),...bn.createCortexCustomBlockTools(e),fetch_ecommerce_stats:x.tool({description:"Fetch quantitative ecommerce statistics and reports from the database. Use this to answer questions about revenue, order counts, order status counts such as pending or trial, and top-selling products over a time range. This tool is read-only and does not require confirmation.",execute:t=>Zt(t,e),inputSchema:De,strict:!0}),read_current_cms_item:x.tool({description:"Read the CMS item currently being edited. Requires pageContext and returns page/post/product metadata plus page/post block summaries or content.",execute:t=>en(t,e),inputSchema:Ke,strict:!0}),search_documentation:x.tool({description:"Search the NextBlock documentation database and return concise source snippets for factual CMS guidance.",execute:t=>Qt(t,e),inputSchema:Se,strict:!0}),fetch_url_content:x.tool({description:"Fetch an external web page and return its title, meta description, headings, body text, AND its images: `mainImage` (the page's subject image — schema.org Product image, else og:image, else the best in-body <img>) plus a ranked `images` list, all as absolute URLs. Read-only, no confirmation. Use this first whenever the user references an external URL to copy, adapt, clone, or draw inspiration from. To reuse the source page's image, pass `mainImage` straight into create_cms_product `images` or a page/post `feature_image_id` — it is imported into the media library automatically. Never invent an image URL: if `mainImage` is null, the page had none.",execute:t=>gn(t),inputSchema:gt,strict:!0}),search_stock_photos:x.tool({description:"Find relevant, free, high-quality stock photos (Unsplash/Pexels) for page imagery. Returns a list of photos each with a direct image `url`, `width`, `height`, `alt`, and `photographer`. Read-only, zero cost. Use the returned `url` directly as an image block's external_url or a section image background's image.external_url when building or revamping pages, so layouts show real photos instantly. Set orientation \"landscape\" for hero/section backgrounds.",execute:t=>fn(t,e),inputSchema:ft,strict:!0}),rewrite_page_draft:x.tool({description:'Replace ALL blocks of an existing page or post with a brand-new set of blocks, staged as a Live Draft (content_drafts) that the user previews before publishing. Use this for whole-page redesigns/rewrites such as "rewrite my home page with 5 sections". Provide the complete new list of top-level blocks in `blocks` (usually section blocks for a landing/home page, each with nested heading/text/button blocks). Nothing goes live until the user publishes the draft, and publishing auto-creates a revision snapshot so the change is reversible. Mutating: first returns a confirmation phrase; only stages the draft after the user replies with the exact phrase.',execute:t=>hn(t,e),inputSchema:ht,strict:!0}),translate_page:x.tool({description:'Translate the CURRENT page or post into another language. This copies the source page\'s entire structure, layout, and images automatically and links the new page to the original as a translation — you ONLY supply the text translations. Provide targetLanguageCode (e.g. "fr") and a `translations` map of every visible source string to its translation (headings, paragraph text, button labels, image alt text, captions, form labels). Do NOT rebuild the layout or call search_stock_photos for a translation. Requires an open page/post. Mutating: first returns a confirmation phrase; only creates the translation after exact confirmation.',execute:t=>yn(t,e),inputSchema:yt,strict:!0}),set_content_images:x.tool({description:"Set the feature image for a page or post, or the image gallery for a product. Pass `images`: a list of image URLs (e.g. `mainImage` from fetch_url_content or `url` values from search_stock_photos) and/or existing media library IDs. External URLs are imported into the media library automatically — NEVER put an image URL directly into feature_image_id. The FIRST image becomes the feature image (pages/posts) or the main product image (products); for a product the remaining images become its gallery in order (this REPLACES the product's current images). Targets the currently open page/post/product by default; to target any other item (for example a product you just created from the dashboard) pass contentType plus slug, entityId, or title — no open editor needed. Mutating: first returns a confirmation phrase; only applies after exact confirmation.",execute:t=>_t(t,e),inputSchema:se,strict:!0}),create_cms_page:x.tool({description:"Create a new CMS page with metadata and optional validated page blocks. Mutating: first returns a confirmation phrase; only executes after the user replies with the exact phrase. For translations, pass translationGroupId from the source page/post/product context so the new language is linked to the same backend translation group. For contact pages, provide contactEmail or a form block with recipient_email and fields.",execute:t=>Ae(t,e),inputSchema:le,strict:!0}),create_cms_post:x.tool({description:"Create a new CMS post with metadata and optional validated post blocks. Mutating: first returns a confirmation phrase; only executes after the user replies with the exact phrase. For translations, pass translationGroupId from the source post context so the new language is linked to the same backend translation group.",execute:t=>Pe(t,e),inputSchema:ue,strict:!0}),create_cms_product:x.tool({description:"Create a new draft-capable product, complete with its images and its body copy in ONE call. Pass `images` to set the main product image and gallery (external https URLs are imported into the media library automatically — use `mainImage` from fetch_url_content to reuse a source page's photo). Pass `blocks` to build the product's \"Product Description Blocks\" — the SAME block vocabulary and section-based design rules as create_cms_page, rendered on the public product page. This is the richest product body and is what you should produce whenever the user asks to copy or write real product content. Also pass `short_description` for the one-line summary shown on product cards. `description_html` is a plain-HTML fallback body used only when no blocks are supplied. Defaults missing fields safely: physical Stripe product, generated SKU, price 0, stock 0, taxable, draft. `price` is in major units (25 = $25.00). For translations, pass translationGroupId from the source product context. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>ut(t,e),inputSchema:de,strict:!0}),delete_cms_item:x.tool({description:"Delete a resolved page, post, or product after exact confirmation. Pages/posts delete all translations in the translation group and related navigation links. Mutating: refuses unless the latest user message includes the exact confirmation phrase.",execute:t=>mt(t,e),inputSchema:me,strict:!0}),prepare_delete_cms_item:x.tool({description:"Inspect the page, post, or product that would be deleted and return the exact confirmation phrase. This tool does not mutate data.",execute:t=>cn(t,e),inputSchema:He,strict:!0}),update_footer:x.tool({description:"Replace the public footer links and/or footer copyright settings for a locale. Use links for footer navigation and copyright for locale text templates. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>it(t,e),inputSchema:ne,strict:!0}),update_content_block:x.tool({description:'Update the JSON content of an existing top-level page/post block that belongs to the current CMS edit context. Content is merged with the existing block before validation. For section blocks, add nested blocks with content.append_block or content.append_blocks using objects like { block_type: "button", content: { text: "Contact Us", url: "/contact" } }; existing column_blocks and layout fields are preserved. Mutating: first returns a confirmation phrase; only executes after exact confirmation.',execute:t=>st(t,e),inputSchema:re,strict:!0}),insert_content_block:x.tool({description:'Insert a new validated top-level page/post block before or after an existing block, or at the start/end. Use this for visible content additions like adding a rich text title and paragraph above a form. For "above the form", use position "before" with anchorBlockType "form" and blockType "text" containing html_content. Mutating: first returns a confirmation phrase; only executes after exact confirmation.',execute:t=>ct(t,e),inputSchema:ce,strict:!0}),update_current_cms_fields:x.tool({description:"Update validated metadata fields on the current page, post, or product. For products, description_json must be a valid NextBlock editor document JSON object. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>at(t,e),inputSchema:oe,strict:!0}),update_cms_item_field:x.tool({description:"Update one field on a page, post, or product, resolving by current edit context, id, slug, or exact title. Use this for requests like changing price, stock, title, slug, status, sale_price, or meta fields. Interpret public as published for pages/posts and active for products. Scheduled sale date ranges are not supported and will be refused without mutation. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>pt(t,e),inputSchema:pe,strict:!0}),update_navigation_bar:x.tool({description:'Update the public header navigation bar for a locale. Use mode "append" when adding links while preserving existing navigation. Use mode "update" when renaming or changing an existing single link. Use mode "replace" only when the user asks to rebuild the complete header and you provide the full menu; destructive partial replacements are refused. Mutating: first returns a confirmation phrase; only executes after exact confirmation.',execute:t=>rt(t,e),inputSchema:te,strict:!0}),update_section_column_block:x.tool({description:"Update the content of one existing nested block inside a section block that belongs to the current CMS edit context. This tool must not change the nested block type. To add a new nested block, update the parent section with update_content_block and preserve existing column_blocks. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:t=>lt(t,e),inputSchema:ie,strict:!0}),execute_cms_action_plan:x.tool({description:"Execute multiple CMS mutations as one confirmed plan. Use this whenever the user asks for more than one change in the same prompt, such as creating a page and adding a navigation link. First returns one combined confirmation preview and Confirm button; after confirmation, runs each action in order and stops on the first failure.",execute:t=>ln(t,e),inputSchema:Ve,strict:!0})}}exports.availableCortexAiBlockTypes=H;exports.buildVisibleContactIntroActionPlan=Pn;exports.cortexAiPageContextSchema=Ge;exports.createCmsPageInputSchema=le;exports.createCmsPostInputSchema=ue;exports.createCmsProductInputSchema=de;exports.createCortexGlobalAgentTools=ar;exports.deleteCmsItemInputSchema=me;exports.executeCmsActionPlan=ln;exports.executeCmsActionPlanInputSchema=Ve;exports.executeCreateCmsPage=Ae;exports.executeCreateCmsPost=Pe;exports.executeCreateCmsProduct=ut;exports.executeDeleteCmsItem=mt;exports.executeFetchEcommerceStats=Zt;exports.executeFetchUrlContent=gn;exports.executeInsertContentBlock=ct;exports.executePrepareDeleteCmsItem=cn;exports.executeReadCurrentCmsItem=en;exports.executeRewritePageDraft=hn;exports.executeSearchDocumentation=Xt;exports.executeSearchDocumentationWithTimeout=Qt;exports.executeSearchStockPhotos=fn;exports.executeSetContentImages=_t;exports.executeTranslatePage=yn;exports.executeUpdateCmsItemField=pt;exports.executeUpdateContentBlock=st;exports.executeUpdateCurrentCmsFields=at;exports.executeUpdateFooter=it;exports.executeUpdateNavigationBar=rt;exports.executeUpdateSectionColumnBlock=lt;exports.fetchEcommerceStatsInputSchema=De;exports.fetchUrlContentInputSchema=gt;exports.insertContentBlockInputSchema=ce;exports.maybeTriggerStockPhotoDownloads=ye;exports.navigationItemInputSchema=Me;exports.prepareDeleteCmsItemInputSchema=He;exports.readCurrentCmsItemInputSchema=Ke;exports.resolveCortexAiStockPhotoProvider=Zo;exports.resolveCortexAiStockPhotoProviders=Ne;exports.rewritePageDraftInputSchema=ht;exports.searchDocumentationInputSchema=Se;exports.searchStockPhotosInputSchema=ft;exports.setContentImagesInputSchema=se;exports.translatePageInputSchema=yt;exports.updateCmsItemFieldInputSchema=pe;exports.updateContentBlockInputSchema=re;exports.updateCurrentCmsFieldsInputSchema=oe;exports.updateFooterInputSchema=ne;exports.updateNavigationBarInputSchema=te;exports.updateSectionColumnBlockInputSchema=ie;