@nextblock-cms/cortex 0.22.0 → 0.22.1

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.
@@ -12,4 +12,4 @@ require("./zod-config.cjs");const e=require("./ai-global-agent-custom-block-tool
12
12
  paid_at,
13
13
  currency
14
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(/&nbsp;/gi,` `).replace(/&amp;/gi,`&`).replace(/&lt;/gi,`<`).replace(/&gt;/gi,`>`).replace(/&quot;/gi,`"`).replace(/&#39;/gi,`'`).replace(/\s+/g,` `).trim()}function er(e){return e.trim().replace(/&amp;/gi,`&`).replace(/&#38;/g,`&`).replace(/&quot;/gi,`"`).replace(/&#39;/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;
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(/&nbsp;/gi,` `).replace(/&amp;/gi,`&`).replace(/&lt;/gi,`<`).replace(/&gt;/gi,`>`).replace(/&quot;/gi,`"`).replace(/&#39;/gi,`'`).replace(/\s+/g,` `).trim()}function er(e){return e.trim().replace(/&amp;/gi,`&`).replace(/&#38;/g,`&`).replace(/&quot;/gi,`"`).replace(/&#39;/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)||await a.resolvedHostIsBlocked(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{let e=new URL(i).hostname;if(a.isBlockedFetchHost(e)||await a.resolvedHostIsBlocked(e))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;