@nextblock-cms/cortex 0.21.0 → 0.21.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +46 -0
- package/client.cjs +1 -0
- package/index.cjs +1 -0
- package/lib/{ai-block-generation.cjs.js → ai-block-generation.cjs} +1 -1
- package/lib/ai-block-generation.es.js +1 -1
- package/lib/ai-client.cjs +1 -0
- package/lib/ai-client.es.js +1 -1
- package/lib/ai-config.cjs +1 -0
- package/lib/ai-config.es.js +1 -1
- package/lib/ai-cortex-widget-builder.cjs +1 -0
- package/lib/ai-cortex-widget-builder.es.js +1 -1
- package/lib/ai-global-agent-content-ops-tools.cjs +1 -0
- package/lib/ai-global-agent-content-ops-tools.es.js +1 -1
- package/lib/ai-global-agent-custom-block-tools.cjs +1 -0
- package/lib/ai-global-agent-custom-block-tools.es.js +1 -1
- package/lib/ai-global-agent-db-tools.cjs +1 -0
- package/lib/ai-global-agent-db-tools.es.js +1 -1
- package/lib/{ai-global-agent-site-tools.cjs.js → ai-global-agent-site-tools.cjs} +1 -1
- package/lib/ai-global-agent-site-tools.es.js +1 -1
- package/lib/ai-global-agent-theming-tools.cjs +1 -0
- package/lib/ai-global-agent-theming-tools.es.js +1 -1
- package/lib/ai-global-agent-tools.cjs +15 -0
- package/lib/ai-global-agent-tools.es.js +1 -1
- package/lib/ai-key-crypto.es.js +1 -1
- package/lib/ai-model-catalog.cjs +1 -0
- package/lib/ai-model-catalog.es.js +1 -1
- package/lib/ai-model-registry.es.js +1 -1
- package/lib/ai-seo-metadata.cjs +3 -0
- package/lib/ai-seo-metadata.es.js +1 -1
- package/lib/ai-vision.cjs +3 -0
- package/lib/ai-vision.es.js +1 -1
- package/lib/block-content-schemas.cjs +1 -0
- package/lib/block-content-schemas.es.js +2 -1
- package/lib/cortex-widget-registry.es.js +1 -1
- package/lib/cortex-widget-schema.cjs +4 -0
- package/lib/cortex-widget-schema.es.js +1 -1
- package/lib/editor-document-from-html.es.js +1 -1
- package/lib/fetch-host-guard.es.js +1 -1
- package/lib/mcp-server.cjs +1 -0
- package/lib/mcp-server.es.js +1 -1
- package/lib/mcp-tokens.es.js +1 -1
- package/lib/mcp-tool-registry.cjs +5 -0
- package/lib/mcp-tool-registry.d.ts +1 -1
- package/lib/mcp-tool-registry.es.js +1 -1
- package/lib/site-brief.cjs +2 -0
- package/lib/site-brief.es.js +1 -1
- package/lib/vision-image-download.cjs +1 -0
- package/lib/vision-image-download.es.js +1 -1
- package/lib/zod-config.es.js +1 -1
- package/package.json +9 -8
- package/client.cjs.js +0 -1
- package/index.cjs.js +0 -1
- package/lib/ai-client.cjs.js +0 -1
- package/lib/ai-config.cjs.js +0 -1
- package/lib/ai-cortex-widget-builder.cjs.js +0 -1
- package/lib/ai-global-agent-content-ops-tools.cjs.js +0 -1
- package/lib/ai-global-agent-custom-block-tools.cjs.js +0 -1
- package/lib/ai-global-agent-db-tools.cjs.js +0 -1
- package/lib/ai-global-agent-theming-tools.cjs.js +0 -1
- package/lib/ai-global-agent-tools.cjs.js +0 -15
- package/lib/ai-model-catalog.cjs.js +0 -1
- package/lib/ai-seo-metadata.cjs.js +0 -3
- package/lib/ai-vision.cjs.js +0 -3
- package/lib/block-content-schemas.cjs.js +0 -1
- package/lib/cortex-widget-schema.cjs.js +0 -4
- package/lib/mcp-server.cjs.js +0 -1
- package/lib/mcp-tool-registry.cjs.js +0 -5
- package/lib/site-brief.cjs.js +0 -2
- package/lib/vision-image-download.cjs.js +0 -1
- /package/lib/{ai-global-agent-ecommerce.cjs.js → ai-global-agent-ecommerce.cjs} +0 -0
- /package/lib/{ai-key-crypto.cjs.js → ai-key-crypto.cjs} +0 -0
- /package/lib/{ai-key-verification.cjs.js → ai-key-verification.cjs} +0 -0
- /package/lib/{ai-model-registry.cjs.js → ai-model-registry.cjs} +0 -0
- /package/lib/{cortex-widget-registry.cjs.js → cortex-widget-registry.cjs} +0 -0
- /package/lib/{editor-document-from-html.cjs.js → editor-document-from-html.cjs} +0 -0
- /package/lib/{fetch-host-guard.cjs.js → fetch-host-guard.cjs} +0 -0
- /package/lib/{mcp-tokens.cjs.js → mcp-tokens.cjs} +0 -0
- /package/lib/{zod-config.cjs.js → zod-config.cjs} +0 -0
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
require("./zod-config.cjs");const e=require("./ai-global-agent-custom-block-tools.cjs"),t=require("./block-content-schemas.cjs"),n=require("./ai-global-agent-db-tools.cjs"),r=require("./ai-global-agent-theming-tools.cjs"),i=require("./ai-global-agent-site-tools.cjs"),a=require("./fetch-host-guard.cjs"),o=require("./ai-global-agent-content-ops-tools.cjs"),s=require("./editor-document-from-html.cjs");let c=require("ai"),l=require("next/cache"),u=require("zod");async function d(e,t,n){if(e?.recordRevision)try{return await e.recordRevision({contentType:t,entityId:n,phase:`capture`})}catch(e){console.error(`Cortex AI: failed to capture revision baseline`,e);return}}async function f(e,t,n,r){if(e?.recordRevision&&r!==void 0)try{await e.recordRevision({baseline:r,contentType:t,entityId:n,phase:`commit`})}catch(e){console.error(`Cortex AI: failed to record revision`,e)}}var p=1e4,m={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`},h=u.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.`),g=u.z.strictObject({label:u.z.string().trim().min(1).max(120),target:u.z.enum([`_self`,`_blank`]).optional(),url:h}),_=g.extend({children:u.z.array(g).max(20).optional()}),v=u.z.strictObject({label:u.z.string().trim().min(1).max(120).optional(),url:h.optional()}).refine(e=>!!(e.label||e.url),{message:`Navigation item match requires label or url.`}),y=u.z.strictObject({items:u.z.array(_).min(1).max(30),languageCode:u.z.string().trim().min(2).max(80).default(`en`).describe(`Locale code or language name, for example "en", "fr", "English", or "French".`),match:v.optional().describe(`For mode "update", identifies the existing navigation item to update.`),mode:u.z.enum([`append`,`replace`,`update`]).default(`append`)}),b=u.z.strictObject({copyright:u.z.record(u.z.string().trim().min(2).max(12),u.z.string().trim().min(1).max(500)).optional(),languageCode:u.z.string().trim().min(2).max(80).default(`en`).describe(`Locale code or language name, for example "en", "fr", "English", or "French".`),links:u.z.array(_).min(1).max(30).optional()}),x=u.z.strictObject({limit:u.z.number().int().min(1).max(8).default(4),query:u.z.string().trim().min(2).max(300)}),S=u.z.object({currency:u.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:u.z.string().describe(`The analytical question about orders, products, or revenue.`),reportType:u.z.enum([`revenue`,`orders`,`products`,`general`]).optional().default(`general`).describe(`The focus area of the statistical report.`),timeRange:u.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.`)}),C=u.z.strictObject({contentType:u.z.enum([`page`,`post`,`product`]),currentEditor:u.z.strictObject({blockId:u.z.union([u.z.number().int().positive(),u.z.string().trim().min(1).max(120)]).nullable().optional(),blockType:u.z.string().trim().min(1).max(80).nullable().optional(),field:u.z.string().trim().min(1).max(120).nullable().optional()}).optional(),entityId:u.z.union([u.z.number().int().positive(),u.z.string().trim().min(1).max(120)]),languageId:u.z.number().int().positive().nullable().optional(),slug:u.z.string().trim().min(1).max(300).nullable().optional(),title:u.z.string().trim().min(1).max(300).nullable().optional(),translationGroupId:u.z.string().trim().min(1).max(120).nullable().optional()}),w=u.z.enum([`page`,`post`,`product`]),T=u.z.strictObject({contentType:w.optional(),entityId:u.z.union([u.z.number().int().positive(),u.z.string().trim().min(1).max(120)]).optional(),slug:u.z.string().trim().min(1).max(300).optional(),title:u.z.string().trim().min(1).max(300).optional()}),E=T.optional().describe(`Names the page, post, or product to act on when no CMS editor is open (MCP clients). Pass contentType plus one of slug, entityId, or title. Ignored when an editor is already open.`),ee=u.z.strictObject({cmsTarget:E,includeBlockContent:u.z.boolean().default(!1),includeBlocks:u.z.boolean().default(!0)}),te="The feature image: an existing media library id OR an external https:// image URL, which is downloaded into the media library automatically (pass `mainImage` from fetch_url_content or a `url` from search_stock_photos straight in). WHAT IT DOES: on a page it renders as a full-width title banner ABOVE the page's blocks (the image as a dimmed cover background, about 200-300px tall, with the page title centred over it in white); on a post it is the article's hero image above the header. It is also the social/OG preview image and the card thumbnail in post listings. RULES: give every post one. Give a page one only when a title banner above its content is wanted; NEVER set one on the home page or on any page that opens with its own hero section (the banner would stack above the hero and repeat the title) — set the site-wide social preview with update_site_identity `social_image` instead. Pick a very wide landscape image (about 3:1, at least 1600px wide): the banner crops it to a short full-width band.",D=u.z.strictObject({cmsTarget:E,fields:u.z.strictObject({description_json:u.z.unknown().optional(),excerpt:u.z.string().max(2e3).nullable().optional(),feature_image_id:u.z.string().trim().min(1).max(2048).nullable().optional().describe(te),label:u.z.string().max(120).nullable().optional(),meta_description:u.z.string().max(500).nullable().optional(),meta_title:u.z.string().max(160).nullable().optional(),published_at:u.z.string().max(80).nullable().optional(),short_description:u.z.string().max(2e3).nullable().optional(),slug:u.z.string().trim().min(1).max(300).optional(),status:u.z.enum([`draft`,`published`,`active`,`archived`]).optional(),subtitle:u.z.string().max(300).nullable().optional(),title:u.z.string().trim().min(1).max(300).optional()}).partial()}),ne=u.z.string().trim().min(1).max(120).describe(`A built-in block type (${t.availableCortexAiBlockTypes.join(`, `)}) or the slug of a custom block definition from list_custom_blocks, whose content is the flat { field_key: value } map its fields describe.`),O=u.z.strictObject({blockId:u.z.number().int().positive(),blockType:ne.optional(),cmsTarget:E,content:u.z.record(u.z.string(),u.z.unknown())}),k=u.z.strictObject({blockIndex:u.z.number().int().min(0),blockType:ne.optional(),cmsTarget:E,columnIndex:u.z.number().int().min(0),content:u.z.record(u.z.string(),u.z.unknown()),parentBlockId:u.z.number().int().positive()}),A=u.z.strictObject({blockType:ne,content:u.z.record(u.z.string(),u.z.unknown()).describe('The block content, matching that block type\'s schema. For a `text` block, `html_content` is rendered as real HTML and may include an inline <style> and an inline <script> — so you can add scroll reveals, counters, hover effects, and other motion directly in a block. Inline scripts are stamped with the site CSP nonce automatically. Three rules. (1) THE PAGE IS REACT-HYDRATED. Do not change the text, classes, or attributes of surrounding server-rendered markup: React reconciles afterwards and reverts your change (a counter animates then snaps back) or logs a hydration mismatch. Waiting for `load` is NOT sufficient — hydration can still be in flight. Safe patterns instead: animate with the Web Animations API (el.animate() touches no attribute); append your own new elements and style those; use CSS for anything CSS can do; and if you must set text, render the FINAL value server-side and only animate toward it once the element scrolls into view. (2) `on*` attributes (onclick, onload, …) are stripped, so bind with addEventListener. (3) The script runs once per full page load, not on client-side navigation — for site-wide behaviour use manage_site_script. For a `section` block: `is_hero: true` marks the page hero (the editor checkbox "Hero Section (Prioritized image loading)": its background image loads with priority and its content is vertically centred); `slider: true` with a `slides` array ([{ background, column_blocks }, …], the editor checkbox "Enable Slider (Carousel layout)") renders a carousel of full sections: only the slides are drawn, but the grid track count still comes from the top-level `column_blocks`, so send one top-level column per column you want inside each slide (empty columns are fine) and give every slide that same number of columns. Add `autoplay: true` and `timeframe` in seconds (default 5) to rotate it.'),order:u.z.number().int().min(0).optional()}),j=T.extend({images:u.z.array(u.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).`)}),re=T.extend({anchorBlockId:u.z.number().int().positive().optional(),anchorBlockType:ne.optional(),block:A,position:u.z.enum([`before`,`after`,`start`,`end`]).default(`end`)}),ie=u.z.strictObject({blocks:u.z.array(A).max(20).optional(),contactEmail:u.z.string().email().optional(),feature_image_id:u.z.string().trim().min(1).max(2048).nullable().optional().describe(te),languageCode:u.z.string().trim().min(2).max(80).optional(),meta_description:u.z.string().max(500).nullable().optional(),meta_title:u.z.string().max(160).nullable().optional(),slug:u.z.string().trim().min(1).max(300).optional(),status:u.z.enum([`draft`,`published`,`archived`]).default(`draft`),title:u.z.string().trim().min(1).max(300),translationGroupId:u.z.string().trim().min(1).max(120).optional()}),ae=u.z.strictObject({blocks:u.z.array(A).max(20).optional(),excerpt:u.z.string().max(2e3).nullable().optional(),feature_image_id:u.z.string().trim().min(1).max(2048).nullable().optional().describe(te),label:u.z.string().max(120).nullable().optional(),languageCode:u.z.string().trim().min(2).max(80).optional(),meta_description:u.z.string().max(500).nullable().optional(),meta_title:u.z.string().max(160).nullable().optional(),published_at:u.z.string().max(80).nullable().optional(),slug:u.z.string().trim().min(1).max(300).optional(),status:u.z.enum([`draft`,`published`,`archived`]).default(`draft`),subtitle:u.z.string().max(300).nullable().optional(),title:u.z.string().trim().min(1).max(300),translationGroupId:u.z.string().trim().min(1).max(120).optional()}),oe=u.z.strictObject({blocks:u.z.array(A).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:u.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:u.z.unknown().optional(),freemius_plan_id:u.z.string().optional(),freemius_product_id:u.z.string().optional(),images:u.z.array(u.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:u.z.boolean().default(!0),languageCode:u.z.string().trim().min(2).max(80).optional(),meta_description:u.z.string().max(500).nullable().optional(),meta_title:u.z.string().max(160).nullable().optional(),payment_provider:u.z.enum([`stripe`,`freemius`]).default(`stripe`),price:u.z.number().min(0).default(0),prices:u.z.record(u.z.string(),u.z.number().min(0)).optional(),product_type:u.z.enum([`physical`,`digital`]).default(`physical`),sale_price:u.z.number().min(0).nullable().optional(),sale_prices:u.z.record(u.z.string(),u.z.number().min(0).nullable()).optional(),short_description:u.z.string().max(2e3).nullable().optional(),sku:u.z.string().trim().min(1).max(120).optional(),slug:u.z.string().trim().min(1).max(300).optional(),status:u.z.enum([`draft`,`active`,`archived`]).default(`draft`),stock:u.z.number().int().min(0).default(0),title:u.z.string().trim().min(1).max(300),trial_period_days:u.z.number().int().min(0).default(0),trial_requires_payment_method:u.z.boolean().default(!1),translationGroupId:u.z.string().trim().min(1).max(120).optional(),upc:u.z.string().max(120).nullable().optional()}),se=T.extend({currencyCode:u.z.string().trim().min(3).max(3).optional(),endsAt:u.z.string().max(80).nullable().optional(),field:u.z.string().trim().min(1).max(120),startsAt:u.z.string().max(80).nullable().optional(),value:u.z.unknown()}),ce=T,le=T,ue=u.z.discriminatedUnion(`tool`,[u.z.strictObject({input:ie,tool:u.z.literal(`create_cms_page`)}),u.z.strictObject({input:ae,tool:u.z.literal(`create_cms_post`)}),u.z.strictObject({input:oe,tool:u.z.literal(`create_cms_product`)}),u.z.strictObject({input:le,tool:u.z.literal(`delete_cms_item`)}),u.z.strictObject({input:se,tool:u.z.literal(`update_cms_item_field`)}),u.z.strictObject({input:O,tool:u.z.literal(`update_content_block`)}),u.z.strictObject({input:re,tool:u.z.literal(`insert_content_block`)}),u.z.strictObject({input:D,tool:u.z.literal(`update_current_cms_fields`)}),u.z.strictObject({input:b,tool:u.z.literal(`update_footer`)}),u.z.strictObject({input:y,tool:u.z.literal(`update_navigation_bar`)}),u.z.strictObject({input:k,tool:u.z.literal(`update_section_column_block`)}),u.z.strictObject({input:j,tool:u.z.literal(`set_content_images`)})]),de=u.z.union([ie.extend({tool:u.z.literal(`create_cms_page`)}).transform(({tool:e,...t})=>({input:t,tool:e})),ae.extend({tool:u.z.literal(`create_cms_post`)}).transform(({tool:e,...t})=>({input:t,tool:e})),oe.extend({tool:u.z.literal(`create_cms_product`)}).transform(({tool:e,...t})=>({input:t,tool:e})),le.extend({tool:u.z.literal(`delete_cms_item`)}).transform(({tool:e,...t})=>({input:t,tool:e})),se.extend({tool:u.z.literal(`update_cms_item_field`)}).transform(({tool:e,...t})=>({input:t,tool:e})),O.extend({tool:u.z.literal(`update_content_block`)}).transform(({tool:e,...t})=>({input:t,tool:e})),re.extend({tool:u.z.literal(`insert_content_block`)}).transform(({tool:e,...t})=>({input:t,tool:e})),D.extend({tool:u.z.literal(`update_current_cms_fields`)}).transform(({tool:e,...t})=>({input:t,tool:e})),b.extend({tool:u.z.literal(`update_footer`)}).transform(({tool:e,...t})=>({input:t,tool:e})),y.extend({tool:u.z.literal(`update_navigation_bar`)}).transform(({tool:e,...t})=>({input:t,tool:e})),k.extend({tool:u.z.literal(`update_section_column_block`)}).transform(({tool:e,...t})=>({input:t,tool:e})),j.extend({tool:u.z.literal(`set_content_images`)}).transform(({tool:e,...t})=>({input:t,tool:e}))]),fe=u.z.string().transform((e,t)=>{let n=ye(e);return n.success?n.action:(t.addIssue({code:`custom`,message:n.message}),u.z.NEVER)}),pe=u.z.union([ue,de,fe]),me=u.z.strictObject({actions:u.z.array(pe).min(1).max(8),summary:u.z.string().trim().min(1).max(500).optional()});function he(e){let t=[],n=``,r=0,i=null,a=!1;for(let o of e){if(i){n+=o,a?a=!1:o===`\\`?a=!0:o===i&&(i=null);continue}if(o===`"`||o===`'`){i=o,n+=o;continue}if(o===`[`||o===`{`||o===`(`){r++,n+=o;continue}if(o===`]`||o===`}`||o===`)`){r=Math.max(0,r-1),n+=o;continue}if(o===`,`&&r===0){n.trim()&&t.push(n.trim()),n=``;continue}n+=o}return n.trim()&&t.push(n.trim()),t}function ge(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r!==`'`){t+=r;continue}let i=``,a=!1;for(n++;n<e.length;n++){let t=e[n];if(a){i+=t,a=!1;continue}if(t===`\\`){a=!0;continue}if(t===`'`)break;i+=t}t+=JSON.stringify(i)}return t.replace(/\bTrue\b/g,`true`).replace(/\bFalse\b/g,`false`).replace(/\bNone\b/g,`null`)}function _e(e){let t=e.trim();return t.startsWith(`'`)&&t.endsWith(`'`)||t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`[`)||t.startsWith(`{`)?JSON.parse(ge(t)):/^-?\d+(?:\.\d+)?$/.test(t)?Number(t):t===`true`||t===`True`?!0:t===`false`||t===`False`?!1:t===`null`||t===`None`?null:t}function ve(e){let t={};for(let n of he(e)){let e=n.indexOf(`=`);if(e<=0)throw Error(`Expected key=value argument, received "${n}".`);let r=n.slice(0,e).trim();if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(r))throw Error(`Invalid argument name "${r}".`);t[r]=_e(n.slice(e+1))}return t}function ye(e){let t=e.trim().match(/^([a-z_]+)\(([\s\S]*)\)$/);if(!t)return{message:`Action plan actions must be JSON objects like { "tool": "create_cms_page", "input": { ... } }, not freeform text.`,success:!1};let n=t[1],r;try{r=ve(t[2])}catch(e){return{message:e instanceof Error?e.message:`Could not parse action-plan command arguments.`,success:!1}}let i={input:r,tool:n},a=ue.safeParse(i);return a.success?{action:a.data,success:!0}:{message:`Invalid action-plan command "${n}": ${a.error.issues.map(e=>e.message).join(`; `)}`,success:!1}}function be(e){return e.normalize(`NFD`).replace(/[\u0300-\u036f]/g,``).toLowerCase().replace(/\s+/g,` `).trim()}function xe(e,t){return t.some(t=>e.includes(t))}function Se(e){let t=be(e),n=xe(t,[`add `,`insert `,`put `,`create `]),r=xe(t,[`title`,`heading`,`description`,`intro`,`copy`,`paragraph`]),i=t.includes(`form`)&&xe(t,[`above`,`before`]),a=t.includes(`contact page`)||t.includes(`contact pages`)||t.includes(`contact us`)||t.includes(`contactez-nous`),o=t.includes(`english`)&&xe(t,[`french`,`francais`,`francaise`]);return!n||!r||!i||!a||!o?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.`}}function Ce(){return u.z.object({content:u.z.array(u.z.any()).optional(),type:u.z.literal(`doc`)})}function we(){return l.revalidatePath}function M(e){if(!e?.supabase)throw Error(`A Supabase service client is required to execute Cortex AI global tools.`);return e.supabase}function Te(e,t,n){let r,i=new Promise(e=>{r=setTimeout(()=>e(n()),t)});return Promise.race([e.finally(()=>{r&&clearTimeout(r)}),i])}function Ee(e){let t=C.safeParse(e?.pageContext);if(!t.success)throw 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 De(e){let t=typeof e.entityId==`number`?e.entityId:Number.parseInt(e.entityId,10);if(!Number.isInteger(t)||t<=0)throw Error(`Current ${e.contentType} id must be a positive integer.`);return t}function Oe(e){let t=String(e.entityId||``).trim();if(!t)throw Error(`Current ${e.contentType} id is missing.`);return t}function N(e){return e.contentType===`product`?Oe(e):De(e)}var ke=/^https?:\/\//i,Ae=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;async function P(e,t,n){if(typeof e!=`string`)return null;let r=e.trim();if(!r)return null;if(!ke.test(r)){if(Ae.test(r))return r;throw Error(`"${r}" is not a usable image reference — provide an https:// image URL or a media library id.`)}let i=t?.importExternalImage;if(!i)throw 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.`);let a=await i({altText:n,url:r});if(`error`in a)throw Error(`I could not import the image from that URL: ${a.error}`);return a.id}async function je(e,t,n){let r=[];for(let i=0;i<e.length;i+=1){let a=await P(e[i],t,`${n} image ${i+1}`);a&&r.push(a)}return r}async function Me(e){let t=[...new Set(e.mediaIds)],{error:n}=await e.supabase.from(`product_media`).delete().eq(`product_id`,e.productId);if(n)throw Error(`Could not clear the product's existing images: ${I(n)}`);if(t.length>0){let{error:n}=await e.supabase.from(`product_media`).insert(t.map((t,n)=>({media_id:t,product_id:e.productId,sort_order:n})));if(n)throw Error(`Could not save the product images: ${I(n)}`)}return t}async function Ne(e){if(!e.productId)return!1;let{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;let r=e.patch({blocks:Array.isArray(t.blocks)?U(t.blocks):[],meta:W(t.meta)?U(t.meta):{}}),i={updated_at:new Date().toISOString()};if(r.blocks&&(i.blocks=r.blocks),r.meta&&(i.meta=r.meta),Object.keys(i).length===1)return!1;let{error:a}=await e.supabase.from(`product_drafts`).update(i).eq(`id`,t.id);if(a)throw Error(`The product was updated, but its open draft could not be kept in sync: ${I(a)}. Publishing that draft would undo this change — publish or discard it in the product editor first.`);return!0}function Pe(e){return typeof e==`string`?e.trim().replace(/^\/+|\/+$/g,``):``}function Fe(e,t){let n=Pe(t??e.slug);return n?e.contentType===`page`?n===`home`?`/`:`/${n}`:e.contentType===`post`?`/article/${n}`:`/product/${n}`:null}function Ie(e){let t=String(e.entityId);return e.contentType===`page`?`/cms/pages/${t}/edit`:e.contentType===`post`?`/cms/posts/${t}/edit`:`/cms/products/${t}/edit`}function F(e,t,n){let r=e?.revalidatePath??we();if(!r)return;r(Ie(t));let i=Fe(t,n);i&&r(i),t.contentType===`page`&&i!==`/`&&r(`/`),t.contentType===`product`&&r(`/cms/products`)}function Le(e){let t=e?.revalidatePath??we();t&&(t(`/`,`layout`),t(`/cms/navigation`))}function I(e){return e?typeof e==`object`&&`message`in e?String(e.message||`Unknown database error.`):String(e):`Unknown database error.`}async function Re(){return Promise.resolve().then(()=>require("./ai-global-agent-ecommerce.cjs"))}function ze(e){return typeof e!=`object`||!e?JSON.stringify(e):Array.isArray(e)?`[${e.map(e=>ze(e)).join(`,`)}]`:`{${Object.keys(e).filter(e=>e!==`temp_id`).sort().map(t=>`${JSON.stringify(t)}:${ze(e[t])}`).join(`,`)}}`}function Be(e){let t=2166136261,n=ze(e);for(let e=0;e<n.length;e++)t^=n.charCodeAt(e),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,`0`)}function Ve(e){return e.replace(/\s+/g,` `).trim().toUpperCase()}function He(e,t,n){return`${Ve(`CONFIRM ${e} ${t}`)} #${Be(n)}`}function Ue(e){return{confirmationPhrase:He(e.action,e.subject,e.payload),mutationExecuted:!1,preview:e.preview,requiresConfirmation:!0,success:!0}}function L(e,t){let n=e[t];return typeof n==`string`&&n.trim()?n.trim():null}function R(e,t){let n=Number(e[t]);return Number.isFinite(n)?n:null}function z(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function We(e,t){let n=L(t,`summary`);if(n)return n;let r=L(t,`title`),i=L(t,`slug`),a=L(t,`status`),o=L(t,`contentType`),s=L(t,`field`),c=L(t,`mode`),l=L(t,`languageCode`),u=R(t,`blockCount`),d=R(t,`itemCount`),f=R(t,`affectedCount`);if(e===`create_cms_page`||e===`create_cms_post`)return`Create ${a||`draft`} ${e===`create_cms_page`?`page`:`post`} "${r||i||`Untitled`}"${i?` at slug "${i}"`:``}${u===null?``:` with ${z(u,`content block`)}`}.`;if(e===`create_cms_product`){let e=R(t,`imageCount`),n=R(t,`blockCount`),o=[e?z(e,`image`):null,n?z(n,`description block`):R(t,`descriptionLength`)?`a full description`:null].filter(Boolean);return`Create ${a||`draft`} product "${r||i||`Untitled`}"${i?` at slug "${i}"`:``}${o.length?` with ${o.join(` and `)}`:``}.`}if(e===`update_cms_item_field`)return`Update ${s||`one field`} on the ${o||`CMS item`} "${r||i||`selected item`}".`;if(e===`update_navigation_bar`)return`${c===`append`?`Add`:c===`update`?`Update`:`Replace`} ${d===null?`navigation items`:z(d,`navigation item`)} in the ${l||`selected`} header navigation.`;if(e===`update_footer`){let e=R(t,`linkCount`);return`Update the ${l||`selected`} footer${e===null?``:` with ${z(e,`link`)}`}.`}return e===`update_content_block`?`Update the selected ${L(t,`blockType`)||`content`} block.`:e===`insert_content_block`?`Insert ${L(t,`blockType`)||`content`} block on the ${o||`CMS item`} "${r||i||`selected item`}".`:e===`update_section_column_block`?`Update the selected nested ${L(t,`nestedBlockType`)||`section`} block.`:e===`delete_cms_item`||e===`prepare_delete_cms_item`?`Delete ${f===null?`the selected ${o||`CMS item`}`:z(f,o||`CMS item`)}${r||i?` for "${r||i}"`:``}.`:`Complete the requested CMS change.`}function B(e){if(e.context?.skipConfirmation)return null;let t=Ue(e),n=Ve(e.context?.latestUserMessage||``),r=Ve(t.confirmationPhrase);return n.includes(r)?null:t}function Ge(e){let t=e?.actorUserId;if(!t)throw Error(`A confirmed CMS mutation requires an authenticated admin actor.`);return t}function Ke(){return globalThis.crypto?.randomUUID?.()||`id-${Date.now()}-${Math.random().toString(36).slice(2)}`}function V(e){return e.normalize(`NFD`).replace(/\p{Diacritic}/gu,``).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()}var Je=new Set([`BIF`,`CLP`,`DJF`,`GNF`,`JPY`,`KMF`,`KRW`,`MGA`,`PYG`,`RWF`,`UGX`,`VND`,`VUV`,`XAF`,`XOF`,`XPF`]);function Ye(e){return Je.has(qe(e))?0:2}function Xe(e,t){return Math.round(e*10**Ye(t))}function Ze(e,t){return!e||typeof e!=`object`||Array.isArray(e)?{}:Object.entries(e).reduce((e,[n,r])=>{if(typeof r==`number`&&Number.isFinite(r)&&r>=0){let i=qe(n||t);e[i]=Xe(r,i)}return e},{})}function H(e,t){if(!W(e))throw Error(`${t} content must be a JSON object.`);return JSON.parse(JSON.stringify(e))}function U(e){return JSON.parse(JSON.stringify(e))}function W(e){return!(!e||typeof e!=`object`||Array.isArray(e))}function Qe(e,t){let n=U(e);for(let[e,r]of Object.entries(t))if(r!==void 0){if(W(r)&&W(n[e])){n[e]=Qe(n[e],r);continue}n[e]=U(r)}return n}function $e(e,t){if(t.contentType===`product`){if(String(e.product_id??``)!==String(Oe(t)))throw Error(`Block ${e.id} does not belong to the current product being edited.`);return}let n=De(t);if((t.contentType===`page`?Number(e.page_id):Number(e.post_id))!==n)throw Error(`Block ${e.id} does not belong to the current ${t.contentType} being edited.`)}function et(e,t){return t?.customBlockDefinitions?.find(t=>t.slug===e)??null}function tt(e,t=new Set,n=0){if(n>12||!e)return t;if(typeof e==`string`)return t.add(e),t;if(Array.isArray(e)){for(let r of e)tt(r,t,n+1);return t}if(typeof e==`object`)for(let[r,i]of Object.entries(e))(r===`block_type`||r===`blockType`||r===`anchorBlockType`)&&typeof i==`string`?t.add(i):i&&typeof i==`object`&&tt(i,t,n+1);return t}async function G(e,n){return e?.customBlockDefinitions||!e?.supabase||![...tt(n)].some(e=>!t.isValidBlockType(e))?e:{...e,customBlockDefinitions:await t.loadCustomBlockDefinitions(e.supabase)}}function nt(e,n,r){let i=typeof e==`string`?e.trim():``;if(t.isValidBlockType(i)||i&&et(i,r))return i;throw Error(`${n} has unsupported block type "${i||`unknown`}". Built-in types: ${t.availableCortexAiBlockTypes.join(`, `)}; a custom block must use a slug returned by list_custom_blocks.`)}function rt(e,t,n){if(e&&e!==t)throw Error(`${n} is a "${t}" block. Refusing to update it as "${e}".`)}function K(e,n,r,i){if(!t.isValidBlockType(e)){let a=et(e,i);if(!a)throw Error(`${r} references custom block "${e}", which does not exist.`);let o=t.validateCustomBlockInstanceContent(a,n);if(!o.isValid)throw Error(`${r} content is invalid for custom block "${e}": ${o.errors.join(`; `)}`);return}let a=t.validateCortexBlockContent(e,n,i);if(!a.isValid)throw Error(`${r} content is invalid for block type "${e}": ${a.errors.join(`; `)}`)}function it(e){return e===`section`}function at(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.form_key==`string`||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 ot(e){return`ai-${e}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function st(e,t,n){if(!W(e))throw Error(`${t} must be a JSON object.`);let r=nt(e.block_type??e.blockType,t,n);if(it(r))throw Error(`${t} cannot be a nested ${r} block.`);let i=Ht(r,H(e.content,t),t,n),a=e.temp_id??e.tempId;return{block_type:r,content:i,temp_id:typeof a==`string`&&a.trim()?a:ot(r)}}function ct(e,t){let n=[];if(`append_block`in e&&n.push(st(e.append_block,`Nested block to append`,t)),`append_blocks`in e){let r=e.append_blocks;if(!Array.isArray(r))throw Error(`append_blocks must be an array of nested block objects.`);r.forEach((e,r)=>{n.push(st(e,`Nested block to append ${r}`,t))})}return n}function lt(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;let n=at(e);if(!n)return null;let r=H(e,`Nested ${n} block`);return K(n,r,`Nested ${n} block`,t),{block_type:n,content:r,temp_id:ot(n)}}function ut(e,t){let n=e.append_column_index??e.column_index;if(n===void 0)return 0;if(typeof n!=`number`||!Number.isInteger(n)||n<0)throw Error(`append_column_index must be a non-negative integer.`);if(t>0&&n>=t)throw Error(`append_column_index ${n} is outside the existing ${t} column(s).`);return n}function dt(e,t,n,r){if(!it(e))return Qe(t,n);let i={...n},a=ct(i,r),o=lt(i,r);o&&a.push(o),delete i.append_block,delete i.append_blocks,delete i.append_column_index,delete i.column_index;let s=Qe(t,i);if(a.length>0){let e=Array.isArray(t.column_blocks)?U(t.column_blocks):[],r=ut(n,e.length),i=e.length>0?e:[[]];for(;i.length<=r;)i.push([]);i[r]=[...i[r]||[],...a],s.column_blocks=i}return s}function ft(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 q(e){return typeof e==`string`?e.trim().toLowerCase():``}function pt(e){return typeof e==`string`?e.trim().toLowerCase():``}function mt(e){return e.reduce((e,t)=>e+1+(t.children?.length||0),0)}function ht(e){return typeof e==`string`?e.trim().toLowerCase().normalize(`NFD`).replace(/[\u0300-\u036f]/g,``):``}async function J(e,t){let n=ht(t.trim()),r=m[n],{data:i,error:a}=await e.from(`languages`).select(`id, code, name, is_active`);if(a)throw Error(`Failed to load language "${t}": ${I(a)}`);let o=(Array.isArray(i)?i:[]).filter(e=>e.is_active!==!1),s=o.find(e=>{let t=ht(e.code),i=ht(e.name);return t===n||t===r||i===n});if(!s?.id||!s?.code){let e=o.map(e=>e.code).filter(Boolean).join(`, `);throw Error(`Language "${t}" was not found.${e?` Available languages: ${e}.`:``}`)}return{code:String(s.code),id:Number(s.id)}}async function gt(e,t){if(t)return J(e,t);let{data:n,error:r}=await e.from(`languages`).select(`id, code, name, is_active, is_default`);if(r)throw Error(`Failed to load active languages: ${I(r)}`);let i=(Array.isArray(n)?n:[]).filter(e=>e.is_active!==!1),a=i.find(e=>e.is_default)||i.find(e=>ht(e.code)===`en`)||i[0];if(!a?.id||!a?.code)throw Error(`No active CMS language is available for Cortex AI content creation.`);return{code:String(a.code),id:Number(a.id)}}async function _t(e){try{let{data:t,error:n}=await e.from(`currencies`).select(`code, is_default, is_active`).eq(`is_active`,!0);if(n)return`USD`;let r=Array.isArray(t)?t:[];return qe((r.find(e=>e.is_default)||r[0])?.code||`USD`)}catch{return`USD`}}async function vt(e){let t=e.contentType===`page`?`pages`:e.contentType===`post`?`posts`:`products`,n=`id`,r=e.entityId;if(r===void 0&&e.slug&&(n=`slug`,r=e.slug),r===void 0&&e.title&&(n=`title`,r=e.title),r===void 0)throw Error(`A ${e.contentType} target requires an id, slug, title, or current edit context.`);let{data:i,error:a}=await e.supabase.from(t).select(`*`).eq(n,r);if(a)throw Error(`Failed to resolve ${e.contentType}: ${I(a)}`);let o=Array.isArray(i)?i:i?[i]:[];if(o.length!==1)throw Error(o.length===0?`No ${e.contentType} matched ${n} "${String(r)}".`:`Multiple ${e.contentType}s matched ${n} "${String(r)}"; use an exact id.`);return o[0]}async function Y(e,t){let n=C.safeParse(t?.pageContext).success?t?.pageContext:null,r=e.contentType||n?.contentType;if(!r)throw Error(`Target contentType is required when no current CMS edit context exists.`);let i=e.entityId!==void 0||!!e.slug||!!e.title,a=e.entityId??(i?void 0:n?.entityId),o=e.slug??(i?void 0:n?.slug??void 0),s=e.title??(i?void 0:n?.title??void 0);return{contentType:r,item:await vt({contentType:r,entityId:a,slug:a===void 0&&o||void 0,supabase:M(t),title:a===void 0&&!o&&s||void 0})}}async function X(e,t){let n=C.safeParse(t?.pageContext);if(n.success)return n.data;if(e===void 0||e.entityId===void 0&&!e.slug&&!e.title)throw Error("No current CMS page context is available. Open a page, post, or product edit screen, or pass `cmsTarget` naming the item — contentType plus one of slug, entityId, or title.");let r=await Y(e,t),i=r.item;return{contentType:r.contentType,entityId:i.id,slug:typeof i.slug==`string`?i.slug:``,title:typeof i.title==`string`?i.title:``}}async function yt(e){let t=await xt({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:r,error:i}=await e.supabase.from(`navigation_items`).insert(n).select(`id`).single();if(i)throw Error(`Failed to insert ${e.menuKey} navigation item: ${I(i)}`);return Number(r.id)}function bt(e){let t=e.trim();if(!t.startsWith(`/`)||t.startsWith(`//`))return null;let n=t.split(`?`)[0]?.split(`#`)[0]||``,r=n===`/`?`home`:n.replace(/^\/+|\/+$/g,``);return r&&!r.includes(`/`)?r:null}async function xt(e){let t=bt(e.item.url);if(!t)return null;let{data:n,error:r}=await e.supabase.from(`pages`).select(`id, slug, translation_group_id, language_id`).eq(`slug`,t).eq(`language_id`,e.languageId);if(r)throw Error(`Failed to resolve linked page for navigation item: ${I(r)}`);let i=Array.isArray(n)?n[0]:n;if(!i?.id)return null;let a=Ke();if(i.translation_group_id){let{data:t,error:n}=await e.supabase.from(`pages`).select(`id`).eq(`translation_group_id`,i.translation_group_id);if(n)throw Error(`Failed to inspect linked page translations for navigation item: ${I(n)}`);let r=new Set((Array.isArray(t)?t:[]).map(e=>String(e.id)).filter(Boolean)),{data:o,error:s}=await e.supabase.from(`navigation_items`).select(`id, page_id, translation_group_id, menu_key`).eq(`menu_key`,e.menuKey);if(s)throw Error(`Failed to inspect related navigation translations: ${I(s)}`);let c=(Array.isArray(o)?o:[]).find(e=>e.translation_group_id&&r.has(String(e.page_id)));c?.translation_group_id&&(a=c.translation_group_id)}return{navigationTranslationGroupId:a,pageId:Number(i.id)}}async function St(e){let t=await J(e.supabase,e.languageCode),{data:n,error:r}=await e.supabase.from(`navigation_items`).select(`id, parent_id`).eq(`menu_key`,e.menuKey).eq(`language_id`,t.id);if(r)throw Error(`Failed to inspect existing ${e.menuKey} navigation items: ${I(r)}`);let i=Array.isArray(n)?n:[],a=i.filter(e=>e.parent_id==null).length,o=mt(e.items);Ct({existingItemCount:i.length,existingTopLevelCount:a,languageCode:t.code,menuKey:e.menuKey,replacementItemCount:o});let{error:s}=await e.supabase.from(`navigation_items`).delete().eq(`menu_key`,e.menuKey).eq(`language_id`,t.id);if(s)throw Error(`Failed to clear ${e.menuKey} navigation items: ${I(s)}`);let c=0;for(let[n,r]of e.items.entries()){let i=await yt({item:r,languageId:t.id,menuKey:e.menuKey,order:n,supabase:e.supabase});c++;for(let[n,a]of(r.children??[]).entries())await yt({item:a,languageId:t.id,menuKey:e.menuKey,order:n,parentId:i,supabase:e.supabase}),c++}return{insertedCount:c,languageCode:t.code,menuKey:e.menuKey,skippedCount:0,updatedCount:0}}function Ct(e){if(!(e.existingItemCount===0||e.replacementItemCount>=e.existingItemCount))throw 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 wt(e){let t=await J(e.supabase,e.languageCode),{data:n,error:r}=await e.supabase.from(`navigation_items`).select(`id, parent_id`).eq(`menu_key`,e.menuKey).eq(`language_id`,t.id);if(r)throw Error(`Failed to inspect existing ${e.menuKey} navigation items: ${I(r)}`);let i=Array.isArray(n)?n:[];Ct({existingItemCount:i.length,existingTopLevelCount:i.filter(e=>e.parent_id==null).length,languageCode:t.code,menuKey:e.menuKey,replacementItemCount:mt(e.items)})}async function Tt(e){if(e.items.length!==1)throw Error(`mode "update" requires exactly one navigation item.`);let t=await J(e.supabase,e.languageCode),n=e.items[0],r=q(e.match?.url)||q(n.url),i=pt(e.match?.label),{data:a,error:o}=await e.supabase.from(`navigation_items`).select(`id, label, url, parent_id, order`).eq(`menu_key`,e.menuKey).eq(`language_id`,t.id);if(o)throw Error(`Failed to load existing ${e.menuKey} navigation items: ${I(o)}`);let s=(Array.isArray(a)?a:[]).find(e=>{let t=q(e.url),n=pt(e.label);return!!(r&&t===r||i&&n===i)});if(!s?.id)throw Error(`Could not find a ${e.menuKey} navigation item to update in ${t.code}. Use a matching label or url.`);let{error:c}=await e.supabase.from(`navigation_items`).update({label:n.label,url:n.url}).eq(`id`,s.id);if(c)throw Error(`Failed to update ${e.menuKey} navigation item: ${I(c)}`);return{insertedCount:0,languageCode:t.code,menuKey:e.menuKey,skippedCount:0,updatedCount:1}}async function Et(e){let t=await J(e.supabase,e.languageCode),{data:n,error:r}=await e.supabase.from(`navigation_items`).select(`id, url, parent_id, order`).eq(`menu_key`,e.menuKey).eq(`language_id`,t.id);if(r)throw Error(`Failed to load existing ${e.menuKey} navigation items: ${I(r)}`);let i=0,a=0,o=Array.isArray(n)?n:[],s=new Set(o.map(e=>q(e.url)).filter(Boolean)),c=o.filter(e=>e.parent_id==null).map(e=>Number(e.order)).filter(Number.isFinite),l=c.length>0?Math.max(...c)+1:o.length;for(let n of e.items){let r=q(n.url);if(r&&s.has(r)){a++;continue}let o=await yt({item:n,languageId:t.id,menuKey:e.menuKey,order:l,supabase:e.supabase});i++,l++,r&&s.add(r);let c=0;for(let r of n.children??[]){let n=q(r.url);if(n&&s.has(n)){a++;continue}await yt({item:r,languageId:t.id,menuKey:e.menuKey,order:c,parentId:o,supabase:e.supabase}),i++,c++,n&&s.add(n)}}return{insertedCount:i,languageCode:t.code,menuKey:e.menuKey,skippedCount:a,updatedCount:0}}function Z(e){return typeof e==`string`&&e.trim()?e.trim():``}function Dt(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}function Ot(e){let t=Z(e.field_type??e.fieldType??e.type??e.input_type).toLowerCase().replace(/\s+/g,`_`),n=Z(e.label??e.name??e.placeholder).toLowerCase();return[`email`,`tel`,`url`,`number`,`textarea`,`select`,`radio`,`checkbox`,`text`].includes(t)?t:[`phone`,`telephone`,`phone_number`,`mobile`].includes(t)?`tel`:[`website`,`link`,`uri`].includes(t)?`url`:[`numeric`,`integer`,`quantity`].includes(t)?`number`:n.includes(`email`)||n.includes(`courriel`)?`email`:n.includes(`phone`)||n.includes(`téléphone`)||n.includes(`telephone`)?`tel`:n.includes(`website`)||n.includes(`site web`)?`url`:n.includes(`message`)||n.includes(`comment`)||n.includes(`details`)?`textarea`:`text`}function kt(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((e,t)=>{let n=W(e)?e:{},r=Z(n.label??n.name)||(t===0?`Name`:t===1?`Email`:`Message`),i=Ot({...n,label:r}),a=n.is_required??n.isRequired??n.required;return{field_type:i,is_required:typeof a!=`boolean`||a,label:r,options:Array.isArray(n.options)?n.options:void 0,placeholder:Z(n.placeholder)||void 0,temp_id:Z(n.temp_id??n.tempId??n.id)||`field-${t+1}`}})}var At=new Set([`none`,`sm`,`md`,`lg`,`xl`]),jt=new Set([`none`,`sm`,`md`,`lg`,`xl`]),Mt=new Set([`full-width`,`container`,`container-sm`,`container-lg`,`container-xl`]),Nt=new Set([`start`,`center`,`end`,`stretch`]),Pt=new Set([`none`,`theme`,`solid`,`gradient`,`image`]),Ft=new Set([`primary`,`secondary`,`muted`,`accent`,`destructive`]),It=new Set([`center`,`top`,`bottom`,`left`,`right`]);function Lt(e){return typeof e==`string`&&/^https?:\/\//i.test(e.trim())}function Q(e,t,n){return typeof e==`string`&&t.has(e)?e:n}function Rt(e){return Number.isFinite(e)?Math.min(4,Math.max(1,Math.round(e))):1}function zt(e){let t=[{color:`#1e3a8a`,position:0},{color:`#3b82f6`,position:100}];if(!W(e))return{direction:`to bottom right`,stops:t,type:`linear`};let n=e.type===`radial`?`radial`:`linear`,r=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:r,type:n}}function Bt(e){if(!W(e))return{type:`none`};let t=Q(e.type,Pt,`none`),n=typeof e.min_height==`string`&&e.min_height.trim()?{min_height:e.min_height}:{};if(t===`theme`)return{theme:Q(e.theme,Ft,`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:zt(e.gradient),type:t,...n};if(t===`image`){let r=W(e.image)?e.image:null,i=r&&Lt(r.external_url)?r.external_url.trim():null,a=!!(r&&typeof r.media_id==`string`&&r.media_id.trim()&&typeof r.object_key==`string`&&r.object_key.trim());return r&&(i||a)?{image:{...r,...i?{external_url:i}:{},position:Q(r.position,It,`center`),size:r.size===`contain`?`contain`:`cover`},type:t,...n}:{type:`none`}}return{type:`none`,...n}}function Vt(e,t,n){let r=e.is_hero===!0,i=Array.isArray(e.column_blocks)?e.column_blocks:[];i.length>0&&i.every(e=>W(e)&&!Array.isArray(e))&&(i=[i]);let a=i.map((e,r)=>(Array.isArray(e)?e:[]).map((e,i)=>st(e,`${t} column ${r} block ${i}`,n))),o=a.length>0?a:[[]],s=Rt(o.length),c=W(e.responsive_columns)?e.responsive_columns:{},l=Number(c.tablet),u=Number(c.mobile),d=Number.isFinite(l)?Math.min(3,Math.max(1,Math.min(s,l))):Math.min(3,s),f=Number.isFinite(u)?Math.min(2,Math.max(1,u)):1,p=W(e.padding)?e.padding:{},m={...e,background:Bt(e.background),column_blocks:o,column_gap:Q(e.column_gap,At,`lg`),container_type:Q(e.container_type,Mt,`container`),padding:{bottom:Q(p.bottom,jt,`xl`),top:Q(p.top,jt,`xl`)},responsive_columns:{desktop:s,mobile:f,tablet:d},vertical_alignment:Q(e.vertical_alignment,Nt,r?`center`:`start`)};return Array.isArray(e.slides)&&(m.slides=e.slides.filter(e=>W(e)).map((e,r)=>{let i=Array.isArray(e.column_blocks)?e.column_blocks:[];return i.length>0&&i.every(e=>W(e)&&!Array.isArray(e))&&(i=[i]),{background:Bt(e.background),column_blocks:i.map((e,i)=>(Array.isArray(e)?e:[]).map((e,a)=>st(e,`${t} slide ${r} column ${i} block ${a}`,n)))}})),m.slider===!0&&!(Array.isArray(m.slides)&&m.slides.length>0)&&(m.slider=!1),m}function Ht(e,n,r,i){if(!t.isValidBlockType(e)){let t=U(n);return K(e,t,r,i),t}if(e===`section`){let t=Vt(n,r,i);return K(e,t,r,i),t}let a=U(n);if(e===`heading`&&(a.text_content=Z(a.text_content)||Z(a.text)||Z(a.title)||Z(a.heading)||`Untitled`,a.level=typeof a.level==`number`?a.level:1),e===`text`){let e=Z(a.html_content)||Z(a.html)||Z(a.content)||Z(a.text);e&&(a.html_content=/<\/?[a-z][\s\S]*>/i.test(e)?e:`<p>${Dt(e)}</p>`)}return e===`button`&&(a.text=Z(a.text)||Z(a.label)||Z(a.title)||`Learn More`,a.url=Z(a.url)||Z(a.href)||Z(a.link)||`#`),e===`form`&&(a.fields=kt(a.fields),a.submit_button_text=Z(a.submit_button_text??a.submitButtonText??a.button_text)||`Send Message`,a.success_message=Z(a.success_message??a.successMessage)||`Thanks for reaching out. We will reply as soon as possible.`),K(e,a,r,i),a}function Ut(e,t,n){let r=nt(e.blockType,`Block ${t}`,n);return{block_type:r,content:Ht(r,H(e.content,`Block ${t}`),`Block ${t}`,n),order:e.order??t}}function Wt(e,t=`Contact Us`,n){return[Ut({blockType:`section`,content:{is_hero:!0,background:{type:`none`},column_blocks:[[{block_type:`heading`,content:{level:1,textAlign:`center`,text_content:t},temp_id:ot(`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:ot(`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),Ut({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`}],submit_button_text:`Send Message`,success_message:`Thanks for reaching out. We will reply as soon as possible.`}},1,n)]}function Gt(e,t,n,r){return(!e||e.length===0)&&t?Wt(t,n,r):(e||[]).map((e,t)=>Ut(e,t,r))}async function Kt(e){let t=e.contentType===`page`?`pages`:e.contentType===`post`?`posts`:`products`,{data:n,error:r}=await e.supabase.from(t).select(`id, title, slug, language_id`).eq(`slug`,e.slug).eq(`language_id`,e.languageId);if(r)throw Error(`Failed to check ${e.contentType} slug uniqueness: ${I(r)}`);let i=Array.isArray(n)?n:[];return i.length>0?{duplicate:!0,existingItem:i[0],mutationExecuted:!1,success:!1,message:`A ${e.contentType} with slug "${e.slug}" already exists for this language.`}:null}async function qt(e){if(!e.suppliedTranslationGroupId)return{translationGroupId:void 0};let t=e.contentType===`page`?`pages`:e.contentType===`post`?`posts`:`products`,{data:n,error:r}=await e.supabase.from(t).select(`id, title, slug, language_id, translation_group_id`).eq(`translation_group_id`,e.suppliedTranslationGroupId);if(r)throw Error(`Failed to inspect ${e.contentType} translation group: ${I(r)}`);let i=Array.isArray(n)?n:[];if(i.length===0)return{result:{message:`The ${e.contentType} translation group "${e.suppliedTranslationGroupId}" was not found.`,mutationExecuted:!1,success:!1},translationGroupId:e.suppliedTranslationGroupId};let a=i.find(t=>Number(t.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 Jt(e){if(e.blocks.length===0)return[];let t=e.blocks.map((t,n)=>({block_type:t.block_type,content:t.content,language_id:e.languageId,order:t.order??n,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:r}=await e.supabase.from(`blocks`).insert(t).select(`*`);if(r)throw Error(`Failed to insert ${e.contentType} blocks: ${I(r)}`);return br(e.blocks,e.supabase),Array.isArray(n)?n:[]}async function Yt(e){let t=e.contentType===`page`?`pages`:e.contentType===`post`?`posts`:`products`;await e.supabase.from(t).delete().eq(`id`,e.itemId)}function Xt(e,t){return e===`page`?`/cms/pages/${t}/edit`:e===`post`?`/cms/posts/${t}/edit`:`/cms/products/${t}/edit`}function Zt(e){return e===`page`?`/cms/pages`:e===`post`?`/cms/posts`:`/cms/products`}async function Qt(e,t){let n=y.parse(e),r=M(t);n.mode===`replace`&&await wt({items:n.items,languageCode:n.languageCode,menuKey:`HEADER`,supabase:r});let i=B({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(i)return i;let a=n.mode===`update`?await Tt({items:n.items,languageCode:n.languageCode,match:n.match,menuKey:`HEADER`,supabase:r}):n.mode===`append`?await Et({items:n.items,languageCode:n.languageCode,menuKey:`HEADER`,supabase:r}):await St({items:n.items,languageCode:n.languageCode,menuKey:`HEADER`,supabase:r});return Le(t),{...a,mutationExecuted:!0,mode:n.mode,success:!0}}async function $t(e,t){let n=b.parse(e);if(!n.links?.length&&!n.copyright)throw Error(`update_footer requires links or copyright.`);let r=M(t),i=B({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(i)return i;let a=null;if(n.links?.length&&(a=await St({items:n.links,languageCode:n.languageCode,menuKey:`FOOTER`,supabase:r})),n.copyright){let{error:e}=await r.from(`site_settings`).upsert({key:`footer_copyright`,value:n.copyright});if(e)throw Error(`Failed to update footer copyright: ${I(e)}`)}return Le(t),{copyrightUpdated:!!n.copyright,footerNavigation:a,mutationExecuted:!0,success:!0}}function en(e){return typeof e==`string`?e.toLowerCase():``}function tn(e,t){let n=t.map(en).join(` `);return e.reduce((e,t)=>e+ +!!n.includes(t),0)}function nn(e,t){return(e.find(e=>t.some(t=>en(e).includes(t)))||e.find(e=>e.trim().length>0)||`No excerpt available.`).slice(0,500)}async function rn(e,t){let n=x.parse(e),r=M(t),i=n.query.toLowerCase().split(/\s+/).map(e=>e.trim()).filter(Boolean),[a,o]=await Promise.all([r.from(`posts`).select(`id, title, slug, excerpt, subtitle, meta_description, status, updated_at`).eq(`status`,`published`).limit(100),r.from(`pages`).select(`id, title, slug, meta_description, status, updated_at`).eq(`status`,`published`).limit(100)]);if(a.error)throw Error(`Failed to search documentation posts: ${I(a.error)}`);if(o.error)throw Error(`Failed to search documentation pages: ${I(o.error)}`);let s=(a.data??[]).map(e=>({excerpt:nn([e.excerpt,e.subtitle,e.meta_description,e.slug].filter(Boolean),i),source:`post`,title:e.title,url:`/article/${e.slug}`})),c=(o.data??[]).map(e=>({excerpt:nn([e.meta_description,e.slug].filter(Boolean),i),source:`page`,title:e.title,url:e.slug===`home`?`/`:`/${e.slug}`})),l=[...s,...c].map(e=>({...e,score:tn(i,[e.title,e.excerpt,e.url])})).filter(e=>e.score>0).sort((e,t)=>t.score-e.score).slice(0,n.limit).map(e=>({excerpt:e.excerpt,source:e.source,title:e.title,url:e.url}));return{query:n.query,results:l,success:!0}}async function an(e,t,n=p){let r=x.safeParse(e),i=r.success?r.data.query:``;return Te(rn(e,t),n,()=>({message:`Documentation search took too long to respond. Please try again or ask a more specific question.`,query:i,results:[],success:!1,timedOut:!0}))}var on=[`pending`,`trial`,`paid`,`shipped`,`cancelled`,`refunded`,`failed`],sn={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 cn(e){return String(e??`unknown`).trim().toLowerCase()||`unknown`}function ln(e){let t=Object.fromEntries(on.map(e=>[e,0]));for(let n of e){let e=cn(n.status);t[e]=(t[e]??0)+1}return t}function un(e){let t=e.toLowerCase().replace(/[^a-z0-9_]+/g,` `).split(/\s+/).filter(Boolean);for(let e of t){let t=sn[e];if(t)return t}return null}function dn(e){let t=Number(e);return Number.isFinite(t)?t:0}async function fn(e,t){let n=S.parse(e),r=M(t),i=new Date,a=null,o=null;switch(n.timeRange){case`today`:a=new Date(i.getFullYear(),i.getMonth(),i.getDate());break;case`this_month`:a=new Date(i.getFullYear(),i.getMonth(),1);break;case`last_7_days`:a=new Date(i.getTime()-6048e5);break;case`last_30_days`:a=new Date(i.getTime()-2592e6);break;case`last_month`:a=new Date(i.getFullYear(),i.getMonth()-1,1),o=new Date(i.getFullYear(),i.getMonth(),0,23,59,59,999);break;case`last_90_days`:a=new Date(i.getTime()-7776e6);break;case`all_time`:a=null}let s=n.currency?.toUpperCase(),c=un(n.query),l=r.from(`orders`).select(`id, status, total, currency, created_at, paid_at`);s&&l.eq(`currency`,s),a&&l.gte(`created_at`,a.toISOString()),o&&l.lte(`created_at`,o.toISOString());let u=n.reportType===`products`||n.reportType===`revenue`||n.reportType===`general`?r.from(`order_items`).select(`
|
|
2
|
+
quantity,
|
|
3
|
+
price_at_purchase,
|
|
4
|
+
products!inner (
|
|
5
|
+
id,
|
|
6
|
+
title,
|
|
7
|
+
product_type
|
|
8
|
+
),
|
|
9
|
+
orders!inner (
|
|
10
|
+
id,
|
|
11
|
+
status,
|
|
12
|
+
paid_at,
|
|
13
|
+
currency
|
|
14
|
+
)
|
|
15
|
+
`).eq(`orders.status`,`paid`):null;u&&(s&&u.eq(`orders.currency`,s),a&&u.gte(`orders.paid_at`,a.toISOString()),o&&u.lte(`orders.paid_at`,o.toISOString()));let d=n.timeRange!==`all_time`&&(n.reportType===`orders`||c)?r.from(`orders`).select(`id, status, currency`):null;d&&s&&d.eq(`currency`,s);let[{data:f,error:p},{data:m,error:h},g]=await Promise.all([l,u??Promise.resolve({data:[],error:null}),d??Promise.resolve({data:null,error:null})]);if(p)throw Error(`Failed to fetch ecommerce stats: ${I(p)}`);if(h)throw Error(`Failed to fetch ecommerce stats: ${I(h)}`);if(g.error)throw Error(`Failed to fetch ecommerce stats: ${I(g.error)}`);let _=Array.isArray(f)?f:[],v=Array.isArray(m)?m:[],y=ln(_),b=Array.isArray(g.data)?g.data:null,x=b?ln(b):null,C={};for(let e of v){let t=Array.isArray(e.orders)?e.orders[0]:e.orders,n=String(t?.currency||s||`unknown`).toUpperCase();C[n]=(C[n]??0)+dn(e.quantity)*dn(e.price_at_purchase)/100}let w={currency:s??null,currencyFiltered:!!s,orderStatusCounts:y,paidOrderCount:y.paid??0,query:n.query,reportType:n.reportType,revenueByCurrency:C,timeRange:n.timeRange,totalOrders:_.length,totalRevenue:Object.values(C).reduce((e,t)=>e+t,0)};if(x&&(w.allTimeOrderStatusCounts=x),c&&(w.matchingOrderStatus={allTimeCount:x?.[c]??y[c]??0,count:y[c]??0,status:c,timeRange:n.timeRange}),n.reportType===`products`||n.reportType===`revenue`||n.reportType===`general`){let e={};for(let t of v){let n=Array.isArray(t.products)?t.products[0]:t.products;if(!n?.id)continue;let r=n.id;e[r]||(e[r]={id:r,quantity:0,revenue:0,title:n.title,type:n.product_type}),e[r].quantity+=dn(t.quantity),e[r].revenue+=dn(t.quantity)*dn(t.price_at_purchase)/100}w.topProducts=Object.values(e).sort((e,t)=>t.revenue-e.revenue).slice(0,10)}return{report:w,success:!0}}async function pn(e,t){let n=ee.parse(e),r=M(t),i=await X(n.cmsTarget,t),a=N(i),o=i.contentType===`page`?`pages`:i.contentType===`post`?`posts`:`products`,{data:s,error:c}=await r.from(o).select(`*`).eq(`id`,a).single();if(c||!s)throw Error(`Failed to read current ${i.contentType}: ${I(c)}`);let l=[];if(n.includeBlocks){let e=i.contentType===`page`?`page_id`:i.contentType===`post`?`post_id`:`product_id`,{data:t,error:o}=await r.from(`blocks`).select(`id, page_id, post_id, product_id, language_id, block_type, content, order`).eq(e,a);if(o)throw Error(`Failed to read current ${i.contentType} blocks: ${I(o)}`);l=(Array.isArray(t)?t:[]).slice().sort((e,t)=>Number(e.order)-Number(t.order)).map(e=>ft(e,n.includeBlockContent))}return{blocks:l,context:i,item:s,success:!0}}var mn=new Set([`feature_image_id`,`language_id`,`meta_description`,`meta_title`,`slug`,`status`,`title`]),hn=new Set([`excerpt`,`feature_image_id`,`label`,`language_id`,`meta_description`,`meta_title`,`published_at`,`slug`,`status`,`subtitle`,`title`]),gn=new Set([`description_json`,`language_id`,`meta_description`,`meta_title`,`short_description`,`slug`,`status`,`title`]),_n=new Set([`excerpt`,`feature_image_id`,`label`,`meta_description`,`meta_title`,`published_at`,`short_description`,`subtitle`]);function vn(e){return e===`page`?mn:e===`post`?hn:gn}function yn(e,t){return _n.has(e)&&t===``?null:t}function bn(e,t){if(typeof t!=`string`)return;let n=e===`product`?[`active`,`archived`,`draft`]:[`archived`,`draft`,`published`];if(!n.includes(t))throw Error(`Status "${t}" is not valid for ${e}. Allowed statuses: ${n.join(`, `)}.`)}function xn(e,t){let n=vn(t.contentType),r={};for(let[i,a]of Object.entries(e))if(a!==void 0){if(!n.has(i))throw Error(`Field "${i}" cannot be updated for ${t.contentType} content.`);i===`status`&&bn(t.contentType,a),r[i]=yn(i,a)}return r}async function Sn(e,t){let n=D.parse(e),r=M(t),i=await X(n.cmsTarget,t),a=N(i),o=xn(n.fields,i),s=Object.keys(o);if(s.length===0)throw Error(`update_current_cms_fields requires at least one supported field.`);let c=B({action:`UPDATE CMS FIELDS`,context:t,payload:{contentType:i.contentType,entityId:a,fields:o,tool:`update_current_cms_fields`},preview:{contentType:i.contentType,entityId:a,fields:s,slug:i.slug,title:i.title},subject:`${i.contentType} ${String(a)}`});if(c)return c;let l=await d(t,i.contentType,a);typeof o.feature_image_id==`string`&&(o.feature_image_id=await P(o.feature_image_id,t,typeof i.title==`string`?i.title:void 0));let u=i.contentType===`page`?`pages`:i.contentType===`post`?`posts`:`products`,{data:p,error:m}=await r.from(u).update({...o,updated_at:new Date().toISOString()}).eq(`id`,a).select(`id, language_id, slug, status, title`).single();if(m||!p)throw Error(`Failed to update current ${i.contentType}: ${I(m)}`);return await f(t,i.contentType,a,l),F(t,i,p.slug),{contentType:i.contentType,entityId:a,mutationExecuted:!0,slug:p.slug,success:!0,updatedFields:s}}async function Cn(e,t){let n=O.parse(e),r=M(t),i=await X(n.cmsTarget,t),{data:a,error:o}=await r.from(`blocks`).select(`id, page_id, post_id, product_id, language_id, block_type, content, order`).eq(`id`,n.blockId).single();if(o||!a)throw Error(`Failed to read block ${n.blockId}: ${I(o)}`);$e(a,i),t=await G(t,[a.block_type,a.content,n.content]);let s=nt(a.block_type,`Block ${n.blockId}`,t);rt(n.blockType,s,`Block ${n.blockId}`);let c=dt(s,H(a.content,`Block ${n.blockId}`),n.content,t);K(s,c,`Block ${n.blockId}`,t);let l=B({action:`UPDATE CONTENT BLOCK`,context:t,payload:{blockId:n.blockId,blockType:s,content:c,tool:`update_content_block`},preview:{blockId:n.blockId,blockType:s,contentType:i.contentType,entityId:N(i)},subject:`${s} block ${n.blockId}`});if(l)return l;let u=await d(t,i.contentType,N(i)),{data:p,error:m}=await r.from(`blocks`).update({content:c,updated_at:new Date().toISOString()}).eq(`id`,n.blockId).select(`id, block_type, order`).single();if(m||!p)throw Error(`Failed to update block ${n.blockId}: ${I(m)}`);return await f(t,i.contentType,N(i),u),await Ne({patch:({blocks:e})=>({blocks:e.map(e=>String(e?.id)===String(n.blockId)?{...e,content:c}:e)}),productId:a.product_id,supabase:r}),br([{content:c}],r),F(t,i),{blockId:p.id,blockType:p.block_type,contentUpdated:!0,mutationExecuted:!0,success:!0}}async function wn(e,t){let n=re.parse(e);t=await G(t,n.block);let r=M(t),i=await Y(n,t),a=i.contentType===`product`?i.item.id:Number(i.item.id),o=i.contentType===`page`?`page_id`:i.contentType===`post`?`post_id`:`product_id`,s=async()=>{let{data:e,error:t}=await r.from(`blocks`).select(`id, page_id, post_id, product_id, language_id, block_type, content, order`).eq(o,a);if(t)throw Error(`Failed to read ${i.contentType} blocks: ${I(t)}`);return(Array.isArray(e)?e:[]).sort((e,t)=>Number(e.order)-Number(t.order))},c=e=>{if(n.position===`start`)return 0;if(n.position===`end`){let t=e.map(e=>Number(e.order)).filter(Number.isFinite);return t.length>0?Math.max(...t)+1:0}let t=n.anchorBlockId?e.find(e=>Number(e.id)===n.anchorBlockId):n.anchorBlockType?e.find(e=>e.block_type===n.anchorBlockType):null;if(!t)throw Error(n.anchorBlockType?`Could not find a ${n.anchorBlockType} block to insert ${n.position}.`:`Could not find block ${n.anchorBlockId} to insert ${n.position}.`);let r=Number(t.order);return n.position===`before`?r:r+1},l=Ut(n.block,0,t),u=c(await s()),p={contentType:i.contentType,entityId:i.item.id,languageId:i.item.language_id,slug:i.item.slug,title:i.item.title,translationGroupId:i.item.translation_group_id},m=B({action:`INSERT CONTENT BLOCK`,context:t,payload:{block:l,order:u,target:{contentType:i.contentType,id:i.item.id,slug:i.item.slug},tool:`insert_content_block`},preview:{anchorBlockId:n.anchorBlockId,anchorBlockType:n.anchorBlockType,blockType:l.block_type,contentType:i.contentType,entityId:i.item.id,position:n.position,slug:i.item.slug,summary:`Insert ${l.block_type} block ${n.position} ${n.anchorBlockType?`the first ${n.anchorBlockType} block`:n.anchorBlockId?`block ${n.anchorBlockId}`:`the content`} on ${i.contentType} "${i.item.title||i.item.slug}".`,title:i.item.title},subject:`${l.block_type} block on ${i.contentType} ${i.item.id}`});if(m)return m;let h=await s(),g=c(h),_=h.filter(e=>Number(e.order)>=g).sort((e,t)=>Number(t.order)-Number(e.order)),v=await d(t,i.contentType,a);for(let e of _){let{error:t}=await r.from(`blocks`).update({order:Number(e.order)+1,updated_at:new Date().toISOString()}).eq(`id`,e.id);if(t)throw Error(`Failed to shift block ${e.id}: ${I(t)}`)}let{data:y,error:b}=await r.from(`blocks`).insert({block_type:l.block_type,content:l.content,language_id:i.item.language_id,order:g,page_id:i.contentType===`page`?a:null,post_id:i.contentType===`post`?a:null,product_id:i.contentType===`product`?a:null}).select(`id, block_type, order`).single();if(b||!y)throw Error(`Failed to insert content block: ${I(b)}`);return i.contentType===`product`&&await Ne({patch:({blocks:e})=>({blocks:[...e.map(e=>Number(e?.order)>=g?{...e,order:Number(e.order)+1}:e),{block_type:l.block_type,content:l.content,id:y.id,language_id:i.item.language_id,order:g,page_id:null,post_id:null,product_id:a}].sort((e,t)=>Number(e.order)-Number(t.order))}),productId:a,supabase:r}),await f(t,i.contentType,a,v),br([l],r),F(t,p),{blockId:y.id,blockType:y.block_type,contentType:i.contentType,entityId:i.item.id,mutationExecuted:!0,order:y.order,success:!0}}async function Tn(e,t){let n=k.parse(e),r=M(t),i=await X(n.cmsTarget,t),{data:a,error:o}=await r.from(`blocks`).select(`id, page_id, post_id, product_id, language_id, block_type, content, order`).eq(`id`,n.parentBlockId).single();if(o||!a)throw Error(`Failed to read parent block ${n.parentBlockId}: ${I(o)}`);$e(a,i),t=await G(t,[a.block_type,a.content,n.content]);let s=nt(a.block_type,`Parent block ${n.parentBlockId}`,t);if(s!==`section`)throw Error(`Parent block ${n.parentBlockId} must be a section block, not "${s}".`);let c=H(a.content,`Parent block ${n.parentBlockId}`);K(s,c,`Parent block ${n.parentBlockId}`,t);let l=c.column_blocks?.[n.columnIndex]?.[n.blockIndex];if(!l)throw Error(`Nested block was not found at column ${n.columnIndex}, index ${n.blockIndex}.`);let u=nt(l.block_type,`Nested block ${n.columnIndex}:${n.blockIndex}`,t);rt(n.blockType,u,`Nested block ${n.columnIndex}:${n.blockIndex}`),K(u,n.content,`Nested block ${n.columnIndex}:${n.blockIndex}`,t);let p=c.column_blocks.map((e,t)=>t===n.columnIndex?e.map((e,t)=>t===n.blockIndex?{...e,content:n.content}:e):e),m={...c,column_blocks:p};K(s,m,`Updated parent block ${n.parentBlockId}`,t);let h=B({action:`UPDATE NESTED BLOCK`,context:t,payload:{blockIndex:n.blockIndex,columnIndex:n.columnIndex,content:n.content,nestedBlockType:u,parentBlockId:n.parentBlockId,tool:`update_section_column_block`},preview:{blockIndex:n.blockIndex,columnIndex:n.columnIndex,nestedBlockType:u,parentBlockId:n.parentBlockId,parentBlockType:s},subject:`${u} nested block ${n.columnIndex}:${n.blockIndex}`});if(h)return h;let g=await d(t,i.contentType,N(i)),{data:_,error:v}=await r.from(`blocks`).update({content:m,updated_at:new Date().toISOString()}).eq(`id`,n.parentBlockId).select(`id, block_type`).single();if(v||!_)throw Error(`Failed to update parent block ${n.parentBlockId}: ${I(v)}`);return await Ne({patch:({blocks:e})=>({blocks:e.map(e=>String(e?.id)===String(n.parentBlockId)?{...e,content:m}:e)}),productId:a.product_id,supabase:r}),await f(t,i.contentType,N(i),g),F(t,i),{blockIndex:n.blockIndex,columnIndex:n.columnIndex,mutationExecuted:!0,nestedBlockType:u,parentBlockId:_.id,parentBlockType:_.block_type,success:!0}}async function En(e,t){let n=ie.parse(e);t=await G(t,n.blocks);let r=M(t),i=Ge(t),a=await gt(r,n.languageCode),o=V(n.slug||n.title),s=Gt(n.blocks,n.contactEmail,n.title,t),c=await Kt({contentType:`page`,languageId:a.id,slug:o,supabase:r});if(c)return c;let l=await qt({contentType:`page`,languageCode:a.code,languageId:a.id,suppliedTranslationGroupId:n.translationGroupId,supabase:r});if(l.result)return l.result;let u={blocks:s,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:o,status:n.status,title:n.title,translation_group_id:l.translationGroupId},tool:`create_cms_page`},d=B({action:`CREATE PAGE`,context:t,payload:u,preview:{blockCount:s.length,languageCode:a.code,slug:o,status:n.status,title:n.title,translationGroupId:l.translationGroupId},subject:o});if(d)return d;let f=l.translationGroupId||Ke(),p=await P(u.item.feature_image_id,t,n.title),{data:m,error:h}=await r.from(`pages`).insert({...u.item,author_id:i,feature_image_id:p,translation_group_id:f}).select(`id, language_id, slug, status, title, translation_group_id`).single();if(h||!m?.id)throw Error(`Failed to create page: ${I(h)}`);try{await Jt({blocks:s,contentType:`page`,itemId:Number(m.id),languageId:a.id,supabase:r})}catch(e){throw await Yt({contentType:`page`,itemId:Number(m.id),supabase:r}),e}return F(t,{contentType:`page`,entityId:Number(m.id),languageId:a.id,slug:o,title:n.title},o),t?.revalidatePath?.(`/cms/pages`),{blockCount:s.length,contentType:`page`,editPath:Xt(`page`,m.id),entityId:m.id,mutationExecuted:!0,slug:o,success:!0,title:n.title,translationGroupId:m.translation_group_id}}async function Dn(e,t){let n=ae.parse(e);t=await G(t,n.blocks);let r=M(t),i=Ge(t),a=await gt(r,n.languageCode),o=V(n.slug||n.title),s=Gt(n.blocks,void 0,void 0,t),c=await Kt({contentType:`post`,languageId:a.id,slug:o,supabase:r});if(c)return c;let l=await qt({contentType:`post`,languageCode:a.code,languageId:a.id,suppliedTranslationGroupId:n.translationGroupId,supabase:r});if(l.result)return l.result;let u=n.published_at&&!Number.isNaN(new Date(n.published_at).getTime())?new Date(n.published_at).toISOString():n.published_at??null,d={blocks:s,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:u,slug:o,status:n.status,subtitle:n.subtitle??null,title:n.title,translation_group_id:l.translationGroupId},tool:`create_cms_post`},f=B({action:`CREATE POST`,context:t,payload:d,preview:{blockCount:s.length,languageCode:a.code,slug:o,status:n.status,title:n.title,translationGroupId:l.translationGroupId},subject:o});if(f)return f;let p=l.translationGroupId||Ke(),m=await P(d.item.feature_image_id,t,n.title),{data:h,error:g}=await r.from(`posts`).insert({...d.item,author_id:i,feature_image_id:m,translation_group_id:p}).select(`id, language_id, slug, status, title, translation_group_id`).single();if(g||!h?.id)throw Error(`Failed to create post: ${I(g)}`);try{await Jt({blocks:s,contentType:`post`,itemId:Number(h.id),languageId:a.id,supabase:r})}catch(e){throw await Yt({contentType:`post`,itemId:Number(h.id),supabase:r}),e}return F(t,{contentType:`post`,entityId:Number(h.id),languageId:a.id,slug:o,title:n.title},o),t?.revalidatePath?.(`/cms/posts`),t?.revalidatePath?.(`/articles`),{blockCount:s.length,contentType:`post`,editPath:Xt(`post`,h.id),entityId:h.id,mutationExecuted:!0,slug:o,success:!0,title:n.title,translationGroupId:h.translation_group_id}}function On(e,t){return(t||V(e)||`product`).replace(/-/g,``).slice(0,24).toUpperCase()}function kn(e){if(e==null)return;if(typeof e==`string`)return s.editorDocumentFromHtml(e)??void 0;let t=Array.isArray(e)?{content:e,type:`doc`}:W(e)&&e.type!==`doc`&&Array.isArray(e.content)?{...e,type:`doc`}:e,n=Ce().safeParse(t);if(!n.success){if(W(e)&&typeof e.type==`string`){let t=Ce().safeParse({content:[e],type:`doc`});if(t.success)return t.data}throw 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(e=>e.message).join(`; `)}`)}return n.data}function An(e){let t=e=>!!(e&&Array.isArray(e.content)&&e.content.length>0),n=kn(e.description_json);if(t(n))return n;let r=e.description_html?s.editorDocumentFromHtml(e.description_html):null;return t(r)?r:void 0}async function jn(e,t){let n=oe.parse(e);t=await G(t,n.blocks);let r=M(t),i=await gt(r,n.languageCode),a=V(n.slug||n.title),o=Gt(n.blocks,void 0,void 0,t),s=await Kt({contentType:`product`,languageId:i.id,slug:a,supabase:r});if(s)return s;let c=await qt({contentType:`product`,languageCode:i.code,languageId:i.id,suppliedTranslationGroupId:n.translationGroupId,supabase:r});if(c.result)return c.result;let{createProduct:l,productSchema:u}=await Re(),d=n.product_type===`digital`&&n.payment_provider===`freemius`?n.trial_period_days:0,f=u.parse({description_json:An(n),freemius_plan_id:n.freemius_plan_id||``,freemius_product_id:n.freemius_product_id||``,is_taxable:n.is_taxable,language_id:i.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||On(n.title,a),slug:a,status:n.status,stock:n.stock,title:n.title,trial_period_days:d,trial_requires_payment_method:d>0&&n.trial_requires_payment_method,translation_group_id:c.translationGroupId,upc:n.upc??``,variation_attributes:[],variants:[]}),p=n.images??[],m=B({action:`CREATE PRODUCT`,context:t,payload:{blocks:o,images:p,item:f,tool:`create_cms_product`},preview:{blockCount:o.length,descriptionLength:f.description_json?JSON.stringify(f.description_json).length:0,imageCount:p.length,languageCode:i.code,price:f.price,sku:f.sku,slug:a,status:f.status,stock:f.stock,title:f.title,translationGroupId:c.translationGroupId},subject:a});if(m)return m;let h=[],g=null;if(p.length>0)try{if(h=[...new Set(await je(p,t,n.title))],h.length===0)throw Error(`None of the provided images could be resolved to a media item.`)}catch(e){g=e instanceof Error?e.message:String(e)}let _=await l(r,{...f,product_media:h.map(e=>({media_id:e}))});if(!_?.id)throw Error(`Failed to create product.`);try{await Jt({blocks:o,contentType:`product`,itemId:_.id,languageId:i.id,supabase:r})}catch(e){throw await Yt({contentType:`product`,itemId:_.id,supabase:r}),e}return F(t,{contentType:`product`,entityId:_.id,languageId:i.id,slug:a,title:n.title},a),t?.revalidatePath?.(`/cms/products`),{blockCount:o.length,contentType:`product`,editPath:Xt(`product`,_.id),entityId:_.id,imageCount:h.length,...g?{imageError:g}:{},mutationExecuted:!0,slug:a,success:!0,title:n.title,translationGroupId:_.translation_group_id}}function Mn(e){return e.trim().replace(/[\s-]+/g,`_`).toLowerCase()}function Nn(e,t){let n=typeof t==`string`?Mn(t):t;return e===`product`?n===`public`||n===`publish`||n===`published`?`active`:n:n===`public`||n===`active`||n===`publish`?`published`:n}function Pn(e){let t=Mn(e.field);return!!(e.startsAt||e.endsAt||t.includes(`start`)||t.includes(`end`)||t.includes(`schedule`)||t.includes(`special_date`))}async function Fn(e,t,n){if(e===`price`||e===`sale_price`){if(t==null)return{[e]:null};let r=await _t(n);return{[e]:Xe(Number(t),r)}}if(e===`prices`||e===`sale_prices`){let r=await _t(n);return{[e]:Ze(t,r)}}return e===`description_json`?{description_json:kn(t)}:{[e]:t}}var In=new Set([`language_id`,`price`,`sale_price`,`stock`,`trial_period_days`]),Ln=new Set([`is_taxable`,`trial_requires_payment_method`]);function Rn(e,t){if(typeof t!=`string`)return t;let n=t.trim();if(In.has(e)){if(n.toLowerCase()===`null`)return null;if(n===``)return t;let e=Number(n);return Number.isFinite(e)?e:t}if(Ln.has(e)){let e=n.toLowerCase();if(e===`true`)return!0;if(e===`false`)return!1}return t}function zn(e,t){let n=Mn(e.field),r={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,i=r===`status`?Nn(t.contentType,e.value):Rn(r,e.value);if(t.contentType!==`product`){if(!(t.contentType===`page`?mn:hn).has(r))throw Error(`Field "${e.field}" cannot be updated for ${t.contentType}.`);return r===`status`&&bn(t.contentType,i),{field:r,payload:{[r]:yn(r,i)}}}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(r))throw Error(`Field "${e.field}" cannot be updated for product.`);if(r===`status`&&bn(`product`,i),(r===`price`||r===`sale_price`)&&i!==null&&(typeof i!=`number`||i<0))throw Error(`${r} must be a non-negative number or null.`);if(r===`stock`&&(!Number.isInteger(i)||Number(i)<0))throw Error(`stock must be a non-negative integer.`);if(r===`trial_period_days`&&(!Number.isInteger(i)||Number(i)<0))throw Error(`trial_period_days must be a non-negative integer.`);if(r===`trial_requires_payment_method`&&typeof i!=`boolean`)throw Error(`trial_requires_payment_method must be a boolean.`);return{field:r,payload:{[r]:i}}}async function Bn(e,t){let n=se.parse(e);if(Pn(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};let r=await Y(n,t),i=zn(n,r),a=i.field,o=i.payload;if(a===`language_id`&&typeof o.language_id==`string`){let e=await J(M(t),o.language_id);o={...o,language_id:e.id}}let s=B({action:`UPDATE FIELD`,context:t,payload:{contentType:r.contentType,entityId:r.item.id,field:a,payload:o,tool:`update_cms_item_field`},preview:{contentType:r.contentType,field:a,from:r.item[a],slug:r.item.slug,title:r.item.title,to:o[a]},subject:`${r.contentType} ${r.item.slug||r.item.id} ${a}`});if(s)return s;let c=await d(t,r.contentType,r.item.id);if(r.contentType===`product`){let e=M(t),n=await Fn(a,o[a],e),{data:i,error:s}=await e.from(`products`).update({...n,updated_at:new Date().toISOString()}).eq(`id`,r.item.id).select(`id, language_id, slug, status, title`).single();if(s||!i)throw Error(`Failed to update product: ${I(s)}`);return F(t,{contentType:`product`,entityId:String(i.id),languageId:i.language_id,slug:i.slug,title:i.title},i.slug),await f(t,`product`,i.id,c),{contentType:`product`,entityId:i.id,field:a,mutationExecuted:!0,slug:i.slug,success:!0,updatedFields:[a]}}a===`feature_image_id`&&typeof o.feature_image_id==`string`&&(o={...o,feature_image_id:await P(o.feature_image_id,t,typeof r.item.title==`string`?r.item.title:void 0)});let l=r.contentType===`page`?`pages`:`posts`,{data:u,error:p}=await M(t).from(l).update({...o,updated_at:new Date().toISOString()}).eq(`id`,r.item.id).select(`id, language_id, slug, status, title`).single();if(p||!u)throw Error(`Failed to update ${r.contentType}: ${I(p)}`);return F(t,{contentType:r.contentType,entityId:Number(u.id),languageId:u.language_id,slug:u.slug,title:u.title},u.slug),await f(t,r.contentType,u.id,c),{contentType:r.contentType,entityId:u.id,field:a,mutationExecuted:!0,slug:u.slug,success:!0,updatedFields:[a]}}async function Vn(e,t){let n=await Y(ce.parse(e),t);if(n.contentType===`product`)return{affectedCount:1,collectionPath:Zt(`product`),contentType:`product`,item:n.item,navigationLinkCount:0,publicPaths:n.item.slug?[`/product/${n.item.slug}`]:[],targetIds:[n.item.id]};let r=n.contentType===`page`?`pages`:`posts`,{data:i,error:a}=await M(t).from(r).select(`id, slug, title, translation_group_id`).eq(`translation_group_id`,n.item.translation_group_id);if(a)throw Error(`Failed to inspect related ${n.contentType}s: ${I(a)}`);let o=Array.isArray(i)?i:[],s=o.map(e=>n.contentType===`page`?e.slug===`home`?`/`:`/${e.slug}`:`/article/${e.slug}`).filter(Boolean),c=new Set(s),{data:l,error:u}=await M(t).from(`navigation_items`).select(`id, url`);if(u)throw Error(`Failed to inspect related navigation links: ${I(u)}`);let d=(Array.isArray(l)?l:[]).filter(e=>c.has(e.url)).length;return{affectedCount:o.length,collectionPath:Zt(n.contentType),contentType:n.contentType,item:n.item,navigationLinkCount:d,publicPaths:s,targetIds:o.map(e=>e.id)}}function Hn(e){let 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}.`;let r=[`${z(e.affectedCount,`language version`)}`,e.navigationLinkCount>0?`${z(e.navigationLinkCount,`navigation link`)}`:null].filter(Boolean);return`Delete ${e.contentType} "${t}"${n}, including ${r.join(` and `)}.`}async function Un(e,t){let n=await Vn(e,t);return{...Ue({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:Hn(n),title:n.item.title},subject:`${n.item.id} ${n.item.slug||``}`}),preparedDelete:!0}}async function Wn(e,t){let n=await Vn(le.parse(e),t),r=B({action:`DELETE ${n.contentType}`,context:t,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:Hn(n),title:n.item.title},subject:`${n.item.id} ${n.item.slug||``}`});if(r)return r;let i=M(t);if(n.contentType===`product`){let{error:e}=await i.from(`products`).delete().eq(`id`,n.item.id);if(e)throw Error(`Failed to delete product: ${I(e)}`)}else{for(let e of n.publicPaths)await i.from(`navigation_items`).delete().eq(`url`,e);let e=n.contentType===`page`?`pages`:`posts`,{error:t}=await i.from(e).delete().eq(`translation_group_id`,n.item.translation_group_id);if(t)throw Error(`Failed to delete ${n.contentType}: ${I(t)}`)}let a=t?.revalidatePath??we();return a&&(a(n.collectionPath),a(`/cms/navigation`),n.publicPaths.forEach(e=>a(e))),{affectedCount:n.affectedCount,collectionPath:n.collectionPath,contentType:n.contentType,mutationExecuted:!0,redirectPath:n.collectionPath,success:!0}}async function Gn(e,t){switch(e.tool){case`create_cms_page`:return En(e.input,t);case`create_cms_post`:return Dn(e.input,t);case`create_cms_product`:return jn(e.input,t);case`delete_cms_item`:return Wn(e.input,t);case`update_cms_item_field`:return Bn(e.input,t);case`update_content_block`:return Cn(e.input,t);case`insert_content_block`:return wn(e.input,t);case`update_current_cms_fields`:return Sn(e.input,t);case`update_footer`:return $t(e.input,t);case`update_navigation_bar`:return Qt(e.input,t);case`update_section_column_block`:return Tn(e.input,t);case`set_content_images`:return Ur(e.input,t)}}function Kn(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;let n=t[e.tool];return n?{...e,input:{...e.input,translationGroupId:n}}:e}function qn(e){return e===`create_cms_page`?`page`:e===`create_cms_post`?`post`:`product`}function Jn(e,t,n){if(e.tool!==`set_content_images`)return e;let r=e.input;if(r.entityId!==void 0)return e;let i=r.slug?t.get(`${r.contentType||`product`}:${V(r.slug)}`):n;return i?{...e,input:{...r,contentType:i.contentType,entityId:i.entityId}}:e}async function Yn(e,t){let n=me.parse(e),r=new Set(n.actions.filter(e=>e.tool===`create_cms_page`||e.tool===`create_cms_post`||e.tool===`create_cms_product`).map(e=>{let t=e.input;return`${qn(e.tool)}:${V(t.slug||t.title||``)}`})),i=e=>{if(e.tool!==`set_content_images`)return!1;let t=e.input;return t.slug?r.has(`${t.contentType||`product`}:${V(t.slug)}`):r.size>0};if(!t?.skipConfirmation){let e=[];for(let r of n.actions){if(i(r)){let t=r.input;e.push(`Set ${z(t.images.length,`image`)} on the ${t.slug?`"${t.slug}"`:`new`} item created in this plan.`);continue}let n=await Gn(r,{...t,latestUserMessage:null});if(!n||typeof n!=`object`)return{message:`Could not prepare action ${e.length+1}.`,mutationExecuted:!1,success:!1};if(n.success===!1||n.unsupported===!0)return n;n.requiresConfirmation===!0&&n.preview?e.push(We(r.tool,n.preview)):e.push(`Run ${r.tool.replace(/_/g,` `)}.`)}let r=n.summary||`Complete ${z(n.actions.length,`CMS action`)}.`,a=B({action:`EXECUTE CMS ACTION PLAN`,context:t,payload:{actions:n.actions,tool:`execute_cms_action_plan`},preview:{actionCount:n.actions.length,actionSummaries:e,summary:r},subject:`${n.actions.length} actions`});if(a)return a}let a={...t,skipConfirmation:!0},o=[],s=!1,c=null,l=null,u={},d=new Map,f=null;for(let[e,t]of n.actions.entries()){let r=Jn(Kn(t,u),d,f),i=await Gn(r,a);if(o.push({output:i,tool:r.tool}),i&&typeof i==`object`){let t=i;if(t.mutationExecuted===!0&&(s=!0),!c&&typeof t.editPath==`string`&&(c=t.editPath),typeof t.redirectPath==`string`&&(l=t.redirectPath),(r.tool===`create_cms_page`||r.tool===`create_cms_post`||r.tool===`create_cms_product`)&&(typeof t.translationGroupId==`string`&&(u[r.tool]=t.translationGroupId),t.entityId!==void 0&&t.entityId!==null)){let e=qn(r.tool),n={contentType:e,entityId:t.entityId};f=n,typeof t.slug==`string`&&d.set(`${e}:${t.slug}`,n)}if(t.success===!1||t.unsupported===!0)return{actionCount:n.actions.length,failedActionIndex:e,failedTool:r.tool,message:typeof t.message==`string`?t.message:`Action ${e+1} failed.`,mutationExecuted:s,results:o,success:!1,...c?{editPath:c}:{},...l?{redirectPath:l}:{}}}}return{actionCount:n.actions.length,editPath:l?void 0:c??void 0,mutationExecuted:s,redirectPath:l??void 0,results:o,success:!0,summary:n.summary??null}}var Xn=u.z.strictObject({maxChars:u.z.number().int().min(500).max(2e4).default(8e3).describe(`Maximum characters of readable body text to return.`),url:u.z.string().trim().min(1).max(2048).refine(e=>/^https?:\/\//i.test(e),`URL must start with http:// or https://.`)}),Zn=12e3,Qn=2e6;function $n(e){return e.replace(/<[^>]+>/g,` `).replace(/ /gi,` `).replace(/&/gi,`&`).replace(/</gi,`<`).replace(/>/gi,`>`).replace(/"/gi,`"`).replace(/'/gi,`'`).replace(/\s+/g,` `).trim()}function er(e){return e.trim().replace(/&/gi,`&`).replace(/&/g,`&`).replace(/"/gi,`"`).replace(/'/g,`'`)}var tr=/\.(avif|gif|jpe?g|png|webp)(?:[?#]|$)/i,nr=/(?:^|[/_-])(?: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 rr(e,t){if(typeof e!=`string`)return null;let n=er(e);if(!n||n.startsWith(`data:`))return null;try{let e=new URL(n,t);return e.protocol!==`http:`&&e.protocol!==`https:`?null:e.toString()}catch{return null}}function ir(e){let t=null;for(let n of e.split(`,`)){let e=n.trim().split(/\s+/),r=e[0];if(!r)continue;let i=e[1]||``,a=i.match(/^(\d+(?:\.\d+)?)w$/i),o=i.match(/^(\d+(?:\.\d+)?)x$/i),s=a?Number(a[1]):o?Number(o[1])*1e3:1;(!t||s>t.weight)&&(t={url:r,weight:s})}return t?.url??null}function $(e,t){let n=e.match(RegExp(`\\b${t}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`,`i`));return n?n[1]??n[2]??n[3]??null:null}function ar(e,t){let n=[],r=[],i=(e,n)=>{if(typeof e==`string`){let r=rr(e,t);r&&n.push(r);return}if(Array.isArray(e)){for(let t of e)i(t,n);return}e&&typeof e==`object`&&(i(e.url,n),i(e.contentUrl,n))},a=(e,t)=>{if(t>8||!e||typeof e!=`object`)return;if(Array.isArray(e)){for(let n of e)a(n,t+1);return}let o=e,s=o[`@type`],c=(Array.isArray(s)?s:[s]).filter(e=>typeof e==`string`).map(e=>e.toLowerCase()).some(e=>e===`product`||e===`productgroup`||e===`itempage`);`image`in o&&i(o.image,c?n:r);for(let e of Object.values(o))a(e,t+1)},o=e.matchAll(/<script\b[^>]*type\s*=\s*["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi);for(let e of o){let t=(e[1]||``).trim();if(t)try{a(JSON.parse(t),0)}catch{}}return[...n,...r]}var or=/(?:^|[/_-])(?:thumbnails?|thumbs?|small|mini)(?:[/_.-]|$)/i;function sr(e){try{let{pathname:t}=new URL(e);return decodeURIComponent(t.slice(t.lastIndexOf(`/`)+1)).toLowerCase()||null}catch{return null}}function cr(e,t){let n=new Map;for(let r of e.matchAll(/<a\b[^>]*>/gi)){let e=rr($(r[0],`href`),t);if(!e||!tr.test(e)||or.test(e)||nr.test(e))continue;let i=sr(e);i&&!n.has(i)&&n.set(i,e)}return n}function lr(e,t){let n=[...ar(e,t)];for(let r of[/<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(let i of e.matchAll(r)){let e=i[0],r=rr($(e,`content`)||$(e,`href`),t);r&&n.push(r)}let r=[];for(let n of e.matchAll(/<img\b[^>]*>/gi)){let e=n[0],i=$(e,`srcset`)||$(e,`data-srcset`),a=[i?ir(i):null,$(e,`src`),$(e,`data-src`),$(e,`data-original`),$(e,`data-lazy-src`),$(e,`data-image`)],o=null;for(let e of a)if(o=rr(e,t),o)break;if(!o||nr.test(o))continue;let s=Number($(e,`width`));Number.isFinite(s)&&s>0&&s<200||r.push(o)}let i=e=>tr.test(e);n.push(...r.filter(i),...r.filter(e=>!i(e)));let a=cr(e,t),o=e=>{if(!or.test(e))return e;let t=sr(e);return t&&a.get(t)||e},s=new Set,c=[];for(let e of n){let t=o(e);if(!s.has(t)&&(s.add(t),c.push(t),c.length>=12))break}return{images:c,mainImage:c[0]??null}}function ur(e,t,n){let r=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:i,mainImage:a}=lr(e,n),o=e.match(/<title\b[^>]*>([\s\S]*?)<\/title>/i),s=e.match(/<meta[^>]+name=["']description["'][^>]*content=["']([^"']*)["'][^>]*>/i)||e.match(/<meta[^>]+content=["']([^"']*)["'][^>]*name=["']description["'][^>]*>/i),c=[...r.matchAll(/<h([1-3])\b[^>]*>([\s\S]*?)<\/h\1>/gi)].map(e=>$n(e[2])).filter(Boolean).slice(0,40),l=$n(r.match(/<body\b[^>]*>([\s\S]*?)<\/body>/i)?.[1]??r);return{description:s?$n(s[1]):``,headings:c,images:i,mainImage:a,text:l.slice(0,t),title:o?$n(o[1]):``,truncated:l.length>t}}async function dr(e){let t=Xn.parse(e),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(a.isBlockedFetchHost(n.hostname))return{message:`Refusing to fetch a local, private, or internal address.`,success:!1,url:t.url};let r=new AbortController,i=setTimeout(()=>r.abort(),Zn);try{let e=await fetch(n.toString(),{headers:{accept:`text/html,application/xhtml+xml,text/plain`,"user-agent":`NextBlockCortexAI/1.0 (+https://nextblock.dev)`},redirect:`follow`,signal:r.signal});if(!e.ok)return{message:`The URL responded with HTTP ${e.status}.`,status:e.status,success:!1,url:t.url};let i=e.url||n.toString();try{if(a.isBlockedFetchHost(new URL(i).hostname))return{message:`The URL redirected to a blocked internal address.`,success:!1,url:t.url}}catch{}let o=e.headers.get(`content-type`)||``;if(!/text\/html|text\/plain|application\/xhtml/i.test(o))return{contentType:o,message:`The URL is not an HTML or text page (content-type: ${o||`unknown`}).`,success:!1,url:t.url};let s=await e.text(),c=ur(s.length>Qn?s.slice(0,Qn):s,t.maxChars,i);return!c.text&&!c.title?{message:`The URL returned no readable text content.`,success:!1,url:t.url}:{description:c.description,finalUrl:i,headings:c.headings,images:c.images,mainImage:c.mainImage,success:!0,text:c.text,title:c.title,truncated:c.truncated,url:t.url}}catch(e){return{message:e instanceof Error&&(e.name===`AbortError`||/abort/i.test(e.message))?`Fetching the URL timed out.`:`Failed to fetch the URL: ${I(e)}`,success:!1,url:t.url}}finally{clearTimeout(i)}}var fr=u.z.strictObject({count:u.z.number().int().min(1).max(15).default(6),orientation:u.z.enum([`landscape`,`portrait`,`square`]).optional().describe(`Preferred image orientation. Use landscape for hero/section backgrounds.`),query:u.z.string().trim().min(2).max(200).describe(`What the photos should depict, e.g. "herbal supplements".`)}),pr=12e3;async function mr(e){let t=null,n=null;if(e)try{let{CORTEX_AI_PEXELS_SETTING_KEY:r,CORTEX_AI_UNSPLASH_SETTING_KEY:i,decryptStoredOpenRouterApiKey:a}=await Promise.resolve().then(()=>require("./ai-config.cjs")),o=e=>{if(!e)return null;try{let t=a(e);return typeof t==`string`&&t.trim()?t.trim():null}catch{return null}},{data:s}=await e.from(`site_settings`).select(`key, value`).in(`key`,[r,i]),c=Array.isArray(s)?s:[];t=o(c.find(e=>e.key===r)?.value),n=o(c.find(e=>e.key===i)?.value)}catch{}t||=process.env.PEXELS_API_KEY?.trim()||null,n||=process.env.UNSPLASH_ACCESS_KEY?.trim()||null;let r=[];return t&&r.push({apiKey:t,provider:`pexels`}),n&&r.push({apiKey:n,provider:`unsplash`}),r}async function hr(e){return(await mr(e))[0]??null}async function gr(e){if(e)try{let{CORTEX_AI_UNSPLASH_APP_NAME_SETTING_KEY:t}=await Promise.resolve().then(()=>require("./ai-config.cjs")),{data:n}=await e.from(`site_settings`).select(`value`).eq(`key`,t).maybeSingle(),r=n?.value;if(typeof r==`string`&&r.trim())return r.trim()}catch{}return process.env.UNSPLASH_APP_NAME?.trim()||null}async function _r(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),pr);try{let r=await fetch(e,{headers:t,signal:n.signal});if(!r.ok)throw Error(`Stock photo provider responded with HTTP ${r.status}.`);return await r.json()}finally{clearTimeout(r)}}function vr(e){let t=Number(e);return Number.isFinite(t)&&t>0?t:null}function yr(e,t){if(!W(e))return;let n=e=>{W(e)&&e.provider===`unsplash`&&typeof e.downloadLocation==`string`&&e.downloadLocation.trim()&&t.add(e.downloadLocation.trim())};if(n(e.attribution),W(e.background)&&W(e.background.image)&&n(e.background.image.attribution),Array.isArray(e.column_blocks)){for(let n of e.column_blocks)if(Array.isArray(n))for(let e of n)W(e)&&yr(e.content,t)}if(Array.isArray(e.slides))for(let n of e.slides)yr(n,t)}async function br(e,t){try{let n=new Set;for(let t of e)yr(t?.content,n);if(n.size===0)return;let r=(await mr(t)).find(e=>e.provider===`unsplash`);if(!r)return;await Promise.all([...n].map(e=>fetch(e,{headers:{Authorization:`Client-ID ${r.apiKey}`}}).catch(()=>void 0)))}catch{}}async function xr(e,t,n){let r=new URLSearchParams({per_page:String(t.count),query:t.query});if(t.orientation&&r.set(`orientation`,t.orientation),e.provider===`pexels`){let n=await _r(`https://api.pexels.com/v1/search?${r.toString()}`,{Authorization:e.apiKey});return(Array.isArray(n?.photos)?n.photos:[]).map(e=>{let n=typeof e?.photographer==`string`?e.photographer:null;return{alt:typeof e?.alt==`string`&&e.alt.trim()?e.alt.trim():t.query,credit:n?`Photo by ${n} on Pexels`:`Photo on Pexels`,downloadLocation:null,height:vr(e?.height),photographer:n,photographerUrl:typeof e?.photographer_url==`string`?e.photographer_url:null,provider:`pexels`,sourceUrl:typeof e?.url==`string`?e.url:null,thumbnailUrl:e?.src?.medium||e?.src?.large||null,url:e?.src?.large2x||e?.src?.large||e?.src?.original||null,width:vr(e?.width)}}).filter(e=>typeof e.url==`string`)}let i=await _r(`https://api.unsplash.com/search/photos?${r.toString()}`,{Authorization:`Client-ID ${e.apiKey}`});return(Array.isArray(i?.results)?i.results:[]).map(e=>{let r=typeof e?.user?.name==`string`?e.user.name:null;return{alt:typeof e?.alt_description==`string`&&e.alt_description.trim()||typeof e?.description==`string`&&e.description.trim()||t.query,credit:r?`Photo by ${r} on Unsplash`:`Photo on Unsplash`,downloadLocation:typeof e?.links?.download_location==`string`?e.links.download_location:null,height:vr(e?.height),photographer:r,photographerUrl:typeof e?.user?.links?.html==`string`?e.user.links.html:null,provider:`unsplash`,sourceUrl:typeof e?.links?.html==`string`?e.links.html:null,thumbnailUrl:e?.urls?.small||e?.urls?.thumb||null,url:e?.urls?.regular||e?.urls?.full||e?.urls?.raw||null,utmSource:n||null,width:vr(e?.width)}}).filter(e=>typeof e.url==`string`)}async function Sr(e,t){let n=fr.parse(e),r=await mr(t?.supabase);if(r.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};let i=r.some(e=>e.provider===`unsplash`)?await gr(t?.supabase):null,a=[],o=null;for(let e of r){a.push(e.provider);try{let t=await xr(e,n,i);if(t.length>0)return{attemptedProviders:a,photos:t,provider:e.provider,query:n.query,success:!0,usageGuidance:e.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). Also copy the photo\'s `width` and `height` into the image content: the page then reserves the right space before the file loads instead of shifting.':'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. Also copy each photo `width` and `height` into the image content: the page then reserves the right space before the file loads instead of shifting.'}}catch(e){o=e}}return{attemptedProviders:a,message:o?`Stock photo search failed across ${a.join(`, `)}: ${I(o)}`:`No matching stock photos found for "${n.query}".`,photos:[],success:!1}}var Cr=T.extend({blocks:u.z.array(A).min(1).max(20),meta:u.z.strictObject({meta_description:u.z.string().max(500).nullable().optional(),meta_title:u.z.string().max(160).nullable().optional(),slug:u.z.string().trim().min(1).max(300).optional(),status:u.z.enum([`draft`,`published`,`archived`]).optional(),title:u.z.string().trim().min(1).max(300).optional()}).partial().optional()}),wr=[`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){let t={};for(let n of wr)n in e&&e[n]!==void 0&&(t[n]=e[n]);return t}function Er(e,t){if(!t)return null;let n=e===`page`?t===`home`?`/`:`/${t}`:`/article/${t}`;return`/api/draft/start?path=${encodeURIComponent(n)}`}async function Dr(e,t){let n=Cr.parse(e);t=await G(t,n.blocks);let r=M(t),i=Ge(t),a=await Y(n,t);if(a.contentType===`product`)throw Error(`rewrite_page_draft supports pages and posts only. Products use description_json, not page blocks.`);let o=a.contentType,s=Number(a.item.id);if(!Number.isInteger(s)||s<=0)throw Error(`Could not resolve a valid page/post id for the draft rewrite.`);let c=Number(a.item.language_id);if(!Number.isInteger(c)||c<=0)throw Error(`The target page/post is missing a language id.`);let l=Gt(n.blocks,void 0,void 0,t).map((e,t)=>({block_type:e.block_type,content:e.content,language_id:c,order:t,page_id:o===`page`?s:null,post_id:o===`post`?s:null,product_id:null})),u=Tr(a.item);if(n.meta)for(let[e,t]of Object.entries(n.meta))t!==void 0&&(u[e]=t);let d=Pe(typeof u.slug==`string`?u.slug:a.item.slug),f=typeof u.title==`string`&&u.title.trim()?u.title:String(a.item.title||d||`Untitled`),p=o===`page`?`/cms/pages/${s}/edit`:`/cms/posts/${s}/edit`,m=Er(o,d),h=B({action:`REWRITE DRAFT`,context:t,payload:{blocks:l,meta:u,parent_id:s,parent_type:o,tool:`rewrite_page_draft`},preview:{blockCount:l.length,contentType:o,slug:d,summary:`Stage a Live Draft that replaces the ${o} "${f}" with ${z(l.length,`new block`)}. Nothing goes live until you review the draft and click Publish (which also saves a revision snapshot).`,title:f},subject:`${o}-${s}`});if(h)return h;let g=Number(a.item.version)||1,{error:_}=await r.from(`content_drafts`).delete().eq(`parent_type`,o).eq(`parent_id`,s);if(_)throw Error(`Failed to clear the existing draft: ${I(_)}`);let{error:v}=await r.from(`content_drafts`).insert({author_id:i,base_version:g,blocks:l,meta:u,parent_id:s,parent_type:o});if(v)throw Error(`Failed to save the draft: ${I(v)}`);return br(l,r),F(t,{contentType:o,entityId:s,languageId:c,slug:d,title:f},d),{blockCount:l.length,contentType:o,draftPreviewPath:m,editPath:p,entityId:s,isDraft:!0,mutationExecuted:!0,slug:d,success:!0,title:f}}var Or=u.z.strictObject({attributes:u.z.array(u.z.strictObject({name:u.z.string().trim().min(1).max(120).describe(`Attribute name, e.g. "Size" or "Flavour".`),terms:u.z.array(u.z.string().trim().min(1).max(120)).min(1).max(50).describe(`Every possible value for this attribute, e.g. ["100 ml", "500 ml"].`)})).max(5).optional().describe(`The option axes this product varies on. Attributes and terms are global and reused across products: an existing one with the same name is matched, never duplicated. Omit if the attributes already exist.`),entityId:u.z.union([u.z.number().int().positive(),u.z.string().trim().min(1).max(120)]).optional(),mode:u.z.enum([`replace`,`append`]).default(`replace`).describe(`"replace" removes the product's existing variants first; "append" keeps them and adds these.`),slug:u.z.string().trim().min(1).max(300).optional(),title:u.z.string().trim().min(1).max(300).optional(),variants:u.z.array(u.z.strictObject({image:u.z.string().trim().min(1).max(2048).optional().describe(`Variant-specific image: an https:// URL (imported automatically) or a media library id.`),options:u.z.record(u.z.string(),u.z.string()).describe(`Which term this variant is, per attribute, e.g. { "Size": "500 ml" }. Every attribute must be given a value.`),price:u.z.number().min(0).optional().describe(`Price in major units (25 = $25.00). Defaults to the product price.`),sale_price:u.z.number().min(0).nullable().optional().describe(`Sale price in major units, or null for none.`),sku:u.z.string().trim().min(1).max(120).describe(`Unique SKU for this variant.`),stock:u.z.number().int().min(0).default(0),upc:u.z.string().trim().max(120).nullable().optional()})).min(1).max(50)});async function kr(e,t){let n=V(t.name),{data:r}=await e.from(`product_attributes`).select(`id`).eq(`slug`,n).maybeSingle(),i=r?.id;if(!i){let{data:r,error:a}=await e.from(`product_attributes`).insert({name:t.name,slug:n}).select(`id`).single();if(a||!r?.id)throw Error(`Could not create the "${t.name}" attribute: ${I(a)}`);i=r.id}let a=new Map;for(let n=0;n<t.terms.length;n+=1){let r=t.terms[n],o=V(r),{data:s}=await e.from(`product_attribute_terms`).select(`id`).eq(`attribute_id`,i).eq(`slug`,o).maybeSingle();if(s?.id){a.set(r,s.id);continue}let{data:c,error:l}=await e.from(`product_attribute_terms`).insert({attribute_id:i,slug:o,sort_order:n,value:r}).select(`id`).single();if(l||!c?.id)throw Error(`Could not create the "${r}" option: ${I(l)}`);a.set(r,c.id)}return{attributeId:i,termIdByValue:a}}async function Ar(e,t){let n=Or.parse(e),r=M(t),i=(await Y({contentType:`product`,...n.entityId===void 0?{}:{entityId:n.entityId},...n.slug?{slug:n.slug}:{},...n.title?{title:n.title}:{}},t)).item,a=String(i.id),o=B({action:`SET VARIANTS`,context:t,payload:{entityId:a,mode:n.mode,variantCount:n.variants.length},preview:{contentType:`product`,slug:i.slug,summary:`${n.mode===`replace`?`Replace`:`Add`} ${z(n.variants.length,`variant`)} on "${i.title}". Product stock becomes the sum of variant stock.`,title:i.title},subject:`product-${a}-variants`});if(o)return o;let s=new Map;for(let e of n.attributes??[]){let{termIdByValue:t}=await kr(r,e);s.set(e.name,t)}for(let e of n.variants)for(let[t,n]of Object.entries(e.options)){if(s.get(t)?.has(n))continue;let{data:e}=await r.from(`product_attributes`).select(`id`).eq(`slug`,V(t)).maybeSingle();if(!e?.id)throw Error(`Unknown attribute "${t}". Pass it in \`attributes\` with its full list of terms.`);let{data:i}=await r.from(`product_attribute_terms`).select(`id`).eq(`attribute_id`,e.id).eq(`slug`,V(n)).maybeSingle();if(!i?.id)throw Error(`Unknown option "${n}" for attribute "${t}". Add it to that attribute's \`terms\`.`);let a=s.get(t)??new Map;a.set(n,i.id),s.set(t,a)}if(n.mode===`replace`){let{error:e}=await r.from(`product_variants`).delete().eq(`product_id`,a);if(e)throw Error(`Could not clear the existing variants: ${I(e)}`)}let c=await _t(r),l=Number(i.price)||0,u=[];for(let e of n.variants){let n=e.image?await P(e.image,t,`${i.title} ${e.sku}`):null,{data:o,error:d}=await r.from(`product_variants`).insert({main_media_id:n,price:e.price===void 0?l:Xe(e.price,c),product_id:a,sale_price:e.sale_price===void 0||e.sale_price===null?null:Xe(e.sale_price,c),sku:e.sku,stock_quantity:e.stock,upc:e.upc??null}).select(`id`).single();if(d||!o?.id)throw Error(`Could not create variant "${e.sku}": ${I(d)}`);let f=Object.entries(e.options).map(([e,t])=>({attribute_term_id:s.get(e)?.get(t),variant_id:o.id}));if(f.length>0){let{error:t}=await r.from(`variant_attribute_mapping`).insert(f);if(t)throw Error(`Could not link variant "${e.sku}" to its options: ${I(t)}`)}u.push(e.sku)}let{data:d}=await r.from(`product_variants`).select(`stock_quantity`).eq(`product_id`,a),f=(d??[]).reduce((e,t)=>e+(Number(t?.stock_quantity)||0),0),{error:p}=await r.from(`products`).update({stock:f}).eq(`id`,a);if(p)throw Error(`Variants saved, but the product stock total failed: ${I(p)}`);return F(t,{contentType:`product`,entityId:a,slug:i.slug,title:i.title},i.slug),{contentType:`product`,entityId:a,mode:n.mode,mutationExecuted:!0,skus:u,slug:i.slug,success:!0,totalStock:f,variantCount:u.length}}var jr=u.z.strictObject({items:u.z.array(u.z.strictObject({contentType:u.z.enum([`page`,`post`]).default(`page`),slug:u.z.string().trim().min(1).max(300).describe(`Slug of the source page or post.`),title:u.z.string().trim().min(1).max(300).optional().describe(`Translated title. Defaults to translating the source title.`),translations:u.z.record(u.z.string(),u.z.string()).describe(`Source string -> translated string for every visible string in THIS item.`)})).min(1).max(25),targetLanguageCode:u.z.string().trim().min(2).max(80).describe(`Target language code or name, e.g. "fr". The language must already exist — create it with manage_language first.`)});async function Mr(e,t){let n=jr.parse(e),r=B({action:`TRANSLATE BULK`,context:t,payload:{count:n.items.length,language:n.targetLanguageCode},preview:{contentType:`page`,summary:`Create ${n.targetLanguageCode} translations of ${z(n.items.length,`item`)}: ${n.items.map(e=>e.slug).join(`, `)}.`,title:`Bulk translate to ${n.targetLanguageCode}`},subject:`bulk-translate-${n.targetLanguageCode}`});if(r)return r;let i=[],a=[];for(let e of n.items)try{let r=await Hr({cmsTarget:{contentType:e.contentType,slug:e.slug},targetLanguageCode:n.targetLanguageCode,...e.title?{title:e.title}:{},translations:e.translations},t);i.push({slug:e.slug,...r})}catch(t){a.push({error:t instanceof Error?t.message:String(t),slug:e.slug})}return{failed:a,failedCount:a.length,mutationExecuted:i.length>0,success:a.length===0,targetLanguageCode:n.targetLanguageCode,translated:i,translatedCount:i.length}}var Nr=u.z.strictObject({action:u.z.enum([`publish`,`discard`]).default(`publish`).describe(`"publish" applies the draft to the live page/post; "discard" deletes it and leaves the live content untouched.`),contentType:u.z.enum([`page`,`post`]).optional(),entityId:u.z.union([u.z.number().int().positive(),u.z.string().trim().min(1).max(120)]).optional(),slug:u.z.string().trim().min(1).max(300).optional(),title:u.z.string().trim().min(1).max(300).optional()}),Pr=[`title`,`slug`],Fr=[`custom_canonical`,`feature_image_id`,`meta_description`,`meta_title`];async function Ir(e,t){let n=Nr.parse(e),r=M(t),i=await X({...n.contentType?{contentType:n.contentType}:{},...n.entityId===void 0?{}:{entityId:n.entityId},...n.slug?{slug:n.slug}:{},...n.title?{title:n.title}:{}},t);if(i.contentType===`product`)throw Error(`publish_content_draft supports pages and posts. Product drafts live in product_drafts and are published from the product editor.`);let a=i.contentType,o=De(i),s=a===`page`?`pages`:`posts`,{data:c,error:l}=await r.from(`content_drafts`).select(`*`).eq(`parent_type`,a).eq(`parent_id`,o).maybeSingle();if(l)throw Error(`Failed to read the draft: ${I(l)}`);if(!c)return{contentType:a,entityId:o,message:`No Live Draft exists for ${a} "${i.title||i.slug}". Nothing to ${n.action}.`,mutationExecuted:!1,success:!1};let u=i.title||i.slug||`${a} ${o}`,p=B({action:n.action===`publish`?`PUBLISH DRAFT`:`DISCARD DRAFT`,context:t,payload:{action:n.action,contentType:a,entityId:String(o)},preview:{contentType:a,slug:i.slug,summary:n.action===`publish`?`Publish the Live Draft for ${a} "${u}", replacing its live blocks. A revision snapshot is saved first, so this is reversible from Revision History.`:`Discard the Live Draft for ${a} "${u}". The live content is left untouched.`,title:i.title},subject:`${a}-${o}-draft`});if(p)return p;let m=c.meta??{},h=Array.isArray(c.blocks)?c.blocks:[];if(n.action===`discard`){let{error:e}=await r.from(`content_drafts`).delete().eq(`id`,c.id);if(e)throw Error(`Failed to discard the draft: ${I(e)}`);return F(t,i,i.slug),{action:`discard`,contentType:a,entityId:o,mutationExecuted:!0,success:!0}}let g=await d(t,a,o),_={};for(let e of Pr){let t=m[e];typeof t==`string`&&t.trim()&&(_[e]=t.trim())}for(let e of Fr)if(Object.prototype.hasOwnProperty.call(m,e)){let t=m[e];_[e]=typeof t==`string`&&t.trim()?t.trim():null}if(Object.keys(_).length>0){let{error:e}=await r.from(s).update(_).eq(`id`,o);if(e)throw Error(`Failed to apply the draft metadata: ${I(e)}`)}let v=a===`page`?`page_id`:`post_id`,{error:y}=await r.from(`blocks`).delete().eq(v,o);if(y)throw Error(`Failed to clear the live blocks: ${I(y)}`);let b=Number(m.language_id)||Number(i.languageId)||Number(h[0]?.language_id)||0;if(h.length>0){let e=h.map((e,t)=>({block_type:e?.block_type,content:e?.content??{},language_id:Number(e?.language_id)||b,order:Number.isFinite(e?.order)?e.order:t,page_id:a===`page`?o:null,post_id:a===`post`?o:null,product_id:null})),{error:t}=await r.from(`blocks`).insert(e);if(t)throw Error(`Failed to publish the draft blocks: ${I(t)}`)}await f(t,a,o,g);let{error:x}=await r.from(`content_drafts`).delete().eq(`id`,c.id),S=typeof _.slug==`string`?_.slug:i.slug;return F(t,{...i,slug:S},S??void 0),{action:`publish`,blockCount:h.length,contentType:a,entityId:o,mutationExecuted:!0,slug:S,success:!0,...x?{warning:`Published, but the draft row was not removed: ${I(x)}`}:{}}}var Lr=new Set([`alt_text`,`author_name`,`author_title`,`caption`,`html_content`,`label`,`placeholder`,`quote`,`submit_button_text`,`success_message`,`text`,`text_content`,`title`]);function Rr(e,t,n){if(!e)return e;if(Object.prototype.hasOwnProperty.call(t,e))return t[e];let r=e.trim();if(r!==e&&Object.prototype.hasOwnProperty.call(t,r))return e.replace(r,t[r]);let i=e;for(let[e,t]of n)e&&i.includes(e)&&(i=i.split(e).join(t));return i}function zr(e,t,n,r){if(Array.isArray(e))return e.map(e=>zr(e,t,n,r));if(e&&typeof e==`object`){let i={};for(let[a,o]of Object.entries(e))i[a]=typeof o==`string`&&(Lr.has(a)||r?.has(a))?Rr(o,t,n):o&&typeof o==`object`?zr(o,t,n,r):o;return i}return e}function Br(e,n){if(typeof e!=`string`||t.isValidBlockType(e))return;let r=et(e,n);if(r)return new Set(t.readCustomBlockFields(r).filter(e=>e.type===`text`||e.type===`rich-text`).map(e=>e.key))}var Vr=u.z.strictObject({cmsTarget:E,targetLanguageCode:u.z.string().trim().min(2).max(80).describe(`Target language code or name, e.g. "fr" or "French".`),title:u.z.string().trim().min(1).max(300).optional().describe(`Translated page title (defaults to translating the source title).`),translations:u.z.record(u.z.string(),u.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 Hr(e,t){let n=Vr.parse(e),r=await X(n.cmsTarget,t);if(r.contentType===`product`)throw Error(`translate_page supports pages and posts only.`);let i=M(t),a=De(r),o=r.contentType===`page`?`pages`:`posts`,s=r.contentType===`page`?`page_id`:`post_id`,{data:c,error:l}=await i.from(o).select(`*`).eq(`id`,a).single();if(l||!c)throw Error(`Could not read the source ${r.contentType} to translate: ${I(l)}`);let{data:u,error:d}=await i.from(`blocks`).select(`id, block_type, content, order`).eq(s,a);if(d)throw Error(`Could not read the source blocks: ${I(d)}`);let f=(Array.isArray(u)?u:[]).slice().sort((e,t)=>Number(e.order)-Number(t.order));if(f.length===0)throw Error(`The source ${r.contentType} has no content blocks to translate.`);t=await G(t,f);let p=n.translations||{},m=Object.entries(p).filter(([e])=>!!e).sort((e,t)=>t[0].length-e[0].length),h=f.map((e,n)=>({blockType:e.block_type,content:zr(U(e.content),p,m,Br(e.block_type,t)),order:n})),g=await gt(i,n.targetLanguageCode),_=String(c.title||``),v=n.title||Rr(_,p,m)||_||`Untitled`,y=e=>typeof e==`string`&&e.trim()?Rr(e,p,m):void 0,b=V(v)||c.slug||`translated-page`,x={blocks:h,feature_image_id:c.feature_image_id??void 0,languageCode:g.code,meta_description:y(c.meta_description),meta_title:y(c.meta_title),slug:b,status:`published`,title:v,translationGroupId:c.translation_group_id||void 0},S=r.contentType===`post`?{...x,excerpt:y(c.excerpt),label:y(c.label),published_at:c.published_at??new Date().toISOString(),subtitle:y(c.subtitle)}:x,C=B({action:`TRANSLATE`,context:t,payload:{createInput:S,sourceId:c.id,tool:`translate_page`},preview:{blockCount:h.length,contentType:r.contentType,languageCode:g.code,slug:x.slug,status:x.status,summary:`Publish a ${g.code.toUpperCase()} translation of "${_}" — it goes live immediately, linked to the original ${r.contentType}, at /${x.slug} with ${z(h.length,`translated block`)}.`,title:v},subject:`translate ${r.contentType} ${c.id} to ${g.code}`});if(C)return C;let w={...t,skipConfirmation:!0};return{...r.contentType===`post`?await Dn(S,w):await En(S,w),isTranslation:!0,languageCode:g.code}}async function Ur(e,t){let n=j.parse(e),r=n.entityId!==void 0||!!n.slug||!!n.title,i=M(t),a,o;if(r){let e=await Y({contentType:n.contentType,entityId:n.entityId,slug:n.slug,title:n.title},t),r=e.item;o=r.id,a={contentType:e.contentType,entityId:o,slug:typeof r.slug==`string`?r.slug:``,title:typeof r.title==`string`?r.title:``}}else a=Ee(t),o=N(a);let s=a.title||a.slug||`current item`,c=a.contentType===`product`,l=B({action:`SET IMAGES`,context:t,payload:{contentType:a.contentType,entityId:String(o),images:n.images,tool:`set_content_images`},preview:{contentType:a.contentType,imageCount:n.images.length,slug:a.slug,summary:c?`Set ${z(n.images.length,`image`)} on product "${s}" (the first becomes the main product image, the rest the gallery).`:`Set the feature image on the ${a.contentType} "${s}".`,title:a.title},subject:`set images on ${a.contentType} ${String(o)}`});if(l)return l;let u=await je(n.images,t,s);if(u.length===0)throw Error(`None of the provided images could be resolved to a media item.`);if(c){let{data:e,error:n}=await i.from(`products`).select(`id, slug, language_id, title`).eq(`id`,o).maybeSingle();if(n||!e)throw Error(`Could not load the product to set images: ${I(n)}`);let r=await Me({mediaIds:u,productId:o,supabase:i});return await Ne({patch:({meta:e})=>Array.isArray(e.product_media)?{meta:{...e,product_media:r.map((e,t)=>({media_id:e,sort_order:t}))}}:{},productId:o,supabase:i}),F(t,{contentType:`product`,entityId:String(o),languageId:e.language_id,slug:e.slug,title:e.title},e.slug),t?.revalidatePath?.(`/cms/products`),{contentType:`product`,entityId:o,imageCount:r.length,mutationExecuted:!0,slug:e.slug,success:!0}}let p=await d(t,a.contentType,o),m=a.contentType===`page`?`pages`:`posts`,{data:h,error:g}=await i.from(m).update({feature_image_id:u[0],updated_at:new Date().toISOString()}).eq(`id`,o).select(`id, language_id, slug, status, title`).single();if(g||!h)throw Error(`Failed to set the feature image: ${I(g)}`);return await f(t,a.contentType,o,p),F(t,a,h.slug),{contentType:a.contentType,entityId:o,extraImagesIgnored:u.length-1,imageCount:1,mutationExecuted:!0,slug:h.slug,success:!0}}function Wr(t){return{...n.createCortexDatabaseAgentTools(t),...e.createCortexCustomBlockTools(t),...o.createCortexContentOpsTools(t),...r.createCortexThemingTools(t),...i.createCortexSiteTools(t),fetch_ecommerce_stats:(0,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:e=>fn(e,t),inputSchema:S,strict:!0}),read_current_cms_item:(0,c.tool)({description:"Read a CMS item: page/post/product metadata plus page/post block summaries or content. Defaults to the item currently open in the CMS editor; with no editor open (MCP clients) pass `cmsTarget` with contentType plus slug, entityId, or title. Read-only.",execute:e=>pn(e,t),inputSchema:ee,strict:!0}),search_documentation:(0,c.tool)({description:`Search the NextBlock documentation database and return concise source snippets for factual CMS guidance.`,execute:e=>an(e,t),inputSchema:x,strict:!0}),fetch_url_content:(0,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:e=>dr(e),inputSchema:Xn,strict:!0}),search_stock_photos:(0,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 (copy `width` and `height` into the same image content, so the page does not shift while the photo loads) 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:e=>Sr(e,t),inputSchema:fr,strict:!0}),manage_product_variants:(0,c.tool)({description:'Give a product sellable variations — size, flavour, colour, format — each with its own SKU, price, stock, and optional image. Define the option axes in `attributes` (name plus every term) and one entry in `variants` per purchasable combination, naming its term per attribute in `options`. Attributes and terms are global and reused across products, so an existing "Size" is matched rather than duplicated. Prices are in major units (25 = $25.00). The product\'s stock becomes the sum of its variants. Use mode "replace" to rebuild the variant set, "append" to add to it. Mutating: first returns a confirmation phrase; only executes after exact confirmation.',execute:e=>Ar(e,t),inputSchema:Or,strict:!0}),translate_content_bulk:(0,c.tool)({description:"Translate SEVERAL pages or posts into one language in a single call. Use this instead of repeating translate_page when making a site multilingual: pass the target language once and one entry per item, each with its own source-string -> translation map. Layout, blocks, and imagery are copied automatically and each copy is linked to its original as a translation. The language must exist first (manage_language). Items are processed independently, so one bad entry does not abandon the rest — check `failed` in the result. Mutating: first returns a confirmation phrase; only executes after exact confirmation.",execute:e=>Mr(e,t),inputSchema:jr,strict:!0}),publish_content_draft:(0,c.tool)({description:`Publish (or discard) the Live Draft staged on a page or post by generate_jsonb_layout / rewrite_page_draft. Publishing applies the draft blocks and metadata to the live record and snapshots a revision first, so it is reversible from Revision History; visibility (status/published_at) is never changed. Use this to finish a build that staged a draft — without it the new layout stays invisible on the public site. Target the record with contentType plus slug, entityId, or title. Mutating: first returns a confirmation phrase; only executes after exact confirmation.`,execute:e=>Ir(e,t),inputSchema:Nr,strict:!0}),rewrite_page_draft:(0,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:e=>Dr(e,t),inputSchema:Cr,strict:!0}),translate_page:(0,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. Targets the open page/post by default; with no editor open (MCP clients) pass `cmsTarget` with contentType plus slug, entityId, or title. Mutating: first returns a confirmation phrase; only creates the translation after exact confirmation.',execute:e=>Hr(e,t),inputSchema:Vr,strict:!0}),set_content_images:(0,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). On a PAGE the feature image renders as a full-width title banner above the blocks, so never set one on the home page or on a page that opens with its own hero section — use update_site_identity `social_image` for that page's share preview instead; posts should always have one. 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:e=>Ur(e,t),inputSchema:j,strict:!0}),create_cms_page:(0,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 a form block with fields; the destination address is configured once in CMS -> Messages and is never stored on the block.`,execute:e=>En(e,t),inputSchema:ie,strict:!0}),create_cms_post:(0,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:e=>Dn(e,t),inputSchema:ae,strict:!0}),create_cms_product:(0,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:e=>jn(e,t),inputSchema:oe,strict:!0}),delete_cms_item:(0,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:e=>Wn(e,t),inputSchema:le,strict:!0}),prepare_delete_cms_item:(0,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:e=>Un(e,t),inputSchema:ce,strict:!0}),update_footer:(0,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:e=>$t(e,t),inputSchema:b,strict:!0}),update_content_block:(0,c.tool)({description:'Update the JSON content of an existing top-level page/post block. The block must belong to the item being edited — the open CMS editor, or the item named by `cmsTarget` (contentType plus slug, entityId, or title) when no editor is open, as with MCP clients. 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:e=>Cn(e,t),inputSchema:O,strict:!0}),insert_content_block:(0,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:e=>wn(e,t),inputSchema:re,strict:!0}),update_current_cms_fields:(0,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:e=>Sn(e,t),inputSchema:D,strict:!0}),update_cms_item_field:(0,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:e=>Bn(e,t),inputSchema:se,strict:!0}),update_navigation_bar:(0,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:e=>Qt(e,t),inputSchema:y,strict:!0}),update_section_column_block:(0,c.tool)({description:"Update the content of one existing nested block inside a section block. The parent section must belong to the item being edited — the open CMS editor, or the item named by `cmsTarget` (contentType plus slug, entityId, or title) when no editor is open, as with MCP clients. 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:e=>Tn(e,t),inputSchema:k,strict:!0}),execute_cms_action_plan:(0,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:e=>Yn(e,t),inputSchema:me,strict:!0})}}exports.buildVisibleContactIntroActionPlan=Se,exports.cortexAiPageContextSchema=C,exports.createCmsPageInputSchema=ie,exports.createCmsPostInputSchema=ae,exports.createCmsProductInputSchema=oe,exports.createCortexGlobalAgentTools=Wr,exports.deleteCmsItemInputSchema=le,exports.executeCmsActionPlan=Yn,exports.executeCmsActionPlanInputSchema=me,exports.executeCreateCmsPage=En,exports.executeCreateCmsPost=Dn,exports.executeCreateCmsProduct=jn,exports.executeDeleteCmsItem=Wn,exports.executeFetchEcommerceStats=fn,exports.executeFetchUrlContent=dr,exports.executeInsertContentBlock=wn,exports.executeManageProductVariants=Ar,exports.executePrepareDeleteCmsItem=Un,exports.executePublishContentDraft=Ir,exports.executeReadCurrentCmsItem=pn,exports.executeRewritePageDraft=Dr,exports.executeSearchDocumentation=rn,exports.executeSearchDocumentationWithTimeout=an,exports.executeSearchStockPhotos=Sr,exports.executeSetContentImages=Ur,exports.executeTranslateContentBulk=Mr,exports.executeTranslatePage=Hr,exports.executeUpdateCmsItemField=Bn,exports.executeUpdateContentBlock=Cn,exports.executeUpdateCurrentCmsFields=Sn,exports.executeUpdateFooter=$t,exports.executeUpdateNavigationBar=Qt,exports.executeUpdateSectionColumnBlock=Tn,exports.fetchEcommerceStatsInputSchema=S,exports.fetchUrlContentInputSchema=Xn,exports.insertContentBlockInputSchema=re,exports.isBlockedFetchHost=a.isBlockedFetchHost,exports.manageProductVariantsInputSchema=Or,exports.maybeTriggerStockPhotoDownloads=br,exports.navigationItemInputSchema=_,exports.prepareDeleteCmsItemInputSchema=ce,exports.publishContentDraftInputSchema=Nr,exports.readCurrentCmsItemInputSchema=ee,exports.resolveCortexAiStockPhotoProvider=hr,exports.resolveCortexAiStockPhotoProviders=mr,exports.rewritePageDraftInputSchema=Cr,exports.searchDocumentationInputSchema=x,exports.searchStockPhotosInputSchema=fr,exports.setContentImagesInputSchema=j,exports.translateContentBulkInputSchema=jr,exports.translatePageInputSchema=Vr,exports.updateCmsItemFieldInputSchema=se,exports.updateContentBlockInputSchema=O,exports.updateCurrentCmsFieldsInputSchema=D,exports.updateFooterInputSchema=b,exports.updateNavigationBarInputSchema=y,exports.updateSectionColumnBlockInputSchema=k;
|
|
@@ -9,7 +9,7 @@ import { createCortexContentOpsTools as f } from "./ai-global-agent-content-ops-
|
|
|
9
9
|
import { editorDocumentFromHtml as p } from "./editor-document-from-html.es.js";
|
|
10
10
|
import { tool as m } from "ai";
|
|
11
11
|
import { revalidatePath as h } from "next/cache";
|
|
12
|
-
//#region
|
|
12
|
+
//#region src/lib/ai-global-agent-tools.ts
|
|
13
13
|
async function g(e, t, n) {
|
|
14
14
|
if (e?.recordRevision) try {
|
|
15
15
|
return await e.recordRevision({
|
package/lib/ai-key-crypto.es.js
CHANGED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=require("./ai-model-registry.cjs");var t=`Cortex AI OpenRouter model catalog can only be imported from server-side code.`;function n(){if(typeof window<`u`)throw Error(t)}function r(){let t=new URL(`${e.CORTEX_AI_OPENROUTER_BASE_URL}/models`);return t.searchParams.set(`supported_parameters`,e.CORTEX_AI_REQUIRED_MODEL_PARAMETERS.join(`,`)),t.searchParams.set(`output_modalities`,`text`),t.toString()}async function i(t){n();let i=await(t?.fetch||globalThis.fetch)(r(),{cache:`no-store`,headers:{Accept:`application/json`}});if(!i.ok)throw Error(`Failed to load OpenRouter models: ${i.status} ${i.statusText}`);return e.filterCortexAiCompatibleOpenRouterModels(await i.json(),t?.now)}exports.listCortexAiCompatibleOpenRouterModels=i;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { CORTEX_AI_OPENROUTER_BASE_URL as e, CORTEX_AI_REQUIRED_MODEL_PARAMETERS as t, filterCortexAiCompatibleOpenRouterModels as n } from "./ai-model-registry.es.js";
|
|
2
|
-
//#region
|
|
2
|
+
//#region src/lib/ai-model-catalog.ts
|
|
3
3
|
var r = "Cortex AI OpenRouter model catalog can only be imported from server-side code.";
|
|
4
4
|
function i() {
|
|
5
5
|
if (typeof window < "u") throw Error(r);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { APICallError as e } from "ai";
|
|
2
|
-
//#region
|
|
2
|
+
//#region src/lib/ai-model-registry.ts
|
|
3
3
|
var t = "https://openrouter.ai/api/v1", n = "openrouter/free", r = [
|
|
4
4
|
"nvidia/nemotron-3-super-120b-a12b:free",
|
|
5
5
|
"nvidia/nemotron-3-ultra-550b-a55b:free",
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
const e=require("./ai-model-registry.cjs");require("./zod-config.cjs");let t=require("ai"),n=require("zod");var r=`Cortex AI SEO metadata generation can only be imported from server-side code.`;function i(){if(typeof window<`u`)throw Error(r)}var a=n.z.strictObject({metaDescription:n.z.string().trim().min(1),metaTitle:n.z.string().trim().min(1),ogDescription:n.z.string().trim().min(1),ogTitle:n.z.string().trim().min(1)}),o={metaDescription:160,metaTitle:60,ogDescription:200,ogTitle:88},s=6e3,c=6e4,l=/[\s.,;:!?‐-―\-/\\|&+*_"'([{·•]+$/;function u(e,t){let n=e.trim();if(t<=0)return``;if(n.length<=t)return n;let r=n.slice(0,t),i=r.search(/\s\S*$/);return(i>0?r.slice(0,i):r).replace(l,``).trim()}function d(e){let t=e.replace(/```[a-zA-Z0-9]*/g,``),n=t.indexOf(`{`);if(n===-1)return null;let r=0,i=!1,a=!1;for(let e=n;e<t.length;e++){let o=t[e];if(i){a?a=!1:o===`\\`?a=!0:o===`"`&&(i=!1);continue}if(o===`"`){i=!0;continue}if(o===`{`){r++;continue}if(o===`}`&&(r--,r===0))return t.slice(n,e+1)}return null}function f(){let e=o;return[`You are NextBlock Cortex AI, an SEO metadata writer for a content management system.`,`Return ONLY a single JSON object. No markdown fences, no commentary, no explanation, no trailing prose.`,`The object must have exactly these four keys, all strings, all non-empty: "metaDescription", "metaTitle", "ogDescription", "ogTitle".`,`Do not add any other key.`,`metaTitle must be at most ${e.metaTitle} characters and read as a search-result headline for this specific page.`,`metaDescription must be at most ${e.metaDescription} characters, summarise what the page actually delivers, and end as a complete thought.`,`ogTitle must be at most ${e.ogTitle} characters and may be slightly more conversational than metaTitle, because it is read on a social card rather than in a results list.`,`ogDescription must be at most ${e.ogDescription} characters and should invite a click without over-promising.`,`Write plain text. No emoji, no surrounding quotation marks, no HTML, no markdown.`,`Describe only what the supplied content actually contains. Never invent statistics, prices, dates, awards, or claims that are not in the content.`,`Never keyword-stuff, never repeat the focus keyword more than twice across all four fields, and never pad a field to reach its character budget.`].join(` `)}function p(e){return[`Write SEO metadata for the following page.`,e.title?`Page title: ${e.title}`:null,e.siteTitle?`Site name: ${e.siteTitle}. Do not append the site name to metaTitle; the site appends it separately.`:null,e.focusKeyword?`Focus keyword: ${e.focusKeyword}. Use it naturally in metaTitle and metaDescription, at most once each.`:null,e.locale?`Write every field in this locale: ${e.locale}. Match its conventions for capitalisation and punctuation.`:null,`Page content:\n${e.content}`].filter(Boolean).join(`
|
|
2
|
+
|
|
3
|
+
`)}function m(e){let t=d(e);if(!t)throw Error(`Cortex AI returned no JSON object for the SEO metadata request.`);let n;try{n=JSON.parse(t)}catch(e){throw Error(`Cortex AI returned invalid JSON for the SEO metadata request: ${e instanceof Error?e.message:String(e)}`)}let r=a.parse(n);return{metaDescription:u(r.metaDescription,o.metaDescription),metaTitle:u(r.metaTitle,o.metaTitle),ogDescription:u(r.ogDescription,o.ogDescription),ogTitle:u(r.ogTitle,o.ogTitle)}}function h(t){let n=e.getHttpStatusCode(t);if(n===401||n===402||n===403)return!1;if(e.isOpenRouterRecoverableRoutingError(t)||n&&n>=500)return!0;let r=t instanceof Error?t.message:String(t);return/NoContentGenerated|No content generated|Provider returned error|no JSON object|invalid JSON|invalid_type|too_small|unrecognized_keys|Invalid input|aborted|abort|timeout|timed out/i.test(r)}async function g(n){i();let r=u(n.content,s);if(!r)throw Error(`Cortex AI SEO metadata generation requires non-empty page content.`);let{createCortexAiOpenRouterClient:a}=await Promise.resolve().then(()=>require("./ai-client.cjs")),o=await a({apiKey:n.apiKey||void 0}),l=e.buildCortexAiRoutingPolicy({credentialSource:o.credentialSource,requestedModelId:n.modelId,selectedModel:o.modelSelection}),d=await e.runWithCortexAiModelFallback({modelIds:l.modelIds,shouldRetry:h,execute:async i=>{let a=new AbortController,s=setTimeout(()=>a.abort(),c),u=()=>a.abort();n.abortSignal?.addEventListener(`abort`,u,{once:!0}),n.abortSignal?.aborted&&a.abort();try{let s=e.omitUnsupportedCortexAiModelOptions({abortSignal:a.signal,maxOutputTokens:700,maxRetries:0,prompt:p({content:r,focusKeyword:n.focusKeyword?.trim()||null,locale:n.locale?.trim()||null,siteTitle:n.siteTitle?.trim()||null,title:n.title?.trim()||null}),instructions:f(),temperature:.3},{modelId:i,modelSelection:l.modelSelection});return m((await(0,t.generateText)({...s,model:o.model(i)})).text)}finally{clearTimeout(s),n.abortSignal?.removeEventListener(`abort`,u)}}});return{attempts:d.attempts.length,credentialSource:o.credentialSource,metaDescription:d.result.metaDescription,metaTitle:d.result.metaTitle,modelId:d.modelId,ogDescription:d.result.ogDescription,ogTitle:d.result.ogTitle}}exports.CORTEX_AI_SEO_METADATA_CONTENT_BUDGET=s,exports.CORTEX_AI_SEO_METADATA_LENGTH_BUDGETS=o,exports.cortexAiSeoMetadataOutputSchema=a,exports.extractJsonObject=d,exports.generateCortexAiSeoMetadata=g,exports.truncateOnWordBoundary=u;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { buildCortexAiRoutingPolicy as e, getHttpStatusCode as t, isOpenRouterRecoverableRoutingError as n, omitUnsupportedCortexAiModelOptions as r, runWithCortexAiModelFallback as i } from "./ai-model-registry.es.js";
|
|
2
2
|
import { z as a } from "./zod-config.es.js";
|
|
3
3
|
import { generateText as o } from "ai";
|
|
4
|
-
//#region
|
|
4
|
+
//#region src/lib/ai-seo-metadata.ts
|
|
5
5
|
var s = "Cortex AI SEO metadata generation can only be imported from server-side code.";
|
|
6
6
|
function c() {
|
|
7
7
|
if (typeof window < "u") throw Error(s);
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
const e=require("./ai-model-registry.cjs"),t=require("./ai-seo-metadata.cjs");let n=require("ai");var r=`Cortex AI vision generation can only be imported from server-side code.`;function i(){if(typeof window<`u`)throw Error(r)}var a=[`google/gemma-4-31b-it:free`,`google/gemma-4-26b-a4b-it:free`,`google/gemini-2.5-flash-lite`,`qwen/qwen3-vl-32b-instruct`,`openai/gpt-4o-mini`,`google/gemini-2.5-flash`],o=[/(?:^|\/)[^/]*-vl(?:[-:]|$)/i,/vision/i,/(?:^|\/)gemini-/i,/(?:^|\/)gemma-[3-9]/i,/(?:^|\/)gpt-(?:4o|4\.1|5)/i,/(?:^|\/)claude-/i,/(?:^|\/)llama-4/i,/(?:^|\/)pixtral/i,/(?:^|\/)mistral-(?:small|medium|large)-3/i,/(?:^|\/)nova-(?:lite|pro|premier)/i],s=125,c={max:1e3,min:20},l=6e4,u=new Set([`"`,`'`,`«`,`»`,`‘`,`’`,`‚`,`“`,`”`,`„`,"`"]),d=/^(?:here(?:'s|’s| is)\s+)?(?:the\s+)?alt(?:[-\s]?text)?\s*[:–—-]\s*/i,f=/^(?:this\s+is\s+)?(?:an?|the)?\s*(?:image|photo|photograph|picture|pic|graphic|illustration|rendering|render)\s+(?:of|showing|depicting|that\s+shows)\s+/i;function p(e){let t=new Set,n=[];for(let r of e){let e=r?.trim();e&&!t.has(e)&&(t.add(e),n.push(e))}return n}function m(e){let t=e?.trim();return t?a.includes(t)?!0:o.some(e=>e.test(t)):!1}function h(e){let t=e.requestedModelId?.trim()||null,n=e.selectedModel?.modelId?.trim()||null;return{modelIds:p([t,e.credentialSource!==`env`&&n&&m(n)?n:null,...a])}}function g(e){let t=e.trim();for(;t.length>=2&&u.has(t[0])&&u.has(t[t.length-1]);)t=t.slice(1,-1).trim();return t}function _(e){return!e.endsWith(`.`)||e.endsWith(`...`)||e.endsWith(`…`)?e:(e.match(/[.!?](?=\s|$)/g)||[]).length===1?e.slice(0,-1).trimEnd():e}function v(e,n=125){let r=e.replace(/\s+/g,` `).trim(),i=!1;for(let e=0;e<2;e++){r=g(r);let e=r.replace(d,``);e!==r&&(r=e.trim(),i=!0),r=g(r);let t=r.replace(f,``);t!==r&&(r=t.trim(),i=!0)}return i&&r&&(r=r.charAt(0).toUpperCase()+r.slice(1)),t.truncateOnWordBoundary(_(r),n)}function y(e){let t=e.trim();if(!t)throw Error(`Cortex AI alt text generation requires an image URL.`);let n;try{n=new URL(t)}catch{throw Error(`Cortex AI alt text generation requires an absolute http(s) image URL, received "${t}". A storage key or site-relative path must be resolved to a publicly fetchable URL first, because the model provider downloads the image server-side.`)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw Error(`Cortex AI alt text generation requires an http(s) image URL, received the "${n.protocol}" scheme.`);return n}function b(e){return[`You are NextBlock Cortex AI, writing the alt attribute for an image on a website.`,`You are writing for a person using a screen reader who cannot see the image at all.`,`Describe only what is visibly present in the image: subjects, their appearance, what they are doing, the setting, and any text that appears in the image.`,`Never state or guess anything you cannot see — no names, no locations, no dates, no brands, no emotions, and no backstory unless they are legible in the image itself.`,`Write one short factual description of at most ${e} characters.`,`Do not begin with "image of", "photo of", "picture of", "graphic of", or any similar phrase; the screen reader already announces that this is an image.`,`Do not add a label such as "Alt text:" and do not wrap the description in quotation marks.`,`Do not keyword-stuff, do not list search terms, and do not repeat a word for emphasis.`,`Return plain text only: one line, no markdown, no HTML, no JSON, no commentary, no alternatives to choose between.`,`If surrounding page context is supplied, use it ONLY to disambiguate what you can already see — for example to choose the right word for an object or to know which product is pictured. Never use it to add detail that is not visible in the image.`].join(` `)}function x(e){return[`Write the alt attribute for this image, at most ${e.maxLength} characters.`,e.context?`Surrounding page context, for disambiguation only: ${e.context}`:null].filter(Boolean).join(`
|
|
2
|
+
|
|
3
|
+
`)}function S(t){let n=e.getHttpStatusCode(t);if(n===401||n===402||n===403)return!1;if(e.isOpenRouterRecoverableRoutingError(t)||n&&n>=500)return!0;let r=t instanceof Error?t.message:String(t);return/NoContentGenerated|No content generated|Provider returned error|empty alt text|image|modality|multimodal|not support|unsupported|aborted|abort|timeout|timed out/i.test(r)}async function C(t){i();let r=y(t.imageUrl),a=Number.isFinite(t.maxLength)?Math.round(t.maxLength):125,o=Math.min(c.max,Math.max(c.min,a)),s=t.context?.replace(/\s+/g,` `).trim()||null,{createCortexAiOpenRouterClient:u}=await Promise.resolve().then(()=>require("./ai-client.cjs")),d=await u({apiKey:t.apiKey||void 0}),f=h({credentialSource:d.credentialSource,requestedModelId:t.modelId,selectedModel:d.modelSelection}),{downloadCortexVisionImage:p}=await Promise.resolve().then(()=>require("./vision-image-download.cjs")),m=await p(r,{abortSignal:t.abortSignal}),g=[{content:[{text:x({context:s,maxLength:o}),type:`text`},{data:m.data,mediaType:m.mediaType,type:`file`}],role:`user`}],_=await e.runWithCortexAiModelFallback({modelIds:f.modelIds,shouldRetry:S,execute:async r=>{let i=new AbortController,a=setTimeout(()=>i.abort(),l),s=()=>i.abort();t.abortSignal?.addEventListener(`abort`,s,{once:!0}),t.abortSignal?.aborted&&i.abort();try{let t=e.omitUnsupportedCortexAiModelOptions({abortSignal:i.signal,maxOutputTokens:400,maxRetries:0,messages:g,instructions:b(o),temperature:.2},{modelId:r,modelSelection:d.modelSelection}),a=v((await(0,n.generateText)({...t,model:d.model(r)})).text,o);if(!a)throw Error(`Cortex AI returned empty alt text.`);return a}finally{clearTimeout(a),t.abortSignal?.removeEventListener(`abort`,s)}}});return{altText:_.result,attempts:_.attempts.length,credentialSource:d.credentialSource,modelId:_.modelId}}exports.CORTEX_AI_DEFAULT_ALT_TEXT_MAX_LENGTH=s,exports.CORTEX_AI_VISION_MODEL_FALLBACK_REGISTRY=a,exports.buildCortexAiVisionRoutingPolicy=h,exports.generateCortexAiAltText=C,exports.isKnownVisionCapableCortexAiModelId=m,exports.normalizeGeneratedAltText=v;
|
package/lib/ai-vision.es.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { getHttpStatusCode as e, isOpenRouterRecoverableRoutingError as t, omitUnsupportedCortexAiModelOptions as n, runWithCortexAiModelFallback as r } from "./ai-model-registry.es.js";
|
|
2
2
|
import { truncateOnWordBoundary as i } from "./ai-seo-metadata.es.js";
|
|
3
3
|
import { generateText as a } from "ai";
|
|
4
|
-
//#region
|
|
4
|
+
//#region src/lib/ai-vision.ts
|
|
5
5
|
var o = "Cortex AI vision generation can only be imported from server-side code.";
|
|
6
6
|
function s() {
|
|
7
7
|
if (typeof window < "u") throw Error(o);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
require("./zod-config.cjs");let e=require("zod");var t=[`text`,`heading`,`image`,`button`,`posts_grid`,`video_embed`,`section`,`form`,`testimonial`,`product_grid`,`featured_product`,`cart`,`checkout`,`product_details`],n=e.z.enum(t),r=e.z.object({direction:e.z.string().optional(),stops:e.z.array(e.z.object({color:e.z.string(),position:e.z.number()})),type:e.z.enum([`linear`,`radial`])}),i=e.z.object({gradient:r.optional(),image:e.z.object({alt_text:e.z.string().optional(),blur_data_url:e.z.string().optional(),external_url:e.z.string().optional(),height:e.z.number().optional(),media_id:e.z.string().optional(),object_key:e.z.string().optional(),overlay:e.z.object({gradient:r,type:e.z.literal(`gradient`)}).optional(),position:e.z.enum([`center`,`top`,`bottom`,`left`,`right`]),quality:e.z.number().nullable().optional(),size:e.z.enum([`cover`,`contain`]),width:e.z.number().optional()}).optional(),min_height:e.z.string().optional(),solid_color:e.z.string().optional(),theme:e.z.enum([`primary`,`secondary`,`muted`,`accent`,`destructive`]).optional(),type:e.z.enum([`none`,`theme`,`solid`,`gradient`,`image`])}),a=e.z.string().regex(/^[a-z][a-z0-9-]*$/),o=e.z.object({block_type:e.z.union([n,a]),content:e.z.record(e.z.string(),e.z.any()),temp_id:e.z.string().optional()}),s=e.z.object({background:i,column_blocks:e.z.array(e.z.array(o))}),c=e.z.object({autoplay:e.z.boolean().optional(),background:i,column_blocks:e.z.array(e.z.array(o)),column_gap:e.z.enum([`none`,`sm`,`md`,`lg`,`xl`]),container_type:e.z.enum([`full-width`,`container`,`container-sm`,`container-lg`,`container-xl`]),is_hero:e.z.boolean().optional(),padding:e.z.object({bottom:e.z.enum([`none`,`sm`,`md`,`lg`,`xl`]),top:e.z.enum([`none`,`sm`,`md`,`lg`,`xl`])}),responsive_columns:e.z.object({desktop:e.z.union([e.z.literal(1),e.z.literal(2),e.z.literal(3),e.z.literal(4)]),mobile:e.z.union([e.z.literal(1),e.z.literal(2)]),tablet:e.z.union([e.z.literal(1),e.z.literal(2),e.z.literal(3)])}),slider:e.z.boolean().optional(),slides:e.z.array(s).optional(),timeframe:e.z.number().optional(),vertical_alignment:e.z.enum([`start`,`center`,`end`,`stretch`]).optional()}),l={button:e.z.object({position:e.z.enum([`left`,`center`,`right`]).optional(),size:e.z.enum([`default`,`sm`,`lg`,`full`]).optional(),text:e.z.string(),url:e.z.string(),variant:e.z.enum([`default`,`outline`,`secondary`,`ghost`,`link`]).optional()}),cart:e.z.object({}),checkout:e.z.object({}),featured_product:e.z.object({imagePosition:e.z.enum([`left`,`right`]).default(`left`),productId:e.z.string().min(1),showBackground:e.z.boolean().default(!1)}),form:e.z.object({fields:e.z.array(e.z.object({field_type:e.z.enum([`text`,`email`,`tel`,`url`,`number`,`textarea`,`select`,`radio`,`checkbox`]),is_required:e.z.boolean(),label:e.z.string(),options:e.z.array(e.z.object({label:e.z.string(),value:e.z.string()})).optional(),placeholder:e.z.string().optional(),temp_id:e.z.string()})),form_key:e.z.string().optional(),recipient_email:e.z.string().email().optional(),submit_button_text:e.z.string(),success_message:e.z.string()}),heading:e.z.object({level:e.z.union([e.z.literal(1),e.z.literal(2),e.z.literal(3),e.z.literal(4),e.z.literal(5),e.z.literal(6)]),textAlign:e.z.enum([`left`,`center`,`right`,`justify`]).optional(),textColor:e.z.union([e.z.enum([`foreground`,`primary`,`secondary`,`accent`,`muted`,`destructive`,`background`]),e.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:e.z.string()}),image:e.z.object({alt_text:e.z.string().optional(),caption:e.z.string().optional(),external_url:e.z.string().nullable().optional(),height:e.z.number().nullable().optional(),media_id:e.z.string().nullable().optional(),object_key:e.z.string().nullable().optional(),width:e.z.number().nullable().optional()}),posts_grid:e.z.object({anchor:e.z.string().regex(/^([a-z][a-z0-9-]{0,63})?$/).optional(),columns:e.z.number().min(1).max(6),postsPerPage:e.z.number().min(1).max(50),showPagination:e.z.boolean(),title:e.z.string().optional()}),product_details:e.z.object({}),product_grid:e.z.object({categoryId:e.z.string().optional(),categoryIds:e.z.array(e.z.string()).max(20).optional(),limit:e.z.number().min(0).max(48).default(6),productIds:e.z.array(e.z.string()).max(24).optional(),showPagination:e.z.boolean().default(!1),title:e.z.string().optional(),type:e.z.enum([`latest`,`category`,`manual`]).default(`latest`)}),section:c,testimonial:e.z.object({author_name:e.z.string().min(1),author_title:e.z.string().optional(),image_url:e.z.string().url().optional().or(e.z.literal(``)),quote:e.z.string().min(1)}),text:e.z.object({html_content:e.z.string()}),video_embed:e.z.object({autoplay:e.z.boolean().optional(),controls:e.z.boolean().optional(),title:e.z.string().optional(),url:e.z.string()})};function u(e){return t.includes(e)}function d(e){return typeof e?.validateBlockContent==`function`?e.validateBlockContent:null}function f(e,t,n){let r=d(n);if(r)return r(e,t);let i=l[e].safeParse(t);return i.success?{errors:[],isValid:!0,warnings:[]}:{errors:i.error.issues.map(e=>{let t=e.path.join(`.`);return t?`${t}: ${e.message}`:e.message}),isValid:!1,warnings:[]}}function p(e){return Array.isArray(e.fields)?e.fields.filter(e=>!!e&&typeof e==`object`&&typeof e.key==`string`&&typeof e.type==`string`):[]}function m(e){return e==null||typeof e==`string`&&e.trim()===``||Array.isArray(e)&&e.length===0}function h(e,t){if(!t||typeof t!=`object`||Array.isArray(t))return{errors:[`content must be a JSON object of { field_key: value } pairs.`],isValid:!1,warnings:[]};let n=p(e),r=new Set(n.map(e=>e.key)),i=[],a=[];for(let n of Object.keys(t))r.has(n)||i.push(`Unknown field "${n}" for custom block "${e.slug}". Known fields: ${[...r].join(`, `)||`(none)`}.`);for(let e of n){let n=t[e.key];if(m(n)){e.required&&i.push(`Field "${e.key}" is required.`);continue}if(e.type===`text`||e.type===`rich-text`){if(typeof n!=`string`){i.push(`Field "${e.key}" must be a string${e.type===`rich-text`?` of HTML`:``}.`);continue}typeof e.max_length==`number`&&n.length>e.max_length&&i.push(`Field "${e.key}" exceeds its ${e.max_length}-character limit.`),typeof e.min_length==`number`&&n.length<e.min_length&&i.push(`Field "${e.key}" is shorter than its ${e.min_length}-character minimum.`);continue}if(e.type===`image_r2`){let t=n;(typeof n!=`object`||Array.isArray(n)||typeof t.object_key!=`string`||typeof t.url!=`string`)&&i.push(`Field "${e.key}" must be an uploaded image object with object_key and url (upload it with upload_media first) or null.`);continue}if(e.type===`db_relation`){let t=e=>typeof e==`string`||typeof e==`number`;e.multiple?(!Array.isArray(n)||!n.every(t))&&i.push(`Field "${e.key}" must be an array of related record ids.`):t(n)||i.push(`Field "${e.key}" must be a single related record id.`);continue}a.push(`Field "${e.key}" has an unrecognised type "${String(e.type)}"; it was not validated.`)}return{errors:i,isValid:i.length===0,warnings:a}}async function g(e){let{data:t,error:n}=await e.from(`custom_block_definitions`).select(`slug, name, fields`);if(n)throw Error(`Could not read the custom block definitions: ${typeof n==`object`&&n&&`message`in n?String(n.message):String(n)}`);return(Array.isArray(t)?t:[]).filter(e=>!!e&&typeof e.slug==`string`)}exports.availableCortexAiBlockTypes=t,exports.cortexAiBlockTypeSchema=n,exports.customBlockSlugPatternSchema=a,exports.fallbackBlockSchemas=l,exports.isValidBlockType=u,exports.loadCustomBlockDefinitions=g,exports.readCustomBlockFields=p,exports.sectionBlockFallbackSchema=c,exports.validateCortexBlockContent=f,exports.validateCustomBlockInstanceContent=h;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z as e } from "./zod-config.es.js";
|
|
2
|
-
//#region
|
|
2
|
+
//#region src/lib/block-content-schemas.ts
|
|
3
3
|
var t = [
|
|
4
4
|
"text",
|
|
5
5
|
"heading",
|
|
@@ -220,6 +220,7 @@ var t = [
|
|
|
220
220
|
width: e.number().nullable().optional()
|
|
221
221
|
}),
|
|
222
222
|
posts_grid: e.object({
|
|
223
|
+
anchor: e.string().regex(/^([a-z][a-z0-9-]{0,63})?$/).optional(),
|
|
223
224
|
columns: e.number().min(1).max(6),
|
|
224
225
|
postsPerPage: e.number().min(1).max(50),
|
|
225
226
|
showPagination: e.boolean(),
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { customBlockDefinitionCreateSchema as e, customBlockDefinitionRowSchema as t } from "@nextblock-cms/utils/custom-blocks";
|
|
2
|
-
//#region
|
|
2
|
+
//#region src/lib/cortex-widget-registry.ts
|
|
3
3
|
var n = "id, slug, name, description, fields, layout_schema, is_original", r = class extends Error {
|
|
4
4
|
code;
|
|
5
5
|
status;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
require("./zod-config.cjs");let e=require("@nextblock-cms/utils/custom-blocks"),t=require("zod");var n=[`pages`,`posts`,`products`,`media`,`categories`,`profiles`,`languages`],r=t.z.enum([`article`,`aside`,`blockquote`,`div`,`figure`,`figcaption`,`h2`,`h3`,`img`,`p`,`section`,`span`]).describe(`A safe semantic element supported by the dynamic layout renderer.`),i=t.z.string().trim().max(4e3).describe(`Tailwind utility classes only. Do not include CSS, style tags, or JavaScript.`),a=t.z.strictObject({description:t.z.string().trim().max(500).optional(),key:e.customBlockFieldKeySchema.describe(`Lowercase snake_case field key.`),label:t.z.string().trim().min(1).max(120),required:t.z.boolean().default(!1)}),o=a.extend({default_value:t.z.string().max(5e3).optional(),max_length:t.z.number().int().positive().max(1e4).optional(),min_length:t.z.number().int().min(0).max(1e4).optional(),placeholder:t.z.string().max(250).optional(),type:t.z.literal(`text`)}),s=a.extend({default_value:t.z.string().max(5e4).optional(),placeholder:t.z.string().max(250).optional(),type:t.z.literal(`rich-text`)}),c=a.extend({accept:t.z.array(t.z.string().trim().min(1).max(120)).max(20).optional(),default_value:t.z.strictObject({alt:t.z.string().max(300).optional(),file_name:t.z.string().trim().min(1).max(255).optional(),file_type:t.z.string().trim().min(1).max(120).optional(),height:t.z.number().int().positive().optional(),object_key:t.z.string().trim().min(1).max(1024),size_bytes:t.z.number().int().positive().optional(),url:t.z.string().trim().min(1).max(2048),width:t.z.number().int().positive().optional()}).optional(),max_bytes:t.z.number().int().positive().max(52428800).optional(),type:t.z.literal(`image_r2`)}),l=a.extend({default_value:t.z.union([t.z.string(),t.z.array(t.z.string()),t.z.null()]).optional(),display_column:t.z.string().trim().min(1).max(80).default(`title`),filters:t.z.record(t.z.string(),t.z.unknown()).optional(),multiple:t.z.boolean().default(!1),table:t.z.enum(n),type:t.z.literal(`db_relation`),value_column:t.z.string().trim().min(1).max(80).default(`id`)}),u=t.z.discriminatedUnion(`type`,[o,s,c,l]).describe(`A NextBlock custom block field. Allowed types: text, rich-text, image_r2, db_relation.`),d=t.z.lazy(()=>t.z.discriminatedUnion(`type`,[t.z.strictObject({as:r.optional(),children:t.z.array(d).max(200).default([]),className:i.optional(),type:t.z.literal(`container`)}),t.z.strictObject({as:r.optional(),className:i.optional(),column:t.z.string().trim().min(1).max(80).optional().describe(`For a db_relation field, the related record column to display (e.g. title, price).`),emptyFallback:t.z.string().max(300).optional(),field_key:e.customBlockFieldKeySchema,type:t.z.literal(`field_render`)})])),f=t.z.strictObject({context:t.z.string().trim().max(24e3).optional(),modelId:t.z.string().trim().min(1).max(200).optional(),prompt:t.z.string().trim().min(3).max(4e3)});function p(e){return e.type===`field_render`?[e.field_key]:e.children.flatMap(e=>p(e))}function m(e,t){let n=new Set;e.fields.forEach((e,r)=>{n.has(e.key)&&t.addIssue({code:`custom`,message:`Duplicate field key "${e.key}".`,path:[`fields`,r,`key`]}),n.add(e.key)});for(let r of p(e.layout_schema))n.has(r)||t.addIssue({code:`custom`,message:`Layout references unknown field "${r}".`,path:[`layout_schema`]})}var h=t.z.strictObject({description:t.z.string().trim().max(1e3).default(``),fields:t.z.array(u).min(1).max(80),is_original:t.z.boolean().default(!0),layout_schema:d,name:t.z.string().trim().min(1).max(160),slug:e.customBlockSlugSchema.describe(`Lowercase kebab-case slug.`)}).superRefine(m).describe(`A complete NextBlock custom block definition stored as database JSONB.`);function g(t){let n=h.parse(t);return e.customBlockDefinitionCreateSchema.parse({...n,is_original:!0})}function _(){return[`You are NextBlock Cortex, an expert web platform engineer building database-rendered custom CMS widgets.`,`Return ONLY one clean raw JSON object with the exact structure described in the user message. Do not include markdown fences, comments, prose, or explanatory text.`,`Never emit TSX, JSX, React components, JavaScript, CSS blocks, style attributes, script tags, or runtime code.`,`Use only these field types: text, rich-text, image_r2, db_relation.`,`Use db_relation.table only from this allowlist: ${n.join(`, `)}.`,`Use lowercase kebab-case for slug and lowercase snake_case for field keys.`,`Build layout_schema as a self-referential tree: container nodes may contain nested container or field_render nodes to any needed depth.`,`Use Tailwind utility classes in className strings. Use responsive utilities where helpful.`,`The "as" property of any node MUST be exactly one of: article, aside, blockquote, div, figure, figcaption, h2, h3, img, p, section, span. Never use a, button, ul, ol, li, table, or any other tag. For a call-to-action or "more info" button, use a span or p styled with button-like Tailwind classes (rounded, padded, colored background).`,`Every field_render.field_key must match one field key exactly.`,`For relation fields, set value_column to id and set display_column to a column that actually exists on the chosen table: use title for pages, posts, and products; sku for product_variants; full_name for profiles; name for categories and languages; file_name for media. Do not invent display columns.`,`Entity images: when a block displays an image that belongs to a related product, page, or post (for example a product card photo or a post thumbnail), do NOT add an image_r2 upload field for it. Instead add a single db_relation field to that table (products, product_variants, pages, or posts) and add a field_render node that references it with "as": "img". The renderer automatically resolves the related record's primary image — a product or variant main_image/object_key, or a page/post feature image — so keep the table's normal display_column (for example title for a products relation).`,`You may reference the same db_relation field from more than one field_render node: for example one node with "as": "img" for the image and another text node for its title, plus the relation value to drive a "more info" link. This builds a product/page/post card from a single relation field.`,`To display a SPECIFIC column of a related record (its title, price, sku, etc.), set the field_render node's "column" property to that column name. The "column" overrides the field display_column for that one node, so a single product relation can show its image (as "img"), title (column "title"), and price (column "price") from three field_render nodes.`,`Available record columns by table — only reference these in a node "column": products: title, sku, price, sale_price, stock, short_description, slug, status; product_variants: sku, price, sale_price, stock_quantity; pages: title, slug, status; posts: title, slug, excerpt, subtitle; profiles: full_name; categories: name, slug, description; media: file_name; languages: name, code. Use "as": "img" (no column) to show a record image.`,`Do NOT create a standalone text field for data that lives on a related record. For example, a product price must come from a products db_relation field rendered with column "price" — never a separate "text" field the editor types by hand.`,`Monetary columns (price, sale_price, price_adjustment) are stored in integer cents and are automatically formatted as currency on display, so reference them directly; never multiply, divide, or add currency symbols yourself.`,`Only use image_r2 for standalone images uploaded directly by the editor that are not tied to any database record (for example a decorative banner or icon). Only use text or rich-text fields for free-form copy the editor writes, not for values that exist on a related record.`].join(` `)}function v(e){return[`Create a NextBlock custom block definition for this request:`,e.prompt,e.context?`Additional CMS context:\n${e.context}`:null,[`Return ONLY a JSON object with EXACTLY these top-level keys:`,`- "name": string (human-friendly block name).`,`- "slug": lowercase kebab-case string.`,`- "description": short string.`,`- "is_original": true.`,`- "fields": a non-empty array of field objects. Each field is { "key": lowercase snake_case string, "label": string, "required": boolean, "type": one of "text" | "rich-text" | "image_r2" | "db_relation" }.`,` For "db_relation" fields also include "table" (one of: ${n.join(`, `)}), "display_column" (e.g. title, name, full_name, file_name, code), "value_column": "id", and "multiple": boolean.`,`- "layout_schema": a single root layout node (a tree). Every node is one of:`,` container: { "type": "container", "as": an HTML tag like div/section/article/figure, "className": Tailwind utility classes, "children": array of nodes }.`,` field render: { "type": "field_render", "field_key": one of the field keys above, "as": an HTML tag like p/span/img/h2/h3/div, "className": Tailwind utility classes, "emptyFallback": optional placeholder string }.`,` Containers may nest other containers to any depth. Every field_render.field_key MUST match one of the fields. Render image_r2 fields with "as": "img".`].join(`
|
|
2
|
+
`)].filter(Boolean).join(`
|
|
3
|
+
|
|
4
|
+
`)}function y(){return g({description:`A multi-tier profile card with an R2 image asset slot and a live customer relation list.`,fields:[{accept:[`image/png`,`image/jpeg`,`image/webp`],key:`profile_photo`,label:`Profile Photo`,max_bytes:10485760,required:!1,type:`image_r2`},{key:`profile_name`,label:`Profile Name`,placeholder:`Ada Lovelace`,required:!0,type:`text`},{key:`profile_role`,label:`Profile Role`,placeholder:`Principal Architect`,required:!1,type:`text`},{key:`profile_summary`,label:`Profile Summary`,placeholder:`<p>Short profile biography.</p>`,required:!1,type:`rich-text`},{display_column:`full_name`,key:`customer_list`,label:`Customer List`,multiple:!0,required:!1,table:`profiles`,type:`db_relation`,value_column:`id`}],is_original:!0,layout_schema:{as:`article`,children:[{as:`div`,children:[{as:`div`,children:[{as:`div`,children:[{as:`img`,className:`h-24 w-24 rounded-full border object-cover shadow-sm`,emptyFallback:`Upload profile photo`,field_key:`profile_photo`,type:`field_render`},{as:`span`,className:`rounded-full bg-muted px-3 py-1 text-center text-xs font-medium text-muted-foreground`,emptyFallback:`No customers linked`,field_key:`customer_list`,type:`field_render`}],className:`flex flex-col items-center gap-4 md:w-48`,type:`container`},{as:`div`,children:[{as:`div`,children:[{as:`h2`,className:`text-2xl font-semibold leading-tight`,emptyFallback:`Untitled profile`,field_key:`profile_name`,type:`field_render`},{as:`p`,className:`text-sm font-medium text-muted-foreground`,emptyFallback:`Role pending`,field_key:`profile_role`,type:`field_render`}],className:`flex flex-col gap-1`,type:`container`},{as:`div`,children:[{as:`div`,className:`prose prose-sm max-w-none text-muted-foreground`,emptyFallback:`<p>Add a concise profile summary.</p>`,field_key:`profile_summary`,type:`field_render`}],className:`rounded-md border bg-muted/30 p-4`,type:`container`}],className:`flex min-w-0 flex-1 flex-col gap-4`,type:`container`}],className:`flex flex-col gap-6 md:flex-row`,type:`container`}],className:`rounded-lg border bg-background p-6 shadow-sm`,type:`container`}],className:`mx-auto max-w-3xl p-4`,type:`container`},name:`Cortex Profile Card`,slug:`cortex-profile-card`})}exports.CORTEX_WIDGET_ALLOWED_RELATION_TABLES=n,exports.buildCortexProfileCardVerificationDefinition=y,exports.buildCortexWidgetBuilderPrompt=v,exports.buildCortexWidgetBuilderSystemPrompt=_,exports.cortexWidgetBuildRequestSchema=f,exports.cortexWidgetDbRelationFieldSchema=l,exports.cortexWidgetDefinitionSchema=h,exports.cortexWidgetFieldSchema=u,exports.cortexWidgetImageR2FieldSchema=c,exports.cortexWidgetLayoutNodeSchema=d,exports.cortexWidgetRichTextFieldSchema=s,exports.cortexWidgetTextFieldSchema=o,exports.validateCortexWidgetDefinitionOutput=g;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z as e } from "./zod-config.es.js";
|
|
2
2
|
import { customBlockDefinitionCreateSchema as t, customBlockFieldKeySchema as n, customBlockSlugSchema as r } from "@nextblock-cms/utils/custom-blocks";
|
|
3
|
-
//#region
|
|
3
|
+
//#region src/lib/cortex-widget-schema.ts
|
|
4
4
|
var i = [
|
|
5
5
|
"pages",
|
|
6
6
|
"posts",
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=require("./mcp-tool-registry.cjs");var t=`nextblock-cortex-ai`,n=`NextBlock Cortex AI`,r=`2025-06-18`,i=`2025-11-25`,a=`2026-07-28`,o=[a,i,`2025-06-18`,`2025-03-26`,`2024-11-05`],s=-32700,c=-32600,l=-32601,u=-32602,d=-32603;function f(e,t){return{body:{id:e,jsonrpc:`2.0`,result:t},status:200}}function p(e,t,n,r=200,i){return{body:{error:{code:t,message:n,...i===void 0?{}:{data:i}},id:e,jsonrpc:`2.0`},status:r}}var m={body:null,status:202};function h(e){return typeof e.method==`string`&&e.id===void 0}function g(e,t){let n=e.params?._meta;if(n&&typeof n==`object`){let e=n[`io.modelcontextprotocol/protocolVersion`];if(typeof e==`string`&&e>=`2026-07-28`)return!0}return!!(t&&t>=`2026-07-28`)}function _(e){return typeof e!=`string`||!e?r:o.includes(e)?e:i}function v(e,r){let i=e.scopes.includes(`write`);return{capabilities:{prompts:{},resources:{},tools:{}},instructions:e.instructions??[`NextBlock Cortex AI exposes this CMS through typed tools.`,`Call get_database_schema first when you are unsure what exists.`,`Conventions: a page or post feature_image_id renders as a full-width title banner above the content and is its share preview — give posts one, never the home page or a page with its own hero section (use update_site_identity social_image for the site-wide preview); mark hero sections is_hero:true; slider:true plus slides makes a carousel.`,i?`Page builds should go through generate_jsonb_layout, which stages a reviewable Live Draft rather than publishing directly.`:`This connection is READ-ONLY. Mutating tools are not available on this token.`].join(` `),protocolVersion:_(r),serverInfo:{name:t,title:n,version:e.serverVersion,websiteUrl:`https://nextblock.dev`}}}function y(e){return{authentication:{header:`Authorization`,instructions:"POST JSON-RPC 2.0 messages with `Authorization: Bearer <token>`. Create the token in the NextBlock CMS (Settings → Cortex AI → MCP server access) or set MCP_BEARER_TOKEN in the environment. Cortex AI must be active on the site.",required:!0,schemes:[`bearer`]},capabilities:{prompts:{},resources:{},tools:{}},endpoint:{transport:`streamable-http`,url:e.endpointUrl},name:t,protocolVersions:o,serverCard:e.serverCardUrl,status:`ok`,title:n,version:e.serverVersion,websiteUrl:`https://nextblock.dev`}}function b(e){return!!(e&&e.toLowerCase().includes(`text/event-stream`))}async function x(t,n){if(typeof t!=`object`||!t||Array.isArray(t))return p(null,c,`Expected a single JSON-RPC message.`,400);if(typeof t.method!=`string`)return`result`in t||`error`in t?m:p(t.id??null,c,`Missing "method".`,400);let{method:r}=t,i=t.id??null,a=h(t);if(r.startsWith(`notifications/`))return m;switch(r){case`initialize`:return a?m:f(i,v(n,t.params?.protocolVersion));case`ping`:return a?m:f(i,{});case`tools/list`:return a?m:f(i,{tools:e.buildCortexMcpToolDefinitions({context:n.context,scopes:n.scopes})});case`tools/call`:{if(a)return m;let r=t.params?.name;if(typeof r!=`string`||!r)return p(i,u,`tools/call requires params.name.`);try{return f(i,await e.callCortexMcpTool({args:t.params?.arguments,context:n.context,name:r,scopes:n.scopes}))}catch(t){return t instanceof e.CortexMcpUnknownToolError||t instanceof e.CortexMcpForbiddenToolError?p(i,u,t.message):p(i,d,t instanceof Error?t.message:`Tool execution failed.`)}}case`resources/list`:return a?m:f(i,{resources:e.CORTEX_MCP_RESOURCES});case`resources/templates/list`:return a?m:f(i,{resourceTemplates:[]});case`resources/read`:{if(a)return m;let r=t.params?.uri;if(typeof r!=`string`||!r)return p(i,u,`resources/read requires params.uri.`);try{let t=await e.readCortexMcpResource({context:n.context,uri:r});return t?f(i,{contents:[t]}):p(i,u,`Unknown resource: ${r}`)}catch(e){return p(i,d,e instanceof Error?e.message:`Resource read failed.`)}}case`prompts/list`:return a?m:f(i,{prompts:e.CORTEX_MCP_PROMPTS});case`prompts/get`:{if(a)return m;let n=t.params?.name;if(typeof n!=`string`||!n)return p(i,u,`prompts/get requires params.name.`);let r=t.params?.arguments,o={};if(r&&typeof r==`object`)for(let[e,t]of Object.entries(r))typeof t==`string`&&(o[e]=t);let s=e.getCortexMcpPrompt({args:o,name:n});return s?f(i,s):p(i,u,`Unknown prompt: ${n}`)}default:return a?m:p(i,l,`Method not found: ${r}`)}}exports.CORTEX_MCP_DEFAULT_PROTOCOL_VERSION=r,exports.CORTEX_MCP_LATEST_LEGACY_PROTOCOL_VERSION=i,exports.CORTEX_MCP_MODERN_PROTOCOL_VERSION=a,exports.CORTEX_MCP_SERVER_NAME=t,exports.CORTEX_MCP_SERVER_TITLE=n,exports.CORTEX_MCP_SUPPORTED_PROTOCOL_VERSIONS=o,exports.JSON_RPC_INTERNAL_ERROR=d,exports.JSON_RPC_INVALID_PARAMS=u,exports.JSON_RPC_INVALID_REQUEST=c,exports.JSON_RPC_METHOD_NOT_FOUND=l,exports.JSON_RPC_PARSE_ERROR=s,exports.buildCortexMcpDiscoveryDocument=y,exports.handleCortexMcpMessage=x,exports.isJsonRpcNotification=h,exports.isModernEraMessage=g,exports.wantsMcpEventStream=b;
|
package/lib/mcp-server.es.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { CORTEX_MCP_PROMPTS as e, CORTEX_MCP_RESOURCES as t, CortexMcpForbiddenToolError as n, CortexMcpUnknownToolError as r, buildCortexMcpToolDefinitions as i, callCortexMcpTool as a, getCortexMcpPrompt as o, readCortexMcpResource as s } from "./mcp-tool-registry.es.js";
|
|
2
|
-
//#region
|
|
2
|
+
//#region src/lib/mcp-server.ts
|
|
3
3
|
var c = "nextblock-cortex-ai", l = "NextBlock Cortex AI", u = "2025-06-18", d = "2025-11-25", f = "2026-07-28", p = [
|
|
4
4
|
f,
|
|
5
5
|
d,
|
package/lib/mcp-tokens.es.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createHash as e, randomBytes as t, timingSafeEqual as n } from "node:crypto";
|
|
2
|
-
//#region
|
|
2
|
+
//#region src/lib/mcp-tokens.ts
|
|
3
3
|
var r = "Cortex AI MCP token utilities can only be imported from server-side code.";
|
|
4
4
|
function i() {
|
|
5
5
|
if (typeof window < "u") throw Error(r);
|